summaryrefslogtreecommitdiff
path: root/scripting
diff options
context:
space:
mode:
Diffstat (limited to 'scripting')
-rw-r--r--scripting/README67
-rw-r--r--scripting/examples/basic/InsertColouredText.xba124
-rw-r--r--scripting/examples/basic/InsertColouredTextDialog.xdl17
-rw-r--r--scripting/examples/basic/SearchAndReplace.xba109
-rw-r--r--scripting/examples/basic/SearchAndReplaceDialog.xdl13
-rw-r--r--scripting/examples/basic/dialog.xlb6
-rw-r--r--scripting/examples/basic/script.xlb6
-rw-r--r--scripting/examples/beanshell/Capitalise/capitalise.bsh94
-rwxr-xr-xscripting/examples/beanshell/Capitalise/parcel-descriptor.xml16
-rw-r--r--scripting/examples/beanshell/HelloWorld/helloworld.bsh17
-rwxr-xr-xscripting/examples/beanshell/HelloWorld/parcel-descriptor.xml16
-rw-r--r--scripting/examples/beanshell/Highlight/ButtonPressHandler.bsh106
-rw-r--r--scripting/examples/beanshell/Highlight/ShowDialog.bsh124
-rw-r--r--scripting/examples/beanshell/Highlight/highlighter.bsh149
-rwxr-xr-xscripting/examples/beanshell/Highlight/parcel-descriptor.xml25
-rwxr-xr-xscripting/examples/beanshell/InteractiveBeanShell/interactive.bsh4
-rw-r--r--scripting/examples/beanshell/InteractiveBeanShell/parcel-descriptor.xml16
-rw-r--r--scripting/examples/beanshell/MemoryUsage/memusage.bsh120
-rw-r--r--scripting/examples/beanshell/MemoryUsage/parcel-descriptor.xml16
-rwxr-xr-xscripting/examples/beanshell/WordCount/parcel-descriptor.xml16
-rw-r--r--scripting/examples/beanshell/WordCount/wordcount.bsh64
-rw-r--r--scripting/examples/delzip1
-rw-r--r--scripting/examples/java/HelloWorld/HelloWorld.java22
-rw-r--r--scripting/examples/java/HelloWorld/parcel-descriptor.xml16
-rw-r--r--scripting/examples/java/Highlight/HighlightText.java223
-rwxr-xr-xscripting/examples/java/Highlight/parcel-descriptor.xml17
-rw-r--r--scripting/examples/java/MemoryUsage/MemoryUsage.java141
-rw-r--r--scripting/examples/java/MemoryUsage/parcel-descriptor.xml16
-rw-r--r--scripting/examples/java/Newsgroup/MimeConfiguration.java219
-rw-r--r--scripting/examples/java/Newsgroup/NewsGroup.java23
-rw-r--r--scripting/examples/java/Newsgroup/OfficeAttachment.java307
-rw-r--r--scripting/examples/java/Newsgroup/PostNewsgroup.java625
-rw-r--r--scripting/examples/java/Newsgroup/Sender.java126
-rw-r--r--scripting/examples/java/Newsgroup/StatusWindow.java138
-rw-r--r--scripting/examples/java/Newsgroup/SubscribedNewsgroups.java373
-rwxr-xr-xscripting/examples/java/build.xml143
-rw-r--r--scripting/examples/java/debugger/DebugRunner.java71
-rw-r--r--scripting/examples/java/debugger/OOBeanShellDebugger.java374
-rw-r--r--scripting/examples/java/debugger/OORhinoDebugger.java75
-rw-r--r--scripting/examples/java/debugger/OOScriptDebugger.java7
-rw-r--r--scripting/examples/java/debugger/parcel-descriptor.xml18
-rwxr-xr-xscripting/examples/java/makefile.mk40
-rw-r--r--scripting/examples/java/selector/ScriptSelector.java498
-rw-r--r--scripting/examples/java/selector/container.gifbin0 -> 164 bytes
-rw-r--r--scripting/examples/java/selector/parcel-descriptor.xml17
-rw-r--r--scripting/examples/java/selector/script.gifbin0 -> 187 bytes
-rw-r--r--scripting/examples/java/selector/soffice.gifbin0 -> 136 bytes
-rw-r--r--scripting/examples/javascript/ExportSheetsToHTML/exportsheetstohtml.js71
-rwxr-xr-xscripting/examples/javascript/ExportSheetsToHTML/parcel-descriptor.xml16
-rw-r--r--scripting/examples/javascript/HelloWorld/helloworld.js16
-rwxr-xr-xscripting/examples/javascript/HelloWorld/parcel-descriptor.xml16
-rw-r--r--scripting/examples/javascript/Highlight/ButtonPressHandler.js105
-rw-r--r--scripting/examples/javascript/Highlight/ShowDialog.js115
-rw-r--r--scripting/examples/javascript/Highlight/parcel-descriptor.xml25
-rwxr-xr-xscripting/examples/makefile.mk62
-rw-r--r--scripting/examples/python/Capitalise.py61
-rw-r--r--scripting/examples/python/HelloWorld.py13
-rw-r--r--scripting/examples/python/pythonSamples/TableSample.py96
-rw-r--r--scripting/inc/makefile.mk51
-rw-r--r--scripting/inc/pch/precompiled_scripting.cxx32
-rw-r--r--scripting/inc/pch/precompiled_scripting.hxx35
-rw-r--r--scripting/java/Framework/com/sun/star/script/framework/security/SecurityDialog.java549
-rw-r--r--scripting/java/build.env3
-rwxr-xr-xscripting/java/build.xml289
-rw-r--r--scripting/java/com/sun/star/script/framework/browse/DialogFactory.java426
-rw-r--r--scripting/java/com/sun/star/script/framework/browse/ParcelBrowseNode.java379
-rw-r--r--scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java68
-rw-r--r--scripting/java/com/sun/star/script/framework/browse/ProviderBrowseNode.java294
-rw-r--r--scripting/java/com/sun/star/script/framework/browse/ScriptBrowseNode.java338
-rw-r--r--scripting/java/com/sun/star/script/framework/container/DeployedUnoPackagesDB.java234
-rw-r--r--scripting/java/com/sun/star/script/framework/container/Parcel.java311
-rw-r--r--scripting/java/com/sun/star/script/framework/container/ParcelContainer.java749
-rw-r--r--scripting/java/com/sun/star/script/framework/container/ParcelDescriptor.java453
-rw-r--r--scripting/java/com/sun/star/script/framework/container/ParsedScriptUri.java39
-rw-r--r--scripting/java/com/sun/star/script/framework/container/ScriptEntry.java131
-rw-r--r--scripting/java/com/sun/star/script/framework/container/ScriptMetaData.java413
-rw-r--r--scripting/java/com/sun/star/script/framework/container/UnoPkgContainer.java424
-rw-r--r--scripting/java/com/sun/star/script/framework/container/XMLParser.java41
-rw-r--r--scripting/java/com/sun/star/script/framework/container/XMLParserFactory.java183
-rw-r--r--scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java284
-rw-r--r--scripting/java/com/sun/star/script/framework/io/XInputStreamImpl.java122
-rw-r--r--scripting/java/com/sun/star/script/framework/io/XInputStreamWrapper.java105
-rw-r--r--scripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java131
-rw-r--r--scripting/java/com/sun/star/script/framework/io/XStorageHelper.java281
-rw-r--r--scripting/java/com/sun/star/script/framework/log/LogUtils.java68
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java77
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java103
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java56
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/PathUtils.java90
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/ScriptContext.java168
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java13
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/ScriptProvider.java734
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java250
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java415
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java421
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java144
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceView.java38
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/beanshell/template.bsh48
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/java/Resolver.java53
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java215
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java402
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java95
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java131
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java379
-rwxr-xr-xscripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java395
-rw-r--r--scripting/java/com/sun/star/script/framework/provider/javascript/template.js37
-rwxr-xr-xscripting/java/makefile.mk40
-rw-r--r--scripting/java/manifest.mf26
-rw-r--r--scripting/java/org/openoffice/idesupport/CommandLineTools.java353
-rw-r--r--scripting/java/org/openoffice/idesupport/ExtensionFinder.java60
-rw-r--r--scripting/java/org/openoffice/idesupport/JavaFinder.java227
-rw-r--r--scripting/java/org/openoffice/idesupport/LocalOffice.java112
-rw-r--r--scripting/java/org/openoffice/idesupport/MethodFinder.java8
-rw-r--r--scripting/java/org/openoffice/idesupport/OfficeDocument.java123
-rw-r--r--scripting/java/org/openoffice/idesupport/OfficeInstallation.java113
-rw-r--r--scripting/java/org/openoffice/idesupport/SVersionRCFile.java240
-rw-r--r--scripting/java/org/openoffice/idesupport/filter/AllFilesFilter.java50
-rw-r--r--scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java61
-rw-r--r--scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java62
-rw-r--r--scripting/java/org/openoffice/idesupport/filter/FileFilter.java35
-rw-r--r--scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java157
-rw-r--r--scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java239
-rw-r--r--scripting/java/org/openoffice/idesupport/ui/MethodPanel.java189
-rw-r--r--scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java209
-rw-r--r--scripting/java/org/openoffice/idesupport/ui/add.gifbin0 -> 103 bytes
-rw-r--r--scripting/java/org/openoffice/idesupport/xml/Manifest.java174
-rw-r--r--scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java603
-rw-r--r--scripting/java/org/openoffice/netbeans/editor/JavaKit.java251
-rw-r--r--scripting/java/org/openoffice/netbeans/editor/NetBeansSourceView.java212
-rw-r--r--scripting/java/org/openoffice/netbeans/editor/OOo.jcb5
-rw-r--r--scripting/java/org/openoffice/netbeans/editor/OOo.jcs21
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/Bundle.properties0
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/Bundle_en_US.properties0
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/BuildParcelAction.java72
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/CompileParcelAction.java47
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/ConfigureParcelAction.java73
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/DeployParcelAction.java247
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/MountDocumentAction.java88
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/MountParcelAction.java87
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentCookie.java45
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentSupport.java146
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelCookie.java45
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorEditorSupport.java144
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserCookie.java45
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserSupport.java124
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderCookie.java45
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderSupport.java260
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelSupport.java194
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/filesystem/Bundle.properties43
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/filesystem/Bundle_en_US.properties0
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystem.java1195
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystemBeanInfo.java128
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/Bundle.properties12
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoader.java115
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoaderBeanInfo.java75
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataNode.java123
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataObject.java61
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolder.java140
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoader.java85
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoaderBeanInfo.java79
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoader.java92
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoaderBeanInfo.java79
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataNode.java117
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataObject.java80
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoader.java94
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoaderBeanInfo.java79
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataNode.java84
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataObject.java86
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolder.java306
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoader.java115
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoaderBeanInfo.java79
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/nodes/OfficeDocumentChildren.java150
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/nodes/ParcelDescriptorChildren.java94
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/nodes/ScriptNode.java212
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/options/Bundle.properties13
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettings.java136
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsBeanInfo.java150
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsIcon.gifbin0 -> 145 bytes
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsIcon32.gifbin0 -> 253 bytes
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/AppStorage.html11
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/AppStorage.settings7
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/Bundle.properties23
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/EmptyParcel.html11
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeIcon.gifbin0 -> 588 bytes
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeIcon32.gifbin0 -> 759 bytes
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeSettings.settings9
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystem.html11
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystem.settings7
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystemIcon.pngbin0 -> 702 bytes
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystemIcon32.pngbin0 -> 1533 bytes
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/ParcelIcon.gifbin0 -> 576 bytes
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/ScriptParcel.html11
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/ScriptParcelDescriptor.html11
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/layer.xml98
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/mime-resolver.xml16
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/office-scripting.url1
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/templates/Empty.bsh_24
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/templates/Empty.java_27
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/templates/EmptyParcelDescriptor.xml_4
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/templates/HelloWorld.java_41
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/resources/templates/ParcelDescriptor.xml_8
-rwxr-xr-xscripting/java/org/openoffice/netbeans/modules/office/resources/webLink.gifbin0 -> 969 bytes
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/utils/FrameworkJarChecker.java143
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/utils/ManifestParser.java100
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/utils/NagDialog.java130
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/utils/OfficeModule.java71
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/utils/PackageRemover.java109
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/utils/ZipMounter.java95
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/Bundle.properties26
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/Bundle_en_US.properties0
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathDescriptor.java72
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathIterator.java136
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/JavaScriptIterator.java253
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelContentsIterator.java257
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesPanel.java117
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.form74
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.java157
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathPanel.java123
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.form82
-rw-r--r--scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.java196
-rw-r--r--scripting/prj/build.lst13
-rw-r--r--scripting/prj/d.lst17
-rw-r--r--scripting/source/basprov/baslibnode.cxx151
-rw-r--r--scripting/source/basprov/baslibnode.hxx90
-rw-r--r--scripting/source/basprov/basmethnode.cxx361
-rw-r--r--scripting/source/basprov/basmethnode.hxx135
-rw-r--r--scripting/source/basprov/basmodnode.cxx148
-rw-r--r--scripting/source/basprov/basmodnode.hxx84
-rw-r--r--scripting/source/basprov/basprov.cxx609
-rw-r--r--scripting/source/basprov/basprov.hxx118
-rw-r--r--scripting/source/basprov/basprov.map9
-rw-r--r--scripting/source/basprov/basprov.xml50
-rw-r--r--scripting/source/basprov/basscript.cxx229
-rw-r--r--scripting/source/basprov/basscript.hxx92
-rw-r--r--scripting/source/basprov/makefile.mk77
-rw-r--r--scripting/source/dlgprov/dlgevtatt.cxx677
-rw-r--r--scripting/source/dlgprov/dlgevtatt.hxx167
-rw-r--r--scripting/source/dlgprov/dlgprov.cxx843
-rw-r--r--scripting/source/dlgprov/dlgprov.hxx155
-rw-r--r--scripting/source/dlgprov/dlgprov.map9
-rw-r--r--scripting/source/dlgprov/dlgprov.xml58
-rw-r--r--scripting/source/dlgprov/makefile.mk73
-rw-r--r--scripting/source/inc/bcholder.hxx73
-rw-r--r--scripting/source/inc/util/MiscUtils.hxx180
-rw-r--r--scripting/source/inc/util/scriptingconstants.hxx82
-rw-r--r--scripting/source/inc/util/util.hxx52
-rw-r--r--scripting/source/protocolhandler/exports.dxp3
-rw-r--r--scripting/source/protocolhandler/makefile.mk67
-rwxr-xr-xscripting/source/protocolhandler/protocolhandler.xml30
-rw-r--r--scripting/source/protocolhandler/scripthandler.cxx604
-rw-r--r--scripting/source/protocolhandler/scripthandler.hxx154
-rw-r--r--scripting/source/provider/ActiveMSPList.cxx320
-rw-r--r--scripting/source/provider/ActiveMSPList.hxx116
-rw-r--r--scripting/source/provider/BrowseNodeFactoryImpl.cxx800
-rw-r--r--scripting/source/provider/BrowseNodeFactoryImpl.hxx91
-rwxr-xr-xscripting/source/provider/MasterScriptProvider.cxx1040
-rw-r--r--scripting/source/provider/MasterScriptProvider.hxx160
-rw-r--r--scripting/source/provider/MasterScriptProviderFactory.cxx156
-rw-r--r--scripting/source/provider/MasterScriptProviderFactory.hxx88
-rw-r--r--scripting/source/provider/ProviderCache.cxx225
-rw-r--r--scripting/source/provider/ProviderCache.hxx111
-rw-r--r--scripting/source/provider/ScriptImpl.cxx125
-rw-r--r--scripting/source/provider/ScriptImpl.hxx116
-rwxr-xr-xscripting/source/provider/ScriptingContext.cxx119
-rw-r--r--scripting/source/provider/ScriptingContext.hxx94
-rw-r--r--scripting/source/provider/URIHelper.cxx325
-rw-r--r--scripting/source/provider/URIHelper.hxx111
-rw-r--r--scripting/source/provider/exports.dxp3
-rw-r--r--scripting/source/provider/makefile.mk57
-rwxr-xr-xscripting/source/provider/provider.xml34
-rw-r--r--scripting/source/pyprov/mailmerge.py353
-rw-r--r--scripting/source/pyprov/makefile.mk53
-rw-r--r--scripting/source/pyprov/officehelper.py97
-rw-r--r--scripting/source/pyprov/pythonscript.py967
-rw-r--r--scripting/source/runtimemgr/ScriptExecDialog.hrc31
-rw-r--r--scripting/source/runtimemgr/ScriptExecDialog.src39
-rw-r--r--scripting/source/runtimemgr/ScriptNameResolverImpl.cxx663
-rw-r--r--scripting/source/runtimemgr/ScriptNameResolverImpl.hxx113
-rwxr-xr-xscripting/source/runtimemgr/ScriptRuntimeManager.cxx569
-rw-r--r--scripting/source/runtimemgr/ScriptRuntimeManager.hxx152
-rw-r--r--scripting/source/runtimemgr/StorageBridge.cxx155
-rw-r--r--scripting/source/runtimemgr/StorageBridge.hxx88
-rw-r--r--scripting/source/runtimemgr/StorageBridgeFactory.cxx72
-rw-r--r--scripting/source/runtimemgr/StorageBridgeFactory.hxx61
-rw-r--r--scripting/source/runtimemgr/exports.dxp3
-rw-r--r--scripting/source/runtimemgr/makefile.mk52
-rwxr-xr-xscripting/source/runtimemgr/runtimemgr.xml47
-rw-r--r--scripting/source/storage/ScriptData.hxx94
-rw-r--r--scripting/source/storage/ScriptElement.cxx164
-rw-r--r--scripting/source/storage/ScriptElement.hxx64
-rw-r--r--scripting/source/storage/ScriptInfo.cxx376
-rw-r--r--scripting/source/storage/ScriptInfo.hxx78
-rw-r--r--scripting/source/storage/ScriptInfoImpl.hxx96
-rw-r--r--scripting/source/storage/ScriptMetadataImporter.cxx535
-rw-r--r--scripting/source/storage/ScriptMetadataImporter.hxx254
-rwxr-xr-xscripting/source/storage/ScriptSecurityManager.cxx608
-rwxr-xr-xscripting/source/storage/ScriptSecurityManager.hxx102
-rw-r--r--scripting/source/storage/ScriptStorage.cxx898
-rw-r--r--scripting/source/storage/ScriptStorage.hxx208
-rw-r--r--scripting/source/storage/ScriptStorageManager.cxx576
-rw-r--r--scripting/source/storage/ScriptStorageManager.hxx228
-rw-r--r--scripting/source/storage/ScriptURI.cxx230
-rw-r--r--scripting/source/storage/ScriptURI.hxx123
-rw-r--r--scripting/source/storage/XMLElement.cxx172
-rw-r--r--scripting/source/storage/XMLElement.hxx143
-rw-r--r--scripting/source/storage/exports.dxp3
-rw-r--r--scripting/source/storage/makefile.mk57
-rw-r--r--scripting/source/storage/storage.xml47
-rw-r--r--scripting/source/stringresource/makefile.mk66
-rw-r--r--scripting/source/stringresource/stringresource.cxx3088
-rw-r--r--scripting/source/stringresource/stringresource.hxx691
-rw-r--r--scripting/source/stringresource/stringresource.map9
-rw-r--r--scripting/source/stringresource/stringresource.xml36
-rwxr-xr-xscripting/util/ant.pmk59
-rw-r--r--scripting/util/exports.dxp3
-rw-r--r--scripting/util/makefile.mk71
-rwxr-xr-xscripting/util/makefile.pmk47
-rwxr-xr-xscripting/util/target.pmk32
-rw-r--r--scripting/workben/bindings/EditDebug.xdl36
-rw-r--r--scripting/workben/bindings/EventsBinding.xdl61
-rw-r--r--scripting/workben/bindings/HelpBinding.xdl30
-rw-r--r--scripting/workben/bindings/Highlight.xdl14
-rw-r--r--scripting/workben/bindings/KeyBinding.xdl59
-rw-r--r--scripting/workben/bindings/MacroEditor.xdl10
-rw-r--r--scripting/workben/bindings/MenuBinding.xdl65
-rw-r--r--scripting/workben/bindings/ScriptBinding.xba2093
-rw-r--r--scripting/workben/bindings/calckeybinding.xml94
-rw-r--r--scripting/workben/bindings/calcmenubar.xml319
-rw-r--r--scripting/workben/bindings/dialog.xlb6
-rw-r--r--scripting/workben/bindings/drawkeybinding.xml58
-rw-r--r--scripting/workben/bindings/drawmenubar.xml354
-rw-r--r--scripting/workben/bindings/eventbindings.xml4
-rw-r--r--scripting/workben/bindings/impresskeybinding.xml62
-rw-r--r--scripting/workben/bindings/impressmenubar.xml328
-rw-r--r--scripting/workben/bindings/manifest.xml14
-rw-r--r--scripting/workben/bindings/script.xlb4
-rw-r--r--scripting/workben/bindings/writerkeybinding.xml101
-rw-r--r--scripting/workben/bindings/writermenubar.xml281
-rwxr-xr-xscripting/workben/build.xml401
-rw-r--r--scripting/workben/data/ExampleSpreadSheetLatest.sxcbin0 -> 14635 bytes
-rw-r--r--scripting/workben/data/doc_with_beanshell_scripts.sxwbin0 -> 7044 bytes
-rw-r--r--scripting/workben/data/doc_with_one_script.sxwbin0 -> 6286 bytes
-rw-r--r--scripting/workben/data/doc_with_two_scripts.sxwbin0 -> 6308 bytes
-rw-r--r--scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.protocolhandler.Dispatch.csv5
-rw-r--r--scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.provider.Function.csv1
-rw-r--r--scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.provider.FunctionProvider.csv1
-rwxr-xr-xscripting/workben/data/objdsc/drafts.com.sun.star.script.framework.runtime.ScriptRuntimeManager.csv2
-rw-r--r--scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptInfo.csv8
-rw-r--r--scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptStorage.csv4
-rw-r--r--scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptStorageManager.csv6
-rw-r--r--scripting/workben/data/script_in_class_file.sxwbin0 -> 6976 bytes
-rw-r--r--scripting/workben/data/script_in_jar_file.sxwbin0 -> 8081 bytes
-rw-r--r--scripting/workben/data/share_scripts.zipbin0 -> 2248 bytes
-rw-r--r--scripting/workben/data/testdata/Function.csv4
-rw-r--r--scripting/workben/data/testdata/FunctionProvider.csv1
-rw-r--r--scripting/workben/data/testdata/ScriptInfo.csv8
-rw-r--r--scripting/workben/data/testdata/ScriptRuntimeManager.csv8
-rw-r--r--scripting/workben/data/testdata/ScriptStorage.csv4
-rw-r--r--scripting/workben/data/testdata/ScriptStorageManager.csv18
-rw-r--r--scripting/workben/data/user_scripts.zipbin0 -> 6890 bytes
-rw-r--r--scripting/workben/data/xscriptcontext_test_document.sxwbin0 -> 6580 bytes
-rw-r--r--scripting/workben/ifc/scripting/ScriptingUtils.java127
-rw-r--r--scripting/workben/ifc/scripting/SecurityDialogUtil.java179
-rw-r--r--scripting/workben/ifc/scripting/_XFunction.java172
-rw-r--r--scripting/workben/ifc/scripting/_XFunctionProvider.java104
-rw-r--r--scripting/workben/ifc/scripting/_XScriptInfo.java334
-rw-r--r--scripting/workben/ifc/scripting/_XScriptInfoAccess.java231
-rw-r--r--scripting/workben/ifc/scripting/_XScriptInvocation.java235
-rw-r--r--scripting/workben/ifc/scripting/_XScriptNameResolver.java189
-rw-r--r--scripting/workben/ifc/scripting/_XScriptSecurity.java412
-rw-r--r--scripting/workben/ifc/scripting/_XScriptStorageManager.java270
-rw-r--r--scripting/workben/ifc/scripting/_XScriptStorageRefresh.java93
-rw-r--r--scripting/workben/ifc/scripting/makefile.mk44
-rw-r--r--scripting/workben/installer/Banner.java30
-rw-r--r--scripting/workben/installer/ExceptionTraceHelper.java67
-rw-r--r--scripting/workben/installer/ExecCmd.java100
-rw-r--r--scripting/workben/installer/FileUpdater.java232
-rw-r--r--scripting/workben/installer/Final.java136
-rw-r--r--scripting/workben/installer/IdeFinal.java125
-rw-r--r--scripting/workben/installer/IdeUpdater.java172
-rw-r--r--scripting/workben/installer/IdeVersion.java349
-rw-r--r--scripting/workben/installer/IdeWelcome.java79
-rw-r--r--scripting/workben/installer/InstUtil.java463
-rw-r--r--scripting/workben/installer/InstallListener.java6
-rw-r--r--scripting/workben/installer/InstallWizard.java389
-rw-r--r--scripting/workben/installer/InstallationEvent.java22
-rw-r--r--scripting/workben/installer/LogStream.java54
-rw-r--r--scripting/workben/installer/NavPanel.java113
-rw-r--r--scripting/workben/installer/Navigation.java58
-rw-r--r--scripting/workben/installer/ProtocolHandler.xcu10
-rw-r--r--scripting/workben/installer/Register.java144
-rw-r--r--scripting/workben/installer/Scripting.BeanShell.xcu11
-rwxr-xr-xscripting/workben/installer/Scripting.JavaScript.xcu11
-rw-r--r--scripting/workben/installer/Scripting.xcs60
-rw-r--r--scripting/workben/installer/Version.java339
-rw-r--r--scripting/workben/installer/Welcome.java156
-rw-r--r--scripting/workben/installer/XmlUpdater.java427
-rw-r--r--scripting/workben/installer/ZipData.java103
-rw-r--r--scripting/workben/installer/sidebar.jpgbin0 -> 8393 bytes
-rwxr-xr-xscripting/workben/makefile.mk39
-rw-r--r--scripting/workben/mod/_scripting/Dispatch.java111
-rw-r--r--scripting/workben/mod/_scripting/Function.java98
-rw-r--r--scripting/workben/mod/_scripting/FunctionProvider.java85
-rw-r--r--scripting/workben/mod/_scripting/ScriptInfo.java111
-rw-r--r--scripting/workben/mod/_scripting/ScriptRuntimeManager.java68
-rw-r--r--scripting/workben/mod/_scripting/ScriptStorage.java106
-rw-r--r--scripting/workben/mod/_scripting/ScriptStorageManager.java85
-rw-r--r--scripting/workben/mod/_scripting/TestDataLoader.java126
-rw-r--r--scripting/workben/mod/_scripting/makefile.mk44
409 files changed, 61180 insertions, 0 deletions
diff --git a/scripting/README b/scripting/README
new file mode 100644
index 000000000000..686e4ad30f25
--- /dev/null
+++ b/scripting/README
@@ -0,0 +1,67 @@
+This module provides the source code for the Scripting Framework. For
+more information on the Scripting Framework, see the project web page:
+http://framework.openoffice.org/scripting/
+
+Source Code Structure
+=====================
+
+The following directories contain the source code currently used
+by the Scripting Framework:
+
+- source/provider
+
+C++ source for the implementations of the com.sun.star.script.provider.*
+and com.sun.star.script.browse.* UNO types. These types are used for
+browsing and executing scripts.
+
+- source/protocolhandler
+
+C++ for a ProtocolHandler implementation that handles vnd.sun.star.script
+URIs and dispatches them for execution to the Scripting Framework.
+
+- source/basprov
+
+C++ implementation of the LanguageScriptProvider UNO service for Basic
+
+- source/dlgprov
+
+C++ implementation of the DialogProvider UNO service used for loading
+UNO dialogs from various languages
+
+- java/com/sun/star/script/framework/provider
+
+Implementation of an abstract base class ScriptProvider which provides
+core methods for implementing Java based LanguageScriptProvider implemetations
+
+- java/com/sun/star/script/framework/provider/*
+
+BeanShell, JavaScript and Java LanguageScriptProvider implementations
+
+- java/com/sun/star/script/framework/browse/*
+
+BrowseNode implementations for the Java based LanguageScriptProviders
+
+- java/com/sun/star/script/framework/io
+- java/com/sun/star/script/framework/container
+
+Classes for performing script IO
+
+- examples
+
+Example scripts in BeanShell, JavaScript, Java and Python
+
+Deprecated Code
+===============
+
+- java/org/openoffice/*
+
+Support for developing scripts in IDEs such as NetBeans.
+
+- source/pyprov
+
+LanguageScriptProvider for Python
+
+- source/storage
+- source/runtimemgr
+
+Implementations of deprecated Scripting Framework UNO types
diff --git a/scripting/examples/basic/InsertColouredText.xba b/scripting/examples/basic/InsertColouredText.xba
new file mode 100644
index 000000000000..791689a15538
--- /dev/null
+++ b/scripting/examples/basic/InsertColouredText.xba
@@ -0,0 +1,124 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
+<script:module xmlns:script="http://openoffice.org/2000/script" script:name="InsertColouredText" script:language="StarBasic">&apos; ***
+&apos; InsertColouredText basic script
+&apos; Uses a user interface to insert text of a specified colour to the
+&apos; start and end of a document
+&apos;
+&apos; author Neil Montgomery
+&apos; created August 12, 2002
+&apos; ***
+
+
+&apos; Main subprocedure to start script
+Sub Main
+ dialogShow()
+End Sub
+
+
+&apos; Global reference to the dialog object
+Dim oDialog as Object
+
+
+&apos; Uses the loadDialog subprocedure to load and execute the dialog box
+Sub dialogShow
+ oDialog = loadDialog(&quot;Standard&quot;,&quot;InsertColouredTextDialog&quot;)
+ oDialog.execute()
+End Sub
+
+
+&apos; ***
+&apos; Loads the dialog from the dialog library
+&apos;
+&apos; param Libname the library name where dialog is stored
+&apos; param DialogName the name of the dialog
+&apos; param oLibContainer library container to hold the loaded dialog library (optional)
+&apos; return runtime dialog object
+&apos; ***
+Function loadDialog(Libname as String, DialogName as String, Optional oLibContainer)
+ Dim oLib as Object
+ Dim oLibDialog as Object
+ Dim oRuntimeDialog as Object
+
+ &apos; If the optional oLibContainer is not passed to the function then
+ &apos; DialogLibraries is loaded by default
+ If isMissing(oLibContainer ) then
+ oLibContainer = DialogLibraries
+ End If
+
+ &apos; Loads the specified library, then loads the dialog
+ oLibContainer.loadLibrary(LibName)
+ oLib = oLibContainer.getByName(Libname)
+ oLibDialog = oLib.getByName(DialogName)
+ oRuntimeDialog = createUnoDialog(oLibDialog)
+
+ &apos; Returns the runtime dialog object
+ loadDialog() = oRuntimeDialog
+End Function
+
+
+
+&apos; ***
+&apos; Gets the RGB integer values and new text string from the dialog
+&apos; then writes the new coloured text to the start and end of the document
+&apos;
+&apos; ***
+Sub getFromDialog
+ Dim oDocument As Object
+ Dim oText As Object
+ Dim oCursor As Object
+
+ &apos; Create a document object for the current document then create text and
+ &apos; cursor objects
+ oDocument = StarDesktop.ActiveFrame.Controller.Model
+ oText = oDocument.Text
+ oCursor = oText.createTextCursor()
+
+ &apos; Write the coloured text to the start and end of the document
+ oCursor.gotoStart(false)
+ oCursor.CharColor = getColor()
+ oCursor.setString(&quot;New text at start: &quot; + getNewText())
+ oCursor.gotoEnd(false)
+ oCursor.CharColor = getColor()
+ oCursor.setString(&quot;New text at end: &quot; + getNewText())
+End Sub
+
+
+
+&apos; ***
+&apos; Reads the RGB integer values from the dialog
+&apos;
+&apos; returns long representing the RGB value
+&apos; ***
+Function getColor() as Long
+ Dim oRedText as Object
+ Dim oGreenText as Object
+ Dim oBlueText as Object
+ Dim nColor As Long
+
+ &apos; Get the three RGB values
+ oRedText = oDialog.GetControl(&quot;RedTextBox&quot;)
+ oGreenText = oDialog.GetControl(&quot;GreenTextBox&quot;)
+ oBlueText = oDialog.GetControl(&quot;BlueTextBox&quot;)
+
+ &apos; Convert the values to long type and return the value
+ nColor = RGB(oRedText.Text,oGreenText.Text,oBlueText.Text)
+ getColor = nColor
+End Function
+
+
+
+&apos; ***
+&apos; Reads the new text from the dialog
+&apos;
+&apos; returns string the new text
+&apos; ***
+Function getNewText() as String
+ Dim oNewText As Object
+ Dim sNewText As String
+
+ &apos; Gets the string from dialog and returns the new text
+ oNewText = oDialog.GetControl(&quot;NewTextBox&quot;)
+ sNewText = oNewText.Text
+ getNewText = sNewText
+End Function</script:module> \ No newline at end of file
diff --git a/scripting/examples/basic/InsertColouredTextDialog.xdl b/scripting/examples/basic/InsertColouredTextDialog.xdl
new file mode 100644
index 000000000000..c2e8ace8466e
--- /dev/null
+++ b/scripting/examples/basic/InsertColouredTextDialog.xdl
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
+<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="InsertColouredTextDialog" dlg:left="113" dlg:top="112" dlg:width="178" dlg:height="138" dlg:closeable="true" dlg:moveable="true">
+ <dlg:bulletinboard>
+ <dlg:textfield dlg:id="RedTextBox" dlg:tab-index="0" dlg:left="37" dlg:top="26" dlg:width="20" dlg:height="17"/>
+ <dlg:textfield dlg:id="GreenTextBox" dlg:tab-index="1" dlg:left="73" dlg:top="26" dlg:width="20" dlg:height="17"/>
+ <dlg:textfield dlg:id="BlueTextBox" dlg:tab-index="2" dlg:left="109" dlg:top="26" dlg:width="20" dlg:height="17"/>
+ <dlg:textfield dlg:id="NewTextBox" dlg:tab-index="3" dlg:left="57" dlg:top="67" dlg:width="57" dlg:height="15"/>
+ <dlg:button dlg:id="CommandButton1" dlg:tab-index="4" dlg:left="49" dlg:top="97" dlg:width="75" dlg:height="15" dlg:value="Insert New Coloured Text">
+ <script:event script:event-name="on-mousedown" script:location="application" script:macro-name="Standard.InsertColouredText.getFromDialog" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:text dlg:id="Label1" dlg:tab-index="5" dlg:left="44" dlg:top="12" dlg:width="7" dlg:height="10" dlg:value="R"/>
+ <dlg:text dlg:id="Label2" dlg:tab-index="6" dlg:left="78" dlg:top="12" dlg:width="7" dlg:height="10" dlg:value="G"/>
+ <dlg:text dlg:id="Label3" dlg:tab-index="7" dlg:left="114" dlg:top="12" dlg:width="7" dlg:height="10" dlg:value="B"/>
+ <dlg:text dlg:id="Label4" dlg:tab-index="8" dlg:left="71" dlg:top="56" dlg:width="26" dlg:height="8" dlg:value="New Text"/>
+ </dlg:bulletinboard>
+</dlg:window> \ No newline at end of file
diff --git a/scripting/examples/basic/SearchAndReplace.xba b/scripting/examples/basic/SearchAndReplace.xba
new file mode 100644
index 000000000000..d98369e9f372
--- /dev/null
+++ b/scripting/examples/basic/SearchAndReplace.xba
@@ -0,0 +1,109 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
+<script:module xmlns:script="http://openoffice.org/2000/script" script:name="SearchAndReplace" script:language="StarBasic">&apos; ***
+&apos; SearchAndReplace basic script
+&apos; Uses a user interface to search and replace the specified strings
+&apos;
+&apos; author Neil Montgomery
+&apos; created August 12, 2002
+&apos; ***
+
+
+&apos; Main subprocedure to start script
+Sub Main
+ dialogShow()
+End Sub
+
+
+&apos; Global reference to the dialog object
+Dim oDialog as Object
+
+
+&apos; Uses the loadDialog subprocedure to load and execute the dialog box
+Sub dialogShow
+ oDialog = loadDialog(&quot;Standard&quot;,&quot;SearchAndReplaceDialog&quot;)
+ oDialog.execute()
+End Sub
+
+
+
+&apos; ***
+&apos; Loads the dialog from the dialog library
+&apos;
+&apos; param Libname the library name where dialog is stored
+&apos; param DialogName the name of the dialog
+&apos; param oLibContainer library container to hold the loaded dialog library (optional)
+&apos; return runtime dialog object
+&apos; ***
+Function loadDialog(Libname as String, DialogName as String, Optional oLibContainer)
+ Dim oLib as Object
+ Dim oLibDialog as Object
+ Dim oRuntimeDialog as Object
+
+ If isMissing(oLibContainer ) then
+ oLibContainer = DialogLibraries
+ End If
+ oLibContainer.loadLibrary(LibName)
+ oLib = oLibContainer.getByName(Libname)
+ oLibDialog = oLib.getByName(DialogName)
+ oRuntimeDialog = createUnoDialog(oLibDialog)
+ loadDialog() = oRuntimeDialog
+End Function
+
+
+
+&apos; ***
+&apos; Creates a connection to the current document.
+&apos; Gets the search and replace keys from the dialog and replaces all
+&apos; instances of the search key with the replace key.
+&apos;
+&apos; ***
+Sub getInfoFromDialog
+ Dim oDocument As Object
+ Dim oSearch As Object
+ Dim oFound As Object
+ Dim oFoundCursor As Object
+ Dim oSearchText as Object
+ Dim oReplaceText as Object
+
+ &apos; Create a document object for the current document then create text and
+ &apos; cursor objects
+ oDocument = StarDesktop.ActiveFrame.Controller.Model
+ oSearch = oDocument.createSearchDescriptor
+
+ &apos; Replace all instances of the search string with the replavce string
+ oSearch.SearchString = getSearchKey()
+ oSearch.ReplaceString = getReplaceKey()
+ oDocument.replaceAll(oSearch)
+End Sub
+
+
+&apos; ***
+&apos; Gets the search key string from the dialog
+&apos;
+&apos; returns string representing the search key
+&apos; ***
+Function getSearchKey() as String
+ Dim sSearch As String
+
+ &apos; Get the search key from the dialog
+ oSearchText = oDialog.GetControl(&quot;SearchKeyTextBox&quot;)
+ sSearch = oSearchText.Text
+ getSearchKey = sSearch
+End Function
+
+
+
+&apos; ***
+&apos; Gets the replace key string from the dialog
+&apos;
+&apos; returns string representing the replace key
+&apos; ***
+Function getReplaceKey() as String
+ Dim sReplace As String
+
+ &apos; Get the replace key from the dialog
+ oReplaceText = oDialog.GetControl(&quot;ReplaceKeyTextBox&quot;)
+ sReplace = oReplaceText.Text
+ getReplaceKey = sReplace
+End Function</script:module> \ No newline at end of file
diff --git a/scripting/examples/basic/SearchAndReplaceDialog.xdl b/scripting/examples/basic/SearchAndReplaceDialog.xdl
new file mode 100644
index 000000000000..7b0e90dd9779
--- /dev/null
+++ b/scripting/examples/basic/SearchAndReplaceDialog.xdl
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
+<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="SearchAndReplaceDialog" dlg:left="113" dlg:top="112" dlg:width="178" dlg:height="138" dlg:closeable="true" dlg:moveable="true">
+ <dlg:bulletinboard>
+ <dlg:textfield dlg:id="SearchKeyTextBox" dlg:tab-index="0" dlg:left="28" dlg:top="31" dlg:width="53" dlg:height="13"/>
+ <dlg:textfield dlg:id="ReplaceKeyTextBox" dlg:tab-index="1" dlg:left="102" dlg:top="31" dlg:width="51" dlg:height="13"/>
+ <dlg:button dlg:id="CommandButton1" dlg:tab-index="2" dlg:left="59" dlg:top="79" dlg:width="62" dlg:height="13" dlg:value="Search And Replace">
+ <script:event script:event-name="on-mousedown" script:location="application" script:macro-name="Standard.SearchAndReplace.getInfoFromDialog" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:text dlg:id="Label1" dlg:tab-index="3" dlg:left="37" dlg:top="20" dlg:width="33" dlg:height="8" dlg:value="Search Key"/>
+ <dlg:text dlg:id="Label2" dlg:tab-index="4" dlg:left="109" dlg:top="20" dlg:width="35" dlg:height="8" dlg:value="Replace Key"/>
+ </dlg:bulletinboard>
+</dlg:window> \ No newline at end of file
diff --git a/scripting/examples/basic/dialog.xlb b/scripting/examples/basic/dialog.xlb
new file mode 100644
index 000000000000..95dc3a1236a3
--- /dev/null
+++ b/scripting/examples/basic/dialog.xlb
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE library:library PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "library.dtd">
+<library:library xmlns:library="http://openoffice.org/2000/library" library:name="Standard" library:readonly="false" library:passwordprotected="false">
+ <library:element library:name="InsertColouredTextDialog"/>
+ <library:element library:name="SearchAndReplaceDialog"/>
+</library:library>
diff --git a/scripting/examples/basic/script.xlb b/scripting/examples/basic/script.xlb
new file mode 100644
index 000000000000..fa7dd61034cc
--- /dev/null
+++ b/scripting/examples/basic/script.xlb
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE library:library PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "library.dtd">
+<library:library xmlns:library="http://openoffice.org/2000/library" library:name="Standard" library:readonly="false" library:passwordprotected="false">
+ <library:element library:name="InsertColouredText"/>
+ <library:element library:name="SearchAndReplace"/>
+</library:library>
diff --git a/scripting/examples/beanshell/Capitalise/capitalise.bsh b/scripting/examples/beanshell/Capitalise/capitalise.bsh
new file mode 100644
index 000000000000..c059d3990846
--- /dev/null
+++ b/scripting/examples/beanshell/Capitalise/capitalise.bsh
@@ -0,0 +1,94 @@
+// Change the case of a selection, or current word from upper case,
+// to first char upper case, to all lower case to upper case...
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.frame.XModel;
+import com.sun.star.view.XSelectionSupplier;
+import com.sun.star.container.XIndexAccess;
+import com.sun.star.text.XText;
+import com.sun.star.text.XTextRange;
+import com.sun.star.text.XWordCursor;
+import com.sun.star.script.provider.XScriptContext;
+
+// return the new string based on the string passed in
+String getNewString( theString ) {
+ String newString;
+ if(theString==null || theString.length()==0) {
+ return newString;
+ }
+ // should we tokenize on "."?
+ if(Character.isUpperCase(theString.charAt(0)) && theString.length()>=2 && Character.isUpperCase(theString.charAt(1))) { // first two chars are UC => first UC, rest LC
+ newString=theString.substring(0,1).toUpperCase()+theString.substring(1).toLowerCase();
+ } else if (Character.isUpperCase(theString.charAt(0))) { // first char UC => all to LC
+ newString=theString.toLowerCase();
+ } else { // all to UC.
+ newString=theString.toUpperCase();
+ }
+ return newString;
+}
+
+//the method that does the work
+void capitalise() {
+
+ // get the number of regions selected
+ count = xIndexAccess.getCount();
+ if(count>=1) { //ie we have a selection
+ for(i=0;i<count;i++) {
+ // get the i-th region selected
+ xTextRange = (XTextRange)
+ UnoRuntime.queryInterface(XTextRange.class, xIndexAccess.getByIndex(i));
+ System.out.println("string: "+xTextRange.getString());
+ // get the selected string
+ theString = xTextRange.getString();
+ if(theString.length()==0) {
+ // sadly we can have a selection where nothing is selected
+ // in this case we get the XWordCursor and make a selection!
+ xText = (XText)
+ UnoRuntime.queryInterface(XText.class, xTextRange.getText());
+ xWordCursor = (XWordCursor)
+ UnoRuntime.queryInterface(XWordCursor.class, xText.createTextCursorByRange(xTextRange));
+ // move the Word cursor to the start of the word if its not
+ // already there
+ if(!xWordCursor.isStartOfWord()) {
+ xWordCursor.gotoStartOfWord(false);
+ }
+ // move the cursor to the next word, selecting all chars
+ // in between
+ xWordCursor.gotoNextWord(true);
+ // get the selected string
+ theString = xWordCursor.getString();
+ // get the new string
+ newString = getNewString(theString);
+ if(newString!=null) {
+ // set the new string
+ xWordCursor.setString(newString);
+ // keep the current selection
+ xSelectionSupplier.select(xWordCursor);
+ }
+ } else {
+ newString = getNewString( theString );
+ if(newString!=null) {
+ // set the new string
+ xTextRange.setString(newString);
+ // keep the current selection
+ xSelectionSupplier.select(xTextRange);
+ }
+ }
+
+ }
+ }
+}
+
+// The XSCRIPTCONTEXT variable is of type XScriptContext and is available to
+// all BeanShell scripts executed by the Script Framework
+xModel = (XModel)
+ UnoRuntime.queryInterface(XModel.class, XSCRIPTCONTEXT.getDocument());
+//the writer controller impl supports the css.view.XSelectionSupplier interface
+xSelectionSupplier = (XSelectionSupplier)
+ UnoRuntime.queryInterface(XSelectionSupplier.class, xModel.getCurrentController());
+//see section 7.5.1 of developers' guide
+xIndexAccess = (XIndexAccess)
+ UnoRuntime.queryInterface(XIndexAccess.class, xSelectionSupplier.getSelection());
+
+//call the method that does the work
+capitalise();
+return 0;
diff --git a/scripting/examples/beanshell/Capitalise/parcel-descriptor.xml b/scripting/examples/beanshell/Capitalise/parcel-descriptor.xml
new file mode 100755
index 000000000000..bf3730bf1da4
--- /dev/null
+++ b/scripting/examples/beanshell/Capitalise/parcel-descriptor.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="BeanShell" xmlns:parcel="scripting.dtd">
+
+ <script language="BeanShell">
+ <locale lang="en">
+ <displayname value="Capitalise"/>
+ <description>
+ Change the case of a selection, or current word from upper case, to first char upper case, to all lower case to upper case...
+ </description>
+ </locale>
+ <functionname value="capitalise.bsh"/>
+ <logicalname value="Capitalise.BeanShell"/>
+ </script>
+
+</parcel>
diff --git a/scripting/examples/beanshell/HelloWorld/helloworld.bsh b/scripting/examples/beanshell/HelloWorld/helloworld.bsh
new file mode 100644
index 000000000000..2e7655486680
--- /dev/null
+++ b/scripting/examples/beanshell/HelloWorld/helloworld.bsh
@@ -0,0 +1,17 @@
+// Hello World in BeanShell
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.text.XTextDocument;
+import com.sun.star.text.XText;
+import com.sun.star.text.XTextRange;
+
+// get the document from the scripting context which is made available to all
+// scripts
+oDoc = XSCRIPTCONTEXT.getDocument();
+//get the XTextDocument interface
+xTextDoc = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class,oDoc);
+//get the XText interface
+xText = xTextDoc.getText();
+// get an (empty) XTextRange at the end of the document
+xTextRange = xText.getEnd();
+// set the string
+xTextRange.setString( "Hello World (in BeanShell)" );
diff --git a/scripting/examples/beanshell/HelloWorld/parcel-descriptor.xml b/scripting/examples/beanshell/HelloWorld/parcel-descriptor.xml
new file mode 100755
index 000000000000..836470330891
--- /dev/null
+++ b/scripting/examples/beanshell/HelloWorld/parcel-descriptor.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="BeanShell" xmlns:parcel="scripting.dtd">
+
+ <script language="BeanShell">
+ <locale lang="en">
+ <displayname value="Hello World"/>
+ <description>
+ Adds the the string "Hello World" into the current text doc.
+ </description>
+ </locale>
+ <functionname value="helloworld.bsh"/>
+ <logicalname value="HelloWorld.BeanShell"/>
+ </script>
+
+</parcel>
diff --git a/scripting/examples/beanshell/Highlight/ButtonPressHandler.bsh b/scripting/examples/beanshell/Highlight/ButtonPressHandler.bsh
new file mode 100644
index 000000000000..363e12bb82b0
--- /dev/null
+++ b/scripting/examples/beanshell/Highlight/ButtonPressHandler.bsh
@@ -0,0 +1,106 @@
+// this code is bound to the events generated by the buttons in the dialog
+// it will close the dialog or find and highlight the text entered in the
+// dialog (depending on the button pressed)
+import com.sun.star.uno.*;
+import com.sun.star.awt.*;
+import com.sun.star.lang.*;
+import com.sun.star.beans.*;
+import com.sun.star.util.*;
+import com.sun.star.script.framework.browse.DialogFactory;
+
+// Get the ActionEvent object from the ARGUMENTS list
+ActionEvent event = (ActionEvent) ARGUMENTS[0];
+
+// Each argument is of type Any so we must use the AnyConverter class to
+// convert it into the interface or primitive type we expect
+XButton button = (XButton)AnyConverter.toObject(
+ new Type(XButton.class), event.Source);
+
+// We can now query for the model of the button and get its properties
+XControl control = (XControl)UnoRuntime.queryInterface(XControl.class, button);
+XControlModel cmodel = control.getModel();
+XPropertySet pset = (XPropertySet)UnoRuntime.queryInterface(
+ XPropertySet.class, cmodel);
+
+if (pset.getPropertyValue("Label").equals("Exit"))
+{
+ // We can get the XDialog in which this control appears by calling
+ // getContext() on the XControl interface
+ XDialog xDialog = (XDialog)UnoRuntime.queryInterface(
+ XDialog.class, control.getContext());
+
+ // Close the dialog
+ xDialog.endExecute();
+}
+else
+{
+ // We can get the list of controls for this dialog by calling
+ // getContext() on the XControl interface of the button
+ XControlContainer controls = (XControlContainer)UnoRuntime.queryInterface(
+ XControlContainer.class, control.getContext());
+
+ // Now get the text field control from the list
+ XTextComponent textField = (XTextComponent)
+ UnoRuntime.queryInterface(
+ XTextComponent.class, controls.getControl("HighlightTextField"));
+
+ String searchKey = textField.getText();
+
+ // highlight the text in red
+ java.awt.Color cRed = new java.awt.Color(255, 0, 0);
+ int red = cRed.getRGB();
+
+ XReplaceable replaceable = (XReplaceable)
+ UnoRuntime.queryInterface(XReplaceable.class, XSCRIPTCONTEXT.getDocument());
+
+ XReplaceDescriptor descriptor =
+ (XReplaceDescriptor) replaceable.createReplaceDescriptor();
+
+ // Gets a XPropertyReplace object for altering the properties
+ // of the replaced text
+ XPropertyReplace xPropertyReplace = (XPropertyReplace)
+ UnoRuntime.queryInterface(XPropertyReplace.class, descriptor);
+
+ // Sets the replaced text property fontweight value to Bold
+ PropertyValue wv = new PropertyValue("CharWeight", -1,
+ new Float(com.sun.star.awt.FontWeight.BOLD),
+ com.sun.star.beans.PropertyState.DIRECT_VALUE);
+
+ // Sets the replaced text property color value to RGB parameter
+ PropertyValue cv = new PropertyValue("CharColor", -1,
+ new Integer(red),
+ com.sun.star.beans.PropertyState.DIRECT_VALUE);
+
+ // Apply the properties
+ PropertyValue[] props = new PropertyValue[] { cv, wv };
+
+ try {
+ xPropertyReplace.setReplaceAttributes(props);
+
+ // Only matches whole words and case sensitive
+ descriptor.setPropertyValue(
+ "SearchCaseSensitive", new Boolean(true));
+ descriptor.setPropertyValue("SearchWords", new Boolean(true));
+ }
+ catch (com.sun.star.beans.UnknownPropertyException upe) {
+ System.err.println("Error setting up search properties");
+ return;
+ }
+ catch (com.sun.star.beans.PropertyVetoException pve) {
+ System.err.println("Error setting up search properties");
+ return;
+ }
+ catch (com.sun.star.lang.WrappedTargetException wte) {
+ System.err.println("Error setting up search properties");
+ return;
+ }
+
+ // Replaces all instances of searchKey with new Text properties
+ // and gets the number of instances of the searchKey
+ descriptor.setSearchString(searchKey);
+ descriptor.setReplaceString(searchKey);
+ replaceable.replaceAll(descriptor);
+}
+
+// BeanShell OpenOffice.org scripts should always return 0
+return 0;
diff --git a/scripting/examples/beanshell/Highlight/ShowDialog.bsh b/scripting/examples/beanshell/Highlight/ShowDialog.bsh
new file mode 100644
index 000000000000..e632c8f212c0
--- /dev/null
+++ b/scripting/examples/beanshell/Highlight/ShowDialog.bsh
@@ -0,0 +1,124 @@
+// this script serves as an example of how to launch a Basic Dialog
+// from a script
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.EventObject;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.text.XTextDocument;
+import com.sun.star.beans.PropertyValue;
+import com.sun.star.script.XLibraryContainer;
+import com.sun.star.awt.*;
+import com.sun.star.util.*;
+
+boolean tryLoadingLibrary( xmcf, context, name )
+{
+ try
+ {
+ obj = xmcf.createInstanceWithContext(
+ "com.sun.star.script.Application" + name + "LibraryContainer",
+ context.getComponentContext());
+
+ xLibraryContainer = (XLibraryContainer)
+ UnoRuntime.queryInterface(XLibraryContainer.class, obj);
+
+ System.err.println("Got XLibraryContainer");
+
+ serviceObj = context.getComponentContext().getValueByName(
+ "/singletons/com.sun.star.util.theMacroExpander");
+
+ xme = (XMacroExpander) AnyConverter.toObject(
+ new Type(XMacroExpander.class), serviceObj);
+
+ bootstrapName = "bootstraprc";
+ if (System.getProperty("os.name").startsWith("Windows"))
+ {
+ bootstrapName = "bootstrap.ini";
+ }
+
+ libURL = xme.expandMacros(
+ "${$BRAND_BASE_DIR/program/" + bootstrapName + "::BaseInstallation}" +
+ "/share/basic/ScriptBindingLibrary/" +
+ name.toLowerCase() + ".xlb/");
+
+ System.err.println("libURL is: " + libURL);
+
+ xLibraryContainer.createLibraryLink(
+ "ScriptBindingLibrary", libURL, false);
+
+ System.err.println("liblink created");
+
+ }
+ catch (com.sun.star.uno.Exception e)
+ {
+ System.err.println("Got an exception loading lib: " + e.getMessage());
+ return false;
+ }
+ return true;
+}
+
+// get the XMultiComponentFactory from the XSCRIPTCONTEXT
+XMultiComponentFactory xmcf =
+ XSCRIPTCONTEXT.getComponentContext().getServiceManager();
+
+Object[] args = new Object[1];
+args[0] = XSCRIPTCONTEXT.getDocument();
+
+Object obj;
+try {
+ // try to create an instance of the DialogProvider
+ obj = xmcf.createInstanceWithArgumentsAndContext(
+ "com.sun.star.awt.DialogProvider", args,
+ XSCRIPTCONTEXT.getComponentContext());
+ /*
+ obj = xmcf.createInstanceWithContext(
+ "com.sun.star.awt.DialogProvider",
+ XSCRIPTCONTEXT.getComponentContext());
+ */
+}
+catch (com.sun.star.uno.Exception e) {
+ System.err.println("Error getting DialogProvider object");
+ return 0;
+}
+
+// get the XDialogProvider interface from the object created above
+XDialogProvider xDialogProvider = (XDialogProvider)
+ UnoRuntime.queryInterface(XDialogProvider.class, obj);
+
+System.err.println("Got DialogProvider, now get dialog");
+
+try {
+ // try to create the Highlight dialog (found in the ScriptBindingLibrary)
+ findDialog = xDialogProvider.createDialog("vnd.sun.star.script:" +
+ "ScriptBindingLibrary.Highlight?location=application");
+ if( findDialog == null )
+ {
+ if (tryLoadingLibrary(xmcf, XSCRIPTCONTEXT, "Dialog") == false ||
+ tryLoadingLibrary(xmcf, XSCRIPTCONTEXT, "Script") == false)
+ {
+ System.err.println("Error loading ScriptBindingLibrary");
+ return 0;
+ }
+ else
+ {
+ // try to create the Highlight dialog (found in the ScriptBindingLibrary)
+ findDialog = xDialogProvider.createDialog("vnd.sun.star.script:" +
+ "ScriptBindingLibrary.Highlight?location=application");
+ }
+ }
+}
+catch (java.lang.Exception e) {
+ System.err.println("Got exception on first creating dialog: " +
+ e.getMessage());
+}
+
+// execute the dialog in a new thread (so that this script can finish)
+Thread t = new Thread() {
+ public void run() {
+ findDialog.execute();
+ }
+};
+t.start();
+
+return 0;
diff --git a/scripting/examples/beanshell/Highlight/highlighter.bsh b/scripting/examples/beanshell/Highlight/highlighter.bsh
new file mode 100644
index 000000000000..742471844309
--- /dev/null
+++ b/scripting/examples/beanshell/Highlight/highlighter.bsh
@@ -0,0 +1,149 @@
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.util.XReplaceable;
+import com.sun.star.util.XReplaceDescriptor;
+import com.sun.star.util.XPropertyReplace;
+import com.sun.star.beans.PropertyValue;
+import com.sun.star.text.XTextDocument;
+import com.sun.star.script.provider.XScriptContext;
+
+int replaceText(searchKey, color, bold) {
+
+ result = 0;
+
+ try {
+ // Create an XReplaceable object and an XReplaceDescriptor
+ replaceable = (XReplaceable)
+ UnoRuntime.queryInterface(XReplaceable.class, xTextDocument);
+
+ descriptor =
+ (XReplaceDescriptor) replaceable.createReplaceDescriptor();
+
+ // Gets a XPropertyReplace object for altering the properties
+ // of the replaced text
+ xPropertyReplace = (XPropertyReplace)
+ UnoRuntime.queryInterface(XPropertyReplace.class, descriptor);
+
+ // Sets the replaced text property fontweight value to Bold or Normal
+ wv = null;
+ if (bold) {
+ wv = new PropertyValue("CharWeight", -1,
+ new Float(com.sun.star.awt.FontWeight.BOLD),
+ com.sun.star.beans.PropertyState.DIRECT_VALUE);
+ }
+ else {
+ wv = new PropertyValue("CharWeight", -1,
+ new Float(com.sun.star.awt.FontWeight.NORMAL),
+ com.sun.star.beans.PropertyState.DIRECT_VALUE);
+ }
+
+ // Sets the replaced text property color value to RGB color parameter
+ cv = new PropertyValue("CharColor", -1, new Integer(color),
+ com.sun.star.beans.PropertyState.DIRECT_VALUE);
+
+ // Apply the properties
+ PropertyValue[] props = { cv, wv };
+ xPropertyReplace.setReplaceAttributes(props);
+
+ // Only matches whole words and case sensitive
+ descriptor.setPropertyValue("SearchCaseSensitive", new Boolean(true));
+ descriptor.setPropertyValue("SearchWords", new Boolean(true));
+
+ // Replaces all instances of searchKey with new Text properties
+ // and gets the number of instances of the searchKey
+ descriptor.setSearchString(searchKey);
+ descriptor.setReplaceString(searchKey);
+ result = replaceable.replaceAll(descriptor);
+
+ }
+ catch (Exception e) {
+ }
+
+ return result;
+}
+
+searchKey = "";
+
+// The XSCRIPTCONTEXT variable is of type XScriptContext and is available to
+// all BeanShell scripts executed by the Script Framework
+xTextDocument = (XTextDocument)
+ UnoRuntime.queryInterface(XTextDocument.class, XSCRIPTCONTEXT.getDocument());
+
+// Create a JButton and add an ActionListener
+// When clicked the value for the searchKey is read and passed to replaceText
+myListener = new ActionListener() {
+ actionPerformed(ActionEvent e) {
+ searchKey = findTextBox.getText();
+
+ if(searchKey.equalsIgnoreCase("")) {
+ JOptionPane.showMessageDialog(null,
+ "No text entered for search",
+ "No text", JOptionPane.INFORMATION_MESSAGE);
+ }
+ else {
+ // highlight the text in red
+ cRed = new Color(255, 0, 0);
+ red = cRed.getRGB();
+ num = replaceText(searchKey, red, true);
+
+ if(num > 0) {
+ int response = JOptionPane.showConfirmDialog(null,
+ searchKey + " was found " + num +
+ " times\nDo you wish to keep the text highlighted?",
+ "Confirm highlight", JOptionPane.YES_NO_OPTION,
+ JOptionPane.QUESTION_MESSAGE);
+
+ if (response == 1) {
+ cBlack = new Color(255, 255, 255);
+ black = cBlack.getRGB();
+ replaceText(searchKey, black, false);
+ }
+ }
+ else {
+ JOptionPane.showMessageDialog(null,
+ "No matches were found", "Not found",
+ JOptionPane.INFORMATION_MESSAGE);
+ }
+ }
+ }
+};
+
+
+exitListener = new ActionListener() {
+ actionPerformed(ActionEvent e) {
+ frame.dispose();
+ }
+};
+
+
+searchButton = new JButton("Highlight");
+searchButton.addActionListener(myListener);
+
+exitButton = new JButton("Exit");
+exitButton.addActionListener(exitListener);
+
+buttonPanel = new JPanel();
+buttonPanel.setLayout(new FlowLayout());
+buttonPanel.add(searchButton);
+buttonPanel.add(exitButton);
+
+
+// Create a JPanel containing one JTextField for the search text.
+searchPanel = new JPanel();
+searchPanel.setLayout(new FlowLayout());
+findTextBox = new JTextField(20);
+findWhat = new JLabel("Find What: ");
+searchPanel.add(findWhat);
+searchPanel.add(findTextBox);
+
+// Create frame and add a window listener
+frame = new JFrame("Highlight Text");
+frame.setSize(350,130);
+frame.setLocation(430,430);
+frame.setResizable(false);
+// Add the panel and button to the frame
+frame.getContentPane().setLayout(new GridLayout(2,1,10,10));
+frame.getContentPane().add(searchPanel);
+frame.getContentPane().add(buttonPanel);
+
+frame.setVisible(true);
+frame.pack();
diff --git a/scripting/examples/beanshell/Highlight/parcel-descriptor.xml b/scripting/examples/beanshell/Highlight/parcel-descriptor.xml
new file mode 100755
index 000000000000..dad8560db8ea
--- /dev/null
+++ b/scripting/examples/beanshell/Highlight/parcel-descriptor.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="BeanShell" xmlns:parcel="scripting.dtd">
+ <script language="BeanShell">
+ <locale lang="en">
+ <displayname value="ShowDialog" />
+ <description>
+ Example of how to show a dialog from BeanShell
+ </description>
+ </locale>
+ <functionname value="ShowDialog.bsh" />
+ <logicalname value="ShowDialog.BeanShell" />
+ </script>
+ <script language="BeanShell">
+ <locale lang="en">
+ <displayname value="ButtonPressHandler" />
+ <description>
+ Example of handle button press events for the Dialog
+ </description>
+ </locale>
+ <functionname value="ButtonPressHandler.bsh" />
+ <logicalname value="ButtonPressHandler.BeanShell" />
+ </script>
+</parcel>
+
diff --git a/scripting/examples/beanshell/InteractiveBeanShell/interactive.bsh b/scripting/examples/beanshell/InteractiveBeanShell/interactive.bsh
new file mode 100755
index 000000000000..5311882c1be3
--- /dev/null
+++ b/scripting/examples/beanshell/InteractiveBeanShell/interactive.bsh
@@ -0,0 +1,4 @@
+//Pops up a window into which you can type BeanShell code and run it
+//against the current document
+editor();
+return 0;
diff --git a/scripting/examples/beanshell/InteractiveBeanShell/parcel-descriptor.xml b/scripting/examples/beanshell/InteractiveBeanShell/parcel-descriptor.xml
new file mode 100644
index 000000000000..5c2ff6c182c8
--- /dev/null
+++ b/scripting/examples/beanshell/InteractiveBeanShell/parcel-descriptor.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="BeanShell" xmlns:parcel="scripting.dtd">
+
+ <script language="BeanShell">
+ <locale lang="en">
+ <displayname value="Interactive BeanShell"/>
+ <description>
+ Pops up a window into which you can type BeanShell code and run it against the current document
+ </description>
+ </locale>
+ <functionname value="interactive.bsh"/>
+ <logicalname value="Interactive.BeanShell"/>
+ </script>
+
+</parcel>
diff --git a/scripting/examples/beanshell/MemoryUsage/memusage.bsh b/scripting/examples/beanshell/MemoryUsage/memusage.bsh
new file mode 100644
index 000000000000..2200b7b29203
--- /dev/null
+++ b/scripting/examples/beanshell/MemoryUsage/memusage.bsh
@@ -0,0 +1,120 @@
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.uno.Type;
+import com.sun.star.lang.XComponent;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.frame.XComponentLoader;
+import com.sun.star.document.XEmbeddedObjectSupplier;
+import com.sun.star.awt.ActionEvent;
+import com.sun.star.awt.Rectangle;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.beans.PropertyValue;
+
+import com.sun.star.container.*;
+import com.sun.star.chart.*;
+import com.sun.star.table.*;
+import com.sun.star.sheet.*;
+
+import com.sun.star.script.provider.XScriptContext;
+
+createSpreadsheet()
+{
+ loader = (XComponentLoader)
+ UnoRuntime.queryInterface(
+ XComponentLoader.class, XSCRIPTCONTEXT.getDesktop());
+
+ comp = loader.loadComponentFromURL(
+ "private:factory/scalc", "_blank", 4, new PropertyValue[0]);
+
+ doc = (XSpreadsheetDocument)
+ UnoRuntime.queryInterface(XSpreadsheetDocument.class, comp);
+
+ index = (XIndexAccess)
+ UnoRuntime.queryInterface(XIndexAccess.class, doc.getSheets());
+
+ sheet = (XSpreadsheet) AnyConverter.toObject(
+ new Type(com.sun.star.sheet.XSpreadsheet.class), index.getByIndex(0));
+
+ return sheet;
+}
+
+addData(sheet, date, total, free)
+{
+ // set the labels
+ sheet.getCellByPosition(0, 0).setFormula("Used");
+ sheet.getCellByPosition(0, 1).setFormula("Free");
+ sheet.getCellByPosition(0, 2).setFormula("Total");
+
+ // set the values in the cells
+ sheet.getCellByPosition(1, 0).setValue(total - free);
+ sheet.getCellByPosition(1, 1).setValue(free);
+ sheet.getCellByPosition(1, 2).setValue(total);
+}
+
+addChart(sheet)
+{
+ rect = new Rectangle();
+ rect.X = 500;
+ rect.Y = 3000;
+ rect.Width = 10000;
+ rect.Height = 8000;
+
+ range = (XCellRange) UnoRuntime.queryInterface(XCellRange.class, sheet);
+ myRange = range.getCellRangeByName("A1:B2");
+
+ rangeAddr = (XCellRangeAddressable)
+ UnoRuntime.queryInterface(XCellRangeAddressable.class, myRange);
+
+ myAddr = rangeAddr.getRangeAddress();
+
+ CellRangeAddress[] addr = new CellRangeAddress[1];
+ addr[0] = myAddr;
+
+ supp = (XTableChartsSupplier)
+ UnoRuntime.queryInterface( XTableChartsSupplier.class, sheet);
+ charts = supp.getCharts();
+ charts.addNewByName("Example", rect, addr, false, true);
+
+ try { Thread.sleep(3000); } catch (java.lang.InterruptedException e) { }
+
+ // get the diagram and Change some of the properties
+ chartsAccess = (XNameAccess)
+ UnoRuntime.queryInterface( XNameAccess.class, charts);
+
+ tchart = (XTableChart)
+ UnoRuntime.queryInterface(
+ XTableChart.class, chartsAccess.getByName("Example"));
+
+ eos = (XEmbeddedObjectSupplier)
+ UnoRuntime.queryInterface( XEmbeddedObjectSupplier.class, tchart );
+ xifc = eos.getEmbeddedObject();
+
+ xChart = (XChartDocument)
+ UnoRuntime.queryInterface(XChartDocument.class, xifc);
+
+ xDocMSF = (XMultiServiceFactory)
+ UnoRuntime.queryInterface(XMultiServiceFactory.class, xChart);
+
+ diagObject = xDocMSF.createInstance("com.sun.star.chart.PieDiagram");
+ xDiagram = (XDiagram)
+ UnoRuntime.queryInterface(XDiagram.class, diagObject);
+ xChart.setDiagram(xDiagram);
+
+ propset = (XPropertySet)
+ UnoRuntime.queryInterface( XPropertySet.class, xChart.getTitle() );
+ propset.setPropertyValue("String", "JVM Memory Usage");
+}
+
+runtime = Runtime.getRuntime();
+generator = new Random();
+date = new Date();
+
+// allocate a random number of bytes so that the data changes
+len = (int)(generator.nextFloat() * runtime.freeMemory() / 5);
+bytes = new byte[len];
+
+sheet = createSpreadsheet();
+addData(sheet, date.toString(), runtime.totalMemory(), runtime.freeMemory());
+addChart(sheet);
+
+return 0;
diff --git a/scripting/examples/beanshell/MemoryUsage/parcel-descriptor.xml b/scripting/examples/beanshell/MemoryUsage/parcel-descriptor.xml
new file mode 100644
index 000000000000..f2783e9067ed
--- /dev/null
+++ b/scripting/examples/beanshell/MemoryUsage/parcel-descriptor.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="BeanShell" xmlns:parcel="scripting.dtd">
+
+ <script language="BeanShell">
+ <locale lang="en">
+ <displayname value="BeanShell JVM Usage"/>
+ <description>
+ Updates a spreadsheet with the current memory usage statistics for the Java Virtual Machine
+ </description>
+ </locale>
+ <functionname value="memusage.bsh"/>
+ <logicalname value="MemoryUsage.BeanShell"/>
+ </script>
+
+</parcel>
diff --git a/scripting/examples/beanshell/WordCount/parcel-descriptor.xml b/scripting/examples/beanshell/WordCount/parcel-descriptor.xml
new file mode 100755
index 000000000000..fb6b5f50109c
--- /dev/null
+++ b/scripting/examples/beanshell/WordCount/parcel-descriptor.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="BeanShell" xmlns:parcel="scripting.dtd">
+
+ <script language="BeanShell">
+ <locale lang="en">
+ <displayname value="Word Count"/>
+ <description>
+ Provides a word count of the selected text in A Writer document.
+ </description>
+ </locale>
+ <functionname value="wordcount.bsh"/>
+ <logicalname value="WordCount.BeanShell"/>
+ </script>
+
+</parcel>
diff --git a/scripting/examples/beanshell/WordCount/wordcount.bsh b/scripting/examples/beanshell/WordCount/wordcount.bsh
new file mode 100644
index 000000000000..a2018c00d420
--- /dev/null
+++ b/scripting/examples/beanshell/WordCount/wordcount.bsh
@@ -0,0 +1,64 @@
+//Provides a word count of the selected text in A Writer document.
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.frame.XModel;
+import com.sun.star.view.XSelectionSupplier;
+import com.sun.star.container.XIndexAccess;
+import com.sun.star.text.XText;
+import com.sun.star.text.XTextRange;
+import com.sun.star.script.provider.XScriptContext;
+
+// display the count in a Swing dialog
+void doDisplay(numWords) {
+ wordsLabel = new JLabel("Word count = " + numWords);
+ closeButton = new JButton("Close");
+ frame = new JFrame("Word Count");
+ closeButton.addActionListener(new ActionListener() {
+ actionPerformed(ActionEvent e) {
+ frame.setVisible(false);
+ }
+ });
+ frame.getContentPane().setLayout(new BorderLayout());
+ frame.getContentPane().add(wordsLabel, BorderLayout.CENTER);
+ frame.getContentPane().add(closeButton, BorderLayout.SOUTH);
+ frame.pack();
+ frame.setSize(190,90);
+ frame.setLocation(430,430);
+ frame.setVisible(true);
+}
+
+int wordcount() {
+
+ result = 0;
+
+ // iterate through each of the selections
+ count = xIndexAccess.getCount();
+ for(i=0;i<count;i++) {
+ // get the XTextRange of the selection
+ xTextRange = (XTextRange)
+ UnoRuntime.queryInterface(XTextRange.class, xIndexAccess.getByIndex(i));
+ //System.out.println("string: "+xTextRange.getString());
+ // use the standard J2SE delimiters to tokenize the string
+ // obtained from the XTextRange
+ strTok = new StringTokenizer(xTextRange.getString());
+ result += strTok.countTokens();
+ }
+
+ doDisplay(result);
+ return result;
+}
+
+// The XSCRIPTCONTEXT variable is of type XScriptContext and is available to
+// all BeanShell scripts executed by the Script Framework
+xModel = (XModel)
+ UnoRuntime.queryInterface(XModel.class, XSCRIPTCONTEXT.getDocument());
+//the writer controller impl supports the css.view.XSelectionSupplier interface
+xSelectionSupplier = (XSelectionSupplier)
+ UnoRuntime.queryInterface(XSelectionSupplier.class, xModel.getCurrentController());
+//see section 7.5.1 of developers' guide
+// the getSelection provides an XIndexAccess to the one or more selections
+xIndexAccess = (XIndexAccess)
+ UnoRuntime.queryInterface(XIndexAccess.class, xSelectionSupplier.getSelection());
+
+count = wordcount();
+System.out.println("count = "+count);
+return 0;
diff --git a/scripting/examples/delzip b/scripting/examples/delzip
new file mode 100644
index 000000000000..636fda90bfcb
--- /dev/null
+++ b/scripting/examples/delzip
@@ -0,0 +1 @@
+ECHO is OFF
diff --git a/scripting/examples/java/HelloWorld/HelloWorld.java b/scripting/examples/java/HelloWorld/HelloWorld.java
new file mode 100644
index 000000000000..eaed56fc6063
--- /dev/null
+++ b/scripting/examples/java/HelloWorld/HelloWorld.java
@@ -0,0 +1,22 @@
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.text.XTextDocument;
+import com.sun.star.text.XTextRange;
+import com.sun.star.text.XText;
+/**
+ * HelloWorld class
+ *
+ */
+public class HelloWorld {
+ public static void printHW(XScriptContext xSc) {
+
+ // getting the text document object
+ XTextDocument xtextdocument = (XTextDocument) UnoRuntime.queryInterface(
+XTextDocument.class, xSc.getDocument());
+ XText xText = xtextdocument.getText();
+ XTextRange xTextRange = xText.getEnd();
+ xTextRange.setString( "Hello World (in Java)" );
+
+ }// printHW
+
+}
diff --git a/scripting/examples/java/HelloWorld/parcel-descriptor.xml b/scripting/examples/java/HelloWorld/parcel-descriptor.xml
new file mode 100644
index 000000000000..692933afbae2
--- /dev/null
+++ b/scripting/examples/java/HelloWorld/parcel-descriptor.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<parcel language="Java" xmlns:parcel="scripting.dtd">
+ <script language="Java">
+ <locale lang="en">
+ <displayname value="HelloWorld.Java"/>
+ <description>
+ Prints "Helo World".
+ </description>
+ </locale>
+ <functionname value="HelloWorld.printHW"/>
+ <logicalname value="HelloWorld.printHW"/>
+ <languagedepprops>
+ <prop name="classpath" value="HelloWorld.jar"/>
+ </languagedepprops>
+ </script>
+</parcel>
diff --git a/scripting/examples/java/Highlight/HighlightText.java b/scripting/examples/java/Highlight/HighlightText.java
new file mode 100644
index 000000000000..53c98fdb177b
--- /dev/null
+++ b/scripting/examples/java/Highlight/HighlightText.java
@@ -0,0 +1,223 @@
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.EventObject;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.text.XTextDocument;
+import com.sun.star.beans.PropertyValue;
+import com.sun.star.script.XLibraryContainer;
+import com.sun.star.awt.*;
+import com.sun.star.util.*;
+
+import java.awt.Color;
+
+public class HighlightText implements com.sun.star.awt.XActionListener {
+
+ // UNO awt components of the Highlight dialog
+ XDialog findDialog = null;
+ XTextComponent findTextBox;
+
+ // The document being searched
+ XTextDocument theDocument;
+
+ // The text to be searched for
+ private String searchKey = "";
+
+ public void showForm(XScriptContext context) {
+ System.err.println("Starting showForm");
+
+ XMultiComponentFactory xmcf =
+ context.getComponentContext().getServiceManager();
+
+ Object[] args = new Object[1];
+ args[0] = context.getDocument();
+
+ Object obj;
+ try {
+ obj = xmcf.createInstanceWithArgumentsAndContext(
+ "com.sun.star.awt.DialogProvider", args,
+ context.getComponentContext());
+ }
+ catch (com.sun.star.uno.Exception e) {
+ System.err.println("Error getting DialogProvider object");
+ return;
+ }
+
+ XDialogProvider xDialogProvider = (XDialogProvider)
+ UnoRuntime.queryInterface(XDialogProvider.class, obj);
+
+ System.err.println("Got DialogProvider, now get dialog");
+
+ try {
+ findDialog = xDialogProvider.createDialog(
+ "vnd.sun.star.script:" +
+ "ScriptBindingLibrary.Highlight?location=application");
+ }
+ catch (java.lang.Exception e) {
+ System.err.println("Got exception on first creating dialog: " +
+ e.getMessage());
+ }
+
+ if (findDialog == null) {
+ if (tryLoadingLibrary(xmcf, context, "Dialog") == false ||
+ tryLoadingLibrary(xmcf, context, "Script") == false)
+ {
+ System.err.println("Error loading ScriptBindingLibrary");
+ return;
+ }
+ try {
+ findDialog = xDialogProvider.createDialog(
+ "vnd.sun.star.script://" +
+ "ScriptBindingLibrary.Highlight?location=application");
+ }
+ catch (com.sun.star.lang.IllegalArgumentException iae) {
+ System.err.println("Error loading ScriptBindingLibrary");
+ return;
+ }
+ }
+
+ XControlContainer controls = (XControlContainer)
+ UnoRuntime.queryInterface(XControlContainer.class, findDialog);
+
+ XButton highlightButton = (XButton) UnoRuntime.queryInterface(
+ XButton.class, controls.getControl("HighlightButton"));
+ highlightButton.setActionCommand("Highlight");
+
+ findTextBox = (XTextComponent) UnoRuntime.queryInterface(
+ XTextComponent.class, controls.getControl("HighlightTextField"));
+
+ XButton exitButton = (XButton) UnoRuntime.queryInterface(
+ XButton.class, controls.getControl("ExitButton"));
+ exitButton.setActionCommand("Exit");
+
+ theDocument = (XTextDocument) UnoRuntime.queryInterface(
+ XTextDocument.class, context.getDocument());
+
+ highlightButton.addActionListener(this);
+ exitButton.addActionListener(this);
+
+ findDialog.execute();
+
+ return;
+ }
+
+ public void actionPerformed(ActionEvent e) {
+ if (e.ActionCommand.equals("Exit")) {
+ findDialog.endExecute();
+ return;
+ }
+ else if (e.ActionCommand.equals("Highlight")) {
+ searchKey = findTextBox.getText();
+
+ // highlight the text in red
+ Color cRed = new Color(255, 0, 0);
+ int red = cRed.getRGB();
+
+ XReplaceable replaceable = (XReplaceable)
+ UnoRuntime.queryInterface(XReplaceable.class, theDocument);
+
+ XReplaceDescriptor descriptor =
+ (XReplaceDescriptor) replaceable.createReplaceDescriptor();
+
+ // Gets a XPropertyReplace object for altering the properties
+ // of the replaced text
+ XPropertyReplace xPropertyReplace = (XPropertyReplace)
+ UnoRuntime.queryInterface(XPropertyReplace.class, descriptor);
+
+ // Sets the replaced text property fontweight value to Bold
+ PropertyValue wv = new PropertyValue("CharWeight", -1,
+ new Float(com.sun.star.awt.FontWeight.BOLD),
+ com.sun.star.beans.PropertyState.DIRECT_VALUE);
+
+ // Sets the replaced text property color value to RGB parameter
+ PropertyValue cv = new PropertyValue("CharColor", -1,
+ new Integer(red),
+ com.sun.star.beans.PropertyState.DIRECT_VALUE);
+
+ // Apply the properties
+ PropertyValue[] props = new PropertyValue[] { cv, wv };
+
+ try {
+ xPropertyReplace.setReplaceAttributes(props);
+
+ // Only matches whole words and case sensitive
+ descriptor.setPropertyValue(
+ "SearchCaseSensitive", new Boolean(true));
+ descriptor.setPropertyValue("SearchWords", new Boolean(true));
+ }
+ catch (com.sun.star.beans.UnknownPropertyException upe) {
+ System.err.println("Error setting up search properties");
+ return;
+ }
+ catch (com.sun.star.beans.PropertyVetoException pve) {
+ System.err.println("Error setting up search properties");
+ return;
+ }
+ catch (com.sun.star.lang.WrappedTargetException wte) {
+ System.err.println("Error setting up search properties");
+ return;
+ }
+ catch (com.sun.star.lang.IllegalArgumentException iae) {
+ System.err.println("Error setting up search properties");
+ return;
+ }
+
+ // Replaces all instances of searchKey with new Text properties
+ // and gets the number of instances of the searchKey
+ descriptor.setSearchString(searchKey);
+ descriptor.setReplaceString(searchKey);
+ replaceable.replaceAll(descriptor);
+ }
+ }
+
+ public void disposing(EventObject o)
+ {
+ // do nothing
+ }
+
+ private boolean tryLoadingLibrary(
+ XMultiComponentFactory xmcf, XScriptContext context, String name)
+ {
+ System.err.println("Try to load ScriptBindingLibrary");
+
+ try {
+ Object obj = xmcf.createInstanceWithContext(
+ "com.sun.star.script.Application" + name + "LibraryContainer",
+ context.getComponentContext());
+
+ XLibraryContainer xLibraryContainer = (XLibraryContainer)
+ UnoRuntime.queryInterface(XLibraryContainer.class, obj);
+
+ System.err.println("Got XLibraryContainer");
+
+ Object serviceObj = context.getComponentContext().getValueByName(
+ "/singletons/com.sun.star.util.theMacroExpander");
+
+ XMacroExpander xme = (XMacroExpander) AnyConverter.toObject(
+ new Type(XMacroExpander.class), serviceObj);
+
+ String bootstrapName = "bootstraprc";
+ if (System.getProperty("os.name").startsWith("Windows")) {
+ bootstrapName = "bootstrap.ini";
+ }
+
+ String libURL = xme.expandMacros(
+ "${$BRAND_BASE_DIR/program/" + bootstrapName + "::BaseInstallation}" +
+ "/share/basic/ScriptBindingLibrary/" +
+ name.toLowerCase() + ".xlb/");
+
+ System.err.println("libURL is: " + libURL);
+
+ xLibraryContainer.createLibraryLink(
+ "ScriptBindingLibrary", libURL, false);
+
+ System.err.println("liblink created");
+
+ } catch (com.sun.star.uno.Exception e) {
+ System.err.println("Got an exception loading lib: " + e.getMessage());
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/scripting/examples/java/Highlight/parcel-descriptor.xml b/scripting/examples/java/Highlight/parcel-descriptor.xml
new file mode 100755
index 000000000000..2612eaec4632
--- /dev/null
+++ b/scripting/examples/java/Highlight/parcel-descriptor.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="Java" xmlns:parcel="scripting.dtd">
+ <script language="Java">
+ <locale lang="en">
+ <displayname value="HighlightText.showForm"/>
+ <description>
+ Text highlighting
+ </description>
+ </locale>
+ <functionname value="HighlightText.showForm"/>
+ <logicalname value="HighlightText.showForm"/>
+ <languagedepprops>
+ <prop name="classpath" value="Highlight.jar"/>
+ </languagedepprops>
+ </script>
+</parcel>
diff --git a/scripting/examples/java/MemoryUsage/MemoryUsage.java b/scripting/examples/java/MemoryUsage/MemoryUsage.java
new file mode 100644
index 000000000000..727f94a9291c
--- /dev/null
+++ b/scripting/examples/java/MemoryUsage/MemoryUsage.java
@@ -0,0 +1,141 @@
+import java.util.Random;
+import java.util.Date;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.XInterface;
+import com.sun.star.lang.XComponent;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.frame.XComponentLoader;
+import com.sun.star.document.XEmbeddedObjectSupplier;
+import com.sun.star.awt.Rectangle;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.beans.PropertyValue;
+
+import com.sun.star.container.*;
+import com.sun.star.chart.*;
+import com.sun.star.table.*;
+import com.sun.star.sheet.*;
+
+import com.sun.star.script.provider.XScriptContext;
+
+public class MemoryUsage
+{
+ // public void updateMemoryUsage(XScriptContext ctxt, ActionEvent evt)
+ public void updateMemoryUsage(XScriptContext ctxt)
+ throws Exception
+ {
+ XSpreadsheet sheet = createSpreadsheet(ctxt);
+
+ Runtime runtime = Runtime.getRuntime();
+ Random generator = new Random();
+ Date date = new Date();
+
+ // allocate a random amount of memory
+ int len = (int)(generator.nextFloat() * runtime.freeMemory() / 5);
+ byte[] bytes = new byte[len];
+
+ addData(sheet, date.toString(),
+ runtime.totalMemory(), runtime.freeMemory());
+
+ addChart(sheet);
+ }
+
+ private XSpreadsheet createSpreadsheet(XScriptContext ctxt)
+ throws Exception
+ {
+ XComponentLoader loader = (XComponentLoader)
+ UnoRuntime.queryInterface(
+ XComponentLoader.class, ctxt.getDesktop());
+
+ XComponent comp = loader.loadComponentFromURL(
+ "private:factory/scalc", "_blank", 4, new PropertyValue[0]);
+
+ XSpreadsheetDocument doc = (XSpreadsheetDocument)
+ UnoRuntime.queryInterface(XSpreadsheetDocument.class, comp);
+
+ XIndexAccess index = (XIndexAccess)
+ UnoRuntime.queryInterface(XIndexAccess.class, doc.getSheets());
+
+ XSpreadsheet sheet = (XSpreadsheet) AnyConverter.toObject(
+ new Type(com.sun.star.sheet.XSpreadsheet.class), index.getByIndex(0));
+
+ return sheet;
+ }
+
+ private void addData(
+ XSpreadsheet sheet, String date, long total, long free)
+ throws Exception
+ {
+ sheet.getCellByPosition(0, 0).setFormula("Used");
+ sheet.getCellByPosition(0, 1).setFormula("Free");
+ sheet.getCellByPosition(0, 2).setFormula("Total");
+
+ sheet.getCellByPosition(1, 0).setValue(total - free);
+ sheet.getCellByPosition(1, 1).setValue(free);
+ sheet.getCellByPosition(1, 2).setValue(total);
+ }
+
+ private void addChart(XSpreadsheet sheet)
+ throws Exception
+ {
+ Rectangle rect = new Rectangle();
+ rect.X = 500;
+ rect.Y = 3000;
+ rect.Width = 10000;
+ rect.Height = 8000;
+
+ XCellRange range = (XCellRange)
+ UnoRuntime.queryInterface(XCellRange.class, sheet);
+
+ XCellRange myRange =
+ range.getCellRangeByName("A1:B2");
+
+ XCellRangeAddressable rangeAddr = (XCellRangeAddressable)
+ UnoRuntime.queryInterface(XCellRangeAddressable.class, myRange);
+
+ CellRangeAddress myAddr = rangeAddr.getRangeAddress();
+
+ CellRangeAddress[] addr = new CellRangeAddress[1];
+ addr[0] = myAddr;
+
+ XTableChartsSupplier supp = (XTableChartsSupplier)
+ UnoRuntime.queryInterface( XTableChartsSupplier.class, sheet);
+
+ XTableCharts charts = supp.getCharts();
+ charts.addNewByName("Example", rect, addr, false, true);
+
+ try { Thread.sleep(3000); } catch (java.lang.InterruptedException e) { }
+
+ // get the diagram and Change some of the properties
+ XNameAccess chartsAccess = (XNameAccess)
+ UnoRuntime.queryInterface( XNameAccess.class, charts);
+
+ XTableChart tchart = (XTableChart)
+ UnoRuntime.queryInterface(
+ XTableChart.class, chartsAccess.getByName("Example"));
+
+ XEmbeddedObjectSupplier eos = (XEmbeddedObjectSupplier)
+ UnoRuntime.queryInterface( XEmbeddedObjectSupplier.class, tchart );
+
+ XInterface xifc = eos.getEmbeddedObject();
+
+ XChartDocument xChart = (XChartDocument)
+ UnoRuntime.queryInterface(XChartDocument.class, xifc);
+
+ XMultiServiceFactory xDocMSF = (XMultiServiceFactory)
+ UnoRuntime.queryInterface(XMultiServiceFactory.class, xChart);
+
+ Object diagObject =
+ xDocMSF.createInstance("com.sun.star.chart.PieDiagram");
+
+ XDiagram xDiagram = (XDiagram)
+ UnoRuntime.queryInterface(XDiagram.class, diagObject);
+
+ xChart.setDiagram(xDiagram);
+
+ XPropertySet propset = (XPropertySet)
+ UnoRuntime.queryInterface( XPropertySet.class, xChart.getTitle() );
+ propset.setPropertyValue("String", "JVM Memory Usage");
+ }
+}
diff --git a/scripting/examples/java/MemoryUsage/parcel-descriptor.xml b/scripting/examples/java/MemoryUsage/parcel-descriptor.xml
new file mode 100644
index 000000000000..e09bf4a81517
--- /dev/null
+++ b/scripting/examples/java/MemoryUsage/parcel-descriptor.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<parcel language="Java" xmlns:parcel="scripting.dtd">
+ <script language="Java">
+ <locale lang="en">
+ <displayname value="MemoryUtils.MemUsage"/>
+ <description>
+ Text highlighting
+ </description>
+ </locale>
+ <functionname value="MemoryUsage.updateMemoryUsage"/>
+ <logicalname value="MemoryUtils.MemUsage"/>
+ <languagedepprops>
+ <prop name="classpath" value="MemoryUsage.jar"/>
+ </languagedepprops>
+ </script>
+</parcel>
diff --git a/scripting/examples/java/Newsgroup/MimeConfiguration.java b/scripting/examples/java/Newsgroup/MimeConfiguration.java
new file mode 100644
index 000000000000..8604c0afbd1b
--- /dev/null
+++ b/scripting/examples/java/Newsgroup/MimeConfiguration.java
@@ -0,0 +1,219 @@
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.script.framework.runtime.XScriptContext;
+import com.sun.star.util.XStringSubstitution;
+
+import javax.mail.*;
+import javax.activation.*;
+
+import java.io.*;
+
+
+public class MimeConfiguration
+{
+
+ // Office Installation path
+ private static String instPath = "";
+
+
+ public static boolean createFiles( XScriptContext xsc )
+ {
+ try
+ {
+ XComponentContext xcc = xsc.getComponentContext();
+ XMultiComponentFactory xmf = xcc.getServiceManager();
+
+ Object pathSub = xmf.createInstanceWithContext( "com.sun.star.comp.framework.PathSubstitution", xcc );
+ XStringSubstitution stringSub = ( XStringSubstitution ) UnoRuntime.queryInterface( XStringSubstitution.class, pathSub );
+ instPath = stringSub.getSubstituteVariableValue( "$(inst)" );
+
+ }
+ catch( com.sun.star.beans.UnknownPropertyException upe )
+ {
+ System.out.println( "com.sun.star.beans.UnknownPropertyException" );
+ upe.printStackTrace();
+ }
+ catch( com.sun.star.uno.Exception e )
+ {
+ System.out.println( "com.sun.star.uno.Exception" );
+ e.printStackTrace();
+ }
+
+ writeMailCap();
+ writeMimeTypes();
+
+ // ToDo: include status feedback to StatusWindow
+ return true;
+ }
+
+
+
+
+ private static void writeMailCap()
+ {
+ String mailcapPath = getConfigDir() + System.getProperty( "file.separator" ) + "mailcap";
+
+ try
+ {
+ if( ! new File( java.net.URLDecoder.decode( mailcapPath ) ).exists() )
+ {
+ //System.out.println( "URLDecoder: " + java.net.URLDecoder.decode( mailcapPath ) );
+ File mailcapFile = new File( mailcapPath );
+ FileWriter out = new FileWriter( mailcapFile );
+ String[] lines = getMailcapText();
+ for( int i=0; i<lines.length; i++ )
+ {
+ out.write( lines[i], 0, lines[i].length() );
+ }
+ out.close();
+ }
+ else
+ {
+ //System.out.println( "URLDecoder: " + java.net.URLDecoder.decode( mailcapPath ) );
+ }
+
+
+
+ // use prog dir, if not there then java.io to create/write new file
+ MailcapCommandMap map = new MailcapCommandMap( mailcapPath );
+ CommandMap.setDefaultCommandMap ( map );
+ }
+ catch( IOException ioe )
+ {
+ ioe.printStackTrace();
+ }
+ catch( Exception e )
+ {
+ e.printStackTrace();
+ }
+ }
+
+
+ private static String[] getMailcapText()
+ {
+ String[] mailcapText = {
+ "#\n",
+ "# Default mailcap file for the JavaMail System.\n",
+ "#\n",
+ "# JavaMail content-handlers:\n",
+ "#\n",
+ "text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain\n",
+ "text/html;; x-java-content-handler=com.sun.mail.handlers.text_html\n",
+ "text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml\n",
+ "image/gif;; x-java-content-handler=com.sun.mail.handlers.image_gif\n",
+ "image/jpeg;; x-java-content-handler=com.sun.mail.handlers.image_jpeg\n",
+ "multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed\n",
+ "message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822\n"
+ };
+
+ return mailcapText;
+ }
+
+
+
+ private static void writeMimeTypes()
+ {
+ String mimetypesPath = getConfigDir() + System.getProperty( "file.separator" ) + "mimetypes.default";
+
+ try
+ {
+ if( ! new File( java.net.URLDecoder.decode( mimetypesPath ) ).exists() )
+ {
+ //System.out.println( "URLDecoder: " + java.net.URLDecoder.decode( mimetypesPath ) );
+ File mimetypesFile = new File( mimetypesPath );
+ FileWriter out = new FileWriter( mimetypesFile );
+ String[] lines = getMimeTypesText();
+ for( int i=0; i<lines.length; i++ )
+ {
+ out.write( lines[i], 0, lines[i].length() );
+ }
+ out.close();
+ }
+ else
+ {
+ //System.out.println( "URLDecoder: " + java.net.URLDecoder.decode( mimetypesPath ) );
+ }
+
+ MimetypesFileTypeMap mimeTypes = new MimetypesFileTypeMap( mimetypesPath );
+ FileTypeMap.setDefaultFileTypeMap( mimeTypes );
+ }
+ catch( IOException ioe )
+ {
+ ioe.printStackTrace();
+ }
+ catch( Exception e )
+ {
+ e.printStackTrace();
+ }
+ }
+
+
+ private static String[] getMimeTypesText()
+ {
+ String[] mimesText = {
+ "#\n",
+ "# A simple, old format, mime.types file\n",
+ "#\n",
+ "text/html html htm HTML HTM\n",
+ "text/plain txt text TXT TEXT\n",
+ "image/gif gif GIF\n",
+ "image/ief ief\n",
+ "image/jpeg jpeg jpg jpe JPG\n",
+ "image/tiff tiff tif\n",
+ "image/x-xwindowdump xwd\n",
+ "application/postscript ai eps ps\n",
+ "application/rtf rtf\n",
+ "application/x-tex tex\n",
+ "application/x-texinfo texinfo texi\n",
+ "application/x-troff t tr roff\n",
+ "audio/basic au\n",
+ "audio/midi midi mid\n",
+ "audio/x-aifc aifc\n",
+ "audio/x-aiff aif aiff\n",
+ "audio/x-mpeg mpeg mpg\n",
+ "audio/x-wav wav\n",
+ "video/mpeg mpeg mpg mpe\n",
+ "video/quicktime qt mov\n",
+ "video/x-msvideo avi\n"
+ };
+
+ return mimesText;
+ }
+
+
+ private static String getConfigDir()
+ {
+ // mailcap file must be written to the Office user/config directory
+
+ // instPath is a URL, needs to be converted to a system pathname
+ String config = instPath + "/user/config";
+ String configNonURL = "";
+
+ if( System.getProperty( "os.name" ).indexOf( "Windows" ) != -1 )
+ {
+ // Windows
+ // removes "file:///"
+ int start = 8;
+ configNonURL = config.substring( start, config.length() );
+ // Convert forward to back-slashes
+ while( configNonURL.indexOf( "/" ) != -1 )
+ {
+ int fSlash = configNonURL.indexOf( "/" );
+ String firstPart = configNonURL.substring( 0, fSlash );
+ String secondPart = configNonURL.substring( fSlash + 1, configNonURL.length() );
+ configNonURL = firstPart + "\\" + secondPart;
+ }
+ }
+ else
+ {
+ // Unix/Linux
+ // removes "file://"
+ int start = 7;
+ configNonURL = config.substring( start, config.length() );
+ }
+
+ return configNonURL;
+ }
+
+}
diff --git a/scripting/examples/java/Newsgroup/NewsGroup.java b/scripting/examples/java/Newsgroup/NewsGroup.java
new file mode 100644
index 000000000000..714b81ec86ce
--- /dev/null
+++ b/scripting/examples/java/Newsgroup/NewsGroup.java
@@ -0,0 +1,23 @@
+public class NewsGroup
+{
+
+ private String hostname = "";
+ private String newsgroupName = "";
+
+ public NewsGroup( String host, String group )
+ {
+ hostname = host;
+ newsgroupName = group;
+ }
+
+ public String getHostName()
+ {
+ return hostname;
+ }
+
+ public String getNewsgroupName()
+ {
+ return newsgroupName;
+ }
+
+}
diff --git a/scripting/examples/java/Newsgroup/OfficeAttachment.java b/scripting/examples/java/Newsgroup/OfficeAttachment.java
new file mode 100644
index 000000000000..c2816e0e133b
--- /dev/null
+++ b/scripting/examples/java/Newsgroup/OfficeAttachment.java
@@ -0,0 +1,307 @@
+//import com.sun.star.frame.XComponentLoader;
+import java.io.*;
+import com.sun.star.lang.XComponent;
+import com.sun.star.beans.PropertyValue;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.frame.XStorable;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.frame.XModel;
+import com.sun.star.script.framework.runtime.XScriptContext;
+
+// for debug only
+import javax.swing.JOptionPane;
+
+public class OfficeAttachment
+{
+
+ private StatusWindow status = null;
+ private XStorable storedDoc = null;
+ private File htmlFile = null;
+ private File officeFile = null;
+ private boolean isHtmlDoc = false;
+ private boolean isOfficeDoc = false;
+ private String templocationURL = "";
+ private String templocationSystem = "";
+ private String attachmentName = "";
+ private String statusLine = "";
+
+ public OfficeAttachment( XScriptContext xsc, StatusWindow sw, boolean html, boolean office )
+ {
+ status = sw;
+ isHtmlDoc = html;
+ isOfficeDoc = office;
+
+ templocationSystem = templocationURL = System.getProperty( "user.home" );
+ if( System.getProperty( "os.name" ).indexOf( "Windows" ) != -1 )
+ {
+ while( templocationURL.indexOf( "\\" ) != -1 )
+ {
+ int sepPos = templocationURL.indexOf( "\\" );
+ String firstPart = templocationURL.substring( 0, sepPos );
+ String lastPart = templocationURL.substring( sepPos + 1, templocationURL.length() );
+ templocationURL = firstPart + "/" + lastPart;
+ //JOptionPane.showMessageDialog( null, "Temp Location URL is: " + templocationURL + "\nfirstPart is: " + firstPart + "\nlastPart is: " + lastPart );
+ }
+ }
+
+ try
+ {
+ statusLine = "Querying Office for current document";
+ status.setStatus( 1, statusLine );
+ XScriptContext scriptcontext = xsc;
+ XModel xmodel = scriptcontext.getDocument();
+ storedDoc = (XStorable) UnoRuntime.queryInterface(XStorable.class, xmodel);
+ // find document name from storedDoc
+ attachmentName = storedDoc.getLocation();
+ }
+ catch( Exception e )
+ {
+ //UNO error
+ status.setStatus( 1, "Error: " + statusLine );
+ }
+
+ if( attachmentName.equalsIgnoreCase( "" ) )
+ {
+ attachmentName = "Attachment";
+ }
+ else
+ {
+ //int lastSep = attachmentName.lastIndexOf( System.getProperty( "file.separator" ) );
+ int lastSep = attachmentName.lastIndexOf( "/" );
+ attachmentName = attachmentName.substring( lastSep + 1, attachmentName.length() );
+ int dot = attachmentName.indexOf( "." );
+ attachmentName = attachmentName.substring( 0, dot );
+ }
+ }
+
+
+ public boolean createTempDocs()
+ {
+ String filenameURL = "file:///" + templocationURL + "/" + attachmentName;
+ //String filenameSystem = templocationSystem + System.getProperty( "file.separator" ) + attachmentName;
+ //JOptionPane.showMessageDialog( null, "Filename URL " + filenameURL );
+ try
+ {
+ if( isHtmlDoc )
+ {
+ //JOptionPane.showMessageDialog( null, "Saving doc in HTML format" );
+ statusLine = "Saving doc in HTML format";
+ status.setStatus( 4, statusLine );
+ //System.out.print( "Saving attachment as " + filename + ".html..." );
+ PropertyValue[] propertyvalue_html = new PropertyValue[2];
+ propertyvalue_html[0] = new PropertyValue();
+ propertyvalue_html[0].Name = new String("Overwrite");
+ propertyvalue_html[0].Value = new Boolean(true);
+ propertyvalue_html[1] = new PropertyValue();
+ propertyvalue_html[1].Name = ("FilterName");
+// propertyvalue_html[1].Value = new String("scalc: HTML (StarCalc)");
+ propertyvalue_html[1].Value = new String("swriter: HTML (StarWriter)");
+ storedDoc.storeAsURL( filenameURL + ".html", propertyvalue_html);
+
+ File homedir = new File( templocationSystem );
+ //JOptionPane.showMessageDialog( null, "homedir (Java File): " + homedir.getPath() );
+ File homefiles[] = homedir.listFiles();
+ String file = "";
+ for(int i=0; i < homefiles.length; i++ )
+ {
+ if( homefiles[i].getName().equals( attachmentName + ".html" ) )
+ {
+ //htmlFile = new File( homefiles[i].getAbsolutePath() );
+ //JOptionPane.showMessageDialog( null, "Found HTML" );
+ file = homefiles[i].getAbsolutePath();
+ }
+ }
+ htmlFile = new File( file );
+ //htmlFile = new File( filename + ".html" );
+ //htmlFile = new File( storedDoc.getLocation() );
+ }
+
+ if( isOfficeDoc )
+ {
+ //JOptionPane.showMessageDialog( null, "Saving doc in .sxw format" );
+ statusLine = "Saving doc in .sxw format";
+ status.setStatus( 4, statusLine );
+ //System.out.print( "Saving attachment as " + filename + ".sxw..." );
+ PropertyValue[] propertyvalue_sxw = new PropertyValue[2];
+ propertyvalue_sxw[0] = new PropertyValue();
+ propertyvalue_sxw[0].Name = new String("Overwrite");
+ propertyvalue_sxw[0].Value = new Boolean(true);
+ propertyvalue_sxw[1] = new PropertyValue();
+ propertyvalue_sxw[1].Name = new String("Overwrite");
+ propertyvalue_sxw[1].Value = new Boolean(true);
+ storedDoc.storeAsURL( filenameURL + ".sxw", propertyvalue_sxw);
+
+ File homedir = new File( templocationSystem );
+
+ //JOptionPane.showMessageDialog( null, "homedir (Java File): " + homedir.getPath() );
+
+ File homefiles[] = homedir.listFiles();
+ String file = "";
+ for(int i=0; i < homefiles.length; i++ )
+ {
+ if( homefiles[i].getName().equals( attachmentName + ".sxw" ) )
+ {
+ //officeFile = new File( homefiles[i].getAbsolutePath() );
+ //JOptionPane.showMessageDialog( null, "Found .sxw" );
+ file = homefiles[i].getAbsolutePath();
+ }
+ }
+ officeFile = new File( file );
+ //officeFile = new File( filename + ".sxw" );
+ //officeFile = new File (storedDoc.getLocation() );
+ }
+
+ //status.setStatus( 10, "Attachments successfully created" );
+
+ }
+ catch( SecurityException se )
+ {
+ status.setStatus( 4, "Error: " + statusLine );
+ System.out.println( "Security error while saving temporary Document(s). Check file permissions in home directory." );
+ se.printStackTrace();
+ htmlFile = null;
+ officeFile = null;
+ return false;
+ }
+ catch( Exception e )
+ {
+ status.setStatus( 4, "Error: " + statusLine );
+ System.out.println( "Error saving temporary Document(s)" );
+ e.printStackTrace();
+ htmlFile = null;
+ officeFile = null;
+ return false;
+ }
+ return true;
+ }
+
+
+ public boolean removeTempDocs()
+ {
+ /*
+ if( !htmlFile.exists() && !officeFile.exists() )
+ {
+ System.out.println("Error: Document(s) have not been saved." );
+ }
+ */
+
+ statusLine = "Removing temp docs";
+ status.setStatus( 13, statusLine );
+
+ try
+ {
+ if( isOfficeDoc && isHtmlDoc )
+ {
+ //System.out.println( "Removing: " + htmlFile.getPath() + " " + officeFile.getPath() );
+ //System.out.println( "htmlfile " + htmlFile.exists() + " officeFile " + officeFile.exists() );
+ //JOptionPane.showMessageDialog( null, "Removing: " + htmlFile.getPath() + " " + officeFile.getPath() );
+ //JOptionPane.showMessageDialog( null, "htmlfile " + htmlFile.exists() + " officeFile " + officeFile.exists() );
+ htmlFile.delete();
+ officeFile.delete();
+ //JOptionPane.showMessageDialog( null, "htmlfile " + htmlFile.exists() + " officeFile " + officeFile.exists() );
+ }
+ else
+ {
+ if( isOfficeDoc )
+ {
+ //System.out.println( "Removing: " + officeFile.getPath() );
+ officeFile.delete();
+ }
+ else
+ {
+ //System.out.println( "Removing: " + htmlFile.getPath() );
+ htmlFile.delete();
+ }
+ }
+ }
+ catch( SecurityException se )
+ {
+ status.setStatus( 13, "Error: " + statusLine );
+ System.out.println( "Security Error while deleting temporary Document(s). Check file permissions in home directory." );
+ se.printStackTrace();
+ return false;
+ }
+ return true;
+ }
+
+
+ public void cleanUpOnError()
+ {
+ try
+ {
+ if( isOfficeDoc && isHtmlDoc )
+ {
+ htmlFile.delete();
+ officeFile.delete();
+ }
+ else
+ {
+ if( isOfficeDoc )
+ {
+ officeFile.delete();
+ }
+ else
+ {
+ htmlFile.delete();
+ }
+ }
+ }
+ catch( SecurityException se )
+ {
+ System.out.println( "Security Error while deleting temporary Document(s). Check file permissions in home directory." );
+ se.printStackTrace();
+ }
+ }
+
+
+ public File[] getAttachments()
+ {
+ /*
+ if( htmlFile == null && officeFile == null )
+ {
+ System.out.println( "Error: Document(s) have not been saved." );
+ return null;
+ }
+ */
+ //(officeDoc) ? (number = 2) : (number = 1);
+
+ statusLine = "Retrieving temp docs";
+ status.setStatus( 8, statusLine );
+
+ File attachments[] = null;
+ if( isOfficeDoc && isHtmlDoc )
+ {
+ attachments = new File[2];
+ attachments[0] = htmlFile;
+ attachments[1] = officeFile;
+ }
+ else
+ {
+ if( isOfficeDoc )
+ {
+ attachments = new File[1];
+ attachments[0] = officeFile;
+ }
+ else
+ {
+ attachments = new File[1];
+ attachments[0] = htmlFile;
+ }
+ }
+
+ return attachments;
+ }
+
+
+ public boolean isHtmlAttachment()
+ {
+ return isHtmlDoc;
+ }
+
+
+ public boolean isOfficeAttachment()
+ {
+ return isOfficeDoc;
+ }
+
+}
diff --git a/scripting/examples/java/Newsgroup/PostNewsgroup.java b/scripting/examples/java/Newsgroup/PostNewsgroup.java
new file mode 100644
index 000000000000..a88b1d3e8844
--- /dev/null
+++ b/scripting/examples/java/Newsgroup/PostNewsgroup.java
@@ -0,0 +1,625 @@
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+import javax.swing.border.*;
+import java.util.Vector;
+import com.sun.star.script.framework.runtime.XScriptContext;
+
+
+public class PostNewsgroup extends JFrame
+{
+
+ // Post to newsgroup objects
+ private NewsGroup[] subscribedNewsgroups = null;
+ private XScriptContext xscriptcontext = null;
+
+ private final int FRAMEX = 300;
+ private final int FRAMEY = 300;
+ private final int TEXTBOXWIDTH = 300;
+ private final int TEXTBOXHEIGHT = 24;
+ private final int TEXTAREAHEIGHT = 70;
+ private final int BUTTONWIDTH = 80;
+ private final int BUTTONHEIGHT = 30;
+
+ private PostNewsgroup window = null;
+ private JComboBox newsgroupComboBox = null;
+ private JTextField hostTextField = null;
+ private JTextField replyTextField = null;
+ private JTextField subjectTextField = null;
+ private JTextArea commentTextArea = null;
+ private JRadioButton officeHtmlButton = null;
+ private JRadioButton officeButton = null;
+ private JRadioButton htmlButton = null;
+ private JButton postButton = null;
+ private JButton cancelButton = null;
+
+ // JFrame for launch progress dialog
+ private StatusWindow statusWindow = null;
+ private String statusLine = "";
+
+ // Tool tip text
+ private final String newsgroupText = "Newsgroup name";
+ private final String hostText = "Newsgroup host/server name";
+ private final String replyText = "Email address to reply to";
+ private final String subjectText = "Subject title for the mail";
+ private final String commentText = "Additional comment on mail";
+ private final String officeHtmlText = "Post as both Office and HTML attachments";
+ private final String officeText = "Post as Office attachment only";
+ private final String htmlText = "Post as HTML attachment only";
+ private final String postText = "Post to newsgroup";
+ private final String cancelText = "Cancel post to newsgroup";
+
+
+ public void post( XScriptContext xsc )
+ {
+ xscriptcontext = xsc;
+ window = this;
+
+ // create mailcap and mimetypes files (fix for classloader problem)
+ MimeConfiguration.createFiles( xscriptcontext );
+
+ this.setTitle( "Post Document To Newsgroup" );
+ this.setLocation( FRAMEX, FRAMEY );
+
+ this.addFocusListener( new FocusAdapter()
+ {
+ public void focusGained( FocusEvent event )
+ {
+ System.out.println( "Focus gained" );
+ window.update( window.getGraphics() );
+ }
+
+ public void focusLost( FocusEvent event )
+ {
+ System.out.println( "Focus lost" );
+ }
+ });
+
+ Container container = getContentPane();
+ container.setLayout( new GridBagLayout() );;
+ GridBagConstraints constraints = new GridBagConstraints();
+ constraints.fill = GridBagConstraints.BOTH;
+
+ JPanel labelPanel = constructLabelPanel();
+ JPanel textPanel = constructTextPanel();
+ JPanel optionPanel = constructOptionPanel();
+ JPanel buttonPanel = constructButtonPanel();
+
+ constraints.gridx = 0;
+ constraints.gridy = 0;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 3;
+ constraints.insets = new Insets( 15, 15, 5, 5 );
+ container.add( labelPanel, constraints );
+
+ constraints.gridx = 1;
+ constraints.gridy = 0;
+ constraints.gridwidth = 4;
+ constraints.gridheight = 3;
+ constraints.insets = new Insets( 15, 5, 5, 15 );
+ container.add( textPanel, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 3;
+ constraints.gridwidth = 5;
+ constraints.gridheight = 1;
+ constraints.insets = new Insets( 5, 15, 5, 15 );
+ container.add( optionPanel, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 4;
+ constraints.gridwidth = 5;
+ constraints.gridheight = 1;
+ constraints.insets = new Insets( 5, 5, 5, 5 );
+ container.add( buttonPanel, constraints );
+
+ this.pack();
+ this.setResizable( false );
+ this.setVisible( true );
+ }
+
+
+ private JPanel constructLabelPanel()
+ {
+ JLabel newsgroupLabel = new JLabel( "Newsgroup:" );
+ JLabel hostLabel = new JLabel( "Host:" );
+ JLabel replyLabel = new JLabel( "Reply:" );
+ JLabel subjectLabel = new JLabel( "Subject:" );
+ JLabel commentLabel = new JLabel( "Comment:" );
+
+ newsgroupLabel.setToolTipText( newsgroupText );
+ hostLabel.setToolTipText( hostText );
+ replyLabel.setToolTipText( replyText );
+ subjectLabel.setToolTipText( subjectText );
+ commentLabel.setToolTipText( commentText );
+
+ JPanel newsgroupPanel = new JPanel();
+ newsgroupPanel.setLayout( new BorderLayout() );
+ newsgroupPanel.add( newsgroupLabel, "West" );
+ JPanel hostPanel = new JPanel();
+ hostPanel.setLayout( new BorderLayout() );
+ hostPanel.add( hostLabel, "West" );
+ JPanel replyPanel = new JPanel();
+ replyPanel.setLayout( new BorderLayout() );
+ replyPanel.add( replyLabel, "West" );
+ JPanel subjectPanel = new JPanel();
+ subjectPanel.setLayout( new BorderLayout() );
+ subjectPanel.add( subjectLabel, "West" );
+ JPanel commentPanel = new JPanel();
+ commentPanel.setLayout( new BorderLayout() );
+ commentPanel.add( commentLabel, "West" );
+ JPanel emptyPanel = new JPanel();
+
+ final int labelWidth = 80;
+ newsgroupPanel.setPreferredSize( new Dimension( labelWidth, TEXTBOXHEIGHT ) );
+ hostPanel.setPreferredSize( new Dimension( labelWidth, TEXTBOXHEIGHT ) );
+ replyPanel.setPreferredSize( new Dimension( labelWidth, TEXTBOXHEIGHT ) );
+ subjectPanel.setPreferredSize( new Dimension( labelWidth, TEXTBOXHEIGHT ) );
+ commentPanel.setPreferredSize( new Dimension( labelWidth, TEXTBOXHEIGHT ) );
+
+ JPanel panel = new JPanel();
+ panel.setLayout( new GridBagLayout() );
+ GridBagConstraints constraints = new GridBagConstraints();
+ constraints.fill = GridBagConstraints.BOTH;
+ constraints.insets = new Insets( 5, 5, 5, 5 );
+
+ constraints.gridx = 0;
+ constraints.gridy = 0;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ constraints.weightx = constraints.weighty = 0.0;
+ panel.add( newsgroupPanel, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 1;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ panel.add( hostPanel, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 2;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ panel.add( replyPanel, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 3;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ panel.add( subjectPanel, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 4;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ panel.add( commentPanel, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 5;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ constraints.weightx = constraints.weighty = 1.0;
+ panel.add( emptyPanel, constraints );
+
+ return panel;
+ }
+
+
+ private JPanel constructTextPanel()
+ {
+ hostTextField = new JTextField();
+ hostTextField.setPreferredSize( new Dimension( TEXTBOXWIDTH, TEXTBOXHEIGHT ) );
+ hostTextField.setToolTipText( hostText );
+ hostTextField.setBorder( new EtchedBorder() );
+
+ //optionPanel.setBorder( new TitledBorder( new EtchedBorder(), "Document Format" ) );
+ newsgroupComboBox = getNewsgroupCombo();
+
+ replyTextField = new JTextField();
+ replyTextField.setPreferredSize( new Dimension( TEXTBOXWIDTH, TEXTBOXHEIGHT ) );
+ replyTextField.setToolTipText( replyText );
+ replyTextField.setBorder( new EtchedBorder() );
+
+ subjectTextField = new JTextField();
+ subjectTextField.setPreferredSize( new Dimension( TEXTBOXWIDTH, TEXTBOXHEIGHT ) );
+ subjectTextField.setToolTipText( subjectText );
+ subjectTextField.setBorder( new EtchedBorder() );
+
+ commentTextArea = new JTextArea();
+ commentTextArea.setPreferredSize( new Dimension( TEXTBOXWIDTH, TEXTAREAHEIGHT ) );
+ commentTextArea.setToolTipText( commentText );
+ commentTextArea.setBorder( new EtchedBorder() );
+
+ JPanel panel = new JPanel();
+ panel.setLayout( new GridBagLayout() );
+ GridBagConstraints constraints = new GridBagConstraints();
+ constraints.fill = GridBagConstraints.BOTH;
+ constraints.insets = new Insets( 5, 5, 5, 5 );
+
+ constraints.gridx = 0;
+ constraints.gridy = 0;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ panel.add( newsgroupComboBox, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 1;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ panel.add( hostTextField, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 2;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ panel.add( replyTextField, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 3;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ panel.add( subjectTextField, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 4;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 2;
+ panel.add( commentTextArea, constraints );
+
+ return panel;
+ }
+
+
+ private JComboBox getNewsgroupCombo()
+ {
+ newsgroupComboBox = new JComboBox();
+ //newsgroupComboBox.setBorder( new EtchedBorder() );
+
+ newsgroupComboBox.addActionListener(new ActionListener()
+ {
+ public void actionPerformed(ActionEvent e)
+ {
+ // when newsgroup is selected
+ if( subscribedNewsgroups != null )
+ {
+ int position = newsgroupComboBox.getSelectedIndex();
+ if( position != -1 )
+ {
+ hostTextField.setText( subscribedNewsgroups[ position ].getHostName() );
+ newsgroupComboBox.setToolTipText( "Newsgroup name: " + subscribedNewsgroups[ position ].getNewsgroupName() + " (Host name: " + subscribedNewsgroups[ position ].getHostName() + ")" );
+ }
+ }
+ }
+ });
+
+ NewsGroup groupToSend = null;
+ SubscribedNewsgroups newsgroups = new SubscribedNewsgroups();
+ subscribedNewsgroups = newsgroups.getNewsGroups();
+
+ // Test for no .mozilla or no subscribed newsgroups
+ // subscribedNewsgroups = null;
+
+ if( subscribedNewsgroups == null )
+ {
+ //System.out.println( "Couldn't find any subscibed newsgroups in .mozilla" );
+ JOptionPane.showMessageDialog( window, "No subscribed newsgroups found in mozilla/netscape profile \nPlease enter newsgroup and host name",
+ "Newsgroups Information", JOptionPane.INFORMATION_MESSAGE );
+ }
+ else
+ {
+ // Copy all newsgroups into a vector for comparison
+ // Alter entries (to include host name) if duplication is found
+ Vector vector = new Vector( subscribedNewsgroups.length );
+ for(int i=0; i < subscribedNewsgroups.length; i++ )
+ {
+ vector.add( subscribedNewsgroups[i].getNewsgroupName() );
+ }
+ // Compare and alter
+ for(int i=0; i < subscribedNewsgroups.length; i++ )
+ {
+ // check if combo box already has a newsgroup with same name
+ // then add host name to differentiate
+ for(int j=0; j < subscribedNewsgroups.length; j++ )
+ {
+ if( j != i && subscribedNewsgroups[j].getNewsgroupName().equalsIgnoreCase( subscribedNewsgroups[i].getNewsgroupName() ) )
+ {
+ vector.set( j, subscribedNewsgroups[j].getNewsgroupName() + " (" + subscribedNewsgroups[j].getHostName() + ")" );
+ vector.set( i, subscribedNewsgroups[i].getNewsgroupName() + " (" + subscribedNewsgroups[i].getHostName() + ")" );
+ }
+ }
+ }
+ // Copy converted newsgroups from vector to combo box
+ for(int i=0; i < subscribedNewsgroups.length; i++ )
+ {
+ newsgroupComboBox.addItem( vector.elementAt(i) );
+ }
+ }// else
+
+ newsgroupComboBox.setPreferredSize( new Dimension( TEXTBOXWIDTH, TEXTBOXHEIGHT ) );
+ newsgroupComboBox.setEditable( true );
+
+ return newsgroupComboBox;
+ }
+
+
+
+ private JPanel constructOptionPanel()
+ {
+ officeHtmlButton = new JRadioButton( "Office and HTML", true );
+ officeHtmlButton.setToolTipText( officeHtmlText );
+
+ officeButton = new JRadioButton( "Office" );
+ officeButton.setToolTipText( officeText );
+
+ htmlButton = new JRadioButton( "HTML" );
+ htmlButton.setToolTipText( htmlText );
+
+ JRadioButton[] rbuttons = { officeHtmlButton, officeButton, htmlButton };
+ ButtonGroup radioButtonGroup = new ButtonGroup();
+ for( int i=0; i < rbuttons.length; i++ )
+ {
+ radioButtonGroup.add( rbuttons[i] );
+ }
+
+ JPanel optionPanel = new JPanel();
+ //optionPanel.setLayout( new GridLayout( 1, 3, 20, 0 ) );
+ optionPanel.setBorder( new TitledBorder( new EtchedBorder(), "Document Format" ) );
+ optionPanel.setLayout( new GridBagLayout() );
+ GridBagConstraints constraints = new GridBagConstraints();
+ constraints.fill = GridBagConstraints.BOTH;
+
+ constraints.gridx = 0;
+ constraints.gridy = 0;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ constraints.insets = new Insets( 5, 5, 5, 30 );
+ optionPanel.add( officeHtmlButton, constraints );
+
+ constraints.gridx = 1;
+ constraints.gridy = 0;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ constraints.insets = new Insets( 5, 20, 5, 30 );
+ optionPanel.add( officeButton, constraints );
+
+ constraints.gridx = 2;
+ constraints.gridy = 0;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ constraints.insets = new Insets( 5, 20, 5, 5 );
+ optionPanel.add( htmlButton, constraints );
+
+ return optionPanel;
+ }
+
+
+
+ public boolean sendingActions()
+ {
+ // posting actions
+ // Validate the data
+ if( isValidData() )
+ {
+ // Create status window
+ StatusWindow statusWindow = new StatusWindow( window, "Posting to Newsgroup", FRAMEX, FRAMEY );
+
+ statusWindow.setVisible( true );
+ //statusWindow.requestFocusInWindow();
+ statusLine = "Ready to send...";
+ statusWindow.setStatus( 0, statusLine );
+
+ // Get the boolean values for HTML/Office document
+ // params: ( XScriptContext, StatusWindow, html document, office document )
+
+ boolean html = false;
+ boolean office = false;
+ if( officeHtmlButton.isSelected() ) { html = true; office = true; }
+ if( officeButton.isSelected() ) { office = true; html = false; }
+ if( htmlButton.isSelected() ) { html = true; office = false; }
+
+ OfficeAttachment officeAttach = new OfficeAttachment( xscriptcontext, statusWindow, html, office );
+
+ statusLine = "Getting user input";
+ statusWindow.setStatus( 2, statusLine );
+ // Get replyto, subject, comment from textboxes
+ String replyto = replyTextField.getText();
+ String subject = subjectTextField.getText();
+ String comment = commentTextArea.getText();
+
+ // Get newsgroup from combo box (corresponding position)
+ String host = "";
+ String group = "";
+ int position = newsgroupComboBox.getSelectedIndex();
+ if( subscribedNewsgroups == null || position == -1 )
+ {
+ host = hostTextField.getText();
+ group = newsgroupComboBox.getSelectedItem().toString();
+ }
+ else
+ {
+ //int position = newsgroupComboBox.getSelectedIndex();
+ host = subscribedNewsgroups[ position ].getHostName();
+ group = subscribedNewsgroups[ position ].getNewsgroupName();
+ }
+
+ statusLine = "Creating sender object";
+ statusWindow.setStatus( 3, statusLine );
+ Sender sender = new Sender( statusWindow, officeAttach, replyto, subject, comment, host, group );
+ if( !sender.sendMail() )
+ {
+ //System.out.println( "Should end here (?)" );
+ statusWindow.enableCancelButton( true );
+ officeAttach.cleanUpOnError();
+ return false;
+ }
+
+ statusLine = "Send is complete";
+ statusWindow.setStatus( 14, statusLine );
+ }
+ else
+ {
+ //System.out.println( "Non valid data" );
+ return false;
+ }
+ return true;
+ }
+
+
+ private JPanel constructButtonPanel()
+ {
+ Action postAction = new AbstractAction() {
+ public void actionPerformed( ActionEvent event ) {
+ // posting actions
+ sendingActions();
+ }// actionPerformed
+ };
+
+ Action cancelAction = new AbstractAction() {
+ public void actionPerformed( ActionEvent event ) {
+ // cancelling actions
+ window.dispose();
+ }
+ };
+
+ postButton = new JButton();
+ postButton.setAction( postAction );
+ postButton.setToolTipText( postText );
+ postButton.setText( "Post" );
+ postButton.setPreferredSize( new Dimension( BUTTONWIDTH + 20, BUTTONHEIGHT ) );
+
+ cancelButton = new JButton();
+ cancelButton.setAction( cancelAction );
+ cancelButton.setToolTipText( cancelText );
+ cancelButton.setText( "Cancel" );
+ cancelButton.setPreferredSize( new Dimension( BUTTONWIDTH + 20, BUTTONHEIGHT ) );
+
+ JSeparator sep = new JSeparator( SwingConstants.HORIZONTAL );
+
+ JPanel buttonPanel = new JPanel();
+ buttonPanel.setLayout( new GridBagLayout() );
+ GridBagConstraints constraints = new GridBagConstraints();
+ constraints.fill = GridBagConstraints.BOTH;
+ constraints.insets = new Insets( 5, 5, 5, 5 );
+
+ JPanel emptyPanel1 = new JPanel();
+ emptyPanel1.setPreferredSize( new Dimension( BUTTONWIDTH, BUTTONHEIGHT ) );
+
+ JPanel emptyPanel2 = new JPanel();
+ emptyPanel2.setPreferredSize( new Dimension( BUTTONWIDTH, BUTTONHEIGHT ) );
+
+ constraints.gridx = 0;
+ constraints.gridy = 0;
+ constraints.gridwidth = 4;
+ constraints.gridheight = 1;
+ buttonPanel.add( sep, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 1;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ buttonPanel.add( emptyPanel1, constraints );
+
+ constraints.gridx = 1;
+ constraints.gridy = 1;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ buttonPanel.add( emptyPanel2, constraints );
+
+ constraints.gridx = 2;
+ constraints.gridy = 1;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ buttonPanel.add( postButton, constraints );
+
+ constraints.gridx = 3;
+ constraints.gridy = 1;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ constraints.insets = new Insets( 5, 5, 5, 0 );
+ buttonPanel.add( cancelButton, constraints );
+
+ return buttonPanel;
+ }
+
+
+ public void enableButtons( boolean enable )
+ {
+ if( enable )
+ {
+ postButton.setEnabled( true );
+ cancelButton.setEnabled( true );
+ }
+ else
+ {
+ postButton.setEnabled( false );
+ cancelButton.setEnabled( false );
+ }
+ }
+
+
+ private boolean isValidData()
+ {
+ // newsgroupComboBox must not be blank (format? dots and whitespace)
+ String newsgroupString = "";
+ int position = newsgroupComboBox.getSelectedIndex();
+ if( subscribedNewsgroups == null || position == -1 )
+ {
+ newsgroupString = newsgroupComboBox.getSelectedItem().toString();
+ }
+ else
+ {
+ //int position = newsgroupComboBox.getSelectedIndex();
+ newsgroupString = subscribedNewsgroups[ position ].getNewsgroupName();
+ }
+ if( newsgroupString.length() == 0 )
+ {
+ //System.out.println( "Please enter a newsgroup name" );
+ newsgroupComboBox.requestFocus();
+ JOptionPane.showMessageDialog( window, "Please enter a newsgroup name", "Input Error", JOptionPane.ERROR_MESSAGE );
+ return false;
+ }
+
+
+ // hostTextField must not be blank (format?)
+ String hostString = hostTextField.getText();
+ if( hostString.length() == 0 )
+ {
+ //System.out.println( "Please enter a hostname" );
+ hostTextField.requestFocus();
+ JOptionPane.showMessageDialog( window, "Please enter a hostname", "Input Error", JOptionPane.ERROR_MESSAGE );
+ return false;
+ }
+
+
+ // replyTextField must have <string>@<string>.<string>
+ // (string at least 2 chars long)
+ // consider <s>.<s>@<s>.<s>.<s> format? (array of dot positons?)
+ String replyString = replyTextField.getText();
+ int atPos = replyString.indexOf( "@" );
+ int dotPos = replyString.lastIndexOf( "." );
+ int length = replyString.length();
+ //System.out.println( "length: " + length + "\n atPos: " + atPos + "\n dotPos: " + dotPos );
+ if( length == 0 || atPos == -1 || dotPos == -1 || atPos < 2 || dotPos < atPos || dotPos + 2 == length || atPos + 2 == dotPos || atPos != replyString.lastIndexOf( "@" ) || replyString.indexOf(" ") != -1 )
+ {
+ //System.out.println( "Please enter a valid reply to email address" );
+ replyTextField.requestFocus();
+ JOptionPane.showMessageDialog( window, "Please enter a valid reply to email address", "Input Error", JOptionPane.ERROR_MESSAGE );
+ return false;
+ }
+
+
+ // subjectTextField must not be blank?
+ String subjectString = subjectTextField.getText();
+ if( subjectString.length() == 0 )
+ {
+ //System.out.println( "Please enter subject title" );
+ subjectTextField.requestFocus();
+ JOptionPane.showMessageDialog( window, "Please enter subject title", "Input Error", JOptionPane.ERROR_MESSAGE );
+ return false;
+ }
+
+ // details are valid
+ return true;
+ }
+
+}
diff --git a/scripting/examples/java/Newsgroup/Sender.java b/scripting/examples/java/Newsgroup/Sender.java
new file mode 100644
index 000000000000..eb1da2868f0d
--- /dev/null
+++ b/scripting/examples/java/Newsgroup/Sender.java
@@ -0,0 +1,126 @@
+import javax.mail.*;
+import javax.mail.internet.*;
+import com.msoft.mail.provider.nntp.NNTPTransport;
+import java.util.Properties;
+import java.io.*;
+import javax.activation.*;
+
+
+public class Sender
+{
+ // Constructor params:
+ private StatusWindow status = null;
+ private OfficeAttachment attachments = null;
+ private String replyto = "";
+ private String subject = "";
+ private String comment = "";
+ private String hostname = "";
+ private String newsgroup = "";
+ private String statusLine = "";
+
+
+
+ public Sender( StatusWindow sw, OfficeAttachment attach, String reply,
+ String sub, String com, String host, String group )
+ {
+ status = sw;
+ attachments = attach;
+ replyto = reply;
+ subject = sub;
+ comment = com;
+ hostname = host;
+ newsgroup = group;
+ }
+
+
+
+ public boolean sendMail()
+ {
+ int statusPos = 5;
+ try
+ {
+ attachments.createTempDocs();
+ // Property for any information
+ Properties props = new Properties();
+
+ // Create unique session (null is unused authenticator info)
+ statusLine = "Creating unique session";
+ status.setStatus( statusPos, statusLine ); // 5
+ Session session = Session.getInstance( props, null );
+
+ // Create message
+ statusPos++; // 6
+ statusLine = "Creating message";
+ status.setStatus( statusPos, statusLine );
+ MimeMessage message = new MimeMessage( session );
+ message.setFrom( new InternetAddress( replyto ) );
+ message.setSubject( subject );
+ message.setText( comment );
+ message.addHeader( "Newsgroups", newsgroup );
+
+ // Buildup bodypart with text and attachments
+ Multipart multipart = new MimeMultipart();
+
+ BodyPart messageBodyPart = new MimeBodyPart();
+ messageBodyPart.setText( comment );
+ multipart.addBodyPart( messageBodyPart );
+
+ statusPos++; // 7
+ statusLine = "Adding attachment(s)";
+ status.setStatus( statusPos, statusLine );
+ File attachs[] = attachments.getAttachments();
+ for(int i=0; i < attachs.length; i++ )
+ {
+ //System.out.println( "Adding file: " + attachs[i].getName() );
+ messageBodyPart = new MimeBodyPart();
+ DataSource filesource = new FileDataSource( attachs[i] );
+ messageBodyPart.setDataHandler( new DataHandler( filesource ));
+ messageBodyPart.setFileName( attachs[i].getName() );
+ multipart.addBodyPart( messageBodyPart );
+ }
+
+ // Add multipart to mail
+ message.setContent( multipart );
+
+ // Create and send NNTP transport
+ statusPos += 2; // 9
+ statusLine = "Creating NNTP transport";
+ status.setStatus( statusPos, statusLine );
+ Transport transport = new NNTPTransport( session, new URLName( "news:" + newsgroup ));
+
+ // Null parameters are for user name and password
+ statusPos++; // 10
+ statusLine = "Connecting to mail server";
+ status.setStatus( statusPos, statusLine );
+ transport.connect( hostname, null, null );
+
+ statusPos++; // 11
+ statusLine = "Sending message";
+ status.setStatus( statusPos, statusLine );
+ transport.sendMessage( message, message.getAllRecipients() );
+
+ statusPos++; // 12
+ statusLine = "Closing transport";
+ status.setStatus( statusPos, statusLine );
+ transport.close();
+
+ // Clean up when finished
+ attachments.removeTempDocs();
+
+ return true;
+ }
+ catch( MessagingException me )
+ {
+ if( statusPos == 10 )
+ {
+ statusLine = "Error connecting (User authentication?)";
+ }
+ status.setStatus( statusPos, statusLine );
+ System.out.println( "Error sending message: ");
+ me.printStackTrace();
+ return false;
+ }
+
+ }
+
+}
diff --git a/scripting/examples/java/Newsgroup/StatusWindow.java b/scripting/examples/java/Newsgroup/StatusWindow.java
new file mode 100644
index 000000000000..2fcffaeb6ca6
--- /dev/null
+++ b/scripting/examples/java/Newsgroup/StatusWindow.java
@@ -0,0 +1,138 @@
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+import javax.swing.border.*;
+
+public class StatusWindow extends JFrame
+{
+
+ private JProgressBar progressBar = null;
+ private JTextField statusLabel = null;
+ private JButton cancelButton = null;
+ private JFrame statusWindow = null;
+ private PostNewsgroup mainWindow = null;
+
+ private final int MAXPROGRESS = 13;
+ private final int MINPROGRESS = 0;
+
+
+ public StatusWindow( PostNewsgroup mw, String title, int parentX, int parentY )
+ {
+ this.setTitle( title );
+ this.setLocation( parentX + 100, parentY + 100 );
+ statusWindow = this;
+ mainWindow = mw;
+
+ mainWindow.enableButtons( false );
+
+ statusWindow.addWindowListener( new WindowAdapter()
+ {
+ public void windowClosing( WindowEvent event ) {
+ mainWindow.enableButtons( true );
+ }
+ });
+
+ progressBar = new JProgressBar();
+ progressBar.setStringPainted( true );
+ progressBar.setMaximum( MAXPROGRESS );
+ progressBar.setMinimum( MINPROGRESS );
+ progressBar.setSize( 30, 400 );
+
+ JLabel progLabel = new JLabel( "Progress:" );
+
+ JPanel progressPanel = new JPanel();
+ progressPanel.setLayout( new BorderLayout( 10, 0 ) );
+ progressPanel.add( progLabel, "West" );
+ progressPanel.add( progressBar, "East" );
+
+ statusLabel = new JTextField();
+ statusLabel.setColumns( 25 );
+ statusLabel.setEditable( false );
+ statusLabel.setBorder( null );
+ //statusLabel.setBorder( LineBorder.createGrayLineBorder() );
+ JPanel statusPanel = new JPanel();
+ //statusPanel.setBorder( LineBorder.createBlackLineBorder() );
+ statusPanel.setLayout( new BorderLayout() );
+ statusPanel.add( statusLabel, "West" );
+
+ cancelButton = new JButton( "Cancel" );
+ cancelButton.setSize( 30, 100 );
+ cancelButton.setEnabled( false );
+ cancelButton.addActionListener( new ActionListener()
+ {
+ public void actionPerformed( ActionEvent event ) {
+ // cancelling actions
+ mainWindow.enableButtons( true );
+ statusWindow.dispose();
+ }
+ });
+
+ JPanel buttonPanel = new JPanel();
+ buttonPanel.setLayout( new BorderLayout( 0, 5 ) );
+ buttonPanel.add( cancelButton, "East" );
+ buttonPanel.add( new JSeparator( SwingConstants.HORIZONTAL ), "North" );
+
+ Container container = getContentPane();
+ container.setLayout( new GridBagLayout() );
+ GridBagConstraints constraints = new GridBagConstraints();
+ constraints.fill = GridBagConstraints.BOTH;
+
+ constraints.gridx = 0;
+ constraints.gridy = 0;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ constraints.insets = new Insets( 15, 15, 10, 15 );
+ container.add( progressPanel, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 1;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ constraints.insets = new Insets( 10, 15, 10, 15 );
+ container.add( statusPanel, constraints );
+
+ constraints.gridx = 0;
+ constraints.gridy = 2;
+ constraints.gridwidth = 1;
+ constraints.gridheight = 1;
+ constraints.insets = new Insets( 10, 15, 5, 15 );
+ container.add( buttonPanel, constraints );
+
+ this.pack();
+ this.setResizable( false );
+ //this.setVisible( true );
+
+ }
+
+
+ public void setStatus( int progress, String status )
+ {
+ progressBar.setValue( progress );
+ statusLabel.setText( status );
+ statusLabel.setToolTipText( status );
+ if( progress == MAXPROGRESS )
+ {
+ cancelButton.setEnabled( true );
+ cancelButton.setText( "Close" );
+ }
+ update( getGraphics() );
+ mainWindow.update( mainWindow.getGraphics() );
+ }
+
+
+ public void enableCancelButton( boolean enable )
+ {
+ if( enable )
+ {
+ cancelButton.setEnabled( true );
+ cancelButton.setText( "Finish" );
+ }
+ else
+ {
+ cancelButton.setEnabled( false );
+ cancelButton.setText( "Cancel" );
+ }
+
+ }
+
+}
diff --git a/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java b/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java
new file mode 100644
index 000000000000..b227791c0299
--- /dev/null
+++ b/scripting/examples/java/Newsgroup/SubscribedNewsgroups.java
@@ -0,0 +1,373 @@
+import java.io.*;
+import java.util.Vector;
+
+
+public class SubscribedNewsgroups {
+
+
+ private static NewsGroup[] allSubscribed = null;
+ private static boolean windows = false;
+
+ public static void main( String[] args ) {
+ // Test the class
+ SubscribedNewsgroups subscribed = new SubscribedNewsgroups();
+
+ NewsGroup allGroups[] = subscribed.getNewsGroups();
+
+ if( allGroups == null )
+ {
+ System.out.println("Could not find subscribed newsgroups from mozilla/netscape mailrc files");
+ }
+ else
+ {
+ for( int i=0; i < allGroups.length; i++ )
+ {
+ System.out.println( "Hostname is: " + allGroups[i].getHostName() + " Newsgroup is: " + allGroups[i].getNewsgroupName() );
+ }
+ }
+ }
+
+
+
+ // Only public method of the class
+ // Returns and array of unique NewsGroup objects
+ public NewsGroup[] getNewsGroups()
+ {
+ windows = false;
+ if( System.getProperty( "os.name" ).indexOf( "Windows" ) != -1 )
+ {
+ windows = true;
+ }
+
+ String mozillaHome = "";
+ if( windows )
+ {
+ mozillaHome = System.getProperty( "user.home" ) + System.getProperty( "file.separator" ) + "Application Data" + System.getProperty( "file.separator" ) + "Mozilla" + System.getProperty( "file.separator" ) + "Profiles";
+ //System.out.println( "Windows mozilla path: " + mozillaHome );
+ }
+ else
+ {
+ mozillaHome = System.getProperty( "user.home" ) + System.getProperty( "file.separator" ) + ".mozilla";
+ //System.out.println( "Unix/Linux mozilla path: " + mozillaHome );
+ }
+ if( !new File( mozillaHome ).isDirectory() )
+ {
+ //System.out.println("Could not find .mozilla directory");
+ return null;
+ }
+ //System.out.println(".mozilla directory found");
+
+ // Get all the profiles belonging to the user
+ File profiles[] = findProfiles( new File ( mozillaHome ) );
+ if( profiles.length < 1 )
+ {
+ //System.out.println("Could not find Profiles");
+ return null;
+ }
+ //System.out.println("Profiles found");
+
+ // Get the News directory for each profile
+ File allNewsDirs[] = new File[ profiles.length ];
+ for( int i=0; i < profiles.length; i++ ) {
+ File newsDir = findNewsDir( profiles[i] );
+ allNewsDirs[i] = newsDir;
+ //System.out.println( "News is at: " + newsDir.getPath() );
+ }
+ // Check that at least one News directory exists and remove nulls
+ boolean newsFound = false;
+ //Vector nonNullNews = new Vector();
+ for( int i=0; i < allNewsDirs.length; i++ ) {
+ if( allNewsDirs[i] != null ) {
+ newsFound = true;
+ break;
+ }
+ }
+ if( !newsFound )
+ {
+ //System.out.println("Could not find News directory");
+ return null;
+ }
+ //System.out.println("News directory found");
+
+ // Get all the mailrc files for each News directory
+ File allMailrcs[] = findMailrcFiles( allNewsDirs );
+ if( allMailrcs == null )
+ {
+ //System.out.println("Could not find mailrc files");
+ return null;
+ }
+ //System.out.println("mailrc files found");
+
+ Vector subscribed = new Vector();
+ // Get the newsgroups in each mailrc file
+ for( int i=0; i < allMailrcs.length; i++ )
+ {
+ File mailrc = (File) allMailrcs[i];
+ NewsGroup newsgroup[] = findNewsgroups( mailrc );
+ //if the Newsgroup has not already been added to the list
+ for( int j=0; j < newsgroup.length; j++ )
+ {
+ // if newsgroup is unique then add to the list
+ if( !listed( newsgroup[j], subscribed ) )
+ {
+ subscribed.addElement( newsgroup[j] );
+ }
+ }
+ }
+
+ // Copy all unique Newsgroups into the global array
+ allSubscribed = new NewsGroup[ subscribed.size() ];
+ subscribed.copyInto( allSubscribed );
+ // Test that at least one subscribed newsgroup has been found
+ if( allSubscribed.length < 1 )
+ {
+ //System.out.println("Could not find Subscribed newsgroups ");
+ return null;
+ }
+ //System.out.println("Subscribed newsgroups found");
+
+ return allSubscribed;
+ }
+
+
+
+
+ // Tests if the NewsGroup object has already been listed by another mailrc file
+ private static boolean listed( NewsGroup newsgroup, Vector uniqueSubscription )
+ {
+ for(int i=0; i < uniqueSubscription.size(); i++)
+ {
+ NewsGroup tempGroup = (NewsGroup) uniqueSubscription.elementAt(i);
+ // Test for duplication
+ if(newsgroup.getHostName().equalsIgnoreCase( tempGroup.getHostName()) &&
+ newsgroup.getNewsgroupName().equalsIgnoreCase( tempGroup.getNewsgroupName() ) )
+ return true;
+ }
+ return false;
+ }
+
+
+
+
+ // Finds all the NewsGroups in an individual mailrc file
+ private static NewsGroup[] findNewsgroups(File mailrcfile )
+ {
+
+ String hostname = "";
+ String newsgroup = "";
+ NewsGroup mailrcNewsGroups[] = null;
+
+ //Retrieve name of news host/server from file name
+ //Sequentially access each of the newsgroups
+ //If the newsgroup is not already contained in the global NewsGroup[] array then add it
+
+ String filename = mailrcfile.getPath();
+ if( windows )
+ {
+ // Windows format "staroffice-news.germany.sun.com.rc"
+ int hostNameStart = filename.lastIndexOf("\\") + 1;
+ int hostNameEnd = filename.indexOf(".rc");
+ hostname = filename.substring( hostNameStart, hostNameEnd );
+ }
+ else
+ {
+ // Unix/Linux format "newsrc-staroffice-news.germany.sun.com"
+ int hostNameStart = filename.lastIndexOf("newsrc-") + 7;
+ hostname = filename.substring( hostNameStart, filename.length() );
+ }
+
+ // Assumes the content format in Window is the same as Unix/Linux (unknown at the moment)
+ // i.e. a list of newsgroups each ending with a ":"
+ LineNumberReader in = null;
+ try {
+ in = new LineNumberReader( new FileReader( mailrcfile ) );
+ Vector groups = new Vector();
+ String inString = "";
+ int line = 0;
+ while( inString != null )
+ {
+ in.setLineNumber( line );
+ inString = in.readLine();
+ line++;
+ if( inString != null )
+ {
+ int newsgroupEnd = inString.indexOf(":");
+ newsgroup = inString.substring( 0, newsgroupEnd );
+ NewsGroup group = new NewsGroup( hostname, newsgroup );
+ groups.addElement( group );
+ }
+ }
+ mailrcNewsGroups = new NewsGroup[ groups.size() ];
+ groups.copyInto(mailrcNewsGroups);
+ in.close();
+ }
+ catch( IOException ioe ) {
+ ioe.printStackTrace();
+ }
+
+ return mailrcNewsGroups;
+ }
+
+
+ // Finds all the mailrc files for all the given News directories
+ private static File[] findMailrcFiles(File[] newsDirs)
+ {
+ Vector allFiles = new Vector();
+
+ for( int i=0; i < newsDirs.length; i++ )
+ {
+ //System.out.println( "Finding mailrc for: " + newsDirs[i] );
+ if( newsDirs[i] != null )
+ {
+ File mailrcFiles[] = newsDirs[i].listFiles( new VersionFilter() );
+ if( mailrcFiles != null )
+ {
+ //System.out.println( "Number found: " + mailrcFiles.length );
+ for( int j=0; j < mailrcFiles.length; j++ )
+ {
+ //System.out.println( "This mailrc was found: " + mailrcFiles[j] );
+ allFiles.addElement( mailrcFiles[j] );
+ }
+ }
+ }
+ }
+ File allMailrcFiles[] = new File[ allFiles.size() ];
+ allFiles.copyInto(allMailrcFiles);
+
+ //System.out.println( "number of mailrcs in total: " + allMailrcFiles.length );
+
+ if( allMailrcFiles.length == 0 ) {
+ //System.out.println( "Returning null");
+ return null;
+ }
+
+ //System.out.println( "Returning an File array containing mailrcs");
+ return allMailrcFiles;
+ }
+
+
+ // Finds all profiles belonging to one user (can be more than one)
+ private static File[] findProfiles(File start)
+ {
+ // Get all files and directories in .mozilla
+ File allFiles[] = start.listFiles();
+ File[] dirs = new File[allFiles.length];
+ int dirCounter = 0;
+
+ // Remove files leaving directories only
+ for(int i=0; i < allFiles.length; i++ )
+ {
+ if(allFiles[i].isDirectory())
+ {
+ dirs[dirCounter] = allFiles[i];
+ dirCounter++;
+ }
+ }
+
+ // Add each directory to a user profile array
+ File[] profileDirs = new File[dirCounter];
+ for( int i=0; i < dirCounter; i++ )
+ {
+ profileDirs[i] = dirs[i];
+ }
+
+ // return a File array containing the profile dirs
+ return profileDirs;
+ }
+
+
+ // Recursively searches for the News directory for a given profile directory
+ private static File findNewsDir(File start)
+ {
+ File mailrcFile = null;
+
+ // File array containing all matches for the version filter ("News")
+ File files[] = start.listFiles(new VersionFilter());
+ // If the array is empty then no matches were found
+ if (files.length == 0)
+ {
+ // File array of all the directories in File start
+ File dirs[] = start.listFiles(new DirFilter());
+ // for each of the directories check for a match
+ for (int i=0; i< dirs.length; i++)
+ {
+ mailrcFile = findNewsDir(dirs[i]);
+ if (mailrcFile != null)
+ {
+ // break the for loop
+ break;
+ }
+ }
+ }
+ else
+ {
+ // end recursion
+ // Check for a News directory inside the News directory (fix for bug)
+ // Original solution had only "mailrcFile = files[0];"
+
+ boolean noChildNews = true;
+ File checkChildNewsDirs[] = files[0].listFiles(new VersionFilter());
+ if( checkChildNewsDirs != null )
+ {
+ for( int i=0; i < checkChildNewsDirs.length; i++ )
+ {
+ if( checkChildNewsDirs[i].getName().equals( "News" ) )
+ {
+ noChildNews = false;
+ break;
+ }
+ }
+ }
+
+ if( noChildNews )
+ {
+ mailrcFile = files[0];
+ }
+ else
+ {
+ String childNewsPathName = files[0].getAbsolutePath() + System.getProperty( "file.separator" ) + "News";
+ mailrcFile = new File( childNewsPathName );
+ }
+
+ }
+
+ // return a File representing the News dir in a profile
+ return mailrcFile;
+ }
+}
+
+
+
+class DirFilter implements FileFilter
+{
+ public boolean accept(File aFile)
+ {
+ return aFile.isDirectory();
+ }
+}
+
+
+class VersionFilter implements FileFilter
+{
+ public boolean accept(File aFile)
+ {
+ if( System.getProperty( "os.name" ).indexOf( "Windows" ) != -1 )
+ {
+ if (aFile.getName().compareToIgnoreCase("News") == 0 ||
+ aFile.getName().indexOf(".rc") != -1 )
+ {
+ return true;
+ }
+ }
+ else
+ {
+ if (aFile.getName().compareToIgnoreCase("News") == 0 ||
+ aFile.getName().indexOf("newsrc") != -1 )
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+}
diff --git a/scripting/examples/java/build.xml b/scripting/examples/java/build.xml
new file mode 100755
index 000000000000..f5d70223f270
--- /dev/null
+++ b/scripting/examples/java/build.xml
@@ -0,0 +1,143 @@
+<!--
+
+ DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+
+ Copyright 2008 by Sun Microsystems, Inc.
+
+ OpenOffice.org - a multi-platform office productivity suite
+
+ $RCSfile: build.xml,v $
+
+ $Revision: 1.14 $
+
+ This file is part of OpenOffice.org.
+
+ OpenOffice.org is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License version 3
+ only, as published by the Free Software Foundation.
+
+ OpenOffice.org is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License version 3 for more details
+ (a copy is included in the LICENSE file that accompanied this code).
+
+ You should have received a copy of the GNU Lesser General Public License
+ version 3 along with OpenOffice.org. If not, see
+ <http://www.openoffice.org/license.html>
+ for a copy of the LGPLv3 License.
+
+-->
+<project name="Scripting Framework Java Examples" default="all" basedir=".">
+ <!-- =================== Environmental Properties ======================= -->
+
+ <property name="prj" value="../.."/>
+ <property environment="env"/>
+ <property name="outdir" value="${out}/class/examples/java"/>
+
+ <!-- ==================== classpath setting ============================ -->
+ <path id="idlclasspath">
+ <pathelement location="${solar.jar}/unoil.jar"/>
+ <pathelement location="${solar.jar}/jurt.jar"/>
+ <pathelement location="${solar.jar}/juh.jar"/>
+ <pathelement location="${solar.jar}/ridl.jar"/>
+ <pathelement location="${out}/class/ScriptFramework.jar"/>
+ </path>
+
+ <!-- ===================== HelloWorld example =========================== -->
+ <target name="HelloWorld">
+
+ <mkdir dir="${outdir}/HelloWorld"/>
+
+ <javac srcdir="HelloWorld" destdir="${outdir}/HelloWorld"
+ includes="**/*.java" classpathref="idlclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="on"/>
+
+ <copy file="HelloWorld/HelloWorld.java" todir="${outdir}/HelloWorld"/>
+ <copy file="HelloWorld/parcel-descriptor.xml" todir="${outdir}/HelloWorld"/>
+
+ <jar jarfile="${outdir}/HelloWorld/HelloWorld.jar"
+ basedir="${outdir}/HelloWorld"
+ includes="**/*.class"
+ excludes="${outdir}/HelloWorld/HelloWorld.jar">
+ </jar>
+
+ <delete file="${outdir}/HelloWorld/HelloWorld.class"/>
+
+ </target>
+
+ <!-- ===================== Highlight example ========================== -->
+ <target name="Highlight">
+
+ <mkdir dir="${outdir}/Highlight"/>
+
+ <javac srcdir="Highlight" destdir="${outdir}/Highlight"
+ includes="**/*.java" classpathref="idlclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="on"/>
+
+ <copy file="Highlight/HighlightText.java" todir="${outdir}/Highlight"/>
+ <copy file="Highlight/parcel-descriptor.xml" todir="${outdir}/Highlight"/>
+
+ <jar jarfile="${outdir}/Highlight/Highlight.jar"
+ basedir="${outdir}/Highlight"
+ includes="**/*.class"
+ excludes="${outdir}/Highlight/Highlight.jar">
+ </jar>
+
+ <delete file="${outdir}/Highlight/HighlightText.class"/>
+
+ </target>
+
+ <!-- ===================== MemoryUsage example ========================== -->
+ <target name="MemoryUsage">
+
+ <mkdir dir="${outdir}/MemoryUsage"/>
+
+ <javac srcdir="MemoryUsage" destdir="${outdir}/MemoryUsage"
+ includes="**/*.java" classpathref="idlclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="on"/>
+
+ <copy file="MemoryUsage/MemoryUsage.java" todir="${outdir}/MemoryUsage"/>
+ <copy file="MemoryUsage/parcel-descriptor.xml" todir="${outdir}/MemoryUsage"/>
+
+ <jar jarfile="${outdir}/MemoryUsage/MemoryUsage.jar"
+ basedir="${outdir}/MemoryUsage"
+ includes="**/*.class"
+ excludes="${outdir}/MemoryUsage/MemoryUsage.jar">
+ </jar>
+
+ <delete file="${outdir}/MemoryUsage/MemoryUsage.class"/>
+
+ </target>
+
+ <!-- ===================== selector example ========================== -->
+ <target name="selector">
+
+ <mkdir dir="${outdir}/selector"/>
+
+ <javac srcdir="selector" destdir="${outdir}/selector"
+ includes="**/*.java" classpathref="idlclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="on"/>
+
+ <copy todir="${outdir}/selector">
+ <fileset dir="selector">
+ <include name="**/*.java"/>
+ <include name="*.xml"/>
+ <include name="*.gif"/>
+ </fileset>
+ </copy>
+
+ <jar jarfile="${outdir}/selector/selector.jar"
+ basedir="${outdir}/selector" includes="*.class,*.gif">
+ </jar>
+
+ <delete>
+ <fileset dir="${outdir}/selector" includes="*.class,*.gif"/>
+ </delete>
+
+ </target>
+
+ <!-- ========================= All In One Build ======================= -->
+ <target name="all" depends="HelloWorld,Highlight,MemoryUsage"/>
+
+</project>
diff --git a/scripting/examples/java/debugger/DebugRunner.java b/scripting/examples/java/debugger/DebugRunner.java
new file mode 100644
index 000000000000..4430b970b6bf
--- /dev/null
+++ b/scripting/examples/java/debugger/DebugRunner.java
@@ -0,0 +1,71 @@
+import java.io.File;
+import java.io.InputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLDecoder;
+
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.script.framework.provider.PathUtils;
+import com.sun.star.script.framework.runtime.XScriptContext;
+
+public class DebugRunner {
+
+ private static final String FILE_URL_PREFIX =
+ System.getProperty("os.name").startsWith("Windows") == true ?
+ "file:///" : "file://";
+
+ public void go(final XScriptContext xsctxt, String language, String uri,
+ String filename) {
+
+ OOScriptDebugger debugger;
+ String path = "";
+
+ if (language.equals("JavaScript")) {
+ debugger = new OORhinoDebugger();
+ }
+ else if (language.equals("BeanShell")) {
+ debugger = new OOBeanShellDebugger();
+ }
+ else {
+ return;
+ }
+
+ if (uri.startsWith(FILE_URL_PREFIX)) {
+ uri = URLDecoder.decode(uri);
+ String s = uri.substring(FILE_URL_PREFIX.length());
+ File f = new File(s);
+
+ if (f.exists()) {
+ if (f.isDirectory()) {
+ if (!filename.equals("")) {
+ path = new File(f, filename).getAbsolutePath();
+ }
+ }
+ else {
+ path = f.getAbsolutePath();
+ }
+ }
+ debugger.go(xsctxt, path);
+ }
+ else {
+ if (!uri.endsWith("/")) {
+ uri += "/";
+ }
+
+ String script = uri + filename;
+ InputStream is;
+
+ try {
+ is = PathUtils.getScriptFileStream(
+ script, xsctxt.getComponentContext());
+
+ if (is != null) {
+ debugger.go(xsctxt, is);
+ }
+ }
+ catch (IOException ioe) {
+ System.out.println("Error loading script: " + script);
+ }
+ }
+ }
+}
diff --git a/scripting/examples/java/debugger/OOBeanShellDebugger.java b/scripting/examples/java/debugger/OOBeanShellDebugger.java
new file mode 100644
index 000000000000..be91aa458163
--- /dev/null
+++ b/scripting/examples/java/debugger/OOBeanShellDebugger.java
@@ -0,0 +1,374 @@
+import javax.swing.JFrame;
+import javax.swing.JTextArea;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JButton;
+import javax.swing.JComponent;
+import javax.swing.JFileChooser;
+import javax.swing.JOptionPane;
+import javax.swing.text.Document;
+import javax.swing.event.DocumentListener;
+import javax.swing.event.DocumentEvent;
+
+import java.awt.FlowLayout;
+import java.awt.Graphics;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Polygon;
+import java.awt.Rectangle;
+import java.awt.Dimension;
+import java.awt.event.ActionListener;
+import java.awt.event.ActionEvent;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import drafts.com.sun.star.script.framework.runtime.XScriptContext;
+import bsh.Interpreter;
+
+public class OOBeanShellDebugger implements OOScriptDebugger, ActionListener, DocumentListener {
+
+ private JFrame frame;
+ private JTextArea ta;
+ private GlyphGutter gg;
+ private XScriptContext context;
+ private int currentPosition = -1;
+ private int linecount;
+ private Interpreter sessionInterpreter;
+ private Thread execThread = null;
+ private String filename = null;
+
+ /* Entry point for script execution */
+ public void go(XScriptContext context, String filename) {
+ if (filename != null && filename != "") {
+ try {
+ FileInputStream fis = new FileInputStream(filename);
+ this.filename = filename;
+ go(context, fis);
+ }
+ catch (IOException ioe) {
+ JOptionPane.showMessageDialog(frame,
+ "Error loading file: " + ioe.getMessage(),
+ "Error", JOptionPane.ERROR_MESSAGE);
+ }
+ }
+ }
+
+ /* Entry point for script execution */
+ public void go(XScriptContext context, InputStream in) {
+ this.context = context;
+ initUI();
+
+ if (in != null) {
+ try {
+ loadFile(in);
+ }
+ catch (IOException ioe) {
+ JOptionPane.showMessageDialog(frame,
+ "Error loading stream: " + ioe.getMessage(),
+ "Error", JOptionPane.ERROR_MESSAGE);
+ }
+ }
+ }
+
+ public void loadFile(InputStream in) throws IOException {
+
+ /* Remove ourselves as a DocumentListener while loading the file
+ so we don't get a storm of DocumentEvents during loading */
+ ta.getDocument().removeDocumentListener(this);
+
+ byte[] contents = new byte[1024];
+ int len = 0, pos = 0;
+
+ while ((len = in.read(contents, 0, 1024)) != -1) {
+ ta.insert(new String(contents, 0, len), pos);
+ pos += len;
+ }
+
+ try {
+ in.close();
+ }
+ catch (IOException ignore) {
+ }
+
+ /* Update the GlyphGutter and add back the DocumentListener */
+ gg.update();
+ ta.getDocument().addDocumentListener(this);
+ }
+
+ private void initUI() {
+ frame = new JFrame("BeanShell Debug Window");
+ ta = new JTextArea();
+ ta.setRows(15);
+ ta.setColumns(40);
+ ta.setLineWrap(false);
+ linecount = ta.getLineCount();
+
+ gg = new GlyphGutter(this);
+
+ final JScrollPane sp = new JScrollPane();
+ sp.setViewportView(ta);
+ sp.setRowHeaderView(gg);
+
+ ta.getDocument().addDocumentListener(this);
+ String[] labels = {"Run", "Clear", "Save", "Close"};
+ JPanel p = new JPanel();
+ p.setLayout(new FlowLayout());
+
+ for (int i = 0; i < labels.length; i++) {
+ JButton b = new JButton(labels[i]);
+ b.addActionListener(this);
+ p.add(b);
+
+ if (labels[i].equals("Save") && filename == null) {
+ b.setEnabled(false);
+ }
+ }
+
+ frame.getContentPane().add(sp, "Center");
+ frame.getContentPane().add(p, "South");
+ frame.pack();
+ frame.show();
+ }
+
+ /* Implementation of DocumentListener interface */
+ public void insertUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ public void removeUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ public void changedUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ /* If the number of lines in the JTextArea has changed then update the
+ GlyphGutter */
+ public void doChanged(DocumentEvent e) {
+ if (linecount != ta.getLineCount()) {
+ gg.update();
+ linecount = ta.getLineCount();
+ }
+ }
+
+ private void startExecution() {
+ execThread = new Thread() {
+ public void run() {
+ Interpreter interpreter = new Interpreter();
+ interpreter.getNameSpace().clear();
+
+ // reset position and repaint gutter so no red arrow appears
+ currentPosition = -1;
+ gg.repaint();
+
+ try {
+ interpreter.set("context", context);
+ interpreter.eval(ta.getText());
+ }
+ catch (bsh.EvalError err) {
+ currentPosition = err.getErrorLineNumber() - 1;
+ try {
+ // scroll to line of the error
+ int line = ta.getLineStartOffset(currentPosition);
+ Rectangle rect = ta.modelToView(line);
+ ta.scrollRectToVisible(rect);
+ }
+ catch (Exception e) {
+ // couldn't scroll to line, do nothing
+ }
+ gg.repaint();
+
+ JOptionPane.showMessageDialog(frame, "Error at line " +
+ String.valueOf(err.getErrorLineNumber()) +
+ "\n\n: " + err.getErrorText(),
+ "Error", JOptionPane.ERROR_MESSAGE);
+ }
+ catch (Exception e) {
+ JOptionPane.showMessageDialog(frame,
+ "Error: " + e.getMessage(),
+ "Error", JOptionPane.ERROR_MESSAGE);
+ }
+ }
+ };
+ execThread.start();
+ }
+
+ private void promptForSaveName() {
+ JFileChooser chooser = new JFileChooser();
+ chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
+ public boolean accept(File f) {
+ if (f.isDirectory() || f.getName().endsWith(".bsh")) {
+ return true;
+ }
+ return false;
+ }
+
+ public String getDescription() {
+ return ("BeanShell files: *.bsh");
+ }
+ });
+
+ int ret = chooser.showSaveDialog(frame);
+
+ if (ret == JFileChooser.APPROVE_OPTION) {
+ filename = chooser.getSelectedFile().getAbsolutePath();
+ if (!filename.endsWith(".bsh")) {
+ filename += ".bsh";
+ }
+ }
+
+ }
+
+ private void saveTextArea() {
+ if (filename == null) {
+ promptForSaveName();
+ }
+
+ FileOutputStream fos = null;
+ if (filename != null) {
+ try {
+ File f = new File(filename);
+ fos = new FileOutputStream(f);
+ String s = ta.getText();
+ fos.write(s.getBytes(), 0, s.length());
+ }
+ catch (IOException ioe) {
+ JOptionPane.showMessageDialog(frame,
+ "Error saving file: " + ioe.getMessage(),
+ "Error", JOptionPane.ERROR_MESSAGE);
+ }
+ finally {
+ if (fos != null) {
+ try {
+ fos.close();
+ }
+ catch (IOException ignore) {
+ }
+ }
+ }
+ }
+ }
+
+ public void actionPerformed(ActionEvent e) {
+ if (e.getActionCommand().equals("Run")) {
+ startExecution();
+ }
+ else if (e.getActionCommand().equals("Close")) {
+ frame.dispose();
+ }
+ else if (e.getActionCommand().equals("Save")) {
+ saveTextArea();
+ }
+ else if (e.getActionCommand().equals("Clear")) {
+ ta.setText("");
+ }
+ }
+
+ public JTextArea getTextArea() {
+ return ta;
+ }
+
+ public int getCurrentPosition() {
+ return currentPosition;
+ }
+}
+
+class GlyphGutter extends JComponent {
+
+ private OOBeanShellDebugger debugger;
+ private final String DUMMY_STRING = "99";
+
+ GlyphGutter(OOBeanShellDebugger debugger) {
+ this.debugger = debugger;
+ update();
+ }
+
+ public void update() {
+ JTextArea textArea = debugger.getTextArea();
+ Font font = textArea.getFont();
+ setFont(font);
+
+ FontMetrics metrics = getFontMetrics(font);
+ int h = metrics.getHeight();
+ int lineCount = textArea.getLineCount() + 1;
+
+ String dummy = Integer.toString(lineCount);
+ if (dummy.length() < 2) {
+ dummy = DUMMY_STRING;
+ }
+
+ Dimension d = new Dimension();
+ d.width = metrics.stringWidth(dummy) + 16;
+ d.height = lineCount * h + 100;
+ setPreferredSize(d);
+ setSize(d);
+ }
+
+ public void paintComponent(Graphics g) {
+ JTextArea textArea = debugger.getTextArea();
+
+ Font font = textArea.getFont();
+ g.setFont(font);
+
+ FontMetrics metrics = getFontMetrics(font);
+ Rectangle clip = g.getClipBounds();
+
+ g.setColor(getBackground());
+ g.fillRect(clip.x, clip.y, clip.width, clip.height);
+
+ int ascent = metrics.getMaxAscent();
+ int h = metrics.getHeight();
+ int lineCount = textArea.getLineCount() + 1;
+
+ int startLine = clip.y / h;
+ int endLine = (clip.y + clip.height) / h + 1;
+ int width = getWidth();
+ if (endLine > lineCount) {
+ endLine = lineCount;
+ }
+
+ for (int i = startLine; i < endLine; i++) {
+ String text;
+ text = Integer.toString(i + 1) + " ";
+ int w = metrics.stringWidth(text);
+ int y = i * h;
+ g.setColor(Color.blue);
+ g.drawString(text, 0, y + ascent);
+ int x = width - ascent;
+
+ // if currentPosition is not -1 then a red arrow will be drawn
+ if (i == debugger.getCurrentPosition()) {
+ drawArrow(g, ascent, x, y);
+ }
+ }
+ }
+
+ private void drawArrow(Graphics g, int ascent, int x, int y) {
+ Polygon arrow = new Polygon();
+ int dx = x;
+ y += ascent - 10;
+ int dy = y;
+ arrow.addPoint(dx, dy + 3);
+ arrow.addPoint(dx + 5, dy + 3);
+ for (x = dx + 5; x <= dx + 10; x++, y++) {
+ arrow.addPoint(x, y);
+ }
+ for (x = dx + 9; x >= dx + 5; x--, y++) {
+ arrow.addPoint(x, y);
+ }
+ arrow.addPoint(dx + 5, dy + 7);
+ arrow.addPoint(dx, dy + 7);
+
+ g.setColor(Color.red);
+ g.fillPolygon(arrow);
+ g.setColor(Color.black);
+ g.drawPolygon(arrow);
+ }
+};
+
diff --git a/scripting/examples/java/debugger/OORhinoDebugger.java b/scripting/examples/java/debugger/OORhinoDebugger.java
new file mode 100644
index 000000000000..0aea985cc5f2
--- /dev/null
+++ b/scripting/examples/java/debugger/OORhinoDebugger.java
@@ -0,0 +1,75 @@
+import javax.swing.SwingUtilities;
+import java.io.InputStream;
+
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.ImporterTopLevel;
+import org.mozilla.javascript.tools.debugger.Main;
+import org.mozilla.javascript.tools.debugger.ScopeProvider;
+
+import drafts.com.sun.star.script.framework.runtime.XScriptContext;
+
+public class OORhinoDebugger implements OOScriptDebugger {
+
+ public void go(final XScriptContext xsctxt, String filename) {
+ Main sdb = initUI(xsctxt);
+
+ // This is the method we've added to open a file when starting
+ // the Rhino debugger
+ sdb.openFile(filename);
+ }
+
+ public void go(final XScriptContext xsctxt, InputStream in) {
+ Main sdb = initUI(xsctxt);
+
+ // Open a stream in the debugger
+ sdb.openStream(in);
+ }
+
+ // This code is based on the main method of the Rhino Debugger Main class
+ // We pass in the XScriptContext in the global scope for script execution
+ private Main initUI(final XScriptContext xsctxt) {
+ try {
+ final Main sdb = new Main("Rhino JavaScript Debugger");
+ swingInvoke(new Runnable() {
+ public void run() {
+ sdb.pack();
+ sdb.setSize(640, 640);
+ sdb.setVisible(true);
+ }
+ });
+ sdb.setExitAction(new Runnable() {
+ public void run() {
+ sdb.dispose();
+ }
+ });
+ Context.addContextListener(sdb);
+ sdb.setScopeProvider(new ScopeProvider() {
+ public Scriptable getScope() {
+ Context ctxt = Context.enter();
+ ImporterTopLevel scope = new ImporterTopLevel(ctxt);
+ Scriptable jsArgs = Context.toObject(xsctxt, scope);
+ scope.put("XSCRIPTCONTEXT", scope, jsArgs);
+ Context.exit();
+ return scope;
+ }
+ });
+ return sdb;
+ } catch (Exception exc) {
+ exc.printStackTrace();
+ }
+ return null;
+ }
+
+ static void swingInvoke(Runnable f) {
+ if (SwingUtilities.isEventDispatchThread()) {
+ f.run();
+ return;
+ }
+ try {
+ SwingUtilities.invokeAndWait(f);
+ } catch (Exception exc) {
+ exc.printStackTrace();
+ }
+ }
+}
diff --git a/scripting/examples/java/debugger/OOScriptDebugger.java b/scripting/examples/java/debugger/OOScriptDebugger.java
new file mode 100644
index 000000000000..67532e113f9e
--- /dev/null
+++ b/scripting/examples/java/debugger/OOScriptDebugger.java
@@ -0,0 +1,7 @@
+import java.io.InputStream;
+import drafts.com.sun.star.script.framework.runtime.XScriptContext;
+
+public interface OOScriptDebugger {
+ public void go(XScriptContext ctxt, String filename);
+ public void go(XScriptContext ctxt, InputStream in);
+}
diff --git a/scripting/examples/java/debugger/parcel-descriptor.xml b/scripting/examples/java/debugger/parcel-descriptor.xml
new file mode 100644
index 000000000000..285db1bb7b15
--- /dev/null
+++ b/scripting/examples/java/debugger/parcel-descriptor.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="Java">
+
+ <script language="Java">
+ <locale lang="en">
+ <displayname value="Scripting Framework Debugger" />
+ <description>Script that starts debuggers for JavaScript and BeanShell
+ </description>
+ </locale>
+ <logicalname value="_$DebugRunner.Debug" />
+ <functionname value="DebugRunner.go" />
+ <languagedepprops>
+ <prop name="classpath" value="debugger.jar"/>
+ </languagedepprops>
+ </script>
+</parcel>
+
diff --git a/scripting/examples/java/makefile.mk b/scripting/examples/java/makefile.mk
new file mode 100755
index 000000000000..c4a4c2a081dd
--- /dev/null
+++ b/scripting/examples/java/makefile.mk
@@ -0,0 +1,40 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.8 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+PRJ=..$/..
+PRJNAME=scripting
+TARGET=javaexamples
+
+.INCLUDE : ant.mk
+
+.IF "$(SOLAR_JAVA)"!=""
+ALLTAR : ANTBUILD
+.ENDIF
diff --git a/scripting/examples/java/selector/ScriptSelector.java b/scripting/examples/java/selector/ScriptSelector.java
new file mode 100644
index 000000000000..698faa5a6f04
--- /dev/null
+++ b/scripting/examples/java/selector/ScriptSelector.java
@@ -0,0 +1,498 @@
+import javax.swing.*;
+import javax.swing.tree.*;
+import javax.swing.table.*;
+import javax.swing.event.*;
+import javax.swing.border.*;
+import java.awt.*;
+import java.awt.event.*;
+import java.util.*;
+import java.beans.*;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.Exception;
+import com.sun.star.uno.Any;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.XComponentContext;
+
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XComponent;
+import com.sun.star.frame.XModel;
+import com.sun.star.frame.FrameSearchFlag;
+import com.sun.star.frame.XDispatchProvider;
+import com.sun.star.frame.XDispatchHelper;
+import com.sun.star.frame.XDispatch;
+import com.sun.star.util.XURLTransformer;
+import com.sun.star.beans.*;
+import com.sun.star.script.XInvocation;
+
+import com.sun.star.lib.uno.helper.PropertySet;
+
+import com.sun.star.script.browse.XBrowseNode;
+import com.sun.star.script.browse.BrowseNodeTypes;
+import com.sun.star.script.browse.XBrowseNodeFactory;
+import com.sun.star.script.browse.BrowseNodeFactoryViewTypes;
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.provider.XScript;
+import com.sun.star.script.provider.XScriptProvider;
+
+public class ScriptSelector {
+
+ private static final int BIG_GAP = 10;
+ private static final int MED_GAP = 5;
+
+ private ScriptSelectorPanel selectorPanel;
+
+ public ScriptSelector()
+ {
+ }
+
+ public void showOrganizer(final XScriptContext ctxt)
+ {
+ try {
+ XBrowseNode root = getRootNode(ctxt);
+
+ final XScriptProvider msp =
+ (XScriptProvider)UnoRuntime.queryInterface(
+ XScriptProvider.class, root);
+
+ final JFrame client = new JFrame("Script");
+
+ selectorPanel = new ScriptSelectorPanel(root);
+
+ final JButton runButton, closeButton, createButton,
+ editButton, deleteButton;
+
+ runButton = new JButton("Run");
+ runButton.setEnabled(false);
+
+ closeButton = new JButton("Close");
+
+ editButton = new JButton("Edit");
+ editButton.setEnabled(false);
+
+ JPanel northButtons =
+ new JPanel(new GridLayout(2, 1, MED_GAP, MED_GAP));
+
+ northButtons.add(runButton);
+ northButtons.add(closeButton);
+
+ createButton = new JButton("Create");
+ createButton.setEnabled(false);
+
+ deleteButton = new JButton("Delete");
+ deleteButton.setEnabled(false);
+
+ JPanel southButtons =
+ new JPanel(new GridLayout(3, 1, MED_GAP, MED_GAP));
+
+ southButtons.add(editButton);
+ southButtons.add(createButton);
+ southButtons.add(deleteButton);
+
+ selectorPanel.tree.addTreeSelectionListener(
+ new TreeSelectionListener() {
+ public void valueChanged(TreeSelectionEvent e) {
+ XBrowseNode xbn = selectorPanel.getSelection();
+ XPropertySet props = (XPropertySet)
+ UnoRuntime.queryInterface(XPropertySet.class, xbn);
+
+ checkEnabled(props, "Creatable", createButton);
+ checkEnabled(props, "Deletable", deleteButton);
+ checkEnabled(props, "Editable", editButton);
+
+ if (xbn != null &&
+ xbn.getType() == BrowseNodeTypes.SCRIPT)
+ {
+ runButton.setEnabled(true);
+ }
+ else
+ {
+ runButton.setEnabled(false);
+ }
+ }
+ }
+ );
+
+ ActionListener listener = new ActionListener() {
+ public void actionPerformed(ActionEvent event) {
+ if (event.getSource() == runButton) {
+ String uri = selectorPanel.textField.getText();
+
+ try {
+ XScript script = msp.getScript(uri);
+
+ Object[][] out = new Object[1][0];
+ out[0] = new Object[0];
+
+ short[][] num = new short[1][0];
+ num[0] = new short[0];
+
+ script.invoke(new Object[0], num, out);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ else if (event.getSource() == closeButton) {
+ client.dispose();
+ }
+ else if (event.getSource() == editButton) {
+ DefaultMutableTreeNode node =
+ (DefaultMutableTreeNode)
+ selectorPanel.tree.getLastSelectedPathComponent();
+
+ if (node == null) return;
+
+ showEditor(ctxt, node);
+ }
+ else if (event.getSource() == createButton) {
+ DefaultMutableTreeNode node =
+ (DefaultMutableTreeNode)
+ selectorPanel.tree.getLastSelectedPathComponent();
+
+ if (node == null) return;
+
+ doCreate(ctxt, node);
+ }
+ else if (event.getSource() == deleteButton) {
+ DefaultMutableTreeNode node =
+ (DefaultMutableTreeNode)
+ selectorPanel.tree.getLastSelectedPathComponent();
+
+ if (node == null) return;
+
+ doDelete(ctxt, node);
+ }
+ }
+ };
+
+ runButton.addActionListener(listener);
+ closeButton.addActionListener(listener);
+ createButton.addActionListener(listener);
+ editButton.addActionListener(listener);
+ deleteButton.addActionListener(listener);
+
+ JPanel buttonPanel = new JPanel(new BorderLayout());
+ buttonPanel.add(northButtons, BorderLayout.NORTH);
+ buttonPanel.add(southButtons, BorderLayout.SOUTH);
+
+ JPanel mainPanel = new JPanel(new BorderLayout(MED_GAP, MED_GAP));
+ mainPanel.setBorder(
+ new EmptyBorder(BIG_GAP, BIG_GAP, BIG_GAP, BIG_GAP));
+ mainPanel.add(selectorPanel, BorderLayout.CENTER);
+ mainPanel.add(buttonPanel, BorderLayout.EAST);
+
+ client.getContentPane().add(mainPanel);
+ client.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
+ client.setSize(500, 350);
+
+ // set the x and y locations so that the frame is in the
+ // centre of the screen
+ Dimension d = client.getToolkit().getScreenSize();
+
+ int x = (int)((d.getWidth() - client.getWidth()) / 2);
+ int y = (int)((d.getHeight() - client.getHeight()) / 2);
+
+ client.setLocation(x, y);
+
+ client.show();
+ }
+ catch (com.sun.star.uno.RuntimeException rue) {
+ rue.printStackTrace();
+ }
+ catch (java.lang.Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ public void showOrganizer(final XScriptContext ctxt,
+ final com.sun.star.awt.MouseEvent e)
+ {
+ showOrganizer(ctxt);
+ }
+
+ public void showOrganizer(final XScriptContext ctxt,
+ final com.sun.star.awt.ActionEvent e)
+ {
+ showOrganizer(ctxt);
+ }
+
+ private void doDelete(
+ XScriptContext ctxt, DefaultMutableTreeNode node)
+ {
+ Object obj = node.getUserObject();
+ XInvocation inv =
+ (XInvocation)UnoRuntime.queryInterface(
+ XInvocation.class, obj);
+ Object[] args = new Object[] { ctxt };
+ try {
+ Object result = inv.invoke("Deletable", args,
+ new short[1][0], new Object[1][0]);
+
+ if (result != null && AnyConverter.toBoolean(result) == true)
+ {
+ selectorPanel.removeNode(node);
+ }
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void doCreate(
+ XScriptContext ctxt, DefaultMutableTreeNode node)
+ {
+ Object obj = node.getUserObject();
+ XInvocation inv =
+ (XInvocation)UnoRuntime.queryInterface(
+ XInvocation.class, obj);
+ Object[] args = new Object[] { ctxt };
+ try {
+ Object result = inv.invoke("Creatable", args,
+ new short[1][0], new Object[1][0]);
+
+ if (result != null)
+ {
+ XBrowseNode xbn = (XBrowseNode)
+ AnyConverter.toObject(new Type(XBrowseNode.class), result);
+ selectorPanel.addNode(node, xbn);
+ }
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void showEditor(
+ XScriptContext ctxt, DefaultMutableTreeNode node)
+ {
+ Object obj = node.getUserObject();
+ XInvocation inv =
+ (XInvocation)UnoRuntime.queryInterface(
+ XInvocation.class, obj);
+ Object[] args = new Object[] { ctxt };
+ try {
+ inv.invoke("Editable", args,
+ new short[1][0], new Object[1][0]);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void checkEnabled(XPropertySet props, String name,
+ JButton button)
+ {
+ boolean enable = false;
+
+ try
+ {
+ if (props != null)
+ {
+ Object o = props.getPropertyValue(name);
+ enable = AnyConverter.toBoolean(
+ props.getPropertyValue(name));
+ }
+ }
+ catch (com.sun.star.lang.IllegalArgumentException iae)
+ {
+ // leave enable set to false
+ }
+ catch (com.sun.star.beans.UnknownPropertyException upe)
+ {
+ // leave enable set to false
+ }
+ catch (com.sun.star.lang.WrappedTargetException wte)
+ {
+ // leave enable set to false
+ }
+
+ button.setEnabled(enable);
+ }
+
+ private XBrowseNode getRootNode(XScriptContext ctxt) {
+
+ XBrowseNode result = null;
+
+
+ XComponentContext xcc = ctxt.getComponentContext();
+ XMultiComponentFactory xmcf = xcc.getServiceManager();
+ XBrowseNodeFactory xBrowseFac = (XBrowseNodeFactory)
+ UnoRuntime.queryInterface( XBrowseNodeFactory.class, xcc.getValueByName(
+ "/singletons/com.sun.star.script.browse.theBrowseNodeFactory") );
+
+
+ result = (XBrowseNode)UnoRuntime.queryInterface(
+ XBrowseNode.class, xBrowseFac.createView( BrowseNodeFactoryViewTypes.MACROORGANIZER ) );
+ return result;
+ }
+}
+
+class ScriptSelectorPanel extends JPanel {
+
+ private XBrowseNode myrootnode = null;
+ public JTextField textField;
+ public JTree tree;
+ public DefaultTreeModel treeModel;
+
+ public ScriptSelectorPanel(XBrowseNode root)
+ {
+ this.myrootnode = root;
+ initUI();
+ }
+
+ public XBrowseNode getSelection() {
+ DefaultMutableTreeNode node = (DefaultMutableTreeNode)
+ tree.getLastSelectedPathComponent();
+
+ if (node == null) {
+ return null;
+ }
+
+ return (XBrowseNode)node.getUserObject();
+ }
+
+ private void initUI() {
+ setLayout(new BorderLayout());
+
+ DefaultMutableTreeNode top =
+ new DefaultMutableTreeNode(myrootnode) {
+ public String toString() {
+ return ((XBrowseNode)getUserObject()).getName();
+ }
+ };
+ initNodes(myrootnode, top);
+ treeModel = new DefaultTreeModel(top);
+ tree = new JTree(treeModel);
+
+ tree.setCellRenderer(new ScriptTreeRenderer());
+
+ tree.getSelectionModel().setSelectionMode
+ (TreeSelectionModel.SINGLE_TREE_SELECTION);
+
+ tree.addTreeSelectionListener(new TreeSelectionListener() {
+ public void valueChanged(TreeSelectionEvent e) {
+ XBrowseNode xbn = getSelection();
+ XPropertySet props = (XPropertySet)UnoRuntime.queryInterface(
+ XPropertySet.class, xbn);
+
+ if (xbn == null) {
+ textField.setText("");
+ return;
+ }
+
+ String str = xbn.getName();
+ if (xbn.getType() == BrowseNodeTypes.SCRIPT && props != null)
+ {
+ try {
+ str = AnyConverter.toString(
+ props.getPropertyValue("URI"));
+ }
+ catch (Exception ignore) {
+ // default will be used
+ }
+ }
+ textField.setText(str);
+ }
+ });
+
+ JScrollPane scroller = new JScrollPane(tree);
+ add(scroller, BorderLayout.CENTER);
+
+ textField = new JTextField();
+ add(textField, BorderLayout.SOUTH);
+ }
+
+ public void removeNode(DefaultMutableTreeNode node) {
+ MutableTreeNode parent = (MutableTreeNode)(node.getParent());
+ if (parent != null) {
+ treeModel.removeNodeFromParent(node);
+ }
+ }
+
+ public void addNode(DefaultMutableTreeNode parent, XBrowseNode xbn) {
+ DefaultMutableTreeNode newNode =
+ new DefaultMutableTreeNode(xbn) {
+ public String toString() {
+ return ((XBrowseNode)getUserObject()).getName();
+ }
+ };
+
+ treeModel.insertNodeInto(newNode, parent, parent.getChildCount());
+ tree.scrollPathToVisible(new TreePath(newNode.getPath()));
+ }
+
+ private void initNodes(XBrowseNode parent, DefaultMutableTreeNode top) {
+ if ( parent == null || parent.hasChildNodes() == false )
+ {
+ return;
+ }
+
+ XBrowseNode[] children = parent.getChildNodes();
+
+ try {
+ if (children != null) {
+ for (int i = 0; i < children.length; i++) {
+ if ( children[i] == null )
+ {
+ continue;
+ }
+ DefaultMutableTreeNode newNode =
+ new DefaultMutableTreeNode(children[i]) {
+ public String toString() {
+ return ((XBrowseNode)getUserObject()).getName();
+ }
+ };
+ top.add(newNode);
+ initNodes(children[i], newNode);
+ }
+ }
+ }
+ catch (java.lang.Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
+
+class ScriptTreeRenderer extends DefaultTreeCellRenderer {
+
+ private ImageIcon sofficeIcon;
+ private ImageIcon scriptIcon;
+ private ImageIcon containerIcon;
+
+ public ScriptTreeRenderer() {
+ sofficeIcon = new ImageIcon(getClass().getResource("soffice.gif"));
+ scriptIcon = new ImageIcon(getClass().getResource("script.gif"));
+ containerIcon = new ImageIcon(getClass().getResource("container.gif"));
+ }
+
+ public Component getTreeCellRendererComponent(
+ JTree tree,
+ Object value,
+ boolean sel,
+ boolean expanded,
+ boolean leaf,
+ int row,
+ boolean hasFocus) {
+
+ super.getTreeCellRendererComponent(
+ tree, value, sel,
+ expanded, leaf, row,
+ hasFocus);
+
+ DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
+ XBrowseNode xbn = (XBrowseNode)node.getUserObject();
+ if (xbn.getType() == BrowseNodeTypes.SCRIPT) {
+ setIcon(scriptIcon);
+ }
+ else if(xbn.getType() == BrowseNodeTypes.CONTAINER) {
+ setIcon(containerIcon);
+ }
+ else if(xbn.getType() == BrowseNodeTypes.ROOT) {
+ setIcon(sofficeIcon);
+ }
+
+ return this;
+ }
+}
diff --git a/scripting/examples/java/selector/container.gif b/scripting/examples/java/selector/container.gif
new file mode 100644
index 000000000000..3a345f9bf94a
--- /dev/null
+++ b/scripting/examples/java/selector/container.gif
Binary files differ
diff --git a/scripting/examples/java/selector/parcel-descriptor.xml b/scripting/examples/java/selector/parcel-descriptor.xml
new file mode 100644
index 000000000000..8e3e70e8c60b
--- /dev/null
+++ b/scripting/examples/java/selector/parcel-descriptor.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="Java" xmlns:parcel="scripting.dtd">
+ <script language="Java">
+ <locale lang="en">
+ <displayname value="Script Selector"/>
+ <description>
+ Prototype Script Selector GUI for StarOffice
+ </description>
+ </locale>
+ <functionname value="ScriptSelector.showOrganizer"/>
+ <logicalname value="ScriptSelector.showOrganizer"/>
+ <languagedepprops>
+ <prop name="classpath" value="selector.jar"/>
+ </languagedepprops>
+ </script>
+</parcel>
diff --git a/scripting/examples/java/selector/script.gif b/scripting/examples/java/selector/script.gif
new file mode 100644
index 000000000000..d3b3768cae11
--- /dev/null
+++ b/scripting/examples/java/selector/script.gif
Binary files differ
diff --git a/scripting/examples/java/selector/soffice.gif b/scripting/examples/java/selector/soffice.gif
new file mode 100644
index 000000000000..88124d87d1e6
--- /dev/null
+++ b/scripting/examples/java/selector/soffice.gif
Binary files differ
diff --git a/scripting/examples/javascript/ExportSheetsToHTML/exportsheetstohtml.js b/scripting/examples/javascript/ExportSheetsToHTML/exportsheetstohtml.js
new file mode 100644
index 000000000000..a66d08a185c6
--- /dev/null
+++ b/scripting/examples/javascript/ExportSheetsToHTML/exportsheetstohtml.js
@@ -0,0 +1,71 @@
+// When this script is run on an existing, saved, spreadsheet,
+// eg. /home/testuser/myspreadsheet.sxc, the script will export
+// each sheet to a separate html file,
+// eg. /home/testuser/myspreadsheet_sheet1.html,
+// /home/testuser/myspreadsheet_sheet2.html etc
+importClass(Packages.com.sun.star.uno.UnoRuntime);
+importClass(Packages.com.sun.star.sheet.XSpreadsheetDocument);
+importClass(Packages.com.sun.star.container.XIndexAccess);
+importClass(Packages.com.sun.star.beans.XPropertySet);
+importClass(Packages.com.sun.star.beans.PropertyValue);
+importClass(Packages.com.sun.star.util.XModifiable);
+importClass(Packages.com.sun.star.frame.XStorable);
+importClass(Packages.com.sun.star.frame.XModel);
+importClass(Packages.com.sun.star.uno.AnyConverter);
+importClass(Packages.com.sun.star.uno.Type);
+
+importClass(java.lang.System);
+
+//get the document object from the scripting context
+oDoc = XSCRIPTCONTEXT.getDocument();
+//get the XSpreadsheetDocument interface from the document
+xSDoc = UnoRuntime.queryInterface(XSpreadsheetDocument, oDoc);
+//get the XModel interface from the document
+xModel = UnoRuntime.queryInterface(XModel,oDoc);
+//get the XIndexAccess interface used to access each sheet
+xSheetsIndexAccess = UnoRuntime.queryInterface(XIndexAccess, xSDoc.getSheets());
+//get the XStorable interface used to save the document
+xStorable = UnoRuntime.queryInterface(XStorable,xSDoc);
+//get the XModifiable interface used to indicate if the document has been
+//changed
+xModifiable = UnoRuntime.queryInterface(XModifiable,xSDoc);
+
+//set up an array of PropertyValue objects used to save each sheet in the
+//document
+storeProps = new Array;//PropertyValue[1];
+storeProps[0] = new PropertyValue();
+storeProps[0].Name = "FilterName";
+storeProps[0].Value = "HTML (StarCalc)";
+storeUrl = xModel.getURL();
+storeUrl = storeUrl.substring(0,storeUrl.lastIndexOf('.'));
+
+//set only one sheet visible, and store to HTML doc
+for(var i=0;i<xSheetsIndexAccess.getCount();i++)
+{
+ setAllButOneHidden(xSheetsIndexAccess,i);
+ xModifiable.setModified(false);
+ xStorable.storeToURL(storeUrl+"_sheet"+(i+1)+".html", storeProps);
+}
+
+// now set all visible again
+for(var i=0;i<xSheetsIndexAccess.getCount();i++)
+{
+ xPropSet = AnyConverter.toObject( new Type(XPropertySet), xSheetsIndexAccess.getByIndex(i));
+ xPropSet.setPropertyValue("IsVisible", true);
+}
+
+function setAllButOneHidden(xSheetsIndexAccess,vis) {
+ //System.err.println("count="+xSheetsIndexAccess.getCount());
+ //get an XPropertySet interface for the vis-th sheet
+ xPropSet = AnyConverter.toObject( new Type(XPropertySet), xSheetsIndexAccess.getByIndex(vis));
+ //set the vis-th sheet to be visible
+ xPropSet.setPropertyValue("IsVisible", true);
+ // set all other sheets to be invisible
+ for(var i=0;i<xSheetsIndexAccess.getCount();i++)
+ {
+ xPropSet = AnyConverter.toObject( new Type(XPropertySet), xSheetsIndexAccess.getByIndex(i));
+ if(i!=vis) {
+ xPropSet.setPropertyValue("IsVisible", false);
+ }
+ }
+}
diff --git a/scripting/examples/javascript/ExportSheetsToHTML/parcel-descriptor.xml b/scripting/examples/javascript/ExportSheetsToHTML/parcel-descriptor.xml
new file mode 100755
index 000000000000..d6c3b51f0dda
--- /dev/null
+++ b/scripting/examples/javascript/ExportSheetsToHTML/parcel-descriptor.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="JavaScript" xmlns:parcel="scripting.dtd">
+
+ <script language="JavaScript">
+ <locale lang="en">
+ <displayname value="ExportSheetsToHTML"/>
+ <description>
+ Saves each sheet in the current Calc document as a separate HTML file in the same directory as the original Calc document.
+ </description>
+ </locale>
+ <functionname value="exportsheetstohtml.js"/>
+ <logicalname value="ExportSheetsToHTML.JavaScript"/>
+ </script>
+
+</parcel>
diff --git a/scripting/examples/javascript/HelloWorld/helloworld.js b/scripting/examples/javascript/HelloWorld/helloworld.js
new file mode 100644
index 000000000000..aa170def23a5
--- /dev/null
+++ b/scripting/examples/javascript/HelloWorld/helloworld.js
@@ -0,0 +1,16 @@
+// Hello World in JavaScript
+importClass(Packages.com.sun.star.uno.UnoRuntime);
+importClass(Packages.com.sun.star.text.XTextDocument);
+importClass(Packages.com.sun.star.text.XText);
+importClass(Packages.com.sun.star.text.XTextRange);
+
+//get the document from the scripting context
+oDoc = XSCRIPTCONTEXT.getDocument();
+//get the XTextDocument interface
+xTextDoc = UnoRuntime.queryInterface(XTextDocument,oDoc);
+//get the XText interface
+xText = xTextDoc.getText();
+//get an (empty) XTextRange interface at the end of the text
+xTextRange = xText.getEnd();
+//set the text in the XTextRange
+xTextRange.setString( "Hello World (in JavaScript)" );
diff --git a/scripting/examples/javascript/HelloWorld/parcel-descriptor.xml b/scripting/examples/javascript/HelloWorld/parcel-descriptor.xml
new file mode 100755
index 000000000000..d583ec2e62ad
--- /dev/null
+++ b/scripting/examples/javascript/HelloWorld/parcel-descriptor.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="JavaScript" xmlns:parcel="scripting.dtd">
+
+ <script language="JavaScript">
+ <locale lang="en">
+ <displayname value="Hello World"/>
+ <description>
+ Adds the the string "Hello World" into the current text doc.
+ </description>
+ </locale>
+ <functionname value="helloworld.js"/>
+ <logicalname value="HelloWorld.JavaScript"/>
+ </script>
+
+</parcel>
diff --git a/scripting/examples/javascript/Highlight/ButtonPressHandler.js b/scripting/examples/javascript/Highlight/ButtonPressHandler.js
new file mode 100644
index 000000000000..306b99916000
--- /dev/null
+++ b/scripting/examples/javascript/Highlight/ButtonPressHandler.js
@@ -0,0 +1,105 @@
+//this script acts as a handler for the buttons in the Highlight dialog
+importClass(Packages.com.sun.star.uno.UnoRuntime);
+importClass(Packages.com.sun.star.uno.Type);
+importClass(Packages.com.sun.star.uno.AnyConverter);
+
+importClass(Packages.com.sun.star.awt.XButton);
+importClass(Packages.com.sun.star.awt.XControl);
+importClass(Packages.com.sun.star.awt.ActionEvent);
+importClass(Packages.com.sun.star.awt.XControlModel);
+importClass(Packages.com.sun.star.awt.XControlContainer);
+importClass(Packages.com.sun.star.awt.XDialog);
+importClass(Packages.com.sun.star.awt.XTextComponent);
+
+importClass(Packages.com.sun.star.util.XReplaceable);
+importClass(Packages.com.sun.star.util.XReplaceDescriptor);
+importClass(Packages.com.sun.star.util.XPropertyReplace);
+
+importClass(Packages.com.sun.star.beans.XPropertySet);
+importClass(Packages.com.sun.star.beans.PropertyValue);
+
+// Scripting Framework DialogFactory class
+importClass(Packages.com.sun.star.script.framework.browse.DialogFactory);
+
+// Get the ActionEvent object from the ARGUMENTS list
+event = ARGUMENTS[0];
+
+// Each argument is of type Any so we must use the AnyConverter class to
+// convert it into the interface or primitive type we expect
+button = AnyConverter.toObject(new Type(XButton), event.Source);
+
+// We can now query for the model of the button and get its properties
+control = UnoRuntime.queryInterface(XControl, button);
+cmodel = control.getModel();
+pset = UnoRuntime.queryInterface(XPropertySet, cmodel);
+
+if (pset.getPropertyValue("Label").equals("Exit"))
+{
+ // We can get the XDialog in which this control appears by calling
+ // getContext() on the XControl interface
+ xDialog = UnoRuntime.queryInterface(
+ XDialog, control.getContext());
+
+ // Close the dialog
+ xDialog.endExecute();
+}
+else
+{
+ // We can get the list of controls for this dialog by calling
+ // getContext() on the XControl interface of the button
+ controls = UnoRuntime.queryInterface(
+ XControlContainer, control.getContext());
+
+ // Now get the text field control from the list
+ textField =
+ UnoRuntime.queryInterface(
+ XTextComponent, controls.getControl("HighlightTextField"));
+
+ searchKey = textField.getText();
+
+ // highlight the text in red
+ red = java.awt.Color.red.getRGB();
+
+ replaceable =
+ UnoRuntime.queryInterface(XReplaceable, XSCRIPTCONTEXT.getDocument());
+
+ descriptor = replaceable.createReplaceDescriptor();
+
+ // Gets a XPropertyReplace object for altering the properties
+ // of the replaced text
+ xPropertyReplace = UnoRuntime.queryInterface(XPropertyReplace, descriptor);
+
+ // Sets the replaced text property fontweight value to Bold
+ wv = new PropertyValue("CharWeight", -1,
+ new java.lang.Float(Packages.com.sun.star.awt.FontWeight.BOLD),
+ Packages.com.sun.star.beans.PropertyState.DIRECT_VALUE);
+
+ // Sets the replaced text property color value to RGB parameter
+ cv = new PropertyValue("CharColor", -1,
+ new java.lang.Integer(red),
+ Packages.com.sun.star.beans.PropertyState.DIRECT_VALUE);
+
+ // Apply the properties
+ props = new Array;
+ props[0] = cv;
+ props[1] = wv;
+
+ try {
+ xPropertyReplace.setReplaceAttributes(props);
+
+ // Only matches whole words and case sensitive
+ descriptor.setPropertyValue(
+ "SearchCaseSensitive", new java.lang.Boolean(true));
+ descriptor.setPropertyValue("SearchWords", new java.lang.Boolean(true));
+
+ // Replaces all instances of searchKey with new Text properties
+ // and gets the number of instances of the searchKey
+ descriptor.setSearchString(searchKey);
+ descriptor.setReplaceString(searchKey);
+ replaceable.replaceAll(descriptor);
+ }
+ catch (e) {
+ java.lang.System.err.println("Error setting up search properties"
+ + e.getMessage());
+ }
+}
diff --git a/scripting/examples/javascript/Highlight/ShowDialog.js b/scripting/examples/javascript/Highlight/ShowDialog.js
new file mode 100644
index 000000000000..a6f9759d9a18
--- /dev/null
+++ b/scripting/examples/javascript/Highlight/ShowDialog.js
@@ -0,0 +1,115 @@
+importClass(Packages.com.sun.star.uno.UnoRuntime);
+importClass(Packages.com.sun.star.lang.XMultiComponentFactory);
+importClass(Packages.com.sun.star.awt.XDialogProvider);
+importClass(Packages.com.sun.star.awt.XDialog);
+importClass(Packages.com.sun.star.uno.Exception);
+importClass(Packages.com.sun.star.script.provider.XScriptContext);
+
+importClass(java.lang.Thread);
+importClass(java.lang.System);
+
+function tryLoadingLibrary( xmcf, context, name )
+{
+ try
+ {
+ obj = xmcf.createInstanceWithContext(
+ "com.sun.star.script.Application" + name + "LibraryContainer",
+ context.getComponentContext());
+
+ xLibraryContainer = UnoRuntime.queryInterface(XLibraryContainer, obj);
+
+ System.err.println("Got XLibraryContainer");
+
+ serviceObj = context.getComponentContext().getValueByName(
+ "/singletons/com.sun.star.util.theMacroExpander");
+
+ xme = AnyConverter.toObject(new Type(XMacroExpander), serviceObj);
+
+ bootstrapName = "bootstraprc";
+ if (System.getProperty("os.name").startsWith("Windows"))
+ {
+ bootstrapName = "bootstrap.ini";
+ }
+
+ libURL = xme.expandMacros(
+ "${$BRAND_BASE_DIR/program/" + bootstrapName + "::BaseInstallation}" +
+ "/share/basic/ScriptBindingLibrary/" +
+ name.toLowerCase() + ".xlb/");
+
+ System.err.println("libURL is: " + libURL);
+
+ xLibraryContainer.createLibraryLink(
+ "ScriptBindingLibrary", libURL, false);
+
+ System.err.println("liblink created");
+
+ }
+ catch (e)
+ {
+ System.err.println("Got an exception loading lib: " + e.getMessage());
+ return false;
+ }
+ return true;
+}
+
+function getDialogProvider()
+{
+ // UNO awt components of the Highlight dialog
+ //get the XMultiServiceFactory
+ xmcf = XSCRIPTCONTEXT.getComponentContext().getServiceManager();
+
+ args = new Array;
+ //get the XDocument from the context
+ args[0] = XSCRIPTCONTEXT.getDocument();
+
+ //try to create the DialogProvider
+ try {
+ obj = xmcf.createInstanceWithArgumentsAndContext(
+ "com.sun.star.awt.DialogProvider", args,
+ XSCRIPTCONTEXT.getComponentContext());
+ }
+ catch (e) {
+ System.err.println("Error getting DialogProvider object");
+ return null;
+ }
+
+ return UnoRuntime.queryInterface(XDialogProvider, obj);
+}
+
+//get the DialogProvider
+xDialogProvider = getDialogProvider();
+
+if (xDialogProvider != null)
+{
+ //try to create the Highlight dialog (found in the ScriptBinding library)
+ try
+ {
+ findDialog = xDialogProvider.createDialog("vnd.sun.star.script:" +
+ "ScriptBindingLibrary.Highlight?location=application");
+ if( findDialog == null )
+ {
+ if (tryLoadingLibrary(xmcf, XSCRIPTCONTEXT, "Dialog") == false ||
+ tryLoadingLibrary(xmcf, XSCRIPTCONTEXT, "Script") == false)
+ {
+ System.err.println("Error loading ScriptBindingLibrary");
+ }
+ else
+ {
+ // try to create the Highlight dialog (found in the
+ // ScriptBindingLibrary)
+ findDialog = xDialogProvider.createDialog("vnd.sun.star.script:" +
+ "ScriptBindingLibrary.Highlight?location=application");
+ }
+ }
+
+ //launch the dialog
+ if ( findDialog != null )
+ {
+ findDialog.execute();
+ }
+ }
+ catch (e) {
+ System.err.println("Got exception on first creating dialog: " +
+ e.getMessage());
+ }
+}
diff --git a/scripting/examples/javascript/Highlight/parcel-descriptor.xml b/scripting/examples/javascript/Highlight/parcel-descriptor.xml
new file mode 100644
index 000000000000..a6e6396fbe70
--- /dev/null
+++ b/scripting/examples/javascript/Highlight/parcel-descriptor.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="JavaScript" xmlns:parcel="scripting.dtd">
+ <script language="JavaScript">
+ <locale lang="en">
+ <displayname value="ShowDialog" />
+ <description>
+ Example of how to show a dialog from JavaScript
+ </description>
+ </locale>
+ <functionname value="ShowDialog.js" />
+ <logicalname value="ShowDialog.JavaScript" />
+ </script>
+ <script language="JavaScript">
+ <locale lang="en">
+ <displayname value="ButtonPressHandler" />
+ <description>
+ Example of handle button press events for the Dialog
+ </description>
+ </locale>
+ <functionname value="ButtonPressHandler.js" />
+ <logicalname value="ButtonPressHandler.JavaScript" />
+ </script>
+</parcel>
+
diff --git a/scripting/examples/makefile.mk b/scripting/examples/makefile.mk
new file mode 100755
index 000000000000..53660595538e
--- /dev/null
+++ b/scripting/examples/makefile.mk
@@ -0,0 +1,62 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.12 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+PRJ=..
+PRJNAME=scriptinginstaller
+TARGET=scriptinginstaller
+no_common_build_zip=true
+
+.INCLUDE : settings.mk
+
+.IF "$(SOLAR_JAVA)"!=""
+ZIP1FLAGS=-r
+ZIP1TARGET=ScriptsJava
+ZIP1DIR=$(OUT)$/class$/examples
+ZIP1LIST=java
+.ENDIF
+
+ZIP2FLAGS=-r
+ZIP2TARGET=ScriptsBeanShell
+ZIP2LIST=beanshell/HelloWorld beanshell/Highlight beanshell/WordCount beanshell/Capitalise beanshell/MemoryUsage
+
+ZIP3FLAGS=-r
+ZIP3TARGET=ScriptsJavaScript
+ZIP3LIST=javascript
+
+ZIP4FLAGS=-r
+ZIP4TARGET=ScriptsPython
+ZIP4LIST=python/HelloWorld.py python/Capitalise.py python/pythonSamples
+
+ZIP5FLAGS=-r
+ZIP5TARGET=scriptbindinglib
+ZIP5DIR=$(PRJ)$/workben$/bindings
+ZIP5LIST=*.xlb Highlight.xdl
+
+.INCLUDE : target.mk
diff --git a/scripting/examples/python/Capitalise.py b/scripting/examples/python/Capitalise.py
new file mode 100644
index 000000000000..195d74801b13
--- /dev/null
+++ b/scripting/examples/python/Capitalise.py
@@ -0,0 +1,61 @@
+
+# helper function
+def getNewString( theString ) :
+ if( not theString or len(theString) ==0) :
+ return ""
+ # should we tokenize on "."?
+ if theString[0].isupper() and len(theString)>=2 and theString[1].isupper() :
+ # first two chars are UC => first UC, rest LC
+ newString=theString[0:1].upper() + theString[1:].lower();
+ elif theString[0].isupper():
+ # first char UC => all to LC
+ newString=theString.lower()
+ else: # all to UC.
+ newString=theString.upper()
+ return newString;
+
+def capitalisePython( ):
+ """Change the case of a selection, or current word from upper case, to first char upper case, to all lower case to upper case..."""
+ import string
+
+ # The context variable is of type XScriptContext and is available to
+ # all BeanShell scripts executed by the Script Framework
+ xModel = XSCRIPTCONTEXT.getDocument()
+
+ #the writer controller impl supports the css.view.XSelectionSupplier interface
+ xSelectionSupplier = xModel.getCurrentController()
+
+ #see section 7.5.1 of developers' guide
+ xIndexAccess = xSelectionSupplier.getSelection()
+ count = xIndexAccess.getCount();
+ if(count>=1): #ie we have a selection
+ i=0
+ while i < count :
+ xTextRange = xIndexAccess.getByIndex(i);
+ #print "string: " + xTextRange.getString();
+ theString = xTextRange.getString();
+ if len(theString)==0 :
+ # sadly we can have a selection where nothing is selected
+ # in this case we get the XWordCursor and make a selection!
+ xText = xTextRange.getText();
+ xWordCursor = xText.createTextCursorByRange(xTextRange);
+ if not xWordCursor.isStartOfWord():
+ xWordCursor.gotoStartOfWord(False);
+ xWordCursor.gotoNextWord(True);
+ theString = xWordCursor.getString();
+ newString = getNewString(theString);
+ if newString :
+ xWordCursor.setString(newString);
+ xSelectionSupplier.select(xWordCursor);
+ else :
+
+ newString = getNewString( theString );
+ if newString:
+ xTextRange.setString(newString);
+ xSelectionSupplier.select(xTextRange);
+ i+= 1
+
+
+# lists the scripts, that shall be visible inside OOo. Can be omited, if
+# all functions shall be visible, however here getNewString shall be surpressed
+g_exportedScripts = capitalisePython,
diff --git a/scripting/examples/python/HelloWorld.py b/scripting/examples/python/HelloWorld.py
new file mode 100644
index 000000000000..7f5b45c8cd08
--- /dev/null
+++ b/scripting/examples/python/HelloWorld.py
@@ -0,0 +1,13 @@
+# HelloWorld python script for the scripting framework
+
+def HelloWorldPython( ):
+ """Prints the string 'Hello World(in Python)' into the current document"""
+#get the doc from the scripting context which is made available to all scripts
+ model = XSCRIPTCONTEXT.getDocument()
+#get the XText interface
+ text = model.Text
+#create an XTextRange at the end of the document
+ tRange = text.End
+#and set the string
+ tRange.String = "Hello World (in Python)"
+ return None
diff --git a/scripting/examples/python/pythonSamples/TableSample.py b/scripting/examples/python/pythonSamples/TableSample.py
new file mode 100644
index 000000000000..793b79725a74
--- /dev/null
+++ b/scripting/examples/python/pythonSamples/TableSample.py
@@ -0,0 +1,96 @@
+import uno
+
+# a UNO struct later needed to create a document
+from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
+from com.sun.star.text.TextContentAnchorType import AS_CHARACTER
+from com.sun.star.awt import Size
+
+from com.sun.star.lang import XMain
+
+def insertTextIntoCell( table, cellName, text, color ):
+ tableText = table.getCellByName( cellName )
+ cursor = tableText.createTextCursor()
+ cursor.setPropertyValue( "CharColor", color )
+ tableText.setString( text )
+
+
+def createTable():
+ """creates a new writer document and inserts a table with some data (also known as the SWriter sample)"""
+ ctx = uno.getComponentContext()
+ smgr = ctx.ServiceManager
+ desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
+
+ # open a writer document
+ doc = desktop.loadComponentFromURL( "private:factory/swriter","_blank", 0, () )
+
+ text = doc.Text
+ cursor = text.createTextCursor()
+ text.insertString( cursor, "The first line in the newly created text document.\n", 0 )
+ text.insertString( cursor, "Now we are in the second line\n" , 0 )
+
+ # create a text table
+ table = doc.createInstance( "com.sun.star.text.TextTable" )
+
+ # with 4 rows and 4 columns
+ table.initialize( 4,4)
+
+ text.insertTextContent( cursor, table, 0 )
+ rows = table.Rows
+
+ table.setPropertyValue( "BackTransparent", uno.Bool(0) )
+ table.setPropertyValue( "BackColor", 13421823 )
+ row = rows.getByIndex(0)
+ row.setPropertyValue( "BackTransparent", uno.Bool(0) )
+ row.setPropertyValue( "BackColor", 6710932 )
+
+ textColor = 16777215
+
+ insertTextIntoCell( table, "A1", "FirstColumn", textColor )
+ insertTextIntoCell( table, "B1", "SecondColumn", textColor )
+ insertTextIntoCell( table, "C1", "ThirdColumn", textColor )
+ insertTextIntoCell( table, "D1", "SUM", textColor )
+
+ values = ( (22.5,21.5,121.5),
+ (5615.3,615.3,-615.3),
+ (-2315.7,315.7,415.7) )
+ table.getCellByName("A2").setValue(22.5)
+ table.getCellByName("B2").setValue(5615.3)
+ table.getCellByName("C2").setValue(-2315.7)
+ table.getCellByName("D2").setFormula("sum <A2:C2>")
+
+ table.getCellByName("A3").setValue(21.5)
+ table.getCellByName("B3").setValue(615.3)
+ table.getCellByName("C3").setValue(-315.7)
+ table.getCellByName("D3").setFormula("sum <A3:C3>")
+
+ table.getCellByName("A4").setValue(121.5)
+ table.getCellByName("B4").setValue(-615.3)
+ table.getCellByName("C4").setValue(415.7)
+ table.getCellByName("D4").setFormula("sum <A4:C4>")
+
+
+ cursor.setPropertyValue( "CharColor", 255 )
+ cursor.setPropertyValue( "CharShadowed", uno.Bool(1) )
+
+ text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )
+ text.insertString( cursor, " This is a colored Text - blue with shadow\n" , 0 )
+ text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )
+
+ textFrame = doc.createInstance( "com.sun.star.text.TextFrame" )
+ textFrame.setSize( Size(15000,400))
+ textFrame.setPropertyValue( "AnchorType" , AS_CHARACTER )
+
+ text.insertTextContent( cursor, textFrame, 0 )
+
+ textInTextFrame = textFrame.getText()
+ cursorInTextFrame = textInTextFrame.createTextCursor()
+ textInTextFrame.insertString( cursorInTextFrame, "The first line in the newly created text frame.", 0 )
+ textInTextFrame.insertString( cursorInTextFrame, "\nWith this second line the height of the rame raises.",0)
+ text.insertControlCharacter( cursor, PARAGRAPH_BREAK, 0 )
+
+ cursor.setPropertyValue( "CharColor", 65536 )
+ cursor.setPropertyValue( "CharShadowed", uno.Bool(0) )
+
+ text.insertString( cursor, " That's all for now !!" , 0 )
+
+g_exportedScripts = createTable,
diff --git a/scripting/inc/makefile.mk b/scripting/inc/makefile.mk
new file mode 100644
index 000000000000..86fcaf1b7fdb
--- /dev/null
+++ b/scripting/inc/makefile.mk
@@ -0,0 +1,51 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.3 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+PRJ=..
+
+PRJNAME=scripting
+TARGET=inc
+
+# --- Settings -----------------------------------------------------
+
+.INCLUDE : settings.mk
+
+# --- Files --------------------------------------------------------
+# --- Targets -------------------------------------------------------
+
+.INCLUDE : target.mk
+
+.IF "$(ENABLE_PCH)"!=""
+ALLTAR : \
+ $(SLO)$/precompiled.pch \
+ $(SLO)$/precompiled_ex.pch
+
+.ENDIF # "$(ENABLE_PCH)"!=""
+
diff --git a/scripting/inc/pch/precompiled_scripting.cxx b/scripting/inc/pch/precompiled_scripting.cxx
new file mode 100644
index 000000000000..44d28c40081d
--- /dev/null
+++ b/scripting/inc/pch/precompiled_scripting.cxx
@@ -0,0 +1,32 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: precompiled_scripting.cxx,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#include "precompiled_scripting.hxx"
+
diff --git a/scripting/inc/pch/precompiled_scripting.hxx b/scripting/inc/pch/precompiled_scripting.hxx
new file mode 100644
index 000000000000..88434e527235
--- /dev/null
+++ b/scripting/inc/pch/precompiled_scripting.hxx
@@ -0,0 +1,35 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: precompiled_scripting.hxx,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): Generated on 2006-09-01 17:49:57.436197
+
+#ifdef PRECOMPILED_HEADERS
+#endif
+
diff --git a/scripting/java/Framework/com/sun/star/script/framework/security/SecurityDialog.java b/scripting/java/Framework/com/sun/star/script/framework/security/SecurityDialog.java
new file mode 100644
index 000000000000..02d91c4aad34
--- /dev/null
+++ b/scripting/java/Framework/com/sun/star/script/framework/security/SecurityDialog.java
@@ -0,0 +1,549 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: SecurityDialog.java,v $
+ * $Revision: 1.13 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.security;
+
+import com.sun.star.awt.ActionEvent;
+import com.sun.star.awt.ItemEvent;
+import com.sun.star.awt.XItemListener;
+import com.sun.star.awt.XButton;
+import com.sun.star.awt.XCheckBox;
+import com.sun.star.awt.XControl;
+import com.sun.star.awt.XControlModel;
+import com.sun.star.awt.XControlContainer;
+import com.sun.star.awt.XDialog;
+import com.sun.star.awt.XToolkit;
+import com.sun.star.awt.XWindow;
+
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.comp.loader.FactoryHelper;
+import com.sun.star.container.XNameContainer;
+import com.sun.star.lang.XComponent;
+import com.sun.star.lang.EventObject;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.XSingleServiceFactory;
+import com.sun.star.lang.XServiceInfo;
+import com.sun.star.lang.XInitialization;
+import com.sun.star.lang.IllegalArgumentException;
+import com.sun.star.lib.uno.helper.WeakBase;
+import com.sun.star.registry.XRegistryKey;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.uno.RuntimeException;
+import com.sun.star.uno.XComponentContext;
+
+import com.sun.star.script.framework.log.LogUtils;
+
+public class SecurityDialog extends WeakBase implements XComponent, XServiceInfo, XDialog,
+XInitialization {
+
+ static final String __serviceName = "com.sun.star.script.framework.security.SecurityDialog";
+
+ private static final String _label1Name = "Label1";
+ private static final String _label1String = "This document contains macros. Do you want to allow these macros to be run?";
+
+ private static final String _label2Name = "Label2";
+ private static final String _label2String = "This document contains macros. According to the security settings, the";
+ private static final String _label3Name = "Label3";
+ private static final String _label3String = "macros in this document should not be run. Do you want to run them";
+ private static final String _label4Name = "Label4";
+ private static final String _label4String = "anyway?";
+
+ private static final String _checkBoxName = "CheckBox";
+ private static final String _checkBoxString = "Add this directory to the list of secure paths: ";
+ private static final String _label5Name = "Label5";
+
+ private static final String _title = "Run Macro";
+ private static final String _runMacro = "Run";
+ private static final String _runButtonName = "Run";
+ private static final String _doNotRunMacro = "Do Not Run";
+ private static final String _doNotRunButtonName = "DoNotRun";
+
+ private static final int dialogX = 100;
+ private static final int dialogY = 100;
+ private static final int dialogW = 235;
+ private static final int dialogH = 47;
+
+ private int cbIncrW = -20;
+ private int cbIncrH = 19;
+
+ private static final int runButtonW = 40;
+ private static final int runButtonH = 13;
+ private static final int doNotRunButtonW = 40;
+ private static final int doNotRunButtonH = 13;
+
+ // label for warning dialog
+ private static final int label1X = 20;
+ private static final int label1Y = 9;
+ private static final int label1W = 210;
+ private static final int label1H = 10;
+
+ // labels for confirmation dialog
+ private static final int label2X = 22;
+ private static final int label2Y = 7;
+ private static final int label2W = 210;
+ private static final int label2H = 8;
+ private static final int label3X = 22;
+ private static final int label3Y = 15;
+ private static final int label3W = 210;
+ private static final int label3H = 8;
+ private static final int label4X = 22;
+ private static final int label4Y = 23;
+ private static final int label4W = 210;
+ private static final int label4H = 8;
+
+ // checkbox for confirmation dialog
+ private static final int checkBoxX = 22;
+ private static final int checkBoxY = 40;
+ private static final int checkBoxW = 210;
+ private static final int checkBoxH = 9;
+ // extra label if path longer than 21 chars
+ private static final int label5X = 22;
+ private static final int label5Y = 48;
+ private static final int label5W = 210;
+ private static final int label5H = 9;
+
+ private boolean checkBoxDialog;
+ private short _checkBoxState = 0;
+ private boolean extraPathLine=false;
+ private String checkBoxPath="";
+ private String checkBoxPath2="";
+ private static final int lineWrapLength = 21;
+ private static final int lineWrapH = 12;
+ private String _pushed = _doNotRunButtonName;
+
+ private XComponentContext _xComponentContext;
+ private XDialog _xDialog;
+
+ public SecurityDialog( XComponentContext xComponentContext )
+ {
+ LogUtils.DEBUG( "SecurityDialog ctor" );
+ _xComponentContext = xComponentContext;
+ }
+
+ public void initialize( Object[] args ) throws RuntimeException
+ {
+ LogUtils.DEBUG( "SecurityDialog init" );
+ // figure out if we need a checkbox
+ if ( args.length == 1 && AnyConverter.isString( args[0] ) )
+ {
+ //check args is a path
+ // set checkBoxPath with the arg
+ LogUtils.DEBUG( "checkbox" );
+ try
+ {
+ checkBoxPath = AnyConverter.toString( args[0] );
+ }
+ catch ( IllegalArgumentException e )
+ {
+ throw new RuntimeException( "SecurityDialog::initialize: " + e.getMessage() );
+ }
+ LogUtils.DEBUG( "path: " + checkBoxPath );
+ checkBoxDialog = true;
+ if( checkBoxPath.length() > lineWrapLength )
+ {
+ extraPathLine = true;
+ cbIncrH += lineWrapH;
+ checkBoxPath2 = checkBoxPath.substring( lineWrapLength );
+ checkBoxPath = checkBoxPath.substring( 0, lineWrapLength );
+ }
+
+ }
+ else
+ {
+ LogUtils.DEBUG( "no checkbox: # of args=" +
+ args.length );
+ cbIncrW = 0;
+ cbIncrH = 0;
+ checkBoxDialog = false;
+ }
+
+ // now try and create the dialog
+ try
+ {
+ _xDialog = createDialog();
+ }
+ catch ( com.sun.star.uno.Exception e )
+ {
+ LogUtils.DEBUG( "Couldn't create dialog" );
+ LogUtils.DEBUG( "uno message: " + e.getMessage());
+ throw new RuntimeException( e.getMessage() );
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG( "Couldn't create dialog" );
+ LogUtils.DEBUG( "message: " + e.getMessage());
+ throw new RuntimeException( e.getMessage() );
+ }
+
+ }
+
+ // static component operations
+ public static XSingleServiceFactory __getServiceFactory( String implName,
+ XMultiServiceFactory multiFactory,
+ XRegistryKey regKey ) {
+ XSingleServiceFactory xSingleServiceFactory = null;
+ if ( implName.equals( SecurityDialog.class.getName() ) ) {
+ xSingleServiceFactory = FactoryHelper.getServiceFactory(
+ SecurityDialog.class, SecurityDialog.__serviceName, multiFactory, regKey );
+ }
+ return xSingleServiceFactory;
+ }
+
+ public static boolean __writeRegistryServiceInfo( XRegistryKey regKey ) {
+ return FactoryHelper.writeRegistryServiceInfo(
+ SecurityDialog.class.getName(), SecurityDialog.__serviceName, regKey );
+ }
+
+ // XServiceInfo
+ public String getImplementationName( ) {
+ return getClass().getName();
+ }
+
+ // XServiceInfo
+ public boolean supportsService( /*IN*/String serviceName ) {
+ if ( serviceName.equals( __serviceName))
+ return true;
+ return false;
+ }
+
+ // XServiceInfo
+ public String[] getSupportedServiceNames( ) {
+ String[] retValue= new String[0];
+ retValue[0] = __serviceName;
+ return retValue;
+ }
+
+
+ /** method for creating a dialog at runtime
+ */
+ private XDialog createDialog() throws com.sun.star.uno.Exception {
+
+ // get the service manager from the component context
+ XMultiComponentFactory xMultiComponentFactory = _xComponentContext.getServiceManager();
+
+ // create the dialog model and set the properties
+ Object dialogModel = xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.awt.UnoControlDialogModel", _xComponentContext );
+ XPropertySet xPSetDialog = ( XPropertySet )UnoRuntime.queryInterface(
+ XPropertySet.class, dialogModel );
+ xPSetDialog.setPropertyValue( "PositionX", new Integer( dialogX) );
+ xPSetDialog.setPropertyValue( "PositionY", new Integer( dialogY));
+ xPSetDialog.setPropertyValue( "Width", new Integer( dialogW+cbIncrW ));
+ xPSetDialog.setPropertyValue( "Height", new Integer( dialogH+cbIncrH ));
+ xPSetDialog.setPropertyValue( "Title", _title );
+
+ // get the service manager from the dialog model
+ XMultiServiceFactory xMultiServiceFactory = ( XMultiServiceFactory )UnoRuntime.queryInterface(
+ XMultiServiceFactory.class, dialogModel );
+
+ // create the Run Macro button model and set the properties
+ Object runButtonModel = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlButtonModel" );
+ XPropertySet xPSetButton = ( XPropertySet )UnoRuntime.queryInterface(
+ XPropertySet.class, runButtonModel );
+ LogUtils.DEBUG("run: x="+(((dialogW+cbIncrW)/2)-runButtonW -1) );
+ LogUtils.DEBUG("run: y="+(dialogH+cbIncrH-runButtonH-1));
+ xPSetButton.setPropertyValue( "PositionX", new Integer( (((dialogW+cbIncrW)/2)-runButtonW -1) ));
+ xPSetButton.setPropertyValue( "PositionY", new Integer( dialogH+cbIncrH-runButtonH-1));
+ xPSetButton.setPropertyValue( "Width", new Integer( runButtonW ));
+ xPSetButton.setPropertyValue( "Height", new Integer( runButtonH ));
+ xPSetButton.setPropertyValue( "Name", _runButtonName );
+ xPSetButton.setPropertyValue( "TabIndex", new Short( (short)1 ) );
+ xPSetButton.setPropertyValue( "Label", _runMacro );
+
+ // create the Dont Run Macro button model and set the properties
+ Object doNotRunButtonModel = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlButtonModel" );
+ xPSetButton = ( XPropertySet )UnoRuntime.queryInterface(
+ XPropertySet.class, doNotRunButtonModel );
+ LogUtils.DEBUG("dontrun: x="+(((dialogW+cbIncrW)/2)-1) );
+ LogUtils.DEBUG("dontrun: y="+(dialogH+cbIncrH-doNotRunButtonH-1 ));
+ xPSetButton.setPropertyValue( "PositionX", new Integer( (((dialogW+cbIncrW)/2) + 1) ));
+ xPSetButton.setPropertyValue( "PositionY", new Integer( (dialogH+cbIncrH-doNotRunButtonH-1 ) ));
+ xPSetButton.setPropertyValue( "Width", new Integer( doNotRunButtonW ));
+ xPSetButton.setPropertyValue( "Height", new Integer( doNotRunButtonH ));
+ xPSetButton.setPropertyValue( "Name", _doNotRunButtonName );
+ xPSetButton.setPropertyValue( "TabIndex", new Short( (short)0 ) );
+ xPSetButton.setPropertyValue( "Label", _doNotRunMacro );
+
+ // insert the control models into the dialog model
+ XNameContainer xNameCont = ( XNameContainer )UnoRuntime.queryInterface(
+ XNameContainer.class, dialogModel );
+ xNameCont.insertByName( _runButtonName, runButtonModel );
+ xNameCont.insertByName( _doNotRunButtonName, doNotRunButtonModel );
+
+ if ( checkBoxDialog )
+ {
+ LogUtils.DEBUG("creating label & checkbox");
+ // create the label model and set the properties
+ Object label2Model = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlFixedTextModel" );
+ XPropertySet xPSetLabel = ( XPropertySet )UnoRuntime.queryInterface(
+ XPropertySet.class, label2Model );
+ xPSetLabel.setPropertyValue( "PositionX", new Integer( label2X ));
+ xPSetLabel.setPropertyValue( "PositionY", new Integer( label2Y ));
+ xPSetLabel.setPropertyValue( "Width", new Integer( label2W ));
+ xPSetLabel.setPropertyValue( "Height", new Integer( label2H ));
+ xPSetLabel.setPropertyValue( "Name", _label2Name );
+ xPSetLabel.setPropertyValue( "TabIndex", new Short( (short)1 ) );
+ xPSetLabel.setPropertyValue( "Label", _label2String );
+
+ // create the label model and set the properties
+ Object label3Model = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlFixedTextModel" );
+ XPropertySet xPSetLabel3 = ( XPropertySet )UnoRuntime.queryInterface(
+ XPropertySet.class, label3Model );
+ xPSetLabel3.setPropertyValue( "PositionX", new Integer( label3X ));
+ xPSetLabel3.setPropertyValue( "PositionY", new Integer( label3Y ));
+ xPSetLabel3.setPropertyValue( "Width", new Integer( label3W ));
+ xPSetLabel3.setPropertyValue( "Height", new Integer( label3H ));
+ xPSetLabel3.setPropertyValue( "Name", _label3Name );
+ xPSetLabel3.setPropertyValue( "TabIndex", new Short( (short)1 ) );
+ xPSetLabel3.setPropertyValue( "Label", _label3String );
+
+ // create the label model and set the properties
+ Object label4Model = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlFixedTextModel" );
+ XPropertySet xPSetLabel4 = ( XPropertySet )UnoRuntime.queryInterface(
+ XPropertySet.class, label4Model );
+ xPSetLabel4.setPropertyValue( "PositionX", new Integer( label4X ));
+ xPSetLabel4.setPropertyValue( "PositionY", new Integer( label4Y ));
+ xPSetLabel4.setPropertyValue( "Width", new Integer( label4W ));
+ xPSetLabel4.setPropertyValue( "Height", new Integer( label4H ));
+ xPSetLabel4.setPropertyValue( "Name", _label4Name );
+ xPSetLabel4.setPropertyValue( "TabIndex", new Short( (short)1 ) );
+ xPSetLabel4.setPropertyValue( "Label", _label4String );
+
+ // create the checkbox model and set the properties
+ Object checkBoxModel = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlCheckBoxModel" );
+ XPropertySet xPSetCheckBox = ( XPropertySet )UnoRuntime.queryInterface(
+ XPropertySet.class, checkBoxModel );
+ xPSetCheckBox.setPropertyValue( "PositionX", new Integer( checkBoxX ));
+ xPSetCheckBox.setPropertyValue( "PositionY", new Integer( checkBoxY ));
+ xPSetCheckBox.setPropertyValue( "Width", new Integer( checkBoxW ));
+ xPSetCheckBox.setPropertyValue( "Height", new Integer( checkBoxH ));
+ xPSetCheckBox.setPropertyValue( "State", new Short((short)0) );
+ xPSetCheckBox.setPropertyValue( "Name", _checkBoxName );
+ xPSetCheckBox.setPropertyValue( "TabIndex", new Short( (short)1 ) );
+ xPSetCheckBox.setPropertyValue( "Label", new String(_checkBoxString +checkBoxPath) );
+
+ // insert the control models into the dialog model
+ xNameCont.insertByName( _label2Name, label2Model );
+ xNameCont.insertByName( _label3Name, label3Model );
+ xNameCont.insertByName( _label4Name, label4Model );
+ xNameCont.insertByName( _checkBoxName, checkBoxModel );
+
+ if ( extraPathLine == true )
+ {
+ // create the label model and set the properties
+ Object label5Model = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlFixedTextModel" );
+ XPropertySet xPSetLabel5 = ( XPropertySet )UnoRuntime.queryInterface(
+ XPropertySet.class, label5Model );
+ xPSetLabel5.setPropertyValue( "PositionX", new Integer( label5X ));
+ xPSetLabel5.setPropertyValue( "PositionY", new Integer( label5Y ));
+ xPSetLabel5.setPropertyValue( "Width", new Integer( label5W ));
+ xPSetLabel5.setPropertyValue( "Height", new Integer( label5H ));
+ xPSetLabel5.setPropertyValue( "Name", _label5Name );
+ xPSetLabel5.setPropertyValue( "TabIndex", new Short( (short)1 ) );
+ xPSetLabel5.setPropertyValue( "Label", checkBoxPath2 );
+ xNameCont.insertByName( _label5Name, label5Model );
+ }
+ }
+ else
+ {
+ // create the label model and set the properties
+ Object labelModel = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlFixedTextModel" );
+ XPropertySet xPSetLabel = ( XPropertySet )UnoRuntime.queryInterface(
+ XPropertySet.class, labelModel );
+ xPSetLabel.setPropertyValue( "PositionX", new Integer( label1X ));
+ xPSetLabel.setPropertyValue( "PositionY", new Integer( label1Y ));
+ xPSetLabel.setPropertyValue( "Width", new Integer( label1W ));
+ xPSetLabel.setPropertyValue( "Height", new Integer( label1H ));
+ xPSetLabel.setPropertyValue( "Name", _label1Name );
+ xPSetLabel.setPropertyValue( "TabIndex", new Short( (short)1 ) );
+ xPSetLabel.setPropertyValue( "Label", _label1String );
+
+ // insert the control models into the dialog model
+ xNameCont.insertByName( _label1Name, labelModel );
+ }
+
+ // create the dialog control and set the model
+ Object dialog = xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.awt.UnoControlDialog", _xComponentContext );
+ XControl xControl = ( XControl )UnoRuntime.queryInterface(
+ XControl.class, dialog );
+ XControlModel xControlModel = ( XControlModel )UnoRuntime.queryInterface(
+ XControlModel.class, dialogModel );
+ xControl.setModel( xControlModel );
+
+ // add an action listener to the button control
+ XControlContainer xControlCont = ( XControlContainer )UnoRuntime.queryInterface(
+ XControlContainer.class, dialog );
+
+ // Add to yes button
+ Object objectButton = xControlCont.getControl( _runButtonName );
+ XButton xButton = ( XButton )UnoRuntime.queryInterface(
+ XButton.class, objectButton );
+ xButton.addActionListener( new ActionListenerImpl( xControlCont, _runButtonName ) );
+
+ // add to no button
+ objectButton = xControlCont.getControl( _doNotRunButtonName );
+ xButton = ( XButton )UnoRuntime.queryInterface(
+ XButton.class, objectButton );
+ xButton.addActionListener( new ActionListenerImpl( xControlCont, _doNotRunButtonName ) );
+
+ if ( checkBoxDialog )
+ {
+ // add to checkbox
+ Object objectCheckBox = xControlCont.getControl( _checkBoxName );
+ XCheckBox xCheckBox = ( XCheckBox )UnoRuntime.queryInterface(
+ XCheckBox.class, objectCheckBox );
+ xCheckBox.addItemListener((XItemListener) new ItemListenerImpl( xControlCont ) );
+ }
+
+ // create a peer
+ Object toolkit = xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.awt.ExtToolkit", _xComponentContext );
+ XToolkit xToolkit = ( XToolkit )UnoRuntime.queryInterface(
+ XToolkit.class, toolkit );
+ XWindow xWindow = ( XWindow )UnoRuntime.queryInterface(
+ XWindow.class, xControl );
+ xWindow.setVisible( false );
+ xControl.createPeer( xToolkit, null );
+
+ // return the dialog
+ XDialog xDialog = ( XDialog )UnoRuntime.queryInterface(
+ XDialog.class, dialog );
+ return xDialog;
+ }
+ public short execute()
+ {
+
+ short result = 0;
+ _pushed = _doNotRunButtonName;
+ LogUtils.DEBUG("*DF* Before execute " );
+ _xDialog.execute();
+ LogUtils.DEBUG("*DF* After execute " );
+
+ if ( _pushed.equals( _runButtonName ) )
+ {
+ result += 1;
+ }
+ if ( _checkBoxState == 1 )
+ {
+ result +=2;
+ }
+ return result;
+ }
+
+ public void endExecute()
+ {
+ _xDialog.endExecute();
+ }
+
+ public String getTitle()
+ {
+ return _xDialog.getTitle();
+ }
+
+ public void setTitle( String Title )
+ {
+ _xDialog.setTitle( Title );
+ }
+
+ public void dispose ()
+ {
+ XComponent xComponent = ( XComponent )UnoRuntime.queryInterface(
+ XComponent.class, _xDialog );
+ xComponent.dispose();
+ }
+
+ public void addEventListener ( com.sun.star.lang.XEventListener xListener )
+ {
+ XComponent xComponent = ( XComponent )UnoRuntime.queryInterface(
+ XComponent.class, _xDialog );
+ xComponent.addEventListener( xListener );
+ }
+
+
+ public void removeEventListener ( com.sun.star.lang.XEventListener aListener )
+ {
+ XComponent xComponent = ( XComponent )UnoRuntime.queryInterface(
+ XComponent.class, _xDialog );
+ xComponent.removeEventListener( aListener );
+ }
+
+ public class ActionListenerImpl implements com.sun.star.awt.XActionListener {
+ private XControlContainer _xControlCont;
+ private String _buttonName;
+ public ActionListenerImpl( XControlContainer xControlCont, String buttonName ) {
+ _xControlCont = xControlCont;
+ _buttonName = buttonName;
+ }
+
+ // XEventListener
+ public void disposing( EventObject eventObject ) {
+ _xControlCont = null;
+ }
+
+ // XActionListener
+ public void actionPerformed( ActionEvent actionEvent ) {
+ _pushed = _buttonName;
+ LogUtils.DEBUG("** Button pushed ->" + _pushed );
+
+ _xDialog.endExecute();
+ }
+ }
+
+ public class ItemListenerImpl implements com.sun.star.awt.XItemListener {
+ private XCheckBox _xCheckBox;
+ public ItemListenerImpl( XControlContainer xControlCont ) {
+ Object objectCheckBox = xControlCont.getControl( _checkBoxName );
+ _xCheckBox = ( XCheckBox )UnoRuntime.queryInterface(
+ XCheckBox.class, objectCheckBox );
+ }
+
+ // XEventListener
+ public void disposing( EventObject eventObject ) {
+ _xCheckBox = null;
+ }
+
+ // XAdjustmentListener
+ public void itemStateChanged( ItemEvent itemEvent ) {
+ _checkBoxState = _xCheckBox.getState();
+ LogUtils.DEBUG("** checkbox state ->" + _checkBoxState );
+ }
+ }
+}
diff --git a/scripting/java/build.env b/scripting/java/build.env
new file mode 100644
index 000000000000..5b055e0b8452
--- /dev/null
+++ b/scripting/java/build.env
@@ -0,0 +1,3 @@
+jedit.install.dir=/scde/soperm/projects/scripting/build-dependencies
+install.dir=/scde/soperm/projects/scripting/build-dependencies
+netbeans.home=/scde/soperm/projects/scripting/build-dependencies
diff --git a/scripting/java/build.xml b/scripting/java/build.xml
new file mode 100755
index 000000000000..02975b2d4e7f
--- /dev/null
+++ b/scripting/java/build.xml
@@ -0,0 +1,289 @@
+<!--
+
+ DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+
+ Copyright 2008 by Sun Microsystems, Inc.
+
+ OpenOffice.org - a multi-platform office productivity suite
+
+ $RCSfile: build.xml,v $
+
+ $Revision: 1.36.20.1 $
+
+ This file is part of OpenOffice.org.
+
+ OpenOffice.org is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License version 3
+ only, as published by the Free Software Foundation.
+
+ OpenOffice.org is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License version 3 for more details
+ (a copy is included in the LICENSE file that accompanied this code).
+
+ You should have received a copy of the GNU Lesser General Public License
+ version 3 along with OpenOffice.org. If not, see
+ <http://www.openoffice.org/license.html>
+ for a copy of the LGPLv3 License.
+
+-->
+<project name="Scipting Framework" default="all" basedir=".">
+
+ <!-- =================== Environmental Properties ======================= -->
+
+ <property name="prj" value=".."/>
+ <property name="build.compiler" value="classic"/>
+ <property name="optimize" value="off"/>
+ <property name="debug" value="on"/>
+ <property name="jardir" value="${out}/class"/>
+ <property name="bindir" value="${out}/bin"/>
+ <property name="idesupport.dir" value="org/openoffice/idesupport"/>
+ <property name="netbeans.dir" value="org/openoffice/netbeans/modules/office"/>
+ <property name="framework.dir" value="Framework/com/sun/star/script/framework/security"/>
+
+ <!-- Change this property if you are building NetBeans editor support jar.
+ Not needed in default build -->
+ <property name="netbeans.install.path" value="/export/home/netbeans"/>
+
+ <property environment="env"/>
+ <property name="env.BSH_JAR" value="${solar.jar}/bsh.jar"/>
+
+ <!-- ==================== classpath setting ============================ -->
+ <path id="idlclasspath">
+ <pathelement location="${solar.jar}/jurt.jar"/>
+ <pathelement location="${solar.jar}/unoil.jar"/>
+ <pathelement location="${solar.jar}/juh.jar"/>
+ <pathelement location="${solar.jar}/java_uno.jar"/>
+ <pathelement location="${solar.jar}/ridl.jar"/>
+ <pathelement location="${env.BSH_JAR}"/>
+ <pathelement location="${solar.jar}/js.jar"/>
+ <pathelement location="${jardir}"/>
+ </path>
+
+ <path id="idesupport.class.path">
+ <pathelement path="${jardir}"/>
+ </path>
+
+ <path id="openide.class.path">
+ <pathelement path="${jardir}"/>
+ <pathelement path="${solar.jar}/openide.jar"/>
+ </path>
+
+ <path id="netbeans.editor.support.classpath">
+ <pathelement path="${jardir}"/>
+ <pathelement path="${netbeans.install.path}/modules/ext/nb-editor.jar"/>
+ </path>
+
+ <condition property="boot_refID" value="macPath" else="nonMacPath">
+ <and>
+ <os family="mac"/>
+ <os family="unix"/>
+ </and>
+ </condition>
+ <path id="macPath" location="${java.home}/../Classes/classes.jar"/>
+ <!-- rhino.jar from OpenJDK breaks build -->
+ <path id="nonMacPath">
+ <fileset dir="${java.home}/">
+ <include name="jre/lib/*.jar"/>
+ <include name="lib/*.jar"/>
+ <exclude name="jre/lib/rhino.jar"/>
+ <exclude name="lib/rhino.jar"/>
+ </fileset>
+ </path>
+ <path id="my.bootstrap.classpath" refID="${boot_refID}"/>
+
+ <!-- ===================== Prepare Directories ========================= -->
+ <target name="prepare">
+ <mkdir dir="${jardir}"/>
+ </target>
+
+ <!-- ======================== Compile Classes ========================== -->
+ <target name="compile" depends="prepare">
+ <javac srcdir="com" destdir="${jardir}"
+ includes="**/*.java" classpathref="idlclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="off">
+ <compilerarg value="-Xbootclasspath:${toString:my.bootstrap.classpath}"/>
+ </javac>
+ <javac srcdir="Framework/" destdir="${jardir}"
+ includes="**/*.java" classpathref="idlclasspath" debug="${debug}"
+ optimize="${optimize}" deprecation="off">
+ <compilerarg value="-Xbootclasspath:${toString:my.bootstrap.classpath}"/>
+ </javac>
+ </target>
+
+ <target name="idesupport.compile" depends="compile, prepare">
+ <javac srcdir="." destdir="${jardir}"
+ debug="${debug}" deprecation="on">
+ <classpath refid="idesupport.class.path"/>
+ <exclude name="${idesupport.dir}/**/.*/*"/>
+ <exclude name="${idesupport.dir}/localoffice/**/*"/>
+ <exclude name="${idesupport.dir}/LocalOffice.java"/>
+ <include name="${idesupport.dir}/*.java"/>
+ <include name="${idesupport.dir}/*/*.java"/>
+ </javac>
+ </target>
+
+ <target name="localoffice.compile" depends="prepare">
+ <javac srcdir="." destdir="${jardir}"
+ debug="${debug}" deprecation="on">
+ <classpath refid="idlclasspath"/>
+ <exclude name="${idesupport.dir}/localoffice/.*/*"/>
+ <include name="${idesupport.dir}/localoffice/*.java"/>
+ </javac>
+ </target>
+
+ <target name="netbeans.compile" depends="idesupport.compile, prepare">
+ <javac srcdir="." destdir="${jardir}"
+ debug="${debug}" deprecation="on">
+ <classpath refid="openide.class.path"/>
+ <exclude name="${netbeans.dir}/**/.*/*"/>
+ <include name="${netbeans.dir}/**/*.java"/>
+ </javac>
+ </target>
+
+ <target name="netbeans.editor.support" depends="prepare">
+ <javac srcdir="." destdir="${jardir}"
+ debug="${debug}" deprecation="on">
+ <classpath refid="netbeans.editor.support.classpath"/>
+ <include name="org/openoffice/netbeans/editor/*.java"/>
+ </javac>
+ <jar jarfile="${jardir}/nb-editorsupport.jar">
+ <fileset dir="${jardir}">
+ <include name="org/openoffice/netbeans/editor/*.class"/>
+ </fileset>
+ <fileset dir=".">
+ <include name="org/openoffice/netbeans/editor/OOo.jcs"/>
+ <include name="org/openoffice/netbeans/editor/OOo.jcb"/>
+ </fileset>
+ </jar>
+ </target>
+
+ <!-- ===================== jar ========================= -->
+ <target name="jar" depends="compile">
+ <jar jarfile="${jardir}/ScriptProviderForJava.jar"
+ basedir="${jardir}">
+ <manifest>
+ <attribute name="Built-By" value="Sun Microsystems"/>
+ <attribute name="RegistrationClassName"
+ value="com.sun.star.script.framework.provider.java.ScriptProviderForJava"/>
+ <attribute name="Class-Path" value="ScriptFramework.jar"/>
+ <attribute name="UNO-Type-Path" value=""/>
+ </manifest>
+ <include name="**/provider/java/*.class"/>
+ </jar>
+
+ <jar jarfile="${jardir}/ScriptProviderForBeanShell.jar"
+ basedir="${jardir}">
+ <manifest>
+ <attribute name="Built-By" value="Sun Microsystems"/>
+ <attribute name="RegistrationClassName"
+ value="com.sun.star.script.framework.provider.beanshell.ScriptProviderForBeanShell"/>
+ <attribute name="Class-Path" value="ScriptFramework.jar bsh.jar"/>
+ <attribute name="UNO-Type-Path" value=""/>
+ </manifest>
+ <include name="**/provider/beanshell/*.class"/>
+ <fileset dir=".">
+ <include name="**/provider/beanshell/*.bsh"/>
+ </fileset>
+ </jar>
+
+ <jar jarfile="${jardir}/ScriptProviderForJavaScript.jar"
+ basedir="${jardir}">
+ <manifest>
+ <attribute name="Built-By" value="Sun Microsystems"/>
+ <attribute name="RegistrationClassName"
+ value="com.sun.star.script.framework.provider.javascript.ScriptProviderForJavaScript"/>
+ <attribute name="Class-Path" value="ScriptFramework.jar js.jar"/>
+ <attribute name="UNO-Type-Path" value=""/>
+ </manifest>
+ <include name="**/provider/javascript/*.class"/>
+ <fileset dir=".">
+ <include name="**/provider/javascript/*.js"/>
+ </fileset>
+ </jar>
+
+ <jar jarfile="${jardir}/ScriptFramework.jar"
+ basedir="${jardir}">
+ <manifest>
+ <attribute name="Built-By" value="Sun Microsystems"/>
+ <attribute name="RegistrationClassName"
+ value="com.sun.star.script.framework.security.SecurityDialog"/>
+ <attribute name="UNO-Type-Path" value=""/>
+ </manifest>
+ <include name="**/security/*"/>
+ <include name="**/log/*.class"/>
+ <include name="**/provider/*.class"/>
+ <include name="**/browse/*.class"/>
+ <include name="**/container/*.class"/>
+ <include name="**/io/*.class"/>
+ </jar>
+
+ </target>
+
+ <target name="idesupport.jar" depends="idesupport.compile">
+ <jar jarfile="${jardir}/idesupport.jar">
+ <fileset dir="${jardir}">
+ <include name="${idesupport.dir}/**/*.class"/>
+ <include name="CommandLineTools*"/>
+ <exclude name="${idesupport.dir}/localoffice/*.class"/>
+ </fileset>
+ <fileset dir=".">
+ <include name="${idesupport.dir}/ui/add.gif"/>
+ </fileset>
+ </jar>
+ </target>
+
+ <target name="localoffice.jar" depends="localoffice.compile">
+ <unjar
+ src="${solar.jar}/unoil.jar"
+ dest="${jardir}"/>
+ <jar jarfile="${jardir}/localoffice.jar">
+ <fileset dir="${jardir}">
+ <include name="${idesupport.dir}/localoffice/*.class"/>
+ <include name="drafts/com/sun/star/script/framework/storage/*.class"/>
+ </fileset>
+ </jar>
+ </target>
+
+ <target name="netbeans.jar" depends="netbeans.compile">
+ <jar jarfile="${jardir}/office.jar" manifest="manifest.mf">
+ <fileset dir="${jardir}">
+ <include name="${netbeans.dir}/**/*.class"/>
+ <exclude name="${netbeans.dir}/**/ParcelDescriptorChildren.class"/>
+ <exclude name="${netbeans.dir}/**/ScriptNode.class"/>
+ <include name="${idesupport.dir}/**/*.class"/>
+ <include name="CommandLineTools*"/>
+ </fileset>
+ <fileset dir=".">
+ <include name="${idesupport.dir}/ui/add.gif"/>
+ <include name="${netbeans.dir}/resources/*"/>
+ <include name="${netbeans.dir}/resources/templates/*"/>
+ <include name="${netbeans.dir}/**/Bundle*"/>
+ </fileset>
+ </jar>
+ </target>
+
+ <!-- Uncomment this target when building within NetBeans to reinstall the
+ module.
+ <target name="netbeans.install" depends="netbeans.package">
+ <copy file="${jardir}/localoffice.jar"
+ tofile="${netbeans.home}/modules/ext/localoffice.jar"/>
+ <nbinstaller action="reinstall" module="${jardir}/office.jar"/>
+ </target>
+ -->
+
+ <!-- ====================== Clean Generated Files ===================== -->
+ <target name="clean">
+ <delete file="${jardir}/ScriptProviderForJava.jar"/>
+ <delete file="${jardir}/ScriptProviderForJavaScript.jar"/>
+ <delete file="${jardir}/ScriptProviderForBeanShell.jar"/>
+ <delete file="${jardir}/ScriptFramework.jar"/>
+ <delete file="${jardir}/office.jar"/>
+ <delete file="${jardir}/localoffice.jar"/>
+ <delete file="${jardir}/idesupport.jar"/>
+ </target>
+
+ <!-- ========================= All In One Build ======================= -->
+ <target name="all" depends="jar"/>
+</project>
diff --git a/scripting/java/com/sun/star/script/framework/browse/DialogFactory.java b/scripting/java/com/sun/star/script/framework/browse/DialogFactory.java
new file mode 100644
index 000000000000..bee77e81caf1
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/browse/DialogFactory.java
@@ -0,0 +1,426 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: DialogFactory.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.browse;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XComponentContext;
+
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.EventObject;
+
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.container.XNameContainer;
+
+import com.sun.star.awt.*;
+
+
+public class DialogFactory
+{
+ private static DialogFactory factory;
+ private XComponentContext xComponentContext;
+
+ // singleton
+ private DialogFactory(XComponentContext xComponentContext)
+ {
+ this.xComponentContext = xComponentContext;
+ factory = this;
+ }
+
+ public static void createDialogFactory(XComponentContext xComponentContext)
+ {
+ if (factory == null)
+ {
+ synchronized(DialogFactory.class)
+ {
+ if (factory == null)
+ {
+ factory = new DialogFactory(xComponentContext);
+ }
+ }
+ }
+ }
+
+ public static DialogFactory getDialogFactory()
+ throws java.lang.Exception
+ {
+ if (factory == null)
+ {
+ throw new java.lang.Exception("DialogFactory not initialized");
+ }
+ return factory;
+ }
+
+ public boolean showConfirmDialog(String title, String prompt)
+ {
+ final XDialog xDialog;
+ try
+ {
+ xDialog = createConfirmDialog(title, prompt);
+ }
+ catch (com.sun.star.uno.Exception e)
+ {
+ return false;
+ }
+
+ // add an action listener to the button controls
+ XControlContainer controls = (XControlContainer)
+ UnoRuntime.queryInterface(XControlContainer.class, xDialog);
+
+ XButton okButton = (XButton) UnoRuntime.queryInterface(
+ XButton.class, controls.getControl("Ok"));
+ okButton.setActionCommand("Ok");
+
+ XButton cancelButton = (XButton) UnoRuntime.queryInterface(
+ XButton.class, controls.getControl("Cancel"));
+ cancelButton.setActionCommand("Cancel");
+
+ final ResultHolder resultHolder = new ResultHolder();
+
+ com.sun.star.awt.XActionListener listener =
+ new com.sun.star.awt.XActionListener()
+ {
+ public void actionPerformed(com.sun.star.awt.ActionEvent e) {
+ if (e.ActionCommand.equals("Cancel"))
+ {
+ resultHolder.setResult(Boolean.FALSE);
+ xDialog.endExecute();
+ }
+ else
+ {
+ resultHolder.setResult(Boolean.TRUE);
+ xDialog.endExecute();
+ }
+ }
+
+ public void disposing(EventObject o) {
+ // does nothing
+ }
+ };
+
+ okButton.addActionListener(listener);
+ cancelButton.addActionListener(listener);
+
+ xDialog.execute();
+
+ Boolean result = (Boolean)resultHolder.getResult();
+
+ return result == null ? false : result.booleanValue();
+ }
+
+ public String showInputDialog(String title, String prompt)
+ {
+ final XDialog xDialog;
+ try
+ {
+ xDialog = createInputDialog(title, prompt);
+ }
+ catch (com.sun.star.uno.Exception e)
+ {
+ return null;
+ }
+
+ // add an action listener to the button controls
+ XControlContainer controls = (XControlContainer)
+ UnoRuntime.queryInterface(XControlContainer.class, xDialog);
+
+ XButton okButton = (XButton) UnoRuntime.queryInterface(
+ XButton.class, controls.getControl("Ok"));
+ okButton.setActionCommand("Ok");
+
+ XButton cancelButton = (XButton) UnoRuntime.queryInterface(
+ XButton.class, controls.getControl("Cancel"));
+ cancelButton.setActionCommand("Cancel");
+
+ final XTextComponent textField = (XTextComponent)
+ UnoRuntime.queryInterface(
+ XTextComponent.class, controls.getControl("NameField"));
+
+ final ResultHolder resultHolder = new ResultHolder();
+
+ com.sun.star.awt.XActionListener listener =
+ new com.sun.star.awt.XActionListener()
+ {
+ public void actionPerformed(com.sun.star.awt.ActionEvent e) {
+ if (e.ActionCommand.equals("Cancel"))
+ {
+ resultHolder.setResult(null);
+ xDialog.endExecute();
+ }
+ else
+ {
+ resultHolder.setResult(textField.getText());
+ xDialog.endExecute();
+ }
+ }
+
+ public void disposing(EventObject o) {
+ // does nothing
+ }
+ };
+
+ okButton.addActionListener(listener);
+ cancelButton.addActionListener(listener);
+
+ xDialog.execute();
+
+ return (String)resultHolder.getResult();
+ }
+
+ private XDialog createConfirmDialog(String title, String prompt)
+ throws com.sun.star.uno.Exception
+ {
+ if (title == null || title.equals(""))
+ {
+ title = "Scripting Framework";
+ }
+
+ if (prompt == null || prompt.equals(""))
+ {
+ prompt = "Enter name";
+ }
+
+ // get the service manager from the component context
+ XMultiComponentFactory xMultiComponentFactory =
+ xComponentContext.getServiceManager();
+
+ // create the dialog model and set the properties
+ Object dialogModel = xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.awt.UnoControlDialogModel", xComponentContext);
+
+ XPropertySet props = (XPropertySet) UnoRuntime.queryInterface(
+ XPropertySet.class, dialogModel);
+
+ props.setPropertyValue("Title", title);
+ setDimensions(dialogModel, 100, 100, 157, 37);
+
+ // get the service manager from the dialog model
+ XMultiServiceFactory xMultiServiceFactory =
+ (XMultiServiceFactory) UnoRuntime.queryInterface(
+ XMultiServiceFactory.class, dialogModel);
+
+ // create the label model and set the properties
+ Object label = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlFixedTextModel");
+
+ setDimensions(label, 15, 5, 134, 12);
+
+ XPropertySet labelProps = (XPropertySet) UnoRuntime.queryInterface(
+ XPropertySet.class, label);
+ labelProps.setPropertyValue("Name", "PromptLabel");
+ labelProps.setPropertyValue("Label", prompt);
+
+ // create the Run Macro button model and set the properties
+ Object okButtonModel = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlButtonModel");
+
+ setDimensions(okButtonModel, 40, 18, 38, 15);
+
+ XPropertySet buttonProps = (XPropertySet) UnoRuntime.queryInterface(
+ XPropertySet.class, okButtonModel);
+ buttonProps.setPropertyValue("Name", "Ok");
+ buttonProps.setPropertyValue("Label", "Ok");
+
+ // create the Dont Run Macro button model and set the properties
+ Object cancelButtonModel = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlButtonModel");
+
+ setDimensions(cancelButtonModel, 83, 18, 38, 15);
+
+ buttonProps = (XPropertySet) UnoRuntime.queryInterface(
+ XPropertySet.class, cancelButtonModel);
+ buttonProps.setPropertyValue("Name", "Cancel");
+ buttonProps.setPropertyValue("Label", "Cancel");
+
+ // insert the control models into the dialog model
+ XNameContainer xNameCont = (XNameContainer) UnoRuntime.queryInterface(
+ XNameContainer.class, dialogModel);
+
+ xNameCont.insertByName("PromptLabel", label);
+ xNameCont.insertByName("Ok", okButtonModel);
+ xNameCont.insertByName("Cancel", cancelButtonModel);
+
+ // create the dialog control and set the model
+ Object dialog = xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.awt.UnoControlDialog", xComponentContext);
+ XControl xControl = (XControl) UnoRuntime.queryInterface(
+ XControl.class, dialog);
+
+ XControlModel xControlModel = (XControlModel)
+ UnoRuntime.queryInterface(XControlModel.class, dialogModel);
+ xControl.setModel(xControlModel);
+
+ // create a peer
+ Object toolkit = xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.awt.ExtToolkit", xComponentContext);
+ XToolkit xToolkit = (XToolkit) UnoRuntime.queryInterface(
+ XToolkit.class, toolkit);
+ XWindow xWindow = (XWindow) UnoRuntime.queryInterface(
+ XWindow.class, xControl);
+ xWindow.setVisible(false);
+ xControl.createPeer(xToolkit, null);
+
+ return (XDialog) UnoRuntime.queryInterface(XDialog.class, dialog);
+ }
+
+ private void setDimensions(Object o, int x, int y, int width, int height)
+ throws com.sun.star.uno.Exception
+ {
+ XPropertySet props = (XPropertySet)
+ UnoRuntime.queryInterface(XPropertySet.class, o);
+
+ props.setPropertyValue("PositionX", new Integer(x));
+ props.setPropertyValue("PositionY", new Integer(y));
+ props.setPropertyValue("Height", new Integer(height));
+ props.setPropertyValue("Width", new Integer(width));
+ }
+
+ private XDialog createInputDialog(String title, String prompt)
+ throws com.sun.star.uno.Exception
+ {
+ if (title == null || title.equals(""))
+ {
+ title = "Scripting Framework";
+ }
+
+ if (prompt == null || prompt.equals(""))
+ {
+ prompt = "Enter name";
+ }
+
+ // get the service manager from the component context
+ XMultiComponentFactory xMultiComponentFactory =
+ xComponentContext.getServiceManager();
+
+ // create the dialog model and set the properties
+ Object dialogModel = xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.awt.UnoControlDialogModel", xComponentContext);
+
+ setDimensions(dialogModel, 100, 100, 157, 58);
+
+ XPropertySet props = (XPropertySet) UnoRuntime.queryInterface(
+ XPropertySet.class, dialogModel);
+ props.setPropertyValue("Title", title);
+
+ // get the service manager from the dialog model
+ XMultiServiceFactory xMultiServiceFactory =
+ (XMultiServiceFactory) UnoRuntime.queryInterface(
+ XMultiServiceFactory.class, dialogModel);
+
+ // create the label model and set the properties
+ Object label = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlFixedTextModel");
+
+ setDimensions(label, 15, 5, 134, 12);
+
+ XPropertySet labelProps = (XPropertySet) UnoRuntime.queryInterface(
+ XPropertySet.class, label);
+ labelProps.setPropertyValue("Name", "PromptLabel");
+ labelProps.setPropertyValue("Label", prompt);
+
+ // create the text field
+ Object edit = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlEditModel");
+
+ setDimensions(edit, 15, 18, 134, 12);
+
+ XPropertySet editProps = (XPropertySet) UnoRuntime.queryInterface(
+ XPropertySet.class, edit);
+ editProps.setPropertyValue("Name", "NameField");
+
+ // create the OK button
+ Object okButtonModel = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlButtonModel");
+
+ setDimensions(okButtonModel, 40, 39, 38, 15);
+
+ XPropertySet buttonProps = (XPropertySet) UnoRuntime.queryInterface(
+ XPropertySet.class, okButtonModel);
+ buttonProps.setPropertyValue("Name", "Ok");
+ buttonProps.setPropertyValue("Label", "Ok");
+
+ // create the Cancel button
+ Object cancelButtonModel = xMultiServiceFactory.createInstance(
+ "com.sun.star.awt.UnoControlButtonModel");
+
+ setDimensions(cancelButtonModel, 83, 39, 38, 15);
+
+ buttonProps = (XPropertySet) UnoRuntime.queryInterface(
+ XPropertySet.class, cancelButtonModel);
+ buttonProps.setPropertyValue("Name", "Cancel");
+ buttonProps.setPropertyValue("Label", "Cancel");
+
+ // insert the control models into the dialog model
+ XNameContainer xNameCont = (XNameContainer)
+ UnoRuntime.queryInterface(XNameContainer.class, dialogModel);
+
+ xNameCont.insertByName("PromptLabel", label);
+ xNameCont.insertByName("NameField", edit);
+ xNameCont.insertByName("Ok", okButtonModel);
+ xNameCont.insertByName("Cancel", cancelButtonModel);
+
+ // create the dialog control and set the model
+ Object dialog = xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.awt.UnoControlDialog", xComponentContext);
+ XControl xControl = (XControl) UnoRuntime.queryInterface(
+ XControl.class, dialog);
+
+ XControlModel xControlModel = (XControlModel)
+ UnoRuntime.queryInterface(XControlModel.class, dialogModel);
+ xControl.setModel(xControlModel);
+
+ // create a peer
+ Object toolkit = xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.awt.ExtToolkit", xComponentContext);
+ XToolkit xToolkit = (XToolkit) UnoRuntime.queryInterface(
+ XToolkit.class, toolkit);
+ XWindow xWindow = (XWindow) UnoRuntime.queryInterface(
+ XWindow.class, xControl);
+ xWindow.setVisible(false);
+ xControl.createPeer(xToolkit, null);
+
+ return (XDialog) UnoRuntime.queryInterface(XDialog.class, dialog);
+ }
+
+ private static class ResultHolder {
+ private Object result = null;
+
+ public Object getResult()
+ {
+ return result;
+ }
+
+ public void setResult(Object result)
+ {
+ this.result = result;
+ }
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/browse/ParcelBrowseNode.java b/scripting/java/com/sun/star/script/framework/browse/ParcelBrowseNode.java
new file mode 100644
index 000000000000..15e8170af63c
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/browse/ParcelBrowseNode.java
@@ -0,0 +1,379 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelBrowseNode.java,v $
+ * $Revision: 1.11 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.browse;
+
+import com.sun.star.beans.XIntrospectionAccess;
+
+import com.sun.star.lib.uno.helper.PropertySet;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.Any;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.XComponentContext;
+
+
+import com.sun.star.lang.XMultiComponentFactory;
+
+
+import com.sun.star.script.XInvocation;
+
+import com.sun.star.ucb.XSimpleFileAccess;
+
+import com.sun.star.script.browse.XBrowseNode;
+import com.sun.star.script.browse.BrowseNodeTypes;
+
+import com.sun.star.script.framework.provider.ScriptProvider;
+import com.sun.star.script.framework.log.LogUtils;
+import com.sun.star.script.framework.container.ScriptMetaData;
+import com.sun.star.script.framework.container.ScriptEntry;
+import com.sun.star.script.framework.container.Parcel;
+import com.sun.star.script.framework.container.ParcelContainer;
+import com.sun.star.script.framework.browse.DialogFactory;
+
+import java.util.*;
+import javax.swing.JOptionPane;
+
+public class ParcelBrowseNode extends PropertySet
+ implements XBrowseNode, XInvocation
+{
+ private ScriptProvider provider;
+ //private RootBrowseNode parent;
+ private Collection browsenodes;
+ private String name;
+ private ParcelContainer container;
+ private Parcel parcel;
+ public boolean deletable = true;
+ public boolean editable = false;
+ public boolean creatable = false;
+ public boolean renamable = true;
+
+ public ParcelBrowseNode( ScriptProvider provider, ParcelContainer container, String parcelName ) {
+ this.provider = provider;
+ this.name = parcelName;
+ this.container = container;
+
+ // TODO decide whether exception is propagated out or not
+ try
+ {
+ this.parcel = (Parcel)this.container.getByName( parcelName );
+ }
+ catch ( Exception e )
+ {
+
+ LogUtils.DEBUG("** Exception: " + e );
+ LogUtils.DEBUG(" ** Failed to get parcel named " +
+ parcelName + " from container" );
+ }
+ registerProperty("Deletable", new Type(boolean.class),
+ (short)0, "deletable");
+ registerProperty("Editable", new Type(boolean.class),
+ (short)0, "editable");
+ registerProperty("Creatable", new Type(boolean.class),
+ (short)0, "creatable");
+ registerProperty("Renamable", new Type(boolean.class),
+ (short)0, "renamable");
+ if (provider.hasScriptEditor() == true)
+ {
+ this.creatable = true;
+ }
+
+ String parcelDirUrl = parcel.getPathToParcel();
+ XComponentContext xCtx = provider.getScriptingContext().getComponentContext();
+ XMultiComponentFactory xFac = xCtx.getServiceManager();
+ try
+ {
+ XSimpleFileAccess xSFA = ( XSimpleFileAccess)
+ UnoRuntime.queryInterface( XSimpleFileAccess.class,
+ xFac.createInstanceWithContext(
+ "com.sun.star.ucb.SimpleFileAccess",
+ xCtx ) );
+ if ( xSFA != null && ( xSFA.isReadOnly( parcelDirUrl ) ||
+ container.isUnoPkg() ) )
+ {
+ deletable = false;
+ editable = false;
+ creatable = false;
+ renamable = false;
+ }
+ }
+ catch ( com.sun.star.uno.Exception e )
+ {
+ // TODO propagate potential errors
+ // Pthrow new com.sun.star.uno.RuntimeException( e.toString() );
+ LogUtils.DEBUG( "Caught exception creating ParcelBrowseNode " + e );
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ }
+
+ }
+
+ public String getName() {
+ return parcel.getName();
+ }
+
+ public XBrowseNode[] getChildNodes() {
+ try
+ {
+
+ if ( hasChildNodes() )
+ {
+ String[] names = parcel.getElementNames();
+ browsenodes = new ArrayList( names.length );
+
+ for ( int index = 0; index < names.length; index++ )
+ {
+ browsenodes.add( new ScriptBrowseNode( provider, parcel, names[ index ] ));
+ }
+ }
+ else
+ {
+ LogUtils.DEBUG("ParcelBrowseNode.getChildeNodes no children " );
+ return new XBrowseNode[0];
+ }
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG("Failed to getChildeNodes, exception: " + e );
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ return new XBrowseNode[0];
+ }
+ return (XBrowseNode[])browsenodes.toArray(new XBrowseNode[0]);
+ }
+
+ public boolean hasChildNodes() {
+ if ( container != null && container.hasByName( getName() ) && parcel != null )
+ {
+ return parcel.hasElements();
+ }
+
+ return false;
+ }
+
+ public short getType() {
+ return BrowseNodeTypes.CONTAINER;
+ }
+
+ public String toString()
+ {
+ return getName();
+ }
+
+ // implementation of XInvocation interface
+ public XIntrospectionAccess getIntrospection() {
+ return null;
+ }
+
+ public Object invoke(String aFunctionName, Object[] aParams,
+ short[][] aOutParamIndex, Object[][] aOutParam)
+ throws com.sun.star.lang.IllegalArgumentException,
+ com.sun.star.script.CannotConvertException,
+ com.sun.star.reflection.InvocationTargetException
+ {
+ LogUtils.DEBUG("ParcelBrowseNode invoke for " + aFunctionName );
+ // Initialise the out paramters - not used but prevents error in
+ // UNO bridge
+ aOutParamIndex[0] = new short[0];
+ aOutParam[0] = new Object[0];
+
+ Any result = new Any(new Type(Boolean.class), Boolean.TRUE);
+
+ if (aFunctionName.equals("Creatable"))
+ {
+ try
+ {
+ String newName;
+
+ if (aParams == null || aParams.length < 1 ||
+ AnyConverter.isString(aParams[0]) == false)
+ {
+ String prompt = "Enter name for new Script";
+ String title = "Create Script";
+
+ // try to get a DialogFactory instance, if it fails
+ // just use a Swing JOptionPane to prompt for the name
+ try
+ {
+ DialogFactory dialogFactory =
+ DialogFactory.getDialogFactory();
+
+ newName = dialogFactory.showInputDialog(title, prompt);
+ }
+ catch (Exception e)
+ {
+ newName = JOptionPane.showInputDialog(null, prompt, title,
+ JOptionPane.QUESTION_MESSAGE);
+ }
+ }
+ else {
+ newName = (String) AnyConverter.toString(aParams[0]);
+ }
+
+ if ( newName == null || newName.equals(""))
+ {
+ result = new Any(new Type(Boolean.class), Boolean.FALSE);
+ }
+ else
+ {
+ String source = new String(provider.getScriptEditor().getTemplate().getBytes());
+ String languageName = newName + "." + provider.getScriptEditor().getExtension();
+ String language = container.getLanguage();
+
+ ScriptEntry entry = new ScriptEntry( language, languageName, languageName, "", new HashMap() );
+
+ Parcel parcel = (Parcel)container.getByName( getName() );
+ ScriptMetaData data = new ScriptMetaData( parcel, entry, source );
+ parcel.insertByName( languageName, data );
+
+ ScriptBrowseNode sbn = new ScriptBrowseNode( provider, parcel, languageName );
+
+ if(browsenodes==null)
+ {
+ LogUtils.DEBUG("browsenodes null!!");
+ browsenodes = new ArrayList(4);
+ }
+ browsenodes.add(sbn);
+
+ result = new Any(new Type(XBrowseNode.class), sbn);
+ }
+ }
+ catch (Exception e)
+ {
+ LogUtils.DEBUG("ParcelBrowseNode[create] failed with: " + e );
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ result = new Any(new Type(Boolean.class), Boolean.FALSE);
+
+ // throw new com.sun.star.reflection.InvocationTargetException(
+ // "Error creating script: " + e.getMessage());
+ }
+ }
+ else if (aFunctionName.equals("Deletable"))
+ {
+ try
+ {
+ if ( container.deleteParcel(getName()) )
+ {
+ result = new Any(new Type(Boolean.class), Boolean.TRUE);
+ }
+ else
+ {
+ result = new Any(new Type(Boolean.class), Boolean.FALSE);
+ }
+ }
+ catch (Exception e)
+ {
+ result = new Any(new Type(Boolean.class), Boolean.FALSE);
+
+ // throw new com.sun.star.reflection.InvocationTargetException(
+ // "Error deleting parcel: " + e.getMessage());
+ }
+ }
+ else if (aFunctionName.equals("Renamable"))
+ {
+ String newName = null;
+ try
+ {
+
+ if (aParams == null || aParams.length < 1 ||
+ AnyConverter.isString(aParams[0]) == false)
+ {
+ String prompt = "Enter new name for Library";
+ String title = "Rename Library";
+
+ // try to get a DialogFactory instance, if it fails
+ // just use a Swing JOptionPane to prompt for the name
+ try
+ {
+ DialogFactory dialogFactory =
+ DialogFactory.getDialogFactory();
+
+ newName = dialogFactory.showInputDialog(title, prompt);
+ }
+ catch (Exception e)
+ {
+ newName = JOptionPane.showInputDialog(null, prompt, title,
+ JOptionPane.QUESTION_MESSAGE);
+ }
+ }
+ else {
+ newName = (String) AnyConverter.toString(aParams[0]);
+ }
+ container.renameParcel( getName(), newName );
+ Parcel p = (Parcel)container.getByName( newName );
+ if(browsenodes == null )
+ {
+ getChildNodes();
+ }
+ ScriptBrowseNode[] childNodes = (ScriptBrowseNode[])browsenodes.toArray(new ScriptBrowseNode[0]);
+
+ for ( int index = 0; index < childNodes.length; index++ )
+ {
+ childNodes[ index ].updateURI( p );
+ }
+ result = new Any(new Type(XBrowseNode.class), this);
+ }
+ catch (Exception e)
+ {
+ result = new Any(new Type(Boolean.class), Boolean.FALSE);
+
+ // throw new com.sun.star.reflection.InvocationTargetException(
+ // "Error renaming parcel: " + e.getMessage());
+ }
+ }
+
+ else {
+ throw new com.sun.star.lang.IllegalArgumentException(
+ "Function " + aFunctionName + " not supported.");
+ }
+
+ return result;
+ }
+
+ public void setValue(String aPropertyName, Object aValue)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.script.CannotConvertException,
+ com.sun.star.reflection.InvocationTargetException
+ {
+ }
+
+ public Object getValue(String aPropertyName)
+ throws com.sun.star.beans.UnknownPropertyException
+ {
+ return null;
+ }
+
+ public boolean hasMethod(String aName) {
+ return false;
+ }
+
+ public boolean hasProperty(String aName) {
+ return false;
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java b/scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java
new file mode 100644
index 000000000000..98698e019828
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java
@@ -0,0 +1,68 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: PkgProviderBrowseNode.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.browse;
+
+import com.sun.star.uno.XComponentContext;
+
+import com.sun.star.script.XInvocation;
+
+import com.sun.star.script.browse.XBrowseNode;
+
+import com.sun.star.script.framework.provider.ScriptProvider;
+import com.sun.star.script.framework.log.*;
+import com.sun.star.script.framework.container.*;
+
+
+public class PkgProviderBrowseNode extends ProviderBrowseNode
+ implements XBrowseNode, XInvocation
+{
+
+ public PkgProviderBrowseNode( ScriptProvider provider, ParcelContainer container, XComponentContext xCtx ) {
+ super( provider, container, xCtx );
+ LogUtils.DEBUG("*** PkgProviderBrowseNode ctor container name = " + container.getName());
+ LogUtils.DEBUG("*** PkgProviderBrowseNode ctor container path = " + container.getParcelContainerDir());
+ LogUtils.DEBUG("*** PkgProviderBrowseNode ctor, container has num parcels = " + container.getElementNames().length);
+ deletable = false;
+ editable = false;
+ creatable = false;
+
+ }
+
+ public String getName() {
+ String name = "Unknown";
+ if ( container != null )
+ {
+ name = container.getName();
+ }
+ return name;
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/browse/ProviderBrowseNode.java b/scripting/java/com/sun/star/script/framework/browse/ProviderBrowseNode.java
new file mode 100644
index 000000000000..195912720949
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/browse/ProviderBrowseNode.java
@@ -0,0 +1,294 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ProviderBrowseNode.java,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.browse;
+
+import com.sun.star.lib.uno.helper.PropertySet;
+import com.sun.star.uno.Any;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.uno.UnoRuntime;
+
+import com.sun.star.lang.XMultiComponentFactory;
+
+import com.sun.star.ucb.XSimpleFileAccess;
+
+import com.sun.star.beans.XIntrospectionAccess;
+import com.sun.star.script.XInvocation;
+
+import com.sun.star.script.browse.XBrowseNode;
+import com.sun.star.script.browse.BrowseNodeTypes;
+
+import com.sun.star.script.framework.provider.ScriptProvider;
+import com.sun.star.script.framework.log.*;
+import com.sun.star.script.framework.container.*;
+import com.sun.star.script.framework.browse.DialogFactory;
+
+import java.util.*;
+import javax.swing.JOptionPane;
+
+public class ProviderBrowseNode extends PropertySet
+ implements XBrowseNode, XInvocation
+{
+ protected ScriptProvider provider;
+ protected Collection browsenodes;
+ protected String name;
+ protected ParcelContainer container;
+ protected Parcel parcel;
+ protected XComponentContext m_xCtx;
+
+ public boolean deletable = true;
+ public boolean creatable = true;
+ public boolean editable = false;
+
+ public ProviderBrowseNode( ScriptProvider provider, ParcelContainer container, XComponentContext xCtx ) {
+ LogUtils.DEBUG("*** ProviderBrowseNode ctor");
+ this.container = container;
+ this.name = this.container.getLanguage();
+ this.provider = provider;
+ this.m_xCtx = xCtx;
+
+ registerProperty("Deletable", new Type(boolean.class),
+ (short)0, "deletable");
+ registerProperty("Creatable", new Type(boolean.class),
+ (short)0, "creatable");
+ registerProperty("Editable", new Type(boolean.class),
+ (short)0, "editable");
+ XSimpleFileAccess xSFA = null;
+ XMultiComponentFactory xFac = m_xCtx.getServiceManager();
+ try
+ {
+ xSFA = ( XSimpleFileAccess)
+ UnoRuntime.queryInterface( XSimpleFileAccess.class,
+ xFac.createInstanceWithContext(
+ "com.sun.star.ucb.SimpleFileAccess",
+ xCtx ) );
+ if ( container.isUnoPkg() || xSFA.isReadOnly( container.getParcelContainerDir() ) )
+ {
+ deletable = false;
+ creatable = false;
+ }
+ }
+ // TODO propage errors
+ catch( com.sun.star.uno.Exception e )
+ {
+ LogUtils.DEBUG("Caught exception in creation of ProviderBrowseNode ");
+ LogUtils.DEBUG( LogUtils.getTrace(e));
+
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public XBrowseNode[] getChildNodes() {
+ LogUtils.DEBUG("***** ProviderBrowseNode.getChildNodes()");
+ if ( hasChildNodes() )
+ {
+ // needs initialisation?
+ LogUtils.DEBUG("** ProviderBrowseNode.getChildNodes(), container is " + container );
+ String[] parcels = container.getElementNames();
+ browsenodes = new ArrayList( parcels.length );
+ for ( int index = 0; index < parcels.length; index++ )
+ {
+ try
+ {
+ XBrowseNode node = new ParcelBrowseNode( provider, container, parcels[ index ] );
+ browsenodes.add( node );
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG("*** Failed to create parcel node for " + parcels[ index ] );
+ LogUtils.DEBUG( e.toString() );
+ }
+ }
+ ParcelContainer[] packageContainers = container.getChildContainers();
+ LogUtils.DEBUG("**** For container named " + container.getName() + " with root path " + container.getParcelContainerDir() + " has " + packageContainers.length + " child containers " );
+
+ for ( int i = 0; i < packageContainers.length; i++ )
+ {
+ XBrowseNode node = new PkgProviderBrowseNode( provider, packageContainers[ i ], m_xCtx );
+ browsenodes.add( node );
+ }
+ }
+ else
+ {
+ LogUtils.DEBUG("*** No container available");
+ return new XBrowseNode[0];
+ }
+ return ( XBrowseNode[] )browsenodes.toArray( new XBrowseNode[0] );
+ }
+
+ public boolean hasChildNodes() {
+ boolean result = true;
+
+ if ( container == null ||
+ ( !container.hasElements() &&
+ container.getChildContainers().length == 0 ) )
+ {
+ result = false;
+ }
+
+ LogUtils.DEBUG("***** ProviderBrowseNode.hasChildNodes(): " +
+ "name=" + name +
+ ", path=" + container.getParcelContainerDir() +
+ ", result=" + result );
+
+ return result;
+ }
+
+ public short getType() {
+ return BrowseNodeTypes.CONTAINER;
+ }
+
+ public String toString()
+ {
+ return getName();
+ }
+
+ // implementation of XInvocation interface
+ public XIntrospectionAccess getIntrospection() {
+ return null;
+ }
+
+ public Object invoke(String aFunctionName, Object[] aParams,
+ short[][] aOutParamIndex, Object[][] aOutParam)
+ throws com.sun.star.lang.IllegalArgumentException,
+ com.sun.star.script.CannotConvertException,
+ com.sun.star.reflection.InvocationTargetException
+ {
+ // Initialise the out paramters - not used but prevents error in
+ // UNO bridge
+ aOutParamIndex[0] = new short[0];
+ aOutParam[0] = new Object[0];
+
+ Any result = new Any(new Type(Boolean.class), Boolean.TRUE);
+
+ if (aFunctionName.equals("Creatable"))
+ {
+ try
+ {
+ String name;
+
+ if (aParams == null || aParams.length < 1 ||
+ AnyConverter.isString(aParams[0]) == false)
+ {
+ String prompt = "Enter name for new Parcel";
+ String title = "Create Parcel";
+
+ // try to get a DialogFactory instance, if it fails
+ // just use a Swing JOptionPane to prompt for the name
+ try
+ {
+ DialogFactory dialogFactory =
+ DialogFactory.getDialogFactory();
+
+ name = dialogFactory.showInputDialog(title, prompt);
+ }
+ catch (Exception e)
+ {
+ name = JOptionPane.showInputDialog(null, prompt, title,
+ JOptionPane.QUESTION_MESSAGE);
+ }
+ }
+ else {
+ name = (String) AnyConverter.toString(aParams[0]);
+ }
+
+ if (name == null || name.equals(""))
+ {
+ result = new Any(new Type(Boolean.class), Boolean.FALSE);
+ }
+ else
+ {
+
+ Object newParcel = container.createParcel( name );
+ LogUtils.DEBUG("Parcel created " + name + " " + newParcel );
+ if ( newParcel == null )
+ {
+ result = new Any(new Type(Boolean.class), Boolean.FALSE);
+ }
+ else
+ {
+ ParcelBrowseNode parcel = new ParcelBrowseNode( provider, container, name );
+ LogUtils.DEBUG("created parcel node ");
+ if ( browsenodes == null )
+ {
+ browsenodes = new ArrayList( 5 );
+ }
+
+ browsenodes.add(parcel);
+
+
+ result = new Any(new Type(XBrowseNode.class), parcel);
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ LogUtils.DEBUG("ProviderBrowseNode[create] failed with: " + e );
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ result = new Any(new Type(Boolean.class), Boolean.FALSE);
+
+ // throw new com.sun.star.reflection.InvocationTargetException(
+ // "Error creating script: " + e.getMessage());
+ }
+ }
+ else {
+ throw new com.sun.star.lang.IllegalArgumentException(
+ "Function " + aFunctionName + " not supported.");
+ }
+
+ return result;
+ }
+
+ public void setValue(String aPropertyName, Object aValue)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.script.CannotConvertException,
+ com.sun.star.reflection.InvocationTargetException
+ {
+ }
+
+ public Object getValue(String aPropertyName)
+ throws com.sun.star.beans.UnknownPropertyException
+ {
+ return null;
+ }
+
+ public boolean hasMethod(String aName) {
+ return false;
+ }
+
+ public boolean hasProperty(String aName) {
+ return false;
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/browse/ScriptBrowseNode.java b/scripting/java/com/sun/star/script/framework/browse/ScriptBrowseNode.java
new file mode 100644
index 000000000000..4f5aaf793291
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/browse/ScriptBrowseNode.java
@@ -0,0 +1,338 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptBrowseNode.java,v $
+ * $Revision: 1.15 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.script.framework.browse;
+
+import com.sun.star.script.browse.XBrowseNode;
+import com.sun.star.script.browse.BrowseNodeTypes;
+import com.sun.star.script.provider.XScriptContext;
+
+import com.sun.star.lib.uno.helper.PropertySet;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.uno.Any;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.uno.UnoRuntime;
+
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.beans.XIntrospectionAccess;
+import com.sun.star.script.XInvocation;
+
+import com.sun.star.lang.NoSupportException;
+import com.sun.star.lang.WrappedTargetException;
+import com.sun.star.reflection.InvocationTargetException;
+import com.sun.star.container.NoSuchElementException;
+import com.sun.star.container.ElementExistException;
+
+import java.util.*;
+
+import com.sun.star.script.framework.log.LogUtils;
+import com.sun.star.script.framework.provider.ScriptProvider;
+import com.sun.star.script.framework.container.*;
+
+public class ScriptBrowseNode extends PropertySet
+ implements XBrowseNode, XInvocation
+{
+ private ScriptProvider provider;
+
+ private Parcel parent;
+ private String name;
+ public String uri;
+ public String description;
+ public boolean editable = false;
+ public boolean deletable = false;
+ public boolean renamable = false;
+
+ public ScriptBrowseNode( ScriptProvider provider, Parcel parent,
+ String name )
+ {
+ this.provider = provider;
+ this.name = name;
+ this.parent = parent;
+ ScriptMetaData data = null;
+ XSimpleFileAccess xSFA = null;
+ XComponentContext xCtx = provider.getScriptingContext().getComponentContext();
+ XMultiComponentFactory xFac = xCtx.getServiceManager();
+ try
+ {
+ data = (ScriptMetaData)parent.getByName( name );
+ xSFA = ( XSimpleFileAccess)
+ UnoRuntime.queryInterface( XSimpleFileAccess.class,
+ xFac.createInstanceWithContext(
+ "com.sun.star.ucb.SimpleFileAccess",
+ xCtx ) );
+ }
+
+ // TODO fix exception types to be caught here, should we rethrow?
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG("** caught exception getting script data for " + name + " ->" + e.toString() );
+ }
+
+ uri = data.getShortFormScriptURL();
+ description = data.getDescription();
+
+ if (provider.hasScriptEditor() == true)
+ {
+
+ this.editable = true;
+ try
+ {
+ if ( !parent.isUnoPkg() &&
+ !xSFA.isReadOnly( parent.getPathToParcel() ) )
+ {
+ this.deletable = true;
+ this.renamable = true;
+ }
+ }
+ // TODO propagate errors
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG("Caught exception in creation of ScriptBrowseNode");
+ LogUtils.DEBUG( LogUtils.getTrace(e));
+ }
+
+ }
+
+ registerProperty("Deletable", new Type(boolean.class),
+ (short)0, "deletable");
+ registerProperty("Editable", new Type(boolean.class),
+ (short)0, "editable");
+ registerProperty("Renamable", new Type(boolean.class),
+ (short)0, "renamable");
+ registerProperty("URI", new Type(String.class),
+ (short)0, "uri");
+ registerProperty("Description", new Type(String.class),
+ (short)0, "description");
+ }
+
+
+ public String getName() {
+ return name;
+ }
+
+ public XBrowseNode[] getChildNodes() {
+ return new XBrowseNode[0];
+ }
+
+ public boolean hasChildNodes() {
+ return false;
+ }
+
+ public short getType() {
+ return BrowseNodeTypes.SCRIPT;
+ }
+
+ public String toString() {
+ return getName();
+ }
+
+ public void updateURI( Parcel p ) {
+ parent = p;
+ ScriptMetaData data = null;
+ try
+ {
+ data = (ScriptMetaData)parent.getByName( name );
+ }
+
+ // TODO fix exception types to be caught here, should we rethrow?
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG("** caught exception getting script data for " + name + " ->" + e.toString() );
+ }
+ uri = data.getShortFormScriptURL();
+ }
+ // implementation of XInvocation interface
+ public XIntrospectionAccess getIntrospection() {
+ return null;
+ }
+
+ public Object invoke(String aFunctionName, Object[] aParams,
+ short[][] aOutParamIndex, Object[][] aOutParam)
+ throws com.sun.star.lang.IllegalArgumentException,
+ com.sun.star.script.CannotConvertException,
+ com.sun.star.reflection.InvocationTargetException
+ {
+ // Initialise the out paramters - not used but prevents error in
+ // UNO bridge
+ aOutParamIndex[0] = new short[0];
+ aOutParam[0] = new Object[0];
+
+ Any result = new Any(new Type(Boolean.class), Boolean.TRUE);
+
+ if (aFunctionName.equals("Editable"))
+ {
+ if (!editable)
+ {
+ NoSupportException nse = new NoSupportException(
+ aFunctionName + " is not editable " );
+
+ throw new InvocationTargetException(
+ "Scripting framework error editing script", null, nse );
+ }
+
+ XScriptContext ctxt = provider.getScriptingContext();
+ ScriptMetaData data = null;
+ try
+ {
+ data = (ScriptMetaData)parent.getByName( name );
+ }
+ catch ( NoSuchElementException nse )
+ {
+ throw new com.sun.star.lang.IllegalArgumentException(
+ name + " does not exist or can't be found " );
+ }
+ catch ( com.sun.star.lang.WrappedTargetException wte )
+ {
+ // rethrow
+ throw new InvocationTargetException(
+ "Scripting framework editing script ",
+ null, wte.TargetException );
+ }
+
+ provider.getScriptEditor().edit(ctxt, data);
+ }
+ else if (aFunctionName.equals("Deletable"))
+ {
+ if (!deletable)
+ {
+ NoSupportException nse = new NoSupportException(
+ aFunctionName + " is not supported for this node" );
+
+ throw new InvocationTargetException(
+ "Scripting framework error deleting script", null, nse );
+ }
+ try
+ {
+ parent.removeByName( name );
+ result = new Any(new Type(Boolean.class), Boolean.TRUE);
+ }
+ catch ( NoSuchElementException nse )
+ {
+ throw new com.sun.star.lang.IllegalArgumentException(
+ name + " does not exist or can't be found " );
+ }
+ catch ( WrappedTargetException wte )
+ {
+ // rethrow
+ throw new InvocationTargetException(
+ "Scripting framework deleting script ",
+ null, wte.TargetException );
+ }
+
+ }
+ else if (aFunctionName.equals("Renamable"))
+ {
+ result = new Any(new Type(XBrowseNode.class), new XBrowseNode[0]);
+ if (!renamable)
+ {
+ NoSupportException nse = new NoSupportException(
+ aFunctionName + " is not supported for this node" );
+
+ throw new InvocationTargetException(
+ "Scripting framework error renaming script", null, nse );
+ }
+
+ try
+ {
+ String newName = (String) AnyConverter.toString(aParams[0]);
+ ScriptMetaData oldData = (ScriptMetaData)parent.getByName( name );
+ oldData.loadSource();
+ String oldSource = oldData.getSource();
+
+ LogUtils.DEBUG("Create renamed script");
+ String languageName =
+ newName + "." + provider.getScriptEditor().getExtension();
+ String language = provider.getName();
+
+ ScriptEntry entry = new ScriptEntry(
+ language, languageName, languageName, "", new HashMap() );
+
+ ScriptMetaData data = new ScriptMetaData(
+ parent, entry, oldSource );
+
+ parent.insertByName( languageName, data );
+
+ LogUtils.DEBUG("Now remove old script");
+ parent.removeByName( name );
+
+ uri = data.getShortFormScriptURL();
+ name = languageName;
+ result = new Any(new Type(XBrowseNode.class), this);
+ }
+ catch ( NoSuchElementException nse )
+ {
+ throw new com.sun.star.lang.IllegalArgumentException(
+ name + " does not exist or can't be found " );
+ }
+ catch ( ElementExistException eee )
+ {
+ // rethrow
+ throw new InvocationTargetException(
+ "Scripting framework error renaming script ",
+ null, eee );
+ }
+ catch ( WrappedTargetException wte )
+ {
+ // rethrow
+ throw new InvocationTargetException(
+ "Scripting framework rename script ",
+ null, wte.TargetException );
+ }
+ }
+ else {
+ throw new com.sun.star.lang.IllegalArgumentException(
+ "Function " + aFunctionName + " not supported.");
+ }
+
+ return result;
+ }
+
+ public void setValue(String aPropertyName, Object aValue)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.script.CannotConvertException,
+ com.sun.star.reflection.InvocationTargetException
+ {
+ }
+
+ public Object getValue(String aPropertyName)
+ throws com.sun.star.beans.UnknownPropertyException
+ {
+ return null;
+ }
+
+ public boolean hasMethod(String aName) {
+ return false;
+ }
+
+ public boolean hasProperty(String aName) {
+ return false;
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/container/DeployedUnoPackagesDB.java b/scripting/java/com/sun/star/script/framework/container/DeployedUnoPackagesDB.java
new file mode 100644
index 000000000000..3612e6650d05
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/container/DeployedUnoPackagesDB.java
@@ -0,0 +1,234 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: DeployedUnoPackagesDB.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.container;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.IOException;
+import java.io.ByteArrayInputStream;
+
+import java.util.ArrayList;
+
+// import javax.xml.parsers.DocumentBuilderFactory;
+// import javax.xml.parsers.DocumentBuilder;
+// import javax.xml.parsers.ParserConfigurationException;
+
+import org.w3c.dom.*;
+
+public class DeployedUnoPackagesDB {
+
+ // File name to be used for parcel descriptor files
+ private static final String
+ PARCEL_DESCRIPTOR_NAME = "unopkg-desc.xml";
+
+ // This is the default contents of a parcel descriptor to be used when
+ // creating empty descriptors
+ private static final byte[] EMPTY_DOCUMENT =
+ ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
+ "<unopackages xmlns:unopackages=\"unopackages.dtd\">\n" +
+ "</unopackages>").getBytes();
+
+ private File file = null;
+ private Document document = null;
+
+ public DeployedUnoPackagesDB() throws IOException {
+ ByteArrayInputStream bis = null;
+ try {
+ bis = new ByteArrayInputStream(EMPTY_DOCUMENT);
+ this.document = XMLParserFactory.getParser().parse(bis);
+ }
+ finally {
+ if (bis != null)
+ bis.close();
+ }
+ }
+
+ public DeployedUnoPackagesDB(Document document) {
+ this.document = document;
+ }
+
+ public DeployedUnoPackagesDB(InputStream is) throws IOException {
+ this(XMLParserFactory.getParser().parse(is));
+ }
+
+ public String[] getDeployedPackages( String language )
+ {
+ ArrayList packageUrls = new ArrayList(4);
+ Element main = document.getDocumentElement();
+ Element root = null;
+ Element item;
+ int len = 0;
+ NodeList langNodes = null;
+
+ if ((langNodes = main.getElementsByTagName("language")) != null &&
+ (len = langNodes.getLength()) != 0)
+ {
+ for ( int i=0; i<len; i++ )
+ {
+ Element e = (Element)langNodes.item( i );
+ if ( e.getAttribute("value").equals(language) )
+ {
+ root = e;
+ break;
+ }
+ }
+ }
+ if ( root != null )
+ {
+ len = 0;
+ NodeList packages = null;
+ if ((packages = root.getElementsByTagName("package")) != null &&
+ (len = packages.getLength()) != 0)
+ {
+
+ for ( int i=0; i<len; i++ )
+ {
+
+ Element e = (Element)packages.item( i );
+ packageUrls.add( e.getAttribute("value") );
+ }
+ }
+ }
+ if ( !packageUrls.isEmpty() )
+ {
+ return (String[])packageUrls.toArray( new String[0] );
+ }
+ return new String[0];
+ }
+
+ public void write(OutputStream out) throws IOException {
+ XMLParserFactory.getParser().write(document, out);
+ }
+
+ public Document getDocument() {
+ return document;
+ }
+
+
+ private void clearEntries() {
+ NodeList langNodes;
+ Element main = document.getDocumentElement();
+ int len;
+
+ if ((langNodes = document.getElementsByTagName("language")) != null &&
+ (len = langNodes.getLength()) != 0)
+ {
+ for (int i = len - 1; i >= 0; i--) {
+ try {
+ main.removeChild(langNodes.item(i));
+ }
+ catch (DOMException de) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ public boolean removePackage( String language, String url )
+ {
+ Element main = document.getDocumentElement();
+ Element langNode = null;
+ int len = 0;
+ NodeList langNodes = null;
+ boolean result = false;
+ if ((langNodes = main.getElementsByTagName("language")) != null &&
+ (len = langNodes.getLength()) != 0)
+ {
+ for ( int i=0; i<len; i++ )
+ {
+ Element e = (Element)langNodes.item( i );
+ if ( e.getAttribute("value").equals(language) )
+ {
+ langNode = e;
+ break;
+ }
+ }
+ }
+ if ( langNode != null )
+ {
+ len = 0;
+ NodeList packages = null;
+ if ((packages = langNode.getElementsByTagName("package")) != null &&
+ (len = packages.getLength()) != 0)
+ {
+ for ( int i=0; i<len; i++ )
+ {
+
+ Element e = (Element)packages.item( i );
+ String value = e.getAttribute("value");
+
+ if ( value.equals(url) )
+ {
+ langNode.removeChild( e );
+ result = true;
+ break;
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ public void addPackage(String language, String url ) {
+ Element main = document.getDocumentElement();
+ Element langNode = null;
+ Element pkgNode = null;
+
+ int len = 0;
+ NodeList langNodes = null;
+
+ if ((langNodes = document.getElementsByTagName("language")) != null &&
+ (len = langNodes.getLength()) != 0)
+ {
+ for ( int i=0; i<len; i++ )
+ {
+ Element e = (Element)langNodes.item( i );
+ if ( e.getAttribute("value").equals(language) )
+ {
+ langNode = e;
+ break;
+ }
+ }
+ }
+ if ( langNode == null )
+ {
+ langNode = document.createElement("language");
+ langNode.setAttribute( "value", language );
+ }
+ pkgNode = document.createElement("package");
+ pkgNode.setAttribute( "value", url );
+
+ langNode.appendChild(pkgNode);
+ //add to the Top Element
+ main.appendChild(langNode);
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/container/Parcel.java b/scripting/java/com/sun/star/script/framework/container/Parcel.java
new file mode 100644
index 000000000000..6d33130c7d40
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/container/Parcel.java
@@ -0,0 +1,311 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: Parcel.java,v $
+ * $Revision: 1.7 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.script.framework.container;
+import com.sun.star.script.framework.log.*;
+import com.sun.star.script.framework.io.*;
+import com.sun.star.script.framework.provider.PathUtils;
+
+import com.sun.star.container.*;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.UnoRuntime;
+
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.ucb.XSimpleFileAccess2;
+import java.io.*;
+
+public class Parcel implements XNameContainer
+{
+ protected ParcelDescriptor m_descriptor;
+ protected String name;
+ protected ParcelContainer parent;
+ protected XSimpleFileAccess m_xSFA;
+ public Parcel( XSimpleFileAccess xSFA, ParcelContainer parent, ParcelDescriptor desc, String parcelName )
+ {
+ this( parent, desc, parcelName );
+ this.m_xSFA = xSFA;
+ }
+
+ public Parcel( ParcelContainer parent, ParcelDescriptor desc, String parcelName )
+ {
+ this.parent = parent;
+ this.m_descriptor = desc;
+ this.name = parcelName;
+ }
+
+ /**
+ * Tests if this <tt>Parcel</tt> is in an UNO package
+ * or within a sub package within an UNO package
+ *
+ * @return <tt>true</tt> if has parent <tt>false</tt> otherwise
+ */
+ public boolean isUnoPkg() { return parent.isUnoPkg(); }
+
+ public String getName()
+ {
+ return name;
+ }
+ public java.lang.Object getByName( String aName ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ LogUtils.DEBUG("** Parcel.getByName for " + aName );
+ ScriptEntry script = null;
+ try
+ {
+ if ( m_descriptor != null && hasElements() )
+ {
+ ScriptEntry[] scripts = m_descriptor.getScriptEntries();
+ if ( scripts.length != 0 )
+ {
+ for ( int index = 0; index < scripts.length; index++ )
+ {
+ if ( scripts[ index ].getLanguageName().equals( aName ) )
+ {
+ script = scripts[ index ];
+ break;
+ }
+ }
+ }
+ }
+ }
+ // catch unknown or un-checked exceptions
+ catch ( Exception e )
+ {
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+ if ( script == null )
+ {
+ LogUtils.DEBUG("No script for " + aName );
+ throw new com.sun.star.container.NoSuchElementException("No script named " + aName );
+ }
+ ScriptMetaData data = new ScriptMetaData( this, script, null );
+
+ LogUtils.DEBUG("returning date for " + aName );
+ return data;
+ }
+ public String[] getElementNames()
+ {
+ String[] results = new String[0];
+ if ( m_descriptor != null )
+ {
+ ScriptEntry[] scripts = m_descriptor.getScriptEntries();
+ results = new String[ scripts.length ];
+ for ( int index = 0; index < scripts.length; index++ )
+ {
+ results[ index ] = scripts[ index ].getLanguageName();
+ }
+ }
+ return results;
+ }
+ public boolean hasByName( String aName )
+ {
+
+ boolean result = true;
+ Object containee = null;
+ try
+ {
+ containee = getByName( aName );
+ if ( containee != null )
+ {
+ result = true;
+ }
+ }
+ catch( Exception e )
+ {
+ result = false;
+ }
+ return result;
+ }
+
+ public com.sun.star.uno.Type getElementType() {
+ // TODO at the moment this returns void indicating
+ // type is unknown ( from UNO point of view this is correct )
+ // but, maybe we want to have a private UNO interface
+ //
+ return new Type();
+ }
+
+ public boolean hasElements()
+ {
+ if ( m_descriptor != null && m_descriptor.getScriptEntries().length > 0 )
+ {
+ return true;
+ }
+ return false;
+ }
+
+ public void replaceByName( String aName, java.lang.Object aElement ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ // TODO check type of aElement
+ // if not ok, throw IllegalArgument
+ if ( m_descriptor != null )
+ {
+ try
+ {
+ ScriptEntry script = (ScriptEntry)getByName( aName );
+ if ( script != null )
+ {
+ //m_descriptor.removeScriptEntry( script );
+ // TODO needs to create source file ( if there is one )
+ //m_descriptor.write();
+ }
+ else
+ {
+ throw new com.sun.star.container.NoSuchElementException("No script named " + aName );
+ }
+
+
+ }
+ // TO DO should catch specified exceptions
+ catch ( Exception e )
+ {
+ throw new com.sun.star.lang.WrappedTargetException();
+ }
+
+ }
+ }
+
+ // create
+ public void insertByName( String aName, java.lang.Object aElement ) throws com.sun.star.lang.IllegalArgumentException, ElementExistException, com.sun.star.lang.WrappedTargetException
+ {
+ // TODO check the type of aElement and throw#
+ // if not appropriate
+ try
+ {
+ if ( hasByName( aName ) )
+ {
+ throw new ElementExistException( aName );
+ }
+ ScriptMetaData script = (ScriptMetaData)aElement;
+
+ if ( script.hasSource() )
+ {
+ LogUtils.DEBUG("Inserting source: " + script.getSource());
+ if ( !script.writeSourceFile() )
+ {
+ throw new com.sun.star.lang.WrappedTargetException( "Failed to create source file " + script.getLanguageName() );
+ }
+ }
+ m_descriptor.addScriptEntry( script );
+ writeParcelDescriptor();
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG("Failed to insert entry " + aName + ": " + e.getMessage());
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+ }
+
+
+ private void writeParcelDescriptor()
+ throws com.sun.star.ucb.CommandAbortedException,
+ com.sun.star.io.IOException,
+ com.sun.star.uno.Exception, java.io.IOException
+ {
+ String pathToDescriptor = PathUtils.make_url(
+ getPathToParcel(), ParcelDescriptor.PARCEL_DESCRIPTOR_NAME );
+
+ XSimpleFileAccess2 xSFA2 = ( XSimpleFileAccess2 )
+ UnoRuntime.queryInterface( XSimpleFileAccess2.class, m_xSFA );
+
+ if ( xSFA2 != null )
+ {
+ ByteArrayOutputStream bos = null;
+ ByteArrayInputStream bis = null;
+ XInputStreamImpl xis = null;
+ try
+ {
+ bos = new ByteArrayOutputStream( 1024 );
+ m_descriptor.write( bos );
+ bis = new ByteArrayInputStream( bos.toByteArray() );
+
+ xis = new XInputStreamImpl( bis );
+ xSFA2.writeFile( pathToDescriptor, xis );
+ }
+ finally
+ {
+ if (bos != null) bos.close();
+ if (bis != null) bis.close();
+ if (xis != null) xis.closeInput();
+ }
+ }
+ }
+
+ // delete
+ public void removeByName( String Name ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ try
+ {
+ ScriptMetaData script = null;
+ if ( ( script = (ScriptMetaData)getByName( Name ) ) != null )
+ {
+// if ( script.hasSource() )
+ {
+ if ( !script.removeSourceFile() )
+ {
+ LogUtils.DEBUG("** Parcel.removeByName Failed to remove script " + Name );
+ throw new com.sun.star.lang.WrappedTargetException("Failed to remove script " + Name );
+ }
+ LogUtils.DEBUG("** Parcel.removeByName have removed script source file " + Name );
+ }
+ m_descriptor.removeScriptEntry( script );
+ writeParcelDescriptor();
+
+ }
+ else
+ {
+ throw new com.sun.star.container.NoSuchElementException( "No script named " + Name );
+ }
+
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG("** Parcel.removeByName Exception: " + e );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+
+ }
+ // rename parcel
+ public void rename( String name ) throws com.sun.star.lang.WrappedTargetException
+ {
+ this.name = name;
+ }
+ public ParcelContainer getParent() { return parent; }
+ /**
+ * Returns the path of this <tt>Parcel</tt>
+ *
+ * @return <tt>String</tt> path to parcel
+ */
+ public String getPathToParcel()
+ {
+ String path = parent.getParcelContainerDir() + "/" + name;
+ return path;
+ }
+
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/container/ParcelContainer.java b/scripting/java/com/sun/star/script/framework/container/ParcelContainer.java
new file mode 100644
index 000000000000..7c6148ee2fae
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/container/ParcelContainer.java
@@ -0,0 +1,749 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelContainer.java,v $
+ * $Revision: 1.10 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.container;
+
+import com.sun.star.script.framework.log.*;
+import com.sun.star.script.framework.io.*;
+import com.sun.star.script.framework.provider.PathUtils;
+
+import com.sun.star.container.*;
+import com.sun.star.uno.Type;
+import com.sun.star.lang.*;
+import com.sun.star.io.*;
+import java.io.*;
+import java.util.*;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.ucb.XSimpleFileAccess2;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.uno.UnoRuntime;
+
+import com.sun.star.uri.XUriReference;
+import com.sun.star.uri.XUriReferenceFactory;
+import com.sun.star.uri.XVndSunStarScriptUrl;
+
+/**
+ * The <code>ParcelContainer</code> object is used to store the
+ * ScripingFramework specific Libraries.
+ *
+ * @author
+ * @created
+ */
+
+public class ParcelContainer implements XNameAccess
+{
+ protected String language;
+ protected String containerUrl;
+ protected Collection parcels = new ArrayList(10);
+ static protected XSimpleFileAccess m_xSFA;
+ protected XComponentContext m_xCtx;
+ private ParcelContainer parent = null;
+ private Collection childContainers = new ArrayList(10);;
+ private boolean isPkgContainer = false;
+
+ /**
+ * Tests if this <tt>ParcelContainer</tt> represents an UNO package
+ * or sub package within an UNO package
+ *
+ * @return <tt>true</tt> if has parent <tt>false</tt> otherwise
+ */
+ public boolean isUnoPkg() { return isPkgContainer; }
+ /**
+ * Tests if this <tt>ParcelContainer</tt> has a parent
+ * a parent.
+ *
+ * @return <tt>true</tt> if has parent <tt>false</tt> otherwise
+ */
+ public boolean hasParent()
+ {
+ if ( parent == null )
+ {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns this <tt>ParcelContainer</tt>'s parent
+ *
+ * @return <tt>ParcelContainer</tt> if has parent null otherwise
+ */
+ public ParcelContainer parent()
+ {
+ return parent;
+ }
+
+ /**
+ * Returns all child <tt>ParcelContainer</tt>
+ * this instance of <tt>ParcelContainer</tt>
+ *
+ * @return a new array of ParcelContainers. A zero
+ * length array is returned if no child ParcelContainers.
+ */
+ public ParcelContainer[] getChildContainers()
+ {
+ if ( childContainers.isEmpty() )
+ {
+ return new ParcelContainer[0];
+ }
+ return (ParcelContainer[]) childContainers.toArray( new ParcelContainer[0] );
+
+ }
+ /**
+ * Removes a child <tt>ParcelContainer</tt>
+ * from this instance.
+ * @param child <tt>ParcelContainer</tt> to be added.
+ *
+ * @return <tt>true</tt> if child successfully removed
+ */
+ public boolean removeChildContainer( ParcelContainer child )
+ {
+ return childContainers.remove( child );
+ }
+
+ /**
+ * Adds a new child <tt>ParcelContainer</tt>
+ * to this instance.
+ * @param child <tt>ParcelContainer</tt> to be added.
+ *
+ */
+ public void addChildContainer( ParcelContainer child )
+ {
+ childContainers.add( child );
+ }
+
+ /**
+ * Returns a child <tt>ParcelContainer</tt> whose location
+ * matches the <tt>location</tt> argument passed to this method.
+ * @param key the <tt>location</tt> which is to
+ * be matched.
+ *
+ * @return child <tt>ParcelContainer</tt> or <null> if none
+ * found.
+ */
+
+ public ParcelContainer getChildContainer( String key )
+ {
+ ParcelContainer result = null;
+ Iterator iter = childContainers.iterator();
+ while ( iter.hasNext() )
+ {
+ ParcelContainer c = (ParcelContainer) iter.next();
+ String location = ScriptMetaData.getLocationPlaceHolder(
+ c.containerUrl, c.getName());
+
+ if ( key.equals( location ) )
+ {
+ result = c;
+ break;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Returns a child <tt>ParcelContainer</tt> whose member
+ * <tt>containerUrl</tt> matches the <tt>containerUrl</tt>
+ * argument passed to this method.
+ * @param containerUrl the <tt>containerUrl</tt> which is to
+ * be matched.
+ *
+ * @return child <tt>ParcelContainer</tt> or <null> if none
+ * found.
+ */
+
+ public ParcelContainer getChildContainerForURL( String containerUrl )
+ {
+ ParcelContainer result = null;
+ Iterator iter = childContainers.iterator();
+ while ( iter.hasNext() )
+ {
+ ParcelContainer c = (ParcelContainer) iter.next();
+ if ( containerUrl.equals( c.containerUrl ) )
+ {
+ result = c;
+ break;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Returns Name of this container. Name of this <tt>ParcelContainer</tt>
+ * is determined from the <tt>containerUrl</tt> as the last portion
+ * of the URL after the last forward slash.
+ * @return name of <tt>ParcelContainer</tt>
+ * found.
+ */
+ public String getName()
+ {
+ String name = null;
+ // TODO handler package ParcelContainer?
+ if ( !containerUrl.startsWith( "vnd.sun.star.tdoc:" ) )
+ {
+ // return name
+ String decodedUrl = java.net.URLDecoder.decode( containerUrl );
+ int indexOfSlash = decodedUrl.lastIndexOf( "/" );
+ if ( indexOfSlash != -1 )
+ {
+ name = decodedUrl.substring( indexOfSlash + 1 );
+ }
+ }
+ else
+ {
+ name = "document";
+ }
+ return name;
+ }
+
+ /**
+ * Initializes a newly created <code>ParcelContainer</code> object.
+ * @param xCtx UNO component context
+ * @param containerUrl location of this container.
+ * @param language language for which entries are stored
+ * @return name of <tt>ParcelContainer</tt>
+ * @throws IllegalArgumentException
+ * @throws WrappedTargetException
+ */
+
+ public ParcelContainer( XComponentContext xCtx, String containerUrl, String language ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException
+
+ {
+ this( null, xCtx, containerUrl, language, true );
+ }
+
+ /**
+ * Initializes a newly created <code>ParcelContainer</code> object.
+ * @param xCtx UNO component context
+ * @param containerUrl location of this container.
+ * @param language language for which entries are stored
+ * @param loadParcels set to <tt>true</tt> if parcels are to be loaded
+ * on construction.
+ * @return name of <tt>ParcelContainer</tt>
+ * @throws IllegalArgumentException
+ * @throws WrappedTargetException
+ */
+ public ParcelContainer( XComponentContext xCtx, String containerUrl, String language, boolean loadParcels ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException
+ {
+ this( null, xCtx, containerUrl, language, loadParcels );
+ }
+
+ /**
+ * Initializes a newly created <code>ParcelContainer</code> object.
+ * @param parent parent ParcelContainer
+ * @param xCtx UNO component context
+ * @param containerUrl location of this container.
+ * @param language language for which entries are stored
+ * @param loadParcels set to <tt>true</tt> if parcels are to be loaded
+ * on construction.
+ * @return name of <tt>ParcelContainer</tt>
+ * @throws IllegalArgumentException
+ */
+
+ public ParcelContainer( ParcelContainer parent, XComponentContext xCtx, String containerUrl, String language, boolean loadParcels ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException
+
+ {
+ LogUtils.DEBUG("Creating ParcelContainer for " + containerUrl + " loadParcels = " + loadParcels + " language = " + language );
+ this.m_xCtx = xCtx;
+ this.language = language;
+ this.parent = parent;
+ this.containerUrl = containerUrl;
+
+ initSimpleFileAccess();
+ boolean parentIsPkgContainer = false;
+
+ if ( parent != null )
+ {
+ parentIsPkgContainer = parent.isUnoPkg();
+ }
+
+ if ( containerUrl.endsWith("uno_packages") || parentIsPkgContainer )
+ {
+ isPkgContainer = true;
+ }
+
+ if ( loadParcels )
+ {
+ loadParcels();
+ }
+ }
+
+
+ public String getContainerURL() { return this.containerUrl; }
+
+ private synchronized void initSimpleFileAccess()
+ {
+ if ( m_xSFA != null )
+ {
+ return;
+ }
+ try
+ {
+ m_xSFA = ( XSimpleFileAccess )UnoRuntime.queryInterface(
+ XSimpleFileAccess.class,
+ m_xCtx.getServiceManager().createInstanceWithContext(
+ "com.sun.star.ucb.SimpleFileAccess", m_xCtx ) );
+ }
+ catch ( Exception e )
+ {
+ // TODO should throw
+ LogUtils.DEBUG("Error instantiating simplefile access ");
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ }
+ }
+
+ public String getParcelContainerDir()
+ {
+ // If this container does not represent an uno-package
+ // then then it is a document, user or share
+ // in each case the convention is to have a Scripts/[language]
+ // dir where scripts reside
+ if ( !isUnoPkg() )
+ {
+ return PathUtils.make_url( containerUrl , "Scripts/" + language.toLowerCase() );
+ }
+ return containerUrl;
+ }
+ public Object getByName( String aName ) throws com.sun.star.container.NoSuchElementException, WrappedTargetException
+ {
+ Parcel parcel = null;
+ try
+ {
+ if ( hasElements() )
+ {
+ Iterator iter = parcels.iterator();
+ while ( iter.hasNext() )
+ {
+ Parcel parcelToCheck = (Parcel)iter.next();
+
+ if ( parcelToCheck.getName().equals( aName ) )
+ {
+ parcel = parcelToCheck;
+ break;
+ }
+ }
+ }
+ }
+ catch ( Exception e)
+ {
+ throw new WrappedTargetException( e.toString() );
+ }
+ if ( parcel == null )
+ {
+ throw new com.sun.star.container.NoSuchElementException( "Macro Library " + aName + " not found" );
+ }
+ return parcel;
+ }
+ public String[] getElementNames()
+ {
+ if ( hasElements() )
+ {
+ Parcel[] theParcels = (Parcel[])parcels.toArray( new Parcel[0] );
+ String[] names = new String[ theParcels.length ];
+ for ( int count = 0; count < names.length; count++ )
+ {
+ names[count] = theParcels[ count ].getName();
+ }
+ return names;
+ }
+
+ return new String[0];
+ }
+ public boolean hasByName( String aName )
+ {
+ boolean isFound = false;
+ try
+ {
+ if ( getByName( aName ) != null )
+ {
+ isFound = true;
+ }
+
+ }
+ catch ( Exception e )
+ {
+ //TODO - handle trace
+ }
+ return isFound;
+ }
+ public Type getElementType()
+ {
+ return new Type();
+ }
+ public boolean hasElements()
+ {
+ if ( parcels == null || parcels.isEmpty() )
+ {
+ return false;
+ }
+ return true;
+ }
+
+ private void loadParcels() throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException
+ {
+ try
+ {
+ LogUtils.DEBUG("About to load parcels from " + containerUrl );
+ if ( m_xSFA.isFolder( getParcelContainerDir() ) )
+ {
+ LogUtils.DEBUG( getParcelContainerDir() + " is a folder " );
+ String[] children = m_xSFA.getFolderContents( getParcelContainerDir(), true );
+ parcels = new ArrayList(children.length);
+ for ( int i = 0; i < children.length; i++)
+ {
+ LogUtils.DEBUG("Processing " + children[ i ] );
+ try
+ {
+ loadParcel( children[ i ] );
+ }
+ catch (java.lang.Exception e)
+ {
+ // print an error message and move on to
+ // the next parcel
+ LogUtils.DEBUG("ParcelContainer.loadParcels caught " + e.getClass().getName() + " exception loading parcel " + children[i] + ": " + e.getMessage() );
+ }
+ }
+ }
+ else
+ {
+ LogUtils.DEBUG(" ParcelCOntainer.loadParcels " + getParcelContainerDir() + " is not a folder ");
+ }
+
+ }
+ catch ( com.sun.star.ucb.CommandAbortedException e )
+ {
+ LogUtils.DEBUG("ParcelContainer.loadParcels caught exception processing folders for " + getParcelContainerDir() );
+ LogUtils.DEBUG("TRACE: " + LogUtils.getTrace(e) );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+ catch ( com.sun.star.uno.Exception e )
+ {
+ LogUtils.DEBUG("ParcelContainer.loadParcels caught exception processing folders for " + getParcelContainerDir() );
+ LogUtils.DEBUG("TRACE: " + LogUtils.getTrace(e) );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+ }
+
+ public XNameContainer createParcel(String name) throws ElementExistException, com.sun.star.lang.WrappedTargetException
+ {
+ Parcel p = null;
+ if ( hasByName( name ) )
+ {
+ throw new ElementExistException( "Parcel " + name + " already exists" );
+ }
+ String pathToParcel = PathUtils.make_url( getParcelContainerDir() , name );
+
+ try
+ {
+ LogUtils.DEBUG("ParcelContainer.createParcel, creating folder " + pathToParcel );
+ m_xSFA.createFolder( pathToParcel );
+
+ LogUtils.DEBUG("ParcelContainer.createParcel, folder " + pathToParcel + " created ");
+
+ ParcelDescriptor pd = new ParcelDescriptor();
+ pd.setLanguage( language );
+ String parcelDesc = PathUtils.make_url( pathToParcel, ParcelDescriptor.PARCEL_DESCRIPTOR_NAME );
+ XSimpleFileAccess2 xSFA2 = ( XSimpleFileAccess2 )
+ UnoRuntime.queryInterface( XSimpleFileAccess2.class, m_xSFA );
+ if ( xSFA2 != null )
+ {
+ LogUtils.DEBUG("createParcel() Using XSIMPLEFILEACCESS2 " + parcelDesc );
+ ByteArrayOutputStream bos = new ByteArrayOutputStream( 1024 );
+ pd.write( bos );
+ bos.close();
+ ByteArrayInputStream bis = new ByteArrayInputStream( bos.toByteArray() );
+ XInputStreamImpl xis = new XInputStreamImpl( bis );
+ xSFA2.writeFile( parcelDesc, xis );
+ xis.closeInput();
+ p = loadParcel( pathToParcel );
+ }
+ }
+ catch ( Exception e )
+ {
+
+ LogUtils.DEBUG("createParcel() Exception while attempting to create = " + name );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+ return p;
+ }
+
+ public Parcel loadParcel( String parcelUrl ) throws com.sun.star.lang.WrappedTargetException, com.sun.star.lang.IllegalArgumentException
+ {
+
+ String name = null;
+
+ String parcelDescUrl = PathUtils.make_url( parcelUrl, ParcelDescriptor.PARCEL_DESCRIPTOR_NAME );
+ Parcel parcel = null;
+
+ XInputStream xis = null;
+ InputStream is = null;
+
+ try
+ {
+ if ( m_xSFA.exists( parcelDescUrl ) )
+ {
+ LogUtils.DEBUG("ParcelContainer.loadParcel opening " + parcelDescUrl );
+ xis = m_xSFA.openFileRead( parcelDescUrl );
+ is = new XInputStreamWrapper( xis );
+
+ ParcelDescriptor pd = new ParcelDescriptor(is) ;
+ try
+ {
+ is.close();
+ is = null;
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG("ParcelContainer.loadParcel Exception when closing stream for " + parcelDescUrl + " :" + e );
+ }
+ LogUtils.DEBUG("ParcelContainer.loadParcel closed " + parcelDescUrl );
+ if ( !pd.getLanguage().equals( language ) )
+ {
+ LogUtils.DEBUG("ParcelContainer.loadParcel Language of Parcel does not match this container ");
+ return null;
+ }
+ LogUtils.DEBUG("Processing " + parcelDescUrl + " closed " );
+
+ int indexOfSlash = parcelUrl.lastIndexOf("/");
+ name = parcelUrl.substring( indexOfSlash + 1 );
+
+ parcel = new Parcel( m_xSFA, this, pd, name );
+
+ LogUtils.DEBUG(" ParcelContainer.loadParcel created parcel for " + parcelDescUrl + " for language " + language );
+ parcels.add( parcel );
+ }
+ else
+ {
+ throw new java.io.IOException( parcelDescUrl + " does NOT exist!");
+ }
+ }
+ catch ( com.sun.star.ucb.CommandAbortedException e )
+ {
+
+ LogUtils.DEBUG("loadParcel() Exception while accessing filesystem url = " + parcelDescUrl + e );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+ catch ( java.io.IOException e )
+ {
+ LogUtils.DEBUG("ParcelContainer.loadParcel() caught IOException while accessing " + parcelDescUrl + ": " + e );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+ catch ( com.sun.star.uno.Exception e )
+ {
+
+ LogUtils.DEBUG("loadParcel() Exception while accessing filesystem url = " + parcelDescUrl + e );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+
+ finally
+ {
+ if ( is != null )
+ {
+ try
+ {
+ is.close(); // is will close xis
+ }
+ catch ( Exception ignore )
+ {
+ }
+ }
+ else if ( xis != null )
+ {
+ try
+ {
+ xis.closeInput();
+ }
+ catch ( Exception ignore )
+ {
+ }
+ }
+ }
+ return parcel;
+ }
+ public void renameParcel(String oldName, String newName) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ LogUtils.DEBUG(" ** ParcelContainer Renaming parcel " + oldName + " to " + newName );
+ LogUtils.DEBUG(" ** ParcelContainer is " + this );
+ Parcel p = (Parcel)getByName( oldName );
+ if ( p == null )
+ {
+ throw new com.sun.star.container.NoSuchElementException( "No parcel named " + oldName );
+ }
+ String oldParcelDirUrl = PathUtils.make_url( getParcelContainerDir(),
+ oldName );
+ String newParcelDirUrl = PathUtils.make_url( getParcelContainerDir(),
+ newName );
+ try
+ {
+ if (!m_xSFA.isFolder( oldParcelDirUrl ) )
+ {
+ Exception e = new com.sun.star.io.IOException("Invalid Parcel directory: " + oldName );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+ LogUtils.DEBUG(" ** ParcelContainer Renaming folder " + oldParcelDirUrl + " to " + newParcelDirUrl );
+ m_xSFA.move( oldParcelDirUrl, newParcelDirUrl );
+ }
+ catch ( com.sun.star.ucb.CommandAbortedException ce )
+ {
+ LogUtils.DEBUG(" ** ParcelContainer Renaming failed with " + ce );
+ throw new com.sun.star.lang.WrappedTargetException( ce.toString() );
+ }
+ catch ( com.sun.star.uno.Exception e )
+ {
+ LogUtils.DEBUG(" ** ParcelContainer Renaming failed with " + e );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+
+ p.rename( newName );
+ }
+ // removes but doesn't physically delele parcel from container
+ public boolean removeParcel(String name) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ boolean result = false;
+ Parcel p = (Parcel)getByName( name );
+ if ( p == null )
+ {
+ throw new com.sun.star.container.NoSuchElementException("No parcel named " + name );
+ }
+
+ result = parcels.remove( p );
+ return result;
+ }
+ public boolean deleteParcel(String name) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ LogUtils.DEBUG( "deleteParcel for containerURL " + containerUrl + " name = " + name + " Langueg = " + language );
+ boolean result = false;
+
+ Parcel p = (Parcel)getByName( name );
+ if ( p == null )
+ {
+ throw new com.sun.star.container.NoSuchElementException("No parcel named " + name );
+ }
+
+ try
+ {
+ String pathToParcel = PathUtils.make_url( getParcelContainerDir(), name );
+ m_xSFA.kill( pathToParcel );
+ }
+ catch( Exception e )
+ {
+ LogUtils.DEBUG("Error deleteing parcel " + name );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString() );
+ }
+
+ result = parcels.remove( p );
+ return result;
+ }
+
+ public String getLanguage() { return language; }
+
+ public ScriptMetaData findScript( ParsedScriptUri parsedUri ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ ScriptMetaData scriptData = null;
+ Parcel p = null;
+ p = (Parcel)getByName( parsedUri.parcel);
+ scriptData = (ScriptMetaData)p.getByName( parsedUri.function);
+ LogUtils.DEBUG("** found script data for " + parsedUri.function + " script is " + scriptData );
+ return scriptData;
+
+ }
+public ParsedScriptUri parseScriptUri( String scriptURI ) throws com.sun.star.lang.IllegalArgumentException
+{
+
+ XMultiComponentFactory xMcFac = null;
+ XUriReferenceFactory xFac = null;
+
+ try
+ {
+ xMcFac = m_xCtx.getServiceManager();
+ xFac = ( XUriReferenceFactory )
+ UnoRuntime.queryInterface( XUriReferenceFactory.class,
+ xMcFac.createInstanceWithContext(
+ "com.sun.star.uri.UriReferenceFactory", m_xCtx ) );
+ }
+ catch( com.sun.star.uno.Exception e )
+ {
+ LogUtils.DEBUG("Problems parsing URL:" + e.toString() );
+ throw new com.sun.star.lang.IllegalArgumentException( "Problems parsing URL reason: " + e.toString() );
+ }
+ if ( xFac == null )
+ {
+ LogUtils.DEBUG("Failed to create UrlReference factory");
+ throw new com.sun.star.lang.IllegalArgumentException( "Failed to create UrlReference factory for url " + scriptURI );
+ }
+
+ XUriReference uriRef = xFac.parse( scriptURI );
+ XVndSunStarScriptUrl sfUri = ( XVndSunStarScriptUrl )
+ UnoRuntime.queryInterface( XVndSunStarScriptUrl.class, uriRef );
+
+ if ( sfUri == null )
+ {
+ LogUtils.DEBUG("Failed to parse url");
+ throw new com.sun.star.lang.IllegalArgumentException( "Failed to parse url " + scriptURI );
+ }
+
+ ParsedScriptUri parsedUri = new ParsedScriptUri();
+ // parse language
+ parsedUri.language = sfUri.getParameter("language");
+ parsedUri.function= sfUri.getName();
+ parsedUri.parcel = "";
+
+ // parse parcel name;
+ StringTokenizer tokenizer = new StringTokenizer( parsedUri.function, "." );
+
+ if ( tokenizer.hasMoreElements() )
+ {
+ parsedUri.parcel = (String)tokenizer.nextElement();
+ LogUtils.DEBUG("** parcelName = " + parsedUri.parcel );
+ }
+
+ if ( parsedUri.function != null && ( parsedUri.function.length() > 0 ) )
+ {
+ // strip out parcel name
+ parsedUri.function = parsedUri.function.substring( parsedUri.parcel.length() + 1);
+ }
+
+ // parse location
+ parsedUri.location = sfUri.getParameter("location");
+
+ // TODO basic sanity check on language, location, functioname, parcel
+ // should be correct e.g. verified by MSP and LangProvider by the
+ // time its got to here
+
+ LogUtils.DEBUG("** location = " + parsedUri.location +
+ "\nfunction = " + parsedUri.function +
+ "\nparcel = " + parsedUri.parcel +
+ "\nlocation = " + parsedUri.location );
+ return parsedUri;
+}
+
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/container/ParcelDescriptor.java b/scripting/java/com/sun/star/script/framework/container/ParcelDescriptor.java
new file mode 100644
index 000000000000..1a6047734a07
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/container/ParcelDescriptor.java
@@ -0,0 +1,453 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDescriptor.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.script.framework.container;
+
+import java.io.File;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.FileNotFoundException;
+import java.io.ByteArrayInputStream;
+
+import java.util.ArrayList;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Enumeration;
+import java.util.Iterator;
+
+// import javax.xml.parsers.DocumentBuilderFactory;
+// import javax.xml.parsers.DocumentBuilder;
+// import javax.xml.parsers.ParserConfigurationException;
+
+import org.w3c.dom.*;
+
+public class ParcelDescriptor {
+
+ // File name to be used for parcel descriptor files
+ public static final String
+ PARCEL_DESCRIPTOR_NAME = "parcel-descriptor.xml";
+
+ // Collection of all ParcelDescriptor created for files
+ private static final Map PARCEL_DESCRIPTOR_MAP = new HashMap(5);
+
+ // This is the default contents of a parcel descriptor to be used when
+ // creating empty descriptors
+ private static final byte[] EMPTY_DOCUMENT =
+ ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
+ "<parcel xmlns:parcel=\"scripting.dtd\" language=\"Java\">\n" +
+ "</parcel>").getBytes();
+
+ private File file = null;
+ private Document document = null;
+ private String language = null;
+ private Map languagedepprops = new Hashtable(3);
+
+ public static synchronized void removeParcelDescriptor(File parent) {
+ File path = new File(parent, PARCEL_DESCRIPTOR_NAME);
+ PARCEL_DESCRIPTOR_MAP.remove(path);
+ }
+
+ public static synchronized void renameParcelDescriptor(File oldFile, File newFile) {
+ File oldPath = new File(oldFile, PARCEL_DESCRIPTOR_NAME);
+ ParcelDescriptor pd = (ParcelDescriptor)PARCEL_DESCRIPTOR_MAP.get(oldPath);
+ if(pd != null) {
+ PARCEL_DESCRIPTOR_MAP.remove(oldPath);
+ File newPath = new File(newFile, PARCEL_DESCRIPTOR_NAME);
+ pd.file = newPath;
+ PARCEL_DESCRIPTOR_MAP.put(newPath, pd);
+ }
+ }
+
+ // returns the ParcelDescriptor in the corresponding directory
+ // returns null if no ParcelDescriptor is found in the directory
+ public static synchronized ParcelDescriptor
+ getParcelDescriptor(File parent) {
+
+ File path = new File(parent, PARCEL_DESCRIPTOR_NAME);
+ ParcelDescriptor pd = (ParcelDescriptor)PARCEL_DESCRIPTOR_MAP.get(path);
+
+ if (pd == null && path.exists()) {
+ try {
+ pd = new ParcelDescriptor(path);
+ }
+ catch (IOException ioe) {
+ return null;
+ }
+ PARCEL_DESCRIPTOR_MAP.put(path, pd);
+ }
+ return pd;
+ }
+
+ // returns a ParcelDescriptor for the corresponding directory
+ // if no ParcelDescriptor exists, one is created
+ public static synchronized ParcelDescriptor
+ createParcelDescriptor(File parent) throws IOException {
+
+ ParcelDescriptor pd = getParcelDescriptor(parent);
+
+ if (pd == null) {
+ if (parent == null || !parent.exists() || !parent.isDirectory()) {
+ throw new IOException("Cannot create Parcel Descriptor");
+ }
+
+ File path = new File(parent, PARCEL_DESCRIPTOR_NAME);
+ pd = new ParcelDescriptor(path);
+ PARCEL_DESCRIPTOR_MAP.put(path, pd);
+ }
+ return pd;
+ }
+
+ public ParcelDescriptor() throws IOException {
+ ByteArrayInputStream bis = null;
+ try {
+ bis = new ByteArrayInputStream(EMPTY_DOCUMENT);
+ this.document = XMLParserFactory.getParser().parse(bis);
+ }
+ finally {
+ if (bis != null)
+ bis.close();
+ }
+ }
+
+ public ParcelDescriptor(Document document) {
+ this.document = document;
+ initLanguageProperties();
+ }
+
+ public ParcelDescriptor(InputStream is) throws IOException {
+ this(XMLParserFactory.getParser().parse(is));
+ }
+
+ public ParcelDescriptor(File file) throws IOException {
+ this(file, "Java");
+ }
+
+ public ParcelDescriptor(File file, String language) throws IOException {
+ this.file = file;
+
+ if (file.exists()) {
+ FileInputStream fis = null;
+ try {
+ fis = new FileInputStream(file);
+ this.document = XMLParserFactory.getParser().parse(fis);
+ }
+ finally {
+ if (fis != null)
+ fis.close();
+ }
+ }
+ else {
+ ByteArrayInputStream bis = null;
+ try {
+ bis = new ByteArrayInputStream(EMPTY_DOCUMENT);
+ this.document = XMLParserFactory.getParser().parse(bis);
+ }
+ finally {
+ if (bis != null)
+ bis.close();
+ }
+ setLanguage(language);
+ }
+ initLanguageProperties();
+ }
+
+ public void write(File file) throws IOException {
+ FileOutputStream fos = new FileOutputStream(file);
+ XMLParserFactory.getParser().write(document, fos);
+ fos.close();
+ }
+
+ public void write() throws IOException {
+ if (file == null)
+ throw new FileNotFoundException("No file specified");
+
+ write(file);
+ }
+
+ public void write(OutputStream out) throws IOException {
+ XMLParserFactory.getParser().write(document, out);
+ }
+
+ public Document getDocument() {
+ return document;
+ }
+
+ public String getLanguage() {
+ if (language == null) {
+ if (document != null) {
+ Element e = document.getDocumentElement();
+ language = e.getAttribute("language");
+ }
+ }
+ return language;
+ }
+
+ public void setLanguage(String language) {
+ this.language = language;
+
+ if (document != null) {
+ try {
+ Element e = document.getDocumentElement();
+ e.setAttribute("language", language);
+ }
+ catch (DOMException de) {
+ }
+ }
+ }
+
+ public ScriptEntry[] getScriptEntries() {
+ ArrayList scripts = new ArrayList();
+ NodeList scriptNodes;
+ int len;
+
+ if (document == null ||
+ (scriptNodes = document.getElementsByTagName("script")) == null ||
+ (len = scriptNodes.getLength()) == 0)
+ return new ScriptEntry[0];
+
+ for (int i = 0; i < len; i++) {
+ String language, languagename, logicalname, description = "";
+ Map langProps = new HashMap();
+ NodeList nl;
+ Element tmp;
+
+ Element scriptElement = (Element)scriptNodes.item(i);
+ language = scriptElement.getAttribute("language");
+
+ nl = scriptElement.getElementsByTagName("logicalname");
+ if (nl == null)
+ logicalname = "";
+ else {
+ tmp = (Element)nl.item(0);
+ logicalname = tmp.getAttribute("value");
+ }
+
+ // get the text of the description element
+ nl = scriptElement.getElementsByTagName("locale");
+ if (nl != null)
+ {
+ nl = nl.item(0).getChildNodes();
+ if (nl != null)
+ {
+ for (int j = 0 ; j < nl.getLength(); j++)
+ {
+ if (nl.item(j).getNodeName().equals("description"))
+ {
+ CharacterData cd =
+ (CharacterData)nl.item(j).getFirstChild();
+ description = cd.getData().trim();
+ }
+ }
+ }
+ }
+
+ nl = scriptElement.getElementsByTagName("functionname");
+ if (nl == null) {
+ languagename = "";
+ } else {
+ tmp = (Element)nl.item(0);
+ languagename = tmp.getAttribute("value");
+ }
+ nl = scriptElement.getElementsByTagName("languagedepprops");
+ if ( nl != null && nl.getLength() > 0 )
+ {
+
+ NodeList props = ((Element)nl.item(0)).getElementsByTagName("prop");
+ if ( props != null )
+ {
+ for ( int j=0; j < props.getLength(); j++ )
+ {
+ tmp = (Element)props.item(j);
+ String key = tmp.getAttribute("name");
+ String val = tmp.getAttribute("value");
+ langProps.put( key,val );
+ }
+ }
+ }
+ ScriptEntry entry = new ScriptEntry(language, languagename, logicalname, "",langProps, description);
+ scripts.add(entry);
+ }
+ return (ScriptEntry[])scripts.toArray(new ScriptEntry[0]);
+ }
+
+ public void setScriptEntries(ScriptEntry[] scripts) {
+ clearEntries();
+ for (int i = 0; i < scripts.length; i++)
+ addScriptEntry(scripts[i]);
+ }
+
+ public void setScriptEntries(Enumeration scripts) {
+ clearEntries();
+ while (scripts.hasMoreElements())
+ addScriptEntry((ScriptEntry) scripts.nextElement());
+ }
+
+ public String getLanguageProperty(String name) {
+ return (String)languagedepprops.get(name);
+ }
+
+ public void setLanguageProperty(String name, String value) {
+ languagedepprops.put(name, value);
+ setScriptEntries(getScriptEntries());
+ }
+
+ private void initLanguageProperties() {
+ NodeList nl = document.getElementsByTagName("languagedepprops");
+ int len;
+
+ if (nl != null && (len = nl.getLength()) != 0) {
+
+ for (int i = 0; i < len; i++) {
+ Element e = (Element)nl.item(i);
+ NodeList nl2 = e.getElementsByTagName("prop");
+ int len2;
+
+ if (nl2 != null && (len2 = nl2.getLength()) != 0) {
+ for (int j = 0; j < len2; j++) {
+ Element e2 = (Element)nl2.item(j);
+
+ String name = e2.getAttribute("name");
+ String value = e2.getAttribute("value");
+
+ if (getLanguageProperty(name) == null) {
+ languagedepprops.put(name, value);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private void clearEntries() {
+ NodeList scriptNodes;
+ Element main = document.getDocumentElement();
+ int len;
+
+ if ((scriptNodes = document.getElementsByTagName("script")) != null &&
+ (len = scriptNodes.getLength()) != 0)
+ {
+ for (int i = len - 1; i >= 0; i--) {
+ try {
+ main.removeChild(scriptNodes.item(i));
+ }
+ catch (DOMException de) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ public void removeScriptEntry(ScriptEntry script) {
+ NodeList scriptNodes;
+ Element main = document.getDocumentElement();
+ int len;
+
+ if ((scriptNodes = document.getElementsByTagName("script")) != null &&
+ (len = scriptNodes.getLength()) != 0)
+ {
+ for (int i = len - 1; i >= 0; i--) {
+ try {
+ Element scriptElement = (Element)scriptNodes.item(i);
+ String languagename = "";
+
+ NodeList nl =
+ scriptElement.getElementsByTagName("functionname");
+ if (nl == null) {
+ continue;
+ } else {
+ Element tmp = (Element)nl.item(0);
+ languagename = tmp.getAttribute("value");
+ }
+
+ if (languagename.equals(script.getLanguageName())) {
+ main.removeChild(scriptElement);
+ }
+ }
+ catch (DOMException de) {
+ // ignore
+ }
+ }
+ }
+ }
+
+ public void addScriptEntry(ScriptEntry script) {
+ Element main = document.getDocumentElement();
+ Element root, item, tempitem;
+
+ root = document.createElement("script");
+ root.setAttribute("language", script.getLanguage());
+
+ item = document.createElement("locale");
+ item.setAttribute("lang", "en");
+ tempitem = document.createElement("displayname");
+ tempitem.setAttribute("value", script.getLogicalName());
+ item.appendChild(tempitem);
+
+ tempitem = document.createElement("description");
+ String description = script.getDescription();
+ if (description == null || description.equals(""))
+ {
+ description = script.getLogicalName();
+ }
+ tempitem.appendChild(document.createTextNode(description));
+ item.appendChild(tempitem);
+
+ root.appendChild(item);
+
+ item = document.createElement("logicalname");
+ item.setAttribute("value", script.getLogicalName());
+ root.appendChild(item);
+
+ item = document.createElement("functionname");
+ item.setAttribute("value", script.getLanguageName());
+ root.appendChild(item);
+
+ if (languagedepprops != null && languagedepprops.size() != 0) {
+ String key;
+ item = document.createElement("languagedepprops");
+
+ Iterator iter = languagedepprops.keySet().iterator();
+ while (iter.hasNext()) {
+ tempitem = document.createElement("prop");
+ key = (String)iter.next();
+ tempitem.setAttribute("name", key);
+ tempitem.setAttribute("value", (String)languagedepprops.get(key));
+ item.appendChild(tempitem);
+ }
+ root.appendChild(item);
+ }
+
+ //add to the Top Element
+ main.appendChild(root);
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/container/ParsedScriptUri.java b/scripting/java/com/sun/star/script/framework/container/ParsedScriptUri.java
new file mode 100644
index 000000000000..dda6ddbabd93
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/container/ParsedScriptUri.java
@@ -0,0 +1,39 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParsedScriptUri.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.container;
+
+public class ParsedScriptUri
+{
+ public String language;
+ public String location;
+ public String function;
+ public String parcel;
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/container/ScriptEntry.java b/scripting/java/com/sun/star/script/framework/container/ScriptEntry.java
new file mode 100644
index 000000000000..f33f9637a9a8
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/container/ScriptEntry.java
@@ -0,0 +1,131 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptEntry.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.container;
+import java.util.Map;
+import java.util.HashMap;
+public class ScriptEntry implements Cloneable {
+
+ private String language;
+ private String languagename;
+ private String location;
+ private String logicalname = "";
+ private String description = "";
+
+ private Map languagedepprops;
+
+ public ScriptEntry(String language, String languagename,
+ String logicalname, String location) {
+ this.language = language;
+ this.languagename = languagename;
+ // logical name/ function name concept
+ // needs to be reworked, in meantime
+ // function name ( from xml ) will be used
+ // as logical name also
+ this.logicalname = languagename;
+ this.location = location;
+ this.languagedepprops = new HashMap();
+ }
+
+ public ScriptEntry(ScriptEntry entry)
+ {
+ this.language = entry.language;
+ this.languagename = entry.languagename;
+ this.logicalname = entry.languagename;
+ this.location = entry.location;
+ this.languagedepprops = entry.languagedepprops;
+ this.description = entry.description;
+ }
+
+ public ScriptEntry(String language, String languagename,
+ String logicalname, String location, Map languagedepprops) {
+ this( language, languagename, logicalname, location );
+ this.languagedepprops = languagedepprops;
+ }
+
+ public ScriptEntry(String language, String languagename,
+ String logicalname, String location,
+ Map languagedepprops, String description) {
+ this( language, languagename, logicalname, location );
+ this.languagedepprops = languagedepprops;
+ this.description = description;
+ }
+
+ public ScriptEntry(String languagename, String location) {
+ this("Java", languagename, languagename, location);
+ }
+
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+
+ public boolean equals(ScriptEntry other) {
+ if (language.equals(other.getLanguage()) &&
+ languagename.equals(other.getLanguageName()) &&
+ logicalname.equals(other.getLogicalName()) &&
+ languagedepprops.equals(other.getLanguageProperties()) &&
+ location.equals(other.getLocation()))
+ return true;
+ return false;
+ }
+
+ public Map getLanguageProperties()
+ {
+ return languagedepprops;
+ }
+
+ public String getLanguageName() {
+ return languagename;
+ }
+
+ public String getLogicalName() {
+ return logicalname;
+ }
+
+ public void setLogicalName(String name) {
+ logicalname = name;
+ }
+
+ public String getLanguage() {
+ return language;
+ }
+
+ public String getLocation() {
+ return location;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String toString() {
+ return "\nLogicalName = " + logicalname + "\nLanguageName = " + languagename + "\nLocation = " + location + "\nLanguaguageProperties = " + languagedepprops;
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/container/ScriptMetaData.java b/scripting/java/com/sun/star/script/framework/container/ScriptMetaData.java
new file mode 100644
index 000000000000..a415b02470a4
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/container/ScriptMetaData.java
@@ -0,0 +1,413 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptMetaData.java,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.container;
+
+import java.net.URL;
+
+import java.io.ByteArrayInputStream;
+
+import java.util.Vector;
+import java.util.StringTokenizer;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import com.sun.star.script.framework.log.LogUtils;
+
+import com.sun.star.script.framework.provider.PathUtils;
+
+import com.sun.star.script.framework.io.XInputStreamImpl;
+
+import com.sun.star.script.framework.container.ScriptEntry;
+import com.sun.star.script.framework.container.Parcel;
+
+import com.sun.star.script.framework.io.UCBStreamHandler;
+
+import com.sun.star.ucb.XSimpleFileAccess2;
+
+import com.sun.star.uno.UnoRuntime;
+
+public class ScriptMetaData extends ScriptEntry implements Cloneable {
+ private boolean hasSource = false;
+ private String locationPlaceHolder = "";
+ private String source;
+ private Parcel parent;
+
+
+ public ScriptMetaData( Parcel parent, ScriptEntry entry,
+ String source )
+ {
+ super( entry );
+ this.parent = parent;
+ if ( source != null )
+ {
+ this.hasSource = true;
+ this.source = source;
+ }
+
+ }
+
+ public boolean hasSource()
+ {
+ return hasSource;
+ }
+ public String getSource()
+ {
+
+ if ( source !=null && hasSource )
+ {
+ return source;
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+ public byte[] getSourceBytes()
+ {
+ if ( source !=null && hasSource )
+ {
+ return source.getBytes();
+ }
+ else
+ {
+ return null;
+ }
+
+ }
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+
+ public boolean equals(ScriptMetaData other) {
+ if (super.equals(other) &&
+ hasSource == other.hasSource() )
+ {
+ return true;
+ }
+ return false;
+ }
+
+ public String getScriptFullURL()
+ {
+ String url = "vnd.sun.star.script:" + parent.getName() + "." + getLanguageName() +
+ "?" + "language=" + getLanguage() +
+ "&location=" + getParcelLocation();
+ return url;
+ }
+
+ public String getShortFormScriptURL()
+ {
+ String url = "vnd.sun.star.script:" + parent.getName() + "." + getLanguageName() +
+ "?" + "language=" + getLanguage() +
+ "&location=" + getLocationPlaceHolder();
+ return url;
+ }
+
+ // TODO probably should be private should not be necessary
+ // to be exposed at all
+
+ private static final String SHARE =
+ "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" +
+ PathUtils.BOOTSTRAP_NAME +
+ "::BaseInstallation}/share";
+
+ private static final String USER =
+ "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" +
+ PathUtils.BOOTSTRAP_NAME +
+ "::UserInstallation}/user";
+
+ private static final String UNO_USER_PACKAGES1 =
+ "vnd.sun.star.expand:$UNO_USER_PACKAGES_CACHE";
+
+ private static final String UNO_USER_PACKAGES2 =
+ USER + "/uno_packages";
+
+ private static final String UNO_SHARED_PACKAGES1 =
+ "$UNO_SHARED_PACKAGES_CACHE";
+
+ private static final String UNO_SHARED_PACKAGES2 =
+ SHARE + "/uno_packages";
+
+ public static String getLocationPlaceHolder(String url, String pkgname)
+ {
+ String result = "Unknown";
+
+ if ( url.indexOf(UNO_USER_PACKAGES1) > -1 ||
+ url.indexOf(UNO_USER_PACKAGES2) > -1 )
+ {
+ result = PathUtils.make_url( "user:uno_packages", pkgname );
+ }
+ else if ( url.indexOf(UNO_SHARED_PACKAGES1) > -1 ||
+ url.indexOf(UNO_SHARED_PACKAGES2) > -1 )
+ {
+ result = PathUtils.make_url( "share:uno_packages", pkgname );
+ }
+ else if ( url.indexOf(SHARE) == 0 )
+ {
+ result = "share";
+ }
+ else if ( url.indexOf(USER) == 0 )
+ {
+ result = "user";
+ }
+ else if ( url.indexOf("vnd.sun.star.tdoc:") == 0 )
+ {
+ result = "document";
+ }
+ return result;
+ }
+
+ public String getLocationPlaceHolder()
+ {
+ String placeHolder = "Unknown";
+ String pathToParcel = parent.getPathToParcel();
+
+ if ( pathToParcel.indexOf(UNO_USER_PACKAGES1) > -1 ||
+ pathToParcel.indexOf(UNO_USER_PACKAGES2) > -1 )
+ {
+ // its a package
+ placeHolder = "user:uno_packages";
+ String unoPkg = parent.parent.getName();
+ if ( unoPkg != null )
+ {
+ placeHolder = PathUtils.make_url( placeHolder, unoPkg );
+ }
+ }
+ else if ( pathToParcel.indexOf(UNO_SHARED_PACKAGES1) > -1 ||
+ pathToParcel.indexOf(UNO_SHARED_PACKAGES2) > -1 )
+ {
+ //its a package
+ placeHolder = "share:uno_packages";
+ String unoPkg = parent.parent.getName();
+ if ( unoPkg != null )
+ {
+ placeHolder = PathUtils.make_url( placeHolder, unoPkg );
+ }
+ }
+ else if ( pathToParcel.indexOf(SHARE) == 0 )
+ {
+ placeHolder = "share";
+ }
+ else if ( pathToParcel.indexOf(USER) == 0 )
+ {
+ placeHolder = "user";
+ }
+ else if ( pathToParcel.indexOf("vnd.sun.star.tdoc:") == 0 )
+ {
+ placeHolder = "document";
+ }
+ // TODO handling document packages ??? not really sure of package url
+/* else
+ {
+ } */
+ return placeHolder;
+ }
+
+ // TODO probably should be private should not be necessary
+ // to be exposed at all only used in lang providers at the moment
+ // to generate URL for script, editors should use a model of script
+ // source and not interact with the URL
+ // Also if it is to remain needs to be renamed to getParcelLocationURL
+
+ // return URL string to parcel
+ public String getParcelLocation()
+ {
+ return parent.getPathToParcel();
+ }
+
+
+ public String toString()
+ {
+ return "\nParcelLocation = " + getParcelLocation() + "\nLocationPlaceHolder = " + locationPlaceHolder + super.toString();
+ }
+
+ public URL[] getClassPath() throws java.net.MalformedURLException
+ {
+ try
+ {
+ String classpath = (String)getLanguageProperties().get("classpath");
+ Vector paths = null;
+
+ if ( classpath == null )
+ {
+ classpath = "";
+ }
+
+ String parcelPath = getParcelLocation();
+ // make sure path ends with /
+ if ( !parcelPath.endsWith("/") )
+ {
+ parcelPath += "/";
+ }
+
+ // replace \ with /
+ parcelPath = parcelPath.replace( '\\', '/' );
+
+ Vector classPathVec = new Vector();
+ StringTokenizer stk = new StringTokenizer(classpath, ":");
+ while ( stk.hasMoreElements() )
+ {
+ String relativeClasspath = (String)stk.nextElement();
+ String pathToProcess = PathUtils.make_url( parcelPath, relativeClasspath);
+ URL url = createURL( pathToProcess );
+ if ( url != null )
+ {
+ classPathVec.add ( url );
+ }
+
+ }
+ if ( classPathVec.size() == 0)
+ {
+ URL url = createURL( parcelPath );
+ if ( url != null )
+ {
+ classPathVec.add(url);
+ }
+ }
+
+ return (URL[])classPathVec.toArray( new URL[0]);
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG("Failed to build class path " + e.toString() );
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ return new URL[0];
+ }
+
+ }
+ private URL createURL( String path ) throws java.net.MalformedURLException
+ {
+ URL url = null;
+ int indexOfColon = path.indexOf(":");
+ String scheme = path.substring( 0, indexOfColon );
+ UCBStreamHandler handler = new UCBStreamHandler( parent.parent.m_xCtx, scheme, parent.m_xSFA);
+
+ path += UCBStreamHandler.separator;
+ url = new URL(null, path, handler);
+ return url;
+ }
+
+ // TODO should decide whether this should throw or not
+ // decide whether it should be public or protected ( final ? )
+ public void loadSource()
+ {
+ try
+ {
+ URL sourceUrl = getSourceURL();
+ LogUtils.DEBUG("** In load source BUT not loading yet for " + sourceUrl );
+
+ if ( sourceUrl != null )
+ {
+ StringBuffer buf = new StringBuffer();
+ InputStream in = sourceUrl.openStream();
+
+ byte[] contents = new byte[1024];
+ int len = 0;
+
+ while ((len = in.read(contents, 0, 1024)) != -1) {
+ buf.append(new String(contents, 0, len));
+ }
+
+ try {
+ in.close();
+ }
+ catch (java.io.IOException ignore ) {
+ LogUtils.DEBUG("** Failed to read scriot from url " + ignore.toString() );
+ }
+
+ source = buf.toString();
+ hasSource = true;
+ }
+ }
+ catch (java.io.IOException e) {
+ LogUtils.DEBUG("** Failed to read scriot from url " + e.toString());
+ }
+
+ }
+ protected boolean writeSourceFile()
+ {
+ String parcelLocation = parent.getPathToParcel();
+ String sourceFilePath = parent.getPathToParcel() + "/" + getLanguageName();
+ boolean result = false;
+ OutputStream os = null;
+ try
+ {
+ XSimpleFileAccess2 xSFA2 = ( XSimpleFileAccess2 )
+ UnoRuntime.queryInterface( XSimpleFileAccess2.class,
+ parent.m_xSFA );
+ if ( xSFA2 != null )
+ {
+ ByteArrayInputStream bis = new ByteArrayInputStream( getSourceBytes() );
+ XInputStreamImpl xis = new XInputStreamImpl( bis );
+ xSFA2.writeFile( sourceFilePath, xis );
+ xis.closeInput();
+ result = true;
+ }
+ }
+ // TODO re-examine exception processing should probably throw
+ // exceptions back to caller
+ catch ( Exception ignore )
+
+ {
+ }
+ return result;
+ }
+ protected boolean removeSourceFile()
+ {
+ String parcelLocation = parent.getPathToParcel();
+ String sourceFilePath = parcelLocation + "/" + getLanguageName();
+ boolean result = false;
+ try
+ {
+ parent.m_xSFA.kill( sourceFilePath );
+ result = true;
+ }
+ // TODO reexamine exception handling
+ catch ( Exception e )
+ {
+ }
+ return result;
+ }
+
+ public URL getSourceURL() throws java.net.MalformedURLException
+ {
+ String sUrl = null;
+ URL scriptURL = null;
+
+ sUrl = getParcelLocation();
+ sUrl = PathUtils.make_url( sUrl, getLanguageName() );
+ LogUtils.DEBUG("Creating script url for " + sUrl );
+ scriptURL = createURL( sUrl );
+ return scriptURL;
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/container/UnoPkgContainer.java b/scripting/java/com/sun/star/script/framework/container/UnoPkgContainer.java
new file mode 100644
index 000000000000..40eb7080aa32
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/container/UnoPkgContainer.java
@@ -0,0 +1,424 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: UnoPkgContainer.java,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.script.framework.container;
+
+import com.sun.star.script.framework.log.LogUtils;
+import com.sun.star.script.framework.provider.PathUtils;
+import com.sun.star.script.framework.io.XOutputStreamWrapper;
+import com.sun.star.script.framework.io.XInputStreamWrapper;
+
+import java.util.Map;
+import java.util.HashMap;
+import java.io.OutputStream;
+import java.io.InputStream;
+
+import com.sun.star.uno.XComponentContext;
+
+import com.sun.star.uno.UnoRuntime;
+
+import com.sun.star.io.XOutputStream;
+import com.sun.star.io.XTruncate;
+
+import com.sun.star.deployment.XPackage;
+
+public class UnoPkgContainer extends ParcelContainer
+{
+
+ private Map registeredPackages = new HashMap();
+
+ public UnoPkgContainer( XComponentContext xCtx, String locationURL, String language ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException
+ {
+ super( xCtx, locationURL, language, false );
+ init();
+ }
+
+ // gets the ParcelContainer for persisted uno packages
+ public ParcelContainer getRegisteredUnoPkgContainer( String url )
+ {
+ if (!url.endsWith("/"))
+ {
+ url += "/";
+ }
+
+ LogUtils.DEBUG("** getRegisterPackage ctx = " + containerUrl );
+ LogUtils.DEBUG("** getRegisterPackage for uri " + url );
+ LogUtils.DEBUG("** getRegisterPackage for langugage " + language );
+ ParcelContainer result = (ParcelContainer)registeredPackages.get( url );
+ LogUtils.DEBUG("getRegisterPackage result is " + result );
+ return result;
+ }
+
+ public boolean hasRegisteredUnoPkgContainer( String url )
+ {
+ boolean result = false;
+ if ( getRegisteredUnoPkgContainer( url ) != null )
+ {
+ result = true;
+ }
+ return result;
+ }
+
+ private void registerPackageContainer( String url, ParcelContainer c )
+ {
+ if (!url.endsWith("/"))
+ {
+ url += "/";
+ }
+
+ LogUtils.DEBUG("RegisterPackage ctx = " + containerUrl );
+ LogUtils.DEBUG("RegisterPackage language = " + language );
+ LogUtils.DEBUG("RegisterPackage " + c + " for url " + url );
+ registeredPackages.put( url, c );
+ }
+
+ public void deRegisterPackageContainer( String url )
+ {
+ if (!url.endsWith("/"))
+ {
+ url += "/";
+ }
+
+ LogUtils.DEBUG("In deRegisterPackageContainer for " + url );
+ if ( hasRegisteredUnoPkgContainer( url ) )
+ {
+ try
+ {
+ DeployedUnoPackagesDB db = getUnoPackagesDB();
+ if ( db != null )
+ {
+ if ( db.removePackage( language, url ) )
+ {
+ writeUnoPackageDB( db );
+ ParcelContainer container =
+ ( ParcelContainer ) registeredPackages.get( url );
+ if ( !container.hasElements() )
+ {
+ // When all libraries within a package bundle
+ // ( for this language ) are removed also
+ // remove the container from its parent
+ // Otherwise, a container ( with no containees )
+ // representing the uno package bundle will
+ // still exist and so will get displayed
+ if ( container.parent() != null )
+ {
+ container.parent().removeChildContainer( container );
+ }
+ }
+ registeredPackages.remove( url );
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ //TODO revisit exception handling and exception here
+ //means something very wrong
+ LogUtils.DEBUG("***** deRegisterPackageContainer() got exception " + e );
+ }
+ }
+ LogUtils.DEBUG("Leaving deRegisterPackageContainer for " + url );
+ }
+
+ private void init() throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException
+ {
+ LogUtils.DEBUG("getting container for " + containerUrl );
+ DeployedUnoPackagesDB db = null;
+ try
+ {
+ db = getUnoPackagesDB();
+ if ( db != null )
+ {
+ String[] packages = db.getDeployedPackages( language );
+
+ for ( int i=0; i<packages.length;i++)
+ {
+ try
+ {
+ processUnoPackage( packages[i], language );
+ }
+ catch ( com.sun.star.lang.IllegalArgumentException ila)
+ {
+ LogUtils.DEBUG("Failed to process " + packages[i] + " for " + language);
+ LogUtils.DEBUG(" Reason: " + ila );
+ }
+ catch( Exception e )
+ {
+ // TODO proper exception or do we wish
+ // to ignore errors here
+ LogUtils.DEBUG("Something very wrong!!!!!");
+ LogUtils.DEBUG("Failed to process " + packages[i] + " for " + language);
+ LogUtils.DEBUG(" Reason: " + e );
+ }
+ }
+ }
+ }
+ catch ( com.sun.star.lang.WrappedTargetException e )
+ {
+ // no deployed packages
+ LogUtils.DEBUG("No deployed uno-packages for " + containerUrl );
+ }
+ }
+
+
+ public ScriptMetaData findScript( ParsedScriptUri psu ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+
+ {
+ ScriptMetaData scriptData = null;
+
+ String language = psu.language;
+ String functionName = psu.function;
+ String parcelName = psu.parcel;
+ String location = psu.location;
+
+ LogUtils.DEBUG("*** UnoPkgContainer.findScript() ***" +
+ "\ncontainerUrl = " + containerUrl +
+ "\nfunction = " + functionName +
+ "\nlocation = " + location +
+ "\nparcel = " + parcelName );
+
+ ParcelContainer pc = getChildContainer( location );
+
+ if ( pc == null )
+ {
+ throw new com.sun.star.lang.WrappedTargetException( "Failed to resolve script " , null, new com.sun.star.lang.IllegalArgumentException( "Cannot resolve script location for script = " + functionName ) );
+ }
+
+ scriptData = pc.findScript( psu );
+ return scriptData;
+
+ }
+
+ private DeployedUnoPackagesDB getUnoPackagesDB() throws com.sun.star.lang.WrappedTargetException
+ {
+ InputStream is = null;
+ DeployedUnoPackagesDB dp = null;
+ try
+ {
+ String path = containerUrl.substring( 0, containerUrl.lastIndexOf("/") );
+ String packagesUrl = PathUtils.make_url( path, "Scripts/unopkg-desc.xml" );
+ LogUtils.DEBUG("getUnoPackagesDB() looking for existing db in " + packagesUrl );
+ if ( m_xSFA.exists( packagesUrl ) )
+ {
+ if ( packagesUrl.startsWith( "vnd.sun.star.tdoc" ) )
+ {
+ // handles using XStorage directly
+ throw new com.sun.star.lang.WrappedTargetException("Can't handle documents yet");
+ }
+
+ is = new XInputStreamWrapper( m_xSFA.openFileRead( packagesUrl ) );
+ dp = new DeployedUnoPackagesDB( is );
+ try
+ {
+ is.close();
+ is = null;
+ }
+ catch ( Exception ignore )
+ {
+ }
+ }
+ else
+ {
+ LogUtils.DEBUG("getUnoPackagesDB() " + packagesUrl + " does not exist");
+ }
+ }
+ catch( Exception e )
+ {
+ LogUtils.DEBUG("getUnoPackagesDB() caught Exception: " + e );
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString());
+ }
+ finally
+ {
+ if ( is != null )
+ {
+ try
+ {
+ is.close();
+ is = null;
+ }
+ catch ( Exception ignore )
+ {
+ }
+ }
+ }
+
+ return dp;
+ }
+
+ private void writeUnoPackageDB( DeployedUnoPackagesDB dp ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException
+ {
+ LogUtils.DEBUG("In writeUnoPackageDB() ");
+
+ XOutputStream xos = null;
+ OutputStream os = null;
+ try
+ {
+ String path = containerUrl.substring( 0, containerUrl.lastIndexOf("/") );
+ String packagesUrl = PathUtils.make_url( path, "Scripts/unopkg-desc.xml" );
+ xos = m_xSFA.openFileWrite( packagesUrl );
+ XTruncate xTrc = (XTruncate) UnoRuntime.queryInterface( XTruncate.class, xos );
+ if ( xTrc != null )
+ {
+ LogUtils.DEBUG("In writeUnoPackageDB() Truncating...." );
+ xTrc.truncate();
+ }
+ else
+ {
+ LogUtils.DEBUG("In writeUnoPackageDB() CANT Truncate...." );
+ }
+ os = new XOutputStreamWrapper( xos );
+ dp.write( os );
+ try
+ {
+ os.close(); // will close xos
+ os = null;
+ }
+ catch( Exception ignore )
+ {
+ }
+ }
+ catch( Exception e )
+ {
+ LogUtils.DEBUG("In writeUnoPackageDB() Exception: " + e );
+ throw new com.sun.star.lang.WrappedTargetException( e.toString());
+ }
+ finally
+ {
+ if ( os != null )
+ {
+ try
+ {
+ os.close(); // will close xos
+ os = null;
+ }
+ catch ( Exception ignore )
+ {
+ }
+ }
+ }
+ }
+
+ public void processUnoPackage( XPackage dPackage, String language ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException, com.sun.star.container.ElementExistException
+ {
+ LogUtils.DEBUG("** in processUnoPackage " );
+ String uri = null;
+ DeployedUnoPackagesDB db = null;
+ uri = dPackage.getURL();
+
+ if ( !uri.endsWith( "/" ) )
+ {
+ uri += "/";
+ }
+
+ LogUtils.DEBUG("** processUnoPackage getURL() -> " + uri );
+ LogUtils.DEBUG("** processUnoPackage getName() -> " + dPackage.getName() );
+ LogUtils.DEBUG("** processUnoPackage getMediaType() -> " + dPackage.getPackageType().getMediaType() );
+ LogUtils.DEBUG("** processUnoPackage getDisplayName() -> " + dPackage.getDisplayName() );
+ processUnoPackage( uri, language );
+
+ db = getUnoPackagesDB();
+ if ( db == null )
+ {
+ try
+ {
+ db = new DeployedUnoPackagesDB();
+ }
+ catch ( java.io.IOException ioe )
+ {
+ throw new com.sun.star.lang.WrappedTargetException( ioe.toString());
+ }
+ }
+ db.addPackage( language, uri );
+ writeUnoPackageDB( db );
+ }
+
+ private void processUnoPackage( String uri, String language ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.lang.WrappedTargetException, com.sun.star.container.ElementExistException
+ {
+ if ( hasRegisteredUnoPkgContainer( uri ) )
+ {
+ throw new com.sun.star.container.ElementExistException( "Already a registered uno package " + uri + " for language " + language );
+ }
+ LogUtils.DEBUG("processUnoPackage - URL = " + uri );
+ LogUtils.DEBUG("processUnoPackage - script library package");
+ String parentUrl = uri;
+
+ if ( uri.indexOf( "%2Funo_packages%2F" ) > -1 ||
+ uri.indexOf( "/uno_packages/" ) > -1 )
+ {
+ //its in a bundle need to determine the uno-package file its in
+ LogUtils.DEBUG("processUnoPackage - is part of a uno bundle");
+
+ int index = uri.lastIndexOf("/");
+ if ( uri.endsWith("/") )
+ {
+ uri = uri.substring( 0, index );
+ index = uri.lastIndexOf("/");
+ }
+
+ if ( index > -1 )
+ {
+ parentUrl = uri.substring( 0, index );
+ LogUtils.DEBUG("processUnoPackage - composition is contained in " + parentUrl);
+ }
+
+ ParcelContainer pkgContainer = getChildContainerForURL( parentUrl );
+ if ( pkgContainer == null )
+ {
+ pkgContainer = new ParcelContainer( this, m_xCtx, parentUrl, language, false );
+ if ( pkgContainer.loadParcel( uri ) == null )
+ {
+ throw new com.sun.star.lang.IllegalArgumentException( "Couldn't load script library from composition package " + uri + " for language " + language );
+
+ }
+ addChildContainer( pkgContainer );
+ }
+ else
+ {
+ if ( pkgContainer.loadParcel( uri ) == null )
+ {
+ throw new com.sun.star.lang.IllegalArgumentException( "Couldn't load script library from composition package " + uri + " for language " + language );
+ }
+
+ }
+ registerPackageContainer( uri, pkgContainer );
+ }
+ else
+ {
+ // stand-alone library package, e.g. not contained in
+ // an uno package
+ if ( loadParcel( uri ) == null )
+ {
+ throw new com.sun.star.lang.IllegalArgumentException( "Couldn't load script library package " + uri + " for language " + language );
+ }
+ registerPackageContainer( uri, this );
+ }
+
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/container/XMLParser.java b/scripting/java/com/sun/star/script/framework/container/XMLParser.java
new file mode 100644
index 000000000000..d69f3a1129c6
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/container/XMLParser.java
@@ -0,0 +1,41 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: XMLParser.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.container;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.IOException;
+import org.w3c.dom.Document;
+
+public interface XMLParser {
+ public Document parse(InputStream inputStream) throws IOException;
+ public void write(Document doc, OutputStream out) throws IOException;
+}
diff --git a/scripting/java/com/sun/star/script/framework/container/XMLParserFactory.java b/scripting/java/com/sun/star/script/framework/container/XMLParserFactory.java
new file mode 100644
index 000000000000..7850c0d16543
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/container/XMLParserFactory.java
@@ -0,0 +1,183 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: XMLParserFactory.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.container;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.IOException;
+import java.lang.reflect.Method;
+
+import javax.xml.parsers.*;
+import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+public class XMLParserFactory {
+
+ private static XMLParser parser = null;
+ private static String officedtdurl = null;
+
+ private XMLParserFactory() {}
+
+ public static XMLParser getParser() {
+ if (parser == null) {
+ synchronized (XMLParserFactory.class) {
+ if (parser == null)
+ parser = new DefaultParser();
+ }
+ }
+ return parser;
+ }
+
+ public static void setParser(XMLParser p) {
+ parser = p;
+ }
+
+ public static void setOfficeDTDURL(String url) {
+ officedtdurl = url;
+ }
+
+ private static class DefaultParser implements XMLParser {
+
+ private DocumentBuilderFactory factory;
+
+ public DefaultParser() {
+ factory = DocumentBuilderFactory.newInstance();
+ }
+
+ public Document parse(InputStream inputStream) throws IOException {
+ Document result = null;
+ InputSource is = null;
+
+ try {
+ DocumentBuilder builder = factory.newDocumentBuilder();
+
+ is = new InputSource(inputStream);
+
+ if (officedtdurl != null) {
+ is.setSystemId(officedtdurl);
+ }
+
+ result = builder.parse(is);
+ }
+ catch (SAXParseException spe) {
+ throw new IOException(spe.getMessage());
+ }
+ catch (SAXException se) {
+ throw new IOException(se.getMessage());
+ }
+ catch (ParserConfigurationException pce) {
+ throw new IOException(pce.getMessage());
+ }
+ return result;
+ }
+
+ public void write(Document doc, OutputStream out) throws IOException {
+ Class clazz = doc.getClass();
+ String name = clazz.getName();
+
+ // depending on the class of the Document object use introspection
+ // to invoke the appropriate methods for writing the XML
+ // this code is based on the code used by the NetBeans
+ // class XMLUtilImpl in the openide module
+ try {
+ if (name.equals("com.sun.xml.tree.XmlDocument") ||
+ name.equals("org.apache.crimson.tree.XmlDocument")) {
+
+ // these DOM implementations are self writing
+ Method write;
+ write = clazz.getDeclaredMethod("write",
+ new Class[] {OutputStream.class});
+ write.invoke(doc, new Object[] {out});
+ }
+ else {
+ // try xerces serialize package using introspection
+ ClassLoader cl = this.getClass().getClassLoader();
+
+ Class serializerClass = null;
+ Class formatterClass = null;
+
+ try {
+ serializerClass = Class.forName(
+ "org.apache.xml.serialize.XMLSerializer", true, cl);
+ formatterClass = Class.forName(
+ "org.apache.xml.serialize.OutputFormat", true, cl);
+ } catch (ClassNotFoundException cnfe) {
+ String prefix = "com.sun.org.apache.xml.internal.";
+
+ serializerClass = Class.forName(
+ prefix + "serialize.XMLSerializer" , true, cl);
+ formatterClass = Class.forName(
+ prefix + "serialize.OutputFormat", true, cl);
+ }
+
+ Object serializerObject = serializerClass.newInstance();
+ Object formatterObject = formatterClass.newInstance();
+
+ // improve output readability using the OutputFormat class
+ Method method = null;
+ method = formatterClass.getMethod("setMethod",
+ new Class[] {String.class});
+ method.invoke(formatterObject, new Object[] {"xml"});
+ method = formatterClass.getMethod("setIndenting",
+ new Class[] {Boolean.TYPE});
+ method.invoke(formatterObject, new Object[] {Boolean.TRUE});
+
+ // now set up an instance of XMLSerializer with our
+ // OutputStream and serialize our Document
+ method = serializerClass.getMethod("setOutputByteStream",
+ new Class[] {OutputStream.class});
+ method.invoke(serializerObject, new Object[] {out});
+ method = serializerClass.getMethod("setOutputFormat",
+ new Class[] {formatterClass});
+ method.invoke(serializerObject,
+ new Object[] {formatterObject});
+
+ method = serializerClass.getMethod("asDOMSerializer",
+ new Class[0]);
+ Object impl = method.invoke(serializerObject,
+ new Object[0]);
+
+ method = impl.getClass().getMethod("serialize",
+ new Class[] {Document.class});
+ method.invoke(impl, new Object[] {doc});
+ }
+ } catch (NoSuchMethodException ex) {
+ throw new IOException(ex.getMessage());
+ } catch (ClassNotFoundException ex) {
+ throw new IOException(ex.getMessage());
+ } catch (Exception ex) {
+ throw new IOException(ex.getMessage());
+ }
+ }
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java b/scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java
new file mode 100644
index 000000000000..2010ad6728d3
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/io/UCBStreamHandler.java
@@ -0,0 +1,284 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: UCBStreamHandler.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+package com.sun.star.script.framework.io;
+
+import java.net.*;
+import java.io.*;
+import java.util.*;
+import java.util.zip.*;
+
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.io.XInputStream;
+import com.sun.star.io.XOutputStream;
+import com.sun.star.io.XTruncate;
+
+import com.sun.star.script.framework.log.LogUtils;
+import com.sun.star.script.framework.provider.PathUtils;
+
+public class UCBStreamHandler extends URLStreamHandler {
+
+ public final static String separator = "/ucb/";
+
+ private XComponentContext m_xContext = null;
+ private XMultiComponentFactory m_xMultiComponentFactory = null;
+ private XSimpleFileAccess m_xSimpleFileAccess = null;
+ private HashMap m_jarStreamMap = new HashMap(12);
+ public static String m_ucbscheme;
+
+ public UCBStreamHandler( XComponentContext ctxt, String scheme, XSimpleFileAccess xSFA )
+ {
+ LogUtils.DEBUG( "UCBStreamHandler ctor, scheme = " + scheme );
+ this.m_xContext = ctxt;
+ this.m_ucbscheme = scheme;
+ this.m_xSimpleFileAccess = xSFA;
+ }
+
+ public void parseURL(URL url, String spec, int start, int limit) {
+ LogUtils.DEBUG("**XUCBStreamHandler, parseURL: " + url + " spec: " + spec + " start: " + start + " limit: " + limit );
+
+ String file = url.getFile();
+ if (file == null)
+ file = spec.substring(start, limit);
+ else
+ file += spec.substring(start, limit);
+
+ LogUtils.DEBUG("**For scheme = " + m_ucbscheme );
+ LogUtils.DEBUG("**Setting path = " + file );
+ setURL(url, m_ucbscheme, null, -1, null, null, file, null, null);
+ }
+
+ public URLConnection openConnection(URL u) throws IOException {
+ return new UCBConnection(u);
+ }
+
+ private class UCBConnection extends URLConnection {
+
+ public UCBConnection(URL url) {
+ super(url);
+ }
+
+ public void connect() {
+ }
+
+ public InputStream getInputStream() throws IOException {
+ LogUtils.DEBUG("UCBConnectionHandler GetInputStream on " + url );
+ String sUrl = url.toString();
+ if (sUrl.lastIndexOf(separator) == -1) {
+ LogUtils.DEBUG("getInputStream straight file load" );
+ return getFileStreamFromUCB(sUrl);
+ }
+ else {
+ String path = sUrl.substring(0, sUrl.lastIndexOf(separator) );
+ String file = sUrl.substring(
+ sUrl.lastIndexOf(separator) + separator.length());
+ LogUtils.DEBUG("getInputStream, load of file from another file eg. " + file + " from " + path );
+ return getUCBStream(file, path);
+ }
+ }
+ public OutputStream getOutputStream() throws IOException {
+ LogUtils.DEBUG("UCBConnectionHandler getOutputStream on " + url );
+ OutputStream os = null;
+ try
+ {
+ String sUrl = url.toString();
+ if ( !( sUrl.lastIndexOf(separator) == -1) ) {
+ String path = sUrl.substring(0, sUrl.lastIndexOf(separator));
+ String file = sUrl.substring(
+ sUrl.lastIndexOf(separator) + separator.length());
+
+ if ( m_xSimpleFileAccess.isReadOnly( path ) )
+ {
+ throw new java.io.IOException("File is read only");
+ }
+
+ LogUtils.DEBUG("getOutputStream, create o/p stream for file eg. " + path );
+
+ // we will only deal with simple file write
+ XOutputStream xos = m_xSimpleFileAccess.openFileWrite( path );
+ XTruncate xtrunc = ( XTruncate ) UnoRuntime.queryInterface( XTruncate.class, xos );
+ if ( xtrunc != null )
+ {
+ xtrunc.truncate();
+ }
+ os = new XOutputStreamWrapper( xos );
+ }
+ if ( os == null )
+ {
+ throw new IOException("Failed to get OutputStream for " + sUrl );
+ }
+ }
+ catch ( com.sun.star.ucb.CommandAbortedException cae )
+ {
+ LogUtils.DEBUG("caught exception: " + cae.toString() + " getting writable stream from " + url );
+ throw new IOException( cae.toString() );
+ }
+ catch ( com.sun.star.uno.Exception e )
+ {
+ LogUtils.DEBUG("caught unknown exception: " + e.toString() + " getting writable stream from " + url );
+ throw new IOException( e.toString() );
+ }
+ return os;
+ }
+ }
+
+
+ private InputStream getUCBStream(String file, String path)
+ throws IOException
+ {
+ InputStream is = null;
+ InputStream result = null;
+
+ try {
+ if (path.endsWith(".jar")) {
+ is = (InputStream)m_jarStreamMap.get(path);
+
+ if (is == null) {
+ is = getFileStreamFromUCB(path);
+ m_jarStreamMap.put(path, is);
+ }
+ else {
+ try {
+ is.reset();
+ }
+ catch (IOException e) {
+ is.close();
+ is = getFileStreamFromUCB(path);
+ m_jarStreamMap.put(path, is);
+ }
+ }
+ result = getFileStreamFromJarStream(file, is);
+ }
+ else
+ {
+ String fileUrl = PathUtils.make_url(path,file);
+ result = getFileStreamFromUCB(fileUrl);
+ }
+ }
+ finally {
+ if (is != null) {
+ try {
+ is.close();
+ }
+ catch (IOException ioe) {
+ LogUtils.DEBUG("Caught exception closing stream: " +
+ ioe.getMessage());
+ }
+ }
+ }
+ return result;
+ }
+
+ private InputStream getFileStreamFromJarStream(String file, InputStream is)
+ throws IOException
+ {
+ ZipInputStream zis = null;
+ ZipEntry entry = null;
+ boolean found = false;
+
+ zis = new ZipInputStream(is);
+
+ while (zis.available() != 0) {
+ entry = (ZipEntry)zis.getNextEntry();
+
+ if (entry.getName().equals(file)) {
+ return zis;
+ }
+ }
+ return null;
+ }
+
+ private InputStream getFileStreamFromUCB(String path)
+ throws IOException
+ {
+ InputStream result = null;
+ XInputStream xInputStream = null;
+
+ try {
+ LogUtils.DEBUG("Trying to read from " + path );
+ xInputStream = m_xSimpleFileAccess.openFileRead(path);
+ LogUtils.DEBUG("sfa appeared to read file " );
+ byte[][] inputBytes = new byte[1][];
+
+ int ln = 0;
+ int sz = m_xSimpleFileAccess.getSize(path);
+ // TODO don't depend on result of available() or size()
+ // just read stream 'till complete
+ if ( sz == 0 )
+ {
+ if ( xInputStream.available() > 0 )
+ {
+ sz = xInputStream.available();
+ }
+ }
+ LogUtils.DEBUG("size of file " + path + " is " + sz );
+ LogUtils.DEBUG("available = " + xInputStream.available() );
+ inputBytes[0] = new byte[sz];
+
+ ln = xInputStream.readBytes(inputBytes, sz);
+
+ if (ln != sz) {
+ throw new IOException(
+ "Failed to read " + sz + " bytes from XInputStream");
+ }
+
+ result = new ByteArrayInputStream(inputBytes[0]);
+ }
+ catch (com.sun.star.io.IOException ioe) {
+ LogUtils.DEBUG("caught exception " + ioe );
+ throw new IOException(ioe.getMessage());
+ }
+ catch (com.sun.star.uno.Exception e) {
+ LogUtils.DEBUG("caught exception " + e );
+ throw new IOException(e.getMessage());
+ }
+ finally
+ {
+ if (xInputStream != null) {
+ try {
+ xInputStream.closeInput();
+ }
+ catch (Exception e2) {
+ LogUtils.DEBUG(
+ "Error closing XInputStream:" + e2.getMessage());
+ }
+ }
+ }
+ return result;
+ }
+
+ private String convertClassNameToFileName(String name) {
+ return name.replace('.', File.separatorChar) + ".class";
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/io/XInputStreamImpl.java b/scripting/java/com/sun/star/script/framework/io/XInputStreamImpl.java
new file mode 100644
index 000000000000..0919c1e456d6
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/io/XInputStreamImpl.java
@@ -0,0 +1,122 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: XInputStreamImpl.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.io;
+
+import com.sun.star.io.XInputStream;
+import java.io.InputStream;
+import java.io.IOException;
+
+public class XInputStreamImpl implements XInputStream
+{
+ InputStream is;
+ public XInputStreamImpl( InputStream is )
+ {
+ this.is = is;
+ }
+
+ public int readBytes( /*OUT*/byte[][] aData, /*IN*/int nBytesToRead ) throws com.sun.star.io.NotConnectedException, com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException
+ {
+ aData[ 0 ] = new byte[ nBytesToRead ];
+
+ int totalBytesRead = 0;
+
+ try
+ {
+ int bytesRead = 0;
+ while ( ( bytesRead = is.read( aData[ 0 ], totalBytesRead, nBytesToRead ) ) > 0 && ( totalBytesRead < nBytesToRead ) )
+ {
+ totalBytesRead += bytesRead;
+ nBytesToRead -= bytesRead;
+ }
+ }
+ catch ( IOException e )
+ {
+ throw new com.sun.star.io.IOException( e.toString() );
+ }
+ catch ( IndexOutOfBoundsException aie )
+ {
+ throw new com.sun.star.io.BufferSizeExceededException( aie.toString() );
+ }
+ return totalBytesRead;
+ }
+
+ public int readSomeBytes( /*OUT*/byte[][] aData, /*IN*/int nMaxBytesToRead ) throws com.sun.star.io.NotConnectedException, com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException
+ {
+ int bytesToRead = nMaxBytesToRead;
+ int availableBytes = available();
+ if ( availableBytes < nMaxBytesToRead )
+ {
+ bytesToRead = availableBytes;
+ }
+ int read = readBytes( aData, bytesToRead );
+ return read;
+ }
+
+ public void skipBytes( /*IN*/int nBytesToSkip ) throws com.sun.star.io.NotConnectedException, com.sun.star.io.BufferSizeExceededException, com.sun.star.io.IOException
+ {
+ long bytesSkipped = 0;
+ try
+ {
+ bytesSkipped = is.skip( (long)nBytesToSkip );
+ }
+ catch ( IOException e )
+ {
+ throw new com.sun.star.io.IOException( e.toString() );
+ }
+ }
+
+ public int available( ) throws com.sun.star.io.NotConnectedException, com.sun.star.io.IOException
+ {
+ int bytesAvail = 0;
+ try
+ {
+ bytesAvail = is.available();
+ }
+ catch ( IOException e )
+ {
+ throw new com.sun.star.io.IOException( e.toString() );
+ }
+ return bytesAvail;
+ }
+
+ public void closeInput( ) throws com.sun.star.io.NotConnectedException, com.sun.star.io.IOException
+ {
+ try
+ {
+ is.close();
+ }
+ catch( IOException e )
+ {
+ throw new com.sun.star.io.IOException( e.toString() );
+ }
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/io/XInputStreamWrapper.java b/scripting/java/com/sun/star/script/framework/io/XInputStreamWrapper.java
new file mode 100644
index 000000000000..eec32c65cf5c
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/io/XInputStreamWrapper.java
@@ -0,0 +1,105 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: XInputStreamWrapper.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.script.framework.io;
+
+import java.io.InputStream;
+import com.sun.star.io.XInputStream;
+
+public class XInputStreamWrapper extends InputStream {
+ private XInputStream m_xInputStream;
+
+ public XInputStreamWrapper(XInputStream xInputStream) {
+ m_xInputStream = xInputStream;
+ }
+
+ public int read() throws java.io.IOException
+ {
+ byte[][] byteRet = new byte[1][0];
+ long numRead;
+
+ try {
+ numRead = m_xInputStream.readBytes(byteRet, 1);
+ }
+ catch (com.sun.star.io.IOException ioe) {
+ throw new java.io.IOException(ioe.getMessage());
+ }
+
+ if (numRead != 1) {
+ return -1;
+ }
+ return byteRet[0][0];
+ }
+
+ public int read( byte[] b ) throws java.io.IOException
+ {
+ byte[][] byteRet = new byte[1][];
+ byteRet[0] = b;
+ try
+ {
+ return m_xInputStream.readBytes( byteRet, b.length );
+ }
+ catch ( com.sun.star.io.IOException ioe)
+ {
+ throw new java.io.IOException(ioe.getMessage());
+ }
+ }
+
+ public long skip(long n) throws java.io.IOException
+ {
+ try {
+ m_xInputStream.skipBytes((int)n);
+ return n;
+ }
+ catch (com.sun.star.io.IOException ioe) {
+ throw new java.io.IOException(ioe.getMessage());
+ }
+ }
+
+ public int available() throws java.io.IOException
+ {
+ try {
+ return m_xInputStream.available();
+ }
+ catch (com.sun.star.io.IOException ioe) {
+ throw new java.io.IOException(ioe.getMessage());
+ }
+ }
+
+ public void close() throws java.io.IOException
+ {
+ try {
+ m_xInputStream.closeInput();
+ }
+ catch (com.sun.star.io.IOException ioe) {
+ throw new java.io.IOException(ioe.getMessage());
+ }
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java b/scripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java
new file mode 100644
index 000000000000..d12c22fe259a
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/io/XOutputStreamWrapper.java
@@ -0,0 +1,131 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: XOutputStreamWrapper.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package com.sun.star.script.framework.io;
+import java.io.*;
+import com.sun.star.io.XOutputStream;
+
+
+public class XOutputStreamWrapper extends OutputStream {
+ XOutputStream m_xOutputStream;
+ public XOutputStreamWrapper(XOutputStream xOs ) {
+ this.m_xOutputStream = xOs;
+ }
+ public void write(int b)
+ throws java.io.IOException
+ {
+ if ( m_xOutputStream == null )
+ {
+ throw new java.io.IOException("Stream is null");
+ }
+ byte[] bytes = new byte[1];
+ bytes[0] = (byte) b;
+ try
+ {
+ m_xOutputStream.writeBytes( bytes );
+ }
+ catch ( com.sun.star.io.IOException ioe )
+ {
+ throw new java.io.IOException(ioe.getMessage());
+ }
+ }
+ public void write(byte[] b)
+ throws java.io.IOException
+ {
+
+ if ( m_xOutputStream == null )
+ {
+ throw new java.io.IOException( "Stream is null" );
+ }
+ try
+ {
+ m_xOutputStream.writeBytes( b );
+ }
+ catch ( com.sun.star.io.IOException ioe )
+ {
+ throw new java.io.IOException(ioe.getMessage());
+ }
+ }
+ public void write( byte[] b, int off, int len )
+ throws java.io.IOException
+ {
+ if ( m_xOutputStream == null )
+ {
+ throw new java.io.IOException( "Stream is null" );
+ }
+ byte[] bytes = new byte[len];
+ for ( int i=off; i< off+len; i++ )
+ {
+ bytes[i] = b[i];
+ }
+ try
+ {
+ m_xOutputStream.writeBytes(bytes);
+ }
+ catch ( com.sun.star.io.IOException ioe )
+ {
+ throw new java.io.IOException(ioe.getMessage());
+ }
+ }
+
+ public void flush()
+ throws java.io.IOException
+ {
+ if ( m_xOutputStream == null )
+ {
+ throw new java.io.IOException( "Stream is null" );
+ }
+ try
+ {
+ m_xOutputStream.flush();
+ }
+ catch ( com.sun.star.io.IOException ioe )
+ {
+ throw new java.io.IOException(ioe.getMessage());
+ }
+ }
+ public void close()
+ throws java.io.IOException
+ {
+ if ( m_xOutputStream == null )
+ {
+ throw new java.io.IOException( "Stream is null" );
+ }
+ try
+ {
+ m_xOutputStream.closeOutput();
+ }
+ catch ( com.sun.star.io.IOException ioe )
+ {
+ throw new java.io.IOException(ioe.getMessage());
+ }
+ }
+
+ }
+
diff --git a/scripting/java/com/sun/star/script/framework/io/XStorageHelper.java b/scripting/java/com/sun/star/script/framework/io/XStorageHelper.java
new file mode 100644
index 000000000000..81d2f33435b0
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/io/XStorageHelper.java
@@ -0,0 +1,281 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: XStorageHelper.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.io;
+
+import com.sun.star.frame.XModel;
+
+import com.sun.star.container.XNameAccess;
+
+import com.sun.star.uno.XInterface;
+import com.sun.star.uno.UnoRuntime;
+
+import com.sun.star.lang.XComponent;
+
+import com.sun.star.uno.AnyConverter;
+
+import com.sun.star.io.XStream;
+import com.sun.star.io.XInputStream;
+import com.sun.star.io.XOutputStream;
+
+import com.sun.star.embed.XStorage;
+import com.sun.star.embed.XTransactedObject;
+
+import com.sun.star.document.XDocumentSubStorageSupplier;
+
+import com.sun.star.beans.XPropertySet;
+
+import com.sun.star.lang.XEventListener;
+import com.sun.star.lang.EventObject;
+
+import com.sun.star.script.framework.log.LogUtils;
+import com.sun.star.script.framework.provider.PathUtils;
+
+import java.util.*;
+import java.io.*;
+
+
+public class XStorageHelper implements XEventListener
+{
+ XStorage[] xStorages;
+ XStream xStream;
+ XInputStream xIs = null;
+ XOutputStream xOs = null;
+ static Map modelMap = new HashMap();
+ XModel xModel = null;
+ private static XStorageHelper listener = new XStorageHelper();
+
+ private XStorageHelper() {}
+ public XStorageHelper( String path, int mode, boolean create ) throws IOException
+ {
+ String modelUrl = null;
+ int indexOfScriptsDir = path.lastIndexOf( "Scripts" );
+ if ( indexOfScriptsDir > -1 )
+ {
+ modelUrl = path.substring( 0, indexOfScriptsDir - 1 );
+ path = path.substring( indexOfScriptsDir, path.length());
+ }
+
+ LogUtils.DEBUG("XStorageHelper ctor, path: " + path);
+ this.xModel = getModelForURL( modelUrl );
+
+ try
+ {
+ StringTokenizer tokens = new StringTokenizer(path, "/");
+
+ if (tokens.countTokens() == 0)
+ {
+ throw new IOException("Invalid path");
+ }
+ XDocumentSubStorageSupplier xDocumentSubStorageSupplier =
+ (XDocumentSubStorageSupplier) UnoRuntime.queryInterface(
+ XDocumentSubStorageSupplier.class, xModel);
+ xStorages = new XStorage[tokens.countTokens() ];
+ LogUtils.DEBUG("XStorageHelper ctor, path chunks length: " + xStorages.length );
+
+ for ( int i = 0; i < xStorages.length; i++ )
+ {
+ LogUtils.DEBUG("XStorageHelper, processing index " + i );
+ String name = tokens.nextToken();
+ LogUtils.DEBUG("XStorageHelper, getting: " + name);
+ XStorage storage = null;
+ if ( i == 0 )
+ {
+ storage = xDocumentSubStorageSupplier.getDocumentSubStorage( name, mode );
+ if ( storage == null )
+ {
+ LogUtils.DEBUG("** boo hoo Storage is null " );
+ }
+ XPropertySet xProps = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class,storage );
+ if ( xProps != null )
+ {
+ String mediaType = AnyConverter.toString( xProps.getPropertyValue( "MediaType" ) );
+ LogUtils.DEBUG("***** media type is " + mediaType );
+ if ( !mediaType.equals("scripts") )
+ {
+ xProps.setPropertyValue("MediaType","scripts");
+ }
+ }
+ }
+ else
+ {
+ XNameAccess xNameAccess = (XNameAccess)
+ UnoRuntime.queryInterface(XNameAccess.class, xStorages[i-1]);
+ if (xNameAccess == null )
+ {
+ disposeObject();
+ throw new IOException("No name access " + name);
+ }
+ else if ( !xNameAccess.hasByName(name) || !xStorages[i-1].isStorageElement(name) )
+ {
+ if ( !create )
+ {
+ disposeObject();
+ throw new IOException("No subdir: " + name);
+ }
+ else
+ {
+ // attempt to create new storage
+ LogUtils.DEBUG("Attempt to create new storage for " + name );
+ }
+ }
+
+ storage = xStorages[i-1].openStorageElement(
+ name, mode );
+ }
+ if ( storage == null )
+ {
+ disposeObject();
+ throw new IOException("storage not found: " + name);
+ }
+ xStorages[ i ] = storage;
+
+ }
+ }
+ catch ( com.sun.star.io.IOException ioe)
+ {
+ disposeObject();
+ }
+ catch (com.sun.star.uno.Exception e)
+ {
+ disposeObject();
+ throw new IOException(e.getMessage());
+ }
+ }
+
+ public synchronized static void addNewModel( XModel model )
+ {
+ // TODO needs to cater for model for untitled document
+ modelMap.put( PathUtils.getOidForModel( model ), model );
+ XComponent xComp = (XComponent)
+ UnoRuntime.queryInterface(XComponent.class, model);
+
+ if ( xComp != null )
+ {
+ try
+ {
+ xComp.addEventListener( listener );
+ }
+ catch ( Exception e )
+ {
+ // What TODO here ?
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ }
+ }
+ }
+
+ public void disposing( EventObject Source )
+ {
+ XModel model = (XModel)
+ UnoRuntime.queryInterface(XModel.class,Source.Source );
+
+ if ( model != null )
+ {
+ LogUtils.DEBUG(" Disposing doc " + model.getURL() );
+ Object result = modelMap.remove( model );
+ result = null;
+ }
+ }
+ public XStorage getStorage()
+ {
+ return xStorages[ xStorages.length - 1 ];
+ }
+ public XModel getModel()
+ {
+ return xModel;
+ }
+ public void disposeObject()
+ {
+ disposeObject( false );
+ }
+ public void disposeObject( boolean shouldCommit )
+ {
+ LogUtils.DEBUG("In disposeObject");
+
+ for ( int i = xStorages.length -1 ; i > -1; i-- )
+ {
+ LogUtils.DEBUG("In disposeObject disposing storage " + i );
+ try
+ {
+ XStorage xStorage = xStorages[i];
+ if ( shouldCommit )
+ {
+ commit(xStorage);
+ }
+ disposeObject(xStorage);
+ LogUtils.DEBUG("In disposeObject disposed storage " + i );
+ }
+ catch( Exception ignore )
+ {
+ LogUtils.DEBUG("Exception disposing storage " + i );
+ }
+
+ }
+
+ }
+ static public void disposeObject( XInterface xInterface )
+ {
+ if (xInterface == null) {
+ return;
+ }
+
+ XComponent xComponent = (XComponent)
+ UnoRuntime.queryInterface(XComponent.class, xInterface);
+
+ if (xComponent == null) {
+ return;
+ }
+ xComponent.dispose();
+ }
+ static public void commit( XInterface xInterface )
+ {
+ XTransactedObject xTrans = (XTransactedObject)
+ UnoRuntime.queryInterface(XTransactedObject.class, xInterface);
+ if ( xTrans != null )
+ {
+ try
+ {
+ xTrans.commit();
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG("Something went bellyup exception: " + e );
+ }
+ }
+ }
+
+ public XModel getModelForURL( String url )
+ {
+ //TODO does not cater for untitled documents
+ return (XModel)modelMap.get( url );
+ }
+
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/log/LogUtils.java b/scripting/java/com/sun/star/script/framework/log/LogUtils.java
new file mode 100644
index 000000000000..ef4b1f9a56ec
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/log/LogUtils.java
@@ -0,0 +1,68 @@
+package com.sun.star.script.framework.log;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+public class LogUtils {
+
+ private static boolean m_bDebugEnabled = false;
+
+ static
+ {
+ String debugFlag =
+ System.getProperties().getProperty("ScriptJavaRuntimeDebug");
+
+ if (debugFlag != null && debugFlag.length() > 0)
+ {
+ m_bDebugEnabled = debugFlag.equalsIgnoreCase("true");
+ }
+ }
+
+ // Ensure that instances of this class cannot be created
+ private LogUtils() {
+ }
+
+ /**
+ * Print Debug Output
+ *
+ * @param msg message to be displayed
+ */
+ public static void DEBUG(String msg)
+ {
+ if (m_bDebugEnabled)
+ {
+ System.out.println(msg);
+ }
+ }
+
+ public static String getTrace( Exception e )
+ {
+ ByteArrayOutputStream baos = null;
+ PrintStream ps = null;
+ String result = "";
+ try
+ {
+ baos = new ByteArrayOutputStream( );
+ ps = new PrintStream( baos );
+ e.printStackTrace( ps );
+ }
+ finally
+ {
+ try
+ {
+ if ( baos != null )
+ {
+ baos.close();
+ }
+ if ( ps != null )
+ {
+ ps.close();
+ }
+ }
+ catch ( Exception excp )
+ {
+ }
+ }
+ return result;
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java b/scripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java
new file mode 100755
index 000000000000..e3b4989657da
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/ClassLoaderFactory.java
@@ -0,0 +1,77 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ClassLoaderFactory.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+package com.sun.star.script.framework.provider;
+
+import java.net.*;
+
+import com.sun.star.script.framework.log.LogUtils;
+import com.sun.star.script.framework.container.ScriptMetaData;
+
+/**
+ * Class Loader Factory
+ *
+ * @author Noel Power
+ * @created August 2, 2002
+ */
+public class ClassLoaderFactory
+{
+ private ClassLoaderFactory() {}
+
+ public static ClassLoader getURLClassLoader( ScriptMetaData scriptData )
+ throws NoSuitableClassLoaderException, MalformedURLException
+ {
+ ClassLoader parent = scriptData.getClass().getClassLoader();
+ URL[] classPath = scriptData.getClassPath();
+ LogUtils.DEBUG("Classpath has length " + classPath.length );
+ for ( int i=0; i < classPath.length; i++ )
+ {
+ LogUtils.DEBUG("ClassPath " + i + "} is " + classPath[ i ].toString() );
+ }
+ return getURLClassLoader( parent, classPath );
+ }
+ public static ClassLoader getURLClassLoader( ClassLoader parent, URL[] classpath)
+ throws NoSuitableClassLoaderException
+ {
+ ClassLoader loader =
+ new URLClassLoader( classpath, parent);
+
+ if (loader != null)
+ {
+ return loader;
+ }
+ else
+ {
+ throw new NoSuitableClassLoaderException(
+ "Unable to create URLClassLoader");
+ }
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java b/scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java
new file mode 100644
index 000000000000..5a8b16ff2850
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/EditorScriptContext.java
@@ -0,0 +1,103 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: EditorScriptContext.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider;
+
+import com.sun.star.frame.XModel;
+import com.sun.star.frame.XDesktop;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.document.XScriptInvocationContext;
+
+import com.sun.star.script.provider.XScriptContext;
+
+
+/**
+ * Description of the Class
+ *
+ * @author Noel Power
+ * @created August 2, 2002
+ */
+public class EditorScriptContext implements XScriptContext
+{
+ private XDesktop m_xDeskTop;
+ private XComponentContext m_xComponentContext;
+ private XDesktop m_xCtx;
+ public EditorScriptContext( XComponentContext xmComponentContext,
+ XDesktop xDesktop )
+ {
+ this.m_xComponentContext = xmComponentContext;
+ this.m_xDeskTop = xDesktop;
+ }
+
+ //----------------------------------------------------------------------
+ /**
+ Obtain the document reference on which the script can operate
+
+ @returns
+ XModel interface
+ */
+ public XModel getDocument()
+ {
+ XModel xModel = ( XModel ) UnoRuntime.queryInterface( XModel.class,
+ m_xDeskTop.getCurrentComponent() );
+
+ return xModel;
+ }
+
+ public XScriptInvocationContext getInvocationContext()
+ {
+ XScriptInvocationContext xContext = ( XScriptInvocationContext ) UnoRuntime.queryInterface(
+ XScriptInvocationContext.class, getDocument() );
+ return xContext;
+ }
+
+ /**
+ Obtain the desktop reference on which the script can operate
+
+ @returns
+ XDesktop interface
+ */
+ public XDesktop getDesktop()
+ {
+ return m_xDeskTop;
+ }
+
+ /**
+ Obtain the component context which the script can use to create other uno components
+
+ @returns
+ XComponentContext interface
+ */
+ public XComponentContext getComponentContext()
+ {
+ return m_xComponentContext;
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java b/scripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java
new file mode 100755
index 000000000000..f37f12e239d4
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/NoSuitableClassLoaderException.java
@@ -0,0 +1,56 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: NoSuitableClassLoaderException.java,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.provider;
+
+public class NoSuitableClassLoaderException extends Exception
+{
+ /**
+ * Constructs an <code>NoSuitableClassLoaderException</code> with <code>null</code>
+ * as its error detail message.
+ */
+ public NoSuitableClassLoaderException()
+ {
+ super();
+ }
+ /**
+ * Constructs an <code>NoSuitBaleClassLoaderException</code> with the specified detail
+ * message. The error message string <code>s</code> can later be
+ * retrieved by the <code>{@link java.lang.Throwable#getMessage}</code>
+ * method of class <code>java.lang.Throwable</code>.
+ *
+ * @param s the detail message.
+ */
+ public NoSuitableClassLoaderException(String s)
+ {
+ super(s);
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/PathUtils.java b/scripting/java/com/sun/star/script/framework/provider/PathUtils.java
new file mode 100644
index 000000000000..cc45040e3c5c
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/PathUtils.java
@@ -0,0 +1,90 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: PathUtils.java,v $
+ * $Revision: 1.8.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.provider;
+
+import java.util.StringTokenizer;
+
+import java.lang.reflect.Method;
+
+import com.sun.star.frame.XModel;
+import com.sun.star.uno.IQueryInterface;
+
+public class PathUtils {
+
+ public static String FILE_URL_PREFIX;
+ public static String BOOTSTRAP_NAME;
+ private static boolean m_windows = false;
+
+ static {
+ // detect if windows platform
+ if (System.getProperty("os.name").startsWith("Windows"))
+ m_windows = true;
+
+ FILE_URL_PREFIX = m_windows ? "file:///" : "file://";
+ BOOTSTRAP_NAME = m_windows ? "bootstrap.ini" : "bootstraprc";
+ }
+ public static String getOidForModel( XModel xModel )
+ {
+ String oid = new String("");
+ if ( xModel != null )
+ {
+ try
+ {
+ Method getOid = IQueryInterface.class.getMethod("getOid", (java.lang.Class[])null);
+ if ( getOid != null )
+ {
+ oid = (String)getOid.invoke( xModel, new Object[0] );
+ }
+
+ }
+ catch ( Exception ignore )
+ {
+ }
+ }
+ return oid;
+ }
+ static public String make_url( String baseUrl, String url )
+ {
+ StringBuffer buff = new StringBuffer( baseUrl.length() + url.length() ); buff.append( baseUrl );
+ StringTokenizer t = new StringTokenizer( url, "/");
+ while ( t.hasMoreElements() )
+ {
+ if ( buff.charAt( buff.length() - 1 ) != '/' )
+ {
+ buff.append('/');
+ }
+ buff.append( java.net.URLEncoder.encode( (String)t.nextElement() ) ); }
+ return buff.toString();
+ }
+
+ private PathUtils() {
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/ScriptContext.java b/scripting/java/com/sun/star/script/framework/provider/ScriptContext.java
new file mode 100644
index 000000000000..a821ab6b393b
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/ScriptContext.java
@@ -0,0 +1,168 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptContext.java,v $
+ * $Revision: 1.11 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider;
+
+import com.sun.star.document.XScriptInvocationContext;
+import com.sun.star.frame.XModel;
+import com.sun.star.frame.XDesktop;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.beans.PropertyAttribute;
+import com.sun.star.lib.uno.helper.PropertySet;
+import com.sun.star.uno.Type;
+
+import com.sun.star.script.provider.XScriptContext;
+
+import com.sun.star.script.framework.log.LogUtils;
+
+
+/**
+ * Description of the Class
+ *
+ * @author Noel Power
+ * @created August 2, 2002
+ */
+public class ScriptContext extends PropertySet implements XScriptContext
+{
+ /**
+ * Description of the Class
+ *
+ * @author John Rice
+ * @created 18/09/02
+ */
+
+ public final static String HM_DOC_REF = "DocumentReference";
+ public final static String HM_DESKTOP = "Desktop";
+ public final static String HM_COMPONENT_CONTEXT = "ComponentContext";
+
+ private final static String DOC_REF = "SCRIPTING_DOC_REF";
+ private final static String DOC_URI = "SCRIPTING_DOC_URI";
+
+
+ public XModel m_xModel = null;
+ public XScriptInvocationContext m_xInvocationContext = null;
+ public String m_sDocURI = null;
+ public XDesktop m_xDeskTop = null;
+ public Integer m_iStorageID = null;
+ public XComponentContext m_xComponentContext = null;
+
+ public ScriptContext( XComponentContext xmComponentContext,
+ XDesktop xDesktop, XModel xModel, XScriptInvocationContext xInvocContext)
+ {
+ this.m_xDeskTop = xDesktop;
+ this.m_xComponentContext = xmComponentContext;
+ this.m_xModel = xModel;
+ this.m_xInvocationContext = xInvocContext;
+
+ if ( m_xModel != null )
+ {
+ registerProperty( DOC_URI, new Type(String.class),
+ (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_sDocURI");
+ }
+
+ registerProperty( HM_DOC_REF, new Type(XModel.class),
+ (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_xModel");
+ registerProperty( HM_DESKTOP, new Type(XDesktop.class),
+ (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_xDeskTop");
+ registerProperty( HM_COMPONENT_CONTEXT, new Type(XDesktop.class),
+ (short)(PropertyAttribute.MAYBEVOID | PropertyAttribute.TRANSIENT), "m_xComponentContext");
+ }
+
+ public static XScriptContext createContext( XModel xModel, XScriptInvocationContext xInvocContext,
+ XComponentContext xCtxt, XMultiComponentFactory xMCF)
+ {
+ XScriptContext sc = null;
+
+ try {
+
+ Object xInterface = null;
+ XDesktop xDesktop = null;
+
+ xInterface = xMCF.createInstanceWithContext(
+ "com.sun.star.frame.Desktop", xCtxt);
+ xDesktop = (XDesktop)
+ UnoRuntime.queryInterface(XDesktop.class, xInterface);
+ if ( xModel != null )
+ {
+ sc = new ScriptContext(xCtxt, xDesktop, xModel, xInvocContext);
+ }
+ else
+ {
+ sc = new EditorScriptContext(xCtxt, xDesktop );
+ }
+
+ }
+ catch ( Exception e ) {
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ }
+ return sc;
+ }
+
+ //----------------------------------------------------------------------
+ /**
+ Obtain the document reference on which the script can operate
+
+ @returns
+ XModel interface
+ */
+ public XModel getDocument()
+ {
+ return m_xModel;
+ }
+
+ public XScriptInvocationContext getInvocationContext()
+ {
+ return m_xInvocationContext;
+ }
+
+ /**
+ Obtain the desktop reference on which the script can operate
+
+ @returns
+ XDesktop interface
+ */
+ public XDesktop getDesktop()
+ {
+ return m_xDeskTop;
+ }
+
+ /**
+ Obtain the component context which the script can use to create other uno components
+
+ @returns
+ XComponentContext interface
+ */
+ public XComponentContext getComponentContext()
+ {
+ return m_xComponentContext;
+ }
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java b/scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java
new file mode 100644
index 000000000000..e6654d2bd83f
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/ScriptEditor.java
@@ -0,0 +1,13 @@
+package com.sun.star.script.framework.provider;
+
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.framework.container.ScriptMetaData;
+
+public interface ScriptEditor
+{
+ public Object execute() throws Exception;
+ public void indicateErrorLine( int lineNum );
+ public void edit(XScriptContext context, ScriptMetaData entry);
+ public String getTemplate();
+ public String getExtension();
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java b/scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java
new file mode 100755
index 000000000000..65c07349d740
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/ScriptProvider.java
@@ -0,0 +1,734 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptProvider.java,v $
+ * $Revision: 1.13.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider;
+
+import com.sun.star.container.XNameContainer;
+
+import com.sun.star.uno.Exception;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XInitialization;
+import com.sun.star.lang.XTypeProvider;
+import com.sun.star.lang.XServiceInfo;
+import com.sun.star.frame.XModel;
+
+import com.sun.star.util.XMacroExpander;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.AnyConverter;
+import com.sun.star.uno.Type;
+
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.beans.XVetoableChangeListener;
+import com.sun.star.beans.XPropertyChangeListener;
+import com.sun.star.beans.XPropertySetInfo;
+import com.sun.star.beans.Property;
+
+import com.sun.star.beans.XIntrospectionAccess;
+import com.sun.star.script.XInvocation;
+
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.provider.XScriptProvider;
+import com.sun.star.script.provider.XScript;
+import com.sun.star.script.provider.ScriptFrameworkErrorException;
+import com.sun.star.script.provider.ScriptFrameworkErrorType;
+
+import com.sun.star.script.browse.XBrowseNode;
+import com.sun.star.script.browse.BrowseNodeTypes;
+
+import com.sun.star.script.framework.log.LogUtils;
+
+import com.sun.star.script.framework.container.ScriptMetaData;
+import com.sun.star.script.framework.container.XMLParserFactory;
+import com.sun.star.script.framework.container.ParcelContainer;
+import com.sun.star.script.framework.container.ParsedScriptUri;
+import com.sun.star.script.framework.container.UnoPkgContainer;
+
+import com.sun.star.ucb.Command;
+import com.sun.star.ucb.XContentProvider;
+import com.sun.star.ucb.XContent;
+import com.sun.star.ucb.XCommandProcessor;
+import com.sun.star.ucb.XContentIdentifier;
+import com.sun.star.ucb.XContentIdentifierFactory;
+
+import com.sun.star.sdbc.XRow;
+
+import com.sun.star.script.framework.browse.ProviderBrowseNode;
+import com.sun.star.script.framework.browse.DialogFactory;
+
+import com.sun.star.deployment.XPackage;
+
+
+import com.sun.star.document.XScriptInvocationContext;
+import com.sun.star.frame.XTransientDocumentsDocumentContentFactory;
+import com.sun.star.uno.TypeClass;
+
+public abstract class ScriptProvider
+ implements XScriptProvider, XBrowseNode, XPropertySet, XInvocation,
+ XInitialization, XTypeProvider, XServiceInfo, XNameContainer
+{
+ private final String[] __serviceNames = {
+ "com.sun.star.script.provider.ScriptProviderFor",
+ "com.sun.star.script.provider.LanguageScriptProvider"
+ };
+
+ public final static String CLASSPATH = "classpath";
+
+ protected String language;
+
+ protected XComponentContext m_xContext;
+ protected XMultiComponentFactory m_xMultiComponentFactory;
+ protected XModel m_xModel;
+ protected XScriptInvocationContext m_xInvocContext;
+ protected ParcelContainer m_container;
+
+ // proxies to helper objects which implement interfaces
+ private XPropertySet m_xPropertySetProxy;
+ private XInvocation m_xInvocationProxy;
+ // TODO should this be implemented in this class
+ private XBrowseNode m_xBrowseNodeProxy;
+ private XScriptContext m_xScriptContext;
+
+ public ScriptProvider( XComponentContext ctx, String language )
+ {
+ this.language = language;
+ __serviceNames[0] += language;
+
+ LogUtils.DEBUG( "ScriptProvider: constructor - start. " + language );
+
+ m_xContext = ctx;
+
+ // Initialize DialogFactory class in case dialogs are required
+ DialogFactory.createDialogFactory(m_xContext);
+
+ try
+ {
+ m_xMultiComponentFactory = m_xContext.getServiceManager();
+
+ if ( m_xMultiComponentFactory == null )
+ {
+ throw new Exception( "Error could not obtain a " +
+ "multicomponent factory - rethrowing Exception." );
+ }
+
+ Object serviceObj = m_xContext.getValueByName(
+ "/singletons/com.sun.star.util.theMacroExpander");
+
+ XMacroExpander me = (XMacroExpander) AnyConverter.toObject(
+ new Type(XMacroExpander.class), serviceObj);
+
+ XMLParserFactory.setOfficeDTDURL(me.expandMacros(
+ "${$BRAND_BASE_DIR/program/bootstraprc::BaseInstallation}/share/dtd/officedocument/1_0/"));
+
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ throw new com.sun.star.uno.RuntimeException(
+ "Error constructing ScriptProvider: "
+ + e.getMessage() );
+ }
+
+ LogUtils.DEBUG( "ScriptProvider: constructor - finished." );
+ }
+
+ synchronized public XScriptContext getScriptingContext()
+ {
+ if ( m_xScriptContext == null )
+ {
+ m_xScriptContext = ScriptContext.createContext( m_xModel, m_xInvocContext, m_xContext, m_xMultiComponentFactory );
+ }
+ return m_xScriptContext;
+ }
+ public void initialize( Object[] aArguments )
+ throws com.sun.star.uno.Exception
+ {
+ LogUtils.DEBUG( "entering XInit for language " + language);
+ boolean isPkgProvider = false;
+ if( aArguments.length == 1 )
+ {
+ String contextUrl = null;
+ if ( AnyConverter.getType(aArguments[0]).getTypeClass().equals(TypeClass.INTERFACE) )
+ {
+ // try whether it denotes a XScriptInvocationContext
+ m_xInvocContext = (XScriptInvocationContext)UnoRuntime.queryInterface(
+ XScriptInvocationContext.class, aArguments[0]);
+ if ( m_xInvocContext != null )
+ {
+ // if so, obtain the document - by definition, this must be
+ // the ScriptContainer
+ m_xModel = (XModel)UnoRuntime.queryInterface( XModel.class,
+ m_xInvocContext.getScriptContainer() );
+ }
+ else
+ {
+ // otherwise, check whether it's an XModel
+ m_xModel = (XModel)UnoRuntime.queryInterface( XModel.class,
+ m_xInvocContext.getScriptContainer() );
+ }
+ if ( m_xModel == null )
+ {
+ throw new com.sun.star.uno.Exception(
+ "ScriptProvider argument must be either a string, a valid XScriptInvocationContext, " +
+ "or an XModel", this);
+ }
+
+ contextUrl = getDocUrlFromModel( m_xModel );
+ m_container = new ParcelContainer( m_xContext, contextUrl, language );
+ }
+ else if (AnyConverter.isString(aArguments[0]) == true)
+ {
+ String originalContextURL = AnyConverter.toString(aArguments[0]);
+ LogUtils.DEBUG("creating Application, path: " + originalContextURL );
+ contextUrl = originalContextURL;
+ // TODO no support for packages in documents yet
+ if ( originalContextURL.startsWith( "vnd.sun.star.tdoc" ) )
+ {
+ m_container = new ParcelContainer( m_xContext, contextUrl, language );
+ m_xModel = getModelFromDocUrl( originalContextURL );
+ }
+ else
+ {
+ if ( originalContextURL.startsWith( "share" ) )
+ {
+ contextUrl = "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" + PathUtils.BOOTSTRAP_NAME + "::BaseInstallation}/share";
+ }
+ else if ( originalContextURL.startsWith( "user" ) )
+ {
+ contextUrl = "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" + PathUtils.BOOTSTRAP_NAME + "::UserInstallation}/user";
+ }
+
+ if ( originalContextURL.endsWith( "uno_packages") )
+ {
+ isPkgProvider = true;
+ }
+ if ( originalContextURL.endsWith( "uno_packages") && !originalContextURL.equals( contextUrl ) )
+ {
+ contextUrl = PathUtils.make_url( contextUrl, "uno_packages" );
+ }
+ if ( isPkgProvider )
+ {
+ m_container = new UnoPkgContainer( m_xContext, contextUrl, language );
+ }
+ else
+ {
+ m_container = new ParcelContainer( m_xContext, contextUrl, language );
+ }
+ }
+ }
+ else
+ {
+ throw new com.sun.star.uno.RuntimeException(
+ "ScriptProvider created with invalid argument");
+ }
+
+ LogUtils.DEBUG("Modified Application path is: " + contextUrl );
+ LogUtils.DEBUG("isPkgProvider is: " + isPkgProvider );
+
+ // TODO should all be done in this class instead of
+ // deleagation????
+ m_xBrowseNodeProxy = new ProviderBrowseNode( this,
+ m_container, m_xContext );
+
+ m_xInvocationProxy = (XInvocation)UnoRuntime.queryInterface(XInvocation.class, m_xBrowseNodeProxy);
+ m_xPropertySetProxy = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, m_xBrowseNodeProxy);
+ }
+ else
+ {
+ // this is ok, for example when executing a script from the
+ // command line
+ LogUtils.DEBUG( "ScriptProviderFor" + language +
+ " initialized without a context");
+ }
+ LogUtils.DEBUG( "leaving XInit" );
+ }
+
+ /**
+ * Gets the types attribute of the ScriptProvider object
+ *
+ * @return The types value
+ */
+ public com.sun.star.uno.Type[] getTypes()
+ {
+ Type[] retValue = new Type[ 8 ];
+ retValue[ 0 ] = new Type( XScriptProvider.class );
+ retValue[ 1 ] = new Type( XBrowseNode.class );
+ retValue[ 2 ] = new Type( XInitialization.class );
+ retValue[ 3 ] = new Type( XTypeProvider.class );
+ retValue[ 4 ] = new Type( XServiceInfo.class );
+ retValue[ 5 ] = new Type( XPropertySet.class );
+ retValue[ 6 ] = new Type( XInvocation.class );
+ retValue[ 7 ] = new Type( com.sun.star.container.XNameContainer.class );
+ return retValue;
+ }
+
+ /**
+ * Gets the implementationId attribute of the ScriptProvider object
+ *
+ * @return The implementationId value
+ */
+ public byte[] getImplementationId()
+ {
+ return this.getClass().getName().getBytes();
+ }
+
+ /**
+ * Gets the implementationName attribute of the ScriptProvider object
+ *
+ * @return The implementationName value
+ */
+ public String getImplementationName()
+ {
+ return getClass().getName();
+ }
+
+ /**
+ * Description of the Method
+ *
+ * @param serviceName Description of the Parameter
+ * @return Description of the Return Value
+ */
+ public boolean supportsService( String serviceName )
+ {
+ for ( int index = __serviceNames.length; index-- > 0; )
+ {
+ if ( serviceName.equals( __serviceNames[ index ] ) )
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Gets the supportedServiceNames attribute of the ScriptProvider object
+ *
+ * @return The supportedServiceNames value
+ */
+ public String[] getSupportedServiceNames()
+ {
+ return __serviceNames;
+ }
+
+
+
+ public abstract XScript getScript( /*IN*/String scriptURI )
+ throws com.sun.star.uno.RuntimeException,
+ ScriptFrameworkErrorException;
+
+ // TODO need to encapsulate this better,
+ // Some factory concept for creating/accessing Editor
+ // How this is passed down or how it is accessable by BrowseNode
+ // implementations needs thinking about
+ // This method is used to determine whether the ScriptProvider
+ // has a ScriptEditor
+ public abstract boolean hasScriptEditor();
+ // TODO see above
+ // This method is used to get the ScriptEditor for this ScriptProvider
+ public abstract ScriptEditor getScriptEditor();
+
+ public ScriptMetaData getScriptData( /*IN*/String scriptURI ) throws ScriptFrameworkErrorException
+
+ {
+ ParsedScriptUri details = null;
+ try
+ {
+ details = m_container.parseScriptUri( scriptURI );
+ ScriptMetaData scriptData = m_container.findScript( details );
+ if ( scriptData == null )
+ {
+ throw new ScriptFrameworkErrorException( details.function + " does not exist",
+ null, details.function, language, ScriptFrameworkErrorType.NO_SUCH_SCRIPT );
+ }
+ return scriptData;
+ }
+ catch ( com.sun.star.lang.IllegalArgumentException ila )
+ {
+ // TODO specify the correct error Type
+ throw new ScriptFrameworkErrorException( ila.getMessage(),
+ null, scriptURI, language, ScriptFrameworkErrorType.UNKNOWN );
+ }
+ catch ( com.sun.star.container.NoSuchElementException nse )
+ {
+ throw new ScriptFrameworkErrorException( nse.getMessage(),
+ null, details.function, language, ScriptFrameworkErrorType.NO_SUCH_SCRIPT );
+ }
+ catch ( com.sun.star.lang.WrappedTargetException wta )
+ {
+ // TODO specify the correct error Type
+ Exception wrapped = (Exception)wta.TargetException;
+ String message = wta.getMessage();
+ if ( wrapped != null )
+ {
+ message = wrapped.getMessage();
+ }
+ throw new ScriptFrameworkErrorException( message,
+ null, details.function, language, ScriptFrameworkErrorType.UNKNOWN );
+ }
+
+ }
+
+
+ // Implementation of XBrowseNode interface
+ public String getName()
+ {
+ return language;
+ }
+
+ public XBrowseNode[] getChildNodes()
+ {
+ if ( m_xBrowseNodeProxy == null )
+ {
+ LogUtils.DEBUG("No Nodes available ");
+ return new XBrowseNode[0];
+ }
+ return m_xBrowseNodeProxy .getChildNodes();
+ }
+
+ public boolean hasChildNodes()
+ {
+ if ( m_xBrowseNodeProxy == null )
+ {
+ LogUtils.DEBUG("No Nodes available ");
+ return false;
+ }
+ return m_xBrowseNodeProxy.hasChildNodes();
+ }
+
+ public short getType()
+ {
+ return BrowseNodeTypes.CONTAINER;
+ }
+
+ public String toString()
+ {
+ return getName();
+ }
+
+ // implementation of XInvocation interface
+ public XIntrospectionAccess getIntrospection() {
+ return m_xInvocationProxy.getIntrospection();
+ }
+
+ public Object invoke(String aFunctionName, Object[] aParams,
+ short[][] aOutParamIndex, Object[][] aOutParam)
+ throws com.sun.star.lang.IllegalArgumentException,
+ com.sun.star.script.CannotConvertException,
+ com.sun.star.reflection.InvocationTargetException
+ {
+ return m_xInvocationProxy.invoke(
+ aFunctionName, aParams, aOutParamIndex, aOutParam);
+ }
+
+ public void setValue(String aPropertyName, Object aValue)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.script.CannotConvertException,
+ com.sun.star.reflection.InvocationTargetException
+ {
+ m_xInvocationProxy.setValue(aPropertyName, aValue);
+ }
+
+ public Object getValue(String aPropertyName)
+ throws com.sun.star.beans.UnknownPropertyException
+ {
+ return m_xInvocationProxy.getValue(aPropertyName);
+ }
+
+ public boolean hasMethod(String aName) {
+ return m_xInvocationProxy.hasMethod(aName);
+ }
+
+ public boolean hasProperty(String aName) {
+ return m_xInvocationProxy.hasProperty(aName);
+ }
+
+ public XPropertySetInfo getPropertySetInfo()
+ {
+ return m_xPropertySetProxy.getPropertySetInfo();
+ }
+
+ public void setPropertyValue(String aPropertyName, Object aValue)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.beans.PropertyVetoException,
+ com.sun.star.lang.IllegalArgumentException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ m_xPropertySetProxy.setPropertyValue(aPropertyName, aValue);
+ }
+
+ public Object getPropertyValue(String PropertyName)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ return m_xPropertySetProxy.getPropertyValue(PropertyName);
+ }
+
+ public void addPropertyChangeListener(
+ String aPropertyName, XPropertyChangeListener xListener)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ m_xPropertySetProxy.addPropertyChangeListener(aPropertyName, xListener);
+ }
+
+ public void removePropertyChangeListener(
+ String aPropertyName, XPropertyChangeListener aListener)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ m_xPropertySetProxy.removePropertyChangeListener(
+ aPropertyName, aListener);
+ }
+
+ public void addVetoableChangeListener(
+ String PropertyName, XVetoableChangeListener aListener)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ m_xPropertySetProxy.addVetoableChangeListener(PropertyName, aListener);
+ }
+
+ public void removeVetoableChangeListener(
+ String PropertyName, XVetoableChangeListener aListener)
+ throws com.sun.star.beans.UnknownPropertyException,
+ com.sun.star.lang.WrappedTargetException
+ {
+ m_xPropertySetProxy.removeVetoableChangeListener(
+ PropertyName, aListener);
+ }
+ public java.lang.Object getByName( String aName ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ // TODO needs implementing?
+ if ( true )
+ {
+ throw new com.sun.star.uno.RuntimeException(
+ "getByName not implemented" );
+ }
+ return new Object();
+ }
+
+ public String[] getElementNames()
+ {
+ // TODO needs implementing?
+ String[] result = new String[0];
+ if ( true )
+ {
+ throw new com.sun.star.uno.RuntimeException(
+ "getElementNames not implemented" );
+
+ }
+ return result;
+ }
+
+
+ // Performs the getRegStatus functionality for the PkgMgr
+ public boolean hasByName( String aName )
+ {
+ boolean result = false;
+ if ( ((UnoPkgContainer)m_container).hasRegisteredUnoPkgContainer( aName ) )
+ {
+ result = true;
+ }
+ return result;
+ }
+
+ public com.sun.star.uno.Type getElementType()
+ {
+ // TODO at the moment this returns void indicating
+ // type is unknown should indicate XPackage ? do we implement XPackage
+ return new Type();
+ }
+
+ public boolean hasElements()
+ {
+ // TODO needs implementing?
+ boolean result = false;
+ if ( true )
+ {
+ throw new com.sun.star.uno.RuntimeException(
+ "hasElements not implemented" );
+
+ }
+ return result;
+ }
+ public void replaceByName( String aName, java.lang.Object aElement ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ // TODO needs implementing
+ if ( true )
+ {
+ throw new com.sun.star.uno.RuntimeException(
+ "replaceByName not implemented" );
+
+ }
+ }
+
+ public void insertByName( String aName, java.lang.Object aElement ) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.container.ElementExistException, com.sun.star.lang.WrappedTargetException
+ {
+ LogUtils.DEBUG("Provider for " + language + " received register for package " + aName );
+ XPackage newPackage = ( XPackage ) UnoRuntime.queryInterface( XPackage.class, aElement );
+ if ( aName.length() == 0 )
+ {
+ throw new com.sun.star.lang.IllegalArgumentException( "Empty name" );
+ }
+ if ( newPackage == null )
+ {
+ throw new com.sun.star.lang.IllegalArgumentException( "No package supplied" );
+ }
+
+ ((UnoPkgContainer)m_container).processUnoPackage( newPackage, language );
+ }
+
+ // de-register for library only !!
+ public void removeByName( String Name ) throws com.sun.star.container.NoSuchElementException, com.sun.star.lang.WrappedTargetException
+ {
+ LogUtils.DEBUG("In ScriptProvider.removeByName() for " + Name + " this provider = " + language );
+ ParcelContainer c = ((UnoPkgContainer)m_container).getRegisteredUnoPkgContainer( Name );
+ if ( c != null )
+ {
+ String libName;
+ if (Name.endsWith("/"))
+ {
+ String tmp = Name.substring( 0, Name.lastIndexOf( "/" ) );
+ libName = tmp.substring( tmp.lastIndexOf( "/" ) + 1 );
+ }
+ else
+ {
+ libName = Name.substring( Name.lastIndexOf( "/" ) + 1 );
+ }
+ LogUtils.DEBUG("Deregistering library " + libName );
+ if ( c.removeParcel( libName ) )
+ {
+ ((UnoPkgContainer)m_container).deRegisterPackageContainer( Name );
+ }
+ else
+ {
+ throw new com.sun.star.container.NoSuchElementException( libName + " cannot be removed from container." );
+ }
+ }
+ else
+ {
+ throw new com.sun.star.container.NoSuchElementException( Name + " doesn't exist for " + language );
+ }
+ // TODO see if we want to remove the ParcelContainer is no Parcels/Libraries left
+ }
+
+ private String getDocUrlFromModel( XModel document )
+ {
+ XTransientDocumentsDocumentContentFactory factory = null;
+ try
+ {
+ factory = (XTransientDocumentsDocumentContentFactory)UnoRuntime.queryInterface(
+ XTransientDocumentsDocumentContentFactory.class,
+ m_xMultiComponentFactory.createInstanceWithContext(
+ "com.sun.star.frame.TransientDocumentsDocumentContentFactory",
+ m_xContext
+ )
+ );
+ }
+ catch (Exception ex)
+ {
+ }
+
+ if ( factory == null )
+ throw new com.sun.star.uno.RuntimeException( "ScriptProvider: unable to create a TDOC context factory.", this );
+
+ try
+ {
+ XContent content = factory.createDocumentContent( document );
+ return content.getIdentifier().getContentIdentifier();
+ }
+ catch( Exception ex )
+ {
+ }
+
+ LogUtils.DEBUG("unable to determine the model's TDOC URL");
+ return "";
+ }
+
+ private XModel getModelFromDocUrl( String docUrl )
+ {
+ LogUtils.DEBUG("getModelFromDocUrl - searching for match for ->" + docUrl + "<-" );
+ XModel xModel = null;
+ try
+ {
+ Object[] args = new String[] {"Local", "Office" };
+
+ Object ucb = m_xMultiComponentFactory.createInstanceWithArgumentsAndContext( "com.sun.star.ucb.UniversalContentBroker", args, m_xContext );
+
+
+ XContentIdentifierFactory xFac = ( XContentIdentifierFactory )
+ UnoRuntime.queryInterface( XContentIdentifierFactory.class,
+ ucb );
+
+
+ XContentIdentifier xCntId = xFac.createContentIdentifier( docUrl );
+
+
+ XContentProvider xCntAccess = ( XContentProvider )
+ UnoRuntime.queryInterface( XContentProvider.class,
+ ucb );
+
+
+ XContent xCnt = xCntAccess.queryContent( xCntId );
+
+
+ XCommandProcessor xCmd = ( XCommandProcessor )
+ UnoRuntime.queryInterface( XCommandProcessor.class, xCnt );
+
+
+ Property[] pArgs = new Property[ ] { new Property() };
+ pArgs[ 0 ].Name = "DocumentModel";
+ pArgs[ 0 ].Handle = -1;
+
+ Command command = new Command();
+
+ command.Handle = -1;
+ command.Name = "getPropertyValues";
+ command.Argument = pArgs;
+
+ com.sun.star.ucb.XCommandEnvironment env = null ;
+ Object result = xCmd.execute( command, 0, env ) ;
+
+ XRow values = ( XRow ) UnoRuntime.queryInterface( XRow.class,
+ result );
+
+ xModel = ( XModel ) UnoRuntime.queryInterface( XModel.class,
+ values.getObject( 1, null ) );
+ }
+ catch ( Exception ignore )
+ {
+ LogUtils.DEBUG("Failed to get model exception " + ignore );
+
+ }
+ return xModel;
+ }
+
+
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java
new file mode 100755
index 000000000000..617c99051250
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/PlainSourceView.java
@@ -0,0 +1,250 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: PlainSourceView.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.beanshell;
+
+import javax.swing.JTextArea;
+import javax.swing.JScrollPane;
+import javax.swing.JComponent;
+import javax.swing.event.DocumentListener;
+import javax.swing.event.DocumentEvent;
+
+import java.awt.Graphics;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Polygon;
+import java.awt.Rectangle;
+import java.awt.Dimension;
+
+public class PlainSourceView extends JScrollPane
+ implements ScriptSourceView, DocumentListener {
+
+ private ScriptSourceModel model;
+ private JTextArea ta;
+ private GlyphGutter gg;
+ private int linecount;
+ private boolean isModified = false;
+
+ public PlainSourceView(ScriptSourceModel model) {
+ this.model = model;
+ initUI();
+ model.setView(this);
+ }
+
+ public void clear() {
+ ta.setText("");
+ }
+
+ public void update() {
+ /* Remove ourselves as a DocumentListener while loading the source
+ so we don't get a storm of DocumentEvents during loading */
+ ta.getDocument().removeDocumentListener(this);
+
+ if (isModified == false)
+ {
+ int pos = ta.getCaretPosition();
+ ta.setText(model.getText());
+ try {
+ ta.setCaretPosition(pos);
+ }
+ catch (IllegalArgumentException iae) {
+ // do nothing and allow JTextArea to set it's own position
+ }
+ }
+
+ // scroll to currentPosition of the model
+ try {
+ int line = ta.getLineStartOffset(model.getCurrentPosition());
+ Rectangle rect = ta.modelToView(line);
+ ta.scrollRectToVisible(rect);
+ }
+ catch (Exception e) {
+ // couldn't scroll to line, do nothing
+ }
+
+ gg.repaint();
+
+ // Add back the listener
+ ta.getDocument().addDocumentListener(this);
+ }
+
+ public boolean isModified() {
+ return isModified;
+ }
+
+ public void setModified(boolean value) {
+ isModified = value;
+ }
+
+ private void initUI() {
+ ta = new JTextArea();
+ ta.setRows(15);
+ ta.setColumns(40);
+ ta.setLineWrap(false);
+ ta.insert(model.getText(), 0);
+ linecount = ta.getLineCount();
+
+ gg = new GlyphGutter(this);
+
+ setViewportView(ta);
+ setRowHeaderView(gg);
+
+ ta.getDocument().addDocumentListener(this);
+ }
+
+ /* Implementation of DocumentListener interface */
+ public void insertUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ public void removeUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ public void changedUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ /* If the number of lines in the JTextArea has changed then update the
+ GlyphGutter */
+ public void doChanged(DocumentEvent e) {
+ isModified = true;
+
+ if (linecount != ta.getLineCount()) {
+ gg.update();
+ linecount = ta.getLineCount();
+ }
+ }
+
+ public String getText() {
+ return ta.getText();
+ }
+
+ public JTextArea getTextArea() {
+ return ta;
+ }
+
+ public int getCurrentPosition() {
+ return model.getCurrentPosition();
+ }
+}
+
+class GlyphGutter extends JComponent {
+
+ private PlainSourceView view;
+ private final String DUMMY_STRING = "99";
+
+ GlyphGutter(PlainSourceView view) {
+ this.view = view;
+ update();
+ }
+
+ public void update() {
+ JTextArea textArea = view.getTextArea();
+ Font font = textArea.getFont();
+ setFont(font);
+
+ FontMetrics metrics = getFontMetrics(font);
+ int h = metrics.getHeight();
+ int lineCount = textArea.getLineCount() + 1;
+
+ String dummy = Integer.toString(lineCount);
+ if (dummy.length() < 2) {
+ dummy = DUMMY_STRING;
+ }
+
+ Dimension d = new Dimension();
+ d.width = metrics.stringWidth(dummy) + 16;
+ d.height = lineCount * h + 100;
+ setPreferredSize(d);
+ setSize(d);
+ }
+
+ public void paintComponent(Graphics g) {
+ JTextArea textArea = view.getTextArea();
+
+ Font font = textArea.getFont();
+ g.setFont(font);
+
+ FontMetrics metrics = getFontMetrics(font);
+ Rectangle clip = g.getClipBounds();
+
+ g.setColor(getBackground());
+ g.fillRect(clip.x, clip.y, clip.width, clip.height);
+
+ int ascent = metrics.getMaxAscent();
+ int h = metrics.getHeight();
+ int lineCount = textArea.getLineCount() + 1;
+
+ int startLine = clip.y / h;
+ int endLine = (clip.y + clip.height) / h + 1;
+ int width = getWidth();
+ if (endLine > lineCount) {
+ endLine = lineCount;
+ }
+
+ for (int i = startLine; i < endLine; i++) {
+ String text;
+ text = Integer.toString(i + 1) + " ";
+ int w = metrics.stringWidth(text);
+ int y = i * h;
+ g.setColor(Color.blue);
+ g.drawString(text, 0, y + ascent);
+ int x = width - ascent;
+
+ // if currentPosition is not -1 then a red arrow will be drawn
+ if (i == view.getCurrentPosition()) {
+ drawArrow(g, ascent, x, y);
+ }
+ }
+ }
+
+ private void drawArrow(Graphics g, int ascent, int x, int y) {
+ Polygon arrow = new Polygon();
+ int dx = x;
+ y += ascent - 10;
+ int dy = y;
+ arrow.addPoint(dx, dy + 3);
+ arrow.addPoint(dx + 5, dy + 3);
+ for (x = dx + 5; x <= dx + 10; x++, y++) {
+ arrow.addPoint(x, y);
+ }
+ for (x = dx + 9; x >= dx + 5; x--, y++) {
+ arrow.addPoint(x, y);
+ }
+ arrow.addPoint(dx + 5, dy + 7);
+ arrow.addPoint(dx, dy + 7);
+
+ g.setColor(Color.red);
+ g.fillPolygon(arrow);
+ g.setColor(Color.black);
+ g.drawPolygon(arrow);
+ }
+};
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java
new file mode 100644
index 000000000000..c7286ccb2a0a
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptEditorForBeanShell.java
@@ -0,0 +1,415 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptEditorForBeanShell.java,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.beanshell;
+
+import javax.swing.JComponent;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JButton;
+import javax.swing.JOptionPane;
+
+import java.awt.FlowLayout;
+import java.awt.event.ActionListener;
+import java.awt.event.ActionEvent;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.util.Map;
+import java.util.HashMap;
+
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.framework.provider.ScriptEditor;
+import com.sun.star.script.framework.container.ScriptMetaData;
+import com.sun.star.script.framework.provider.ClassLoaderFactory;
+
+public class ScriptEditorForBeanShell
+ implements ScriptEditor, ActionListener
+{
+ private JFrame frame;
+ private String filename;
+
+ private ScriptSourceModel model;
+ private ScriptSourceView view;
+
+ private XScriptContext context;
+ private URL scriptURL = null;
+ private ClassLoader cl = null;
+
+ // global ScriptEditorForBeanShell returned for getEditor() calls
+ private static ScriptEditorForBeanShell theScriptEditorForBeanShell;
+
+ // global list of ScriptEditors, key is URL of file being edited
+ private static Map BEING_EDITED = new HashMap();
+
+ // template for new BeanShell scripts
+ private static String BSHTEMPLATE;
+
+ // try to load the template for BeanShell scripts
+ static {
+ try {
+ URL url =
+ ScriptEditorForBeanShell.class.getResource("template.bsh");
+
+ InputStream in = url.openStream();
+ StringBuffer buf = new StringBuffer();
+ byte[] b = new byte[1024];
+ int len = 0;
+
+ while ((len = in.read(b)) != -1) {
+ buf.append(new String(b, 0, len));
+ }
+
+ in.close();
+
+ BSHTEMPLATE = buf.toString();
+ }
+ catch (IOException ioe) {
+ BSHTEMPLATE = "// BeanShell script";
+ }
+ catch (Exception e) {
+ BSHTEMPLATE = "// BeanShell script";
+ }
+ }
+
+ /**
+ * Returns the global ScriptEditorForBeanShell instance.
+ */
+ public static ScriptEditorForBeanShell getEditor()
+ {
+ if (theScriptEditorForBeanShell == null)
+ {
+ synchronized(ScriptEditorForBeanShell.class)
+ {
+ if (theScriptEditorForBeanShell == null)
+ {
+ theScriptEditorForBeanShell =
+ new ScriptEditorForBeanShell();
+ }
+ }
+ }
+ return theScriptEditorForBeanShell;
+ }
+
+ /**
+ * Get the ScriptEditorForBeanShell instance for this URL
+ *
+ * @param url The URL of the script source file
+ *
+ * @return The ScriptEditorForBeanShell associated with
+ * the given URL if one exists, otherwise null.
+ */
+ public static ScriptEditorForBeanShell getEditor(URL url)
+ {
+ return (ScriptEditorForBeanShell)BEING_EDITED.get(url);
+ }
+
+ /**
+ * Returns whether or not the script source being edited in this
+ * ScriptEditorForBeanShell has been modified
+ */
+ public boolean isModified()
+ {
+ return view.isModified();
+ }
+
+ /**
+ * Returns the text being displayed in this ScriptEditorForBeanShell
+ *
+ * @return The text displayed in this ScriptEditorForBeanShell
+ */
+ public String getText()
+ {
+ return view.getText();
+ }
+
+ /**
+ * Returns the template text for BeanShell scripts
+ *
+ * @return The template text for BeanShell scripts
+ */
+ public String getTemplate() {
+ return BSHTEMPLATE;
+ }
+
+ /**
+ * Returns the default extension for BeanShell scripts
+ *
+ * @return The default extension for BeanShell scripts
+ */
+ public String getExtension() {
+ return "bsh";
+ }
+
+
+ /**
+ * Indicates the line where error occured
+ *
+ */
+ public void indicateErrorLine( int lineNum )
+ {
+ model.indicateErrorLine( lineNum );
+ }
+ /**
+ * Executes the script edited by the editor
+ *
+ */
+ public Object execute() throws Exception {
+ frame.toFront();
+ return model.execute( context, cl );
+ }
+ /**
+ * Opens an editor window for the specified ScriptMetaData.
+ * If an editor window is already open for that data it will be
+ * moved to the front.
+ *
+ * @param metadata The metadata describing the script
+ * @param context The context in which to execute the script
+ *
+ */
+ public void edit(XScriptContext context, ScriptMetaData entry) {
+
+ if (entry != null ) {
+ try {
+ ClassLoader cl = null;
+ try {
+ cl = ClassLoaderFactory.getURLClassLoader( entry );
+ }
+ catch (Exception ignore) // TODO re-examine error handling
+ {
+ }
+ String sUrl = entry.getParcelLocation();
+ if ( !sUrl.endsWith( "/" ) )
+ {
+ sUrl += "/";
+ }
+ sUrl += entry.getLanguageName();
+ URL url = entry.getSourceURL();
+
+ // check if there is already an editing session for this script
+ if (BEING_EDITED.containsKey(url))
+ {
+ ScriptEditorForBeanShell editor =
+ (ScriptEditorForBeanShell) BEING_EDITED.get(url);
+
+ editor.frame.toFront();
+ }
+ else
+ {
+ new ScriptEditorForBeanShell(context, cl, url);
+ }
+ }
+ catch (IOException ioe) {
+ showErrorMessage( "Error loading file: " + ioe.getMessage() );
+ }
+ }
+ }
+
+ private ScriptEditorForBeanShell() {
+ }
+
+ private ScriptEditorForBeanShell(XScriptContext context, ClassLoader cl,
+ URL url)
+ {
+ this.context = context;
+ this.scriptURL = url;
+ this.model = new ScriptSourceModel(url);
+ this.filename = url.getFile();
+ this.cl = cl;
+ try {
+ Class c = Class.forName(
+ "org.openoffice.netbeans.editor.NetBeansSourceView");
+
+ Class[] types = new Class[] { ScriptSourceModel.class };
+
+ java.lang.reflect.Constructor ctor = c.getConstructor(types);
+
+ if (ctor != null) {
+ Object[] args = new Object[] { this.model };
+ this.view = (ScriptSourceView) ctor.newInstance(args);
+ }
+ else {
+ this.view = new PlainSourceView(model);
+ }
+ }
+ catch (java.lang.Error err) {
+ this.view = new PlainSourceView(model);
+ }
+ catch (Exception e) {
+ this.view = new PlainSourceView(model);
+ }
+
+ this.model.setView(this.view);
+ initUI();
+ frame.show();
+
+ BEING_EDITED.put(url, this);
+ }
+
+ private void showErrorMessage(String message) {
+ JOptionPane.showMessageDialog(frame, message,
+ "Error", JOptionPane.ERROR_MESSAGE);
+ }
+
+ private void initUI() {
+ frame = new JFrame("BeanShell Debug Window: " + filename);
+ frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
+
+ frame.addWindowListener(
+ new WindowAdapter()
+ {
+ public void windowClosing(WindowEvent e) {
+ doClose();
+ }
+ }
+ );
+
+ String[] labels = {"Run", "Clear", "Save", "Close"};
+ JPanel p = new JPanel();
+ p.setLayout(new FlowLayout());
+
+ for (int i = 0; i < labels.length; i++) {
+ JButton b = new JButton(labels[i]);
+ b.addActionListener(this);
+ p.add(b);
+
+ if (labels[i].equals("Save") && filename == null) {
+ b.setEnabled(false);
+ }
+ }
+
+ frame.getContentPane().add((JComponent)view, "Center");
+ frame.getContentPane().add(p, "South");
+ frame.pack();
+ frame.setSize(590, 480);
+ frame.setLocation(300, 200);
+ }
+
+ private void doClose() {
+ if (view.isModified()) {
+ int result = JOptionPane.showConfirmDialog(frame,
+ "The script has been modified. " +
+ "Do you want to save the changes?");
+
+ if (result == JOptionPane.CANCEL_OPTION)
+ {
+ // don't close the window, just return
+ return;
+ }
+ else if (result == JOptionPane.YES_OPTION)
+ {
+ boolean saveSuccess = saveTextArea();
+ if (saveSuccess == false)
+ {
+ return;
+ }
+ }
+ }
+ frame.dispose();
+ shutdown();
+ }
+
+ private boolean saveTextArea() {
+ boolean result = true;
+
+ if (!view.isModified()) {
+ return true;
+ }
+
+ OutputStream fos = null;
+ try {
+ String s = view.getText();
+ fos = scriptURL.openConnection().getOutputStream();
+ if ( fos != null) {
+ fos.write(s.getBytes());
+ }
+ else
+ {
+ showErrorMessage(
+ "Error saving script: Could not open stream for file" );
+ result = false;
+ }
+ view.setModified(false);
+ }
+ catch (IOException ioe) {
+ showErrorMessage( "Error saving script: " + ioe.getMessage() );
+ result = false;
+ }
+ catch (Exception e) {
+ showErrorMessage( "Error saving script: " + e.getMessage() );
+ result = false;
+ }
+ finally {
+ if (fos != null) {
+ try {
+ fos.flush();
+ if ( fos != null )
+ {
+ fos.close();
+ }
+ }
+ catch (IOException ignore) {
+ }
+ }
+ }
+ return result;
+ }
+
+ private void shutdown()
+ {
+ if (BEING_EDITED.containsKey(scriptURL)) {
+ BEING_EDITED.remove(scriptURL);
+ }
+ }
+
+ public void actionPerformed(ActionEvent e) {
+ if (e.getActionCommand().equals("Run")) {
+ try
+ {
+ execute();
+ }
+ catch (Exception invokeException ) {
+ showErrorMessage(invokeException.getMessage());
+ }
+ }
+ else if (e.getActionCommand().equals("Close")) {
+ doClose();
+ }
+ else if (e.getActionCommand().equals("Save")) {
+ saveTextArea();
+ }
+ else if (e.getActionCommand().equals("Clear")) {
+ view.clear();
+ }
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java
new file mode 100755
index 000000000000..732013601c76
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptProviderForBeanShell.java
@@ -0,0 +1,421 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptProviderForBeanShell.java,v $
+ * $Revision: 1.11.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.beanshell;
+
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.XSingleServiceFactory;
+import com.sun.star.registry.XRegistryKey;
+import com.sun.star.comp.loader.FactoryHelper;
+import com.sun.star.frame.XModel;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.Any;
+
+import com.sun.star.reflection.InvocationTargetException;
+
+import java.util.StringTokenizer;
+
+import java.net.URL;
+
+import bsh.Interpreter;
+
+import com.sun.star.document.XScriptInvocationContext;
+import com.sun.star.script.provider.XScript;
+import com.sun.star.script.provider.ScriptErrorRaisedException;
+import com.sun.star.script.provider.ScriptExceptionRaisedException;
+import com.sun.star.script.provider.ScriptFrameworkErrorException;
+import com.sun.star.script.provider.ScriptFrameworkErrorType;
+
+
+import com.sun.star.script.framework.provider.*;
+import com.sun.star.script.framework.log.*;
+import com.sun.star.script.framework.container.ScriptMetaData;
+
+public class ScriptProviderForBeanShell
+{
+ public static class _ScriptProviderForBeanShell extends ScriptProvider
+ {
+ public _ScriptProviderForBeanShell(XComponentContext ctx)
+ {
+ super (ctx, "BeanShell");
+ }
+
+ public XScript getScript( /*IN*/String scriptURI )
+ throws com.sun.star.uno.RuntimeException,
+ ScriptFrameworkErrorException
+ {
+ ScriptMetaData scriptData = null;
+ try
+ {
+ scriptData = getScriptData( scriptURI );
+ ScriptImpl script = new ScriptImpl( m_xContext, scriptData, m_xModel, m_xInvocContext );
+ return script;
+ }
+ catch ( com.sun.star.uno.RuntimeException re )
+ {
+ throw new ScriptFrameworkErrorException( "Failed to create script object: " + re.getMessage(),
+ null, scriptData.getLanguageName(), language, ScriptFrameworkErrorType.UNKNOWN );
+ }
+ }
+
+ public boolean hasScriptEditor()
+ {
+ return true;
+ }
+
+ public ScriptEditor getScriptEditor()
+ {
+ return ScriptEditorForBeanShell.getEditor();
+ }
+ }
+
+ /**
+ * Returns a factory for creating the service.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param implName the name of the implementation for which a service is desired
+ * @param multiFactory the service manager to be used if needed
+ * @param regKey the registryKey
+ * @return returns a <code>XSingleServiceFactory</code> for creating
+ * the component
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static XSingleServiceFactory __getServiceFactory( String implName,
+ XMultiServiceFactory multiFactory,
+ XRegistryKey regKey )
+ {
+ XSingleServiceFactory xSingleServiceFactory = null;
+
+ if ( implName.equals( ScriptProviderForBeanShell._ScriptProviderForBeanShell.class.getName() ) )
+ {
+ xSingleServiceFactory = FactoryHelper.getServiceFactory(
+ ScriptProviderForBeanShell._ScriptProviderForBeanShell.class,
+ "com.sun.star.script.ScriptProviderForBeanShell",
+ multiFactory,
+ regKey );
+ }
+
+ return xSingleServiceFactory;
+ }
+
+
+ /**
+ * Writes the service information into the given registry key.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param regKey the registryKey
+ * @return returns true if the operation succeeded
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static boolean __writeRegistryServiceInfo( XRegistryKey regKey )
+ {
+ String impl = "com.sun.star.script.framework.provider.beanshell." +
+ "ScriptProviderForBeanShell$_ScriptProviderForBeanShell";
+
+ String service1 = "com.sun.star.script.provider." +
+ "ScriptProvider";
+ String service2 = "com.sun.star.script.provider." +
+ "LanguageScriptProvider";
+ String service3 = "com.sun.star.script.provider." +
+ "ScriptProviderForBeanShell";
+ String service4 = "com.sun.star.script.browse." +
+ "BrowseNode";
+
+ if ( FactoryHelper.writeRegistryServiceInfo(impl, service1, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service2, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service3, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service4, regKey) )
+ {
+ return true;
+ }
+ return false;
+ }
+
+}
+
+class ScriptImpl implements XScript
+{
+ private ScriptMetaData metaData;
+ private XComponentContext m_xContext;
+ private XMultiComponentFactory m_xMultiComponentFactory;
+ private XModel m_xModel;
+ private XScriptInvocationContext m_xInvocContext;
+
+ ScriptImpl( XComponentContext ctx, ScriptMetaData metaData, XModel xModel,
+ XScriptInvocationContext xContext ) throws com.sun.star.uno.RuntimeException
+ {
+ this.metaData = metaData;
+ this.m_xContext = ctx;
+ this.m_xModel = xModel;
+ this.m_xInvocContext = xContext;
+
+ try
+ {
+ this.m_xMultiComponentFactory = m_xContext.getServiceManager();
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ throw new com.sun.star.uno.RuntimeException(
+ "Error constructing ScriptImpl [beanshell]: "
+ + e.getMessage() );
+ }
+
+ LogUtils.DEBUG("ScriptImpl [beanshell] script data = " + metaData );
+ }
+ /**
+ * documentStorageID and document reference
+ * for use in script name resolving
+ *
+ * @param aParams All parameters; pure, out params are
+ * undefined in sequence, i.e., the value
+ * has to be ignored by the callee
+ *
+ * @param aOutParamIndex Out indices
+ *
+ * @param aOutParam Out parameters
+ *
+ * @returns The value returned from the function
+ * being invoked
+ *
+ * @throws IllegalArgumentException If there is no matching script name
+ *
+ * @throws CannotConvertException If args do not match or cannot
+ * be converted the those of the
+ * invokee
+ *
+ * @throws InvocationTargetException If the running script throws
+ * an exception this information
+ * is captured and rethrown as
+ * this exception type.
+ */
+
+ public Object invoke( /*IN*/Object[] aParams,
+ /*OUT*/short[][] aOutParamIndex,
+ /*OUT*/Object[][] aOutParam )
+ throws ScriptFrameworkErrorException,
+ InvocationTargetException
+ {
+ // Initialise the out paramters - not used at the moment
+ aOutParamIndex[0] = new short[0];
+ aOutParam[0] = new Object[0];
+
+
+ ClassLoader cl = null;
+ URL sourceUrl = null;
+ try {
+ cl = ClassLoaderFactory.getURLClassLoader( metaData );
+ sourceUrl = metaData.getSourceURL();
+ }
+ catch ( java.net.MalformedURLException mfu )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ mfu.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.MALFORMED_URL );
+ }
+ catch ( NoSuitableClassLoaderException nsc )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ nsc.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ // Set class loader to be used for class files
+ // and jar files
+ Thread.currentThread().setContextClassLoader(cl);
+ Interpreter interpreter = new Interpreter();
+
+ interpreter.getNameSpace().clear();
+ // Set class loader to be used by interpreter
+ // to look for classes by source e.g. interpreter
+ // will use this classloader to search classpath
+ // for source file ( bla.java ) on import or reference
+ interpreter.setClassLoader(cl);
+ try {
+ interpreter.set("XSCRIPTCONTEXT",
+ ScriptContext.createContext(m_xModel, m_xInvocContext,
+ m_xContext, m_xMultiComponentFactory));
+
+ interpreter.set("ARGUMENTS", aParams);
+ }
+ catch (bsh.EvalError e) {
+ // Framework error setting up context
+ throw new ScriptFrameworkErrorException(
+ e.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+
+ try {
+ String source = null;
+ Object result = null;
+
+ ScriptEditorForBeanShell editor =
+ ScriptEditorForBeanShell.getEditor(
+ sourceUrl );
+
+ if ( editor != null )
+ {
+ result = editor.execute();
+
+ if (result == null)
+ {
+ return new Any(new Type(), null);
+ }
+ return result;
+ }
+
+ metaData.loadSource();
+ source = metaData.getSource();
+
+ if ( source == null || source.length() == 0 )
+ {
+ throw new ScriptFrameworkErrorException(
+ "Failed to read script", null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.NO_SUCH_SCRIPT );
+ }
+ result = interpreter.eval( source );
+
+ if (result == null)
+ {
+ return new Any(new Type(), null);
+ }
+ return result;
+ }
+ catch ( bsh.ParseException pe )
+ {
+ throw new InvocationTargetException( "Beanshell failed to parse " + metaData.getLanguageName(), null, processBshException( pe, metaData.getLanguageName() ) );
+ }
+ catch ( bsh.TargetError te )
+ {
+ throw new InvocationTargetException( "Beanshell uncaught exception for " + metaData.getLanguageName(), null, processBshException( te, metaData.getLanguageName() ) );
+ }
+ catch ( bsh.EvalError ex )
+ {
+ throw new InvocationTargetException( "Beanshell error for " + metaData.getLanguageName(), null, processBshException( ex, metaData.getLanguageName() ) );
+ }
+ catch ( Exception e )
+ {
+ throw new ScriptFrameworkErrorException(
+ "Failed to read script", null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ }
+ private void raiseEditor( int lineNum )
+ {
+ ScriptEditorForBeanShell editor = null;
+ try
+ {
+ URL sourceUrl = metaData.getSourceURL();
+ editor = ScriptEditorForBeanShell.getEditor( sourceUrl );
+ if ( editor == null )
+ {
+ editor = ScriptEditorForBeanShell.getEditor();
+ editor.edit(
+ ScriptContext.createContext(m_xModel, m_xInvocContext,
+ m_xContext, m_xMultiComponentFactory), metaData );
+ editor = ScriptEditorForBeanShell.getEditor( sourceUrl );
+ }
+ if ( editor != null )
+ {
+ editor.indicateErrorLine( lineNum );
+ }
+ }
+ catch( Exception ignore )
+ {
+ }
+ }
+
+ private ScriptErrorRaisedException processBshException( bsh.EvalError e, String script )
+ {
+ LogUtils.DEBUG("Beanshell error RAW message " + e.getMessage());
+ String message = e.getMessage();
+ int usefullInfoIndex = message.lastIndexOf("\' :" );
+ int lineNum = e.getErrorLineNumber();
+
+ raiseEditor( lineNum );
+
+ //String stackTrace = te.getScriptStackTrace(); // never seems to have any info??
+ if ( usefullInfoIndex > -1 )
+ {
+ message = message.substring( usefullInfoIndex + 2 );
+ }
+ if ( e instanceof bsh.TargetError )
+ {
+ LogUtils.DEBUG("got instance of TargetError");
+ if ( usefullInfoIndex == -1 )
+ {
+ message = ( ( bsh.TargetError)e ).getTarget().getMessage();
+ }
+ String wrappedException = "";
+ String full = e.toString();
+ int index = full.indexOf( "Target exception:" );
+ if ( index > -1 )
+ {
+ String toParse = full.substring( index );
+ LogUtils.DEBUG("About to parse " + toParse );
+ StringTokenizer tokenizer = new StringTokenizer( full.substring( index ),":" );
+ if ( tokenizer.countTokens() > 2 )
+ {
+ LogUtils.DEBUG("First token = " + (String)tokenizer.nextElement());
+ wrappedException = (String)tokenizer.nextElement();
+ LogUtils.DEBUG("wrapped exception = = " + wrappedException );
+ }
+ }
+ ScriptExceptionRaisedException se = new ScriptExceptionRaisedException( message);
+ se.lineNum = lineNum;
+ se.scriptName = script;
+ se.exceptionType = wrappedException;
+ se.language = "BeanShell";
+ LogUtils.DEBUG("UnCaught Exception error: " );
+ LogUtils.DEBUG("\tscript: " + script );
+ LogUtils.DEBUG("\tline: " + lineNum );
+ LogUtils.DEBUG("\twrapped exception: " + wrappedException );
+ LogUtils.DEBUG("\tmessage: " + message );
+ return se;
+ }
+ else
+ {
+ LogUtils.DEBUG("Error or ParseError Exception error: " );
+ LogUtils.DEBUG("\tscript: " + script );
+ LogUtils.DEBUG("\tline: " + lineNum );
+ LogUtils.DEBUG("\tmessage: " + message );
+ return new ScriptErrorRaisedException( message, null, script, "BeanShell", lineNum );
+ }
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java
new file mode 100644
index 000000000000..186fed25a6e4
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceModel.java
@@ -0,0 +1,144 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptSourceModel.java,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.beanshell;
+
+import java.io.InputStream;
+import java.io.IOException;
+
+import java.net.URL;
+
+import com.sun.star.script.provider.XScriptContext;
+
+public class ScriptSourceModel {
+
+ private int currentPosition = -1;
+ private URL file = null;
+ private ScriptSourceView view = null;
+
+ public ScriptSourceModel(URL file ) {
+ this.file = file;
+ }
+
+ private String load() throws IOException {
+ StringBuffer buf = new StringBuffer();
+ InputStream in = file.openStream();
+
+ byte[] contents = new byte[1024];
+ int len = 0;
+
+ while ((len = in.read(contents, 0, 1024)) != -1) {
+ buf.append(new String(contents, 0, len));
+ }
+
+ try {
+ in.close();
+ }
+ catch (IOException ignore) {
+ }
+
+ return buf.toString();
+ }
+
+ public String getText() {
+ String result = "";
+
+ try {
+ result = load();
+ }
+ catch (IOException ioe) {
+ // do nothing, empty string will be returned
+ }
+
+ return result;
+ }
+
+ public int getCurrentPosition() {
+ return this.currentPosition;
+ }
+
+ public void setView(ScriptSourceView view) {
+ this.view = view;
+ }
+
+ public Object execute(final XScriptContext context, ClassLoader cl )
+ throws Exception
+ {
+ Object result = null;
+ // Thread execThread = new Thread() {
+ // public void run() {
+ if ( cl != null )
+ {
+ // sets this threads class loader
+ // hopefully any threads spawned by this
+ // will inherit this cl
+ // this enables any class files imported
+ // from the interpreter to be loaded
+ // note: setting the classloader on the
+ // interpreter has a slightly different
+ // meaning in that the classloader for
+ // the interpreter seems only to look for
+ // source files ( bla.java ) in the classpath
+ Thread.currentThread().setContextClassLoader(cl);
+ }
+ bsh.Interpreter interpreter = new bsh.Interpreter();
+ if ( cl != null )
+ {
+ // additionally set class loader on the interpreter
+ // to allow it to load java classes defined in source
+ // files e.g. bla.java
+ interpreter.getNameSpace().clear();
+ }
+
+
+ // reset position
+ currentPosition = -1;
+ view.update();
+
+ interpreter.set("XSCRIPTCONTEXT", context);
+ interpreter.set("ARGUMENTS", new Object[0]);
+
+ if (view.isModified()) {
+ result = interpreter.eval(view.getText());
+ }
+ else {
+ result = interpreter.eval(getText());
+ }
+ // }
+ // };
+ // execThread.start();
+ return result;
+ }
+ public void indicateErrorLine( int lineNum )
+ {
+ System.out.println("Beanshell indicateErrorLine " + lineNum );
+ currentPosition = lineNum - 1;
+ view.update();
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceView.java b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceView.java
new file mode 100644
index 000000000000..98d5214d4a78
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/ScriptSourceView.java
@@ -0,0 +1,38 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptSourceView.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.beanshell;
+
+public interface ScriptSourceView {
+ public void clear();
+ public void update();
+ public boolean isModified();
+ public void setModified(boolean value);
+ public String getText();
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/beanshell/template.bsh b/scripting/java/com/sun/star/script/framework/provider/beanshell/template.bsh
new file mode 100644
index 000000000000..03cb114d79b7
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/beanshell/template.bsh
@@ -0,0 +1,48 @@
+/*
+ Import standard OpenOffice.org API classes. For more information on
+ these classes and the OpenOffice.org API, see the OpenOffice.org
+ Developers Guide at:
+
+ http://api.openoffice.org/
+*/
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.frame.XDesktop;
+import com.sun.star.frame.XModel;
+
+/*
+ Import XScriptContext class. An instance of this class is available
+ to all BeanShell scripts in the global variable "XSCRIPTCONTEXT". This
+ variable can be used to access the document for which this script
+ was invoked.
+
+ Methods available are:
+
+ XSCRIPTCONTEXT.getDocument() returns XModel
+ XSCRIPTCONTEXT.getInvocationContext() returns XScriptInvocationContext or NULL
+ XSCRIPTCONTEXT.getDesktop() returns XDesktop
+ XSCRIPTCONTEXT.getComponentContext() returns XComponentContext
+
+ For more information on using this class see the scripting
+ developer guides at:
+
+ http://api.openoffice.org/docs/DevelopersGuide/ScriptingFramework/ScriptingFramework.xhtml
+*/
+
+// Hello World in BeanShell
+import com.sun.star.text.XTextDocument;
+import com.sun.star.text.XText;
+import com.sun.star.text.XTextRange;
+
+oDoc = UnoRuntime.queryInterface(XModel.class,XSCRIPTCONTEXT.getInvocationContext());
+if ( oDoc == null )
+ oDoc = XSCRIPTCONTEXT.getDocument();
+
+xTextDoc = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class,oDoc);
+xText = xTextDoc.getText();
+xTextRange = xText.getEnd();
+xTextRange.setString( "Hello World (in BeanShell)" );
+
+// BeanShell OpenOffice.org scripts should always return 0
+return 0;
diff --git a/scripting/java/com/sun/star/script/framework/provider/java/Resolver.java b/scripting/java/com/sun/star/script/framework/provider/java/Resolver.java
new file mode 100755
index 000000000000..addea113390a
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/java/Resolver.java
@@ -0,0 +1,53 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: Resolver.java,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.provider.java;
+
+/**
+ * The Resolver interface is an interface common to all classes which
+ * want to implement an algorithm for obtaining a ScriptProxy object
+ * for a particular ScriptDescriptor and Class
+ *
+ * @author Tomas O'Connor
+ * @created August 2, 2002
+ */
+
+public interface Resolver {
+ /**
+ * Returns a ScriptProxy object for the given ScriptDescriptor and Class
+ *
+ * @param sd A script Descriptor
+ * @param c A Class
+ * @return The ScriptProxy value
+ */
+ public ScriptProxy getProxy( ScriptDescriptor sd, Class c )
+ throws NoSuchMethodException;
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java b/scripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java
new file mode 100755
index 000000000000..35bdf76f9ae9
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/java/ScriptDescriptor.java
@@ -0,0 +1,215 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptDescriptor.java,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+package com.sun.star.script.framework.provider.java;
+
+import java.util.Vector;
+import java.util.StringTokenizer;
+
+/**
+ * The <code>ScriptDescriptor</code> object is used to store the search
+ * criteria that should be used for finding a particular script
+ *
+ * @author Tomas O'Connor
+ * @created August 2, 2002
+ */
+public class ScriptDescriptor
+{
+ private String m_name;
+ private String m_methodName;
+ private String m_className;
+ private Vector m_classpath;
+ private Vector m_argumentTypes = new Vector( 11 );
+
+
+ /**
+ * Constructs a ScriptDescriptor for the given name
+ *
+ * @param name Script Name
+ * @exception IllegalArgumentException if the given name does not contain a "."
+ */
+ public ScriptDescriptor( String name )
+ throws IllegalArgumentException
+ {
+ int idx = name.lastIndexOf( '.' );
+
+ if ( idx == -1 )
+ {
+ throw new IllegalArgumentException( "Invalid method name" );
+ }
+
+ this.m_name = name;
+ this.m_methodName = name.substring( idx + 1 );
+ this.m_className = name.substring( 0, idx );
+ }
+
+
+ /**
+ * Gets the fully qualified name of this <code>ScriptDescriptor</code>
+ *
+ * @return The Script Name value
+ */
+ public String getName()
+ {
+ return m_name;
+ }
+
+ /**
+ * Gets the fully qualified name of this <code>ScriptDescriptor</code>
+ *
+ * @return The Script Name value
+ */
+ public String getClassName()
+ {
+ return m_className;
+ }
+
+
+ /**
+ * Gets the method name of this <code>ScriptDescriptor</code>
+ *
+ * @return The methodName value
+ */
+ public String getMethodName()
+ {
+ return m_methodName;
+ }
+
+
+ /**
+ * Sets the classpath value stored by this <code>ScriptDescriptor</code>
+ *
+ * @param classpath The new classpath value
+ */
+ public void setClasspath( String classpath )
+ {
+ StringTokenizer stk = new StringTokenizer( classpath, ":" );
+ while( stk.hasMoreElements() )
+ {
+ this.m_classpath.add( (String) stk.nextElement() );
+ }
+ }
+
+ /**
+ * Sets the classpath value stored by this <code>ScriptDescriptor</code>
+ *
+ * @param classpath The new classpath value
+ */
+ public void setClasspath( Vector classpath )
+ {
+ this.m_classpath = classpath;
+ }
+
+
+ /**
+ * Gets the classpath value stored by this <code>ScriptDescriptor</code>
+ *
+ * @return The classpath value
+ */
+ public Vector getClasspath()
+ {
+ return m_classpath;
+ }
+
+
+ /**
+ * Adds the given <code>Class</code> to the list of argument types stored in
+ * this ScriptDescriptor
+ *
+ * @param clazz The feature to be added to the ArgumentType attribute
+ */
+ public synchronized void addArgumentType( Class clazz )
+ {
+ m_argumentTypes.addElement( clazz );
+ }
+
+
+ /**
+ * Adds the given array of <code>Class</code> to the list of argument types
+ * stored in this ScriptDescriptor
+ *
+ * @param classes The feature to be added to the ArgumentTypes attribute
+ */
+ public synchronized void addArgumentTypes( Class[] classes )
+ {
+ for ( int i = 0; i < classes.length; i++ )
+ {
+ addArgumentType( classes[ i ] );
+ }
+ }
+
+
+ /**
+ * Gets a list of the types of the arguments stored in this
+ * <code>ScriptDescriptor</code>
+ *
+ * return the argument types as an array of Class
+ *
+ * @return The argumentTypes value
+ */
+ public synchronized Class[]
+ getArgumentTypes()
+ {
+ if ( m_argumentTypes.size() > 0 )
+ return ( Class[] ) m_argumentTypes.toArray( new Class[ 0 ] );
+ else
+ return null;
+ }
+
+
+ /**
+ * Returns a <code>String</code> representation of this
+ * <code>ScriptDescriptor</code>
+ *
+ * @return The scriptName including the parameters.
+ */
+ public String toString()
+ {
+ StringBuffer description = new StringBuffer( m_name );
+ Class[] types = getArgumentTypes();
+
+ description.append( " (" );
+
+ if ( types != null )
+ {
+ for ( int i = 0; i < types.length - 1; i++ )
+ {
+ description.append( types[ i ].getName() );
+ description.append( ", " );
+ }
+
+ description.append( types[ types.length - 1 ].getName() );
+ }
+ description.append( ")" );
+
+ return description.toString();
+ }
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java
new file mode 100755
index 000000000000..14fcfa348137
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProviderForJava.java
@@ -0,0 +1,402 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptProviderForJava.java,v $
+ * $Revision: 1.10.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.java;
+
+import com.sun.star.frame.XModel;
+import com.sun.star.comp.loader.FactoryHelper;
+import com.sun.star.document.XScriptInvocationContext;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.XSingleServiceFactory;
+import com.sun.star.registry.XRegistryKey;
+import com.sun.star.uno.Type;
+import com.sun.star.uno.Any;
+
+import java.util.ArrayList;
+import java.util.Map;
+import java.net.MalformedURLException;
+
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.provider.XScript;
+import com.sun.star.script.provider.ScriptExceptionRaisedException;
+import com.sun.star.script.provider.ScriptFrameworkErrorException;
+import com.sun.star.script.provider.ScriptFrameworkErrorType;
+
+import com.sun.star.script.framework.container.ScriptMetaData;
+
+import com.sun.star.script.framework.provider.*;
+import com.sun.star.script.framework.log.LogUtils;
+/**
+ * Description of the Class
+ *
+ * @author Noel Power
+ * @created August 2, 2002
+ */
+public class ScriptProviderForJava
+{
+ /**
+ * Description of the Class
+ *
+ * @author Noel Power
+ * @created August 2, 2002
+ */
+ public static class _ScriptProviderForJava extends ScriptProvider
+ {
+ private Resolver m_resolutionPolicy = new StrictResolver();
+
+ public _ScriptProviderForJava( XComponentContext ctx )
+ {
+ super (ctx, "Java");
+ }
+
+ public XScript getScript( /*IN*/String scriptURI )
+ throws com.sun.star.uno.RuntimeException,
+ ScriptFrameworkErrorException
+ {
+ ScriptMetaData scriptData = null;
+ scriptData = getScriptData( scriptURI );
+ ScriptImpl script = null;
+ try
+ {
+ script = new ScriptImpl( m_xContext, m_resolutionPolicy, scriptData, m_xModel, m_xInvocContext );
+ return script;
+ }
+ catch ( com.sun.star.uno.RuntimeException re )
+ {
+ throw new ScriptFrameworkErrorException( "Failed to create script object: " + re.getMessage(),
+ null, scriptData.getLanguageName(), language, ScriptFrameworkErrorType.UNKNOWN );
+ }
+
+ }
+
+ public boolean hasScriptEditor()
+ {
+ return false;
+ }
+
+ public ScriptEditor getScriptEditor()
+ {
+ return null;
+ }
+ }
+
+ /**
+ * Returns a factory for creating the service.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param implName the name of the implementation for which a service is desired
+ * @param multiFactory the service manager to be used if needed
+ * @param regKey the registryKey
+ * @return returns a <code>XSingleServiceFactory</code> for creating
+ * the component
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static XSingleServiceFactory __getServiceFactory( String implName,
+ XMultiServiceFactory multiFactory,
+ XRegistryKey regKey )
+ {
+ XSingleServiceFactory xSingleServiceFactory = null;
+
+ if ( implName.equals( ScriptProviderForJava._ScriptProviderForJava.class.getName() ) )
+ {
+ xSingleServiceFactory = FactoryHelper.getServiceFactory(
+ ScriptProviderForJava._ScriptProviderForJava.class,
+ "com.sun.star.script.provider.ScriptProviderForJava",
+ multiFactory,
+ regKey );
+ }
+
+ return xSingleServiceFactory;
+ }
+
+
+ /**
+ * Writes the service information into the given registry key.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param regKey the registryKey
+ * @return returns true if the operation succeeded
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static boolean __writeRegistryServiceInfo( XRegistryKey regKey )
+ {
+ String impl = "com.sun.star.script.framework.provider.java." +
+ "ScriptProviderForJava$_ScriptProviderForJava";
+
+ String service1 = "com.sun.star.script.provider." +
+ "ScriptProvider";
+ String service2 = "com.sun.star.script.provider." +
+ "LanguageScriptProvider";
+ String service3 = "com.sun.star.script.provider." +
+ "ScriptProviderForJava";
+ String service4 = "com.sun.star.script.browse." +
+ "BrowseNode";
+
+ if ( FactoryHelper.writeRegistryServiceInfo(impl, service1, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service2, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service3, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service4, regKey) )
+ {
+ return true;
+ }
+ return false;
+ }
+
+}
+
+class ScriptImpl implements XScript
+{
+ private ScriptMetaData metaData;
+ private XComponentContext m_xContext;
+ private XModel m_xModel;
+ private XScriptInvocationContext m_xInvocContext;
+ private XMultiComponentFactory m_xMultiComponentFactory;
+ private Resolver m_resolutionPolicy;
+ ScriptImpl( XComponentContext ctx, Resolver resolver, ScriptMetaData metaData, XModel xModel, XScriptInvocationContext xInvocContext ) throws com.sun.star.uno.RuntimeException
+ {
+ this.metaData = metaData;
+ this.m_xContext = ctx;
+ this.m_xModel = xModel;
+ this.m_xInvocContext = xInvocContext;
+ this.m_resolutionPolicy = resolver;
+ try
+ {
+ this.m_xMultiComponentFactory = m_xContext.getServiceManager();
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ throw new com.sun.star.uno.RuntimeException(
+ "Error constructing ScriptProvider: "
+ + e.getMessage() );
+ }
+
+ LogUtils.DEBUG("ScriptImpl [java] script data = " + metaData );
+ }
+ /**
+ * Invoke
+ *
+ *
+ * @param aParams All parameters; pure, out params are undefined in
+ * sequence, i.e., the value has to be ignored by the callee
+ * @param aOutParamIndex Out indices
+ * @param aOutParam Out parameters
+ * @returns The value returned from the function being invoked
+ * @throws IllegalArgumentException If there is no matching script name
+ * @throws CannotConvertException If args do not match or cannot be converted
+ * the those of the invokee
+ * @throws InvocationTargetException If the running script throws an exception
+ * this information is captured and rethrown as this exception type.
+ */
+
+ public Object invoke(
+ /*IN*/Object[] params,
+ /*OUT*/short[][] aOutParamIndex,
+ /*OUT*/Object[][] aOutParam )
+
+ throws ScriptFrameworkErrorException, com.sun.star.reflection.InvocationTargetException
+ {
+ LogUtils.DEBUG( "** ScriptProviderForJava::invoke: Starting..." );
+
+ // Initialise the out paramters - not used at the moment
+ aOutParamIndex[0] = new short[0];
+ aOutParam[0] = new Object[0];
+
+
+ Map languageProps = metaData.getLanguageProperties();
+
+ ScriptDescriptor scriptDesc =
+ new ScriptDescriptor( metaData.getLanguageName() );
+
+ ClassLoader scriptLoader = null;
+
+ try {
+ LogUtils.DEBUG( "Classloader starting..." );
+ scriptLoader = ClassLoaderFactory.getURLClassLoader(
+ metaData );
+ LogUtils.DEBUG( "Classloader finished..." );
+ }
+ catch (MalformedURLException mfe )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ mfe.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.MALFORMED_URL );
+ }
+ catch (NoSuitableClassLoaderException ncl )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ ncl.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ catch (ArrayStoreException e )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ e.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+
+ ArrayList invocationArgList = new ArrayList();
+ Object[] invocationArgs = null;
+
+ LogUtils.DEBUG( "Parameter Mapping..." );
+
+ // Setup Context Object
+ XScriptContext xSc = ScriptContext.createContext(m_xModel, m_xInvocContext,
+ m_xContext, m_xMultiComponentFactory);
+ scriptDesc.addArgumentType( XScriptContext.class );
+ invocationArgList.add( xSc );
+
+ for ( int i = 0; i < params.length; i++ )
+ {
+ scriptDesc.addArgumentType( params[ i ].getClass() );
+ invocationArgList.add( params[ i ] );
+ }
+
+ if ( !invocationArgList.isEmpty() )
+ {
+ invocationArgs = invocationArgList.toArray();
+ }
+
+
+
+ LogUtils.DEBUG( "ScriptProxy starting... " );
+ ScriptProxy script = null;
+ try
+ {
+ String className = metaData.getLanguageName().substring( 0,
+ metaData.getLanguageName().lastIndexOf( '.' ) );
+ LogUtils.DEBUG( "About to load Class " + className + " starting... " );
+
+ long start = new java.util.Date().getTime();
+ Class c = scriptLoader.loadClass( className );
+ long end = new java.util.Date().getTime();
+
+ LogUtils.DEBUG("loadClass took: " + String.valueOf(end - start) +
+ "milliseconds");
+
+ try
+ {
+ LogUtils.DEBUG( "class loaded ... " );
+ script = m_resolutionPolicy.getProxy( scriptDesc, c );
+ LogUtils.DEBUG( "script resolved ... " );
+ }
+ catch( NoSuchMethodException e )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ e.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.NO_SUCH_SCRIPT );
+ }
+ }
+ catch ( ClassNotFoundException e )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ e.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.NO_SUCH_SCRIPT );
+ }
+
+ LogUtils.DEBUG( "Starting Invoke on Proxy ..." );
+ Object result = null;
+
+ try
+ {
+ long start = new java.util.Date().getTime();
+ result = script.invoke( invocationArgs );
+ long end = new java.util.Date().getTime();
+
+ LogUtils.DEBUG("invoke took: " +
+ String.valueOf(end - start) + "milliseconds");
+ }
+ catch ( java.lang.IllegalArgumentException iae )
+ {
+ throw new ScriptFrameworkErrorException(
+ iae.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+
+ }
+ catch ( java.lang.IllegalAccessException ia )
+ {
+ throw new ScriptFrameworkErrorException(
+ ia.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ catch ( java.lang.reflect.InvocationTargetException ite )
+ {
+ Throwable targetException = ite.getTargetException();
+ ScriptExceptionRaisedException se =
+ new ScriptExceptionRaisedException(
+ targetException.toString() );
+ se.lineNum = -1;
+ se.scriptName = metaData.getLanguageName();
+ se.language = "Java";
+ se.exceptionType = targetException.getClass().getName();
+ throw new com.sun.star.reflection.InvocationTargetException(
+ "Scripting Framework error executing script ", null, se );
+ }
+ catch ( Exception unknown )
+ {
+ ScriptExceptionRaisedException se =
+ new ScriptExceptionRaisedException(
+ unknown.toString() );
+ se.lineNum = -1;
+ se.scriptName = metaData.getLanguageName();
+ se.language = "Java";
+ se.exceptionType = unknown.getClass().getName();
+ throw new com.sun.star.reflection.InvocationTargetException(
+ "Scripting Framework error executing script ", null, se );
+ }
+ if ( result == null )
+ {
+ LogUtils.DEBUG( "Got Nothing Back" );
+ // in the case where there is no return type
+ Any voidAny = new Any(new Type(), null);
+ result = voidAny;
+ }
+ else
+ {
+ LogUtils.DEBUG( "Got object " + result );
+ }
+ return result;
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java
new file mode 100755
index 000000000000..3b78a6bc2c5b
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/java/ScriptProxy.java
@@ -0,0 +1,95 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptProxy.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+package com.sun.star.script.framework.provider.java;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.InvocationTargetException;
+
+/**
+ * A ScriptProxy object acts as a proxy for a Java <code>Method</code>
+ *
+ * @author Tomas O'Connor
+ * @created August 2, 2002
+ * @see java.lang.reflect.Method
+ */
+public class ScriptProxy
+{
+ private Object m_targetObject;
+ private Method m_method;
+
+
+ /**
+ * Constructs a <code>ScriptProxy</code> object for the given
+ * <code>Method</code>
+ *
+ * @param method Description of the Parameter
+ */
+ public ScriptProxy( Method method )
+ {
+ this.m_method = method;
+ }
+
+
+ /**
+ * Sets the <code>Object</code> on which the ScriptProxy should invoke
+ * the method
+ *
+ * @param obj The new targetObject value
+ */
+ public void setTargetObject( Object obj )
+ {
+ m_targetObject = obj;
+ }
+
+
+ /**
+ * Invokes the method contained in this <code>ScriptProxy</code>,
+ * any exceptions resulting from the invocation will be thrown
+ *
+ * @param args the arguments to be passed when invoking
+ * the method
+ * @return the Object returned from the method
+ * invocation, may be null
+ * @exception IllegalAccessException Description of the Exception
+ * @exception InvocationTargetException Description of the Exception
+ * @exception IllegalArgumentException Description of the Exception
+ * @exception Exception Description of the Exception
+ * @see java.lang.reflect.Method for the exceptions
+ * that may be thrown
+ */
+ public Object invoke( Object[] args )
+ throws IllegalAccessException, InvocationTargetException,
+ IllegalArgumentException
+ {
+ return m_method.invoke( m_targetObject, args );
+ }
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java b/scripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java
new file mode 100755
index 000000000000..87a6f994e174
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/java/StrictResolver.java
@@ -0,0 +1,131 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: StrictResolver.java,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+package com.sun.star.script.framework.provider.java;
+
+import java.lang.reflect.*;
+import com.sun.star.script.framework.log.LogUtils;
+
+/**
+ * A StrictResolver can be used to get a ScriptProxy object for a given
+ * ScriptDescriptor and Class. The StrictResolver is an implementation of
+ * the Resolver strategy. It will only return a ScriptProxy object if a
+ * method accepting all of the arguments specified in the ScriptDescriptor
+ * can be found in the Class.
+ *
+ * @author Tomas O'Connor
+ * @created August 2, 2002
+ */
+public class StrictResolver implements Resolver
+{
+ /**
+ *Constructor for the StrictResolver object
+ */
+ public StrictResolver()
+ {
+ LogUtils.DEBUG( this.getClass().getName() + " created" );
+ }
+
+
+ /**
+ * Returns a ScriptProxy object for the given ScriptDescriptor and Class.
+ * Only a strict match will be returned ie. where all of the arguments in
+ * the given ScriptDescriptor match the types of the
+ *
+ * @param sd the ScriptDescriptor for which a ScriptProxy is required
+ * @param c the Class file in which to search for the method
+ * @return the ScriptProxy matching the criteria, or null if no match is found
+ */
+ public ScriptProxy getProxy( ScriptDescriptor sd, Class c )
+ throws NoSuchMethodException
+ {
+ Method m = null;
+ ScriptProxy sp = null;
+
+ LogUtils.DEBUG( "StrictResolver.getProxy() for: " + sd.toString() );
+
+ try
+ {
+ m = resolveArguments( sd, c );
+ }
+ catch ( ClassNotFoundException e )
+ {
+ throw new NoSuchMethodException( "StrictResolver.getProxy: Cant find method: "
+ + sd.getMethodName() + ":" + e.getMessage() );
+ }
+ catch ( NoSuchMethodException e )
+ {
+ throw new NoSuchMethodException( "StrictResolver.getProxy: Cant find method: "
+ + sd.getMethodName() + ":" + e.getMessage() );
+ }
+
+ sp = new ScriptProxy( m );
+
+ int modifiers = m.getModifiers();
+ if ( !Modifier.isStatic( modifiers ) )
+ {
+ Object o;
+ try
+ {
+ o = c.newInstance();
+ }
+ catch ( InstantiationException ie )
+ {
+ throw new NoSuchMethodException( "getScriptProxy: Cant instantiate: " +
+ c.getName() );
+ }
+ catch ( IllegalAccessException iae )
+ {
+ throw new NoSuchMethodException( "getScriptProxy: Cant access: "
+ + c.getName() );
+ }
+ sp.setTargetObject( o );
+ }
+
+ return sp;
+ }
+
+
+ /**
+ * Description of the Method
+ *
+ * @param sd Description of the Parameter
+ * @param c Description of the Parameter
+ * @return Description of the Return Value
+ * @exception ClassNotFoundException
+ * @exception NoSuchMethodException
+ */
+ private Method resolveArguments( ScriptDescriptor sd, Class c )
+ throws ClassNotFoundException, NoSuchMethodException
+ {
+ return c.getMethod( sd.getMethodName(), sd.getArgumentTypes() );
+ }
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java
new file mode 100644
index 000000000000..45e99c8c324d
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptEditorForJavaScript.java
@@ -0,0 +1,379 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptEditorForJavaScript.java,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package com.sun.star.script.framework.provider.javascript;
+
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.ImporterTopLevel;
+import org.mozilla.javascript.tools.debugger.Main;
+import org.mozilla.javascript.tools.debugger.ScopeProvider;
+
+import com.sun.star.script.provider.XScriptContext;
+import com.sun.star.script.framework.container.ScriptMetaData;
+import com.sun.star.script.framework.provider.ScriptEditor;
+import com.sun.star.script.framework.log.LogUtils;
+
+import java.io.InputStream;
+import java.io.IOException;
+import java.net.URL;
+
+import java.util.Map;
+import java.util.HashMap;
+
+import javax.swing.SwingUtilities;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+
+public class ScriptEditorForJavaScript implements ScriptEditor
+{
+ // global ScriptEditorForJavaScript instance
+ private static ScriptEditorForJavaScript theScriptEditorForJavaScript;
+
+ // template for JavaScript scripts
+ private static String JSTEMPLATE;
+
+ static private Main rhinoWindow;
+ private URL scriptURL;
+ // global list of ScriptEditors, key is URL of file being edited
+ private static Map BEING_EDITED = new HashMap();
+
+ static {
+ try {
+ URL url =
+ ScriptEditorForJavaScript.class.getResource("template.js");
+
+ InputStream in = url.openStream();
+ StringBuffer buf = new StringBuffer();
+ byte[] b = new byte[1024];
+ int len = 0;
+
+ while ((len = in.read(b)) != -1) {
+ buf.append(new String(b, 0, len));
+ }
+
+ in.close();
+
+ JSTEMPLATE = buf.toString();
+ }
+ catch (IOException ioe) {
+ JSTEMPLATE = "// JavaScript script";
+ }
+ catch (Exception e) {
+ JSTEMPLATE = "// JavaScript script";
+ }
+ }
+
+ /**
+ * Returns the global ScriptEditorForJavaScript instance.
+ */
+ public static ScriptEditorForJavaScript getEditor()
+ {
+ if (theScriptEditorForJavaScript == null)
+ {
+ synchronized(ScriptEditorForJavaScript.class)
+ {
+ if (theScriptEditorForJavaScript == null)
+ {
+ theScriptEditorForJavaScript =
+ new ScriptEditorForJavaScript();
+ }
+ }
+ }
+ return theScriptEditorForJavaScript;
+ }
+
+ /**
+ * Get the ScriptEditorForJavaScript instance for this URL
+ *
+ * @param url The URL of the script source file
+ *
+ * @return The ScriptEditorForJavaScript associated with
+ * the given URL if one exists, otherwise null.
+ */
+ public static ScriptEditorForJavaScript getEditor(URL url)
+ {
+ return (ScriptEditorForJavaScript)BEING_EDITED.get(url);
+ }
+
+ /**
+ * Returns whether or not the script source being edited in this
+ * ScriptEditorForJavaScript has been modified
+ */
+ public boolean isModified()
+ {
+ return rhinoWindow.isModified( scriptURL );
+ }
+
+ /**
+ * Returns the text being displayed in this ScriptEditorForJavaScript
+ *
+ * @return The text displayed in this ScriptEditorForJavaScript
+ */
+ public String getText()
+ {
+ return rhinoWindow.getText( scriptURL );
+ }
+
+ /**
+ * Returns the Rhino Debugger url of this ScriptEditorForJavaScript
+ *
+ * @return The url of this ScriptEditorForJavaScript
+ */
+ public String getURL()
+ {
+ return scriptURL.toString();
+ }
+
+ /**
+ * Returns the template text for JavaScript scripts
+ *
+ * @return The template text for JavaScript scripts
+ */
+ public String getTemplate()
+ {
+ return JSTEMPLATE;
+ }
+
+ /**
+ * Returns the default extension for JavaScript scripts
+ *
+ * @return The default extension for JavaScript scripts
+ */
+ public String getExtension()
+ {
+ return "js";
+ }
+
+ /**
+ * Opens an editor window for the specified ScriptMetaData.
+ * If an editor window is already open for that data it will be
+ * moved to the front.
+ *
+ * @param metadata The metadata describing the script
+ * @param context The context in which to execute the script
+ *
+ */
+ public void edit(final XScriptContext context, ScriptMetaData entry)
+ {
+ try {
+ String sUrl = entry.getParcelLocation();
+ if ( !sUrl.endsWith( "/" ) )
+ {
+ sUrl += "/";
+ }
+ sUrl += entry.getLanguageName();
+ URL url = entry.getSourceURL();
+
+ // check if there is already an editing session for this script
+ //if (BEING_EDITED.containsKey(url))
+ if ( rhinoWindow != null )
+ {
+ ScriptEditorForJavaScript editor =
+ (ScriptEditorForJavaScript) BEING_EDITED.get(url);
+ if ( editor == null )
+ {
+ editor = new ScriptEditorForJavaScript( context, url );
+ editor.edit( context, entry );
+ }
+ else
+ {
+ rhinoWindow.showScriptWindow( url );
+ }
+ }
+ else
+ {
+ ScriptEditorForJavaScript editor =
+ new ScriptEditorForJavaScript( context, url );
+
+ }
+ rhinoWindow.toFront();
+ }
+ catch ( IOException e )
+ {
+ LogUtils.DEBUG("Caught exception: " + e);
+ LogUtils.DEBUG(LogUtils.getTrace(e));
+ }
+ }
+
+ // Ensures that new instances of this class can only be created using
+ // the factory methods
+ private ScriptEditorForJavaScript()
+ {
+ }
+
+ private ScriptEditorForJavaScript(XScriptContext context, URL url)
+ {
+ initUI();
+ Scriptable scope = getScope( context );
+ this.rhinoWindow.openFile(url, scope, new closeHandler( url ) );
+
+
+ this.scriptURL = url;
+ synchronized( ScriptEditorForJavaScript.class )
+ {
+ BEING_EDITED.put(url, this);
+ }
+
+ }
+
+ /**
+ * Executes the script edited by the editor
+ *
+ */
+
+ public Object execute() throws Exception
+ {
+ rhinoWindow.toFront();
+
+ return this.rhinoWindow.runScriptWindow( scriptURL );
+ }
+
+ /**
+ * Indicates the line where error occured
+ *
+ */
+ public void indicateErrorLine( int lineNum )
+ {
+ this.rhinoWindow.toFront();
+ this.rhinoWindow.highlighLineInScriptWindow( scriptURL, lineNum );
+ }
+ // This code is based on the main method of the Rhino Debugger Main class
+ // We pass in the XScriptContext in the global scope for script execution
+ private void initUI() {
+ try {
+ synchronized ( ScriptEditorForJavaScript.class )
+ {
+ if ( this.rhinoWindow != null )
+ {
+ return;
+ }
+
+ final Main sdb = new Main("Rhino JavaScript Debugger");
+ swingInvoke(new Runnable() {
+ public void run() {
+ sdb.pack();
+ sdb.setSize(640, 640);
+ sdb.setVisible(true);
+ }
+ });
+ sdb.setExitAction(new Runnable() {
+ public void run() {
+ sdb.clearAllBreakpoints();
+ sdb.dispose();
+ shutdown();
+ }
+ });
+ Context.addContextListener(sdb);
+ sdb.setScopeProvider(new ScopeProvider() {
+ public Scriptable getScope() {
+ return org.mozilla.javascript.tools.shell.Main.getScope();
+ }
+ });
+ sdb.addWindowListener( new WindowAdapter() {
+ public void windowClosing(WindowEvent e) {
+ shutdown();
+ }
+ });
+ this.rhinoWindow = sdb;
+ }
+ } catch (Exception exc) {
+ LogUtils.DEBUG( LogUtils.getTrace( exc ) );
+ }
+ }
+
+ private static void swingInvoke(Runnable f) {
+ if (SwingUtilities.isEventDispatchThread()) {
+ f.run();
+ return;
+ }
+ try {
+ SwingUtilities.invokeAndWait(f);
+ } catch (Exception exc) {
+ LogUtils.DEBUG( LogUtils.getTrace( exc ) );
+ }
+ }
+
+ private void shutdown()
+ {
+ // dereference Rhino Debugger window
+ this.rhinoWindow = null;
+ this.scriptURL = null;
+ // remove all scripts from BEING_EDITED
+ synchronized( BEING_EDITED )
+ {
+ java.util.Iterator iter = BEING_EDITED.keySet().iterator();
+ java.util.Vector keysToRemove = new java.util.Vector();
+ while ( iter.hasNext() )
+ {
+
+ URL key = (URL)iter.next();
+ keysToRemove.add( key );
+ }
+ for ( int i=0; i<keysToRemove.size(); i++ )
+ {
+ BEING_EDITED.remove( keysToRemove.elementAt( i ) );
+ }
+ keysToRemove = null;
+ }
+
+ }
+ private Scriptable getScope(XScriptContext xsctxt )
+ {
+ Context ctxt = Context.enter();
+ ImporterTopLevel scope = new ImporterTopLevel(ctxt);
+
+ Scriptable jsCtxt = Context.toObject(xsctxt, scope);
+ scope.put("XSCRIPTCONTEXT", scope, jsCtxt);
+
+ Scriptable jsArgs = Context.toObject(
+ new Object[0], scope);
+ scope.put("ARGUMENTS", scope, jsArgs);
+
+ Context.exit();
+ return scope;
+ }
+
+ class closeHandler implements Runnable
+ {
+ URL url;
+ closeHandler( URL url )
+ {
+ this.url = url;
+ }
+ public void run()
+ {
+ synchronized( BEING_EDITED )
+ {
+ Object o = BEING_EDITED.remove( this.url );
+ }
+ }
+ }
+}
diff --git a/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java
new file mode 100755
index 000000000000..d913129c5f87
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/javascript/ScriptProviderForJavaScript.java
@@ -0,0 +1,395 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptProviderForJavaScript.java,v $
+ * $Revision: 1.10.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package com.sun.star.script.framework.provider.javascript;
+
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.XSingleServiceFactory;
+import com.sun.star.frame.XModel;
+import com.sun.star.registry.XRegistryKey;
+import com.sun.star.comp.loader.FactoryHelper;
+
+import com.sun.star.document.XScriptInvocationContext;
+import com.sun.star.reflection.InvocationTargetException;
+
+import java.net.URL;
+
+import com.sun.star.script.provider.XScript;
+
+import com.sun.star.script.provider.ScriptExceptionRaisedException;
+import com.sun.star.script.provider.ScriptFrameworkErrorException;
+import com.sun.star.script.provider.ScriptFrameworkErrorType;
+
+import com.sun.star.script.framework.log.LogUtils;
+import com.sun.star.script.framework.provider.ScriptContext;
+import com.sun.star.script.framework.provider.ClassLoaderFactory;
+import com.sun.star.script.framework.provider.ScriptProvider;
+import com.sun.star.script.framework.provider.ScriptEditor;
+import com.sun.star.script.framework.container.ScriptMetaData;
+
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.ImporterTopLevel;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.JavaScriptException;
+
+public class ScriptProviderForJavaScript
+{
+ public static class _ScriptProviderForJavaScript extends ScriptProvider
+ {
+ public _ScriptProviderForJavaScript(XComponentContext ctx)
+ {
+ super(ctx, "JavaScript");
+ }
+
+ public XScript getScript( /*IN*/String scriptURI )
+ throws com.sun.star.uno.RuntimeException,
+ ScriptFrameworkErrorException
+ {
+ ScriptMetaData scriptData = null;
+ try
+ {
+ scriptData = getScriptData( scriptURI );
+ ScriptImpl script = new ScriptImpl( m_xContext, scriptData, m_xModel, m_xInvocContext );
+ return script;
+ }
+ catch ( com.sun.star.uno.RuntimeException re )
+ {
+ throw new ScriptFrameworkErrorException( "Failed to create script object: " + re.getMessage(),
+ null, scriptData.getLanguageName(), language, ScriptFrameworkErrorType.UNKNOWN );
+ }
+ }
+
+ public boolean hasScriptEditor()
+ {
+ return true;
+ }
+
+ public ScriptEditor getScriptEditor()
+ {
+ return ScriptEditorForJavaScript.getEditor();
+ }
+ }
+
+ /**
+ * Returns a factory for creating the service.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param implName the name of the implementation for which a service is desired
+ * @param multiFactory the service manager to be used if needed
+ * @param regKey the registryKey
+ * @return returns a <code>XSingleServiceFactory</code> for creating
+ * the component
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static XSingleServiceFactory __getServiceFactory( String implName,
+ XMultiServiceFactory multiFactory,
+ XRegistryKey regKey )
+ {
+ XSingleServiceFactory xSingleServiceFactory = null;
+
+ if ( implName.equals( ScriptProviderForJavaScript._ScriptProviderForJavaScript.class.getName() ) )
+ {
+ xSingleServiceFactory = FactoryHelper.getServiceFactory(
+ ScriptProviderForJavaScript._ScriptProviderForJavaScript.class,
+ "com.sun.star.script.provider.ScriptProviderForJavaScript",
+ multiFactory,
+ regKey );
+ }
+
+ return xSingleServiceFactory;
+ }
+
+
+ /**
+ * Writes the service information into the given registry key.
+ * This method is called by the <code>JavaLoader</code>
+ * <p>
+ *
+ * @param regKey the registryKey
+ * @return returns true if the operation succeeded
+ * @see com.sun.star.comp.loader.JavaLoader
+ */
+ public static boolean __writeRegistryServiceInfo( XRegistryKey regKey )
+ {
+ String impl = "com.sun.star.script.framework.provider.javascript." +
+ "ScriptProviderForJavaScript$_ScriptProviderForJavaScript";
+
+ String service1 = "com.sun.star.script.provider." +
+ "ScriptProvider";
+ String service2 = "com.sun.star.script.provider." +
+ "LanguageScriptProvider";
+ String service3 = "com.sun.star.script.provider." +
+ "ScriptProviderForJavaScript";
+ String service4 = "com.sun.star.script.browse." +
+ "BrowseNode";
+
+ if ( FactoryHelper.writeRegistryServiceInfo(impl, service1, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service2, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service3, regKey) &&
+ FactoryHelper.writeRegistryServiceInfo(impl, service4, regKey) )
+ {
+ return true;
+ }
+ return false;
+ }
+}
+class ScriptImpl implements XScript
+{
+ private ScriptMetaData metaData;
+ private XComponentContext m_xContext;
+ private XMultiComponentFactory m_xMultiComponentFactory;
+ private XModel m_xModel;
+ private XScriptInvocationContext m_xInvocContext;
+
+ ScriptImpl( XComponentContext ctx, ScriptMetaData metaData, XModel xModel, XScriptInvocationContext xInvocContext ) throws com.sun.star.uno.RuntimeException
+ {
+ this.metaData = metaData;
+ this.m_xContext = ctx;
+ this.m_xModel = xModel;
+ this.m_xInvocContext = xInvocContext;
+ try
+ {
+ this.m_xMultiComponentFactory = m_xContext.getServiceManager();
+ }
+ catch ( Exception e )
+ {
+ LogUtils.DEBUG( LogUtils.getTrace( e ) );
+ throw new com.sun.star.uno.RuntimeException(
+ "Error constructing ScriptImpl: [javascript]");
+ }
+ LogUtils.DEBUG("ScriptImpl [javascript] script data = " + metaData );
+ }
+
+ /**
+ * The invoke method of the ScriptProviderForJavaScript runs the
+ * JavaScript script specified in the URI
+ *
+ *
+ *
+ * @param aParams All parameters; pure, out params are
+ * undefined in sequence, i.e., the value
+ * has to be ignored by the callee
+ *
+ * @param aOutParamIndex Out indices
+ *
+ * @param aOutParam Out parameters
+ *
+ * @returns The value returned from the function
+ * being invoked
+ *
+ * @throws ScriptFrameworkErrorException If there is no matching script name
+ *
+ *
+ * @throws InvocationTargetException If the running script throws
+ * an exception this information
+ * is captured and rethrown as
+ * ScriptErrorRaisedException or
+ * ScriptExceptionRaisedException
+ */
+
+ public Object invoke(
+ /*IN*/Object[] params,
+ /*OUT*/short[][] aOutParamIndex,
+ /*OUT*/Object[][] aOutParam )
+
+ throws ScriptFrameworkErrorException, InvocationTargetException
+ {
+ // Initialise the out paramters - not used at the moment
+ aOutParamIndex[0] = new short[0];
+ aOutParam[0] = new Object[0];
+
+
+
+ ClassLoader cl = null;
+ URL sourceUrl = null;
+ try {
+ cl = ClassLoaderFactory.getURLClassLoader( metaData );
+ sourceUrl = metaData.getSourceURL();
+ }
+ catch ( java.net.MalformedURLException mfu )
+ {
+ throw new ScriptFrameworkErrorException(
+ mfu.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.MALFORMED_URL );
+ }
+ catch ( com.sun.star.script.framework.provider.NoSuitableClassLoaderException nsc )
+ {
+ // Framework error
+ throw new ScriptFrameworkErrorException(
+ nsc.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ Context ctxt = null;
+
+ try
+ {
+ String editorURL = sourceUrl.toString();
+ Object result = null;
+ String source = null;
+ ScriptEditorForJavaScript editor =
+ ScriptEditorForJavaScript.getEditor(
+ metaData.getSourceURL() );
+
+ if (editor != null)
+ {
+ editorURL = editor.getURL();
+ result = editor.execute();
+ if ( result != null &&
+ result.getClass().getName().equals( "org.mozilla.javascript.Undefined" ) )
+ {
+ // Always return a string
+ // TODO revisit
+ return Context.toString( result );
+ }
+
+ }
+
+ if (editor != null && editor.isModified() == true)
+ {
+ LogUtils.DEBUG("GOT A MODIFIED SOURCE");
+ source = editor.getText();
+ }
+ else
+ {
+ metaData.loadSource();
+ source = metaData.getSource();
+
+ }
+
+ if ( source == null || source.length() == 0 ) {
+ throw new ScriptFrameworkErrorException(
+ "Failed to read source data for script", null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+
+ /* Set the context ClassLoader on the current thread to
+ be our custom ClassLoader. This is the suggested method
+ for setting up a ClassLoader to be used by the Rhino
+ interpreter
+ */
+ if (cl != null) {
+ Thread.currentThread().setContextClassLoader(cl);
+ }
+
+ // Initialize a Rhino Context object
+ ctxt = Context.enter();
+
+ /* The ImporterTopLevel ensures that importClass and
+ importPackage statements work in Javascript scripts
+ Make the XScriptContext available as a global variable
+ to the script
+ */
+ ImporterTopLevel scope = new ImporterTopLevel(ctxt);
+
+ Scriptable jsCtxt = Context.toObject(
+ ScriptContext.createContext(
+ m_xModel, m_xInvocContext, m_xContext,
+ m_xMultiComponentFactory), scope);
+ scope.put("XSCRIPTCONTEXT", scope, jsCtxt);
+
+ Scriptable jsArgs = Context.toObject(params, scope);
+ scope.put("ARGUMENTS", scope, jsArgs);
+
+ result = ctxt.evaluateString(scope,
+ source, "<stdin>", 1, null);
+ result = ctxt.toString(result);
+ return result;
+ }
+ catch (JavaScriptException jse) {
+ LogUtils.DEBUG( "Caught JavaScriptException exception for JavaScript type = " + jse.getClass() );
+ String message = jse.getMessage();
+ //int lineNo = jse.getLineNumber();
+ Object wrap = jse.getValue();
+ LogUtils.DEBUG( "\t message " + message );
+ LogUtils.DEBUG( "\t wrapped type " + wrap.getClass() );
+ LogUtils.DEBUG( "\t wrapped toString " + wrap.toString() );
+ ScriptExceptionRaisedException se = new
+ ScriptExceptionRaisedException( message );
+ se.lineNum = -1;
+ se.language = "JavaScript";
+ se.scriptName = metaData.getLanguageName();
+ se.exceptionType = wrap.getClass().getName();
+ se.language = metaData.getLanguage();
+ LogUtils.DEBUG( "ExceptionRaised exception " );
+ LogUtils.DEBUG( "\t message " + se.getMessage() );
+ LogUtils.DEBUG( "\t lineNum " + se.lineNum );
+ LogUtils.DEBUG( "\t language " + se.language );
+ LogUtils.DEBUG( "\t scriptName " + se.scriptName );
+ raiseEditor( se.lineNum );
+ throw new InvocationTargetException( "JavaScript uncaught exception" + metaData.getLanguageName(), null, se );
+ }
+ catch (Exception ex) {
+ LogUtils.DEBUG("Caught Exception " + ex );
+ LogUtils.DEBUG("rethrowing as ScriptFramework error" );
+ throw new ScriptFrameworkErrorException(
+ ex.getMessage(), null,
+ metaData.getLanguageName(), metaData.getLanguage(),
+ ScriptFrameworkErrorType.UNKNOWN );
+ }
+ finally {
+ if ( ctxt != null )
+ {
+ Context.exit();
+ }
+ }
+ }
+
+ private void raiseEditor( int lineNum )
+ {
+ ScriptEditorForJavaScript editor = null;
+ try
+ {
+ URL sourceUrl = metaData.getSourceURL();
+ editor = ScriptEditorForJavaScript.getEditor( sourceUrl );
+ if ( editor == null )
+ {
+ editor = ScriptEditorForJavaScript.getEditor();
+ editor.edit(
+ ScriptContext.createContext(m_xModel, m_xInvocContext,
+ m_xContext, m_xMultiComponentFactory), metaData );
+ editor = ScriptEditorForJavaScript.getEditor( sourceUrl );
+ }
+ if ( editor != null )
+ {
+ System.out.println("** Have raised IDE for JavaScript, calling indicateErrorLine for line " + lineNum );
+ editor.indicateErrorLine( lineNum );
+ }
+ }
+ catch( Exception ignore )
+ {
+ }
+ }
+}
+
diff --git a/scripting/java/com/sun/star/script/framework/provider/javascript/template.js b/scripting/java/com/sun/star/script/framework/provider/javascript/template.js
new file mode 100644
index 000000000000..d992791e647c
--- /dev/null
+++ b/scripting/java/com/sun/star/script/framework/provider/javascript/template.js
@@ -0,0 +1,37 @@
+// Hello World in JavaScript
+// Import standard OpenOffice.org API classes. For more information on
+// these classes and the OpenOffice.org API, see the OpenOffice.org
+// Developers Guide at:
+// http://api.openoffice.org/
+
+importClass(Packages.com.sun.star.uno.UnoRuntime);
+importClass(Packages.com.sun.star.text.XTextDocument);
+importClass(Packages.com.sun.star.text.XText);
+importClass(Packages.com.sun.star.text.XTextRange);
+importClass(Packages.com.sun.star.frame.XModel);
+
+// Import XScriptContext class. An instance of this class is available
+// to all JavaScript scripts in the global variable "XSCRIPTCONTEXT". This
+// variable can be used to access the document for which this script
+// was invoked.
+//
+// Methods available are:
+//
+// XSCRIPTCONTEXT.getDocument() returns XModel
+// XSCRIPTCONTEXT.getInvocationContext() returns XScriptInvocationContext or NULL
+// XSCRIPTCONTEXT.getDesktop() returns XDesktop
+// XSCRIPTCONTEXT.getComponentContext() returns XComponentContext
+//
+// For more information on using this class see the scripting
+// developer guides at:
+//
+// http://api.openoffice.org/docs/DevelopersGuide/ScriptingFramework/ScriptingFramework.xhtml
+//
+
+oDoc = UnoRuntime.queryInterface(XModel,XSCRIPTCONTEXT.getInvocationContext());
+if ( !oDoc )
+ oDoc = XSCRIPTCONTEXT.getDocument();
+xTextDoc = UnoRuntime.queryInterface(XTextDocument,oDoc);
+xText = xTextDoc.getText();
+xTextRange = xText.getEnd();
+xTextRange.setString( "Hello World (in JavaScript)" );
diff --git a/scripting/java/makefile.mk b/scripting/java/makefile.mk
new file mode 100755
index 000000000000..bb87b9da2185
--- /dev/null
+++ b/scripting/java/makefile.mk
@@ -0,0 +1,40 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.9 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+PRJ=..
+PRJNAME=scripting
+TARGET=scriptruntimeforjava
+
+.INCLUDE : ant.mk
+
+.IF "$(SOLAR_JAVA)"!=""
+ALLTAR : ANTBUILD
+.ENDIF
diff --git a/scripting/java/manifest.mf b/scripting/java/manifest.mf
new file mode 100644
index 000000000000..ba14e301b3eb
--- /dev/null
+++ b/scripting/java/manifest.mf
@@ -0,0 +1,26 @@
+Manifest-Version: 1.0
+OpenIDE-Module: org.openoffice.netbeans.modules.office/1
+OpenIDE-Module-Name: Office Support
+OpenIDE-Module-Short-Description: Scripting Support for Office Documents
+OpenIDE-Module-Localizing-Bundle: org/openoffice/netbeans/modules/office/Bundle.properties
+OpenIDE-Module-Specification-Version: 0.2
+OpenIDE-Module-Implementation-Version: 0.2
+OpenIDE-Module-Install: org/openoffice/netbeans/modules/office/utils/OfficeModule.class
+OpenIDE-Module-Layer: org/openoffice/netbeans/modules/office/resources/layer.xml
+
+Name: org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoader.class
+OpenIDE-Module-Class: Loader
+
+Name: org/openoffice/netbeans/modules/office/loader/ParcelDataLoader.class
+OpenIDE-Module-Class: Loader
+
+Name: org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoader.class
+Install-Before: org.openide.loaders.XMLDataObject, org.netbeans.modules.xml.core.XMLDataObject
+OpenIDE-Module-Class: Loader
+
+Name: org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoader.class
+Install-Before: org.openoffice.netbeans.modules.office.loader.ParcelDescriptorDataLoader
+OpenIDE-Module-Class: Loader
+
+Name: org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoader.class
+OpenIDE-Module-Class: Loader
diff --git a/scripting/java/org/openoffice/idesupport/CommandLineTools.java b/scripting/java/org/openoffice/idesupport/CommandLineTools.java
new file mode 100644
index 000000000000..cc9e216f0423
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/CommandLineTools.java
@@ -0,0 +1,353 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: CommandLineTools.java,v $
+ * $Revision: 1.11 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Enumeration;
+import java.util.StringTokenizer;
+
+import com.sun.star.script.framework.container.ScriptEntry;
+import com.sun.star.script.framework.container.ParcelDescriptor;
+
+import org.openoffice.idesupport.zip.ParcelZipper;
+import org.openoffice.idesupport.filter.AllFilesFilter;
+import com.sun.star.script.framework.container.XMLParserFactory;
+import org.openoffice.idesupport.*;
+
+public class CommandLineTools {
+ private static final String PARCEL_XML_FILE =
+ ParcelZipper.PARCEL_DESCRIPTOR_XML;
+
+ private static String officePath = null;
+
+ public static void main(String[] args) {
+ CommandLineTools driver = new CommandLineTools();
+ Command command = driver.parseArgs(args);
+
+ // Get the URL for the Office DTD directory and pass it to the
+ // XMLParserFactory so that Office xml files can be parsed
+ if (officePath == null)
+ {
+ try {
+ SVersionRCFile sv = SVersionRCFile.createInstance();
+ if (sv.getDefaultVersion() != null)
+ {
+ officePath = sv.getDefaultVersion().getPath();
+ }
+ }
+ catch (IOException ioe) {
+ System.err.println("Error getting Office directory");
+ }
+ }
+
+ if (officePath == null)
+ {
+ driver.fatalUsage("Error: Office Installation path not set");
+ }
+
+ File officeDir = new File(officePath);
+ if (officeDir.exists() == false || officeDir.isDirectory() == false)
+ {
+ driver.fatalUsage(
+ "Error: Office Installation path not valid: " + officePath);
+ }
+
+ OfficeInstallation oi = new OfficeInstallation(officePath);
+ String url = oi.getURL("share/dtd/officedocument/1_0/");
+ XMLParserFactory.setOfficeDTDURL(url);
+
+ if (command == null)
+ driver.printUsage();
+ else {
+ try {
+ command.execute();
+ }
+ catch (Exception e) {
+ driver.fatal("Error: " + e.getMessage());
+ }
+ }
+ }
+
+ private interface Command {
+ public void execute() throws Exception;
+ }
+
+ private void printUsage() {
+ System.out.println("java " + getClass().getName() + " -h " +
+ "prints this message");
+ System.out.println("java " + getClass().getName() +
+ " [-o Path to Office Installation] " +
+ "-d <script parcel zip file> " +
+ "<destination document or directory>");
+ System.out.println("java " + getClass().getName() +
+ " [-o Path to Office Installation] " +
+ "-g [parcel root directory] [options] [script names]");
+ System.out.println("options:");
+ System.out.println("\t[-l language[=supported extension 1[" +
+ File.pathSeparator + "supported extension 2]]]");
+ System.out.println("\t[-p name=value]");
+ System.out.println("\t[-v]");
+ }
+
+ private void fatal(String message) {
+ System.err.println(message);
+ System.exit(-1);
+ }
+
+ private void fatalUsage(String message) {
+ System.err.println(message);
+ System.err.println();
+ printUsage();
+ System.exit(-1);
+ }
+ private Command parseArgs(String[] args) {
+
+ if (args.length < 1) {
+ return null;
+ }
+ else if (args[0].equals("-h")) {
+ return new Command() {
+ public void execute() {
+ printUsage();
+ }
+ };
+ }
+
+ int i = 0;
+
+ if(args[0].equals("-o")) {
+ officePath = args[i+1];
+ i += 2;
+ }
+
+ if(args[i].equals("-d")) {
+ if ((args.length - i) != 3)
+ return null;
+ else
+ return new DeployCommand(args[i+1], args[i+2]);
+ }
+ else if(args[i].equals("-g")) {
+
+ if ((args.length - i) == 1)
+ return new GenerateCommand(System.getProperty("user.dir"));
+
+ GenerateCommand command;
+ i++;
+ if (!args[i].startsWith("-"))
+ command = new GenerateCommand(args[i++]);
+ else
+ command = new GenerateCommand(System.getProperty("user.dir"));
+
+ for (; i < args.length; i++) {
+ if (args[i].equals("-l")) {
+ command.setLanguage(args[++i]);
+ }
+ else if (args[i].equals("-p")) {
+ command.addProperty(args[++i]);
+ }
+ else if (args[i].equals("-v")) {
+ command.setVerbose();
+ }
+ else {
+ command.addScript(args[i]);
+ }
+ }
+ return command;
+ }
+ return null;
+ }
+
+ private static class GenerateCommand implements Command {
+
+ private File basedir, contents, parcelxml;
+ private boolean verbose = false;
+ private String language = null;
+ private MethodFinder finder = null;
+ private ArrayList scripts = null;
+ private Hashtable properties = new Hashtable(3);
+
+ public GenerateCommand(String basedir) {
+ this.basedir = new File(basedir);
+ this.contents = new File(basedir, ParcelZipper.CONTENTS_DIRNAME);
+ this.parcelxml = new File(contents, PARCEL_XML_FILE);
+ }
+
+ public void setLanguage(String language) {
+ StringTokenizer tokenizer = new StringTokenizer(language, "=");
+ this.language = tokenizer.nextToken();
+
+ if (this.language.toLowerCase().equals("java")) {
+ this.finder = JavaFinder.getInstance();
+ return;
+ }
+
+ if (tokenizer.hasMoreTokens()) {
+ String ext = (String)tokenizer.nextToken();
+ String[] extensions;
+
+ if (ext.indexOf(File.pathSeparator) != -1) {
+ tokenizer = new StringTokenizer(ext, File.pathSeparator);
+ extensions = new String[tokenizer.countTokens()];
+ int i = 0;
+
+ while(tokenizer.hasMoreTokens())
+ extensions[i++] = (String)tokenizer.nextToken();
+ }
+ else {
+ extensions = new String[1];
+ extensions[0] = ext;
+ }
+ this.finder = new ExtensionFinder(this.language, extensions);
+ }
+ }
+
+ public void addProperty(String prop) {
+ StringTokenizer tok = new StringTokenizer(prop, "=");
+
+ if (tok.countTokens() != 2)
+ return;
+
+ String name = tok.nextToken();
+ String value = tok.nextToken();
+
+ properties.put(name, value);
+ }
+
+ public void setVerbose() {
+ verbose = true;
+ }
+
+ public void addScript(String script) {
+ if (language == null)
+ return;
+
+ addScript(new ScriptEntry(language, script, script, basedir.getName()));
+ }
+
+ public void addScript(ScriptEntry entry) {
+ if (scripts == null)
+ scripts = new ArrayList(3);
+ scripts.add(entry);
+ }
+
+ public void execute() throws Exception {
+
+ if (basedir.isDirectory() != true) {
+ throw new Exception(basedir.getName() + " is not a directory");
+ }
+ else if (contents.exists() != true) {
+ throw new Exception(basedir.getName() +
+ " does not contain a Contents directory");
+ }
+
+ if (language == null && parcelxml.exists() == false) {
+ throw new Exception(parcelxml.getName() + " not found and language " +
+ "not specified");
+ }
+
+ if (language != null && parcelxml.exists() == true) {
+ ParcelDescriptor desc;
+ String desclang = "";
+
+ desc = new ParcelDescriptor(parcelxml);
+ desclang = desc.getLanguage().toLowerCase();
+
+ if (!desclang.equals(language.toLowerCase()))
+ throw new Exception(parcelxml.getName() + " already exists, " +
+ "and has a different language attribute: " +
+ desc.getLanguage());
+ }
+
+ if (language != null && scripts == null) {
+ if (finder == null)
+ throw new Exception("Extension list not specified for this language");
+
+ log("Searching for " + language + " scripts");
+
+ ScriptEntry[] entries = finder.findMethods(contents);
+ for (int i = 0; i < entries.length; i++) {
+ addScript(entries[i]);
+ log("Found: " + entries[i].getLogicalName());
+ }
+ }
+
+ if (scripts != null) {
+ if (scripts.size() == 0)
+ throw new Exception("No valid scripts found");
+
+ ParcelDescriptor desc = new ParcelDescriptor(parcelxml, language);
+ desc.setScriptEntries((ScriptEntry[])scripts.toArray(new ScriptEntry[0]));
+ if (properties.size() != 0) {
+ Enumeration enumer = properties.keys();
+
+ while (enumer.hasMoreElements()) {
+ String name = (String)enumer.nextElement();
+ String value = (String)properties.get(name);
+ log("Setting property: " + name + " to " + value);
+
+ desc.setLanguageProperty(name, value);
+ }
+ }
+ desc.write();
+ }
+ else {
+ if (parcelxml.exists() == false)
+ throw new Exception("No valid scripts found");
+ }
+
+ contents = new File(contents.getAbsolutePath());
+ String name = ParcelZipper.getParcelZipper().zipParcel(contents, AllFilesFilter.getInstance());
+ System.out.println(name + " generated");
+ }
+
+ private void log(String message) {
+ if (verbose)
+ System.out.println(message);
+ }
+ }
+
+ private static class DeployCommand implements Command {
+
+ File source, target;
+
+ public DeployCommand(String source, String target) {
+ this.source = new File(source);
+ this.target = new File(target);
+ }
+
+ public void execute() throws Exception {
+ ParcelZipper.getParcelZipper().deployParcel(source, target);
+ System.out.println(source.getName() +
+ " successfully deployed to " + target.getAbsolutePath());
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/ExtensionFinder.java b/scripting/java/org/openoffice/idesupport/ExtensionFinder.java
new file mode 100644
index 000000000000..8a0a10196a73
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/ExtensionFinder.java
@@ -0,0 +1,60 @@
+package org.openoffice.idesupport;
+
+import java.io.File;
+import java.util.ArrayList;
+import org.openoffice.idesupport.zip.ParcelZipper;
+
+import com.sun.star.script.framework.container.ScriptEntry;
+
+public class ExtensionFinder implements MethodFinder {
+
+ private String[] extensions;
+ private String language;
+
+ public ExtensionFinder(String language, String[] extensions) {
+ this.language = language;
+ this.extensions = extensions;
+ }
+
+ public ScriptEntry[] findMethods(File basedir) {
+ String parcelName;
+ ArrayList files = new ArrayList(10);
+ ScriptEntry[] empty = new ScriptEntry[0];
+
+ if (basedir == null || basedir.exists() == false ||
+ basedir.isDirectory() == false)
+ return empty;
+
+ parcelName = basedir.getName();
+ if (parcelName.equals(ParcelZipper.CONTENTS_DIRNAME))
+ parcelName = basedir.getParentFile().getName();
+
+ findFiles(files, basedir, parcelName);
+
+ if (files.size() != 0)
+ return (ScriptEntry[])files.toArray(empty);
+ return empty;
+ }
+
+ private void findFiles(ArrayList list, File basedir, String parcelName) {
+ File[] children = basedir.listFiles();
+ File f;
+
+ for (int i = 0; i < children.length; i++) {
+ f = children[i];
+
+ if (f.isDirectory())
+ findFiles(list, f, parcelName);
+ else {
+ for (int j = 0; j < extensions.length; j++) {
+ if (f.getName().endsWith(extensions[j])) {
+ ScriptEntry entry = new ScriptEntry(language,
+ f.getName(), f.getName(), parcelName);
+ list.add(entry);
+ break;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/JavaFinder.java b/scripting/java/org/openoffice/idesupport/JavaFinder.java
new file mode 100644
index 000000000000..cf077b6b2c08
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/JavaFinder.java
@@ -0,0 +1,227 @@
+package org.openoffice.idesupport;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.Vector;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.net.MalformedURLException;
+import org.openoffice.idesupport.zip.ParcelZipper;
+
+import com.sun.star.script.framework.container.ScriptEntry;
+
+public class JavaFinder implements MethodFinder {
+
+ private static JavaFinder finder;
+ private static final String JAVA_SUFFIX = ".java";
+ private static final String CLASS_SUFFIX = ".class";
+ private static final String LANGUAGE = "Java";
+ private static final String FIRST_PARAM =
+ "drafts.com.sun.star.script.framework.runtime.XScriptContext";
+
+ private Vector classpath = null;
+
+ private JavaFinder() {}
+
+ private JavaFinder(Vector classpath) {
+ this.classpath = classpath;
+ }
+
+ public static JavaFinder getInstance() {
+ if (finder == null) {
+ synchronized(JavaFinder.class) {
+ if (finder == null)
+ finder = new JavaFinder();
+ }
+ }
+ return finder;
+ }
+
+ public static JavaFinder getInstance(Vector classpath) {
+ return new JavaFinder(classpath);
+ }
+
+ public ScriptEntry[] findMethods(File basedir) {
+ String parcelName;
+ ArrayList result = new ArrayList(10);
+ ScriptEntry[] empty = new ScriptEntry[0];
+
+ if (basedir == null || basedir.exists() == false ||
+ basedir.isDirectory() == false)
+ return empty;
+
+ parcelName = basedir.getName();
+ if (parcelName.equals(ParcelZipper.CONTENTS_DIRNAME))
+ parcelName = basedir.getParentFile().getName();
+
+ String[] classNames = findClassNames(basedir);
+ if (classNames != null && classNames.length != 0) {
+
+ ClassLoader classloader;
+
+ if (classpath == null)
+ classloader = getClassLoader(basedir);
+ else
+ classloader = getClassLoader();
+
+ for (int i = 0; i < classNames.length; i++)
+ {
+ try
+ {
+ Class clazz = classloader.loadClass(classNames[i]);
+ Method[] methods = clazz.getDeclaredMethods();
+ for (int k = 0; k < methods.length; k++)
+ {
+ if (Modifier.isPublic(methods[k].getModifiers()))
+ {
+ Class[] params = methods[k].getParameterTypes();
+ if(params.length > 0)
+ {
+ if(params[0].getName().equals(FIRST_PARAM))
+ {
+ ScriptEntry entry =
+ new ScriptEntry(classNames[i] + "." +
+ methods[k].getName(), parcelName);
+ result.add(entry);
+ }
+ }
+ }
+ }
+ }
+ catch (ClassNotFoundException e)
+ {
+ System.err.println("Caught ClassNotFoundException loading: "
+ + classNames[i]);
+ continue;
+ }
+ catch (NoClassDefFoundError nc)
+ {
+ System.err.println("Caught NoClassDefFoundErr loading: " +
+ classNames[i]);
+ continue;
+ }
+ }
+ }
+
+ if (result.size() != 0)
+ return (ScriptEntry[])result.toArray(empty);
+ return empty;
+ }
+
+ private ClassLoader getClassLoader() {
+ int len = classpath.size();
+ ArrayList urls = new ArrayList(len);
+
+ for (int i = 0; i < len; i++) {
+ try {
+ String s = (String)classpath.elementAt(i);
+ s = SVersionRCFile.toFileURL(s);
+
+ if (s != null)
+ urls.add(new URL(s));
+ }
+ catch (MalformedURLException mue) {
+ }
+ }
+
+ return new URLClassLoader((URL[])urls.toArray(new URL[0]));
+ }
+
+ private ClassLoader getClassLoader(File basedir) {
+ ArrayList files = findFiles(basedir, ".jar");
+ files.add(basedir);
+
+ try {
+ Enumeration offices = SVersionRCFile.createInstance().getVersions();
+
+ while (offices.hasMoreElements()) {
+ OfficeInstallation oi = (OfficeInstallation)offices.nextElement();
+ String unoil = SVersionRCFile.getPathForUnoil(oi.getPath());
+
+ if (unoil != null) {
+ files.add(new File(unoil, "unoil.jar"));
+ break;
+ }
+ }
+ }
+ catch (IOException ioe) {
+ return null;
+ }
+
+ URL[] urls = new URL[files.size()];
+ String urlpath;
+ File f;
+ for (int i = 0; i < urls.length; i++) {
+ try {
+ f = (File)files.get(i);
+ urlpath = SVersionRCFile.toFileURL(f.getAbsolutePath());
+
+ if (urlpath != null)
+ urls[i] = new URL(urlpath);
+ }
+ catch (MalformedURLException mue) {
+ // do nothing, go on to next file
+ }
+ }
+
+ return new URLClassLoader(urls);
+ }
+
+ private ArrayList findFiles(File basedir, String suffix) {
+ ArrayList result = new ArrayList();
+ File[] children = basedir.listFiles();
+
+ for (int i = 0; i < children.length; i++) {
+ if (children[i].isDirectory())
+ result.addAll(findFiles(children[i], suffix));
+ else if (children[i].getName().endsWith(suffix))
+ result.add(children[i]);
+ }
+ return result;
+ }
+
+ private String[] findClassNames(File basedir)
+ {
+ ArrayList classFiles = findFiles(basedir, CLASS_SUFFIX);
+ if(classFiles == null || classFiles.size() == 0)
+ return null;
+
+ ArrayList javaFiles = findFiles(basedir, JAVA_SUFFIX);
+ if(javaFiles == null || javaFiles.size() == 0)
+ return null;
+
+ ArrayList result = new ArrayList();
+ for (int i = 0; i < classFiles.size(); i++)
+ {
+ File classFile = (File)classFiles.get(i);
+ String className = classFile.getName();
+ className = className.substring(0, className.lastIndexOf(CLASS_SUFFIX));
+ boolean finished = false;
+
+
+ for (int j = 0; j < javaFiles.size() && finished == false; j++)
+ {
+ File javaFile = (File)javaFiles.get(j);
+ String javaName = javaFile.getName();
+ javaName = javaName.substring(0, javaName.lastIndexOf(JAVA_SUFFIX));
+
+ if (javaName.equals(className))
+ {
+ String path = classFile.getAbsolutePath();
+ path = path.substring(basedir.getAbsolutePath().length() + 1);
+ path = path.replace(File.separatorChar, '.');
+ path = path.substring(0, path.lastIndexOf(CLASS_SUFFIX));
+
+ result.add(path);
+ javaFiles.remove(j);
+ finished = true;
+ }
+ }
+ }
+ return (String[])result.toArray(new String[0]);
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/LocalOffice.java b/scripting/java/org/openoffice/idesupport/LocalOffice.java
new file mode 100644
index 000000000000..f6edd8483f0c
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/LocalOffice.java
@@ -0,0 +1,112 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: LocalOffice.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport;
+
+import java.io.File;
+import java.net.ConnectException;
+import java.util.Vector;
+
+/**
+ * LocalOffice represents a connection to the local office.
+ *
+ * This class allows to get access to some scripting framework
+ * releated functionality of the locally running office. The
+ * office has to be started with options appropriate for establishing
+ * local connection.
+ *
+ * @author misha <misha@openoffice.org>
+ */
+public class LocalOffice
+{
+ /**
+ * Creates an instance of the local office connection.
+ *
+ * @param parent is an application specific class loader.
+ * @param officePath is a platform specific path string
+ * to the office distribution.
+ * @param port is a communication port.
+ */
+ public static final LocalOffice create(
+ ClassLoader parent, String officePath, int port)
+ {
+ Vector path = new Vector();
+ path.addElement(officePath + "/program/classes/ridl.jar");
+ path.addElement(officePath + "/program/classes/jurt.jar");
+ path.addElement(officePath + "/program/classes/unoil.jar");
+ path.addElement(officePath + "/program/classes/juh.jar");
+ path.addElement(System.getProperties().getProperty("netbeans.home") +
+ File.separator + "modules" +
+ File.separator + "ext" +
+ File.separator + "localoffice.jar");
+ // commented out so code will compile
+ // ClassLoader appcl = new DefaultScriptClassLoader(parent, path);
+ ClassLoader appcl = path.getClass().getClassLoader();
+ Class clazz = null;
+ LocalOffice office = null;
+ try {
+ clazz = appcl.loadClass(
+ "org.openoffice.idesupport.localoffice.LocalOfficeImpl");
+ office = (LocalOffice)clazz.newInstance();
+ office.connect(officePath, port);
+ } catch (java.lang.Exception exp) {
+ office = null;
+ }
+ return office;
+ }
+
+ /**
+ * Connects to the running office.
+ *
+ * @param officePath is a platform specific path string
+ * to the office distribution.
+ * @param port is a communication port.
+ */
+ protected void connect(String officePath, int port)
+ throws ConnectException
+ {
+ }
+
+ /**
+ * Closes the connection to the running office.
+ */
+ public void disconnect()
+ {
+ }
+
+ /**
+ * Refresh the script storage.
+ *
+ * @param uri is an identifier of storage has to be refreshed.
+ */
+ public void refreshStorage(String uri)
+ {
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/MethodFinder.java b/scripting/java/org/openoffice/idesupport/MethodFinder.java
new file mode 100644
index 000000000000..3bf85e323566
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/MethodFinder.java
@@ -0,0 +1,8 @@
+package org.openoffice.idesupport;
+
+import java.io.File;
+import com.sun.star.script.framework.container.ScriptEntry;
+
+public interface MethodFinder {
+ public ScriptEntry[] findMethods(File basedir);
+}
diff --git a/scripting/java/org/openoffice/idesupport/OfficeDocument.java b/scripting/java/org/openoffice/idesupport/OfficeDocument.java
new file mode 100644
index 000000000000..69e44549efdd
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/OfficeDocument.java
@@ -0,0 +1,123 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeDocument.java,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport;
+
+import java.io.*;
+import java.util.zip.*;
+import java.util.Vector;
+import java.util.Enumeration;
+import java.util.StringTokenizer;
+
+import org.openoffice.idesupport.filter.FileFilter;
+import org.openoffice.idesupport.filter.BinaryOnlyFilter;
+import org.openoffice.idesupport.zip.ParcelZipper;
+
+public class OfficeDocument
+{
+ public static final String PARCEL_PREFIX_DIR =
+ ParcelZipper.PARCEL_PREFIX_DIR;
+
+ public static final String[] OFFICE_EXTENSIONS =
+ {".sxc" , ".sxw", ".sxi", ".sxd"};
+ public static final String OFFICE_PRODUCT_NAME = "OpenOffice.org";
+
+ private File file = null;
+
+ public OfficeDocument(File file) throws IllegalArgumentException
+ {
+ if (!file.exists() || file.isDirectory() || !isOfficeFile(file)) {
+ throw new IllegalArgumentException("This is not a valid " +
+ OFFICE_PRODUCT_NAME + " document.");
+ }
+ this.file = file;
+ }
+
+ private boolean isOfficeFile(File file) {
+ for (int i = 0; i < OFFICE_EXTENSIONS.length; i++)
+ if (file.getName().endsWith(OFFICE_EXTENSIONS[i]))
+ return true;
+ return false;
+ }
+
+ public Enumeration getParcels() {
+
+ Vector parcels = new Vector();
+ ZipFile zp = null;
+
+ try
+ {
+ zp = new ZipFile(this.file);
+
+ for (Enumeration enumer = zp.entries(); enumer.hasMoreElements(); )
+ {
+ ZipEntry ze = (ZipEntry)enumer.nextElement();
+ if (ze.getName().endsWith(ParcelZipper.PARCEL_DESCRIPTOR_XML))
+ {
+ String tmp = ze.getName();
+ int end = tmp.lastIndexOf("/");
+ tmp = tmp.substring(0, end);
+
+ String parcelName = ze.getName().substring(0, end);
+ parcels.add(parcelName);
+ }
+ }
+ }
+ catch(ZipException ze) {
+ ze.printStackTrace();
+ }
+ catch(IOException ioe) {
+ ioe.printStackTrace();
+ }
+ finally {
+ if (zp != null) {
+ try {
+ zp.close();
+ }
+ catch (IOException asdf) {
+ }
+ }
+ }
+
+ return parcels.elements();
+ }
+
+ public boolean removeParcel(String parcelName) {
+
+ try {
+ ParcelZipper.getParcelZipper().removeParcel(file, parcelName);
+ }
+ catch (IOException ioe) {
+ ioe.printStackTrace();
+ return false;
+ }
+ return true;
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/OfficeInstallation.java b/scripting/java/org/openoffice/idesupport/OfficeInstallation.java
new file mode 100644
index 000000000000..784bde69456c
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/OfficeInstallation.java
@@ -0,0 +1,113 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeInstallation.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package org.openoffice.idesupport;
+
+import java.io.File;
+import java.net.URLDecoder;
+
+public class OfficeInstallation implements java.io.Serializable {
+
+ private String name;
+ private String path;
+ private String url;
+ private boolean hasFW = false;
+ private boolean supportsFW = false;
+
+ public static final String FILE_URL_PREFIX = SVersionRCFile.FILE_URL_PREFIX;
+
+ public OfficeInstallation(String path) {
+ this(path, path);
+ }
+
+ public OfficeInstallation(String name, String path) {
+
+ this.name = name;
+
+ if (path.startsWith(FILE_URL_PREFIX)) {
+ this.url = path;
+ path = URLDecoder.decode(path);
+ path = path.substring(FILE_URL_PREFIX.length());
+
+ if (System.getProperty("os.name").startsWith("Windows"))
+ path = path.replace('/', File.separatorChar);
+
+ this.path = path;
+ }
+ else {
+ this.path = path;
+
+ if (System.getProperty("os.name").startsWith("Windows"))
+ path = path.replace(File.separatorChar, '/');
+
+ this.url = FILE_URL_PREFIX + path;
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public String getPath(String name) {
+ if (!name.startsWith(File.separator))
+ name = File.separator + name;
+
+ return path + name;
+ }
+
+ public String getURL() {
+ return url;
+ }
+
+ public String getURL(String name) {
+ if (System.getProperty("os.name").startsWith("Windows"))
+ name = name.replace(File.separatorChar, '/');
+
+ if (!name.startsWith("/"))
+ name = "/" + name;
+
+ return url + name;
+ }
+
+ public boolean hasFramework() {
+ return hasFW;
+ }
+
+ public boolean supportsFramework() {
+ return true;
+ }
+
+ public String toString() {
+ return getName();
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/SVersionRCFile.java b/scripting/java/org/openoffice/idesupport/SVersionRCFile.java
new file mode 100644
index 000000000000..b4646326d060
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/SVersionRCFile.java
@@ -0,0 +1,240 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: SVersionRCFile.java,v $
+ * $Revision: 1.13 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport;
+
+import java.io.File;
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.FileNotFoundException;
+import java.util.Vector;
+import java.util.HashMap;
+import java.util.Enumeration;
+import java.util.StringTokenizer;
+
+public class SVersionRCFile {
+
+ public static final String DEFAULT_NAME =
+ System.getProperty("os.name").startsWith("Windows") == true ?
+ System.getProperty("user.home") + File.separator +
+ "Application Data" + File.separator + "sversion.ini" :
+ System.getProperty("user.home") + File.separator +
+ ".sversionrc";
+
+ public static final String FILE_URL_PREFIX =
+ System.getProperty("os.name").startsWith("Windows") == true ?
+ "file:///" : "file://";
+
+ public static final String PKGCHK =
+ System.getProperty("os.name").startsWith("Windows") == true ?
+ "pkgchk.exe" : "pkgchk";
+
+ private static final String VERSIONS_LINE = "[Versions]";
+
+ private static final String UNOILJAR =
+ "skip_registration" + File.separator + "unoil.jar";
+
+ private static final String UNOPACKAGEDIR =
+ File.separator + "user" + File.separator + "uno_packages" +
+ File.separator + "cache" + File.separator + "uno_packages";
+
+ /* Make sure this is in LowerCase !!!!! */
+ private static final String SCRIPTF = "scriptf";
+
+ private static final HashMap files = new HashMap(3);
+
+ private File sversionrc = null;
+ private OfficeInstallation defaultversion = null;
+ private Vector versions = null;
+ private long lastModified = 0;
+
+ public SVersionRCFile() {
+ this(DEFAULT_NAME);
+ }
+
+ public SVersionRCFile(String name) {
+ sversionrc = new File(name);
+ versions = new Vector(5);
+ }
+
+ public static SVersionRCFile createInstance() {
+ return(createInstance(DEFAULT_NAME));
+ }
+
+ public static SVersionRCFile createInstance(String name) {
+ SVersionRCFile result = null;
+
+ synchronized(SVersionRCFile.class) {
+ result = (SVersionRCFile)files.get(name);
+
+ if (result == null) {
+ result = new SVersionRCFile(name);
+ files.put(name, result);
+ }
+ }
+ return result;
+ }
+
+ public OfficeInstallation getDefaultVersion() throws IOException {
+ if (defaultversion == null) {
+ getVersions();
+ }
+
+ return defaultversion;
+ }
+
+ public Enumeration getVersions() throws IOException {
+
+ long l = sversionrc.lastModified();
+
+ if (l > lastModified) {
+ BufferedReader br = null;
+
+ try {
+ br = new BufferedReader(new FileReader(sversionrc));
+ load(br);
+ lastModified = l;
+ }
+ catch (FileNotFoundException fnfe) {
+ throw new IOException(fnfe.getMessage());
+ }
+ finally {
+ if (br != null)
+ br.close();
+ }
+ }
+ return versions.elements();
+ }
+
+ private void load(BufferedReader br) throws IOException {
+ String s;
+
+ while ((s = br.readLine()) != null &&
+ (s.equals(VERSIONS_LINE)) != true);
+
+ while ((s = br.readLine()) != null &&
+ (s.equals("")) != true) {
+ StringTokenizer tokens = new StringTokenizer(s, "=");
+ int count = tokens.countTokens();
+
+ if (count != 2)
+ continue;
+
+ String name = tokens.nextToken();
+ String path = tokens.nextToken();
+ OfficeInstallation oi = new OfficeInstallation(name, path);
+ if (oi.supportsFramework()) {
+ versions.add(oi);
+ defaultversion = oi;
+ }
+ }
+ }
+
+ public static String toFileURL(String path) {
+ File f = new File(path);
+
+ if (!f.exists())
+ return null;
+
+ try {
+ path = f.getCanonicalPath();
+ }
+ catch (IOException ioe) {
+ return null;
+ }
+
+ if (System.getProperty("os.name").startsWith("Windows"))
+ path = path.replace(File.separatorChar, '/');
+
+ StringBuffer buf = new StringBuffer(FILE_URL_PREFIX);
+ buf.append(path);
+
+ if (f.isDirectory())
+ buf.append("/");
+
+ return buf.toString();
+ }
+
+ public static String getPathForUnoil(String officeInstall)
+ {
+ File unopkgdir = new File(officeInstall, UNOPACKAGEDIR);
+ if(!unopkgdir.exists())
+ {
+ return null;
+ }
+ File scriptf = null;
+ String[] listunopkg = unopkgdir.list();
+ int size = listunopkg.length;
+ for(int i=0; i<size; i++)
+ {
+ if (listunopkg[i].toLowerCase().indexOf(SCRIPTF)>-1)
+ {
+ scriptf = new File(unopkgdir, listunopkg[i]);
+ }
+ }
+ if(scriptf != null)
+ {
+ File unoil = new File(scriptf, UNOILJAR);
+ if(unoil.exists())
+ {
+ String path = unoil.getParent();
+ path = path.substring(path.indexOf(UNOPACKAGEDIR));
+ return officeInstall + path;
+ }
+ }
+ return null;
+ }
+
+ public static void main(String[] args) {
+ SVersionRCFile ov;
+
+ if (args.length == 0)
+ ov = new SVersionRCFile();
+ else
+ ov = new SVersionRCFile(args[0]);
+
+ Enumeration enumer;
+
+ try {
+ enumer = ov.getVersions();
+ }
+ catch (IOException ioe) {
+ System.err.println("Error getting versions: " + ioe.getMessage());
+ return;
+ }
+
+ while (enumer.hasMoreElements()) {
+ OfficeInstallation oi = (OfficeInstallation)enumer.nextElement();
+ System.out.println("Name: " + oi.getName() + ", Path: " + oi.getPath() +
+ ", URL: " + oi.getURL());
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/filter/AllFilesFilter.java b/scripting/java/org/openoffice/idesupport/filter/AllFilesFilter.java
new file mode 100644
index 000000000000..2640d04cce2b
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/filter/AllFilesFilter.java
@@ -0,0 +1,50 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: AllFilesFilter.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport.filter;
+
+public class AllFilesFilter implements FileFilter {
+ private static final AllFilesFilter filter = new AllFilesFilter();
+
+ private AllFilesFilter() {
+ }
+
+ public static AllFilesFilter getInstance() {
+ return filter;
+ }
+
+ public boolean validate(String name) {
+ return true;
+ }
+
+ public String toString() {
+ return "<all files>";
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java b/scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java
new file mode 100644
index 000000000000..20882d3ecd66
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/filter/BinaryOnlyFilter.java
@@ -0,0 +1,61 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: BinaryOnlyFilter.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport.filter;
+
+public class BinaryOnlyFilter implements FileFilter {
+ private static final String[] EXTENSIONS = {".class", ".jar", ".bsh"};
+ private static final String DESCRIPTION = "Executable Files Only";
+ private static final BinaryOnlyFilter filter = new BinaryOnlyFilter();
+
+ private BinaryOnlyFilter() {
+ }
+
+ public static BinaryOnlyFilter getInstance() {
+ return filter;
+ }
+ public boolean validate(String name) {
+ for (int i = 0; i < EXTENSIONS.length; i++)
+ if (name.endsWith(EXTENSIONS[i]))
+ return true;
+ return false;
+ }
+
+ public String toString() {
+ /* StringBuffer buf = new StringBuffer(DESCRIPTION + ": ");
+
+ for (int i = 0; i < EXTENSIONS.length - 1; i++)
+ buf.append("<" + EXTENSIONS[i] + "> ");
+ buf.append("<" + EXTENSIONS[EXTENSIONS.length - 1] + ">");
+
+ return buf.toString(); */
+ return DESCRIPTION;
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java b/scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java
new file mode 100644
index 000000000000..53b57b6d5ee4
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/filter/ExceptParcelFilter.java
@@ -0,0 +1,62 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ExceptParcelFilter.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport.filter;
+
+public class ExceptParcelFilter implements FileFilter {
+ private static final String DESCRIPTION = "Remove specified Parcel";
+ private static final ExceptParcelFilter filter = new ExceptParcelFilter();
+ private static String parcelName = null;
+
+ private ExceptParcelFilter() {
+ }
+
+ public void setParcelToRemove(String parcelName)
+ {
+ this.parcelName = parcelName;
+ }
+
+ public static ExceptParcelFilter getInstance() {
+ return filter;
+ }
+ public boolean validate(String name) {
+ if (name.startsWith(this.parcelName))
+ return true;
+ return false;
+ }
+
+ public String toString() {
+ StringBuffer buf = new StringBuffer(DESCRIPTION + ": ");
+
+ buf.append("<" + this.parcelName + ">");
+
+ return buf.toString();
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/filter/FileFilter.java b/scripting/java/org/openoffice/idesupport/filter/FileFilter.java
new file mode 100644
index 000000000000..34add1a1b968
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/filter/FileFilter.java
@@ -0,0 +1,35 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: FileFilter.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport.filter;
+
+public interface FileFilter {
+ public boolean validate(String name);
+}
diff --git a/scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java b/scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java
new file mode 100644
index 000000000000..abcb4f40f8d5
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/localoffice/LocalOfficeImpl.java
@@ -0,0 +1,157 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: LocalOfficeImpl.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport.localoffice;
+
+import java.net.ConnectException;
+
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.XMultiComponentFactory;
+import com.sun.star.lang.XComponent;
+import com.sun.star.bridge.UnoUrlResolver;
+import com.sun.star.bridge.XUnoUrlResolver;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.comp.helper.Bootstrap;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.Exception;
+
+import drafts.com.sun.star.script.framework.storage.XScriptStorageManager;
+
+import org.openoffice.idesupport.LocalOffice;
+
+/**
+ * LocalOfficeImpl represents a connection to the local office.
+ *
+ * This class is an implementation of LocalOffice ane allows to
+ * get access to some scripting framework releated functionality
+ * of the locally running office. The office has to be started
+ * with options appropriate for establishing local connection.
+ *
+ * @author misha <misha@openoffice.org>
+ */
+public final class LocalOfficeImpl
+ extends LocalOffice
+{
+ private final static String STORAGE_MRG_SINGLETON =
+ "/singletons/drafts.com.sun.star.script.framework.storage.theScriptStorageManager";
+
+ private transient String mOfficePath;
+ private transient XMultiComponentFactory mComponentFactory;
+ private transient XComponentContext mComponentContext;
+ private transient XMultiServiceFactory mServiceFactory;
+ /**
+ * Constructor.
+ */
+ public LocalOfficeImpl()
+ {
+ }
+
+ /**
+ * Connects to the running office.
+ *
+ * @param officePath is a platform specific path string
+ * to the office distribution.
+ * @param port is a communication port.
+ */
+ protected void connect(String officePath, int port)
+ throws ConnectException
+ {
+ mOfficePath = officePath;
+ try {
+ bootstrap(port);
+ } catch (java.lang.Exception ex) {
+ throw new ConnectException(ex.getMessage());
+ }
+ }
+
+ /**
+ * Refresh the script storage.
+ *
+ * @param uri is an identifier of storage has to be refreshed.
+ */
+ public void refreshStorage(String uri)
+ {
+ try {
+ Object object = null;
+ object = mComponentContext.getValueByName(STORAGE_MRG_SINGLETON);
+ XScriptStorageManager storageMgr;
+ storageMgr = (XScriptStorageManager)UnoRuntime.queryInterface(
+ XScriptStorageManager.class, object);
+ storageMgr.refreshScriptStorage(uri);
+ } catch (java.lang.Exception ex) {
+System.out.println("*** LocalOfficeImpl.refreshStorage: FAILED " + ex.getMessage());
+System.out.println("*** LocalOfficeImpl.refreshStorage: FAILED " + ex.getClass().getName());
+ }
+System.out.println("*** LocalOfficeImpl.refreshStorage: DONE");
+ }
+
+ /**
+ * Closes the connection to the running office.
+ */
+ public void disconnect()
+ {
+/*
+ if(mComponentFactory != null) {
+ XComponent comp = (XComponent)UnoRuntime.queryInterface(
+ XComponent.class, mComponentFactory);
+ comp.dispose();
+ }
+*/
+ }
+
+ /**
+ * Boot straps UNO.
+ *
+ * The office has to be started with following string:
+ * "-accept=socket,host=localhost,port=<PORT>;urp;StarOffice.ServiceManager"
+ *
+ * @param port is a communication port.
+ */
+ private void bootstrap(int port)
+ throws java.lang.Exception
+ {
+ Object object;
+ mComponentContext = Bootstrap.createInitialComponentContext(null);
+ XUnoUrlResolver urlresolver = UnoUrlResolver.create(mComponentContext);
+ object = urlresolver.resolve(
+ "uno:socket,host=localhost,port=" +
+ port +
+ ";urp;StarOffice.ServiceManager");
+ mComponentFactory = (XMultiComponentFactory)UnoRuntime.queryInterface(
+ XMultiComponentFactory.class, object);
+ XPropertySet factoryProps;
+ factoryProps = (XPropertySet)UnoRuntime.queryInterface(
+ XPropertySet.class, mComponentFactory);
+ object = factoryProps.getPropertyValue("DefaultContext");
+ mComponentContext = (XComponentContext)UnoRuntime.queryInterface(
+ XComponentContext.class, object);
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java b/scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java
new file mode 100644
index 000000000000..7e5a0e330a11
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/ui/ConfigurePanel.java
@@ -0,0 +1,239 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ConfigurePanel.java,v $
+ * $Revision: 1.10 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport.ui;
+
+import java.io.File;
+import java.io.IOException;
+
+import java.util.Vector;
+import java.util.Enumeration;
+
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JButton;
+import javax.swing.AbstractButton;
+import javax.swing.ImageIcon;
+import javax.swing.border.LineBorder;
+
+import java.awt.BorderLayout;
+import java.awt.GridBagLayout;
+import java.awt.GridBagConstraints;
+import java.awt.Insets;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import org.w3c.dom.Document;
+
+import com.sun.star.script.framework.container.ScriptEntry;
+import com.sun.star.script.framework.container.ParcelDescriptor;
+
+import org.openoffice.idesupport.zip.ParcelZipper;
+
+public class ConfigurePanel extends JPanel {
+
+ private File basedir;
+ private Vector classpath;
+ private ParcelDescriptor descriptor;
+
+ private MethodPanel methodPanel;
+ private ScriptPanel scriptPanel;
+
+ public static final String DIALOG_TITLE =
+ "Choose What to Export as Scripts";
+
+ public ConfigurePanel(String basedir, Vector classpath,
+ ParcelDescriptor descriptor) {
+
+ this.basedir = new File(basedir);
+ this.classpath = classpath;
+ this.descriptor = descriptor;
+ initUI();
+ }
+
+ public ConfigurePanel(String basedir, Vector classpath)
+ throws IOException {
+
+ this.basedir = new File(basedir);
+ this.classpath = classpath;
+ this.descriptor = new ParcelDescriptor(new File(this.basedir,
+ ParcelZipper.PARCEL_DESCRIPTOR_XML));
+ initUI();
+ }
+
+ public void reload(String basedir, Vector classpath,
+ ParcelDescriptor descriptor) {
+
+ if (basedir != null)
+ this.basedir = new File(basedir);
+
+ if (classpath != null)
+ this.classpath = classpath;
+
+ if (descriptor != null) {
+ descriptor = descriptor;
+ }
+
+ methodPanel.reload(this.basedir, this.classpath,
+ descriptor.getLanguage());
+ scriptPanel.reload(descriptor.getScriptEntries());
+ }
+
+ public void reload(String basedir, Vector classpath)
+ throws IOException {
+
+ if (basedir != null)
+ this.basedir = new File(basedir);
+
+ if (classpath != null)
+ this.classpath = classpath;
+
+ this.descriptor = new ParcelDescriptor(new File(this.basedir,
+ ParcelZipper.PARCEL_DESCRIPTOR_XML));
+
+ methodPanel.reload(this.basedir, this.classpath,
+ descriptor.getLanguage());
+ scriptPanel.reload(descriptor.getScriptEntries());
+ }
+
+ public ParcelDescriptor getConfiguration() throws Exception {
+ Enumeration scripts = scriptPanel.getScriptEntries();
+ descriptor.setScriptEntries(scripts);
+ return descriptor;
+ }
+
+ private void initUI() {
+
+ JPanel leftPanel = new JPanel();
+ JPanel methodButtons = initMethodButtons();
+ methodPanel = new MethodPanel(basedir, classpath, descriptor.getLanguage());
+
+ leftPanel.setLayout(new BorderLayout());
+ leftPanel.add(methodPanel, BorderLayout.CENTER);
+
+ JPanel rightPanel = new JPanel();
+ JPanel scriptButtons = initScriptButtons();
+ scriptPanel = new ScriptPanel(descriptor.getScriptEntries());
+
+ rightPanel.setLayout(new BorderLayout());
+ rightPanel.add(scriptPanel, BorderLayout.CENTER);
+ rightPanel.add(scriptButtons, BorderLayout.SOUTH);
+
+ setLayout(new GridBagLayout());
+ setPreferredSize(new java.awt.Dimension(700, 300));
+ setBorder(LineBorder.createBlackLineBorder());
+
+ GridBagConstraints gbc = new GridBagConstraints();
+ gbc.gridx = 0;
+ gbc.gridy = 0;
+ gbc.fill = java.awt.GridBagConstraints.BOTH;
+ gbc.ipadx = 40;
+ gbc.anchor = java.awt.GridBagConstraints.WEST;
+ gbc.insets = new Insets(10, 5, 5, 5);
+ gbc.weightx = 0.75;
+ add(leftPanel, gbc);
+
+ gbc = new java.awt.GridBagConstraints();
+ gbc.gridx = 1;
+ gbc.gridy = 0;
+ add(methodButtons, gbc);
+
+ gbc = new java.awt.GridBagConstraints();
+ gbc.gridx = 2;
+ gbc.gridy = 0;
+ gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER;
+ gbc.fill = java.awt.GridBagConstraints.BOTH;
+ gbc.anchor = java.awt.GridBagConstraints.EAST;
+ gbc.insets = new Insets(10, 5, 5, 5);
+ gbc.weightx = 1.0;
+ gbc.weighty = 1.0;
+ add(rightPanel, gbc);
+ }
+
+ private JPanel initMethodButtons() {
+ JPanel panel = new JPanel();
+ panel.setLayout(new GridBagLayout());
+ ImageIcon icon = new ImageIcon(getClass().getResource("/org/openoffice/idesupport/ui/add.gif"));
+ JButton addButton = new JButton("Add", icon);
+ addButton.setHorizontalTextPosition(AbstractButton.LEFT);
+
+ addButton.addActionListener(
+ new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ scriptPanel.addScriptEntries(methodPanel.getSelectedEntries());
+ }
+ }
+ );
+
+ GridBagConstraints gbc = new java.awt.GridBagConstraints();
+ gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER;
+ gbc.fill = java.awt.GridBagConstraints.HORIZONTAL;
+ gbc.insets = new Insets(5, 5, 5, 5);
+ panel.add(addButton, gbc);
+
+ JPanel dummyPanel = new JPanel();
+ gbc = new java.awt.GridBagConstraints();
+ gbc.gridwidth = java.awt.GridBagConstraints.REMAINDER;
+ gbc.gridheight = java.awt.GridBagConstraints.REMAINDER;
+ gbc.fill = java.awt.GridBagConstraints.BOTH;
+ gbc.weightx = 1.0;
+ gbc.weighty = 1.0;
+ panel.add(dummyPanel, gbc);
+
+ return panel;
+ }
+
+ private JPanel initScriptButtons() {
+ JPanel panel = new JPanel();
+ JButton removeButton = new JButton("Remove");
+ JButton removeAllButton = new JButton("Remove All");
+
+ removeButton.addActionListener(
+ new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ scriptPanel.removeSelectedRows();
+ }
+ }
+ );
+
+ removeAllButton.addActionListener(
+ new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ scriptPanel.removeAllRows();
+ }
+ }
+ );
+
+ panel.add(removeButton);
+ panel.add(removeAllButton);
+
+ return panel;
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/ui/MethodPanel.java b/scripting/java/org/openoffice/idesupport/ui/MethodPanel.java
new file mode 100644
index 000000000000..4236c7dcd305
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/ui/MethodPanel.java
@@ -0,0 +1,189 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: MethodPanel.java,v $
+ * $Revision: 1.11 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport.ui;
+
+import java.io.File;
+import java.util.Vector;
+import java.util.ArrayList;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JList;
+import javax.swing.JTable;
+import javax.swing.table.AbstractTableModel;
+import javax.swing.JLabel;
+import java.awt.BorderLayout;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.net.MalformedURLException;
+
+import com.sun.star.script.framework.container.ScriptEntry;
+import org.openoffice.idesupport.MethodFinder;
+import org.openoffice.idesupport.ExtensionFinder;
+import org.openoffice.idesupport.JavaFinder;
+
+public class MethodPanel extends JPanel {
+
+ private File basedir;
+ private Vector classpath;
+ private final static String FIRST_PARAM =
+ "drafts.com.sun.star.script.framework.runtime.XScriptContext";
+
+ // private JTable table;
+ // private MethodTableModel model;
+ private JList list;
+ private ScriptEntry[] values;
+
+ public MethodPanel(File basedir, Vector classpath, String language) {
+ this.basedir = basedir;
+ this.classpath = classpath;
+
+ initValues(language);
+ initUI();
+ }
+
+ public void reload(File basedir, Vector classpath, String language) {
+ this.basedir = basedir;
+ this.classpath = classpath;
+
+ initValues(language);
+ list.setListData(values);
+ }
+
+ public ScriptEntry[] getSelectedEntries() {
+ Object[] selections = list.getSelectedValues();
+ ScriptEntry[] entries = new ScriptEntry[selections.length];
+
+ for (int i = 0; i < selections.length; i++) {
+ entries[i] = (ScriptEntry)selections[i];
+ }
+
+ return entries;
+ }
+
+ private void initUI() {
+ JLabel label = new JLabel("Available Methods:");
+ // table = new JTable(model);
+ list = new JList(values);
+
+ JScrollPane pane = new JScrollPane(list);
+ label.setLabelFor(pane);
+
+ BorderLayout layout = new BorderLayout();
+ setLayout(layout);
+ layout.setVgap(5);
+
+ add(label, BorderLayout.NORTH);
+ add(pane, BorderLayout.CENTER);
+ }
+
+ private void initValues(String language) {
+ MethodFinder finder;
+
+ if (language == null)
+ finder = JavaFinder.getInstance(classpath);
+ else if (language.toLowerCase().equals("beanshell"))
+ finder = new ExtensionFinder(language, new String[] {".bsh"});
+ else
+ finder = JavaFinder.getInstance(classpath);
+
+ values = finder.findMethods(basedir);
+ }
+
+ /*
+ private class MethodTableModel extends AbstractTableModel {
+ final String[] columnNames = {"Method",
+ "Language"};
+
+ private Vector methods;
+ private int nextRow;
+
+ public MethodTableModel() {
+ methods = new Vector(11);
+ }
+
+ public int getColumnCount() {
+ return columnNames.length;
+ }
+
+ public int getRowCount() {
+ return methods.size();
+ }
+
+ public String getColumnName(int col) {
+ return columnNames[col];
+ }
+
+ public void add(ScriptEntry entry) {
+ methods.addElement(entry);
+ fireTableRowsInserted(nextRow, nextRow);
+ nextRow++;
+ }
+
+ public void remove(int row) {
+ methods.removeElementAt(row);
+ fireTableRowsDeleted(row, row);
+ nextRow--;
+ }
+
+ public void removeAll() {
+ methods.removeAllElements();
+ fireTableRowsDeleted(0, nextRow);
+ nextRow = 0;
+ }
+
+ public Object getValueAt(int row) {
+ return methods.elementAt(row);
+ }
+
+ public Object getValueAt(int row, int col) {
+ String result = "";
+ ScriptEntry entry;
+
+ entry = (ScriptEntry)methods.elementAt(row);
+
+ if (col == 0)
+ result = entry.getLanguageName();
+ else if (col == 1)
+ result = entry.getLanguage();
+
+ return result;
+ }
+
+ public boolean isCellEditable(int row, int col) {
+ return false;
+ }
+ }
+ */
+}
diff --git a/scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java b/scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java
new file mode 100644
index 000000000000..19fcf85e7ea1
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/ui/ScriptPanel.java
@@ -0,0 +1,209 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptPanel.java,v $
+ * $Revision: 1.7 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport.ui;
+
+import java.io.File;
+import java.util.Vector;
+import java.util.Enumeration;
+
+import java.awt.BorderLayout;
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusAdapter;
+
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JLabel;
+import javax.swing.JTextField;
+import javax.swing.JTable;
+import javax.swing.DefaultCellEditor;
+import javax.swing.table.TableCellEditor;
+import javax.swing.table.TableColumn;
+import javax.swing.table.AbstractTableModel;
+
+import com.sun.star.script.framework.container.ScriptEntry;
+
+public class ScriptPanel extends JPanel {
+ private ScriptTableModel model;
+ private JTable table;
+
+ public ScriptPanel(ScriptEntry[] scripts) {
+ model = new ScriptTableModel(scripts);
+ initUI();
+ }
+
+ public void reload(ScriptEntry[] entries) {
+ model.removeAll();
+ addScriptEntries(entries);
+ }
+
+ public void addScriptEntries(ScriptEntry[] entries) {
+ for (int i = 0; i < entries.length; i++) {
+ ScriptEntry entry;
+
+ try {
+ entry = (ScriptEntry) entries[i].clone();
+ }
+ catch (CloneNotSupportedException cnse) {
+ entry = new ScriptEntry(entries[i].getLanguage(),
+ entries[i].getLanguageName(),
+ entries[i].getLogicalName(),
+ entries[i].getLocation());
+ }
+
+ model.add(entry);
+ }
+ }
+
+ public void removeSelectedRows() {
+ int[] selections = table.getSelectedRows();
+
+ for (int i = selections.length - 1; i >= 0; i--) {
+ model.remove(selections[i]);
+ }
+ }
+
+ public void removeAllRows() {
+ model.removeAll();
+ }
+
+ public Enumeration getScriptEntries() {
+ return model.getScriptEntries();
+ }
+
+ private void initUI() {
+ table = new JTable(model);
+ TableColumn column = table.getColumnModel().getColumn(1);
+ column.setCellEditor(new DefaultCellEditor(new JTextField()));
+
+ table.addFocusListener(new FocusAdapter() {
+ public void focusLost(FocusEvent evt) {
+ tableFocusLost(evt);
+ }
+ });
+
+ JScrollPane pane = new JScrollPane(table);
+ JLabel label = new JLabel("Scripts:");
+ label.setLabelFor(pane);
+
+ BorderLayout layout = new BorderLayout();
+ setLayout(layout);
+ layout.setVgap(5);
+ add(label, BorderLayout.NORTH);
+ add(pane, BorderLayout.CENTER);
+ }
+
+ private void tableFocusLost(FocusEvent evt) {
+ TableCellEditor editor = table.getCellEditor();
+ if (editor != null) {
+ Object value = editor.getCellEditorValue();
+ if (value != null)
+ model.setValueAt(value,
+ table.getEditingRow(), table.getEditingColumn());
+ }
+ }
+
+ private class ScriptTableModel extends AbstractTableModel {
+ final String[] columnNames = {"Exported Method",
+ "Script Name"};
+
+ private Vector scripts;
+ private int nextRow;
+
+ public ScriptTableModel(ScriptEntry[] entries) {
+ scripts = new Vector(entries.length + 11);
+ for (int i = 0; i < entries.length; i++) {
+ scripts.addElement(entries[i]);
+ }
+ nextRow = entries.length;
+ }
+
+ public int getColumnCount() {
+ return columnNames.length;
+ }
+
+ public int getRowCount() {
+ return scripts.size();
+ }
+
+ public String getColumnName(int col) {
+ return columnNames[col];
+ }
+
+ public void add(ScriptEntry entry) {
+ scripts.addElement(entry);
+ fireTableRowsInserted(nextRow, nextRow);
+ nextRow++;
+ }
+
+ public void remove(int row) {
+ scripts.removeElementAt(row);
+ fireTableRowsDeleted(row, row);
+ nextRow--;
+ }
+
+ public void removeAll() {
+ scripts.removeAllElements();
+ fireTableRowsDeleted(0, nextRow);
+ nextRow = 0;
+ }
+
+ public Enumeration getScriptEntries() {
+ return scripts.elements();
+ }
+
+ public Object getValueAt(int row, int col) {
+ String result = "";
+ ScriptEntry entry;
+
+ entry = (ScriptEntry)scripts.elementAt(row);
+
+ if (col == 0)
+ result = entry.getLanguageName();
+ else if (col == 1)
+ result = entry.getLogicalName();
+
+ return result;
+ }
+
+ public boolean isCellEditable(int row, int col) {
+ if (col == 0)
+ return false;
+ else
+ return true;
+ }
+
+ public void setValueAt(Object value, int row, int col) {
+ ScriptEntry entry = (ScriptEntry)scripts.elementAt(row);
+ entry.setLogicalName((String)value);
+ fireTableCellUpdated(row, col);
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/ui/add.gif b/scripting/java/org/openoffice/idesupport/ui/add.gif
new file mode 100644
index 000000000000..e47c986ccf1f
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/ui/add.gif
Binary files differ
diff --git a/scripting/java/org/openoffice/idesupport/xml/Manifest.java b/scripting/java/org/openoffice/idesupport/xml/Manifest.java
new file mode 100644
index 000000000000..37e7890898c6
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/xml/Manifest.java
@@ -0,0 +1,174 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: Manifest.java,v $
+ * $Revision: 1.10 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport.xml;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.IOException;
+
+import java.util.Enumeration;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Element;
+
+import com.sun.star.script.framework.container.XMLParserFactory;
+
+public class Manifest {
+
+ private Document document = null;
+ private boolean baseElementsExist = false;
+
+ public Manifest(InputStream inputStream) throws IOException {
+ document = XMLParserFactory.getParser().parse(inputStream);
+ }
+
+ public void add(String entry) {
+ add(entry, "");
+ }
+
+ private void add(String entry, String type) {
+ Element root, el;
+
+ ensureBaseElementsExist();
+
+ try {
+ root = (Element)
+ document.getElementsByTagName("manifest:manifest").item(0);
+
+ el = document.createElement("manifest:file-entry");
+ el.setAttribute("manifest:media-type", type);
+ el.setAttribute("manifest:full-path", entry);
+ // System.out.println("added: " + el.toString());
+ root.appendChild(el);
+ }
+ catch (Exception e) {
+ System.err.println("Error adding entry: " + e.getMessage());
+ }
+ }
+
+ private void ensureBaseElementsExist() {
+ if (baseElementsExist == false) {
+ baseElementsExist = true;
+ add("Scripts/", "application/script-parcel");
+ }
+ }
+
+ public void remove(String entry) {
+ Element root, el;
+ int len;
+
+ try {
+ root = (Element)
+ document.getElementsByTagName("manifest:manifest").item(0);
+
+ NodeList nl = root.getElementsByTagName("manifest:file-entry");
+ if (nl == null || (len = nl.getLength()) == 0)
+ return;
+
+ ArrayList list = new ArrayList();
+ for (int i = 0; i < len; i++) {
+ el = (Element)nl.item(i);
+ if (el.getAttribute("manifest:full-path").startsWith(entry)) {
+ // System.out.println("found: " + el.toString());
+ list.add(el);
+ }
+ }
+
+ Iterator iter = list.iterator();
+ while (iter.hasNext())
+ root.removeChild((Element)iter.next());
+
+ // System.out.println("and after root is: " + root.toString());
+ }
+ catch (Exception e) {
+ System.err.println("Error removing entry: " + e.getMessage());
+ }
+ }
+
+ public InputStream getInputStream() throws IOException {
+ InputStream result = null;
+ ByteArrayOutputStream out = null;
+
+ try {
+ out = new ByteArrayOutputStream();
+ write(out);
+ result = new ByteArrayInputStream(out.toByteArray());
+ // result = replaceNewlines(out.toByteArray());
+ }
+ finally {
+ if (out != null)
+ out.close();
+ }
+
+ return result;
+ }
+
+ private InputStream replaceNewlines(byte[] bytes) throws IOException {
+ InputStream result;
+ ByteArrayOutputStream out;
+ BufferedReader reader;
+
+ reader = new BufferedReader(new InputStreamReader(
+ new ByteArrayInputStream(bytes)));
+ out = new ByteArrayOutputStream();
+
+ int previous = reader.read();
+ out.write(previous);
+ int current;
+
+ while ((current = reader.read()) != -1) {
+ if (((char)current == '\n' || (char)current == ' ') &&
+ (char)previous == '\n')
+ continue;
+ else {
+ out.write(current);
+ previous = current;
+ }
+ }
+ result = new ByteArrayInputStream(out.toByteArray());
+
+ return result;
+ }
+
+ public void write(OutputStream out) throws IOException {
+ XMLParserFactory.getParser().write(document, out);
+ }
+}
diff --git a/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java b/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java
new file mode 100644
index 000000000000..01f82977ca84
--- /dev/null
+++ b/scripting/java/org/openoffice/idesupport/zip/ParcelZipper.java
@@ -0,0 +1,603 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelZipper.java,v $
+ * $Revision: 1.12 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.idesupport.zip;
+
+import java.io.*;
+import java.util.Enumeration;
+import java.util.zip.*;
+import java.beans.PropertyVetoException;
+
+import org.openoffice.idesupport.filter.FileFilter;
+import org.openoffice.idesupport.filter.BinaryOnlyFilter;
+import org.openoffice.idesupport.filter.ExceptParcelFilter;
+
+import com.sun.star.script.framework.container.ParcelDescriptor;
+import org.openoffice.idesupport.xml.Manifest;
+
+public class ParcelZipper
+{
+ public static final String PARCEL_PREFIX_DIR = "Scripts/";
+ public static final String PARCEL_EXTENSION = "sxp";
+ public static final String CONTENTS_DIRNAME = "Contents";
+ public static final String PARCEL_DESCRIPTOR_XML = "parcel-descriptor.xml";
+
+ private static ParcelZipper zipper = null;
+
+ private static final FileFilter DEFAULT_FILTER =
+ BinaryOnlyFilter.getInstance();
+
+ private ParcelZipper() {
+ }
+
+ public static ParcelZipper getParcelZipper() {
+ if (zipper == null) {
+ synchronized(ParcelZipper.class) {
+ if (zipper == null)
+ zipper = new ParcelZipper();
+ }
+ }
+ return zipper;
+ }
+
+ public String zipParcel(File basedir) throws IOException {
+ File targetfile, targetdir;
+
+ if (basedir.getName().equals(CONTENTS_DIRNAME))
+ targetdir = basedir.getParentFile();
+ else
+ targetdir = basedir;
+
+ targetfile = new File(targetdir, targetdir.getName() + "." + PARCEL_EXTENSION);
+
+ return zipParcel(basedir, targetfile, DEFAULT_FILTER);
+ }
+
+ public String zipParcel(File basedir, File targetfile) throws IOException {
+ return zipParcel(basedir, targetfile, DEFAULT_FILTER);
+ }
+
+ public String zipParcel(File basedir, FileFilter filter) throws IOException {
+ File targetfile, targetdir;
+
+ if (basedir.getName().equals(CONTENTS_DIRNAME))
+ targetdir = basedir.getParentFile();
+ else
+ targetdir = basedir;
+
+ targetfile = new File(targetdir, targetdir.getName() + "." + PARCEL_EXTENSION);
+
+ return zipParcel(basedir, targetfile, filter);
+ }
+
+ public String zipParcel(File basedir, File targetfile, FileFilter filter)
+ throws IOException {
+ String realpath, tmppath;
+
+ realpath = targetfile.getPath();
+ tmppath = realpath + ".tmp";
+
+ File tmpfile = new File(tmppath);
+ ZipOutputStream out = null;
+ try {
+ if (tmpfile.exists() == true)
+ tmpfile.delete();
+
+ out = new ZipOutputStream(new FileOutputStream(tmpfile));
+
+ File[] children = basedir.listFiles();
+ for (int i = 0; i < children.length; i++)
+ addFileToParcel(children[i], "", out, filter);
+ }
+ catch (IOException ioe) {
+ out.close();
+ tmpfile.delete();
+ throw ioe;
+ }
+ finally {
+ if (out != null)
+ out.close();
+ }
+
+ if (targetfile.exists() == true)
+ targetfile.delete();
+ tmpfile.renameTo(targetfile);
+
+ return targetfile.getAbsolutePath();
+ }
+
+ private void addFileToParcel(File root, String path, ZipOutputStream out, FileFilter filter)
+ throws IOException {
+ ZipEntry ze;
+
+ if (root.isDirectory() == true) {
+ ze = new ZipEntry(/* PARCEL_PREFIX_DIR + */ path + root.getName() + "/");
+ out.putNextEntry(ze);
+ out.closeEntry();
+ File[] children = root.listFiles();
+
+ for (int i = 0; i < children.length; i++)
+ addFileToParcel(children[i], path + root.getName() + "/", out, filter);
+ }
+ else {
+ if (filter.validate(root.getName()) == false &&
+ root.getName().equals("parcel-descriptor.xml") == false)
+ return;
+
+ ze = new ZipEntry(/* PARCEL_PREFIX_DIR + */ path + root.getName());
+ out.putNextEntry(ze);
+
+ byte[] bytes = new byte[1024];
+ int len;
+
+ FileInputStream fis = null;
+ try {
+ fis = new FileInputStream(root);
+
+ while ((len = fis.read(bytes)) != -1)
+ out.write(bytes, 0, len);
+ }
+ finally {
+ if (fis != null) fis.close();
+ }
+ out.closeEntry();
+ }
+ }
+
+ public boolean isOverwriteNeeded(File parcel, File target)
+ throws IOException
+ {
+ boolean result;
+
+ if (target.isDirectory())
+ result = isDirectoryOverwriteNeeded(parcel, target);
+ else
+ result = isDocumentOverwriteNeeded(parcel, target);
+
+ return result;
+ }
+
+ private boolean isDirectoryOverwriteNeeded(File parcel, File target) {
+ String parcelDir = getParcelDirFromParcelZip(parcel.getName());
+
+ File langdir;
+ try {
+ langdir = new File(target, getParcelLanguage(parcel));
+ }
+ catch (IOException ioe) {
+ return false;
+ }
+
+ if (langdir.exists() == false)
+ return false;
+
+ File[] children = langdir.listFiles();
+
+ for (int i = 0; i < children.length; i++)
+ if (children[i].getName().equals(parcelDir))
+ return true;
+
+ return false;
+ }
+
+ private boolean isDocumentOverwriteNeeded(File parcel, File document)
+ throws IOException
+ {
+ ZipFile documentZip = null;
+ boolean result = false;
+
+ try {
+ documentZip = new ZipFile(document);
+
+ String name =
+ PARCEL_PREFIX_DIR + getParcelLanguage(parcel) +
+ "/" + getParcelDirFromParcelZip(parcel.getName()) +
+ "/" + PARCEL_DESCRIPTOR_XML;
+
+ if (documentZip.getEntry(name) != null)
+ result = true;
+ }
+ catch (IOException ioe) {
+ return false;
+ }
+ finally {
+ if (documentZip != null) documentZip.close();
+ }
+
+ return result;
+ }
+
+ public String deployParcel(File parcel, File target)
+ throws IOException {
+
+ String output = null;
+ if (target.isDirectory())
+ output = unzipToDirectory(parcel, target);
+ else
+ output = unzipToZip(parcel, target);
+ return output;
+ }
+
+ private String getParcelDirFromParcelZip(String zipname) {
+ String result = zipname.substring(0, zipname.lastIndexOf("."));
+ return result;
+ }
+
+ private String unzipToDirectory(File parcel, File targetDirectory)
+ throws IOException {
+
+ ZipInputStream in = null;
+ File parcelDir = new File(targetDirectory,
+ getParcelLanguage(parcel) + File.separator +
+ getParcelDirFromParcelZip(parcel.getName()));
+
+ if (isDirectoryOverwriteNeeded(parcel, targetDirectory)) {
+ if (deleteDir(parcelDir) == false) {
+ throw new IOException("Could not overwrite: " +
+ parcelDir.getAbsolutePath());
+ }
+ }
+
+ try {
+ in = new ZipInputStream(new FileInputStream(parcel));
+
+ File outFile;
+ ZipEntry inEntry = in.getNextEntry();
+ byte[] bytes = new byte[1024];
+ int len;
+
+ while (inEntry != null) {
+ outFile = new File(parcelDir, inEntry.getName());
+ if (inEntry.isDirectory()) {
+ outFile.mkdir();
+ }
+ else {
+ if (outFile.getParentFile().exists() != true)
+ outFile.getParentFile().mkdirs();
+
+ FileOutputStream out = null;
+ try {
+ out = new FileOutputStream(outFile);
+
+ while ((len = in.read(bytes)) != -1)
+ out.write(bytes, 0, len);
+ }
+ finally {
+ if (out != null) out.close();
+ }
+ }
+ inEntry = in.getNextEntry();
+ }
+ }
+ finally {
+ if (in != null) in.close();
+ }
+
+ return parcelDir.getAbsolutePath();
+ }
+
+ private boolean deleteDir(File basedir) {
+ if (basedir.isDirectory()) {
+ String[] children = basedir.list();
+ for (int i=0; i<children.length; i++) {
+ boolean success = deleteDir(new File(basedir, children[i]));
+ if (!success) {
+ return false;
+ }
+ }
+ }
+ return basedir.delete();
+ }
+
+ private String unzipToZip(File parcel, File targetDocument)
+ throws IOException {
+
+ ZipInputStream documentStream = null;
+ ZipInputStream parcelStream = null;
+ ZipOutputStream outStream = null;
+ Manifest manifest;
+
+ String language = getParcelLanguage(parcel);
+
+ if (isDocumentOverwriteNeeded(parcel, targetDocument)) {
+ String parcelName = language + "/" +
+ getParcelDirFromParcelZip(parcel.getName());
+ removeParcel(targetDocument, parcelName);
+ }
+
+ // first write contents of document to tmpfile
+ File tmpfile = new File(targetDocument.getAbsolutePath() + ".tmp");
+
+ manifest = addParcelToManifest(targetDocument, parcel);
+
+ try {
+ documentStream =
+ new ZipInputStream(new FileInputStream(targetDocument));
+ parcelStream = new ZipInputStream(new FileInputStream(parcel));
+ outStream = new ZipOutputStream(new FileOutputStream(tmpfile));
+
+ copyParcelToZip(parcelStream, outStream, PARCEL_PREFIX_DIR +
+ language + "/" + getParcelDirFromParcelZip(parcel.getName()));
+ copyDocumentToZip(documentStream, outStream, manifest);
+ }
+ catch (IOException ioe) {
+ tmpfile.delete();
+ throw ioe;
+ }
+ finally {
+ if (documentStream != null) documentStream.close();
+ if (parcelStream != null) parcelStream.close();
+ if (outStream != null) outStream.close();
+ }
+
+ if (targetDocument.delete() == false) {
+ tmpfile.delete();
+ throw new IOException("Could not overwrite " + targetDocument);
+ }
+ else
+ tmpfile.renameTo(targetDocument);
+
+ return targetDocument.getAbsolutePath();
+ }
+
+ private void copyParcelToZip(ZipInputStream in, ZipOutputStream out,
+ String parcelName) throws IOException {
+
+ ZipEntry outEntry;
+ ZipEntry inEntry = in.getNextEntry();
+ byte[] bytes = new byte[1024];
+ int len;
+
+ while (inEntry != null) {
+ if(parcelName!=null)
+ outEntry = new ZipEntry(parcelName + "/" + inEntry.getName());
+ else
+ outEntry = new ZipEntry(inEntry);
+ out.putNextEntry(outEntry);
+
+ if (inEntry.isDirectory() == false)
+ while ((len = in.read(bytes)) != -1)
+ out.write(bytes, 0, len);
+
+ out.closeEntry();
+ inEntry = in.getNextEntry();
+ }
+ }
+
+ private void copyDocumentToZip(ZipInputStream in, ZipOutputStream out,
+ Manifest manifest) throws IOException {
+
+ ZipEntry outEntry;
+ ZipEntry inEntry;
+ byte[] bytes = new byte[1024];
+ int len;
+
+ while ((inEntry = in.getNextEntry()) != null) {
+
+ outEntry = new ZipEntry(inEntry);
+ out.putNextEntry(outEntry);
+
+ if(inEntry.getName().equals("META-INF/manifest.xml") &&
+ manifest != null) {
+ InputStream manifestStream = null;
+ try {
+ manifestStream = manifest.getInputStream();
+ while ((len = manifestStream.read(bytes)) != -1)
+ out.write(bytes, 0, len);
+ }
+ finally {
+ if (manifestStream != null)
+ manifestStream.close();
+ }
+ }
+ else if (inEntry.isDirectory() == false) {
+ while ((len = in.read(bytes)) != -1)
+ out.write(bytes, 0, len);
+ }
+
+ out.closeEntry();
+ }
+ }
+
+ public String removeParcel(File document, String parcelName)
+ throws IOException {
+
+ ZipInputStream documentStream = null;
+ ZipOutputStream outStream = null;
+ Manifest manifest = null;
+
+ if (!parcelName.startsWith(PARCEL_PREFIX_DIR))
+ parcelName = PARCEL_PREFIX_DIR + parcelName;
+ manifest = removeParcelFromManifest(document, parcelName);
+
+ // first write contents of document to tmpfile
+ File tmpfile = new File(document.getAbsolutePath() + ".tmp");
+
+ try {
+ ZipEntry outEntry;
+ ZipEntry inEntry;
+ byte[] bytes = new byte[1024];
+ int len;
+
+ documentStream = new ZipInputStream(new FileInputStream(document));
+ outStream = new ZipOutputStream(new FileOutputStream(tmpfile));
+
+ while ((inEntry = documentStream.getNextEntry()) != null) {
+
+ if(inEntry.getName().startsWith(parcelName))
+ continue;
+
+ outEntry = new ZipEntry(inEntry);
+ outStream.putNextEntry(outEntry);
+
+ if(inEntry.getName().equals("META-INF/manifest.xml") &&
+ manifest != null) {
+ InputStream manifestStream = null;
+ try {
+ manifestStream = manifest.getInputStream();
+ while ((len = manifestStream.read(bytes)) != -1)
+ outStream.write(bytes, 0, len);
+ }
+ finally {
+ if (manifestStream != null)
+ manifestStream.close();
+ }
+ }
+ else if (inEntry.isDirectory() == false) {
+ while ((len = documentStream.read(bytes)) != -1)
+ outStream.write(bytes, 0, len);
+ }
+
+ outStream.closeEntry();
+ }
+ }
+ catch (IOException ioe) {
+ tmpfile.delete();
+ throw ioe;
+ }
+ finally {
+ if (documentStream != null)
+ documentStream.close();
+
+ if (outStream != null)
+ outStream.close();
+ }
+
+ if (document.delete() == false) {
+ tmpfile.delete();
+ throw new IOException("Could not overwrite " + document);
+ }
+ else
+ tmpfile.renameTo(document);
+
+ return document.getAbsolutePath();
+ }
+
+ private Manifest getManifestFromDocument(File document) {
+ ZipFile documentZip = null;
+ Manifest result = null;
+
+ try {
+ documentZip = new ZipFile(document);
+ ZipEntry original = documentZip.getEntry("META-INF/manifest.xml");
+ if (original != null) {
+ result = new Manifest(documentZip.getInputStream(original));
+ }
+ }
+ catch (IOException ioe) {
+ result = null;
+ }
+ finally {
+ try {
+ if (documentZip != null)
+ documentZip.close();
+ }
+ catch (IOException ioe) {}
+ }
+
+ return result;
+ }
+
+ private Manifest addParcelToManifest(File document, File parcel)
+ throws IOException {
+
+ ZipFile parcelZip = null;
+ Manifest result = null;
+
+ result = getManifestFromDocument(document);
+ if (result == null)
+ return null;
+
+ String language = getParcelLanguage(parcel);
+
+ try {
+ parcelZip = new ZipFile(parcel);
+
+ String prefix = PARCEL_PREFIX_DIR + language + "/" +
+ getParcelDirFromParcelZip(parcel.getName()) + "/";
+
+ Enumeration entries = parcelZip.entries();
+ while (entries.hasMoreElements()) {
+ ZipEntry entry = (ZipEntry)entries.nextElement();
+ result.add(prefix + entry.getName());
+ }
+ }
+ catch (IOException ioe) {
+ return null;
+ }
+ finally {
+ try {
+ if (parcelZip != null)
+ parcelZip.close();
+ }
+ catch (IOException ioe) {}
+ }
+
+ return result;
+ }
+
+ private Manifest removeParcelFromManifest(File document, String name) {
+ Manifest result = null;
+
+ result = getManifestFromDocument(document);
+ if (result == null)
+ return null;
+
+ result.remove(name);
+ return result;
+ }
+
+ public String getParcelLanguage(File file) throws IOException {
+ ZipFile zf = null;
+ ZipEntry ze = null;
+ InputStream is = null;
+ ParcelDescriptor pd;
+
+ try {
+ zf = new ZipFile(file);
+ ze = zf.getEntry(PARCEL_DESCRIPTOR_XML);
+
+ if (ze == null)
+ throw new IOException("Could not find Parcel Descriptor in parcel");
+
+ is = zf.getInputStream(ze);
+ pd = new ParcelDescriptor(is);
+ }
+ finally {
+ if (zf != null)
+ zf.close();
+
+ if (is != null)
+ is.close();
+ }
+
+ return pd.getLanguage().toLowerCase();
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/editor/JavaKit.java b/scripting/java/org/openoffice/netbeans/editor/JavaKit.java
new file mode 100644
index 000000000000..45fedd82b20c
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/editor/JavaKit.java
@@ -0,0 +1,251 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: JavaKit.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package org.openoffice.netbeans.editor;
+
+import java.io.*;
+import java.awt.event.KeyEvent;
+import java.awt.event.InputEvent;
+import java.awt.event.ActionEvent;
+import java.net.URL;
+import java.text.MessageFormat;
+
+import java.util.Map;
+import java.util.List;
+import java.util.ResourceBundle;
+import java.util.MissingResourceException;
+import javax.swing.KeyStroke;
+import javax.swing.JEditorPane;
+import javax.swing.JMenuItem;
+import javax.swing.Action;
+import javax.swing.text.Document;
+import javax.swing.text.JTextComponent;
+import javax.swing.text.TextAction;
+import javax.swing.text.BadLocationException;
+import org.netbeans.editor.*;
+import org.netbeans.editor.ext.*;
+import org.netbeans.editor.ext.java.*;
+
+/**
+* Java editor kit with appropriate document
+*
+* @author Miloslav Metelka
+* @version 1.00
+*/
+
+/* This class is based on the JavaKit class in the demosrc directory of
+ * the editor module of the NetBeans project: http://www.netbeans.org
+ *
+ * The class sets up an EditorKit for syntax highlighting and code completion
+ * of Java syntax
+ */
+
+public class JavaKit extends ExtKit {
+
+ public static final String JAVA_MIME_TYPE = "text/x-java"; // NOI18N
+
+ static final long serialVersionUID =-5445829962533684922L;
+
+ static {
+ Settings.addInitializer( new JavaSettingsInitializer( JavaKit.class ) );
+ Settings.reset();
+
+ URL skeleton = null, body = null;
+ skeleton = JavaKit.class.getResource("OOo.jcs");
+ body = JavaKit.class.getResource("OOo.jcb");
+
+ if (skeleton != null && body != null) {
+ DAFileProvider provider = new DAFileProvider(
+ new URLAccessor(skeleton),
+ new URLAccessor(body));
+
+ JCBaseFinder finder = new JCBaseFinder();
+ finder.append( provider );
+ JavaCompletion.setFinder( finder );
+ }
+ }
+
+ public String getContentType() {
+ return JAVA_MIME_TYPE;
+ }
+
+ /** Create new instance of syntax coloring scanner
+ * @param doc document to operate on. It can be null in the cases the syntax
+ * creation is not related to the particular document
+ */
+ public Syntax createSyntax(Document doc) {
+ return new JavaSyntax();
+ }
+
+ /** Create syntax support */
+ public SyntaxSupport createSyntaxSupport(BaseDocument doc) {
+ return new JavaSyntaxSupport(doc);
+ }
+
+ public Completion createCompletion(ExtEditorUI extEditorUI) {
+ return new JavaCompletion(extEditorUI);
+ }
+
+ /** Create the formatter appropriate for this kit */
+ public Formatter createFormatter() {
+ return new JavaFormatter(this.getClass());
+ }
+
+ protected EditorUI createEditorUI() {
+ return new ExtEditorUI();
+ }
+
+ protected void initDocument(BaseDocument doc) {
+ doc.addLayer(new JavaDrawLayerFactory.JavaLayer(),
+ JavaDrawLayerFactory.JAVA_LAYER_VISIBILITY);
+ doc.addDocumentListener(new JavaDrawLayerFactory.LParenWatcher());
+ }
+
+ /**
+ * DataAccessor for parser DB files via URL streams
+ *
+ * @author Petr Nejedly
+ */
+ public static class URLAccessor implements DataAccessor {
+
+ URL url;
+ InputStream stream;
+ int streamOff;
+ int actOff;
+
+ public URLAccessor(URL url) {
+ this.url = url;
+ }
+
+ /** Not implemented
+ */
+ public void append(byte[] buffer, int off, int len)
+ throws IOException
+ {
+ throw new IllegalArgumentException("read only!");
+ }
+
+ /**
+ * Reads exactly <code>len</code> bytes from this file resource
+ * into the byte array, starting at the current file pointer.
+ * This method reads repeatedly from the file until the requested
+ * number of bytes are read. This method blocks until the requested
+ * number of bytes are read, the end of the inputStream is detected,
+ * or an exception is thrown.
+ *
+ * @param buffer the buffer into which the data is read.
+ * @param off the start offset of the data.
+ * @param len the number of bytes to read.
+ */
+ public void read(byte[] buffer, int off, int len) throws IOException {
+ InputStream str = getStream(actOff);
+ while (len > 0) {
+ int count = str.read(buffer, off, len);
+ streamOff += count;
+ off += count;
+ len -= count;
+ }
+ }
+
+ /** Opens DataAccessor file resource
+ * @param requestWrite if true, file is opened for read/write
+ */
+ public void open(boolean requestWrite) throws IOException {
+ if(requestWrite)
+ throw new IllegalArgumentException("read only!");
+ }
+
+ /** Closes DataAccessor file resource */
+ public void close() throws IOException {
+ if (stream != null) {
+ stream.close();
+ stream = null;
+ }
+ }
+
+ /**
+ * Returns the current offset in this file.
+ *
+ * @return the offset from the beginning of the file, in bytes,
+ * at which the next read or write occurs.
+ */
+ public long getFilePointer() throws IOException {
+ return actOff;
+ }
+
+ /** Clears the file and sets the offset to 0 */
+ public void resetFile() throws IOException {
+ throw new IllegalArgumentException("read only!");
+ }
+
+ /**
+ * Sets the file-pointer offset, measured from the beginning of this
+ * file, at which the next read or write occurs.
+ */
+ public void seek(long pos) throws IOException {
+ actOff = (int)pos;
+ }
+
+ /** Gets InputStream prepared for reading from <code>off</code>
+ * offset position
+ */
+ private InputStream getStream(int off) throws IOException {
+ if (streamOff > off && stream != null) {
+ stream.close();
+ stream = null;
+ }
+
+ if(stream == null) {
+ stream = url.openStream();
+ streamOff = 0;
+ }
+
+ while (streamOff < off) {
+ long len = stream.skip(off - streamOff);
+ streamOff += (int)len;
+ if (len == 0) throw new IOException("EOF");
+ }
+
+ return stream;
+ }
+
+ public int getFileLength() {
+ try {
+ int l = url.openConnection().getContentLength();
+ return l;
+ } catch (IOException e) {
+ return 0;
+ }
+ }
+
+ public String toString() {
+ return url.toString();
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/editor/NetBeansSourceView.java b/scripting/java/org/openoffice/netbeans/editor/NetBeansSourceView.java
new file mode 100644
index 000000000000..09796543f4bc
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/editor/NetBeansSourceView.java
@@ -0,0 +1,212 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: NetBeansSourceView.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package org.openoffice.netbeans.editor;
+
+import javax.swing.*;
+import javax.swing.text.Document;
+import javax.swing.event.DocumentListener;
+import javax.swing.event.DocumentEvent;
+
+import java.io.*;
+import java.util.ResourceBundle;
+
+import javax.swing.text.Caret;
+import org.netbeans.editor.*;
+import org.netbeans.editor.ext.*;
+
+import com.sun.star.script.framework.provider.beanshell.ScriptSourceView;
+import com.sun.star.script.framework.provider.beanshell.ScriptSourceModel;
+
+public class NetBeansSourceView extends JPanel
+ implements ScriptSourceView, DocumentListener {
+
+ private ScriptSourceModel model;
+ private JEditorPane pane;
+ private boolean isModified = false;
+
+ static {
+ // Feed our kits with their default Settings
+ Settings.addInitializer(
+ new BaseSettingsInitializer(), Settings.CORE_LEVEL);
+ Settings.addInitializer(
+ new ExtSettingsInitializer(), Settings.CORE_LEVEL);
+ Settings.reset();
+
+ try {
+ Class kitClass = Class.forName(
+ NetBeansSourceView.class.getPackage().getName() + ".JavaKit");
+
+ JEditorPane.registerEditorKitForContentType(
+ "text/x-java", kitClass.getName(), kitClass.getClassLoader());
+ }
+ catch( ClassNotFoundException exc ) {
+ }
+ }
+
+ private class MyLocalizer implements LocaleSupport.Localizer {
+ private ResourceBundle bundle;
+
+ public MyLocalizer( String bundleName ) {
+ bundle = ResourceBundle.getBundle( bundleName );
+ }
+
+ // Localizer
+ public String getString( String key ) {
+ return bundle.getString( key );
+ }
+ }
+
+ public NetBeansSourceView(ScriptSourceModel model) {
+ this.model = model;
+
+ LocaleSupport.addLocalizer(
+ new MyLocalizer("org.netbeans.editor.Bundle"));
+
+ pane = new JEditorPane("text/x-java", "");
+ pane.setText(model.getText());
+
+ JScrollPane spane = new JScrollPane();
+ spane.setViewportView(pane);
+ setLayout(new java.awt.GridLayout(1, 1));
+ add(spane);
+
+ pane.getDocument().addDocumentListener(this);
+ }
+
+ public static void main(String[] args) {
+ if (args.length < 1) {
+ System.err.println("No file specified");
+ System.exit(-1);
+ }
+
+ File f = new File(args[0]);
+
+ if (!f.exists() || !f.isFile()) {
+ System.err.println("Invalid file");
+ System.exit(-1);
+ }
+
+ java.net.URL url = null;
+ try {
+ url = f.toURL();
+ }
+ catch (java.net.MalformedURLException mue) {
+ System.err.println("Invalid file");
+ System.exit(-1);
+ }
+
+ NetBeansSourceView view =
+ new NetBeansSourceView(new ScriptSourceModel(url));
+
+ JFrame frame = new JFrame();
+ frame.getContentPane().add(view);
+ frame.setSize(640, 480);
+ frame.show();
+ }
+
+ // Code grabbed from NetBeans editor module
+ public void scrollToLine(int line)
+ {
+ BaseDocument doc = Utilities.getDocument(pane);
+
+ int pos = -1;
+ if (doc != null) {
+ // Obtain the offset where to jump
+ pos = Utilities.getRowStartFromLineOffset(doc, line);
+ }
+
+ if (pos != -1) {
+ Caret caret = pane.getCaret();
+ if (caret instanceof BaseCaret) { // support extended scroll mode
+ BaseCaret bCaret = (BaseCaret)caret;
+ bCaret.setDot(pos, bCaret, EditorUI.SCROLL_FIND);
+ }
+ else {
+ caret.setDot(pos);
+ }
+ }
+ }
+
+ public void clear() {
+ pane.setText("");
+ }
+
+ public void update() {
+ /* Remove ourselves as a DocumentListener while loading the source
+ so we don't get a storm of DocumentEvents during loading */
+ pane.getDocument().removeDocumentListener(this);
+
+ if (isModified == false)
+ {
+ pane.setText(model.getText());
+ }
+
+ // scroll to current position of the model
+ try {
+ scrollToLine(model.getCurrentPosition());
+ }
+ catch (Exception e) {
+ // couldn't scroll to line, do nothing
+ }
+
+ // Add back the listener
+ pane.getDocument().addDocumentListener(this);
+ }
+
+ public boolean isModified() {
+ return isModified;
+ }
+
+ public void setModified(boolean value) {
+ isModified = value;
+ }
+
+ public String getText() {
+ return pane.getText();
+ }
+
+ /* Implementation of DocumentListener interface */
+ public void insertUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ public void removeUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ public void changedUpdate(DocumentEvent e) {
+ doChanged(e);
+ }
+
+ public void doChanged(DocumentEvent e) {
+ isModified = true;
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/editor/OOo.jcb b/scripting/java/org/openoffice/netbeans/editor/OOo.jcb
new file mode 100644
index 000000000000..7286934fae65
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/editor/OOo.jcb
@@ -0,0 +1,5 @@
+LABELED_BYshortSPLIT_PANEshortHYPER_LINKshortPOPUP_MENUshortGLASS_PANEshortTABLE_CELLshortTEXT_FRAMEshortSTATUS_BARshortROW_HEADERshortSCROLL_BARshortSELECTABLEshortEXPANDABLEshortMULTI_LINEshortHORIZONTALshortLastColumnintSegmentEndintdeleteTextbooleaninsertTextbooleanADJUST_ABScom.sun.star.awt.AdjustmentTypegetDefaultcom.sun.star.awt.AdjustmentTypeRightInsetintFocusFlagsshortDECORATIVEshortNONE_valueintgetDefaultcom.sun.star.awt.FontSlantBOLDDOTTEDshortDOUBLEWAVEshortDASHDOTDOTshortNORMALfloatULTRALIGHTfloat ULTRAEXPANDEDfloatStartColorintRECT_valueintELLIPTICALcom.sun.star.awt.GradientStylegetDefaultcom.sun.star.awt.GradientStyleNOCHILDRENshortPROPERTIESshortPROPERTIESshortRADIOCHECKshortClickCountintUpdateRectcom.sun.star.awt.RectangleEXECUTE_UPshortHELP_valueintgetDefaultcom.sun.star.awt.PushButtonTypeZEROBITS com.sun.star.awt.RasterOperationgetDefault com.sun.star.awt.RasterOperationHORIZONTALintNOTALLOWEDintDEF_CANCELintgetDefaultcom.sun.star.awt.WindowClassRightInsetintgetMaskDIBbytecreatePeervoidgetContextjava.lang.Object setContextvoidgetControlcom.sun.star.awt.XControladdControlvoidendExecutevoidsetFiltersvoidselectFontvoidkeyPressedbooleankeyPressedvoidselectItemvoidinsertItemvoidgetItemPosshortremoveItemvoidenableItemvoiddeactivatevoidmouseMovedvoidselectFormvoidupdateTextvoidremoveTextvoidgetMaximumintsetMaximumvoidisEditablebooleaninsertTextvoidsetMenuBarvoidgetWindowscom.sun.star.awt.XWindowgetPosSizecom.sun.star.awt.RectanglesetPosSizevoidsetVisiblevoidinvalidatevoidsetPointervoidgetToolkitcom.sun.star.awt.XToolkitAttributesshortREADONLYshortREMOVEABLEshortATTRIBUTESintgetDefault com.sun.star.beans.PropertyStategetStringsjava.lang.String setStringsvoidgetMethods"com.sun.star.reflection.XIdlMethod.lib.uno.typeinfo.TypeInfoAUTO_valueintgetDefault,com.sun.star.chart.ChartAxisArrangeOrderTypeDATA_RANGE&com.sun.star.chart.ChartDataChangeTypegetDefault&com.sun.star.chart.ChartDataChangeTypeROWS_valueintgetDefault%com.sun.star.chart.ChartDataRowSourceNONE_valueintgetDefault%com.sun.star.chart.ChartErrorCategoryNONE_valueintgetDefault*com.sun.star.chart.ChartErrorIndicatorType
+NONE_valueintLEFT_valueintgetDefault&com.sun.star.chart.ChartLegendPositionNONE_valueintPOLYNOMIAL+com.sun.star.chart.ChartRegressionCurveTypegetDefault+com.sun.star.chart.ChartRegressionCurveTypegetDiagramcom.sun.star.chart.XDiagramsetDiagramvoidattachDatavoidgetDownBarcom.sun.star.beans.XPropertySet__waitTimeint_otherSide-com.sun.star.comp.connections.PipedConnectionm_lateInitjava.lang.Object initializevoidm_manifestjava.lang.String initializevoidEXTENSIBLEshortlistLayers)com.sun.star.configuration.backend.XLayer"startLayervoidreadSchemavoidstartGroupvoidremoveNodevoidmodifyNodevoidtar.container.XElementAccess UNOTYPEINFO&com.sun.star.lib.uno.typeinfo.TypeInfogetByIndexjava.lang.Object request_idintrequest_idintrequest_idintrequest_idintobject_keybytegetDefault,com.sun.star.corba.giop.LocateStatusType_1_2byte_orderbooleangetDefault#com.sun.star.corba.giop.MsgType_1_1request_idintgetDefault+com.sun.star.corba.giop.ReplyStatusType_1_2service_context%com.sun.star.corba.iop.ServiceContextobject_keybyterequest_idintreserved_2byterequest_idintreserved_3byteobject_keybytereserved_1byteservice_context%com.sun.star.corba.iop.ServiceContextreserved_2bytereserved_1byterequest_idintreserved_3byteobject_keybyteobject_keybytecomponents&com.sun.star.corba.iop.TaggedComponentobject_keybytecontext_idinttk_booleancom.sun.star.corba.TCKindtk_wstringcom.sun.star.corba.TCKindgetDefaultcom.sun.star.corba.TCKindPersistantbyteDragSource)com.sun.star.datatransfer.dnd.XDragSourceDragActionbyteUserActionbyteDropActionbyteDropActionbyteDragSource)com.sun.star.datatransfer.dnd.XDragSourceDropActionbyteDropActionbyteautoscrollvoidacceptDragvoidrejectDragvoidrejectDropvoidacceptDropvoidUSE_CONFIGshortLEFT_valueintgetDefaultcom.sun.star.drawing.AlignmentMORE_FRONT com.sun.star.drawing.ArrangementBACK_valueintgetDefault com.sun.star.drawing.ArrangementgetDefaultcom.sun.star.drawing.BitmapModehorizontalshortFULL_valueintgetDefaultcom.sun.star.drawing.CircleKindMONO_valueintgetDefaultcom.sun.star.drawing.ColorModeLEFT_valueintAUTO_valueintgetDefault#com.sun.star.drawing.ConnectionTypeLINE_valueintgetDefault"com.sun.star.drawing.ConnectorTypeRECT_valueintgetDefaultcom.sun.star.drawing.DashStyleDirectionYdoubleDirectionZdoubleDirectionXdoubleDRAW_valueintgetDefault!com.sun.star.drawing.DrawViewModeDOWN_valueintLEFT_valueintHORIZONTAL$com.sun.star.drawing.EscapeDirectiongetDefault$com.sun.star.drawing.EscapeDirectionHATCHcom.sun.star.drawing.FillStyleNONE_valueintgetDefaultcom.sun.star.drawing.FillStyleIsRelativebooleangetDefaultcom.sun.star.drawing.HatchStyleLEFT_valueintAUTO_valueintgetDefault+com.sun.star.drawing.HorizontalDimensioninggetDefaultcom.sun.star.drawing.LayerType ARROW_valueintNONE_valueintgetDefault com.sun.star.drawing.LineEndType MITER_valueintNONE_valueintgetDefaultcom.sun.star.drawing.LineJointNONE_valueintDASH_valueintgetDefaultcom.sun.star.drawing.LineStylegetDefault com.sun.star.drawing.MeasureKindAUTO_valueintgetDefault'com.sun.star.drawing.MeasureTextHorzPosBREAKEDLINE_valueintWEST_valueintEAST_valueintAUTO_valueintgetDefault'com.sun.star.drawing.MeasureTextVertPosHORIZONTALcom.sun.star.drawing.MirrorAxisgetDefaultcom.sun.star.drawing.MirrorAxisFLAT_valueintgetDefault com.sun.star.drawing.NormalsKindgetDefault!com.sun.star.drawing.PolygonFlagsLINE_valueintPOLY_valueintPLIN_valueintgetDefault com.sun.star.drawing.PolygonKindgetDefault#com.sun.star.drawing.ProjectionModeMIDDLE_TOP#com.sun.star.drawing.RectanglePointgetDefault#com.sun.star.drawing.RectanglePointFLAT_valueintgetDefaultcom.sun.star.drawing.ShadeModeHORIZONTAL#com.sun.star.drawing.SnapObjectTypegetDefault#com.sun.star.drawing.SnapObjectTypeBLOCKcom.sun.star.drawing.TextAdjustLEFT_valueintgetDefaultcom.sun.star.drawing.TextAdjustDOWN_valueintLEFT_valueintgetDefault+com.sun.star.drawing.TextAnimationDirectionSCROLL&com.sun.star.drawing.TextAnimationKindNONE_valueintgetDefault&com.sun.star.drawing.TextAnimationKindNONE_valueintRESIZEATTR&com.sun.star.drawing.TextFitToSizeTypegetDefault&com.sun.star.drawing.TextFitToSizeTypeLEFT_valueintgetDefault)com.sun.star.drawing.TextHorizontalAdjustgetDefault'com.sun.star.drawing.TextVerticalAdjustgetDefault com.sun.star.drawing.TextureKindgetDefault!com.sun.star.drawing.TextureKind2getDefault com.sun.star.drawing.TextureModegetDefault*com.sun.star.drawing.TextureProjectionModeAUTO_valueintgetDefault)com.sun.star.drawing.VerticalDimensioningcanConnectbooleanconnectEndvoidgetControlcom.sun.star.awt.XControlModelsetControlvoidsendToBackvoidenterGroupvoidleaveGroupvoidnNextStateintgetClassIDbyteisReadonlybooleansaveObjectvoidgetPosRectcom.sun.star.awt.RectangledoHandsOffvoidisHandsOffbooleangetDefault#com.sun.star.form.DataSelectionTypeParameters#com.sun.star.container.XIndexAccessPUSH_valueintgetDefault com.sun.star.form.FormButtonTypeTEXT_valueintgetDefault$com.sun.star.form.FormSubmitEncodingPOST_valueintgetDefault"com.sun.star.form.FormSubmitMethodgetDefault com.sun.star.form.ListSourceTypeNONE_valueintgetDefault#com.sun.star.form.NavigationBarModePAGE_valueintgetDefault com.sun.star.form.TabulatorCyclesetColumnsvoidgetColumns&com.sun.star.container.XIndexContainerpositionedvoidnCharacterintsSymbolSetjava.lang.String FeatureURLcom.sun.star.util.URLbIsCommentbooleanFeatureURLcom.sun.star.util.URLgetDefaultcom.sun.star.frame.FrameActionHORIZONTALshortinitializevoidgetContentcom.sun.star.ucb.XContentsetCreatorvoidgetCreator"com.sun.star.frame.XFramesSupplierdeactivatevoidinitializevoidisReadonlybooleanstoreToURLvoidstoreAsURLvoidCTL_ARABICshortCTL_HEBREWshortSHORT_YEARintLONG_MONTHintDST_OFFSETshortAbbrevNamejava.lang.String BankSymboljava.lang.String getDefault#com.sun.star.i18n.DirectionPropertyformatCodejava.lang.String formatNamejava.lang.String formatTypejava.lang.String TITLE_CASEintANY_LETTERintASC_DOLLARintUNI_LETTERintUNI_NUMBERintANY_NUMBERintUNI_NUMBERintANY_NUMBERintASC_NUMBERintbreakIndexintNUMBER_ENDshortNUMBER_INTshortFRACTION_1shortTIME_STARTshortDATE_STARTshortFRACTION_2shortStartFlagsintCandidatesjava.lang.String getDefault(com.sun.star.i18n.TransliterationModulesgetDefault+com.sun.star.i18n.TransliterationModulesNewONE_TO_ONEshortkLao_valueintkMongoliancom.sun.star.i18n.UnicodeScriptkMalayalamcom.sun.star.i18n.UnicodeScriptgetDefaultcom.sun.star.i18n.UnicodeScriptUNASSIGNEDshortWORD_COUNTshortnextScriptintgetDefault"com.sun.star.i18n.NumberFormatCodeloadModulevoidABOVE_WORDshortBELOW_WORDshortFALSE_WORDshortgetDefault$com.sun.star.installation.ProtDlgResaExceptionjava.lang.Object exportDatavoidimportDatavoidreadDoubledoublewriteHypervoidwriteFloatvoidwriteShortvoidcloseInputvoidjumpToMarkvoiddeleteMarkvoidcreateMarkintreadObjectcom.sun.star.io.XPersistObjectwriteBytesvoidterminatedvoidreadStringjava.lang.String SYSTEM_OS2shortSYSTEM_MACshortinitializevoid_listenersjava.util.Vector _firstReadbooleansetWeakRefvoidsetWeakRefvoidshowStatusvoidshowStatusvoidgetContentjava.lang.Object setWeakRefvoidgetContentjava.lang.Object checkWritevoidcheckWritevoidgetContextjava.lang.Object addWatchervoid_iProtocol2com.sun.star.lib.uno.environments.remote.IProtocol(_negotiateboolean_listenersjava.util.Vector getContextjava.lang.Object isSynchronbooleanwriteReplyvoidreadObjectjava.lang.Object _jobQueuesjava.util.Hashtable _iReceiver2com.sun.star.lib.uno.environments.remote.IReceiver(isSynchronboolean_disposeIdjava.lang.Object _doDisposejava.lang.Object _ref_countint_throwablejava.lang.Throwable getContextjava.lang.Object bInDisposebooleantrimToSizevoidgetRootOidjava.lang.String writeReplyvoid_superType-com.sun.star.lib.uno.typedesc.TypeDescription_typeClasscom.sun.star.uno.TypeClassisReadOnlybooleanCONSTintisUnsignedbooleanFROM_RIGHT,com.sun.star.linguistic2.ConversionDirectiongetDefault,com.sun.star.linguistic2.ConversionDirectiongetDefault'com.sun.star.linguistic2.DictionaryTypegetEntries)com.sun.star.linguistic2.XDictionaryEntrygetEntries)com.sun.star.linguistic2.XDictionaryEntryisNegativebooleangetMeaningjava.lang.String getLocalescom.sun.star.lang.LocaleBEST_SPEEDshortPluginNamejava.lang.String getDefault"com.sun.star.plugin.PluginVariableNONE_valueintPATH_valueintHIDE_valueintgetDefault)com.sun.star.presentation.AnimationEffectSLOW_valueintFAST_valueintgetDefault(com.sun.star.presentation.AnimationSpeedVERB_valueintNONE_valueintgetDefault%com.sun.star.presentation.ClickActionNONE_valueintgetDefault$com.sun.star.presentation.FadeEffectgetDefault+com.sun.star.presentation.PresentationRangegetDefault'com.sun.star.reflection.FieldAccessModegetDefault"com.sun.star.reflection.MethodModegetDefault!com.sun.star.reflection.ParamModegetDefault2com.sun.star.reflection.TypeDescriptionSearchDepthgetMethods"com.sun.star.reflection.XIdlMethodgetClasses!com.sun.star.reflection.XIdlClassisReadOnlybooleangetMembers7com.sun.star.reflection.XInterfaceMemberTypeDescriptiongetMembers(com.sun.star.reflection.XTypeDescriptiongetService/com.sun.star.reflection.XServiceTypeDescriptionLINK_valueintgetDefault%com.sun.star.registry.RegistryKeyTypeSTRINGLIST'com.sun.star.registry.RegistryValueTypeLONG_valueintgetDefault'com.sun.star.registry.RegistryValueTypegetKeyNamejava.lang.String createLinkbooleanisReadOnlybooleangetKeyType%com.sun.star.registry.RegistryKeyTypedeleteLinkvoidgetRootKey"com.sun.star.registry.XRegistryKeyisReadOnlybooleansetDefaultvoidgetDefaultcom.sun.star.lang.LocaleloadBundle%com.sun.star.resource.XResourceBundleScanFailedcom.sun.star.scanner.ScanErrorgetDefaultcom.sun.star.scanner.ScanErrorMethodNamejava.lang.String SourceCodejava.lang.String UNKNOWNintgetDefault com.sun.star.script.FinishReasonSourceCodejava.lang.String Step_valueintBreakPoint#com.sun.star.script.InterruptReasongetDefault#com.sun.star.script.InterruptReasongetDefaultcom.sun.star.script.MemberTypeScriptCodejava.lang.String ScriptTypejava.lang.String ScriptCodejava.lang.String ScriptTypejava.lang.String doContinuevoidisVariablebooleanisFunctionbooleanConnectioncom.sun.star.sdbc.XConnectionParameters#com.sun.star.container.XIndexAccessgetBooleanbooleanupdateNullvoidupdateTimevoidupdateDatevoidupdateBytevoidupdateLongvoidgetQueries"com.sun.star.container.XNameAccessNOT_PSEUDOintNOT_PSEUDOintDuringReadbooleanIsRequiredbooleanclearBatchvoidfindColumnintgetTypeMap"com.sun.star.container.XNameAccessgetCatalogjava.lang.String setCatalogvoidisReadOnlybooleansetTypeMapvoidgetSchemascom.sun.star.sdbc.XResultSetgetColumnscom.sun.star.sdbc.XResultSetisReadOnlybooleanacceptsURLbooleansetBooleanvoidclearBatchvoidrefreshRowvoidrowUpdatedbooleanrowDeletedbooleanisWritablebooleanisCurrencybooleanisNullableintisReadOnlybooleangetBooleanbooleanrowChangedvoidupdateBytevoidupdateNullvoidupdateDatevoidupdateTimevoidupdateLongvoidreadDoubledoublereadObjectjava.lang.Object readStringjava.lang.String writeBytesvoidwriteArrayvoidwriteShortvoidwriteFloatvoidgetColumns"com.sun.star.container.XNameAccessdeleteRowsintdropByNamevoidgetIndexes"com.sun.star.container.XNameAccessgetContext+com.sun.star.security.XAccessControlContextFONT_valueintDELETEFILEcom.sun.star.setup.ActionTypeMAKEFOLDERcom.sun.star.setup.ActionTypegetDefaultcom.sun.star.setup.ActionTypebOverwritebooleanstrDirnamejava.lang.String strPatternjava.lang.String nDriveSizeintstrCountryjava.lang.String eErrorCode$com.sun.star.setup.ResponseErrorCodeFULLDELETEcom.sun.star.setup.InstallTypegetDefaultcom.sun.star.setup.InstallTypestrDirnamejava.lang.String isSelectedbooleanUNIX_SOLSGcom.sun.star.setup.OSTypeUNIX_LINUXcom.sun.star.setup.OSTypeUNIX_SOLIGcom.sun.star.setup.OSTypegetDefaultcom.sun.star.setup.OSTypestrSectionjava.lang.String getDefault$com.sun.star.setup.ResponseErrorCodestrPatternjava.lang.String bOverwritebooleangetDefaultcom.sun.star.setup.UpdateTypebDeleteAllbooleanLEFT_valueintgetDefaultcom.sun.star.sheet.Border COLUMNS_valueintNONE_valueintLEFT_valueintROWS_valueintgetDefault!com.sun.star.sheet.CellDeleteModeANNOTATIONint
+DOWN_valueintNONE_valueintROWS_valueintgetDefault!com.sun.star.sheet.CellInsertModeNONE_valueintLESS_valueintLESS_EQUAL$com.sun.star.sheet.ConditionOperatorgetDefault$com.sun.star.sheet.ConditionOperatorNONE_valueintgetDefault!com.sun.star.sheet.DataImportMode
+DATA_valueintPAGE_valueintgetDefault,com.sun.star.sheet.DataPilotFieldOrientationgetDefaultcom.sun.star.sheet.FillDateModegetDefault com.sun.star.sheet.FillDirection SIMPLE_valueintDATE_valueintAUTO_valueintgetDefaultcom.sun.star.sheet.FillModegetDefault#com.sun.star.sheet.FilterConnectionTOP_VALUES!com.sun.star.sheet.FilterOperatorLESS_valueintLESS_EQUAL!com.sun.star.sheet.FilterOperatorgetDefault!com.sun.star.sheet.FilterOperatorIsOptionalbooleanVARP_valueintNONE_valueintAUTO_valueintgetDefault"com.sun.star.sheet.GeneralFunctionDivergencedoublePRINT_AREAintROW_HEADERint
+NONE_valueintgetDefault!com.sun.star.sheet.PasteOperationNONE_valueintgetDefault com.sun.star.sheet.SheetLinkModeConnection#com.sun.star.sheet.FilterConnectionBOTH_valueintgetDefault%com.sun.star.sheet.TableOperationModeSTOP_valueintINFO_valueintgetDefault'com.sun.star.sheet.ValidationAlertStyleDATE_valueintLIST_valueintTIME_valueintgetDefault!com.sun.star.sheet.ValidationTypefillSeriesvoidsetSourcesvoidgetSources#com.sun.star.table.CellRangeAddressgetResultscom.sun.star.sheet.MemberResultgetResultscom.sun.star.sheet.DataResultgetMembers"com.sun.star.container.XNameAccessgetContentjava.lang.String setContentvoidoutputListvoidshowErrorsbooleansetLinkUrlvoidgetLinkUrljava.lang.String hideDetailvoidshowDetailvoidmoveByNamevoidcopyByNamevoidPRINT_AREAintROW_HEADERintNONE_valueintPAGE_AFTERcom.sun.star.style.BreakTypegetDefaultcom.sun.star.style.BreakTypeMIDDLE_TOP"com.sun.star.style.GraphicLocationNONE_valueintAREA_valueintgetDefault"com.sun.star.style.GraphicLocationLEFT_valueintgetDefault&com.sun.star.style.HorizontalAlignmentCHARS_THAIshortLEFT_valueintgetDefault"com.sun.star.style.PageStyleLayoutBLOCK"com.sun.star.style.ParagraphAdjustLEFT_valueintgetDefault"com.sun.star.style.ParagraphAdjustDEFAULTcom.sun.star.style.TabAlignLEFT_valueintgetDefaultcom.sun.star.style.TabAligngetDefault$com.sun.star.style.VerticalAlignmentGenerationintSyncFilterjava.lang.String VFS_FOLDERintinitializebooleanPosixErrorintgetSubjectjava.lang.String setSubjectvoidTEXT_valueintgetDefault"com.sun.star.table.CellContentTypeLEFT_valueintgetDefault"com.sun.star.table.CellHoriJustifygetDefault"com.sun.star.table.CellOrientationgetDefault"com.sun.star.table.CellVertJustifyBOTTOM_RIGHT_valueintNONE_valueintgetDefault!com.sun.star.table.ShadowLocationBottomLinecom.sun.star.table.BorderLineROWS_valueintgetDefault#com.sun.star.table.TableOrientationgetDefault%com.sun.star.table.TableSortFieldTypeautoFormatvoidsetFormulavoidgetFormulajava.lang.String gotoOffsetvoidgetColumns com.sun.star.table.XTableColumnsINFO_valueintgetDefault+com.sun.star.task.InteractionClassificationgetDefault%com.sun.star.task.PasswordRequestModegetRequestjava.lang.Object LOLA_valueintTEST_valueintgetDefault!com.sun.star.test.bridge.TestEnumsetValues2)com.sun.star.test.bridge.TestDataElementscallOnewayvoidcomplex_in*com.sun.star.test.performance.ComplexTypestestPassedbooleanFIRST_NAMEshortIDENTIFIERshortTECHREPORTshortCONFERENCEshortHARD_SPACEshortLINE_BREAKshortDDMMMMYYYYshortDISK_ABOVEshortDISK_BELOWshortLEFT_valueintgetDefault"com.sun.star.text.HorizontalAdjustONLY_valueintgetDefaultcom.sun.star.text.NotePrintModePREV_valueintNEXT_valueintgetDefault com.sun.star.text.PageNumberTypePRINT_AREAshortFRAME_LEFTshortPAGE_RIGHTshortPAGE_FRAMEshortBLOCKcom.sun.star.text.RubyAdjustLEFT_valueintgetDefaultcom.sun.star.text.RubyAdjustFilterNamejava.lang.String LeftMarginint AT_PARAGRAPH'com.sun.star.text.TextContentAnchorTypegetDefault'com.sun.star.text.TextContentAnchorTypeHHMMSSAMPMshortCHAR_TOPshortNONE_valueintLEFT_valueintgetDefaultcom.sun.star.text.WrapTextModegetDefaultcom.sun.star.text.WritingModejumpToPagebooleanprintPagesvoidsetColumnsvoidgetColumnscom.sun.star.text.TextColumninitializevoidgetColumns com.sun.star.table.XTableColumnsmergeRangebooleansplitRangebooleansetVisiblevoidServerNamejava.lang.String HasAccountbooleanDiagnosticjava.lang.String getDefault%com.sun.star.ucb.ContentCreationErrorPropertiescom.sun.star.beans.PropertyAttributesintgetDefaultcom.sun.star.ucb.CookiePolicySEND_valueintgetDefaultcom.sun.star.ucb.CookieRequestgetDefault"com.sun.star.ucb.DocumentStoreModeNO_DOCINFOintFetchErrorshortStartIndexintgetDefault"com.sun.star.ucb.FolderListCommandSubscribedbooleanCANT_WRITEcom.sun.star.ucb.IOErrorCodegetDefaultcom.sun.star.ucb.IOErrorCodeDiagnosticjava.lang.String Diagnosticjava.lang.String ActionInfojava.lang.Object LockTokensjava.lang.String ZERO_valueintgetDefaultcom.sun.star.ucb.LockDepthgetDefaultcom.sun.star.ucb.LockScopegetDefaultcom.sun.star.ucb.LockTypePropertiesjava.lang.String Propertiescom.sun.star.beans.PropertygetDefault%com.sun.star.ucb.OutgoingMessageState LOWEST_valueintHIGH_valueintgetDefaultcom.sun.star.ucb.PriorityValueState#com.sun.star.ucb.PropertyValueStategetDefault#com.sun.star.ucb.PropertyValueStateNewsgroupsjava.lang.String PERSISTENT'com.sun.star.ucb.RememberAuthenticationgetDefault'com.sun.star.ucb.RememberAuthenticationgetDefault2com.sun.star.ucb.RemoteContentProviderChangeActionIdentifierjava.lang.String MARKUNREADshortVALUE_TRUEshortPropertiescom.sun.star.beans.PropertyDEEP_valueintNONE_valueintgetDefault com.sun.star.ucb.SearchRecursiongetDefault"com.sun.star.ucb.SynchronizePolicyMOVE_valueintLINK_valueintCOPY_valueintgetDefault)com.sun.star.ucb.TransferCommandOperationONCE_valueintgetDefault!com.sun.star.ucb.VerificationModemapContentcom.sun.star.ucb.XContentgetDataURLjava.lang.String setDataURLvoidsetAccountvoidisReadOnlybooleanGET_SELECTED_ITEM_INDEXshortgetDefault,com.sun.star.ui.ContextMenuInterceptorActiongetContextjava.lang.Object isUnsignedboolean_typeClasscom.sun.star.uno.TypeClassCHAR_valueintBYTE_valueintTYPE_valueintVOID_valueintLONG_valueintENUM_valueintgetDefaultcom.sun.star.uno.TypeClassgetMappingcom.sun.star.uno.IMappinggetBridgescom.sun.star.uno.IBridgeisLoggablebooleanisLoggablebooleanDONE_valueintgetDefault%com.sun.star.util.DataEditorEventTypeEndMinutesshortStartHoursshortEndSecondsshortStartMonthshortINCH_100THshortSCIENTIFICshortgetDefault"com.sun.star.util.SearchAlgorithms searchStringjava.lang.String searchFlagintgetDefaultcom.sun.star.util.SortFieldTypegetContent#com.sun.star.container.XIndexAccessgetClasses!com.sun.star.util.AtomDescriptionisModifiedbooleanreplaceAllintmapStringsbooleansetOptionsvoidparseSmartbooleanPAGE_WIDTHshortUSER_valueintgetDefaultcom.sun.star.view.PaperFormatgetDefault"com.sun.star.view.PaperOrientationJOB_FAILED com.sun.star.view.PrintableStategetDefault com.sun.star.view.PrintableStategetControlcom.sun.star.awt.XControlgetPrinter com.sun.star.beans.PropertyValuesetPrintervoidgetPrinter com.sun.star.beans.PropertyValuescreenDownbooleanendElementvoidcharactersvoidLineNumberintcharactersvoidendElementvoidfatalErrorvoidstartCDATAvoidgetDesktopcom.sun.star.frame.XDesktop \ No newline at end of file
diff --git a/scripting/java/org/openoffice/netbeans/editor/OOo.jcs b/scripting/java/org/openoffice/netbeans/editor/OOo.jcs
new file mode 100644
index 000000000000..c5cc334221ba
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/editor/OOo.jcs
@@ -0,0 +1,21 @@
+!com.sun.star.awt.XProgressMonitor† ¸44com.sun.star.awt.XRadioButton† ¹hKcom.sun.star.awt.XRegion† º³‚´com.sun.star.awt.XScrollBar† ½g‚‹com.sun.star.awt.XSpinField† ¿òQcom.sun.star.awt.XSpinListener† ÁC+$com.sun.star.awt.XSystemChildFactory† Ân€Æ+com.sun.star.awt.XSystemDependentWindowPeer† Ã4€¤com.sun.star.awt.XTabController† ÃØé$com.sun.star.awt.XTabControllerModel† ÅÁ‚.com.sun.star.awt.XTextArea† Çï€com.sun.star.awt.XTextComponent† È‚„com.sun.star.awt.XTextEditField† Ë€‹&com.sun.star.awt.XTextLayoutConstrains† ËŽ€Úcom.sun.star.awt.XTextListener† Ìh€¦com.sun.star.awt.XTimeField† ÍÀcom.sun.star.awt.XToolkit† Î΂Kcom.sun.star.awt.XTopWindow† ÑY#com.sun.star.awt.XTopWindowListener† Òr‚%com.sun.star.awt.XUnoControlContainer† Ôˆh'com.sun.star.awt.XUserInputInterception† Õðucom.sun.star.awt.XVclContainer† ×e5&com.sun.star.awt.XVclContainerListener† Øš€î"com.sun.star.awt.XVclContainerPeer† Ùˆcom.sun.star.awt.XVclWindowPeer† Ú¢‚5com.sun.star.awt.XView† Ü×<com.sun.star.awt.XWindow† Þ„S com.sun.star.awt.XWindowListener† âfUcom.sun.star.awt.XWindowPeer† ã»O'com.sun.star.beans.IllegalTypeException å
+i)com.sun.star.beans.IntrospectionException åsi com.sun.star.beans.MethodConcept† åÜ€˜com.sun.star.beans.NamedValue æt€³)com.sun.star.beans.NotRemoveableException ç'icom.sun.star.beans.Property ç€ð$com.sun.star.beans.PropertyAttribute† è€€ä&com.sun.star.beans.PropertyChangeEvent édN"com.sun.star.beans.PropertyConcept† ê²l)com.sun.star.beans.PropertyExistException ëi(com.sun.star.beans.PropertySetInfoChange† ë‡J-com.sun.star.beans.PropertySetInfoChangeEvent ëÑ€Ñ com.sun.star.beans.PropertyState ì¢s+com.sun.star.beans.PropertyStateChangeEvent îo com.sun.star.beans.PropertyValue ï„(com.sun.star.beans.PropertyVetoException ðœicom.sun.star.beans.StringPair ñ€µ+com.sun.star.beans.UnknownPropertyException ñºicom.sun.star.beans.XExactName† ò#€¤#com.sun.star.beans.XFastPropertySet† òÇß+com.sun.star.beans.XHierarchicalPropertySet† ô¦‚‹/com.sun.star.beans.XHierarchicalPropertySetInfo† ÷1.com.sun.star.beans.XIntroTest† ø_…•!com.sun.star.beans.XIntrospection† ýô€¶'com.sun.star.beans.XIntrospectionAccess† þªƒ "com.sun.star.beans.XMaterialHolder†¡Ê€0com.sun.star.beans.XMultiHierarchicalPropertySet†¡Y‚3$com.sun.star.beans.XMultiPropertySet†¡Œ‚Þ'com.sun.star.beans.XMultiPropertyStates†¡j‚,com.sun.star.beans.XPropertiesChangeListener†¡ q€·,com.sun.star.beans.XPropertiesChangeNotifier†¡
+(Fcom.sun.star.beans.XProperty†¡ n€œ"com.sun.star.beans.XPropertyAccess†¡
+”*com.sun.star.beans.XPropertyChangeListener†¡ ž€µ%com.sun.star.beans.XPropertyContainer†¡S»com.sun.star.beans.XPropertySet†¡…1#com.sun.star.beans.XPropertySetInfo†¡?G1com.sun.star.beans.XPropertySetInfoChangeListener†¡†€Ã1com.sun.star.beans.XPropertySetInfoChangeNotifier†¡I2!com.sun.star.beans.XPropertyState†¡{‚X/com.sun.star.beans.XPropertyStateChangeListener†¡Ó€¿%com.sun.star.beans.XPropertyWithState†¡’J*com.sun.star.beans.XVetoableChangeListener†¡Ü€ß)com.sun.star.bridge.BridgeExistsException¡»i2com.sun.star.bridge.InvalidProtocolChangeException¡$"com.sun.star.bridge.ModelDependent†¡;R$com.sun.star.bridge.ProtocolProperty¡€³com.sun.star.bridge.XBridge†¡ @€ê"com.sun.star.bridge.XBridgeFactory†¡!*á#com.sun.star.bridge.XBridgeSupplier†¡# $com.sun.star.bridge.XBridgeSupplier2†¡$ €ê%com.sun.star.bridge.XInstanceProvider†¡$ö€Ò'com.sun.star.bridge.XProtocolProperties†¡%È:#com.sun.star.bridge.XUnoUrlResolver†¡'),com.sun.star.chart.ChartAxisArrangeOrderType¡(+î"com.sun.star.chart.ChartAxisAssign†¡*=!com.sun.star.chart.ChartAxisMarks†¡*V@#com.sun.star.chart.ChartDataCaption†¡*–m'com.sun.star.chart.ChartDataChangeEvent¡+C&com.sun.star.chart.ChartDataChangeType¡,F‚tcom.sun.star.chart.ChartDataRow¡.º%com.sun.star.chart.ChartDataRowSource¡/É!com.sun.star.chart.ChartDataValue¡0ီ%com.sun.star.chart.ChartErrorCategory¡1‚h*com.sun.star.chart.ChartErrorIndicatorType¡3÷Ì&com.sun.star.chart.ChartLegendPosition¡5Ãã+com.sun.star.chart.ChartRegressionCurveType¡7¦‚t%com.sun.star.chart.ChartSeriesAddress¡::!com.sun.star.chart.ChartSolidType†¡;T_"com.sun.star.chart.ChartSymbolType†¡;³€Ãcom.sun.star.chart.X3DDisplay†¡<v€Ê!com.sun.star.chart.XAxisXSupplier†¡=@4!com.sun.star.chart.XAxisYSupplier†¡>t4!com.sun.star.chart.XAxisZSupplier†¡?¨4com.sun.star.chart.XChartData†¡@Üp"com.sun.star.chart.XChartDataArray†¡BLc0com.sun.star.chart.XChartDataChangeEventListener†¡C¯€¸!com.sun.star.chart.XChartDocument†¡Dgécom.sun.star.chart.XDiagram†¡FP{$com.sun.star.chart.XStatisticDisplay†¡GË$com.sun.star.chart.XTwoAxisXSupplier†¡HÍ€ª$com.sun.star.chart.XTwoAxisYSupplier†¡Iw€ª-com.sun.star.comp.bridgefactory.BridgeFactory¡J!ƒ3&com.sun.star.comp.connections.Acceptor¡MT‚o'com.sun.star.comp.connections.Connector¡OÂ%6com.sun.star.comp.connections.ConstantInstanceProvider¡Qè‚¿-com.sun.star.comp.connections.PipedConnection¡T§ƒ®"com.sun.star.comp.helper.Bootstrap¡XUä)com.sun.star.comp.helper.ComponentContext¡Z9«.com.sun.star.comp.helper.ComponentContextEntry¡[䀘/com.sun.star.comp.helper.RegistryServiceFactory¡\|‚9,com.sun.star.comp.helper.SharedLibraryLoader¡^µƒ .com.sun.star.comp.loader.FactoryHelper.Factory ¡a¾…‡&com.sun.star.comp.loader.FactoryHelper¡gE‚´#com.sun.star.comp.loader.JavaLoader¡iù„ï*com.sun.star.comp.loader.JavaLoaderFactory¡nè‚°0com.sun.star.comp.loader.RegistrationClassFinder¡q˜‚ /com.sun.star.comp.servicemanager.ServiceManager ¡s¡‰°?com.sun.star.comp.typedescriptionmanager.TypeDescriptionManager(¡}Q96com.sun.star.comp.urlresolver.UrlResolver._UrlResolver ¡~ŠJ)com.sun.star.comp.urlresolver.UrlResolver¡Ô@com.sun.star.configuration.backend.AuthenticationFailedException"¡€ä€›9com.sun.star.configuration.backend.BackendAccessException"¡€‹8com.sun.star.configuration.backend.BackendSetupException"¡‚
+€û9com.sun.star.configuration.backend.CannotConnectException"¡ƒ€›:com.sun.star.configuration.backend.ConnectionLostException"¡ƒ €œDcom.sun.star.configuration.backend.InsufficientAccessRightsException"¡„<€œJcom.sun.star.configuration.backend.InvalidAuthenticationMechanismException"¡„Ø€›9com.sun.star.configuration.backend.MalformedDataException"¡…s€Ö0com.sun.star.configuration.backend.NodeAttribute"†¡†Ia2com.sun.star.configuration.backend.SchemaAttribute"†¡†ªb5com.sun.star.configuration.backend.TemplateIdentifier"¡‡ €·+com.sun.star.configuration.backend.XBackend"†¡‡ÃƒÝ3com.sun.star.configuration.backend.XBackendEntities"†¡‹ Ò2com.sun.star.configuration.backend.XCompositeLayer"†¡ré)com.sun.star.configuration.backend.XLayer"†¡[A0com.sun.star.configuration.backend.XLayerHandler"†¡œˆ„1com.sun.star.configuration.backend.XLayerImporter"†¡™ ƒ<5com.sun.star.configuration.backend.XMultiLayerStratum"†¡œ\…O*com.sun.star.configuration.backend.XSchema"†¡¡«‚ü1com.sun.star.configuration.backend.XSchemaHandler"†¡¤§Š2com.sun.star.configuration.backend.XSchemaSupplier"†¡®¿+6com.sun.star.configuration.backend.XSingleLayerStratum"†¡¯ê‚!2com.sun.star.configuration.backend.XUpdatableLayer"†¡² K1com.sun.star.configuration.backend.XUpdateHandler"†¡³V‹=;com.sun.star.configuration.CannotLoadConfigurationException¡¾“i:com.sun.star.configuration.InstallationIncompleteException¡¾ü€Š8com.sun.star.configuration.InvalidBootstrapFileException¡¿†€û8com.sun.star.configuration.MissingBootstrapFileException¡À€û-com.sun.star.configuration.XTemplateContainer†¡Á|€š,com.sun.star.configuration.XTemplateInstance†¡Â€“1com.sun.star.connection.AlreadyAcceptingException¡Â©i0com.sun.star.connection.ConnectionSetupException¡Ãi*com.sun.star.connection.NoConnectException¡Ã{i(com.sun.star.connection.SocketPermission¡Ã䀵!com.sun.star.connection.XAcceptor†¡Ä™\#com.sun.star.connection.XConnection†¡Åõc$com.sun.star.connection.XConnection2†¡ÇX€ê.com.sun.star.connection.XConnectionBroadcaster†¡ÈB€ð"com.sun.star.connection.XConnector†¡É2%com.sun.star.container.ContainerEvent¡ÊB,com.sun.star.container.ElementExistException¡ËUi-com.sun.star.container.NoSuchElementException¡Ë¾icom.sun.star.container.XChild†¡Ì'€Ý,com.sun.star.container.XComponentEnumeration†¡Í€Ô2com.sun.star.container.XComponentEnumerationAccess†¡ÍØ€È!com.sun.star.container.XContainer†¡Î 
+)com.sun.star.container.XContainerListener†¡Ïª>&com.sun.star.container.XContainerQuery†¡Ðè90com.sun.star.container.XContentEnumerationAccess†¡Ò!€ô%com.sun.star.container.XElementAccess†¡Ó€²#com.sun.star.container.XEnumeration†¡ÓÇ)com.sun.star.container.XEnumerationAccess†¡Ô΀²(com.sun.star.container.XHierarchicalName†¡Õ€-.com.sun.star.container.XHierarchicalNameAccess†¡Ö­1com.sun.star.container.XHierarchicalNameContainer†¡×Ââ/com.sun.star.container.XHierarchicalNameReplace†¡Ù¤Q(com.sun.star.container.XIdentifierAccess†¡Úõ+com.sun.star.container.XIdentifierContainer†¡Ü t)com.sun.star.container.XIdentifierReplace†¡Ý€7(com.sun.star.container.XImplicitIDAccess†¡Þ·+com.sun.star.container.XImplicitIDContainer†¡ß¾)com.sun.star.container.XImplicitIDReplace†¡à×€à#com.sun.star.container.XIndexAccess†¡á·
+&com.sun.star.container.XIndexContainer†¡âÁ¤$com.sun.star.container.XIndexReplace†¡äe,"com.sun.star.container.XNameAccess†¡å‘Y%com.sun.star.container.XNameContainer†¡æê¾#com.sun.star.container.XNameReplace†¡è¨9com.sun.star.container.XNamed†¡éဳcom.sun.star.container.XSet†¡ê”£&com.sun.star.container.XUniqueIDAccess†¡ì74+com.sun.star.corba.giop.CancelRequestHeader¡íkp*com.sun.star.corba.giop.FragmentHeader_1_2¡íÛp)com.sun.star.corba.giop.IORAddressingInfo¡îK€½-com.sun.star.corba.giop.LocateReplyHeader_1_2¡ï€ß/com.sun.star.corba.giop.LocateRequestHeader_1_0¡ï瀬,com.sun.star.corba.giop.LocateStatusType_1_2¡ð“‚ð)com.sun.star.corba.giop.MessageHeader_1_0¡óƒj)com.sun.star.corba.giop.MessageHeader_1_1¡ôí_#com.sun.star.corba.giop.MsgType_1_1¡öL‚ò'com.sun.star.corba.giop.ReplyHeader_1_2¡ù>…+com.sun.star.corba.giop.ReplyStatusType_1_2¡úÂâ)com.sun.star.corba.giop.RequestHeader_1_0¡ý¥‚)com.sun.star.corba.giop.RequestHeader_1_1¡ÿÄ‚s)com.sun.star.corba.giop.RequestHeader_1_2¢7‚80com.sun.star.corba.giop.SystemExceptionReplyBody¢o€ë%com.sun.star.corba.giop.TargetAddress¢Z€*com.sun.star.corba.giop.TargetAddressGroup†¢ÚWcom.sun.star.corba.giop.Version¢1€„/com.sun.star.corba.iiop.BiDirIIOPServiceContext¢µ€õ#com.sun.star.corba.iiop.ListenPoint¢ª€º'com.sun.star.corba.iiop.ProfileBody_1_0¢ dJ'com.sun.star.corba.iiop.ProfileBody_1_1¢
+®ìcom.sun.star.corba.iiop.Version¢ š€„com.sun.star.corba.iop.IOR¢ =%com.sun.star.corba.iop.ProfileIdGroup†¢[€‡%com.sun.star.corba.iop.ServiceContext¢‰%com.sun.star.corba.iop.ServiceIdGroup†¢’I&com.sun.star.corba.iop.TaggedComponent¢Û€­$com.sun.star.corba.iop.TaggedProfile¢ˆ€©com.sun.star.corba.CorbaString8¢1€‰com.sun.star.corba.CorbaUnion¢ºk"com.sun.star.corba.LogicalThreadID¢%€Òcom.sun.star.corba.ObjectKey¢÷€ïcom.sun.star.corba.OneThreadID¢怦com.sun.star.corba.TCKind¢ŒˆÊ2com.sun.star.datatransfer.clipboard.ClipboardEvent#¢V€×9com.sun.star.datatransfer.clipboard.RenderingCapabilities#†¢-<.com.sun.star.datatransfer.clipboard.XClipboard#†¢i@0com.sun.star.datatransfer.clipboard.XClipboardEx#†¢ ©€£5com.sun.star.datatransfer.clipboard.XClipboardFactory#†¢!L€ñ6com.sun.star.datatransfer.clipboard.XClipboardListener#†¢"=€Â5com.sun.star.datatransfer.clipboard.XClipboardManager#†¢"ÿñ6com.sun.star.datatransfer.clipboard.XClipboardNotifier#†¢$ð$3com.sun.star.datatransfer.clipboard.XClipboardOwner#†¢&€â7com.sun.star.datatransfer.clipboard.XFlushableClipboard#†¢&ö€†*com.sun.star.datatransfer.dnd.DNDConstants†¢'|€º.com.sun.star.datatransfer.dnd.DragGestureEvent¢(6^1com.sun.star.datatransfer.dnd.DragSourceDragEvent¢)” 1com.sun.star.datatransfer.dnd.DragSourceDropEvent¢*´'-com.sun.star.datatransfer.dnd.DragSourceEvent¢+ÛX6com.sun.star.datatransfer.dnd.DropTargetDragEnterEvent¢-3™1com.sun.star.datatransfer.dnd.DropTargetDragEvent¢.Ìu1com.sun.star.datatransfer.dnd.DropTargetDropEvent¢0AÙ-com.sun.star.datatransfer.dnd.DropTargetEvent¢2€Ž:com.sun.star.datatransfer.dnd.InvalidDNDOperationException¢2¨p)com.sun.star.datatransfer.dnd.XAutoscroll†¢3€¼2com.sun.star.datatransfer.dnd.XDragGestureListener†¢3Ô€Ä4com.sun.star.datatransfer.dnd.XDragGestureRecognizer†¢4˜<)com.sun.star.datatransfer.dnd.XDragSource†¢5Ô0com.sun.star.datatransfer.dnd.XDragSourceContext†¢7q€è1com.sun.star.datatransfer.dnd.XDragSourceListener†¢8Yë)com.sun.star.datatransfer.dnd.XDropTarget†¢:D™4com.sun.star.datatransfer.dnd.XDropTargetDragContext†¢;Ý€¡4com.sun.star.datatransfer.dnd.XDropTargetDropContext†¢<~€Å1com.sun.star.datatransfer.dnd.XDropTargetListener†¢=Cé$com.sun.star.datatransfer.DataFlavor¢?,4com.sun.star.datatransfer.UnsupportedFlavorException¢@.i/com.sun.star.datatransfer.XDataFormatTranslator†¢@—+*com.sun.star.datatransfer.XMimeContentType†¢A¤1com.sun.star.datatransfer.XMimeContentTypeFactory†¢Cf€ó-com.sun.star.datatransfer.XSystemTransferable†¢DY€“-com.sun.star.datatransfer.XTransferDataAccess†¢Dì€õ'com.sun.star.datatransfer.XTransferable†¢Eáž)com.sun.star.datatransfer.XTransferableEx†¢G€Ø-com.sun.star.datatransfer.XTransferableSource†¢HW€œ+com.sun.star.document.AmbigousFilterRequest¢Hó=*com.sun.star.document.BrokenPackageRequest¢J0€Ï!com.sun.star.document.EventObject¢Jÿ€ª*com.sun.star.document.FilterOptionsRequest¢K©t%com.sun.star.document.LinkUpdateModes†¢MX#com.sun.star.document.MacroExecMode†¢Mu€å)com.sun.star.document.NoSuchFilterRequest¢NZ€Í.com.sun.star.document.PrinterIndependentLayout†¢O'o(com.sun.star.document.RedlineDisplayType†¢O–j#com.sun.star.document.UpdateDocMode†¢P'com.sun.star.drawing.MeasureTextHorzPos¢”6Ä'com.sun.star.drawing.MeasureTextVertPos¢•úücom.sun.star.drawing.MirrorAxis¢—ö com.sun.star.drawing.NormalsKind¢™G,com.sun.star.drawing.PolyPolygonBezierCoords¢šKS'com.sun.star.drawing.PolyPolygonShape3D¢›ž!com.sun.star.drawing.PolygonFlags¢œ´– com.sun.star.drawing.PolygonKind¢žJ‚Ùcom.sun.star.drawing.Position3D¢¡#€³#com.sun.star.drawing.ProjectionMode¢¡Ö #com.sun.star.drawing.RectanglePoint¢¢öƒHcom.sun.star.drawing.ShadeMode¢¦>t#com.sun.star.drawing.SnapObjectType¢§²`com.sun.star.drawing.TextAdjust¢©¼+com.sun.star.drawing.TextAnimationDirection¢ªÎ¸&com.sun.star.drawing.TextAnimationKind¢¬†ñ&com.sun.star.drawing.TextFitToSizeType¢®wÀ)com.sun.star.drawing.TextHorizontalAdjust¢°7¶'com.sun.star.drawing.TextVerticalAdjust¢±íª com.sun.star.drawing.TextureKind¢³—
+!com.sun.star.drawing.TextureKind2¢´¡V com.sun.star.drawing.TextureMode¢µ÷K*com.sun.star.drawing.TextureProjectionMode¢·B)com.sun.star.drawing.VerticalDimensioning¢¸Ï¸&com.sun.star.drawing.XConnectableShape†¢º‡€ö$com.sun.star.drawing.XConnectorShape†¢»}Ç"com.sun.star.drawing.XControlShape†¢½D€Õcom.sun.star.drawing.XDrawPage†¢¾l(com.sun.star.drawing.XDrawPageDuplicator†¢¾…€½&com.sun.star.drawing.XDrawPageExpander†¢¿B€»(com.sun.star.drawing.XDrawPageSummarizer†¢¿ý€¾&com.sun.star.drawing.XDrawPageSupplier†¢À»€com.sun.star.drawing.XDrawPages†¢ÁX€æ'com.sun.star.drawing.XDrawPagesSupplier†¢Â>€Ÿcom.sun.star.drawing.XDrawView†¢ÂÝ€Ý(com.sun.star.drawing.XGluePointsSupplier†¢Ãº€§com.sun.star.drawing.XLayer†¢Äao"com.sun.star.drawing.XLayerManager†¢Äп#com.sun.star.drawing.XLayerSupplier†¢Æ€¥&com.sun.star.drawing.XMasterPageTarget†¢Ç4€Û)com.sun.star.drawing.XMasterPagesSupplier†¢È€¡com.sun.star.drawing.XShape†¢È°M"com.sun.star.drawing.XShapeAligner†¢Éý€Å#com.sun.star.drawing.XShapeArranger†¢Ê‚0!com.sun.star.drawing.XShapeBinder†¢Ìò€å#com.sun.star.drawing.XShapeCombiner†¢Í×€ç%com.sun.star.drawing.XShapeDescriptor†¢Î¾€ com.sun.star.drawing.XShapeGroup†¢ÏN€™"com.sun.star.drawing.XShapeGrouper†¢Ïç€ñ!com.sun.star.drawing.XShapeMirror†¢ÐØcom.sun.star.drawing.XShapes†¢Ññ€Ô.com.sun.star.drawing.XUniversalShapeDescriptor†¢ÒÅ€¢com.sun.star.embed.Aspects†¢Óg€¶com.sun.star.embed.BorderWidths¢Ô€¨com.sun.star.embed.ElementModes†¢ÔÅ€Äcom.sun.star.embed.EmbedMisc†¢Õ‰‚÷com.sun.star.embed.EmbedStates†¢Ø€€Œ#com.sun.star.embed.EmbedUpdateModes†¢Ù Qcom.sun.star.embed.EmbedVerbs†¢Ù]€Ú!com.sun.star.embed.EntryInitModes†¢Ú7€¤*com.sun.star.embed.InvalidStorageException¢ÚÛi%com.sun.star.embed.StorageWTException¢ÛD€‹,com.sun.star.embed.UnreachableStateException¢ÛÏ€Ó&com.sun.star.embed.WrongStateException¢Ü¢i$com.sun.star.embed.XClassifiedObject†¢Ý %com.sun.star.embed.XComponentSupplier†¢Þ €œ&com.sun.star.embed.XEmbedObjectFactory†¢Þ©ƒã com.sun.star.embed.XEmbedPersist†¢âŒ…¹"com.sun.star.embed.XEmbeddedClient†¢èE€Â"com.sun.star.embed.XEmbeddedObject†¢é„1-com.sun.star.embed.XEncryptionProtectedSource†¢í8€)com.sun.star.embed.XIPMainContainerWindow†¢íÈ+!com.sun.star.embed.XInplaceClient†¢îó„U!com.sun.star.embed.XInplaceObject†¢óH‚„#com.sun.star.embed.XInplaceUIWindow†¢õÌ‚"com.sun.star.embed.XLinkageSupport†¢÷Í%com.sun.star.embed.XPersistanceHolder†¢øÛ€àcom.sun.star.embed.XStorage†¢ù»ŒE$com.sun.star.embed.XTransactedObject†£'com.sun.star.embed.XTransactionListener†£)‚(com.sun.star.embed.XTransferableSupplier†£ «€ª com.sun.star.embed.XVisualObject†£
+U‚7"com.sun.star.embed.XWindowSupplier†£ Œ€•#com.sun.star.form.DataSelectionType£ ! %com.sun.star.form.DatabaseDeleteEvent£Á€Õ(com.sun.star.form.DatabaseParameterEvent£–€Ñcom.sun.star.form.ErrorEvent£g€§ com.sun.star.form.FormButtonType£|#com.sun.star.form.FormComponentType†£Š©$com.sun.star.form.FormSubmitEncoding£3W"com.sun.star.form.FormSubmitMethod£Š com.sun.star.form.ListSourceType£Ž‚ #com.sun.star.form.NavigationBarMode£®T com.sun.star.form.TabulatorCycle£G+com.sun.star.form.XApproveActionBroadcaster†£I(com.sun.star.form.XApproveActionListener†£Y€®!com.sun.star.form.XBoundComponent†£€Šcom.sun.star.form.XBoundControl†£‘€¡$com.sun.star.form.XChangeBroadcaster†£2€ô!com.sun.star.form.XChangeListener†£&€¥+com.sun.star.form.XConfirmDeleteBroadcaster†£Ë(com.sun.star.form.XConfirmDeleteListener†£ Û€°/com.sun.star.form.XDatabaseParameterBroadcaster†£!‹,com.sun.star.form.XDatabaseParameterListener†£"›€¼!com.sun.star.form.XDeleteListener†£#W€ã#com.sun.star.form.XErrorBroadcaster†£$:€ð com.sun.star.form.XErrorListener†£%*€©com.sun.star.form.XForm†£%Óp com.sun.star.form.XFormComponent†£&Cm!com.sun.star.form.XFormController†£&°?)com.sun.star.form.XFormControllerListener†£'ï€è com.sun.star.form.XFormsSupplier†£(×€¡com.sun.star.form.XGrid†£)x€¿$com.sun.star.form.XGridColumnFactory†£*7(com.sun.star.form.XGridFieldDataSupplier†£+=€ícom.sun.star.form.XGridPeer†£,*€å(com.sun.star.form.XImageProducerSupplier†£-€£!com.sun.star.form.XInsertListener†£-²€Ýcom.sun.star.form.XLoadListener†£.~com.sun.star.form.XLoadable†£0 ;&com.sun.star.form.XPositioningListener†£1H€¨com.sun.star.form.XReset†£1ð com.sun.star.form.XResetListener†£2ò€ã"com.sun.star.form.XRestoreListener†£3Õ€¦com.sun.star.form.XSubmit†£4{C!com.sun.star.form.XSubmitListener†£5¾€®$com.sun.star.form.XUpdateBroadcaster†£6l€ô!com.sun.star.form.XUpdateListener†£7`€ã%com.sun.star.formula.SymbolDescriptor£8CÂ%com.sun.star.frame.DispatchDescriptor£:€â&com.sun.star.frame.DispatchResultEvent£:ç€À&com.sun.star.frame.DispatchResultState†£;§N$com.sun.star.frame.DispatchStatement£;õw0com.sun.star.frame.DoubleInitializationException£=li$com.sun.star.frame.FeatureStateEvent£=Õ_com.sun.star.frame.FrameAction£?4ƒ8#com.sun.star.frame.FrameActionEvent£Bl"com.sun.star.frame.FrameSearchFlag†£Cp€š-com.sun.star.frame.IllegalArgumentIOException£D
+j+com.sun.star.frame.TerminationVetoException£Dti com.sun.star.frame.WindowArrange†£DÝ€†)com.sun.star.frame.XBrowseHistoryRegistry†£Ec#com.sun.star.frame.XComponentLoader†£Fd@%com.sun.star.frame.XComponentRegistry†£G¤€¼!com.sun.star.frame.XConfigManager†£H`com.sun.star.frame.XController†£Ið£com.sun.star.frame.XDesktop†£K“Ãcom.sun.star.frame.XDesktopTask†£MV€´com.sun.star.frame.XDispatch†£N
+z"com.sun.star.frame.XDispatchHelper†£O„$com.sun.star.frame.XDispatchProvider†£P’.0com.sun.star.frame.XDispatchProviderInterception†£QÀ0/com.sun.star.frame.XDispatchProviderInterceptor†£Rðš$com.sun.star.frame.XDispatchRecorder†£TŠž,com.sun.star.frame.XDispatchRecorderSupplier†£V(n*com.sun.star.frame.XDispatchResultListener†£W–€·%com.sun.star.frame.XDocumentTemplates†£XM‚¤+com.sun.star.frame.XExtendedFilterDetection†£Zñ€Â com.sun.star.frame.XFilterDetect†£[³€Úcom.sun.star.frame.XFrame†£\ƒ¦'com.sun.star.frame.XFrameActionListener†£`3€¯com.sun.star.frame.XFrameLoader†£`â $com.sun.star.frame.XFrameLoaderQuery†£aïH!com.sun.star.frame.XFrameSetModel†£c7€·com.sun.star.frame.XFrames†£cî"com.sun.star.frame.XFramesSupplier†£dõ€ý#com.sun.star.frame.XInterceptorInfo†£eò€–%com.sun.star.frame.XLoadEventListener†£fˆ€écom.sun.star.frame.XLoadable†£gqŠcom.sun.star.frame.XModel†£hû‚Ë%com.sun.star.frame.XNotifyingDispatch†£kÆ€ü&com.sun.star.frame.XRecordableDispatch†£l€î"com.sun.star.frame.XStatusListener†£m°€²com.sun.star.frame.XStorable†£nbË'com.sun.star.frame.XSynchronousDispatch†£p-€Ø*com.sun.star.frame.XSynchronousFrameLoader†£q€Ócom.sun.star.frame.XTask†£qØ€Þ!com.sun.star.frame.XTasksSupplier†£r¶€Ó%com.sun.star.frame.XTerminateListener†£s‰com.sun.star.frame.XUrlList†£t£€³"com.sun.star.frame.XWindowArranger†£uV€²com.sun.star.i18n.AmPmValue†£v1com.sun.star.i18n.Boundary£v9€„com.sun.star.i18n.BreakType†£v½acom.sun.star.i18n.CTLScriptType†£w~com.sun.star.i18n.Calendar£wœ‚‰%com.sun.star.i18n.CalendarDisplayCode†£z%g&com.sun.star.i18n.CalendarDisplayIndex†£{Œb$com.sun.star.i18n.CalendarFieldIndex†£{îNcom.sun.star.i18n.CalendarItem£}<€ècom.sun.star.i18n.CharType†£~$ƒ3'com.sun.star.i18n.CharacterIteratorMode†£Wa!com.sun.star.i18n.CollatorOptions†£¸€Šcom.sun.star.i18n.Currency£‚B‡#com.sun.star.i18n.DirectionProperty£ƒÉ‡‚%com.sun.star.i18n.ForbiddenCharacters£‹K€ºcom.sun.star.i18n.FormatElement£Œš com.sun.star.i18n.Implementation£Ÿ€¦(com.sun.star.i18n.InputSequenceCheckMode†£ŽEN com.sun.star.i18n.KCharacterType†£Ž“€¥#com.sun.star.i18n.KNumberFormatType†£8G$com.sun.star.i18n.KNumberFormatUsage†£€Âcom.sun.star.i18n.KParseTokens†£A‚Ócom.sun.star.i18n.KParseType†£“€Ö%com.sun.star.i18n.LanguageCountryInfo£“êc-com.sun.star.i18n.LineBreakHyphenationOptions£•Mp"com.sun.star.i18n.LineBreakResults£–½€ö&com.sun.star.i18n.LineBreakUserOptions£—³e com.sun.star.i18n.LocaleDataItem£™„`com.sun.star.i18n.LocaleItem†£x‚com.sun.star.i18n.Months†£Ÿ—€å.com.sun.star.i18n.MultipleCharsOutputException£ |i"com.sun.star.i18n.NativeNumberMode†£ å€ñ+com.sun.star.i18n.NativeNumberXmlAttributes£¡Ö€õ"com.sun.star.i18n.NumberFormatCode£¢ËR#com.sun.star.i18n.NumberFormatIndex†£¤†¶com.sun.star.i18n.ParseResult£ªÓI!com.sun.star.i18n.ScriptDirection†£¬Ycom.sun.star.i18n.ScriptType†£¬uX&com.sun.star.i18n.TextConversionOption†£¬Íg&com.sun.star.i18n.TextConversionResult£­4€ü$com.sun.star.i18n.TextConversionType†£®0j(com.sun.star.i18n.TransliterationModules£®šŽù+com.sun.star.i18n.TransliterationModulesNew£½“š½%com.sun.star.i18n.TransliterationType†£ØP€com.sun.star.i18n.UnicodeScript£ØÝ›ãcom.sun.star.i18n.UnicodeType†£ôÀƒ5com.sun.star.i18n.Weekdays†£÷õ€–com.sun.star.i18n.WordType†£ø‹} com.sun.star.i18n.XBreakIterator†£ù‡žcom.sun.star.i18n.XCalendar†¤€ê&com.sun.star.lang.NoSuchFieldException¤Vôi'com.sun.star.lang.NoSuchMethodException¤W]i$com.sun.star.lang.NoSupportException¤WÆi&com.sun.star.lang.NullPointerException¤X/i/com.sun.star.lang.ServiceNotRegisteredException¤X˜i!com.sun.star.lang.SystemDependent†¤Y€ž(com.sun.star.lang.WrappedTargetException¤YŸ€Ù/com.sun.star.lang.WrappedTargetRuntimeException¤Zx€àcom.sun.star.lang.XComponent†¤[X"com.sun.star.lang.XConnectionPoint†¤\\¶+com.sun.star.lang.XConnectionPointContainer†¤^z com.sun.star.lang.XEventListener†¤_Œ€¢!com.sun.star.lang.XInitialization†¤`.€²com.sun.star.lang.XLocalizable†¤`à€Çcom.sun.star.lang.XMain†¤a§€Ž(com.sun.star.lang.XMultiComponentFactory†¤b5Ì&com.sun.star.lang.XMultiServiceFactory†¤dk%com.sun.star.lang.XServiceDisplayName†¤el€µcom.sun.star.lang.XServiceInfo†¤f!€ýcom.sun.star.lang.XServiceName†¤g€’)com.sun.star.lang.XSingleComponentFactory†¤g°s'com.sun.star.lang.XSingleServiceFactory†¤i#com.sun.star.lang.XTypeProvider†¤j5€±com.sun.star.lang.XUnoTunnel†¤j怌)com.sun.star.ldap.LdapConnectionException¤kri&com.sun.star.ldap.LdapGenericException¤kÛ€¹0com.sun.star.lib.connections.pipe.PipeConnection!¤l”ƒˆ.com.sun.star.lib.connections.pipe.pipeAcceptor!¤p‚E/com.sun.star.lib.connections.pipe.pipeConnector!¤raû4com.sun.star.lib.connections.socket.SocketConnection#¤t\ƒê2com.sun.star.lib.connections.socket.socketAcceptor#¤xF‚E3com.sun.star.lib.connections.socket.socketConnector#¤z‹û!com.sun.star.lib.sandbox.Cachable†¤|†x%com.sun.star.lib.sandbox.ClassContext†¤|þ‚ *com.sun.star.lib.sandbox.ClassContextProxy¤ ƒß#com.sun.star.lib.sandbox.CodeSource¤‚èY#com.sun.star.lib.sandbox.Disposable†¤ƒA+)com.sun.star.lib.sandbox.ExecutionContext„¤ƒl…com.sun.star.lib.sandbox.Holder†¤ˆ†l!com.sun.star.lib.sandbox.JarEntry¤ˆò€µ-com.sun.star.lib.sandbox.PermissionCollection¤‰§€Ô)com.sun.star.lib.sandbox.ProtectionDomain¤Š{€¶!com.sun.star.lib.sandbox.Resource†¤‹1°&com.sun.star.lib.sandbox.ResourceProxy¤ŒáƒM'com.sun.star.lib.sandbox.ResourceViewer¤.€‘(com.sun.star.lib.sandbox.SandboxSecurity¤¿†Ë1com.sun.star.lib.sandbox.SandboxSecurityException¤—Š€Ñ+com.sun.star.lib.sandbox.SandboxThreadGroup¤˜[€Ö com.sun.star.lib.sandbox.WeakRef¤™1€"com.sun.star.lib.sandbox.WeakTable¤™Îtcom.sun.star.lib.sandbox.XImage†¤›B„²=com.sun.star.lib.uno.adapter.XInputStreamToInputStreamAdapter¤Ÿô?com.sun.star.lib.uno.adapter.XOutputStreamToOutputStreamAdapter¤¡‘#Mcom.sun.star.lib.uno.bridges.java_remote.java_remote_bridge.MessageDispatcher(¤¢´€;com.sun.star.lib.uno.bridges.java_remote.java_remote_bridge(¤£C‡Õ7com.sun.star.lib.uno.environments.java.java_environment&¤«‚1com.sun.star.lib.uno.environments.remote.IMarshal(†¤­6z1com.sun.star.lib.uno.environments.remote.IMessage(†¤­°X2com.sun.star.lib.uno.environments.remote.IProtocol(†¤¯ƒ2com.sun.star.lib.uno.environments.remote.IReceiver(†¤²€4com.sun.star.lib.uno.environments.remote.IThreadPool(†¤²‚c3com.sun.star.lib.uno.environments.remote.IUnmarshal(†¤´ó_7com.sun.star.lib.uno.environments.remote.JavaThreadPool(¤µR‚>com.sun.star.lib.uno.environments.remote.JavaThreadPoolFactory(¤·á€Î,com.sun.star.lib.uno.environments.remote.Job(¤¸¯ƒ©1com.sun.star.lib.uno.environments.remote.JobQueue(¤¼X‚Ï1com.sun.star.lib.uno.environments.remote.Protocol(„¤¿'‚]1com.sun.star.lib.uno.environments.remote.ThreadId(¤Á„:com.sun.star.lib.uno.environments.remote.ThreadPoolManager(¤ÂŒq;com.sun.star.lib.uno.environments.remote.remote_environment(¤Âýõ)com.sun.star.lib.uno.helper.ComponentBase¤Äò¸#com.sun.star.lib.uno.helper.Factory¤Æªƒ.com.sun.star.lib.uno.helper.InterfaceContainer¤ÉÀ„47com.sun.star.lib.uno.helper.MultiTypeInterfaceContainer¤Íôm'com.sun.star.lib.uno.helper.PropertySet¤Ïa•"com.sun.star.lib.uno.helper.UnoUrl¤ßö‚2'com.sun.star.lib.uno.helper.WeakAdapter¤â(€ß$com.sun.star.lib.uno.helper.WeakBase¤ã2?com.sun.star.lib.uno.protocols.urp.Marshal.M_InterfaceReference" ¤ä9x5com.sun.star.lib.uno.protocols.urp.Marshal.M_ThreadId" ¤ä±l&com.sun.star.lib.uno.protocols.urp.urp"¤åƒ5.com.sun.star.lib.uno.typedesc.FieldDescription¤èR€¹/com.sun.star.lib.uno.typedesc.MethodDescription¤é ‚È-com.sun.star.lib.uno.typedesc.TypeDescription¤ëÓ‹¬/com.sun.star.lib.uno.typeinfo.AttributeTypeInfo¤÷€.com.sun.star.lib.uno.typeinfo.ConstantTypeInfo¤øL,com.sun.star.lib.uno.typeinfo.MemberTypeInfo¤øZf,com.sun.star.lib.uno.typeinfo.MethodTypeInfo¤øÀ€Â/com.sun.star.lib.uno.typeinfo.ParameterTypeInfo¤ù‚&com.sun.star.lib.uno.typeinfo.TypeInfo¤úOcom.sun.star.lib.uno.Proxy†¤ûß%com.sun.star.lib.util.DisposeListener†¤ûöZ%com.sun.star.lib.util.DisposeNotifier†¤üP_ com.sun.star.lib.util.IInvokable†¤ü¯J!com.sun.star.lib.util.IInvokeHook†¤üù€ƒ)com.sun.star.lib.util.NativeLibraryLoader¤ý|€§"com.sun.star.lib.util.StringHelper¤þ#fcom.sun.star.lib.util.WeakMap¤þ‰‚d#com.sun.star.lib.util.WeakMap.Entry„ ¥{ƒ2com.sun.star.linguistic2.XConversionDictionaryList†¥ ™‚Â$com.sun.star.linguistic2.XDictionary†¥[ƒ%com.sun.star.linguistic2.XDictionary1†¥܃_)com.sun.star.linguistic2.XDictionaryEntry†¥;€Ú1com.sun.star.linguistic2.XDictionaryEventListener†¥€¿(com.sun.star.linguistic2.XDictionaryList†¥Ôƒ}5com.sun.star.linguistic2.XDictionaryListEventListener†¥Q€Ç(com.sun.star.linguistic2.XHyphenatedWord†¥=$com.sun.star.linguistic2.XHyphenator†¥U‚Ö6com.sun.star.linguistic2.XLinguServiceEventBroadcaster†¥!+43com.sun.star.linguistic2.XLinguServiceEventListener†¥"_€Ã-com.sun.star.linguistic2.XLinguServiceManager†¥#"‚ã!com.sun.star.linguistic2.XMeaning†¥&€´)com.sun.star.linguistic2.XPossibleHyphens†¥&¹2com.sun.star.linguistic2.XSearchableDictionaryList†¥'¾+com.sun.star.linguistic2.XSpellAlternatives†¥(Â&com.sun.star.linguistic2.XSpellChecker†¥)ÝÊ'com.sun.star.linguistic2.XSpellChecker1†¥+§¦,com.sun.star.linguistic2.XSupportedLanguages†¥-M€©*com.sun.star.linguistic2.XSupportedLocales†¥-ö€Ë#com.sun.star.linguistic2.XThesaurus†¥.Á12com.sun.star.loader.CannotActivateFactoryException¥/òi)com.sun.star.loader.XImplementationLoader†¥0[Î'com.sun.star.mozilla.MenuMultipleChange¥2)%com.sun.star.mozilla.MenuSingleChange¥3¶€¸*com.sun.star.mozilla.XCloseSessionListener†¥4n€™com.sun.star.mozilla.XMenuProxy†¥5,'com.sun.star.mozilla.XMenuProxyListener†¥63"$com.sun.star.mozilla.XPluginInstance†¥7U‚.com.sun.star.mozilla.XPluginInstanceNotifySink†¥9f€•(com.sun.star.mozilla.XPluginInstancePeer†¥9û‚ð,com.sun.star.mozilla.XPluginInstanceSyncPeer†¥<ë€Ó&com.sun.star.mozilla.XPluginWindowPeer†¥=¾€š2com.sun.star.mozilla.XRemoteServiceManagerProvider†¥>X€¿.com.sun.star.packages.manifest.XManifestReader†¥?€È.com.sun.star.packages.manifest.XManifestWriter†¥?߀Ò&com.sun.star.packages.zip.ZipConstants†¥@±ƒÀ"com.sun.star.packages.zip.ZipEntry¥DqÌ&com.sun.star.packages.zip.ZipException¥F=i(com.sun.star.packages.zip.ZipIOException¥F¦j3com.sun.star.packages.EncryptionNotAllowedException¥Gi+com.sun.star.packages.NoEncryptionException¥Gyi*com.sun.star.packages.NoRawFormatException¥Gâj,com.sun.star.packages.WrongPasswordException¥HLi*com.sun.star.packages.XDataSinkEncrSupport†¥Hµ‚q%com.sun.star.plugin.PluginDescription¥K&$#com.sun.star.plugin.PluginException¥LJ€½com.sun.star.plugin.PluginMode†¥M6"com.sun.star.plugin.PluginVariable¥M="com.sun.star.plugin.XPlugin†¥N_"com.sun.star.plugin.XPluginContext†¥Ou„ô"com.sun.star.plugin.XPluginManager†¥Ti‚ )com.sun.star.presentation.AnimationEffect¥W  *Õ(com.sun.star.presentation.AnimationSpeed¥Þg%com.sun.star.presentation.ClickAction¥ƒE„Œ$com.sun.star.presentation.FadeEffect¥‡Ñ”_+com.sun.star.presentation.PresentationRange¥œ0ò5com.sun.star.presentation.XCustomPresentationSupplier†¥ž"€¯0com.sun.star.presentation.XHandoutMasterSupplier†¥žÑ€¦'com.sun.star.presentation.XPresentation†¥Ÿw€©+com.sun.star.presentation.XPresentationPage†¥  €¡/com.sun.star.presentation.XPresentationSupplier†¥ Á€ª'com.sun.star.reflection.FieldAccessMode¥¡kÀ0com.sun.star.reflection.InvalidTypeNameException¥£+i1com.sun.star.reflection.InvocationTargetException¥£”€‹"com.sun.star.reflection.MethodMode¥¤/com.sun.star.reflection.NoSuchTypeNameException¥¥-i!com.sun.star.reflection.ParamInfo¥¥–'!com.sun.star.reflection.ParamMode¥¦½<2com.sun.star.reflection.TypeDescriptionSearchDepth¥§ùL-com.sun.star.reflection.XArrayTypeDescription†¥©E€ê0com.sun.star.reflection.XCompoundTypeDescription†¥ª/0com.sun.star.reflection.XConstantTypeDescription†¥«I€¡1com.sun.star.reflection.XConstantsTypeDescription†¥«ê€½,com.sun.star.reflection.XEnumTypeDescription†¥¬§€Õ!com.sun.star.reflection.XIdlArray†¥­|‚J!com.sun.star.reflection.XIdlClass†¥¯ÆƒÖ)com.sun.star.reflection.XIdlClassProvider†¥³œ€¢!com.sun.star.reflection.XIdlField†¥´>Ê"com.sun.star.reflection.XIdlField2†¥¶Ê"com.sun.star.reflection.XIdlMember†¥·Ò€Æ"com.sun.star.reflection.XIdlMethod†¥¸˜‚2&com.sun.star.reflection.XIdlReflection†¥ºÊ€õ0com.sun.star.reflection.XIndirectTypeDescription†¥»¿€º:com.sun.star.reflection.XInterfaceAttributeTypeDescription†¥¼y€Ù7com.sun.star.reflection.XInterfaceMemberTypeDescription†¥½R€µ7com.sun.star.reflection.XInterfaceMethodTypeDescription†¥¾Y1com.sun.star.reflection.XInterfaceTypeDescription†¥¿`!(com.sun.star.reflection.XMethodParameter†¥À.com.sun.star.reflection.XModuleTypeDescription†¥Á„€³0com.sun.star.reflection.XPropertyTypeDescription†¥Â7€á%com.sun.star.reflection.XProxyFactory†¥Ã€°/com.sun.star.reflection.XServiceTypeDescription†¥ÃÈô1com.sun.star.reflection.XSingletonTypeDescription†¥Å¼€º(com.sun.star.reflection.XTypeDescription†¥Æv€º3com.sun.star.reflection.XTypeDescriptionEnumeration†¥Ç0€æ9com.sun.star.reflection.XTypeDescriptionEnumerationAccess†¥È’-com.sun.star.reflection.XUnionTypeDescription†¥É¨¿;com.sun.star.registry.CannotRegisterImplementationException¥Ëgi.com.sun.star.registry.InvalidRegistryException¥ËÐi+com.sun.star.registry.InvalidValueException¥Ì9i,com.sun.star.registry.MergeConflictException¥Ì¢i%com.sun.star.registry.RegistryKeyType¥Í 'com.sun.star.registry.RegistryValueType¥Î‚è1com.sun.star.registry.XImplementationRegistration†¥Ñ‚"com.sun.star.registry.XRegistryKey†¥Ó‹³%com.sun.star.registry.XSimpleRegistry†¥ÞÅ‚Ü.com.sun.star.resource.MissingResourceException¥á¡pcom.sun.star.resource.XLocale†¥â…ä%com.sun.star.resource.XResourceBundle†¥çõO+com.sun.star.resource.XResourceBundleLoader†¥éD‡com.sun.star.scanner.ScanError¥êË‚V#com.sun.star.scanner.ScannerContext¥í!€§%com.sun.star.scanner.ScannerException¥íÈ€ë$com.sun.star.scanner.XScannerManager†¥î³‚–"com.sun.star.script.AllEventObject¥ñIy*com.sun.star.script.CannotConvertException¥òÂ%0com.sun.star.script.CannotCreateAdapterException¥óçi&com.sun.star.script.ContextInformation¥ôPŒcom.sun.star.script.FailReason†¥õÜ€þ%com.sun.star.script.FinishEngineEvent¥öÚ- com.sun.star.script.FinishReason¥ø=(com.sun.star.script.InterruptEngineEvent¥ùDÉ#com.sun.star.script.InterruptReason¥û ‚Ú"com.sun.star.script.InvocationInfo¥ýç‚:com.sun.star.script.MemberType¦seAccess†¦E"÷(com.sun.star.sdb.XDatabaseAccessListener†¦G7%com.sun.star.sdb.XDatabaseEnvironment†¦HPc'com.sun.star.sdb.XFormDocumentsSupplier†¦I³€¦-com.sun.star.sdb.XInteractionSupplyParameters†¦JY€¸$com.sun.star.sdb.XParametersSupplier†¦K€¤!com.sun.star.sdb.XQueriesSupplier†¦Kµ€ *com.sun.star.sdb.XQueryDefinitionsSupplier†¦LU€©)com.sun.star.sdb.XReportDocumentsSupplier†¦Lþ€¨!com.sun.star.sdb.XResultSetAccess†¦M¦€¿*com.sun.star.sdb.XRowSetApproveBroadcaster†¦Ne'com.sun.star.sdb.XRowSetApproveListener†¦Os9 com.sun.star.sdb.XRowSetSupplier†¦P¬€É%com.sun.star.sdb.XSQLErrorBroadcaster†¦Qu€ú"com.sun.star.sdb.XSQLErrorListener†¦Ro€«"com.sun.star.sdb.XSQLQueryComposer†¦S‚â)com.sun.star.sdb.XSQLQueryComposerFactory†¦Uü€©&com.sun.star.sdbc.BatchUpdateException¦V¥com.sun.star.sdbc.BestRowScope†¦WµMcom.sun.star.sdbc.BestRowType†¦XIcom.sun.star.sdbc.ChangeAction†¦XKQcom.sun.star.sdbc.ChangeEvent¦Xœ€¡com.sun.star.sdbc.ColumnSearch†¦Y=Lcom.sun.star.sdbc.ColumnType†¦Y‰Icom.sun.star.sdbc.ColumnValue†¦YÒR com.sun.star.sdbc.DataTruncation¦Z$_com.sun.star.sdbc.DataType†¦[ƒÂcom.sun.star.sdbc.Deferrability†¦]E[$com.sun.star.sdbc.DriverPropertyInfo¦] d com.sun.star.sdbc.FetchDirection†¦_Gcom.sun.star.sdbc.IndexType†¦_K`com.sun.star.sdbc.KeyRule†¦_«o!com.sun.star.sdbc.ProcedureColumn†¦`j!com.sun.star.sdbc.ProcedureResult†¦`„C&com.sun.star.sdbc.ResultSetConcurrency†¦`Ç;com.sun.star.sdbc.ResultSetType†¦a`com.sun.star.sdbc.SQLException¦ab"com.sun.star.sdbc.SQLWarning¦b„€œ&com.sun.star.sdbc.TransactionIsolation†¦c €com.sun.star.sdbc.XArray†¦c¡‚Ð!com.sun.star.sdbc.XBatchExecution†¦fq#com.sun.star.sdbc.XBlob†¦g”Ùcom.sun.star.sdbc.XClob†¦im÷com.sun.star.sdbc.XCloseable†¦kd€com.sun.star.sdbc.XColumnLocate†¦l€µcom.sun.star.sdbc.XConnection†¦l¶…·com.sun.star.sdbc.XDataSource†¦rmd#com.sun.star.sdbc.XDatabaseMetaData†¦sÑ /com.sun.star.sdbc.XDriver†¦£n‚com.sun.star.sdbc.XDriverAccess†¦¥v€¯ com.sun.star.sdbc.XDriverManager†¦¦%£%com.sun.star.sdbc.XGeneratedResultSet†¦§È€Â%com.sun.star.sdbc.XIsolatedConnection†¦¨Š€"com.sun.star.sdbc.XMultipleResults†¦ª
+4 com.sun.star.sdbc.XOutParameters†¦«>+com.sun.star.sdbc.XParameters†¦¬i‡ª#com.sun.star.sdbc.XPooledConnection†¦´€¾)com.sun.star.sdbc.XPreparedBatchExecution†¦´Ñ$com.sun.star.sdbc.XPreparedStatement†¦µàcom.sun.star.sdbc.XRef†¦·_€³com.sun.star.sdbc.XResultSet†¦¸„n$com.sun.star.sdbc.XResultSetMetaData†¦¼€†&,com.sun.star.sdbc.XResultSetMetaDataSupplier†¦Â¦€Ã"com.sun.star.sdbc.XResultSetUpdate†¦ÃiÃcom.sun.star.sdbc.XRow†¦Å,† com.sun.star.sdbc.XRowSet†¦ËL)!com.sun.star.sdbc.XRowSetListener†¦Ìucom.sun.star.sdbc.XRowUpdate†¦Í‘…Þcom.sun.star.sdbc.XSQLData†¦Óoncom.sun.star.sdbc.XSQLInput†¦ÔÝ…ˆcom.sun.star.sdbc.XSQLOutput†¦Úe†[com.sun.star.sdbc.XStatement†¦àÀ»com.sun.star.sdbc.XStruct†¦â{#com.sun.star.sdbc.XWarningsSupplier†¦ã™€écom.sun.star.sdbcx.CheckOption†¦ä‚B"com.sun.star.sdbcx.CompareBookmark†¦äÄkcom.sun.star.sdbcx.KeyType†¦å/Fcom.sun.star.sdbcx.Privilege†¦åu€œ"com.sun.star.sdbcx.PrivilegeObject†¦æAcom.sun.star.sdbcx.XAlterTable†¦æR¥com.sun.star.sdbcx.XAppend†¦ç÷€û com.sun.star.sdbcx.XAuthorizable†¦èòÙ#com.sun.star.sdbcx.XColumnsSupplier†¦êË€ !com.sun.star.sdbcx.XCreateCatalog†¦ëk€÷*com.sun.star.sdbcx.XDataDefinitionSupplier†¦ìb)com.sun.star.sdbcx.XDataDescriptorFactory†¦ícom.sun.star.sdbcx.XDeleteRows†¦î–€µcom.sun.star.sdbcx.XDrop†¦ïKQcom.sun.star.sdbcx.XDropCatalog†¦ðœ
+"com.sun.star.sdbcx.XGroupsSupplier†¦ñ¦€Ÿ#com.sun.star.sdbcx.XIndexesSupplier†¦òE€  com.sun.star.sdbcx.XKeysSupplier†¦ò倞com.sun.star.sdbcx.XRename†¦óƒ€àcom.sun.star.sdbcx.XRowLocate†¦ôc‚U"com.sun.star.sdbcx.XTablesSupplier†¦ö¸€Ÿcom.sun.star.sdbcx.XUser†¦÷W€Ó!com.sun.star.sdbcx.XUsersSupplier†¦ø*€ž!com.sun.star.sdbcx.XViewsSupplier†¦øÈ€ž,com.sun.star.security.AccessControlException¦ùf€ã#com.sun.star.security.AllPermission¦úIm'com.sun.star.security.RuntimePermission¦ú¶€„+com.sun.star.security.XAccessControlContext†¦û:€É'com.sun.star.security.XAccessController†¦ü‚)com.sun.star.security.XAction†¦þ,€£com.sun.star.security.XPolicy†¦þÏ€ècom.sun.star.setup.ActionType¦ÿ·„˜com.sun.star.setup.BaseAction§O€Ü!com.sun.star.setup.CopyFileAction§+Ú"com.sun.star.setup.DeleteDirAction§€Î#com.sun.star.setup.DeleteFileAction§Ó·%com.sun.star.setup.DeleteFolderAction§ Š€Ñ)com.sun.star.setup.DeleteFolderItemAction§
+[!com.sun.star.setup.DownloadAction§ a€úcom.sun.star.setup.FontAction§ ['%com.sun.star.setup.InstallEnvironment§ ‚†"com.sun.star.setup.InstallResponse§…+com.sun.star.setup.InstallType§°‚Ž com.sun.star.setup.MakeDirAction§>€å#com.sun.star.setup.MakeFolderAction§#€ô'com.sun.star.setup.MakeFolderItemAction§º%com.sun.star.setup.MakeShortcutAction§Ñncom.sun.star.setup.MirrorEntry§?€Ûcom.sun.star.setup.ModuleInfo§‚gcom.sun.star.setup.ModuleState§€Êcom.sun.star.setup.OSType§ Kƒ$com.sun.star.setup.ProfileItemAction§#Y‡$com.sun.star.setup.ResponseErrorCode§$à,com.sun.star.setup.SizeInfo§& €Ôcom.sun.star.setup.UnzipAction§&à‚lcom.sun.star.setup.UpdateType§)L~$com.sun.star.setup.VersionIdentifier§*Êy(com.sun.star.setup.WindowsRegistryAction§,CÂcom.sun.star.setup.XSetup†§.†ocom.sun.star.sheet.Border§4tR!com.sun.star.sheet.CellDeleteMode§5ƾcom.sun.star.sheet.CellFlags†§7„€©!com.sun.star.sheet.CellInsertMode§8-Ä$com.sun.star.sheet.ConditionOperator§9ñƒ`!com.sun.star.sheet.DataImportMode§=Q€,com.sun.star.sheet.DataPilotFieldOrientation§>Ñ‚com.sun.star.sheet.DataResult§@à€†"com.sun.star.sheet.DataResultFlags†§AfFcom.sun.star.sheet.FillDateMode§A¬È com.sun.star.sheet.FillDirection§Ct”com.sun.star.sheet.FillMode§Ež#com.sun.star.sheet.FilterConnection§F¦!com.sun.star.sheet.FilterOperator§Gªƒê com.sun.star.sheet.FormulaResult†§K”B#com.sun.star.sheet.FunctionArgument§KÖ€Û#com.sun.star.sheet.FunctionCategory†§L±€Ö"com.sun.star.sheet.GeneralFunction§M‡ƒÑcom.sun.star.sheet.GoalResult§QX€’ com.sun.star.sheet.LocalizedName§Qê€Äcom.sun.star.sheet.MemberResult§R®€Ê$com.sun.star.sheet.MemberResultFlags†§SxK com.sun.star.sheet.MoveDirection†§SÃR!com.sun.star.sheet.NamedRangeFlag†§Tk!com.sun.star.sheet.PasteOperation§T€Î&com.sun.star.sheet.RangeSelectionEvent§VN€°com.sun.star.sheet.ResultEvent§Vþ€¦ com.sun.star.sheet.SheetLinkMode§W¤A$com.sun.star.sheet.StatusBarFunction†§X倆!com.sun.star.sheet.SubTotalColumn§Yk€Â#com.sun.star.sheet.TableFilterField§Z-‘%com.sun.star.sheet.TableOperationMode§[¾V%com.sun.star.sheet.TablePageBreakData§]€‘,com.sun.star.sheet.TableValidationVisibility†§]¥X'com.sun.star.sheet.ValidationAlertStyle§]ýª!com.sun.star.sheet.ValidationType§_§‚ˆcom.sun.star.sheet.XAddIn†§b/‚Zcom.sun.star.sheet.XAreaLink†§d‰5com.sun.star.sheet.XAreaLinks†§e¾#%com.sun.star.sheet.XArrayFormulaRange†§fá€Ã com.sun.star.sheet.XCalculatable†§g¤€ù#com.sun.star.sheet.XCellAddressable†§h€ ,com.sun.star.sheet.XCellFormatRangesSupplier†§i=€ª(com.sun.star.sheet.XCellRangeAddressable†§i瀦!com.sun.star.sheet.XCellRangeData†§j€½$com.sun.star.sheet.XCellRangeFormula†§kJ€Ã%com.sun.star.sheet.XCellRangeMovement†§l ñ%com.sun.star.sheet.XCellRangeReferrer†§mþ€¡#com.sun.star.sheet.XCellRangesQuery†§nŸ‚–com.sun.star.sheet.XCellSeries†§q5<&com.sun.star.sheet.XCompatibilityNames†§rq€½"com.sun.star.sheet.XConsolidatable†§s.+com.sun.star.sheet.XConsolidationDescriptor†§t<‚¯com.sun.star.sheet.XDDELink†§vë€Ó'com.sun.star.sheet.XDataPilotDescriptor†§w¾‚Ò*com.sun.star.sheet.XDataPilotMemberResults†§z€$com.sun.star.sheet.XDataPilotResults†§{-€›"com.sun.star.sheet.XDataPilotTable†§{È€¹#com.sun.star.sheet.XDataPilotTables†§|e+com.sun.star.sheet.XDataPilotTablesSupplier†§}怩!com.sun.star.sheet.XDatabaseRange†§~ô"com.sun.star.sheet.XDatabaseRanges†§€ƒ€ó&com.sun.star.sheet.XDimensionsSupplier†§v€£$com.sun.star.sheet.XDocumentAuditing†§‚€…#com.sun.star.sheet.XFillAcrossSheet†§‚ž€ com.sun.star.sheet.XFormulaQuery†§ƒ-€÷"com.sun.star.sheet.XFunctionAccess†§„$(com.sun.star.sheet.XFunctionDescriptions†§…7€Öcom.sun.star.sheet.XGoalSeek†§† €ñ'com.sun.star.sheet.XHeaderFooterContent†§†þ€ï'com.sun.star.sheet.XHierarchiesSupplier†§‡í€¤com.sun.star.sheet.XLabelRange†§ˆ‘Ycom.sun.star.sheet.XLabelRanges†§‰ê€õ"com.sun.star.sheet.XLevelsSupplier†§Šß€Ÿ#com.sun.star.sheet.XMembersSupplier†§‹~€ %com.sun.star.sheet.XMultipleOperation†§Œcom.sun.star.sheet.XNamedRange†§;gcom.sun.star.sheet.XNamedRanges†§Ž¢£com.sun.star.sheet.XPrintAreas†§E‚u"com.sun.star.sheet.XRangeSelection†§’º‚=0com.sun.star.sheet.XRangeSelectionChangeListener†§”÷€¸*com.sun.star.sheet.XRangeSelectionListener†§•¯€é#com.sun.star.sheet.XRecentFunctions†§–˜€Ô"com.sun.star.sheet.XResultListener†§—l€§com.sun.star.sheet.XScenario†§˜5com.sun.star.sheet.XScenarios†§™H%com.sun.star.sheet.XScenariosSupplier†§šO€#com.sun.star.sheet.XSheetAnnotation†§šì)com.sun.star.sheet.XSheetAnnotationAnchor†§œ €¤$com.sun.star.sheet.XSheetAnnotations†§œ¯€à,com.sun.star.sheet.XSheetAnnotationsSupplier†§€¦!com.sun.star.sheet.XSheetAuditing†§ž5Ú#com.sun.star.sheet.XSheetCellCursor†§ D"com.sun.star.sheet.XSheetCellRange†§¡S€£+com.sun.star.sheet.XSheetCellRangeContainer†§¡öý#com.sun.star.sheet.XSheetCellRanges†§£ó"com.sun.star.sheet.XSheetCondition†§¥û+com.sun.star.sheet.XSheetConditionalEntries†§§
+€Ý)com.sun.star.sheet.XSheetConditionalEntry†§§ç€½)com.sun.star.sheet.XSheetFilterDescriptor†§¨¤€é#com.sun.star.sheet.XSheetFilterable†§©€þ%com.sun.star.sheet.XSheetFilterableEx†§ª‹€ê!com.sun.star.sheet.XSheetLinkable†§«u‚"com.sun.star.sheet.XSheetOperation†§­}€ì com.sun.star.sheet.XSheetOutline†§®i‚G"com.sun.star.sheet.XSheetPageBreak†§°°!com.sun.star.sheet.XSheetPastable†§±À£com.sun.star.sheet.XSpreadsheet†§³c'com.sun.star.sheet.XSpreadsheetDocument†§´r€#com.sun.star.sheet.XSpreadsheetView†§µ€ß com.sun.star.sheet.XSpreadsheets†§µî*(com.sun.star.sheet.XSubTotalCalculatable†§·)&com.sun.star.sheet.XSubTotalDescriptor†§¸A€¼!com.sun.star.sheet.XSubTotalField†§¸ý'2com.sun.star.sheet.XUniqueCellFormatRangesSupplier†§º$€°"com.sun.star.sheet.XUsedAreaCursor†§ºÔ€¿!com.sun.star.sheet.XViewFreezable†§»“€´com.sun.star.sheet.XViewPane†§¼G4%com.sun.star.sheet.XViewPanesSupplier†§½{€£!com.sun.star.sheet.XViewSplitable†§¾ "com.sun.star.sheet.XVolatileResult†§¿>€öcom.sun.star.sheet._NamedRange†§À4kcom.sun.star.style.BreakType§ÀŸ‚_com.sun.star.style.CaseMap†§Âþr com.sun.star.style.DropCapFormat§Ãp€ "com.sun.star.style.GraphicLocation§Äƒü&com.sun.star.style.HorizontalAlignment§È _%com.sun.star.style.LineNumberPosition†§ÉkYcom.sun.star.style.LineSpacing§ÉÄ€ˆ"com.sun.star.style.LineSpacingMode†§ÊLX com.sun.star.style.NumberingType†§Ê¤ƒs"com.sun.star.style.PageStyleLayout§ÎŒ"com.sun.star.style.ParagraphAdjust§Ï£Ñ)com.sun.star.style.ParagraphStyleCategory†§Ñtvcom.sun.star.style.TabAlign§Ñê¤com.sun.star.style.TabStop§ÓŽ€î$com.sun.star.style.VerticalAlignment§Ô|U$com.sun.star.style.XDefaultsSupplier†§ÕÑ€žcom.sun.star.style.XStyle†§Öo&"com.sun.star.style.XStyleCondition†§×•€å)com.sun.star.style.XStyleFamiliesSupplier†§Øz€¦com.sun.star.style.XStyleLoader†§Ù com.sun.star.svg.XSVGPrinter†§Ú< com.sun.star.svg.XSVGWriter†§ÛG€®com.sun.star.sync.SyncAction†§Ûõ€ïcom.sun.star.sync.SyncElement§Üä€ýcom.sun.star.sync.SyncEvent†§Ýဋcom.sun.star.sync.SyncInfo§Þl…com.sun.star.sync.SyncMode†§ßñ€com.sun.star.sync.SyncOptions†§à~€¿com.sun.star.sync.SyncScheme§á=€´com.sun.star.sync.SyncType†§áñ€µ com.sun.star.sync.XSyncCollector†§â¦ƒ_com.sun.star.sync.XSynchronizer†§æŸ*com.sun.star.sync2.BadPartnershipException§ç¤€Õ)com.sun.star.system.SimpleMailClientFlags†§èyZ/com.sun.star.system.SystemShellExecuteException§èÓ€º+com.sun.star.system.SystemShellExecuteFlags†§éH"com.sun.star.system.XProxySettings†§éÕ‚f%com.sun.star.system.XSimpleMailClient†§ì;L-com.sun.star.system.XSimpleMailClientSupplier†§í‡€®&com.sun.star.system.XSimpleMailMessage†§î5‚'com.sun.star.system.XSystemShellExecute†§ðÄ com.sun.star.table.BorderLine§ñÏ€Ïcom.sun.star.table.CellAddress§òž€˜"com.sun.star.table.CellContentType§ó6Ž"com.sun.star.table.CellHoriJustify§ôÄ‚"com.sun.star.table.CellOrientation§öÚ¦#com.sun.star.table.CellRangeAddress§ø€€Ñ"com.sun.star.table.CellVertJustify§ùQ’com.sun.star.table.ShadowFormat§úã!com.sun.star.table.ShadowLocation§ûæìcom.sun.star.table.TableBorder§ýÒƒc#com.sun.star.table.TableOrientation¨5!com.sun.star.table.TableSortField¨E•%com.sun.star.table.TableSortFieldType¨Út#com.sun.star.table.XAutoFormattable†¨N€Âcom.sun.star.table.XCell†¨5com.sun.star.table.XCellCursor†¨E€êcom.sun.star.table.XCellRange†¨/©"com.sun.star.table.XColumnRowRange†¨ Ø€Ëcom.sun.star.table.XTableChart†¨
+£scom.sun.star.table.XTableCharts†¨ ''com.sun.star.table.XTableChartsSupplier†¨ =€œ com.sun.star.table.XTableColumns†¨ Ù€Ãcom.sun.star.table.XTableRows†¨œ€Ã.com.sun.star.task.ClassifiedInteractionRequest¨_)com.sun.star.task.DocumentPasswordRequest¨m-"com.sun.star.task.ErrorCodeRequest¨š€·+com.sun.star.task.InteractionClassification¨QÄ'com.sun.star.task.MasterPasswordRequest¨€È#com.sun.star.task.NoMasterException¨Ý€ÿ!com.sun.star.task.PasswordRequest¨Ü;%com.sun.star.task.PasswordRequestMode¨–-com.sun.star.task.UnsupportedOverwriteRequest¨­com.sun.star.task.UrlRecord¨¾com.sun.star.task.UserRecord¨Á€æcom.sun.star.task.XAsyncJob†¨§€ó#com.sun.star.task.XInteractionAbort†¨šz%com.sun.star.task.XInteractionApprove†¨z*com.sun.star.task.XInteractionContinuation†¨Ž~(com.sun.star.task.XInteractionDisapprove†¨ z%com.sun.star.task.XInteractionHandler†¨†€§&com.sun.star.task.XInteractionPassword†¨-€Ê%com.sun.star.task.XInteractionRequest†¨÷€Ñ#com.sun.star.task.XInteractionRetry†¨ Èzcom.sun.star.task.XJob†¨!B€ôcom.sun.star.task.XJobExecutor†¨"6€“com.sun.star.task.XJobListener†¨"É€»$com.sun.star.task.XPasswordContainer†¨#„ƒA"com.sun.star.task.XStatusIndicator†¨&Å€þ)com.sun.star.task.XStatusIndicatorFactory†¨'À«*com.sun.star.task.XStatusIndicatorSupplier†¨(n€¨)com.sun.star.test.bridge.TestDataElements¨)Á$com.sun.star.test.bridge.TestElement¨*×|!com.sun.star.test.bridge.TestEnum¨,S‚4#com.sun.star.test.bridge.TestSimple¨.‡®$com.sun.star.test.bridge.XBridgeTest†¨05«%com.sun.star.test.bridge.XBridgeTest2†¨1à…(com.sun.star.test.bridge.XBridgeTestBase†¨7}‰ž'com.sun.star.test.bridge.XRecursiveCall†¨A€¸*com.sun.star.test.performance.ComplexTypes¨AÓ’)com.sun.star.test.performance.SimpleTypes¨Ce^.com.sun.star.test.performance.XPerformanceTest†¨DǺcom.sun.star.test.TestEvent¨L}€Ûcom.sun.star.test.XSimpleTest†¨MXÏcom.sun.star.test.XTest†¨O'‚;com.sun.star.test.XTestListener†¨Qb%com.sun.star.text.AuthorDisplayFormat†¨Rvb'com.sun.star.text.BibliographyDataField†¨RØ‚Q&com.sun.star.text.BibliographyDataType†¨U)¶com.sun.star.text.ChapterFormat†¨Vßx*com.sun.star.text.CharacterCompressionType†¨WW`"com.sun.star.text.ControlCharacter†¨W·€¢#com.sun.star.text.DateDisplayFormat†¨XY€Å#com.sun.star.text.DocumentStatistic†¨YW'com.sun.star.text.FilenameDisplayFormat†¨Yu[com.sun.star.text.FontEmphasis†¨YЀÔcom.sun.star.text.FontRelief†¨Z¤L#com.sun.star.text.FootnoteNumbering†¨ZðWcom.sun.star.text.GraphicCrop¨[G€¨!com.sun.star.text.HoriOrientation†¨['com.sun.star.text.HoriOrientationFormat¨\€ß"com.sun.star.text.HorizontalAdjust¨]oK-com.sun.star.text.InvalidTextContentException¨^º€ñ com.sun.star.text.MailMergeEvent¨_«€¸com.sun.star.text.MailMergeType†¨`c8com.sun.star.text.NotePrintMode¨`›~ com.sun.star.text.PageNumberType¨bA$com.sun.star.text.ParagraphVertAlign†¨cZn!com.sun.star.text.PlaceholderType†¨cÈm$com.sun.star.text.ReferenceFieldPart†¨d5€Á&com.sun.star.text.ReferenceFieldSource†¨dö€ com.sun.star.text.RelOrientation†¨ew€Îcom.sun.star.text.RubyAdjust¨fE±!com.sun.star.text.SectionFileLink¨gö€»!com.sun.star.text.SetVariableType†¨h±[com.sun.star.text.SizeType†¨i F&com.sun.star.text.TableColumnSeparator¨iR€“'com.sun.star.text.TemplateDisplayFormat†¨iåzcom.sun.star.text.TextColumn¨j_€ 'com.sun.star.text.TextContentAnchorType¨jÿ‚$com.sun.star.text.TextGridMode†¨m#P#com.sun.star.text.TimeDisplayFormat†¨ms€œcom.sun.star.text.UserDataPart†¨n !com.sun.star.text.UserFieldFormat†¨o/E!com.sun.star.text.VertOrientation†¨ot€Ô'com.sun.star.text.VertOrientationFormat¨pH€µcom.sun.star.text.WrapTextMode¨pýúcom.sun.star.text.WritingMode¨r÷2com.sun.star.text.WritingMode2†¨t)f$com.sun.star.text.XAutoTextContainer†¨tt com.sun.star.text.XAutoTextEntry†¨v€Ÿ com.sun.star.text.XAutoTextGroup†¨v¢‚j%com.sun.star.text.XBookmarkInsertTool†¨y €×$com.sun.star.text.XBookmarksSupplier†¨y〢+com.sun.star.text.XChapterNumberingSupplier†¨z…€°+com.sun.star.text.XDefaultNumberingProvider†¨{56%com.sun.star.text.XDependentTextField†¨|k com.sun.star.text.XDocumentIndex†¨}‚€¨$com.sun.star.text.XDocumentIndexMark†¨~*€À*com.sun.star.text.XDocumentIndexesSupplier†¨~ꀩ+com.sun.star.text.XEndnotesSettingsSupplier†¨“€¦#com.sun.star.text.XEndnotesSupplier†¨€9€Ücom.sun.star.text.XFootnote†¨€¸,com.sun.star.text.XFootnotesSettingsSupplier†¨Í€§$com.sun.star.text.XFootnotesSupplier†¨‚t€Þcom.sun.star.text.XHeaderFooter†¨ƒR€Ì(com.sun.star.text.XHeaderFooterPageStyle†¨„€Í*com.sun.star.text.XLineNumberingProperties†¨„뀭(com.sun.star.text.XLineNumberingSupplier†¨…˜€ï'com.sun.star.text.XMailMergeBroadcaster†¨†‡
+$com.sun.star.text.XMailMergeListener†¨‡‘€°com.sun.star.text.XModule†¨ˆAk%com.sun.star.text.XNumberingFormatter†¨ˆ¬)com.sun.star.text.XNumberingRulesSupplier†¨‰¯€¨$com.sun.star.text.XNumberingTypeInfo†¨ŠW1com.sun.star.text.XPageCursor†¨‹ˆ` com.sun.star.text.XPagePrintable†¨ŒèT"com.sun.star.text.XParagraphCursor†¨Ž<g)com.sun.star.text.XReferenceMarksSupplier†¨£€§,com.sun.star.text.XRelativeTextContentInsert†¨J’,com.sun.star.text.XRelativeTextContentRemove†¨‘ÜN com.sun.star.text.XRubySelection†¨“*€ñ!com.sun.star.text.XSentenceCursor†¨”acom.sun.star.text.XSimpleText†¨•|Úcom.sun.star.text.XText†¨—Vscom.sun.star.text.XTextColumns†¨˜É.com.sun.star.text.XTextContent†¨™÷€ùcom.sun.star.text.XTextCursor†¨šð“com.sun.star.text.XTextDocument†¨œƒ€¥%com.sun.star.text.XTextEmbeddedObject†¨(€º.com.sun.star.text.XTextEmbeddedObjectsSupplier†¨â€¨com.sun.star.text.XTextField†¨žŠ€¡%com.sun.star.text.XTextFieldsSupplier†¨Ÿ+€ècom.sun.star.text.XTextFrame†¨ €•%com.sun.star.text.XTextFramesSupplier†¨ ¨€£-com.sun.star.text.XTextGraphicObjectsSupplier†¨¡K€§com.sun.star.text.XTextRange†¨¡ò6#com.sun.star.text.XTextRangeCompare†¨£(ƒ!com.sun.star.text.XTextRangeMover†¨¤«€®com.sun.star.text.XTextSection†¨¥Y€Ü'com.sun.star.text.XTextSectionsSupplier†¨¦5€¥%com.sun.star.text.XTextShapesSupplier†¨¦Ú€ com.sun.star.text.XTextTable†¨§z¯"com.sun.star.text.XTextTableCursor†¨©)ü%com.sun.star.text.XTextTablesSupplier†¨«%€£!com.sun.star.text.XTextViewCursor†¨«È€Ò)com.sun.star.text.XTextViewCursorSupplier†¨¬š€¢com.sun.star.text.XWordCursor†¨­<I,com.sun.star.ucb.AlreadyInitializedException¨®…i&com.sun.star.ucb.AuthenticationRequest¨®î‚—#com.sun.star.ucb.CHAOSProgressStart¨±…€²com.sun.star.ucb.Command¨²7€Ì(com.sun.star.ucb.CommandAbortedException¨³i'com.sun.star.ucb.CommandFailedException¨³l€Ðcom.sun.star.ucb.CommandInfo¨´<€Õ"com.sun.star.ucb.CommandInfoChange†¨µH'com.sun.star.ucb.CommandInfoChangeEvent¨µY€Ñcom.sun.star.ucb.ConnectionMode†¨¶*:com.sun.star.ucb.ContentAction†¨¶dq%com.sun.star.ucb.ContentCreationError¨¶Õ‚Ì)com.sun.star.ucb.ContentCreationException¨¹¡€úcom.sun.star.ucb.ContentEvent¨º›"com.sun.star.ucb.ContentInfo¨»½%com.sun.star.ucb.ContentInfoAttribute†¨¼Ü€Š$com.sun.star.ucb.ContentProviderInfo¨½f€á+com.sun.star.ucb.ContentResultSetCapability†¨¾G(com.sun.star.ucb.Cookie¨¾o¾com.sun.star.ucb.CookiePolicy¨À-:com.sun.star.ucb.CookieRequest¨Ág€ücom.sun.star.ucb.CrossReference¨Âc€—$com.sun.star.ucb.DocumentHeaderField¨Âú€³"com.sun.star.ucb.DocumentStoreMode¨Ã­ 4com.sun.star.ucb.DuplicateCommandIdentifierException¨Ä¹i+com.sun.star.ucb.DuplicateProviderException¨Å"icom.sun.star.ucb.Error†¨Å‹Š!com.sun.star.ucb.ExportStreamInfo¨Ïª€Ãcom.sun.star.ucb.FetchError†¨ÐmQcom.sun.star.ucb.FetchResult¨Ð¾#com.sun.star.ucb.FileSystemNotation†¨ÑÃpcom.sun.star.ucb.FolderList¨Ò3/"com.sun.star.ucb.FolderListCommand¨ÓbU com.sun.star.ucb.FolderListEntry¨Ô·*.com.sun.star.ucb.GlobalTransferCommandArgument¨Õál%com.sun.star.ucb.HandleCookiesRequest¨×MÌcom.sun.star.ucb.IOErrorCode¨ÙŠî+com.sun.star.ucb.IllegalIdentifierException¨äi&com.sun.star.ucb.InsertCommandArgument¨äp€Ã(com.sun.star.ucb.InteractiveAppException¨å3€÷0com.sun.star.ucb.InteractiveAugmentedIOException¨æ*Z3com.sun.star.ucb.InteractiveBadTransferURLException¨ç„i*com.sun.star.ucb.InteractiveCHAOSException¨çíS+com.sun.star.ucb.InteractiveFileIOException¨é@.'com.sun.star.ucb.InteractiveIOException¨ên)3com.sun.star.ucb.InteractiveNetworkConnectException¨ë—,com.sun.star.ucb.InteractiveNetworkException¨ì¨€¬3com.sun.star.ucb.InteractiveNetworkGeneralException¨íT€ª3com.sun.star.ucb.InteractiveNetworkOffLineException¨íþ€ª0com.sun.star.ucb.InteractiveNetworkReadException¨î¨7com.sun.star.ucb.InteractiveNetworkResolveNameException¨ï½1com.sun.star.ucb.InteractiveNetworkWriteException¨ðÎ0com.sun.star.ucb.InteractiveWrongMediumException¨ñãcom.sun.star.ucb.Link¨òö€»com.sun.star.ucb.ListAction¨ó±€Õcom.sun.star.ucb.ListActionType†¨ô†€“com.sun.star.ucb.ListEvent¨õ€ò,com.sun.star.ucb.ListenerAlreadySetException¨ö icom.sun.star.ucb.Lock¨öt†com.sun.star.ucb.LockDepth¨÷ú#com.sun.star.ucb.LockEntry¨ù€Ùcom.sun.star.ucb.LockScope¨ùö€ôcom.sun.star.ucb.LockType¨úꀮ,com.sun.star.ucb.MissingInputStreamException¨û˜i+com.sun.star.ucb.MissingPropertiesException¨ü‰#com.sun.star.ucb.PropertyValueState© œÂcom.sun.star.ucb.RecipientInfo© ^‚æ'com.sun.star.ucb.RememberAuthentication©Dl2com.sun.star.ucb.RemoteContentProviderChangeAction©°N1com.sun.star.ucb.RemoteContentProviderChangeEvent©þ#com.sun.star.ucb.ResultSetException©€œcom.sun.star.ucb.Rule©¹com.sun.star.ucb.RuleAction†©Í€Ücom.sun.star.ucb.RuleOperator†©©€¹com.sun.star.ucb.RuleSet©b€ßcom.sun.star.ucb.RuleTerm©A#&com.sun.star.ucb.SearchCommandArgument©d com.sun.star.ucb.SearchCriterium©€Çcom.sun.star.ucb.SearchInfo©Fé com.sun.star.ucb.SearchRecursion©/Ecom.sun.star.ucb.SendInfo©t€»com.sun.star.ucb.SendMediaTypes©/€â)com.sun.star.ucb.ServiceNotFoundException© icom.sun.star.ucb.SortingInfo© z€­"com.sun.star.ucb.SynchronizePolicy©!'‰)com.sun.star.ucb.TransferCommandOperation©"°hcom.sun.star.ucb.TransferInfo©$€ôcom.sun.star.ucb.TransferResult©% €æ,com.sun.star.ucb.UnsupportedCommandException©%òi-com.sun.star.ucb.UnsupportedDataSinkException©&[€Î.com.sun.star.ucb.UnsupportedNameClashException©')€¹-com.sun.star.ucb.UnsupportedOpenModeException©'‸!com.sun.star.ucb.VerificationMode©(šF.com.sun.star.ucb.WelcomeDynamicResultSetStruct©)à€àcom.sun.star.ucb.XAnyCompare†©*À€¨#com.sun.star.ucb.XAnyCompareFactory†©+h€º/com.sun.star.ucb.XCachedContentResultSetFactory†©,"€ú3com.sun.star.ucb.XCachedContentResultSetStubFactory†©-€Ð/com.sun.star.ucb.XCachedDynamicResultSetFactory†©-ì3com.sun.star.ucb.XCachedDynamicResultSetStubFactory†©.òî$com.sun.star.ucb.XCommandEnvironment†©0à€êcom.sun.star.ucb.XCommandInfo†©1Êã+com.sun.star.ucb.XCommandInfoChangeListener†©3­€¹+com.sun.star.ucb.XCommandInfoChangeNotifier†©4f"com.sun.star.ucb.XCommandProcessor†©5„X#com.sun.star.ucb.XCommandProcessor2†©6Ü€žcom.sun.star.ucb.XContent†©7zjcom.sun.star.ucb.XContentAccess†©8ä com.sun.star.ucb.XContentCreator†©9ô€ü&com.sun.star.ucb.XContentEventListener†©:ð€ª#com.sun.star.ucb.XContentIdentifier†©;š€É*com.sun.star.ucb.XContentIdentifierFactory†©<c€Â*com.sun.star.ucb.XContentIdentifierMapping†©=%Œ!com.sun.star.ucb.XContentProvider†©>±X(com.sun.star.ucb.XContentProviderFactory†©@ €¾(com.sun.star.ucb.XContentProviderManager†©@Ç‚)com.sun.star.ucb.XContentProviderSupplier†©B×€§$com.sun.star.ucb.XContentTransmitter†©C~€¯com.sun.star.ucb.XDataContainer†©D-J"com.sun.star.ucb.XDynamicResultSet†©Ew‚**com.sun.star.ucb.XDynamicResultSetListener†©G¡€¡com.sun.star.ucb.XFetchProvider†©HB€®/com.sun.star.ucb.XFetchProviderForContentAccess†©Hðf)com.sun.star.ucb.XFileIdentifierConverter†©JV@+com.sun.star.ucb.XInteractionCookieHandling†©K–€ü,com.sun.star.ucb.XInteractionHandlerSupplier†©L’€0com.sun.star.ucb.XInteractionReplaceExistingData†©M"z1com.sun.star.ucb.XInteractionSupplyAuthentication†©Mœƒ'com.sun.star.ucb.XInteractionSupplyName†©P°€¢.com.sun.star.ucb.XParameterizedContentProvider†©QR”'com.sun.star.ucb.XPersistentPropertySet†©Ræ€Ç!com.sun.star.ucb.XProgressHandler†©S­€Ç!com.sun.star.ucb.XPropertyMatcher†©Tt€Ð(com.sun.star.ucb.XPropertyMatcherFactory†©UD€Î%com.sun.star.ucb.XPropertySetRegistry†©V€û,com.sun.star.ucb.XPropertySetRegistryFactory†©W €Æcom.sun.star.ucb.XRecycler†©WÓ€Ñ/com.sun.star.ucb.XRemoteContentProviderAcceptor†©X¤[0com.sun.star.ucb.XRemoteContentProviderActivator†©Yÿ€º5com.sun.star.ucb.XRemoteContentProviderChangeListener†©Z¹€Í5com.sun.star.ucb.XRemoteContentProviderChangeNotifier†©[†F8com.sun.star.ucb.XRemoteContentProviderConnectionControl†©\Ì€Ö2com.sun.star.ucb.XRemoteContentProviderDistributor†©]¢¢3com.sun.star.ucb.XRemoteContentProviderDoneListener†©_D€É/com.sun.star.ucb.XRemoteContentProviderSupplier†©` €È"com.sun.star.ucb.XSimpleFileAccess†©`Õˆ#com.sun.star.ucb.XSimpleFileAccess2†©hê€Ø#com.sun.star.ucb.XSimpleFileAccess3†©iÂ`/com.sun.star.ucb.XSortedDynamicResultSetFactory†©k"'&com.sun.star.ucb.XSourceInitialization†©lI€Ã2com.sun.star.ui.dialogs.CommonFilePickerElementIds†©m €Ò&com.sun.star.ui.dialogs.ControlActions†©mÞ1com.sun.star.ui.dialogs.ExecutableDialogException©nãi/com.sun.star.ui.dialogs.ExecutableDialogResults†©oL54com.sun.star.ui.dialogs.ExtendedFilePickerElementIds†©o¹'com.sun.star.ui.dialogs.FilePickerEvent©q:€”/com.sun.star.ui.dialogs.FilePreviewImageFormats†©qÎ(-com.sun.star.ui.dialogs.ListboxControlActions†©qö€µ+com.sun.star.ui.dialogs.TemplateDescription†©r«®&com.sun.star.ui.dialogs.XControlAccess†©tYq+com.sun.star.ui.dialogs.XControlInformation†©uÊÂ)com.sun.star.ui.dialogs.XExecutableDialog†©wŒ€©#com.sun.star.ui.dialogs.XFilePicker†©x5‚0com.sun.star.ui.dialogs.XFilePickerControlAccess†©y·k+com.sun.star.ui.dialogs.XFilePickerListener†©{"¾+com.sun.star.ui.dialogs.XFilePickerNotifier†©|à$com.sun.star.ui.dialogs.XFilePreview†©}ðŒ+com.sun.star.ui.dialogs.XFilterGroupManager†©|€ê&com.sun.star.ui.dialogs.XFilterManager†©€f^%com.sun.star.ui.dialogs.XFolderPicker†©ÄY*com.sun.star.ui.ActionTriggerSeparatorType†©ƒJ'com.sun.star.ui.ContextMenuExecuteEvent©ƒg¨,com.sun.star.ui.ContextMenuInterceptorAction©…‚(com.sun.star.ui.XContextMenuInterception†©‡'com.sun.star.ui.XContextMenuInterceptor†©ˆ'€ãcom.sun.star.uno.Any©‰
+3com.sun.star.uno.AnyConverter©Š=ˆTcom.sun.star.uno.Ascii©’‘2com.sun.star.uno.AsciiString©’ÃP$com.sun.star.uno.DeploymentException©“pcom.sun.star.uno.Enum„©“ƒ5com.sun.star.uno.Exception©“¸€¶com.sun.star.uno.IBridge†©”n¦com.sun.star.uno.IEnvironment†©–Å"com.sun.star.uno.IFieldDescription†©—Ù€ com.sun.star.uno.IMapping†©˜yi#com.sun.star.uno.IMemberDescription†©˜â€•#com.sun.star.uno.IMethodDescription†©™wB com.sun.star.uno.IQueryInterface†©š¹€ !com.sun.star.uno.ITypeDescription†©›Y‚‘!com.sun.star.uno.MappingException©êp!com.sun.star.uno.RuntimeException©žZ€½"com.sun.star.uno.SecurityException©Ÿpcom.sun.star.uno.Type©Ÿ‡„Þcom.sun.star.uno.TypeClass©¤eˆ8com.sun.star.uno.Uik©¬€Ñcom.sun.star.uno.Union©­nXcom.sun.star.uno.UnoRuntime©­Æ„ºcom.sun.star.uno.WeakReference©²€pcom.sun.star.uno.XAdapter†©²ðcom.sun.star.uno.XAggregation†©³ó€Ú"com.sun.star.uno.XComponentContext†©´Í€è com.sun.star.uno.XCurrentContext†©µµ€¦com.sun.star.uno.XInterface†©¶[Ncom.sun.star.uno.XNamingService†©¶©ocom.sun.star.uno.XReference†©¸com.sun.star.uno.XWeak†©¸—€™"com.sun.star.util.logging.LogLevel†©¹0€”!com.sun.star.util.logging.XLogger†©¹Ä['com.sun.star.util.logging.XLoggerRemote†©»€'com.sun.star.util.AliasProgrammaticPair©¼Ÿ€¿"com.sun.star.util.AtomClassRequest©½^€ž!com.sun.star.util.AtomDescription©½ü€Ÿ com.sun.star.util.CellProtection©¾›€âcom.sun.star.util.ChangesEvent©¿},$com.sun.star.util.CloseVetoException©À©i!com.sun.star.util.DataEditorEvent©Á€Ï%com.sun.star.util.DataEditorEventType©Áácom.sun.star.util.Date©Âû€žcom.sun.star.util.DateTime©Ã™com.sun.star.util.DateTimeRange©Äª‚#com.sun.star.util.DiskFullException©Æ®pcom.sun.star.util.ElementChange©Ç€ò!com.sun.star.util.FileIOException©Èi0com.sun.star.util.MalformedNumberFormatException©Èy€¸com.sun.star.util.MeasureUnit†©É1!com.sun.star.util.ModeChangeEvent©ÊL€¨%com.sun.star.util.NotNumericException©Êôicom.sun.star.util.NumberFormat†©Ë]€û"com.sun.star.util.SearchAlgorithms©ÌX_com.sun.star.util.SearchFlags†©Í·€Ëcom.sun.star.util.SearchOptions©Î‚ïcom.sun.star.util.SearchResult©Ðq€écom.sun.star.util.SortField©ÑZ€ácom.sun.star.util.SortFieldType©Ò;Vcom.sun.star.util.Time©Ó‘€Écom.sun.star.util.URL©ÔZ‚Mcom.sun.star.util.VetoException©Ö§icom.sun.star.util.XArchiver†©×Äcom.sun.star.util.XAtomServer†©ØÔ° com.sun.star.util.XCancelManager†©Ú„€îcom.sun.star.util.XCancellable†©Ûr~com.sun.star.util.XChainable†©Ûðocom.sun.star.util.XChangesBatch†©Ý_ "com.sun.star.util.XChangesListener†©Þh€®"com.sun.star.util.XChangesNotifier†©ß€øcom.sun.star.util.XChangesSet†©à€ªcom.sun.star.util.XCloneable†©à¸€›#com.sun.star.util.XCloseBroadcaster†©áS€ð com.sun.star.util.XCloseListener†©âCcom.sun.star.util.XCloseable†©ãY€¶com.sun.star.util.XDataEditor†©ä_%com.sun.star.util.XDataEditorListener†©ån€² com.sun.star.util.XFlushListener†©æ €¥com.sun.star.util.XFlushable†©æÅcom.sun.star.util.XImportable†©çÇ€îcom.sun.star.util.XIndent†©èµ€£com.sun.star.util.XLinkUpdate†©éX€ƒ#com.sun.star.util.XLocalizedAliases†©éÛ„ƒ com.sun.star.util.XMacroExpander†©î^€Ðcom.sun.star.util.XMergeable†©ï.€£,com.sun.star.util.XModeChangeApproveListener†©ïÑ€Ô(com.sun.star.util.XModeChangeBroadcaster†©ð¥‚%com.sun.star.util.XModeChangeListener†©òª€­com.sun.star.util.XModeSelector†©óW3com.sun.star.util.XModifiable†©ôŠ€Û$com.sun.star.util.XModifyBroadcaster†©õe€ô!com.sun.star.util.XModifyListener†©öY€¦(com.sun.star.util.XNumberFormatPreviewer†©öÿ»$com.sun.star.util.XNumberFormatTypes†©øº— com.sun.star.util.XNumberFormats†©úQ‚Ô(com.sun.star.util.XNumberFormatsSupplier†©ý%€ã"com.sun.star.util.XNumberFormatter†©þ‚ý"com.sun.star.util.XPropertyReplace†ª‚lcom.sun.star.util.XProtectable†ªq"com.sun.star.util.XRefreshListener†ªu€§com.sun.star.util.XRefreshable†ª $com.sun.star.util.XReplaceDescriptor†ª(€Ícom.sun.star.util.XReplaceable†ªõ€î#com.sun.star.util.XSearchDescriptor†ªã€Çcom.sun.star.util.XSearchable†ªª¬%com.sun.star.util.XSimpleErrorHandler†ª
+V€šcom.sun.star.util.XSortable†ª
+ð€Ý%com.sun.star.util.XStringAbbreviation†ª Í€Ñcom.sun.star.util.XStringEscape†ª ž7 com.sun.star.util.XStringMapping†ª Õ€™%com.sun.star.util.XStringSubstitution†ªncom.sun.star.util.XStringWidth†ª €›com.sun.star.util.XTextSearch†ª¦Rcom.sun.star.util.XTimeStamped†ªø€!com.sun.star.util.XURLTransformer†ªˆc"com.sun.star.util.XUniqueIDFactory†ª뀒com.sun.star.util.XUpdatable†ª}~"com.sun.star.view.DocumentZoomType†ªû€‚com.sun.star.view.PaperFormatª}‚€"com.sun.star.view.PaperOrientationªýcom.sun.star.view.PrintJobEventª€Æ com.sun.star.view.PrintableStateªÛ‚X%com.sun.star.view.PrintableStateEventª3€Æ com.sun.star.view.XControlAccess†ªù€ècom.sun.star.view.XLineCursor†ªá€ócom.sun.star.view.XPrintJob†ªÔ&com.sun.star.view.XPrintJobBroadcaster†ªñ€ü#com.sun.star.view.XPrintJobListener†ª 퀭com.sun.star.view.XPrintPreview†ª!š€å(com.sun.star.view.XPrintSettingsSupplier†ª"€£com.sun.star.view.XPrintable†ª#"g'com.sun.star.view.XPrintableBroadcaster†ª$‰ \ No newline at end of file
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/Bundle.properties b/scripting/java/org/openoffice/netbeans/modules/office/Bundle.properties
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/Bundle.properties
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/Bundle_en_US.properties b/scripting/java/org/openoffice/netbeans/modules/office/Bundle_en_US.properties
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/Bundle_en_US.properties
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/BuildParcelAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/BuildParcelAction.java
new file mode 100644
index 000000000000..3feae839f531
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/BuildParcelAction.java
@@ -0,0 +1,72 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: BuildParcelAction.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import java.util.Vector;
+import java.util.Enumeration;
+
+import org.openide.nodes.Node;
+import org.openide.util.HelpCtx;
+import org.openide.util.RequestProcessor;
+import org.openide.actions.BuildAllAction;
+
+import org.openide.compiler.Compiler;
+import org.openide.compiler.CompilerJob;
+import org.openide.compiler.CompilerTask;
+
+import org.openoffice.netbeans.modules.office.utils.FrameworkJarChecker;
+
+public class BuildParcelAction extends BuildAllAction {
+ public String getName() {
+ return "Build";
+ }
+
+ protected void performAction(Node[] activatedNodes) {
+ FrameworkJarChecker.mountDependencies();
+
+ for (int i = 0; i < activatedNodes.length; i++) {
+ Vector v = new Vector(1);
+ v.addElement(activatedNodes[i]);
+
+ CompilerJob job = createJob(v.elements(), Compiler.DEPTH_INFINITE);
+ CompilerTask task = job.start();
+ task.waitFinished();
+
+ if (task.isSuccessful()) {
+ ParcelFolderCookie cookie = (ParcelFolderCookie)
+ activatedNodes[i].getCookie(ParcelFolderCookie.class);
+
+ if (cookie != null)
+ cookie.generate();
+ }
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/CompileParcelAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/CompileParcelAction.java
new file mode 100644
index 000000000000..e9aa01340ad7
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/CompileParcelAction.java
@@ -0,0 +1,47 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: CompileParcelAction.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import org.openide.nodes.Node;
+import org.openide.actions.CompileAllAction;
+
+import org.openoffice.netbeans.modules.office.utils.FrameworkJarChecker;
+
+public class CompileParcelAction extends CompileAllAction {
+ public String getName() {
+ return "Compile";
+ }
+
+ protected void performAction(Node[] activatedNodes) {
+ FrameworkJarChecker.mountDependencies();
+ super.performAction(activatedNodes);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ConfigureParcelAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ConfigureParcelAction.java
new file mode 100644
index 000000000000..21209dd715f4
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ConfigureParcelAction.java
@@ -0,0 +1,73 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ConfigureParcelAction.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import org.openide.nodes.Node;
+import org.openide.util.HelpCtx;
+import org.openide.util.RequestProcessor;
+import org.openide.util.actions.CookieAction;
+
+import org.openoffice.netbeans.modules.office.utils.FrameworkJarChecker;
+
+public class ConfigureParcelAction extends CookieAction {
+
+ public java.lang.String getName() {
+ return "Configure";
+ }
+
+ protected java.lang.Class[] cookieClasses() {
+ return new Class[] {ParcelFolderCookie.class};
+ }
+
+ protected int mode() {
+ return CookieAction.MODE_EXACTLY_ONE;
+ }
+
+ public HelpCtx getHelpCtx() {
+ return HelpCtx.DEFAULT_HELP;
+ }
+
+ protected void performAction(final Node[] activatedNodes)
+ {
+ FrameworkJarChecker.mountDependencies();
+
+ RequestProcessor.getDefault().post(new Runnable() {
+ public void run() {
+ for (int i = 0; i < activatedNodes.length; i++) {
+ ParcelFolderCookie pfc = (ParcelFolderCookie)
+ activatedNodes[i].getCookie(ParcelFolderCookie.class);
+ if (pfc != null)
+ pfc.configure();
+ }
+ }
+ });
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/DeployParcelAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/DeployParcelAction.java
new file mode 100644
index 000000000000..ab414dacd78b
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/DeployParcelAction.java
@@ -0,0 +1,247 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: DeployParcelAction.java,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Hashtable;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Enumeration;
+
+import javax.swing.JMenuItem;
+import javax.swing.JFileChooser;
+import javax.swing.filechooser.FileFilter;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+import java.awt.event.ActionListener;
+import java.awt.event.ActionEvent;
+
+import org.openide.TopManager;
+import org.openide.NotifyDescriptor;
+import org.openide.awt.Actions;
+import org.openide.nodes.Node;
+import org.openide.util.HelpCtx;
+import org.openide.util.NbBundle;
+import org.openide.util.RequestProcessor;
+import org.openide.util.actions.*;
+import org.openide.awt.JMenuPlus;
+
+import org.openoffice.idesupport.SVersionRCFile;
+import org.openoffice.idesupport.OfficeInstallation;
+import org.openoffice.idesupport.zip.ParcelZipper;
+import org.openoffice.idesupport.LocalOffice;
+
+import org.openoffice.netbeans.modules.office.utils.NagDialog;
+import org.openoffice.netbeans.modules.office.options.OfficeSettings;
+
+public class DeployParcelAction extends CookieAction implements Presenter.Popup {
+
+ private static final String BROWSE_LABEL = "Office Document...";
+ private static final String DEPLOY_LABEL = "Deploy To";
+
+ public String getName () {
+ return DEPLOY_LABEL;
+ }
+
+ public HelpCtx getHelpCtx () {
+ return HelpCtx.DEFAULT_HELP;
+ }
+
+ public JMenuItem getPopupPresenter() {
+ JMenuPlus menu = new JMenuPlus(DEPLOY_LABEL);
+ JMenuItem item, user, share;
+ final OfficeInstallation oi = OfficeSettings.getDefault().getOfficeDirectory();
+
+ ActionListener listener = new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ JMenuItem choice = (JMenuItem)e.getSource();
+ String label = choice.getText();
+
+ Node[] nodes = getActivatedNodes();
+ final ParcelCookie parcelCookie =
+ (ParcelCookie)nodes[0].getCookie(ParcelCookie.class);
+
+ File target = new File(oi.getPath(File.separator + label +
+ File.separator + "Scripts"));
+
+ File langdir = new File(target, parcelCookie.getLanguage());
+
+ if (!langdir.exists()) {
+ boolean response = askIfCreateDirectory(langdir);
+ if (response == false) {
+ return;
+ }
+ }
+
+ deploy(target);
+ }
+ };
+
+ user = new JMenuItem("user");
+ user.addActionListener(listener);
+
+ share = new JMenuItem("share");
+ share.addActionListener(listener);
+
+ item = new JMenuPlus(oi.getName());
+ item.add(user);
+ item.add(share);
+ menu.add(item);
+
+ menu.addSeparator();
+ item = new JMenuItem(BROWSE_LABEL);
+ item.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ File target = getTargetFile();
+ if (target == null)
+ return;
+ deploy(target);
+ }
+ });
+ menu.add(item);
+
+ return menu;
+ }
+
+ protected int mode () {
+ return MODE_ONE;
+ }
+
+ protected Class[] cookieClasses () {
+ return new Class[] { ParcelCookie.class };
+ }
+
+ protected void performAction (Node[] activatedNodes) {
+ // do nothing, should not happen
+ }
+
+ private void deploy(final File target) {
+ Node[] nodes = getActivatedNodes();
+ final ParcelCookie parcelCookie =
+ (ParcelCookie)nodes[0].getCookie(ParcelCookie.class);
+
+ RequestProcessor.getDefault().post(new Runnable() {
+ public void run() {
+ boolean result = parcelCookie.deploy(target);
+
+ if (result == true && target.isDirectory()) {
+ showNagDialog();
+ // refreshOffice((String)versions.get(label));
+ }
+ }
+ });
+ }
+
+ private boolean askIfCreateDirectory(File directory) {
+ String message = directory.getAbsolutePath() + " does not exist. " +
+ "Do you want to create it now?";
+
+ NotifyDescriptor d = new NotifyDescriptor.Confirmation(
+ message, NotifyDescriptor.OK_CANCEL_OPTION);
+ TopManager.getDefault().notify(d);
+
+ if (d.getValue() == NotifyDescriptor.CANCEL_OPTION)
+ return false;
+
+ boolean result;
+ try {
+ result = directory.mkdirs();
+ }
+ catch (SecurityException se) {
+ result = false;
+ }
+
+ if (result == false) {
+ String tmp = "Error creating: " + directory.getAbsolutePath();
+ NotifyDescriptor d2 = new NotifyDescriptor.Message(
+ tmp, NotifyDescriptor.ERROR_MESSAGE);
+ TopManager.getDefault().notify(d2);
+ }
+ return result;
+ }
+
+ private void refreshOffice(String path) {
+ ClassLoader syscl = TopManager.getDefault().currentClassLoader();
+ LocalOffice office = LocalOffice.create(syscl, path, 8100);
+ office.refreshStorage("file://" + path + "/program/../user");
+ office.disconnect();
+ }
+
+ private void showNagDialog() {
+ String message = "If you currently have Office running you will " +
+ "need to click on the Tools/Scripting Add-on's/Refresh All Scripts " +
+ " menu item in Office so that the scripts in this parcel can be detected.";
+
+ OfficeSettings settings = OfficeSettings.getDefault();
+
+ if (settings.getWarnAfterDirDeploy() == true) {
+ NagDialog warning = NagDialog.createInformationDialog(
+ message, "Show this message in future", true);
+
+ warning.show();
+
+ if (warning.getState() == false)
+ settings.setWarnAfterDirDeploy(false);
+ }
+ }
+
+ private File getTargetFile() {
+ File target = null;
+
+ JFileChooser chooser = new JFileChooser();
+ chooser.setDialogTitle("Deploy Parcel To Office Document");
+ chooser.setApproveButtonText("Deploy");
+ chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
+ chooser.setFileFilter(new FileFilter() {
+ public boolean accept(File file) {
+ if (file.isDirectory() ||
+ file.getName().endsWith(".sxw") ||
+ file.getName().endsWith(".sxc") ||
+ file.getName().endsWith(".sxd") ||
+ file.getName().endsWith(".sxi"))
+ return true;
+ return false;
+ }
+
+ public String getDescription() {
+ return "Office Documents";
+ }
+ });
+
+ int result = chooser.showDialog(null, null);
+
+ if (result == JFileChooser.APPROVE_OPTION) {
+ target = chooser.getSelectedFile();
+ }
+ return target;
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/MountDocumentAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/MountDocumentAction.java
new file mode 100644
index 000000000000..5925e498bdc7
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/MountDocumentAction.java
@@ -0,0 +1,88 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: MountDocumentAction.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import org.openide.nodes.Node;
+import org.openide.util.HelpCtx;
+import org.openide.util.RequestProcessor;
+import org.openide.util.actions.CookieAction;
+
+/**
+ *
+ * @author adams
+ * @version 1.0
+ */
+public class MountDocumentAction extends CookieAction
+{
+ public MountDocumentAction()
+ {
+ }
+
+ public java.lang.String getName()
+ {
+ return "Mount Document"; //NOI18N
+ }
+
+ public HelpCtx getHelpCtx()
+ {
+ return HelpCtx.DEFAULT_HELP;
+ }
+
+ protected int mode()
+ {
+ // enable duplication for as many qualifying nodes as are selected:
+ return CookieAction.MODE_ALL;
+ }
+
+ protected java.lang.Class[] cookieClasses()
+ {
+ // just the DuplicateCookie:
+ return new Class[] {OfficeDocumentCookie.class};
+ }
+
+ protected void performAction(final Node[] activatedNodes)
+ {
+ RequestProcessor.getDefault().post(new Runnable()
+ {
+ public void run()
+ {
+ for (int i=0; i<activatedNodes.length; i++)
+ {
+ OfficeDocumentCookie cookie = (OfficeDocumentCookie)activatedNodes[i].getCookie(OfficeDocumentCookie.class);
+ if (cookie != null)
+ {
+ cookie.mount();
+ }
+ }
+ }
+ });
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/MountParcelAction.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/MountParcelAction.java
new file mode 100644
index 000000000000..201333827184
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/MountParcelAction.java
@@ -0,0 +1,87 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: MountParcelAction.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import org.openide.nodes.Node;
+import org.openide.util.HelpCtx;
+import org.openide.util.RequestProcessor;
+import org.openide.util.actions.CookieAction;
+
+/**
+ *
+ * @author adams
+ * @version 1.0
+ */
+public class MountParcelAction extends CookieAction
+{
+ public MountParcelAction()
+ {
+ }
+
+ public java.lang.String getName()
+ {
+ return "Mount Parcel"; //NOI18N
+ }
+
+ public HelpCtx getHelpCtx()
+ {
+ return HelpCtx.DEFAULT_HELP;
+ }
+
+ protected int mode()
+ {
+ // enable duplication for as many qualifying nodes as are selected:
+ return CookieAction.MODE_ALL;
+ }
+
+ protected java.lang.Class[] cookieClasses()
+ {
+ return new Class[] {ParcelCookie.class};
+ }
+
+ protected void performAction(final Node[] activatedNodes)
+ {
+ RequestProcessor.getDefault().post(new Runnable()
+ {
+ public void run()
+ {
+ for (int i=0; i<activatedNodes.length; i++)
+ {
+ ParcelCookie mpc = (ParcelCookie)activatedNodes[i].getCookie(ParcelCookie.class);
+ if (mpc != null)
+ {
+ mpc.mount();
+ }
+ }
+ }
+ });
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentCookie.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentCookie.java
new file mode 100644
index 000000000000..eba503d5eb10
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentCookie.java
@@ -0,0 +1,45 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeDocumentCookie.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import java.util.Enumeration;
+import javax.swing.event.ChangeListener;
+import org.openide.nodes.Node;
+
+public interface OfficeDocumentCookie extends Node.Cookie
+{
+ public void mount();
+ public Enumeration getParcels();
+ public void removeParcel(String name);
+
+ public void addChangeListener(ChangeListener cl);
+ public void removeChangeListener(ChangeListener cl);
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentSupport.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentSupport.java
new file mode 100644
index 000000000000..82d8887189cf
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/OfficeDocumentSupport.java
@@ -0,0 +1,146 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeDocumentSupport.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import java.io.IOException;
+import java.io.File;
+import java.beans.PropertyVetoException;
+import java.util.Enumeration;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Iterator;
+import javax.swing.event.ChangeListener;
+import javax.swing.event.ChangeEvent;
+
+import org.openide.ErrorManager;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileUtil;
+import org.openide.filesystems.FileChangeListener;
+import org.openide.filesystems.FileEvent;
+import org.openide.filesystems.FileAttributeEvent;
+import org.openide.filesystems.FileRenameEvent;
+import org.openide.cookies.OpenCookie;
+
+import org.openoffice.idesupport.OfficeDocument;
+
+import org.openoffice.netbeans.modules.office.options.OfficeSettings;
+import org.openoffice.netbeans.modules.office.loader.OfficeDocumentDataObject;
+import org.openoffice.netbeans.modules.office.utils.ZipMounter;
+import org.openoffice.netbeans.modules.office.utils.ManifestParser;
+
+public class OfficeDocumentSupport implements OfficeDocumentCookie, OpenCookie, FileChangeListener
+{
+ protected OfficeDocumentDataObject dataObj;
+ private boolean isMounted = false;
+ private OfficeDocument document;
+ private Set listeners;
+
+ public OfficeDocumentSupport(OfficeDocumentDataObject dataObj) {
+ this.dataObj = dataObj;
+ FileObject fo = dataObj.getPrimaryFile();
+ try {
+ this.document = new OfficeDocument(FileUtil.toFile(fo));
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ fo.addFileChangeListener(this);
+ }
+
+ public void mount() {
+ File file = FileUtil.toFile(dataObj.getPrimaryFile());
+
+ try {
+ ZipMounter.getZipMounter().mountZipFile(file);
+ isMounted = true;
+ }
+ catch (IOException ioe) {
+ ErrorManager.getDefault().notify(ioe);
+ }
+ catch (PropertyVetoException pve) {
+ ErrorManager.getDefault().notify(pve);
+ }
+ }
+
+ public void open () {
+ File file = FileUtil.toFile(dataObj.getPrimaryFile());
+
+ OfficeSettings settings = OfficeSettings.getDefault();
+ File soffice = new File(settings.getOfficeDirectory().getPath(
+ File.separator + "soffice"));
+
+ try {
+ Process p = Runtime.getRuntime ().exec (new String[] {
+ soffice.getAbsolutePath(), file.getAbsolutePath ()
+ });
+ } catch (IOException ioe) {
+ ErrorManager.getDefault().notify(ioe);
+ }
+ }
+
+ public Enumeration getParcels() {
+ return document.getParcels();
+ }
+
+ public void removeParcel(String name) {
+ document.removeParcel(name);
+ dataObj.getPrimaryFile().refresh(true);
+ }
+
+ public void addChangeListener(ChangeListener cl) {
+ if (listeners == null)
+ listeners = new HashSet();
+
+ listeners.add(cl);
+ }
+
+ public void removeChangeListener(ChangeListener cl) {
+ if (listeners == null)
+ return;
+
+ listeners.remove(cl);
+ }
+
+ public void fileChanged(FileEvent fe) {
+ if (listeners != null) {
+ Iterator iter = listeners.iterator();
+
+ while (iter.hasNext())
+ ((ChangeListener)iter.next()).stateChanged(new ChangeEvent(this));
+ }
+ }
+
+ public void fileAttributeChanged(FileAttributeEvent fe) {}
+ public void fileDataCreated(FileEvent fe) {}
+ public void fileDeleted(FileEvent fe) {}
+ public void fileFolderCreated(FileEvent fe) {}
+ public void fileRenamed(FileRenameEvent fe) {}
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelCookie.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelCookie.java
new file mode 100644
index 000000000000..a48e50acb245
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelCookie.java
@@ -0,0 +1,45 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelCookie.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import java.io.File;
+import org.openide.nodes.Node;
+
+public interface ParcelCookie extends Node.Cookie
+{
+ public File getFile();
+
+ public String getLanguage();
+
+ public void mount();
+
+ public boolean deploy(File target);
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorEditorSupport.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorEditorSupport.java
new file mode 100644
index 000000000000..a0adf2633aa0
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorEditorSupport.java
@@ -0,0 +1,144 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDescriptorEditorSupport.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import java.io.IOException;
+
+import org.openide.cookies.*;
+import org.openide.filesystems.FileLock;
+import org.openide.filesystems.FileObject;
+import org.openide.loaders.DataObject;
+import org.openide.text.DataEditorSupport;
+import org.openide.windows.CloneableOpenSupport;
+
+import org.openoffice.netbeans.modules.office.loader.ParcelDescriptorDataObject;
+
+/** Support for editing a data object as text.
+ *
+ * @author tomaso
+ */
+// Replace OpenCookie with EditCookie or maybe ViewCookie as desired:
+public class ParcelDescriptorEditorSupport extends DataEditorSupport implements EditorCookie, OpenCookie, CloseCookie, PrintCookie {
+
+ /** Create a new editor support.
+ * @param obj the data object whose primary file will be edited as text
+ */
+ public ParcelDescriptorEditorSupport(ParcelDescriptorDataObject obj) {
+ super(obj, new ParcelDescriptorEnv(obj));
+ // Set a MIME type as needed, e.g.:
+ setMIMEType("text/xml");
+ }
+
+ /** Called when the document is modified.
+ * Here, adding a save cookie to the object and marking it modified.
+ * @return true if the modification is acceptable
+ */
+ protected boolean notifyModified() {
+ if (!super.notifyModified()) {
+ return false;
+ }
+ ParcelDescriptorDataObject obj = (ParcelDescriptorDataObject)getDataObject();
+ if (obj.getCookie(SaveCookie.class) == null) {
+ obj.setModified(true);
+ // You must implement this method on the object:
+ obj.addSaveCookie(new Save());
+ }
+ return true;
+ }
+
+ /** Called when the document becomes unmodified.
+ * Here, removing the save cookie from the object and marking it unmodified.
+ */
+ protected void notifyUnmodified() {
+ ParcelDescriptorDataObject obj = (ParcelDescriptorDataObject)getDataObject();
+ SaveCookie save = (SaveCookie)obj.getCookie(SaveCookie.class);
+ if (save != null) {
+ // You must implement this method on the object:
+ obj.removeSaveCookie(save);
+ obj.setModified(false);
+ }
+ super.notifyUnmodified();
+ }
+
+ /** A save cookie to use for the editor support.
+ * When saved, saves the document to disk and marks the object unmodified.
+ */
+ private class Save implements SaveCookie {
+ public void save() throws IOException {
+ saveDocument();
+ getDataObject().setModified(false);
+ }
+ }
+
+ /** A description of the binding between the editor support and the object.
+ * Note this may be serialized as part of the window system and so
+ * should be static, and use the transient modifier where needed.
+ */
+ private static class ParcelDescriptorEnv extends DataEditorSupport.Env {
+
+ //private static final long serialVersionUID = ...L;
+
+ /** Create a new environment based on the data object.
+ * @param obj the data object to edit
+ */
+ public ParcelDescriptorEnv(ParcelDescriptorDataObject obj) {
+ super(obj);
+ }
+
+ /** Get the file to edit.
+ * @return the primary file normally
+ */
+ protected FileObject getFile() {
+ return getDataObject().getPrimaryFile();
+ }
+
+ /** Lock the file to edit.
+ * Should be taken from the file entry if possible, helpful during
+ * e.g. deletion of the file.
+ * @return a lock on the primary file normally
+ * @throws IOException if the lock could not be taken
+ */
+ protected FileLock takeLock() throws IOException {
+ return ((ParcelDescriptorDataObject)getDataObject()).getPrimaryEntry().takeLock();
+ }
+
+ /** Find the editor support this environment represents.
+ * Note that we have to look it up, as keeping a direct
+ * reference would not permit this environment to be serialized.
+ * @return the editor support
+ */
+ public CloneableOpenSupport findCloneableOpenSupport() {
+ return (ParcelDescriptorEditorSupport)getDataObject().getCookie(ParcelDescriptorEditorSupport.class);
+ }
+
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserCookie.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserCookie.java
new file mode 100644
index 000000000000..cafc7ed714a5
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserCookie.java
@@ -0,0 +1,45 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDescriptorParserCookie.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import org.w3c.dom.NodeList;
+import javax.swing.event.ChangeListener;
+import org.openide.nodes.Node;
+
+public interface ParcelDescriptorParserCookie extends Node.Cookie
+{
+ // should return a NodeList of org.w3c.dom.Element
+ public NodeList getScriptElements();
+
+ public void addChangeListener(ChangeListener cl);
+
+ public void removeChangeListener(ChangeListener cl);
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserSupport.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserSupport.java
new file mode 100644
index 000000000000..dc019f734359
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelDescriptorParserSupport.java
@@ -0,0 +1,124 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDescriptorParserSupport.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import java.io.*;
+import java.util.*;
+import javax.swing.event.ChangeListener;
+import javax.swing.event.ChangeEvent;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import org.openide.filesystems.*;
+import org.openide.xml.XMLUtil;
+
+public class ParcelDescriptorParserSupport
+ implements ParcelDescriptorParserCookie, FileChangeListener
+{
+ private FileObject fo;
+ private Document document;
+ private Set listeners;
+
+ public ParcelDescriptorParserSupport(FileObject fo)
+ {
+ this.fo = fo;
+ fo.addFileChangeListener(this);
+ }
+
+ private synchronized void parseFile()
+ {
+ File file = FileUtil.toFile(fo);
+ InputSource is;
+
+ try {
+ is = new InputSource(new FileInputStream(file));
+ }
+ catch (FileNotFoundException fnfe) {
+ System.out.println("Couldn't find file: " + file.getName());
+ return;
+ }
+
+ document = null;
+ try {
+ document = XMLUtil.parse(is, false, false, null, null);
+ }
+ catch (IOException ioe) {
+ System.out.println("IO Error parsing file: " + file.getName());
+ }
+ catch (SAXException se) {
+ System.out.println("Sax Error parsing file: " + file.getName());
+ }
+ }
+
+ public synchronized NodeList getScriptElements()
+ {
+ if (document == null)
+ parseFile();
+
+ if (document != null)
+ return document.getElementsByTagName("script");
+ return null;
+ }
+
+ public void addChangeListener(ChangeListener cl) {
+ if (listeners == null)
+ listeners = new HashSet();
+
+ listeners.add(cl);
+ }
+
+ public void removeChangeListener(ChangeListener cl) {
+ if (listeners == null)
+ return;
+
+ listeners.remove(cl);
+ }
+
+ public void fileChanged(FileEvent fe) {
+ parseFile();
+
+ if (listeners != null) {
+ Iterator iter = listeners.iterator();
+
+ while (iter.hasNext())
+ ((ChangeListener)iter.next()).stateChanged(new ChangeEvent(this));
+ }
+ }
+
+ public void fileAttributeChanged(FileAttributeEvent fe) {}
+ public void fileDataCreated(FileEvent fe) {}
+ public void fileDeleted(FileEvent fe) {}
+ public void fileFolderCreated(FileEvent fe) {}
+ public void fileRenamed(FileRenameEvent fe) {}
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderCookie.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderCookie.java
new file mode 100644
index 000000000000..fa2dc61b0f48
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderCookie.java
@@ -0,0 +1,45 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelFolderCookie.java,v $
+ * $Revision: 1.7 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import org.openide.nodes.Node;
+
+public interface ParcelFolderCookie extends Node.Cookie
+{
+ public void generate();
+
+ public boolean configure();
+
+ public void setClasspath(String value);
+ public String getClasspath();
+
+ public String getLanguage();
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderSupport.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderSupport.java
new file mode 100644
index 000000000000..5cd6640053cf
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelFolderSupport.java
@@ -0,0 +1,260 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelFolderSupport.java,v $
+ * $Revision: 1.15 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import java.util.Vector;
+import java.util.StringTokenizer;
+
+import java.io.*;
+import java.beans.PropertyVetoException;
+import java.awt.Dialog;
+
+import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+
+import org.openide.TopManager;
+import org.openide.DialogDescriptor;
+import org.openide.ErrorManager;
+import org.openide.xml.XMLUtil;
+import org.openide.execution.NbClassPath;
+
+import org.openide.cookies.OpenCookie;
+import org.openide.loaders.DataObject;
+import org.openide.loaders.DataNode;
+
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileSystem;
+import org.openide.filesystems.JarFileSystem;
+import org.openide.filesystems.FileUtil;
+import org.openide.filesystems.Repository;
+
+import org.openide.nodes.*;
+import org.openide.windows.OutputWriter;
+
+import org.openoffice.netbeans.modules.office.loader.ParcelFolder;
+import org.openoffice.netbeans.modules.office.options.OfficeSettings;
+import org.openoffice.netbeans.modules.office.utils.ManifestParser;
+
+import com.sun.star.script.framework.container.ParcelDescriptor;
+
+import org.openoffice.idesupport.zip.ParcelZipper;
+import org.openoffice.idesupport.filter.FileFilter;
+import org.openoffice.idesupport.ui.ConfigurePanel;
+
+public class ParcelFolderSupport implements ParcelFolderCookie
+{
+ protected ParcelFolder parcelFolder;
+ private ConfigurePanel configuror = null;
+
+ public ParcelFolderSupport(ParcelFolder parcelFolder) {
+ this.parcelFolder = parcelFolder;
+ }
+
+ public String getLanguage() {
+ ParcelDescriptor descriptor = getParcelDescriptor();
+
+ if (descriptor == null) {
+ return "";
+ }
+ else {
+ return descriptor.getLanguage();
+ }
+ }
+
+ public String getClasspath() {
+ ParcelDescriptor descriptor = getParcelDescriptor();
+
+ if (descriptor == null) {
+ return "";
+ }
+ else {
+ return descriptor.getLanguageProperty("classpath");
+ }
+ }
+
+ public void setClasspath(String value) {
+ ParcelDescriptor descriptor = getParcelDescriptor();
+
+ if (descriptor != null) {
+ descriptor.setLanguageProperty("classpath", value);
+
+ try {
+ descriptor.write();
+ }
+ catch (IOException ioe) {
+ ErrorManager.getDefault().notify(ioe);
+ }
+ }
+ }
+
+ private ParcelDescriptor getParcelDescriptor() {
+ FileObject primary = parcelFolder.getPrimaryFile();
+
+ File contents = FileUtil.toFile(
+ primary.getFileObject(ParcelZipper.CONTENTS_DIRNAME));
+
+ return ParcelDescriptor.getParcelDescriptor(contents);
+ }
+
+ public void generate() {
+ ParcelFolder.ParcelFolderNode node =
+ (ParcelFolder.ParcelFolderNode)parcelFolder.getNodeDelegate();
+
+ FileObject parcelBase = parcelFolder.getPrimaryFile();
+ FileObject contentsBase =
+ parcelBase.getFileObject(ParcelZipper.CONTENTS_DIRNAME);
+
+ File parcelDir = FileUtil.toFile(parcelBase);
+ File contentsDir = FileUtil.toFile(contentsBase);
+
+ // The Location property is not displayed so just
+ // use the Parcel Recipe directory as the target directory
+ File targetDir = FileUtil.toFile(parcelFolder.getPrimaryFile());
+ File targetfile = new File(targetDir, File.separator +
+ parcelBase.getName() + "." + ParcelZipper.PARCEL_EXTENSION);
+
+ boolean proceed = configure();
+ if (proceed == false) {
+ return;
+ }
+
+ final OutputWriter out =
+ ParcelSupport.getOutputWindowWriter(parcelDir.getName() + " (generating)");
+ try {
+ out.println("Generating: " + parcelDir.getName(), null);
+ ParcelZipper.getParcelZipper().zipParcel(contentsDir, targetfile, node.getFileFilter());
+ out.println("\nGENERATION SUCCESSFUL.");
+ out.println("\nRight click on the generated parcel to deploy it");
+
+ if (targetDir.equals(parcelDir)) {
+ parcelBase.refresh(true);
+ }
+ }
+ catch (IOException ioe) {
+ out.println("GENERATION FAILED: reason: " + ioe.getClass().getName() + ": "+ ioe.getMessage());
+ }
+ finally
+ {
+ if( out != null)
+ {
+ out.close();
+ }
+ }
+ }
+
+ public boolean configure() {
+
+ FileObject primary = parcelFolder.getPrimaryFile();
+
+ File contents = FileUtil.toFile(
+ primary.getFileObject(ParcelZipper.CONTENTS_DIRNAME));
+
+ Vector classpath = getConfigureClasspath();
+ classpath.addElement(contents.getAbsolutePath());
+
+ try {
+ ParcelDescriptor descriptor = getParcelDescriptor();
+ if (descriptor == null) {
+ descriptor = ParcelDescriptor.createParcelDescriptor(contents);
+ }
+
+ if (configuror == null) {
+ configuror = new ConfigurePanel(contents.getAbsolutePath(),
+ classpath, descriptor);
+ }
+ else {
+ configuror.reload(contents.getAbsolutePath(), classpath,
+ descriptor);
+ }
+ }
+ catch (IOException ioe) {
+ ErrorManager.getDefault().notify(ioe);
+ return false;
+ }
+
+ DialogDescriptor dd = new DialogDescriptor(configuror,
+ ConfigurePanel.DIALOG_TITLE);
+
+ Dialog dialog = TopManager.getDefault().createDialog(dd);
+ dialog.show();
+
+ if (dd.getValue() == DialogDescriptor.OK_OPTION) {
+ try {
+ ParcelDescriptor descriptor = configuror.getConfiguration();
+ descriptor.write();
+ }
+ catch (Exception e) {
+ ErrorManager.getDefault().notify(e);
+ }
+ }
+ else {
+ return false;
+ }
+ return true;
+ }
+
+ private Vector getConfigureClasspath() {
+ Vector result = new Vector();
+
+ String classpath = NbClassPath.createRepositoryPath().getClassPath();
+ if ( System.getProperty( "os.name" ).startsWith( "Windows" ) )
+ {
+ // under windows path is enclosed by quotes
+ // e.g. C:\path1;d:\path2 would appear as
+ // "C:\path1;d:\path2" therefore for us
+ // we need to remove 1 character at either end of the
+ // classpath returned from "createRepositoryPath().getClassPath()"
+
+ if ( classpath.startsWith("\"") && classpath.endsWith("\"") )
+ {
+ StringBuffer buff = new StringBuffer(classpath);
+ buff.delete(0,1);
+ buff.delete( buff.length() - 1, buff.length() );
+ classpath = buff.toString();
+ }
+ }
+ StringTokenizer tokens = new StringTokenizer(classpath, File.pathSeparator);
+
+ while(tokens.hasMoreTokens())
+ result.addElement(tokens.nextToken());
+
+ OfficeSettings settings = OfficeSettings.getDefault();
+ File classesDir = new File(settings.getOfficeDirectory().getPath(
+ File.separator + "program" + File.separator + "classes"));
+ File[] jarfiles = classesDir.listFiles();
+
+ for (int i = 0; i < jarfiles.length; i++)
+ result.addElement(jarfiles[i].getAbsolutePath());
+
+ return result;
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelSupport.java b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelSupport.java
new file mode 100644
index 000000000000..589b8914da31
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/actions/ParcelSupport.java
@@ -0,0 +1,194 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelSupport.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.actions;
+
+import java.io.File;
+import java.io.IOException;
+import java.beans.PropertyVetoException;
+import java.util.Enumeration;
+import java.util.Calendar;
+
+import org.openide.TopManager;
+import org.openide.NotifyDescriptor;
+import org.openide.windows.OutputWriter;
+import org.openide.windows.InputOutput;
+
+import org.openide.ErrorManager;
+import org.openide.nodes.Node;
+import org.openide.filesystems.Repository;
+import org.openide.filesystems.FileSystem;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileUtil;
+import org.openide.filesystems.FileEvent;
+
+import org.openoffice.idesupport.zip.ParcelZipper;
+
+import org.openoffice.netbeans.modules.office.options.OfficeSettings;
+import org.openoffice.netbeans.modules.office.utils.NagDialog;
+import org.openoffice.netbeans.modules.office.utils.ZipMounter;
+import org.openoffice.netbeans.modules.office.utils.ManifestParser;
+
+public class ParcelSupport implements ParcelCookie
+{
+ private FileObject fo;
+ private ParcelZipper zipper = ParcelZipper.getParcelZipper();
+ private String language = null;
+
+ public ParcelSupport(FileObject fo) {
+ this.fo = fo;
+ }
+
+ public File getFile() {
+ return FileUtil.toFile(fo);
+ }
+
+ public String getLanguage() {
+ if (language == null) {
+ try {
+ language = zipper.getParcelLanguage(getFile());
+ }
+ catch (IOException ioe) {
+ return null;
+ }
+ }
+ return language;
+ }
+
+ public void mount()
+ {
+ File parcel = FileUtil.toFile(fo);
+
+ if (parcel != null) {
+ try {
+ ZipMounter.getZipMounter().mountZipFile(parcel);
+ }
+ catch (IOException ioe) {
+ ErrorManager.getDefault().notify(ioe);
+ }
+ catch (PropertyVetoException pve) {
+ ErrorManager.getDefault().notify(pve);
+ }
+ }
+ }
+
+ public boolean deploy(File target) {
+ File source = FileUtil.toFile(fo);
+
+ if (!target.isDirectory()) {
+ OfficeSettings settings = OfficeSettings.getDefault();
+ String message = "If you already have this document open in " +
+ "Office, please close it before continuing. Click OK to " +
+ "continue deployment.";
+
+ if (settings.getWarnBeforeDocDeploy() == true) {
+ NagDialog warning = NagDialog.createConfirmationDialog(
+ message, "Show this message in future", true);
+
+ boolean result = warning.show();
+
+ if (warning.getState() == false)
+ settings.setWarnBeforeDocDeploy(false);
+
+ if (result == false)
+ return false;
+ }
+ }
+
+ OutputWriter out =
+ getOutputWindowWriter(fo.getName() + " (deploying)");
+
+ try {
+ if (zipper.isOverwriteNeeded(source, target) == true)
+ if (promptForOverwrite(source, target) == false)
+ return false;
+ }
+ catch (IOException ioe) {
+ out.println("DEPLOYMENT FAILED: reason: " +
+ ioe.getClass().getName() + ": "+ ioe.getMessage());
+ return false;
+ }
+
+ try {
+ out.println("Deploying: " + fo.getName() +
+ "\nTo: " + target.getAbsolutePath(), null);
+
+ zipper.deployParcel(source, target);
+
+ out.println("\nDEPLOYMENT SUCCESSFUL.");
+
+ FileObject[] fileobjs = FileUtil.fromFile(target);
+ if (fileobjs != null) {
+ for (int i = 0; i < fileobjs.length; i++)
+ fileobjs[i].refresh(true);
+ }
+ }
+ catch (IOException ioe) {
+ out.println("DEPLOYMENT FAILED: reason: " +
+ ioe.getClass().getName() + ": "+ ioe.getMessage());
+ return false;
+ }
+ finally {
+ if( out != null)
+ out.close();
+ }
+ return true;
+ }
+
+ public static OutputWriter getOutputWindowWriter(String title) {
+ InputOutput io = TopManager.getDefault().getIO(title, false);
+ io.setFocusTaken(true);
+ io.setOutputVisible(true);
+
+ OutputWriter out = io.getOut();
+ try {
+ out.reset();
+ }
+ catch( IOException e) {
+ e.printStackTrace(System.err);
+ }
+ out.println(Calendar.getInstance().getTime() + ":\n");
+ return out;
+ }
+
+ private boolean promptForOverwrite(File source, File target) {
+ String message = source.getName() + " has already been deployed " +
+ "to this target. Do you wish to overwrite it?";
+
+ NotifyDescriptor d = new NotifyDescriptor.Confirmation(
+ message, NotifyDescriptor.OK_CANCEL_OPTION);
+ TopManager.getDefault().notify(d);
+
+ if (d.getValue() == NotifyDescriptor.CANCEL_OPTION)
+ return false;
+ else
+ return true;
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/filesystem/Bundle.properties b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/Bundle.properties
new file mode 100644
index 000000000000..3137b89dde94
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/Bundle.properties
@@ -0,0 +1,43 @@
+# Filesystems API
+# {0} - root path
+LAB_invalid_file_system=invalid OpenOffice.org document {0}
+# {0} - root path
+LAB_valid_file_system={0}
+# {0} - root path
+EXC_root_dir_does_not_exist=Root directory {0} does not exist.
+# {0} - original name before annotation
+LBL_modified_files={0} <somehow annotated>
+# {0} - file name and extension
+# {1} - display name of filesystem
+# {2} - full path to file
+EXC_file_could_not_be_locked={2} could not be locked; it did not exist or was not writable.
+# {0} - file name and extension
+# {1} - display name of filesystem
+# {2} - full path to file
+EXC_create_empty_name=Cannot create a file with an empty name.
+# {0} - file name and extension
+# {1} - display name of filesystem
+# {2} - full path to file
+EXC_folder_already_exists=Folder {2} already exists.
+# {0} - file name and extension
+# {1} - display name of filesystem
+# {2} - full path to file
+EXC_folder_could_not_be_created=Folder {2} could not be created.
+# {0} - file name and extension
+# {1} - display name of filesystem
+# {2} - full path to file
+EXC_file_could_not_be_created=File {2} could not be created.
+# {0} - old file name and extension
+# {1} - new file name and extension
+# {2} - display name of filesystem
+# {3} - full path to old file
+# {4} - full path to new file
+EXC_file_could_not_be_renamed=File {3} could not be renamed to {4}.
+# {0} - file name and extension
+# {1} - display name of filesystem
+# {2} - full path to file
+EXC_file_could_not_be_deleted=File {2} could not be deleted.
+PROP_readOnly=Read Only
+HINT_readOnly=Whether this filesystem should be writable, or read-only.
+PROP_document=OpenOffice.org Document
+HINT_document=OpenOffice.org Document (mount point) of this filesystem.
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/filesystem/Bundle_en_US.properties b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/Bundle_en_US.properties
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/Bundle_en_US.properties
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystem.java b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystem.java
new file mode 100644
index 000000000000..7355e07e9661
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystem.java
@@ -0,0 +1,1195 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OpenOfficeDocFileSystem.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.filesystem;
+
+import java.beans.*;
+import java.io.*;
+import java.util.*;
+import java.util.zip.*;
+
+import org.openide.ErrorManager;
+import org.openide.filesystems.*;
+import org.openide.filesystems.FileSystem; // override java.io.FileSystem
+import org.openide.util.NbBundle;
+
+// ISSUES:
+// - This FS saves (updates) the file on 'setDocument' or 'removeNotify'.
+// It has to let the user to decide to update or not.
+//
+// TODOS:
+// - 'Update' action on the mounted document which saves all recent modifications.
+// - To introduce 'scope' editable property to control editable portion of
+// the mounted document.
+// - Acceptable document type identification before mount.
+
+/**
+ * OpenOffice.org Document filesystem.
+ *
+ * @author misha <misha@openoffice.org>
+ */
+public class OpenOfficeDocFileSystem
+ extends AbstractFileSystem
+{
+ public static final String SCRIPTS_ROOT = "Scripts"; // must be a folder
+ public static final String SEPARATOR = "/"; // zip file separator
+
+ private static final int OS_UNKNOWN = 0;
+ private static final int OS_UNIX = 1;
+ private static final int OS_MACOS = 2;
+ private static final int OS_WINDOWS = 3;
+
+ private static final int REFRESH_OFF = -1; // -1 is desabled
+ private static final int REFRESH_TIME = REFRESH_OFF; // (mS)
+ private static final String TMP_FILE_PREF = "sx_";
+ private static final String TMP_FILE_SUFX = ".sxx";
+
+ private transient Map cache; // filesystem cache
+ private transient File docFile; // OpenOffice document
+ private transient ZipFile zipFile;
+
+ private static transient int osType; // type of OS
+
+ private transient ChildrenStrategy childrenStrategy;
+ private transient EditableStrategy editableStrategy;
+
+ private transient boolean isModified; // true if an entry has been removed
+
+ /**
+ * Static constructor.
+ */
+ static {
+ // Identify the type of OS
+ String osname = System.getProperty("os.name");
+ if (osname.startsWith("Mac OS"))
+ osType = OS_MACOS;
+ else if (osname.startsWith("Windows"))
+ osType = OS_WINDOWS;
+ else
+ osType = OS_UNIX;
+ }
+
+ /**
+ * Default constructor. Initializes new OpenOffice filesystem.
+ */
+ public OpenOfficeDocFileSystem()
+ {
+ // Create the filesystem cache
+ cache = new HashMap();
+
+ // Initialize strategies
+ editableStrategy = new EditableStrategy(SCRIPTS_ROOT);
+ childrenStrategy = new ChildrenStrategy();
+
+ // Create and use implementations of filesystem functionality:
+ info = new InfoImpl();
+ change = new ChangeImpl();
+
+ // Handle filesystem.attributes files normally:
+ DefaultAttributes defattr = new DefaultAttributes(
+ info, change, new ListImpl());
+
+ // Handle filesystem.attributes files normally + adds virtual attribute
+ // "java.io.File" that is used in conversion routines FileUtil.toFile and
+ // FileUtil.fromFile
+ //defattr = new InnerAttrs(this, info, change, new ListImpl());
+ // (Otherwise set attr to a special implementation, and use ListImpl for list.)
+ attr = defattr;
+ list = defattr;
+
+ // transfer = new TransferImpl();
+ setRefreshTime(REFRESH_OFF);
+ }
+
+ /**
+ * Constructor. Initializes new OpenOffice filesystem with FS capability.
+ */
+ public OpenOfficeDocFileSystem(FileSystemCapability cap)
+ {
+ this();
+ setCapability(cap);
+ }
+
+ /**
+ * Provides unique signature of an instance of the filesystem.
+ * NOTE: The scope is not a part of the signature so it is impossible
+ * to mount the same archive more then once.
+ */
+ public static String computeSystemName(File file)
+ {
+ return OpenOfficeDocFileSystem.class.getName() + "[" + file + "]";
+ }
+
+ // ----------- PROPERTIES --------------
+
+ /**
+ * Provides the 'human readable' name of the instance of the filesystem.
+ */
+ public String getDisplayName()
+ {
+ if (!isValid())
+ return NbBundle.getMessage(OpenOfficeDocFileSystem.class,
+ "LAB_invalid_file_system", ((docFile != null)? docFile.toString(): ""));
+ else
+ return NbBundle.getMessage(OpenOfficeDocFileSystem.class,
+ "LAB_valid_file_system", docFile.toString());
+ }
+
+ /**
+ * Retrives the 'document' property.
+ */
+ public File getDocument()
+ {
+ return docFile;
+ }
+
+ /**
+ * Sets the 'document' property.
+ */
+ // Bean setter. Changing the OpenOffice document (or in general, the identity
+ // of the root file object) should cause everything using this filesystem
+ // to refresh. The system name must change and refreshRoot should be used
+ // to ensure that everything is correctly updated.
+ public synchronized void setDocument(File file)
+ throws java.beans.PropertyVetoException, java.io.IOException
+ {
+System.out.println("OpenOfficeDocFileSystem.setDocument: file=\"" + file.toString() + "\"");
+ if((file.exists() == false) || (file.isFile() == false)) {
+ IOException ioe = new IOException(
+ file.toString() + " does not exist");
+ ErrorManager.getDefault().annotate(ioe, NbBundle.getMessage(
+ OpenOfficeDocFileSystem.class, "EXC_root_dir_does_not_exist",
+ file.toString()));
+ throw ioe;
+ }
+ // update the document
+ try {
+ updateDocument();
+ } catch(IOException ioe) {
+ // cannot save all!!!
+System.out.println("*** OpenOfficeDocFileSystem.setDocument:");
+System.out.println(" file: " + ((docFile != null)? docFile.toString(): ""));
+System.out.println(" exception: " + ioe.getMessage());
+ }
+ // new document type verification!!!
+ closeDocument();
+ // open a new document
+ try {
+ openDocument(file);
+ firePropertyChange(PROP_ROOT, null, refreshRoot());
+ setRefreshTime(REFRESH_TIME);
+ } catch(IOException ioe) {
+ // cannot open a new document!!!
+System.out.println("*** OpenOfficeDocFileSystem.setDocument:");
+System.out.println(" file: " + ((file != null)? file.toString(): ""));
+System.out.println(" exception: " + ioe.getMessage());
+ }
+ }
+
+ /**
+ * Retrives 'readonly' property.
+ * NOTE: The portion of the mounted document available to the user is
+ * always editable.
+ */
+ public boolean isReadOnly()
+ {
+ return false;
+ }
+
+ /**
+ * Sets 'readonly' property.
+ * NOTE: The portion of the mounted document available to the user is
+ * always editable.
+ */
+ public void setReadOnly(boolean flag)
+ {
+ // sorry! it is not supported.
+ }
+
+ // ----------- SPECIAL CAPABILITIES --------------
+
+ /**
+ * Participates in the environment configuration.
+ * This is how you can affect the classpath for execution, compilation, etc.
+ */
+ public void prepareEnvironment(FileSystem.Environment environment)
+ {
+ // BUG: the compiller cannot access files withing the OpenOffice document.
+ //environment.addClassPath(docFile.toString());
+ }
+
+ /* -----------------------------------------------------------
+ * Affect the name and icon of files on this filesystem according to their
+ * "status", e.g. version-control modification-commit state:
+ /*
+ private class StatusImpl implements Status {
+ public Image annotateIcon(Image icon, int iconType, Set files) {
+ // You may first modify it, e.g. by adding a check mark to the icon
+ // if that makes sense for this file or group of files.
+ return icon;
+ }
+ public String annotateName(String name, Set files) {
+ // E.g. add some sort of suffix to the name if some of the
+ // files are modified but not backed up or committed somehow:
+ if (theseFilesAreModified(files))
+ return NbBundle.getMessage(OpenOfficeDocFileSystem.class, "LBL_modified_files", name);
+ else
+ return name;
+ }
+ }
+
+ private transient Status status;
+
+ public Status getStatus() {
+ if (status == null) {
+ status = new StatusImpl();
+ }
+ return status;
+ }
+ // And use fireFileStatusChanged whenever you know something has changed.
+ */
+
+ /*
+ // Filesystem-specific actions, such as version-control operations.
+ // The actions should typically be CookieActions looking for DataObject
+ // cookies, where the object's primary file is on this type of filesystem.
+ public SystemAction[] getActions() {
+// ------>>>> UPDATE OPENOFFICE DOCUMENT <<<<------
+ return new SystemAction[] {
+ SystemAction.get(SomeAction.class),
+ null, // separator
+ SystemAction.get(SomeOtherAction.class)
+ };
+ }
+ */
+
+ /**
+ * Notifies this filesystem that it has been removed from the repository.
+ * Concrete filesystem implementations could perform clean-up here.
+ * The default implementation does nothing.
+ * <p>Note that this method is <em>advisory</em> and serves as an optimization
+ * to avoid retaining resources for too long etc. Filesystems should maintain correct
+ * semantics regardless of whether and when this method is called.
+ */
+ public void removeNotify()
+ {
+ setRefreshTime(REFRESH_OFF); // disable refresh
+ // update the document
+ try {
+ updateDocument();
+ } catch(IOException ioe) {
+ // cannot save all!!!
+System.out.println("*** OpenOfficeDocFileSystem.removeNotify:");
+System.out.println(" exception: " + ioe.getMessage());
+ }
+ closeDocument();
+ super.removeNotify();
+ }
+
+ /*
+ * Opens (mounts) an OpenOffice document.
+ */
+ private void openDocument(File file)
+ throws IOException, PropertyVetoException
+ {
+ synchronized(cache) {
+ setSystemName(computeSystemName(file));
+ docFile = file;
+ zipFile = new ZipFile(docFile);
+ cacheDocument(zipFile.entries(), editableStrategy);
+ isModified = false;
+ } // synchronized
+ }
+
+ /*
+ * Closes the document and cleans up the cache.
+ */
+ private void closeDocument()
+ {
+ synchronized(cache) {
+ // if a document mounted - close it
+ if(docFile != null) {
+ // close the document archive
+ if(zipFile != null) {
+ try {
+ zipFile.close();
+ } catch(IOException ioe) {
+ // sorry! we can do nothing about it.
+ }
+ }
+ zipFile = null;
+ // clean up cache
+ scanDocument(new CleanStrategy());
+ docFile = null;
+ isModified = false;
+ }
+ } // synchronized
+ }
+
+ /*
+ * Creates a document cache.
+ */
+ private void cacheDocument(Enumeration entries, Strategy editables)
+ {
+ Entry cacheEntry;
+ ZipEntry archEntry;
+ synchronized(cache) {
+ cache.clear();
+ // root folder
+ cacheEntry = new ReadWriteEntry(null);
+ cache.put(cacheEntry.getName(), cacheEntry);
+ // the rest of items
+ while(entries.hasMoreElements()) {
+ archEntry = (ZipEntry)entries.nextElement();
+ cacheEntry = new Entry(archEntry);
+ if(editables.evaluate(cacheEntry))
+ cacheEntry = new ReadWriteEntry(archEntry);
+ cache.put(cacheEntry.getName(), cacheEntry);
+ }
+ } // synchronized
+ }
+
+ /*
+ * Updates the document.
+ */
+ private void updateDocument()
+ throws IOException
+ {
+ if(docFile == null)
+ return;
+ synchronized(cache) {
+ ModifiedStrategy modifiedStrategy = new ModifiedStrategy();
+ scanDocument(modifiedStrategy);
+ if((isModified == true) ||
+ (modifiedStrategy.isModified() == true))
+ {
+ File tmpFile = null;
+ try {
+ // create updated document
+ tmpFile = File.createTempFile(
+ TMP_FILE_PREF, TMP_FILE_SUFX, docFile.getParentFile());
+ saveDocument(tmpFile);
+ } catch(IOException ioe) {
+ if(tmpFile != null)
+ tmpFile.delete();
+ throw ioe;
+ }
+ // close the document archive
+ if(zipFile != null) {
+ try {
+ zipFile.close();
+ } catch(IOException ioe) {
+ }
+ }
+ zipFile = null;
+ // create the document and backup
+ File newFile = new File(docFile.getParentFile() + File.separator +
+ "~" + docFile.getName());
+ if(newFile.exists())
+ newFile.delete(); // delete old backup
+ docFile.renameTo(newFile);
+ tmpFile.renameTo(docFile);
+ // open the document archive
+ zipFile = new ZipFile(docFile);
+ }
+ isModified = false;
+ } // synchronized
+ }
+
+ /*
+ * Saves the document in a new archive.
+ */
+ private void saveDocument(File file)
+ throws IOException
+ {
+ synchronized(cache) {
+ SaveStrategy saver = new SaveStrategy(file);
+ scanDocument(saver);
+ saver.close();
+ } // synchronized
+ }
+
+ /*
+ * Provides each individual entry in the cached document to an apraiser.
+ */
+ private void scanDocument(Strategy strategy)
+ {
+ synchronized(cache) {
+ Iterator itr = cache.values().iterator();
+ while(itr.hasNext()) {
+ strategy.evaluate((Entry)itr.next());
+ }
+ } // synchronized
+ }
+
+ /*
+ * Retrives or creates a file.
+ */
+ private Entry getFileEntry(String name)
+ throws IOException
+ {
+ Entry cEntry = null;
+ synchronized(cache) {
+ cEntry = (Entry)cache.get(name);
+ if(cEntry == null) {
+ // create a new file
+ ZipEntry zEntry = new ZipEntry(name);
+ zEntry.setTime(new Date().getTime());
+ cEntry = new Entry(zEntry);
+ if(editableStrategy.evaluate(cEntry) == false) {
+ throw new IOException(
+ "cannot create/edit readonly file"); // I18N
+ }
+ cEntry = new ReadWriteEntry(zEntry);
+ cache.put(cEntry.getName(), cEntry);
+ isModified = true;
+ }
+ } // synchronized
+ return cEntry;
+ }
+
+ /*
+ * Retrives or creates a folder.
+ */
+ private Entry getFolderEntry(String name)
+ throws IOException
+ {
+ Entry cEntry = null;
+ synchronized(cache) {
+ cEntry = (Entry)cache.get(name);
+ if(cEntry == null) {
+ // create a new folder
+ ZipEntry zEntry = new ZipEntry(name + SEPARATOR);
+ zEntry.setMethod(ZipEntry.STORED);
+ zEntry.setSize(0);
+ CRC32 crc = new CRC32();
+ zEntry.setCrc(crc.getValue());
+ zEntry.setTime(new Date().getTime());
+ cEntry = new Entry(zEntry);
+ if(editableStrategy.evaluate(cEntry) == false) {
+ throw new IOException(
+ "cannot create folder"); // I18N
+ }
+ cEntry = new ReadWriteEntry(zEntry);
+ cEntry.getOutputStream(); // sets up modified flag
+ cache.put(cEntry.getName(), cEntry);
+ isModified = true;
+ } else {
+ if(cEntry.isFolder() == false)
+ cEntry = null;
+ }
+ } // synchronized
+ return cEntry;
+ }
+
+ /*
+ * Converts the name to ZIP file name.
+ * Removes the leading file separator if there is one.
+ * This is WORKAROUND of the BUG in AbstractFileObject:
+ * While AbstractFileObject reprecents the root of the filesystem it uses
+ * the absolute path (the path starts with '/'). It is inconsistent with
+ * the rest of the code.
+ * WORKAROUND: we have to strip leading '/' if it is in the name.
+ */
+ private static String zipName(String name)
+ {
+ String zname = ((name.startsWith(File.separator))?
+ name.substring(File.separator.length()): name);
+ switch(osType) {
+ case OS_MACOS:
+ zname = zname.replace(':', '/'); // ':' by '/'
+ break;
+ case OS_WINDOWS:
+ zname = zname.replace((char)0x5c, '/'); // '\' by '/'
+ break;
+ default:
+ break;
+ }
+ return zname;
+ }
+
+ // ----------- IMPLEMENTATIONS OF ABSTRACT FUNCTIONALITY ----------
+
+ /* -----------------------------------------------------------
+ * Information about files and operations on the contents which do
+ * not affect the file's presence or name.
+ */
+ private class InfoImpl
+ implements Info
+ {
+ public boolean folder(String name) {
+ synchronized(cache) {
+ String zname = zipName(name);
+ Entry entry = (Entry)cache.get(zname);
+ if(entry != null)
+ return entry.isFolder();
+ // logical zip file entry
+ childrenStrategy.setParent(zname);
+ scanDocument(childrenStrategy);
+ return (childrenStrategy.countChildren() > 0);
+ }
+ }
+
+ public Date lastModified(String name) {
+ synchronized(cache) {
+ Entry entry = (Entry)cache.get(zipName(name));
+ return new Date((entry != null)? entry.getTime(): 0L);
+ }
+ }
+
+ public boolean readOnly(String name) {
+ synchronized(cache) {
+ Entry entry = (Entry)cache.get(zipName(name));
+ return (entry != null)? entry.isReadOnly(): false;
+ }
+ }
+
+ public String mimeType(String name) {
+ // Unless you have some special means of determining MIME type
+ // (e.g. HTTP headers), ask IDE to use its normal heuristics:
+ // the MIME resolver pool and then file extensions, or if nothing
+ // matches, just content/unknown.
+ return null;
+ }
+
+ public long size(String name) {
+ synchronized(cache) {
+ Entry entry = (Entry)cache.get(zipName(name));
+ return (entry != null)? entry.getSize(): 0;
+ } // synchronized
+ }
+
+ public InputStream inputStream(String name)
+ throws FileNotFoundException
+ {
+ synchronized(cache) {
+ Entry entry = (Entry)cache.get(zipName(name));
+ return (entry != null)? entry.getInputStream(): null;
+ } // synchronized
+ }
+
+ public OutputStream outputStream(String name)
+ throws IOException
+ {
+ return getFileEntry(zipName(name)).getOutputStream();
+ }
+
+ // AbstractFileSystem handles locking the file to the rest of the IDE.
+ // This only means that you should define how the file should be locked
+ // to the outside world--perhaps it does not need to be.
+ public void lock(String name)
+ throws IOException
+ {
+/*
+ File file = getFile(name);
+ if (file.exists() == true && file.canWrite() == false) {
+ IOException ioe = new IOException("file " + file +
+ " could not be locked");
+ ErrorManager.getDefault().annotate(ioe, NbBundle.getMessage(
+ OpenOfficeDocFileSystem.class, "EXC_file_could_not_be_locked",
+ file.getName(), getDisplayName(), file.getPath()));
+ throw ioe;
+ }
+*/
+ }
+
+ public void unlock(String name) {
+ // Nothing special needed to unlock a file to the outside world.
+ }
+
+ public void markUnimportant(String name) {
+ // Do nothing special. Version-control systems may use this to mark
+ // certain files (e.g. *.class) as not needing to be stored in the VCS
+ // while others (source files) are by default important.
+ }
+
+ }
+
+ /* -----------------------------------------------------------
+ * Operations that change the available files.
+ */
+ private class ChangeImpl
+ implements Change
+ {
+ public void createFolder(String name)
+ throws IOException
+ {
+ synchronized(cache) {
+ String zname = zipName(name);
+ if(cache.get(zname) != null) {
+ throw new IOException(
+ "cannot create new folder: " + name); // I18N
+ }
+ getFolderEntry(zname);
+ } // synchronized
+ }
+
+ public void createData(String name)
+ throws IOException
+ {
+ synchronized(cache) {
+ String zname = zipName(name);
+ if(cache.get(zname) != null) {
+ throw new IOException(
+ "cannot create new data: " + name); // I18N
+ }
+ OutputStream os = getFileEntry(zname).getOutputStream();
+ os.close();
+ } // synchronized
+ }
+
+ public void rename(String oldName, String newName)
+ throws IOException
+ {
+ String oname = zipName(oldName);
+ String nname = zipName(newName);
+ if((oname.length() == 0) || (nname.length() == 0)) {
+ throw new IOException(
+ "cannot move or rename the root folder"); // I18N
+ }
+ synchronized(cache) {
+ if(cache.get(nname) != null) {
+ throw new IOException(
+ "target file/folder " + newName + " exists"); // I18N
+ }
+ Entry entry = (Entry)cache.get(oname);
+ if(entry == null) {
+ throw new IOException(
+ "there is no such a file/folder " + oldName); // I18N
+ }
+ if(entry.isReadOnly() == true) {
+ throw new IOException(
+ "file/folder " + oldName + " is readonly"); // I18N
+ }
+ entry.rename(nname);
+ if(editableStrategy.evaluate(entry) == false) {
+ entry.rename(oname);
+ throw new IOException(
+ "cannot create file/folder"); // I18N
+ }
+ cache.remove(oname);
+ cache.put(entry.getName(), entry);
+ } // synchronized
+ }
+
+ public void delete(String name)
+ throws IOException
+ {
+ String zname = zipName(name);
+ if(zname.length() == 0) {
+ throw new IOException(
+ "cannot delete the root folder"); // I18N
+ }
+ synchronized(cache) {
+ Entry entry = (Entry)cache.remove(zname);
+ if(entry != null) {
+ // BUG: this is the design bug. Cache has to
+ // remember that the entry was removed.
+ isModified = true;
+ entry.clean();
+ }
+ } // synchronized
+ }
+ }
+
+ /* -----------------------------------------------------------
+ * Operation which provides the directory structure.
+ */
+ private class ListImpl
+ implements List
+ {
+ public String[] children(String name)
+ {
+ String[] children = null;
+ synchronized(cache) {
+ String zname = zipName(name);
+ Entry entry = (Entry)cache.get(zname);
+ if(entry != null) {
+ // real zip file entry
+ if(entry.isFolder()) {
+ childrenStrategy.setParent(entry.getName());
+ }
+ } else {
+ // logical zip file entry
+ // (portion of the path of a real zip file entry)
+ childrenStrategy.setParent(zname);
+ }
+ scanDocument(childrenStrategy);
+ children = childrenStrategy.getChildren();
+ } // synchronize
+ return children;
+ }
+
+ }
+
+ /** -----------------------------------------------------------
+ * This class adds new virtual attribute "java.io.File".
+ * Because of the fact that FileObjects of __Sample__FileSystem are convertible
+ * to java.io.File by means of attributes. */
+ /*private static class InnerAttrs extends DefaultAttributes {
+ //static final long serialVersionUID = 1257351369229921993L;
+ __Sample__FileSystem sfs;
+ public InnerAttrs(__Sample__FileSystem sfs, AbstractFileSystem.Info info,
+ AbstractFileSystem.Change change,AbstractFileSystem.List list ) {
+ super(info, change, list);
+ this.sfs = sfs;
+ }
+ public Object readAttribute(String name, String attrName) {
+ if (attrName.equals("java.io.File")) // NOI18N
+ return sfs.getFile(name);
+
+ return super.readAttribute(name, attrName);
+ }
+ }*/
+
+ /* -----------------------------------------------------------
+ // Optional special implementations of copy and (cross-directory) move.
+ private class TransferImpl implements Transfer {
+
+ public boolean copy(String name, Transfer target, String targetName) throws IOException {
+ // Only permit special implementation within single FS
+ // (or you could implement it across filesystems if you wished):
+ if (target != this) return false;
+ // Specially copy the file in an efficient way, e.g. implement
+ // a copy-on-write algorithm.
+ return true;
+ }
+
+ public boolean move(String name, Transfer target, String targetName) throws IOException {
+ // Only permit special implementation within single FS
+ // (or you could implement it across filesystems if you wished):
+ if (target != this) return false;
+ // Specially move the file, e.g. retain rename information even
+ // across directories in a version-control system.
+ return true;
+ }
+
+ }
+ */
+
+ /* -----------------------------------------------------------
+ * This interface hides an action will be performed on an entry.
+ */
+ private interface Strategy
+ {
+ public boolean evaluate(Entry entry);
+ }
+
+ /* -----------------------------------------------------------
+ * Recognizes editable (read-write) entires
+ */
+ private class EditableStrategy
+ implements Strategy
+ {
+ private String scope;
+
+ public EditableStrategy(String scope)
+ {
+ this.scope = scope;
+ }
+
+ public boolean evaluate(Entry entry)
+ {
+ // recognizes all entries in a subtree of the
+ // 'scope' as editable entries
+ return (entry != null)?
+ entry.getName().startsWith(scope): false;
+ }
+ }
+
+ /* -----------------------------------------------------------
+ * Recognizes and accumulates immediate children of the parent.
+ */
+ private class ChildrenStrategy
+ implements Strategy
+ {
+ private String parent;
+ private Collection children = new HashSet();
+
+ public ChildrenStrategy()
+ {
+ }
+
+ public void setParent(String name)
+ {
+ parent = (name.length() > 0)? (name + SEPARATOR): "";
+ if(children == null)
+ children = (java.util.List)new LinkedList();
+ children.clear();
+ }
+
+ public boolean evaluate(Entry entry)
+ {
+ // do not accept "children" of a file
+ // ignore "read only" part of the filesystem
+ if(entry.isReadOnly() == false) {
+ // identify a child
+ if( (entry.getName().length() > 0) &&
+ (entry.getName().startsWith(parent)))
+ {
+ // identify an immediate child
+ String child = entry.getName();
+ if(parent.length() > 0) {
+ child = entry.getName().substring(parent.length());
+ }
+ int idx = child.indexOf(SEPARATOR);
+ if(idx > 0) // more path elements ahead
+ child = child.substring(0, idx);
+ return children.add(child);
+ }
+ }
+ return false;
+ }
+
+ public int countChildren()
+ {
+ return children.size();
+ }
+
+ public String[] getChildren()
+ {
+ String[] chn = new String[children.size()];
+ Iterator itr = children.iterator();
+ int idx = 0;
+ while(itr.hasNext()) {
+ chn[idx++] = (String)itr.next();
+ }
+ return chn;
+ }
+ }
+
+ /* -----------------------------------------------------------
+ * Recognizes cache entries which have to be save into new archive.
+ */
+ private class ModifiedStrategy
+ implements Strategy
+ {
+ private boolean modified;
+
+ public boolean evaluate(Entry entry)
+ {
+ modified |= entry.isModified();
+ return entry.isModified();
+ }
+
+ public boolean isModified()
+ {
+ return modified;
+ }
+ }
+
+ /* -----------------------------------------------------------
+ * Saves each entry in the filesystem cache.
+ */
+ private class SaveStrategy
+ implements Strategy
+ {
+ ZipOutputStream docos;
+ IOException ioexp;
+
+ public SaveStrategy(File newdoc)
+ throws IOException
+ {
+ docos = new ZipOutputStream(new FileOutputStream(newdoc));
+ ioexp = null; // success by default
+ }
+
+ public boolean evaluate(Entry entry)
+ {
+ if(entry.getName().length() == 0)
+ return false;
+ try {
+ entry.save(docos);
+ } catch(IOException ioe) {
+ if(ioexp == null)
+ ioexp = ioe;
+ }
+ return true;
+ }
+
+ public void close()
+ throws IOException
+ {
+ if(docos != null) {
+ try {
+ docos.close();
+ } catch (IOException ioe) {
+ ioexp = ioe;
+ } finally {
+ docos = null;
+ }
+ if(ioexp != null) {
+ throw ioexp;
+ }
+ }
+ }
+ }
+
+ /* -----------------------------------------------------------
+ * Cleans each entiry in the filesystem cache.
+ */
+ private class CleanStrategy
+ implements Strategy
+ {
+ public boolean evaluate(Entry entry)
+ {
+ try {
+ entry.clean();
+ } catch(java.lang.Exception exp) {
+ // sorry! can do nothing about it.
+ }
+ return true;
+ }
+ }
+
+ /* -----------------------------------------------------------
+ * ReadOnly cache entry
+ */
+ private class Entry
+ {
+ private String name;
+ private boolean folder;
+ private long size;
+ private long time;
+ private File node; // data files only
+
+ public Entry(ZipEntry entry)
+ {
+ if(entry != null) {
+ name = entry.getName();
+ folder = entry.isDirectory();
+ size = entry.getSize();
+ time = entry.getTime();
+ // removes tail file separator from a folder name
+ if((folder == true) && (name.endsWith(SEPARATOR))) {
+ name = name.substring(
+ 0, name.length() - SEPARATOR.length());
+ }
+ } else {
+ // 'null' is special cace of root folder
+ name = "";
+ folder = true;
+ size = 0;
+ time = -1;
+ }
+ }
+
+ public boolean isReadOnly()
+ {
+ return true;
+ }
+
+ public boolean isFolder()
+ {
+ return folder;
+ }
+
+ public boolean isModified()
+ {
+ return false;
+ }
+
+ public String getName()
+ {
+ return name;
+ }
+
+ public long getSize()
+ {
+ return size;
+ }
+
+ public long getTime()
+ {
+ // ajust last modified time to the java.io.File
+ return (time >= 0)? time: 0;
+ }
+
+ public InputStream getInputStream()
+ throws FileNotFoundException
+ {
+ return (isFolder() == false)? new FileInputStream(getFile()): null;
+ }
+
+ public OutputStream getOutputStream()
+ throws IOException
+ {
+ return null;
+ }
+
+ public void rename(String name)
+ throws IOException
+ {
+// throw new IOException(
+// "cannot rename readonly file: " + getName()); // I18N
+ // BUG: this is the design bug. Cache has to mamage such kind
+ // of operation in order to keep the data integrity.
+ this.name = name;
+ }
+
+ public void save(ZipOutputStream arch)
+ throws IOException
+ {
+ InputStream is = null;
+ ZipEntry entry = new ZipEntry(
+ getName() + ((isFolder())? SEPARATOR: ""));
+ try {
+ if(isFolder()) {
+ // folder
+ entry.setMethod(ZipEntry.STORED);
+ entry.setSize(0);
+ CRC32 crc = new CRC32();
+ entry.setCrc(crc.getValue());
+ entry.setTime(getTime());
+ arch.putNextEntry(entry);
+ } else {
+ // file
+ if(isModified() == false)
+ entry.setTime(getTime());
+ else
+ entry.setTime(node.lastModified());
+ arch.putNextEntry(entry);
+ is = getInputStream();
+ FileUtil.copy(is, arch);
+ }
+ } finally {
+ // close streams
+ if(is != null) {
+ try {
+ is.close();
+ } catch(java.io.IOException ioe) {
+ // sorry! can do nothing about it.
+ }
+ }
+ if(arch != null)
+ arch.closeEntry();
+ }
+ }
+
+ public void clean()
+ throws IOException
+ {
+ if(node != null)
+ node.delete();
+ }
+
+ public String toString()
+ {
+ return (
+ ((isReadOnly())? "RO ": "RW ") +
+ ((isFolder())? "D": "F") +
+ " \"" + getName() + "\"");
+ }
+
+ /* package */ File getFile()
+ throws FileNotFoundException
+ {
+ if(node == null) {
+ try {
+ node = File.createTempFile(TMP_FILE_PREF, TMP_FILE_SUFX);
+ // copy the file from archive to the cache
+ OutputStream nos = null;
+ InputStream zis = null;
+ try {
+ ZipEntry entry = zipFile.getEntry(getName());
+ if(entry != null) {
+ // copy existing file to the cache
+ zis = zipFile.getInputStream(entry);
+ nos = new FileOutputStream(node);
+ FileUtil.copy(zis, nos);
+ }
+ } finally {
+ // close streams
+ if(nos != null) {
+ try {
+ nos.close();
+ } catch(java.io.IOException ioe) {
+ }
+ }
+ if(zis != null) {
+ try {
+ zis.close();
+ } catch(java.io.IOException ioe) {
+ }
+ }
+ }
+ } catch(java.lang.Exception exp) {
+ // delete cache file
+ if(node != null)
+ node.delete();
+ node = null;
+ throw new FileNotFoundException(
+ "cannot access file: " + getName()); // I18N
+ }
+ }
+ return node;
+ }
+
+ }
+
+ /* -----------------------------------------------------------
+ * ReadWrite cache entry
+ */
+ private class ReadWriteEntry
+ extends Entry
+ {
+ private boolean modified;
+
+ // 'null' is special cace of root folder
+ public ReadWriteEntry(ZipEntry entry)
+ {
+ super(entry);
+ }
+
+ public boolean isReadOnly()
+ {
+ return false;
+ }
+
+ public boolean isModified()
+ {
+ return modified;
+ }
+
+ public void rename(String name)
+ throws IOException
+ {
+ modified = true;
+ super.rename(name);
+ }
+
+ public OutputStream getOutputStream()
+ throws IOException
+ {
+ modified = true;
+ return (isFolder() == false)? new FileOutputStream(getFile()): null;
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystemBeanInfo.java b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystemBeanInfo.java
new file mode 100644
index 000000000000..28fa3697c83e
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/filesystem/OpenOfficeDocFileSystemBeanInfo.java
@@ -0,0 +1,128 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OpenOfficeDocFileSystemBeanInfo.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.filesystem;
+
+import java.awt.Image;
+import java.io.File;
+import java.beans.*;
+
+import org.openide.ErrorManager;
+import org.openide.filesystems.FileSystem;
+import org.openide.util.NbBundle;
+import org.openide.util.Utilities;
+
+/**
+ * Description of the OpenOffice.org Document filesystem.
+ *
+ * @author misha <misha@openoffice.org>
+ */
+public class OpenOfficeDocFileSystemBeanInfo
+ extends SimpleBeanInfo
+{
+ private static String ICONLOCATION =
+ "org/openoffice/netbeans/modules/office/resources";
+ private static String COLORICON16NAME =
+ ICONLOCATION + File.separator + "OpenOfficeDocFileSystemIcon.png";
+ private static String COLORICON32NAME =
+ ICONLOCATION + File.separator + "OpenOfficeDocFileSystemIcon32.png";
+
+ /**
+ * Retrives an additional bean information.
+ */
+ public BeanInfo[] getAdditionalBeanInfo()
+ {
+ try {
+ return new BeanInfo[] {
+ Introspector.getBeanInfo(FileSystem.class)
+ };
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+/*
+ // If you have a visual dialog to customize configuration of the
+ // filesystem:
+ public BeanDescriptor getBeanDescriptor()
+ {
+ return new BeanDescriptor(OpenOfficeDocFileSystem.class,
+ OpenOfficeDocFileSystemCustomizer.class);
+ }
+*/
+ /**
+ * Retrives bean property descriptors.
+ */
+ public PropertyDescriptor[] getPropertyDescriptors()
+ {
+ try {
+ // Included only to make it a writable property (it is read-only
+ // in FileSystem):
+ PropertyDescriptor readOnly = new PropertyDescriptor(
+ "readOnly", OpenOfficeDocFileSystem.class);
+ readOnly.setDisplayName(NbBundle.getMessage(
+ OpenOfficeDocFileSystemBeanInfo.class, "PROP_readOnly"));
+ readOnly.setShortDescription(NbBundle.getMessage(
+ OpenOfficeDocFileSystemBeanInfo.class, "HINT_readOnly"));
+
+ // This could be whatever properties you use to configure the
+ // filesystem:
+ PropertyDescriptor document = new PropertyDescriptor(
+ "Document", OpenOfficeDocFileSystem.class);
+ document.setDisplayName(NbBundle.getMessage(
+ OpenOfficeDocFileSystemBeanInfo.class, "PROP_document"));
+ document.setShortDescription(NbBundle.getMessage(
+ OpenOfficeDocFileSystemBeanInfo.class, "HINT_document"));
+ // Request to the property editor that it be permitted only to
+ // choose directories:
+ document.setValue("directories", Boolean.FALSE); // NOI18N
+ document.setValue("files", Boolean.TRUE); // NOI18N
+
+ return new PropertyDescriptor[] {readOnly, document};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+
+ /**
+ * Retrives an icon by the icon type.
+ */
+ public Image getIcon(int type)
+ {
+ if((type == BeanInfo.ICON_COLOR_16x16) ||
+ (type == BeanInfo.ICON_MONO_16x16)) {
+ return Utilities.loadImage(COLORICON16NAME);
+ } else {
+ return Utilities.loadImage(COLORICON32NAME);
+ }
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/Bundle.properties b/scripting/java/org/openoffice/netbeans/modules/office/loader/Bundle.properties
new file mode 100644
index 000000000000..a3bf47447607
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/Bundle.properties
@@ -0,0 +1,12 @@
+# Datasystems API
+#PROP_myProp=<name of my property>
+#HINT_myProp=<description of my property>
+#LBL_DataNode_exec_sheet=Execution
+#HINT_DataNode_exec_sheet=Properties pertaining to compiling, running, and debugging.
+LBL_loaderName=<display name of the data loader>
+# Datasystems API
+#PROP_myProp=<name of my property>
+#HINT_myProp=<description of my property>
+#LBL_DataNode_exec_sheet=Execution
+#HINT_DataNode_exec_sheet=Properties pertaining to compiling, running, and debugging.
+LBL_loaderName=<display name of the data loader>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoader.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoader.java
new file mode 100644
index 000000000000..b03e123b7d75
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoader.java
@@ -0,0 +1,115 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeDocumentDataLoader.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.io.IOException;
+import java.io.File;
+
+import org.openide.actions.*;
+import org.openide.filesystems.*;
+import org.openide.loaders.*;
+import org.openide.util.NbBundle;
+import org.openide.util.actions.SystemAction;
+
+import org.openoffice.netbeans.modules.office.actions.MountDocumentAction;
+
+/** Recognizes single files in the Repository as being of a certain type.
+ *
+ * @author tomaso
+ */
+public class OfficeDocumentDataLoader extends UniFileLoader {
+
+ public OfficeDocumentDataLoader() {
+ this("org.openoffice.netbeans.modules.office.loader.OfficeDocumentDataObject");
+ }
+
+ // Can be useful for subclasses:
+ protected OfficeDocumentDataLoader(String recognizedObjectClass) {
+ super(recognizedObjectClass);
+ }
+
+ protected String defaultDisplayName() {
+ return "Office Document";
+ }
+
+ protected void initialize() {
+ super.initialize();
+
+ ExtensionList extensions = new ExtensionList();
+ extensions.addExtension("sxw");
+ extensions.addExtension("sxc");
+ extensions.addExtension("sxd");
+ extensions.addExtension("sxi");
+ setExtensions(extensions);
+ }
+
+ protected FileObject findPrimaryFile(FileObject fo) {
+ ExtensionList extensions = getExtensions();
+ if (extensions.isRegistered(fo) == false)
+ return null;
+
+ File document = FileUtil.toFile(fo);
+ JarFileSystem jarFs = new JarFileSystem();
+
+ try {
+ jarFs.setJarFile(document);
+ }
+ catch (IOException e) {
+ // TopManager.getDefault().notify(new NotifyDescriptor.Exception(e, "asdf"));
+ return null;
+ }
+ catch (Exception e) {
+ return null;
+ }
+ return fo;
+ }
+
+ protected SystemAction[] defaultActions() {
+ return new SystemAction[] {
+ SystemAction.get(OpenAction.class),
+ // SystemAction.get(MountDocumentAction.class),
+ null,
+ SystemAction.get(CutAction.class),
+ SystemAction.get(CopyAction.class),
+ SystemAction.get(PasteAction.class),
+ null,
+ SystemAction.get(DeleteAction.class),
+ SystemAction.get(RenameAction.class),
+ null,
+ // SystemAction.get(ToolsAction.class),
+ SystemAction.get(PropertiesAction.class),
+ };
+ }
+
+ protected MultiDataObject createMultiObject(FileObject primaryFile) throws DataObjectExistsException, IOException {
+ return new OfficeDocumentDataObject(primaryFile, this);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoaderBeanInfo.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoaderBeanInfo.java
new file mode 100644
index 000000000000..d953058063a3
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataLoaderBeanInfo.java
@@ -0,0 +1,75 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeDocumentDataLoaderBeanInfo.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.awt.Image;
+import java.beans.*;
+
+import org.openide.ErrorManager;
+import org.openide.util.NbBundle;
+import org.openide.util.Utilities;
+
+public class OfficeDocumentDataLoaderBeanInfo extends SimpleBeanInfo {
+
+ // If you have additional properties:
+ /*
+ public PropertyDescriptor[] getPropertyDescriptors() {
+ try {
+ PropertyDescriptor myProp = new PropertyDescriptor("myProp", OfficeDocumentDataLoader.class);
+ myProp.setDisplayName(NbBundle.getMessage(OfficeDocumentDataLoaderBeanInfo.class, "PROP_myProp"));
+ myProp.setShortDescription(NbBundle.getMessage(OfficeDocumentDataLoaderBeanInfo.class, "HINT_myProp"));
+ return new PropertyDescriptor[] {myProp};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+ */
+
+ public BeanInfo[] getAdditionalBeanInfo() {
+ try {
+ // I.e. MultiFileLoader.class or UniFileLoader.class.
+ return new BeanInfo[] {Introspector.getBeanInfo(OfficeDocumentDataLoader.class.getSuperclass())};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+
+ public Image getIcon(int type) {
+ if (type == BeanInfo.ICON_COLOR_16x16 || type == BeanInfo.ICON_MONO_16x16) {
+ return Utilities.loadImage("org/openoffice/netbeans/modules/office/resources/OfficeIcon.gif");
+ } else {
+ return Utilities.loadImage("org/openoffice/netbeans/modules/office/resources/OfficeIcon32.gif");
+ }
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataNode.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataNode.java
new file mode 100644
index 000000000000..d0f722137e15
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataNode.java
@@ -0,0 +1,123 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeDocumentDataNode.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.awt.datatransfer.Transferable;
+import java.util.List;
+import java.io.*;
+
+import org.openide.loaders.*;
+import org.openide.nodes.*;
+import org.openide.util.NbBundle;
+import org.openide.filesystems.*;
+
+import org.openoffice.netbeans.modules.office.actions.OfficeDocumentCookie;
+import org.openoffice.netbeans.modules.office.nodes.OfficeDocumentChildren;
+
+/** A node to represent this object.
+ *
+ * @author tomaso
+ */
+public class OfficeDocumentDataNode extends DataNode {
+
+ public OfficeDocumentDataNode(OfficeDocumentDataObject obj) {
+ // this(obj, Children.LEAF);
+ this(obj, new OfficeDocumentChildren((OfficeDocumentCookie)
+ obj.getCookie(OfficeDocumentCookie.class)));
+ }
+
+ public OfficeDocumentDataNode(OfficeDocumentDataObject obj, Children ch) {
+ super(obj, ch);
+ setIconBase("/org/openoffice/netbeans/modules/office/resources/OfficeIcon");
+ }
+
+ protected OfficeDocumentDataObject getOfficeDocumentDataObject() {
+ return (OfficeDocumentDataObject)getDataObject();
+ }
+
+ // Allow for pasting of Script Parcels to Office Documents
+ protected void createPasteTypes(Transferable t, List ls) {
+ Node[] copies = NodeTransfer.nodes(t, NodeTransfer.COPY);
+
+ if (copies != null) {
+ for (int i = 0; i < copies.length; i++) {
+ if (copies[i] instanceof ParcelDataNode) {
+ File source = FileUtil.toFile(((ParcelDataNode)copies[i]).getDataObject().getPrimaryFile());
+ File target = FileUtil.toFile(getDataObject().getPrimaryFile());
+
+ if (source.exists() && source.canRead() &&
+ target.exists() && target.canWrite()) {
+ ls.add(new ParcelDataNode.ParcelPasteType((ParcelDataNode)copies[i], target, false));
+ }
+ }
+ }
+ }
+
+ Node[] moves = NodeTransfer.nodes(t, NodeTransfer.MOVE);
+ if (moves != null) {
+ for (int i = 0; i < moves.length; i++) {
+ if (moves[i] instanceof ParcelDataNode) {
+ File source = FileUtil.toFile(((ParcelDataNode)moves[i]).getDataObject().getPrimaryFile());
+ File target = FileUtil.toFile(getDataObject().getPrimaryFile());
+
+ if (source.exists() && source.canRead() &&
+ target.exists() && target.canWrite()) {
+ ls.add(new ParcelDataNode.ParcelPasteType((ParcelDataNode)moves[i], target, true));
+ }
+ }
+ }
+ }
+
+ // Also try superclass, but give it lower priority:
+ super.createPasteTypes(t, ls);
+ }
+
+ /* Example of adding Executor / Debugger / Arguments to node:
+ protected Sheet createSheet() {
+ Sheet sheet = super.createSheet();
+ Sheet.Set set = sheet.get(ExecSupport.PROP_EXECUTION);
+ if (set == null) {
+ set = new Sheet.Set();
+ set.setName(ExecSupport.PROP_EXECUTION);
+ set.setDisplayName(NbBundle.getMessage(OfficeDocumentDataNode.class, "LBL_DataNode_exec_sheet"));
+ set.setShortDescription(NbBundle.getMessage(OfficeDocumentDataNode.class, "HINT_DataNode_exec_sheet"));
+ }
+ ((ExecSupport)getCookie(ExecSupport.class)).addProperties(set);
+ // Maybe:
+ ((CompilerSupport)getCookie(CompilerSupport.class)).addProperties(set);
+ sheet.put(set);
+ return sheet;
+ }
+ */
+
+ // Don't use getDefaultAction(); just make that first in the data loader's getActions list
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataObject.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataObject.java
new file mode 100644
index 000000000000..7f013d122633
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/OfficeDocumentDataObject.java
@@ -0,0 +1,61 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeDocumentDataObject.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import org.openide.actions.*;
+import org.openide.cookies.*;
+import org.openide.filesystems.*;
+import org.openide.loaders.*;
+import org.openide.nodes.*;
+import org.openide.util.HelpCtx;
+
+import org.openoffice.netbeans.modules.office.actions.*;
+
+public class OfficeDocumentDataObject extends MultiDataObject {
+
+ public OfficeDocumentDataObject(FileObject pf, OfficeDocumentDataLoader loader) throws DataObjectExistsException {
+ super(pf, loader);
+ init();
+ }
+
+ private void init() {
+ CookieSet cookies = getCookieSet();
+ cookies.add(new OfficeDocumentSupport(this));
+ }
+
+ public HelpCtx getHelpCtx() {
+ return HelpCtx.DEFAULT_HELP;
+ }
+
+ protected Node createNodeDelegate() {
+ return new OfficeDocumentDataNode(this);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolder.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolder.java
new file mode 100644
index 000000000000..efc0869f0e4f
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolder.java
@@ -0,0 +1,140 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelContentsFolder.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.io.IOException;
+
+import org.openide.TopManager;
+import org.openide.NotifyDescriptor;
+import org.openide.ErrorManager;
+
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileLock;
+import org.openide.filesystems.FileUtil;
+import org.openide.filesystems.FileSystem;
+import org.openide.filesystems.Repository;
+
+import org.openide.loaders.DataObject;
+import org.openide.loaders.DataFolder;
+import org.openide.loaders.DataObjectExistsException;
+
+import org.openide.nodes.Node;
+import org.openide.util.datatransfer.NewType;
+
+import org.openoffice.netbeans.modules.office.actions.ParcelFolderCookie;
+import org.openoffice.netbeans.modules.office.utils.PackageRemover;
+
+public class ParcelContentsFolder extends DataFolder {
+ public ParcelContentsFolder(FileObject pf, ParcelContentsFolderDataLoader loader)
+ throws DataObjectExistsException {
+ super(pf, loader);
+ }
+
+ public Node createNodeDelegate() {
+ return new DataFolder.FolderNode() {
+ public NewType[] getNewTypes() {
+ NewType[] newtypes = new NewType[1];
+ newtypes[0] = new NewType() {
+ public String getName() {
+ return "New Script";
+ }
+
+ public void create() {
+ DataFolder contents = (DataFolder)getDataObject();
+ ParcelFolderCookie cookie =
+ (ParcelFolderCookie)contents.getFolder().
+ getCookie(ParcelFolderCookie.class);
+
+ String language = cookie.getLanguage();
+ ParcelContentsFolder.createEmptyScript(contents,
+ language);
+ }
+ };
+ return newtypes;
+ }
+ };
+ }
+
+ public static void createEmptyScript(DataFolder parent, String language) {
+ String sourceFile = "Templates/OfficeScripting/EmptyScript/Empty";
+
+ if (language.toLowerCase().equals("java")) {
+ sourceFile += ".java";
+ }
+ else if (language.toLowerCase().equals("beanshell")) {
+ sourceFile += ".bsh";
+ }
+ else {
+ NotifyDescriptor d = new NotifyDescriptor.Message(
+ "Language not defined for this Parcel Folder");
+ TopManager.getDefault().notify(d);
+ return;
+ }
+
+ FileSystem fs = Repository.getDefault().getDefaultFileSystem();
+ DataObject result = null;
+ try {
+ DataObject dObj = DataObject.find(fs.findResource(sourceFile));
+ result = dObj.createFromTemplate(parent);
+ }
+ catch (IOException ioe) {
+ ErrorManager.getDefault().notify(ioe);
+ }
+
+ FileObject fo = result.getPrimaryFile();
+ if (fo.getExt().equals("java")) {
+ FileLock lock = null;
+ try {
+ PackageRemover.removeDeclaration(FileUtil.toFile(fo));
+
+ // IssueZilla 11986 - rename the FileObject
+ // so the JavaNode is resynchronized
+ lock = fo.lock();
+ if (lock != null) {
+ fo.rename(lock, fo.getName(), fo.getExt());
+ }
+ }
+ catch (IOException ioe) {
+ NotifyDescriptor d = new NotifyDescriptor.Message(
+ "Error removing package declaration from file: " +
+ fo.getNameExt() +
+ ". You should manually remove this declaration " +
+ "before building the Parcel Recipe");
+ TopManager.getDefault().notify(d);
+ }
+ finally {
+ if (lock != null) {
+ lock.releaseLock();
+ }
+ }
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoader.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoader.java
new file mode 100644
index 000000000000..e041153efa0c
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoader.java
@@ -0,0 +1,85 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelContentsFolderDataLoader.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import org.openide.loaders.*;
+import org.openide.filesystems.FileObject;
+import org.openide.actions.*;
+import org.openide.util.NbBundle;
+import org.openide.util.actions.SystemAction;
+
+import org.openoffice.idesupport.zip.ParcelZipper;
+
+public class ParcelContentsFolderDataLoader extends UniFileLoader {
+
+ public ParcelContentsFolderDataLoader() {
+ this("org.openide.loaders.DataFolder");
+ }
+
+ protected ParcelContentsFolderDataLoader(String recognizedObjectClass) {
+ super(recognizedObjectClass);
+ }
+
+ protected String defaultDisplayName() {
+ return "Office Script Parcel Contents";
+ }
+
+ protected void initialize() {
+ super.initialize();
+ }
+
+ protected FileObject findPrimaryFile(FileObject fo) {
+ if (fo.isFolder() == false ||
+ fo.getName().equals(ParcelZipper.CONTENTS_DIRNAME) == false ||
+ fo.getFileObject(ParcelZipper.PARCEL_DESCRIPTOR_XML) == null)
+ return null;
+
+ return fo;
+ }
+
+ protected SystemAction[] defaultActions() {
+ return new SystemAction[] {
+ SystemAction.get(PasteAction.class),
+ SystemAction.get(NewAction.class),
+ // null,
+ // SystemAction.get(PropertiesAction.class),
+ };
+ }
+
+ protected MultiDataObject createMultiObject(FileObject primaryFile)
+ throws DataObjectExistsException {
+ return new ParcelContentsFolder(primaryFile, this);
+ }
+
+ protected MultiDataObject.Entry createPrimaryEntry(MultiDataObject obj, FileObject primaryFile) {
+ return new FileEntry.Folder(obj, primaryFile);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoaderBeanInfo.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoaderBeanInfo.java
new file mode 100644
index 000000000000..fafbe279d6be
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelContentsFolderDataLoaderBeanInfo.java
@@ -0,0 +1,79 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelContentsFolderDataLoaderBeanInfo.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.awt.Image;
+import java.beans.*;
+
+import org.openide.ErrorManager;
+import org.openide.util.NbBundle;
+import org.openide.util.Utilities;
+
+/** Description of {@link ParcelFolderDataLoader}.
+ *
+ * @author tomaso
+ */
+public class ParcelContentsFolderDataLoaderBeanInfo extends SimpleBeanInfo {
+
+ // If you have additional properties:
+ /*
+ public PropertyDescriptor[] getPropertyDescriptors() {
+ try {
+ PropertyDescriptor myProp = new PropertyDescriptor("myProp", ParcelFolderDataLoader.class);
+ myProp.setDisplayName(NbBundle.getMessage(ParcelFolderDataLoaderBeanInfo.class, "PROP_myProp"));
+ myProp.setShortDescription(NbBundle.getMessage(ParcelFolderDataLoaderBeanInfo.class, "HINT_myProp"));
+ return new PropertyDescriptor[] {myProp};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+ */
+
+ public BeanInfo[] getAdditionalBeanInfo() {
+ try {
+ // I.e. MultiFileLoader.class or UniFileLoader.class.
+ return new BeanInfo[] {Introspector.getBeanInfo(ParcelContentsFolderDataLoader.class.getSuperclass())};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+
+ public Image getIcon(int type) {
+ if (type == BeanInfo.ICON_COLOR_16x16 || type == BeanInfo.ICON_MONO_16x16) {
+ return Utilities.loadImage("org/openoffice/netbeans/modules/office/loaders/ParcelFolderDataIcon.gif");
+ } else {
+ return Utilities.loadImage("org/openoffice/netbeans/modules/office/loaders/ParcelFolderDataIcon32.gif");
+ }
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoader.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoader.java
new file mode 100644
index 000000000000..7c19575663f4
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoader.java
@@ -0,0 +1,92 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDataLoader.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.io.IOException;
+import java.io.File;
+
+import org.openide.actions.*;
+import org.openide.filesystems.*;
+import org.openide.loaders.*;
+import org.openide.util.NbBundle;
+import org.openide.util.actions.SystemAction;
+
+import org.openoffice.netbeans.modules.office.actions.*;
+import org.openoffice.idesupport.zip.ParcelZipper;
+
+/** Recognizes single files in the Repository as being of a certain type.
+ *
+ * @author tomaso
+ */
+public class ParcelDataLoader extends UniFileLoader {
+
+ public ParcelDataLoader() {
+ this("org.openoffice.netbeans.modules.office.loader.ParcelDataObject");
+ }
+
+ // Can be useful for subclasses:
+ protected ParcelDataLoader(String recognizedObjectClass) {
+ super(recognizedObjectClass);
+ }
+
+ protected String defaultDisplayName() {
+ return "Office Script Parcel";
+ }
+
+ protected void initialize() {
+ super.initialize();
+
+ ExtensionList extensions = new ExtensionList();
+ extensions.addExtension(ParcelZipper.PARCEL_EXTENSION);
+ setExtensions(extensions);
+ }
+
+ protected SystemAction[] defaultActions() {
+ return new SystemAction[] {
+ // SystemAction.get(MountParcelAction.class),
+ SystemAction.get(DeployParcelAction.class),
+ null,
+ SystemAction.get(CutAction.class),
+ SystemAction.get(CopyAction.class),
+ // SystemAction.get(PasteAction.class),
+ null,
+ SystemAction.get(DeleteAction.class),
+ SystemAction.get(RenameAction.class),
+ null,
+ // SystemAction.get(ToolsAction.class),
+ SystemAction.get(PropertiesAction.class),
+ };
+ }
+
+ protected MultiDataObject createMultiObject(FileObject primaryFile) throws DataObjectExistsException, IOException {
+ return new ParcelDataObject(primaryFile, this);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoaderBeanInfo.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoaderBeanInfo.java
new file mode 100644
index 000000000000..21237248a2ad
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataLoaderBeanInfo.java
@@ -0,0 +1,79 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDataLoaderBeanInfo.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.awt.Image;
+import java.beans.*;
+
+import org.openide.ErrorManager;
+import org.openide.util.NbBundle;
+import org.openide.util.Utilities;
+
+/** Description of {@link ParcelDataLoader}.
+ *
+ * @author tomaso
+ */
+public class ParcelDataLoaderBeanInfo extends SimpleBeanInfo {
+
+ // If you have additional properties:
+ /*
+ public PropertyDescriptor[] getPropertyDescriptors() {
+ try {
+ PropertyDescriptor myProp = new PropertyDescriptor("myProp", ParcelDataLoader.class);
+ myProp.setDisplayName(NbBundle.getMessage(ParcelDataLoaderBeanInfo.class, "PROP_myProp"));
+ myProp.setShortDescription(NbBundle.getMessage(ParcelDataLoaderBeanInfo.class, "HINT_myProp"));
+ return new PropertyDescriptor[] {myProp};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+ */
+
+ public BeanInfo[] getAdditionalBeanInfo() {
+ try {
+ // I.e. MultiFileLoader.class or UniFileLoader.class.
+ return new BeanInfo[] {Introspector.getBeanInfo(ParcelDataLoader.class.getSuperclass())};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+
+ public Image getIcon(int type) {
+ if (type == BeanInfo.ICON_COLOR_16x16 || type == BeanInfo.ICON_MONO_16x16) {
+ return Utilities.loadImage("org/openoffice/netbeans/modules/office/loaders/ParcelDataIcon.gif");
+ } else {
+ return Utilities.loadImage("org/openoffice/netbeans/modules/office/loaders/ParcelDataIcon32.gif");
+ }
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataNode.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataNode.java
new file mode 100644
index 000000000000..e773e1474a87
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataNode.java
@@ -0,0 +1,117 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDataNode.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.io.*;
+import java.awt.datatransfer.Transferable;
+import java.util.zip.*;
+
+import org.openide.loaders.*;
+import org.openide.nodes.*;
+import org.openide.filesystems.FileObject;
+import org.openide.util.NbBundle;
+import org.openide.util.datatransfer.*;
+import org.openide.ErrorManager;
+import org.openide.windows.OutputWriter;
+
+import org.openoffice.netbeans.modules.office.actions.ParcelCookie;
+
+/** A node to represent this object.
+ *
+ * @author tomaso
+ */
+public class ParcelDataNode extends DataNode {
+
+ public ParcelDataNode(ParcelDataObject obj) {
+ this(obj, Children.LEAF);
+ }
+
+ public ParcelDataNode(ParcelDataObject obj, Children ch) {
+ super(obj, ch);
+ setIconBase("/org/openoffice/netbeans/modules/office/resources/ParcelIcon");
+ }
+
+ protected ParcelDataObject getParcelDataObject() {
+ return (ParcelDataObject)getDataObject();
+ }
+
+ public static class ParcelPasteType extends PasteType {
+ ParcelDataNode sourceParcel = null;
+ File targetDocument = null;
+ boolean isCut = false;
+
+ public ParcelPasteType(ParcelDataNode sourceParcel,
+ File targetDocument, boolean isCut) {
+ this.sourceParcel = sourceParcel;
+ this.targetDocument = targetDocument;
+ this.isCut = isCut;
+ }
+
+ public Transferable paste() {
+ ParcelCookie parcelCookie =
+ (ParcelCookie)sourceParcel.getCookie(ParcelCookie.class);
+ parcelCookie.deploy(targetDocument);
+
+ if (isCut == true) {
+ FileObject fo = sourceParcel.getDataObject().getPrimaryFile();
+ try {
+ fo.delete();
+ }
+ catch (IOException ioe) {}
+ return ExTransferable.EMPTY;
+ }
+ else {
+ return null;
+ }
+ }
+ }
+
+ /* Example of adding Executor / Debugger / Arguments to node:
+ protected Sheet createSheet() {
+ Sheet sheet = super.createSheet();
+ Sheet.Set set = sheet.get(ExecSupport.PROP_EXECUTION);
+ if (set == null) {
+ set = new Sheet.Set();
+ set.setName(ExecSupport.PROP_EXECUTION);
+ set.setDisplayName(NbBundle.getMessage(ParcelDataNode.class, "LBL_DataNode_exec_sheet"));
+ set.setShortDescription(NbBundle.getMessage(ParcelDataNode.class, "HINT_DataNode_exec_sheet"));
+ }
+ ((ExecSupport)getCookie(ExecSupport.class)).addProperties(set);
+ // Maybe:
+ ((CompilerSupport)getCookie(CompilerSupport.class)).addProperties(set);
+ sheet.put(set);
+ return sheet;
+ }
+ */
+
+ // Don't use getDefaultAction(); just make that first in the data loader's getActions list
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataObject.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataObject.java
new file mode 100644
index 000000000000..89aaf89e7a56
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDataObject.java
@@ -0,0 +1,80 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDataObject.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import org.openide.actions.*;
+import org.openide.cookies.*;
+import org.openide.filesystems.FileObject;
+import org.openide.loaders.*;
+import org.openide.nodes.*;
+import org.openide.util.HelpCtx;
+
+import org.openoffice.netbeans.modules.office.actions.*;
+
+/** Represents a Parcel object in the Repository.
+ *
+ * @author tomaso
+ */
+public class ParcelDataObject extends MultiDataObject {
+
+ public ParcelDataObject(FileObject pf, ParcelDataLoader loader) throws DataObjectExistsException {
+ super(pf, loader);
+ init();
+ }
+
+ private void init() {
+ CookieSet cookies = getCookieSet();
+ cookies.add(new ParcelSupport(getPrimaryFile()));
+ }
+
+ public HelpCtx getHelpCtx() {
+ return HelpCtx.DEFAULT_HELP;
+ // If you add context help, change to:
+ // return new HelpCtx(ParcelDataObject.class);
+ }
+
+ protected Node createNodeDelegate() {
+ return new ParcelDataNode(this);
+ }
+
+ /* If you made an Editor Support you will want to add these methods:
+
+ final void addSaveCookie(SaveCookie save) {
+ getCookieSet().add(save);
+ }
+
+ final void removeSaveCookie(SaveCookie save) {
+ getCookieSet().remove(save);
+ }
+
+ */
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoader.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoader.java
new file mode 100644
index 000000000000..6744211c939c
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoader.java
@@ -0,0 +1,94 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDescriptorDataLoader.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.io.IOException;
+
+import org.openide.actions.*;
+import org.openide.filesystems.*;
+import org.openide.loaders.*;
+import org.openide.util.NbBundle;
+import org.openide.util.actions.SystemAction;
+
+import org.openoffice.idesupport.OfficeDocument;
+
+/** Recognizes single files in the Repository as being of a certain type.
+ *
+ * @author tomaso
+ */
+public class ParcelDescriptorDataLoader extends UniFileLoader {
+
+ public ParcelDescriptorDataLoader() {
+ this("org.openoffice.netbeans.modules.office.loader.ParcelDescriptorDataObject");
+ }
+
+ // Can be useful for subclasses:
+ protected ParcelDescriptorDataLoader(String recognizedObjectClass) {
+ super(recognizedObjectClass);
+ }
+
+ protected String defaultDisplayName() {
+ return OfficeDocument.OFFICE_PRODUCT_NAME + " Script Parcel Descriptor";
+ }
+
+ protected void initialize() {
+ super.initialize();
+
+ // ExtensionList extensions = new ExtensionList();
+ // extensions.addMimeType("text/x-parcel+xml");
+ // extensions.addExtension("pml");
+ getExtensions().addMimeType("text/x-parcel+xml");
+ // setExtensions(extensions);
+ }
+
+ protected SystemAction[] defaultActions() {
+ return new SystemAction[] {
+ SystemAction.get(OpenAction.class),
+ // SystemAction.get(GenerateParcelAction.class),
+ null,
+ SystemAction.get(CutAction.class),
+ SystemAction.get(CopyAction.class),
+ SystemAction.get(PasteAction.class),
+ null,
+ SystemAction.get(DeleteAction.class),
+ SystemAction.get(RenameAction.class),
+ null,
+ // SystemAction.get(SaveAsTemplateAction.class),
+ // null,
+ // SystemAction.get(ToolsAction.class),
+ SystemAction.get(PropertiesAction.class),
+ };
+ }
+
+ protected MultiDataObject createMultiObject(FileObject primaryFile) throws DataObjectExistsException, IOException {
+ return new ParcelDescriptorDataObject(primaryFile, this);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoaderBeanInfo.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoaderBeanInfo.java
new file mode 100644
index 000000000000..6893c6caff58
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataLoaderBeanInfo.java
@@ -0,0 +1,79 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDescriptorDataLoaderBeanInfo.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.awt.Image;
+import java.beans.*;
+
+import org.openide.ErrorManager;
+import org.openide.util.NbBundle;
+import org.openide.util.Utilities;
+
+/** Description of {@link ParcelDescriptorDataLoader}.
+ *
+ * @author tomaso
+ */
+public class ParcelDescriptorDataLoaderBeanInfo extends SimpleBeanInfo {
+
+ // If you have additional properties:
+ /*
+ public PropertyDescriptor[] getPropertyDescriptors() {
+ try {
+ PropertyDescriptor myProp = new PropertyDescriptor("myProp", ParcelDescriptorDataLoader.class);
+ myProp.setDisplayName(NbBundle.getMessage(ParcelDescriptorDataLoaderBeanInfo.class, "PROP_myProp"));
+ myProp.setShortDescription(NbBundle.getMessage(ParcelDescriptorDataLoaderBeanInfo.class, "HINT_myProp"));
+ return new PropertyDescriptor[] {myProp};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+ */
+
+ public BeanInfo[] getAdditionalBeanInfo() {
+ try {
+ // I.e. MultiFileLoader.class or UniFileLoader.class.
+ return new BeanInfo[] {Introspector.getBeanInfo(ParcelDescriptorDataLoader.class.getSuperclass())};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+
+ public Image getIcon(int type) {
+ if (type == BeanInfo.ICON_COLOR_16x16 || type == BeanInfo.ICON_MONO_16x16) {
+ return Utilities.loadImage("org/openoffice/netbeans/modules/office/loaders/ParcelDescriptorDataIcon.gif");
+ } else {
+ return Utilities.loadImage("org/openoffice/netbeans/modules/office/loaders/ParcelDescriptorDataIcon32.gif");
+ }
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataNode.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataNode.java
new file mode 100644
index 000000000000..853566176cac
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataNode.java
@@ -0,0 +1,84 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDescriptorDataNode.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import org.openide.loaders.*;
+import org.openide.nodes.*;
+import org.openide.util.NbBundle;
+
+import org.openoffice.netbeans.modules.office.nodes.*;
+import org.openoffice.netbeans.modules.office.actions.*;
+
+/** A node to represent this object.
+ *
+ * @author tomaso
+ */
+public class ParcelDescriptorDataNode extends DataNode {
+
+ public ParcelDescriptorDataNode(ParcelDescriptorDataObject obj) {
+ this(obj, Children.LEAF);
+ }
+
+ public ParcelDescriptorDataNode(ParcelDescriptorDataObject obj, Children ch) {
+ super(obj, ch);
+ setHidden(true);
+ setIconBase("/org/openoffice/netbeans/modules/office/resources/OfficeIcon");
+ }
+
+ protected ParcelDescriptorDataObject getParcelDescriptorDataObject() {
+ return (ParcelDescriptorDataObject)getDataObject();
+ }
+
+ public boolean canRename() {
+ return false;
+ }
+
+ /* Example of adding Executor / Debugger / Arguments to node:
+ protected Sheet createSheet() {
+ Sheet sheet = super.createSheet();
+ Sheet.Set set = sheet.get(ExecSupport.PROP_EXECUTION);
+ if (set == null) {
+ set = new Sheet.Set();
+ set.setName(ExecSupport.PROP_EXECUTION);
+ set.setDisplayName(NbBundle.getMessage(ParcelDescriptorDataNode.class, "LBL_DataNode_exec_sheet"));
+ set.setShortDescription(NbBundle.getMessage(ParcelDescriptorDataNode.class, "HINT_DataNode_exec_sheet"));
+ }
+ ((ExecSupport)getCookie(ExecSupport.class)).addProperties(set);
+ // Maybe:
+ ((CompilerSupport)getCookie(CompilerSupport.class)).addProperties(set);
+ sheet.put(set);
+ return sheet;
+ }
+ */
+
+ // Don't use getDefaultAction(); just make that first in the data loader's getActions list
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataObject.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataObject.java
new file mode 100644
index 000000000000..999227d8509c
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelDescriptorDataObject.java
@@ -0,0 +1,86 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDescriptorDataObject.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import org.openide.actions.*;
+import org.openide.cookies.*;
+import org.openide.filesystems.*;
+import org.openide.loaders.*;
+import org.openide.nodes.*;
+import org.openide.util.HelpCtx;
+
+import org.openoffice.netbeans.modules.office.actions.ParcelDescriptorEditorSupport;
+import org.openoffice.netbeans.modules.office.actions.ParcelDescriptorParserSupport;
+
+/** Represents a ParcelDescriptor object in the Repository.
+ *
+ * @author tomaso
+ */
+public class ParcelDescriptorDataObject extends MultiDataObject {
+
+ private boolean canParse = false;
+
+ public ParcelDescriptorDataObject(FileObject pf, ParcelDescriptorDataLoader loader) throws DataObjectExistsException {
+ super(pf, loader);
+ init();
+ }
+
+ private void init() {
+ FileObject fo = getPrimaryFile();
+ if (FileUtil.toFile(fo) != null)
+ canParse = true;
+
+ CookieSet cookies = getCookieSet();
+ cookies.add(new ParcelDescriptorEditorSupport(this));
+ if (canParse == true)
+ cookies.add(new ParcelDescriptorParserSupport(getPrimaryFile()));
+ }
+
+ public HelpCtx getHelpCtx() {
+ return HelpCtx.DEFAULT_HELP;
+ }
+
+ protected Node createNodeDelegate() {
+ if (canParse == true)
+ return new ParcelDescriptorDataNode(this);
+ else
+ return new ParcelDescriptorDataNode(this, Children.LEAF);
+ }
+
+ // If you made an Editor Support you will want to add these methods:
+ public final void addSaveCookie(SaveCookie save) {
+ getCookieSet().add(save);
+ }
+
+ public final void removeSaveCookie(SaveCookie save) {
+ getCookieSet().remove(save);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolder.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolder.java
new file mode 100644
index 000000000000..5776ef4b6311
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolder.java
@@ -0,0 +1,306 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelFolder.java,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.io.File;
+import java.io.IOException;
+import java.beans.PropertyEditor;
+import java.beans.PropertyEditorSupport;
+
+import org.openide.loaders.DataFolder;
+import org.openide.loaders.DataObject;
+import org.openide.loaders.DataFilter;
+import org.openide.loaders.DataObjectExistsException;
+
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileUtil;
+
+import org.openide.nodes.CookieSet;
+import org.openide.nodes.Node;
+import org.openide.nodes.PropertySupport;
+import org.openide.nodes.Sheet;
+import org.openide.util.HelpCtx;
+
+import org.openoffice.idesupport.filter.*;
+import org.openoffice.idesupport.zip.ParcelZipper;
+import org.openoffice.netbeans.modules.office.actions.ParcelFolderCookie;
+import org.openoffice.netbeans.modules.office.actions.ParcelFolderSupport;
+
+public class ParcelFolder extends DataFolder {
+
+ public static final String LANGUAGE_ATTRIBUTE = "language";
+
+ public ParcelFolder(FileObject pf, ParcelFolderDataLoader loader)
+ throws DataObjectExistsException {
+ super(pf, loader);
+ CookieSet cookies = getCookieSet();
+ cookies.add(new ParcelFolderSupport(this));
+ }
+
+ public Node createNodeDelegate() {
+ return new ParcelFolderNode(this, new ParcelFolderFilter());
+ }
+
+ public class ParcelFolderNode extends DataFolder.FolderNode {
+ private static final String LOCATION = "location";
+ private static final String FILTER = "filter";
+ private static final String LANGUAGE = LANGUAGE_ATTRIBUTE;
+ private static final String CLASSPATH = "classpath";
+
+ private File location;
+ private FileFilter filter;
+ private String language;
+ private String classpath;
+
+ private final FileFilter DEFAULT_FILTER = BinaryOnlyFilter.getInstance();
+
+ public ParcelFolderNode(ParcelFolder pf, DataFilter dataFilter) {
+ super(pf.createNodeChildren(dataFilter));
+
+ location = (File)pf.getPrimaryFile().getAttribute(LOCATION);
+ if (location == null)
+ location = FileUtil.toFile(pf.getPrimaryFile());
+
+ String name = (String)pf.getPrimaryFile().getAttribute(FILTER);
+ if (name == null)
+ filter = DEFAULT_FILTER;
+ else {
+ for (int i = 0; i < availableFilters.length; i++)
+ if (name.equals(availableFilters[i].toString()))
+ filter = availableFilters[i];
+ }
+
+ language = (String)pf.getPrimaryFile().getAttribute(LANGUAGE);
+
+ ParcelFolderCookie cookie =
+ (ParcelFolderCookie)pf.getCookie(ParcelFolderCookie.class);
+ String s = cookie.getClasspath();
+ if (s != null) {
+ classpath = s;
+ }
+ else {
+ classpath = ".";
+ cookie.setClasspath(classpath);
+ }
+ }
+
+ public File getTargetDir() {
+ return location;
+ }
+
+ public FileFilter getFileFilter() {
+ return filter;
+ }
+
+ public String getLanguage() {
+ if (language == null)
+ language = (String)getPrimaryFile().getAttribute(LANGUAGE);
+ return language;
+ }
+
+ public Sheet createSheet() {
+ Sheet sheet;
+ Sheet.Set props;
+ Node.Property prop;
+
+ sheet = super.createSheet();
+ props = sheet.get(Sheet.PROPERTIES);
+ if (props == null) {
+ props = Sheet.createPropertiesSet();
+ sheet.put(props);
+ }
+
+ // prop = createLocationProperty();
+ // props.put(prop);
+
+ prop = createFilterProperty();
+ props.put(prop);
+
+ prop = createFilterProperty();
+ props.put(prop);
+
+ // prop = createLanguageProperty();
+ // props.put(prop);
+
+ prop = createClasspathProperty();
+ props.put(prop);
+
+ return sheet;
+ }
+
+ private Node.Property createLocationProperty() {
+ Node.Property prop =
+ new PropertySupport.ReadWrite(LOCATION, File.class,
+ "Location", "Output location of Parcel Zip File") {
+ public void setValue(Object obj) {
+ if (obj instanceof File) {
+ location = (File)obj;
+ try {
+ getPrimaryFile().setAttribute(LOCATION, location);
+ }
+ catch (IOException ioe) {
+ }
+ }
+ }
+
+ public Object getValue() {
+ return location;
+ }
+ };
+ prop.setValue("files", Boolean.FALSE);
+ return prop;
+ }
+
+ private String[] languages = {"Java", "BeanShell"};
+
+ private Node.Property createLanguageProperty() {
+ Node.Property prop =
+ new PropertySupport.ReadWrite(LANGUAGE, String.class,
+ "Parcel Language", "Language of scripts in this Parcel") {
+ public void setValue(Object obj) {
+ if (obj instanceof String) {
+ language = (String)obj;
+
+ try {
+ getPrimaryFile().setAttribute(LANGUAGE, language);
+ }
+ catch (IOException ioe) {
+ }
+ }
+ }
+
+ public Object getValue() {
+ if (language == null)
+ language = (String)getPrimaryFile().getAttribute(LANGUAGE);
+ return language;
+ }
+
+ public PropertyEditor getPropertyEditor() {
+ return new PropertyEditorSupport() {
+ public String[] getTags() {
+ return languages;
+ }
+
+ public void setAsText(String text) {
+ for (int i = 0; i < languages.length; i++)
+ if (text.equals(languages[i]))
+ this.setValue(languages[i]);
+ }
+
+ public String getAsText() {
+ return (String)this.getValue();
+ }
+ };
+ }
+ };
+ return prop;
+ }
+
+ private FileFilter[] availableFilters = new FileFilter[] {
+ BinaryOnlyFilter.getInstance(), AllFilesFilter.getInstance()};
+
+ private Node.Property createFilterProperty() {
+ Node.Property prop =
+ new PropertySupport.ReadWrite(FILTER, String.class,
+ "File Filter", "Files to be included in Parcel") {
+ public void setValue(Object obj) {
+ if (obj instanceof FileFilter) {
+ filter = (FileFilter)obj;
+
+ try {
+ getPrimaryFile().setAttribute(FILTER, filter.toString());
+ }
+ catch (IOException ioe) {
+ }
+ }
+ }
+
+ public Object getValue() {
+ return filter;
+ }
+
+ public PropertyEditor getPropertyEditor() {
+ return new PropertyEditorSupport() {
+ public String[] getTags() {
+ String[] tags = new String[availableFilters.length];
+
+ for (int i = 0; i < availableFilters.length; i++)
+ tags[i] = availableFilters[i].toString();
+
+ return tags;
+ }
+
+ public void setAsText(String text) {
+ for (int i = 0; i < availableFilters.length; i++)
+ if (text.equals(availableFilters[i].toString()))
+ this.setValue(availableFilters[i]);
+ }
+
+ public String getAsText() {
+ return this.getValue().toString();
+ }
+ };
+ }
+ };
+ return prop;
+ }
+
+ private Node.Property createClasspathProperty() {
+ Node.Property prop =
+ new PropertySupport.ReadWrite(CLASSPATH, String.class,
+ "Classpath", "Classpath property for scripts in this parcel") {
+ public void setValue(Object obj) {
+ if (obj instanceof String) {
+ classpath = (String)obj;
+
+ ParcelFolderCookie cookie = (ParcelFolderCookie)
+ getDataObject().getCookie(ParcelFolderCookie.class);
+ cookie.setClasspath(classpath);
+ }
+ }
+
+ public Object getValue() {
+ return classpath;
+ }
+ };
+ return prop;
+ }
+ }
+
+ private class ParcelFolderFilter implements DataFilter {
+ public boolean acceptDataObject(DataObject dobj) {
+ String name = dobj.getPrimaryFile().getNameExt();
+ if (name.equals(ParcelZipper.PARCEL_DESCRIPTOR_XML))
+ return false;
+ return true;
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoader.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoader.java
new file mode 100644
index 000000000000..334e324fb010
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoader.java
@@ -0,0 +1,115 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelFolderDataLoader.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.io.IOException;
+import java.io.File;
+
+import org.openide.actions.*;
+import org.openide.filesystems.*;
+import org.openide.loaders.*;
+import org.openide.util.NbBundle;
+import org.openide.util.actions.SystemAction;
+
+import org.openoffice.idesupport.zip.ParcelZipper;
+import org.openoffice.netbeans.modules.office.actions.*;
+
+/** Recognizes single files in the Repository as being of a certain type.
+ *
+ * @author tomaso
+ */
+
+public class ParcelFolderDataLoader extends UniFileLoader {
+
+ public ParcelFolderDataLoader() {
+ this("org.openoffice.netbeans.modules.office.loader.ParcelFolder");
+ }
+
+ protected ParcelFolderDataLoader(String recognizedObjectClass) {
+ super(recognizedObjectClass);
+ }
+
+ protected String defaultDisplayName() {
+ return "Office Script Parcel Folder";
+ }
+
+ protected void initialize() {
+ super.initialize();
+ }
+
+ protected FileObject findPrimaryFile(FileObject fo) {
+ if (fo.isFolder() == false)
+ return null;
+
+ FileObject contents = fo.getFileObject(ParcelZipper.CONTENTS_DIRNAME);
+ if (contents == null)
+ return null;
+
+ FileObject descriptor = contents.getFileObject(ParcelZipper.PARCEL_DESCRIPTOR_XML);
+ if (descriptor == null)
+ return null;
+
+ return fo;
+ }
+
+ protected SystemAction[] defaultActions() {
+ return new SystemAction[] {
+ // SystemAction.get(OpenLocalExplorerAction.class),
+ // SystemAction.get(FindAction.class),
+ // null,
+ // SystemAction.get(FileSystemAction.class),
+ // null,
+ SystemAction.get(CompileParcelAction.class),
+ SystemAction.get(BuildParcelAction.class),
+ SystemAction.get(ConfigureParcelAction.class),
+ null,
+ SystemAction.get(CutAction.class),
+ SystemAction.get(CopyAction.class),
+ // SystemAction.get(PasteAction.class),
+ null,
+ SystemAction.get(DeleteAction.class),
+ SystemAction.get(RenameAction.class),
+ null,
+ // SystemAction.get(SaveAsTemplateAction.class),
+ // null,
+ // SystemAction.get(ToolsAction.class),
+ SystemAction.get(PropertiesAction.class),
+ };
+ }
+
+ protected MultiDataObject createMultiObject(FileObject primaryFile) throws DataObjectExistsException, IOException {
+ return new ParcelFolder(primaryFile, this);
+ }
+
+ protected MultiDataObject.Entry createPrimaryEntry(MultiDataObject obj, FileObject primaryFile) {
+ return new FileEntry.Folder(obj, primaryFile);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoaderBeanInfo.java b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoaderBeanInfo.java
new file mode 100644
index 000000000000..87a5b23a168e
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/loader/ParcelFolderDataLoaderBeanInfo.java
@@ -0,0 +1,79 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelFolderDataLoaderBeanInfo.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.loader;
+
+import java.awt.Image;
+import java.beans.*;
+
+import org.openide.ErrorManager;
+import org.openide.util.NbBundle;
+import org.openide.util.Utilities;
+
+/** Description of {@link ParcelFolderDataLoader}.
+ *
+ * @author tomaso
+ */
+public class ParcelFolderDataLoaderBeanInfo extends SimpleBeanInfo {
+
+ // If you have additional properties:
+ /*
+ public PropertyDescriptor[] getPropertyDescriptors() {
+ try {
+ PropertyDescriptor myProp = new PropertyDescriptor("myProp", ParcelFolderDataLoader.class);
+ myProp.setDisplayName(NbBundle.getMessage(ParcelFolderDataLoaderBeanInfo.class, "PROP_myProp"));
+ myProp.setShortDescription(NbBundle.getMessage(ParcelFolderDataLoaderBeanInfo.class, "HINT_myProp"));
+ return new PropertyDescriptor[] {myProp};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+ */
+
+ public BeanInfo[] getAdditionalBeanInfo() {
+ try {
+ // I.e. MultiFileLoader.class or UniFileLoader.class.
+ return new BeanInfo[] {Introspector.getBeanInfo(ParcelFolderDataLoader.class.getSuperclass())};
+ } catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+
+ public Image getIcon(int type) {
+ if (type == BeanInfo.ICON_COLOR_16x16 || type == BeanInfo.ICON_MONO_16x16) {
+ return Utilities.loadImage("org/openoffice/netbeans/modules/office/loaders/ParcelFolderDataIcon.gif");
+ } else {
+ return Utilities.loadImage("org/openoffice/netbeans/modules/office/loaders/ParcelFolderDataIcon32.gif");
+ }
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/nodes/OfficeDocumentChildren.java b/scripting/java/org/openoffice/netbeans/modules/office/nodes/OfficeDocumentChildren.java
new file mode 100644
index 000000000000..22a79eb69b32
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/nodes/OfficeDocumentChildren.java
@@ -0,0 +1,150 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeDocumentChildren.java,v $
+ * $Revision: 1.7 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.nodes;
+
+import java.io.IOException;
+import java.util.*;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import org.openide.nodes.*;
+import org.openide.actions.*;
+import org.openide.util.actions.SystemAction;
+import org.openide.util.HelpCtx;
+
+import org.openoffice.netbeans.modules.office.options.OfficeSettings;
+import org.openoffice.netbeans.modules.office.utils.NagDialog;
+import org.openoffice.netbeans.modules.office.actions.OfficeDocumentCookie;
+
+public class OfficeDocumentChildren extends Children.Keys
+ implements ChangeListener {
+
+ private OfficeDocumentCookie document = null;
+
+ public OfficeDocumentChildren(OfficeDocumentCookie cookie) {
+ document = cookie;
+ }
+
+ private void refreshKeys() {
+ if (document == null) {
+ setKeys(Collections.EMPTY_SET);
+ return;
+ }
+
+ Enumeration parcels = document.getParcels();
+ if (parcels.hasMoreElements() != true) {
+ setKeys(Collections.EMPTY_SET);
+ return;
+ }
+
+ ArrayList keys = new ArrayList();
+ while (parcels.hasMoreElements()) {
+ String parcel = (String)parcels.nextElement();
+ keys.add(parcel);
+ }
+ setKeys(keys);
+ }
+
+ protected void addNotify() {
+ super.addNotify();
+ document.addChangeListener(this);
+ refreshKeys();
+ }
+
+ protected void removeNotify() {
+ super.removeNotify();
+ document.removeChangeListener(this);
+ setKeys(Collections.EMPTY_SET);
+ }
+
+ protected Node[] createNodes(Object key) {
+ String name = (String)key;
+ return new Node[] {new ParcelNode(name)};
+ }
+
+ public void stateChanged(ChangeEvent e) {
+ refreshKeys();
+ }
+
+ private class ParcelNode extends AbstractNode {
+ private String name;
+
+ public ParcelNode(String name) {
+ super(Children.LEAF);
+ this.name = name;
+ init();
+ }
+
+ private void init() {
+ setIconBase("/org/openoffice/netbeans/modules/office/resources/ParcelIcon");
+
+ setName(name);
+ setDisplayName(name.substring(name.lastIndexOf("/") + 1));
+ setShortDescription(name);
+ }
+
+ protected SystemAction[] createActions() {
+ return new SystemAction[] {
+ SystemAction.get(DeleteAction.class),
+ };
+ }
+
+ public HelpCtx getHelpCtx() {
+ return HelpCtx.DEFAULT_HELP;
+ }
+
+ public boolean canDestroy() {
+ return true;
+ }
+
+ public void destroy() throws IOException {
+ OfficeSettings settings = OfficeSettings.getDefault();
+ String message = "If you already have this document open in " +
+ "Office, please close it before continuing. Click OK to " +
+ "delete this parcel.";
+
+ if (settings.getWarnBeforeParcelDelete() == true) {
+ NagDialog warning = NagDialog.createConfirmationDialog(
+ message, "Show this message in future", true);
+
+ boolean result = warning.show();
+
+ if (warning.getState() == false)
+ settings.setWarnBeforeParcelDelete(false);
+
+ if (result == false)
+ return;
+ }
+ super.destroy();
+ document.removeParcel(name);
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/nodes/ParcelDescriptorChildren.java b/scripting/java/org/openoffice/netbeans/modules/office/nodes/ParcelDescriptorChildren.java
new file mode 100644
index 000000000000..84a4c571becd
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/nodes/ParcelDescriptorChildren.java
@@ -0,0 +1,94 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelDescriptorChildren.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.nodes;
+
+import java.util.*;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Element;
+
+import org.openide.nodes.*;
+import org.openoffice.netbeans.modules.office.actions.ParcelDescriptorParserCookie;
+
+/** List of children of a containing node.
+ * Remember to document what your permitted keys are!
+ *
+ * @author tomaso
+ */
+public class ParcelDescriptorChildren extends Children.Keys implements ChangeListener {
+
+ private ParcelDescriptorParserCookie parserCookie = null;
+
+ public ParcelDescriptorChildren(ParcelDescriptorParserCookie cookie) {
+ parserCookie = cookie;
+ }
+
+ private void refreshKeys() {
+ NodeList nl;
+ int len;
+
+ if (parserCookie == null ||
+ (nl = parserCookie.getScriptElements()) == null ||
+ (len = nl.getLength()) == 0) {
+ setKeys(Collections.EMPTY_SET);
+ return;
+ }
+
+ ArrayList keys = new ArrayList(len);
+ for (int i = 0; i < len; i++)
+ keys.add(nl.item(i));
+ setKeys(keys);
+ }
+
+ protected void addNotify() {
+ super.addNotify();
+ parserCookie.addChangeListener(this);
+ refreshKeys();
+ }
+
+ protected void removeNotify() {
+ super.removeNotify();
+ parserCookie.removeChangeListener(this);
+ setKeys(Collections.EMPTY_SET);
+ }
+
+ protected Node[] createNodes(Object key) {
+ Element el = (Element)key;
+ System.out.println("element is: " + el);
+ return new Node[] {new ScriptNode(el)};
+ }
+
+ public void stateChanged(ChangeEvent e) {
+ refreshKeys();
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/nodes/ScriptNode.java b/scripting/java/org/openoffice/netbeans/modules/office/nodes/ScriptNode.java
new file mode 100644
index 000000000000..1676a326c492
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/nodes/ScriptNode.java
@@ -0,0 +1,212 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptNode.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.nodes;
+
+import org.w3c.dom.*;
+
+import org.openide.actions.*;
+import org.openide.nodes.*;
+import org.openide.util.HelpCtx;
+import org.openide.util.NbBundle;
+import org.openide.util.actions.SystemAction;
+
+/** A simple node with no children.
+ *
+ * @author tomaso
+ */
+public class ScriptNode extends AbstractNode {
+ private Element element;
+ private static final String LOGICAL_NAME = "logicalname";
+ private static final String LANGUAGE_NAME = "languagename";
+
+ public ScriptNode(Element element) {
+ super(Children.LEAF);
+ this.element = element;
+ init();
+ }
+
+ private void init() {
+ setIconBase("/org/openoffice/netbeans/modules/office/resources/OfficeIcon");
+ setDefaultAction(SystemAction.get(PropertiesAction.class));
+
+ NodeList nl = element.getElementsByTagName(LOGICAL_NAME);
+ Element nameElement = (Element)nl.item(0);
+
+ String name = nameElement.getAttribute("value");
+ setName(name);
+ setDisplayName(name.substring(name.lastIndexOf(".") + 1));
+ setShortDescription(name);
+ }
+
+ protected SystemAction[] createActions() {
+ return new SystemAction[] {
+ SystemAction.get(ToolsAction.class),
+ null,
+ SystemAction.get(PropertiesAction.class),
+ };
+ }
+
+ public HelpCtx getHelpCtx() {
+ return HelpCtx.DEFAULT_HELP;
+ }
+
+ // RECOMMENDED - handle cloning specially (so as not to invoke the overhead of FilterNode):
+ /*
+ public Node cloneNode() {
+ // Try to pass in similar constructor params to what you originally got:
+ return new ScriptNode();
+ }
+ */
+
+ protected Sheet createSheet() {
+ Sheet sheet = super.createSheet();
+ Sheet.Set props = sheet.get(Sheet.PROPERTIES);
+ if (props == null) {
+ props = Sheet.createPropertiesSet();
+ sheet.put(props);
+ }
+
+ org.openide.nodes.Node.Property prop = null;
+ if ((prop = getStringProperty(LOGICAL_NAME)) != null)
+ props.put(prop);
+
+ if ((prop = getStringProperty(LANGUAGE_NAME)) != null)
+ props.put(prop);
+
+ return sheet;
+ }
+
+ private org.openide.nodes.Node.Property getStringProperty(String name) {
+ NodeList nl = element.getElementsByTagName(name);
+ if(nl.getLength() != 1)
+ return null;
+
+ Element nameElement = (Element)nl.item(0);
+ String value = nameElement.getAttribute("value");
+
+ return new StringProperty(this, name, value);
+ }
+
+ private class StringProperty extends PropertySupport.ReadOnly {
+ private String name, value;
+ private ScriptNode sn;
+
+ public StringProperty(ScriptNode sn, String name, String value) {
+ super(value, String.class, name,
+ "The name of the java language method for this script");
+ this.sn = sn;
+ this.name = name;
+ this.value = value;
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ /* public void setValue(Object obj) {
+ System.out.println("Setting value to: " + obj.toString());
+
+ if ((value instanceof String) != true)
+ throw new IllegalArgumentException(name +
+ " property must be of type String");
+
+ value = obj.toString();
+ if (name.equals(LOGICAL_NAME)) {
+ sn.setName(value);
+ sn.setDisplayName(value.substring(value.lastIndexOf(".") + 1));
+ sn.setShortDescription(value);
+ }
+ } */
+ }
+
+ /* public boolean canRename() {
+ return true;
+ }
+
+ public void setName(String nue) {
+ // Update visible name, fire property changes:
+ super.setName(nue);
+ } */
+
+ /*
+ public boolean canDestroy() {
+ return true;
+ }
+ public void destroy() throws IOException {
+ // Actually remove the node itself and fire property changes:
+ super.destroy();
+ // perform additional actions, i.e. delete underlying object
+ } */
+
+ // Handle copying and cutting specially:
+ /*
+ public boolean canCopy() {
+ return true;
+ }
+ public boolean canCut() {
+ return true;
+ }
+ public Transferable clipboardCopy() {
+ // Add to, do not replace, the default node copy flavor:
+ ExTransferable et = ExTransferable.create(super.clipboardCopy());
+ et.put(new ExTransferable.Single(DataFlavor.stringFlavor) {
+ protected Object getData() {
+ return ScriptNode.this.getDisplayName();
+ }
+ });
+ return et;
+ }
+ public Transferable clipboardCut() {
+ // Add to, do not replace, the default node cut flavor:
+ ExTransferable et = ExTransferable.create(super.clipboardCut());
+ // This is not so useful because this node will not be destroyed afterwards
+ // (it is up to the paste type to decide whether to remove the "original",
+ // and it is not safe to assume that getData will only be called once):
+ et.put(new ExTransferable.Single(DataFlavor.stringFlavor) {
+ protected Object getData() {
+ return ScriptNode.this.getDisplayName();
+ }
+ });
+ return et;
+ }
+ */
+
+ // Permit user to customize whole node at once (instead of per-property):
+ /*
+ public boolean hasCustomizer() {
+ return true;
+ }
+ public Component getCustomizer() {
+ return new MyCustomizingPanel(this);
+ }
+ */
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/options/Bundle.properties b/scripting/java/org/openoffice/netbeans/modules/office/options/Bundle.properties
new file mode 100644
index 000000000000..b823204cb227
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/options/Bundle.properties
@@ -0,0 +1,13 @@
+# Options API
+LBL_settings=Office Settings
+PROP_OfficeDirectory=Path to Office installation
+HINT_OfficeDirectory=Path to the Office installation
+
+HINT_WarnBeforeDocDeploy=Pop up a dialog before deploying to a document
+PROP_WarnBeforeDocDeploy=Pop up a dialog before deploying to a document
+
+HINT_WarnAfterDirDeploy=Pop up a dialog after deploying to a directory
+PROP_WarnAfterDirDeploy=Pop up a dialog after deploying to a directory
+
+HINT_WarnBeforeMount=Warn before mounting Office Scripting Framework support jar
+PROP_WarnBeforeMount=Warn before mounting Office Scripting Framework support jar
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettings.java b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettings.java
new file mode 100644
index 000000000000..d4123727baf1
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettings.java
@@ -0,0 +1,136 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeSettings.java,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.options;
+
+import java.util.Hashtable;
+import java.util.Enumeration;
+import java.io.File;
+import java.io.IOException;
+
+import org.openide.options.SystemOption;
+import org.openide.util.HelpCtx;
+import org.openide.util.NbBundle;
+
+import org.openoffice.idesupport.SVersionRCFile;
+import org.openoffice.idesupport.OfficeInstallation;
+
+/** Options for something or other.
+ *
+ * @author tomaso
+ */
+public class OfficeSettings extends SystemOption {
+
+ // private static final long serialVersionUID = ...;
+
+ public static final String OFFICE_DIRECTORY = "OfficeDirectory";
+ public static final String WARN_BEFORE_DOC_DEPLOY = "WarnBeforeDocDeploy";
+ public static final String WARN_BEFORE_PARCEL_DELETE = "WarnBeforeParcelDelete";
+ public static final String WARN_AFTER_DIR_DEPLOY = "WarnAfterDirDeploy";
+ public static final String WARN_BEFORE_MOUNT = "WarnBeforeMount";
+
+ protected void initialize() {
+ super.initialize();
+
+ setWarnBeforeDocDeploy(true);
+ setWarnBeforeParcelDelete(true);
+ setWarnAfterDirDeploy(true);
+ setWarnBeforeMount(true);
+
+ if (getOfficeDirectory() == null) {
+ SVersionRCFile sversion = SVersionRCFile.createInstance();
+
+ try {
+ Enumeration enum = sversion.getVersions();
+ OfficeInstallation oi;
+
+ while (enum.hasMoreElements()) {
+ oi = (OfficeInstallation)enum.nextElement();
+ setOfficeDirectory(oi);
+ return;
+ }
+ }
+ catch (IOException ioe) {
+ }
+ }
+ }
+
+ public String displayName() {
+ return "Office Settings";
+ }
+
+ public HelpCtx getHelpCtx() {
+ return HelpCtx.DEFAULT_HELP;
+ }
+
+ public static OfficeSettings getDefault() {
+ return (OfficeSettings)findObject(OfficeSettings.class, true);
+ }
+
+ public OfficeInstallation getOfficeDirectory() {
+ return (OfficeInstallation)getProperty(OFFICE_DIRECTORY);
+ }
+
+ public void setOfficeDirectory(OfficeInstallation oi) {
+ putProperty(OFFICE_DIRECTORY, oi, true);
+ }
+
+ public boolean getWarnBeforeDocDeploy() {
+ return ((Boolean)getProperty(WARN_BEFORE_DOC_DEPLOY)).booleanValue();
+ }
+
+ public void setWarnBeforeDocDeploy(boolean value) {
+ putProperty(WARN_BEFORE_DOC_DEPLOY, new Boolean(value), true);
+ }
+
+ public boolean getWarnBeforeParcelDelete() {
+ return ((Boolean)getProperty(WARN_BEFORE_PARCEL_DELETE)).booleanValue();
+ }
+
+ public void setWarnBeforeParcelDelete(boolean value) {
+ putProperty(WARN_BEFORE_PARCEL_DELETE, new Boolean(value), true);
+ }
+
+ public boolean getWarnAfterDirDeploy() {
+ return ((Boolean)getProperty(WARN_AFTER_DIR_DEPLOY)).booleanValue();
+ }
+
+ public void setWarnAfterDirDeploy(boolean value) {
+ putProperty(WARN_AFTER_DIR_DEPLOY, new Boolean(value), true);
+ }
+
+ public boolean getWarnBeforeMount() {
+ return ((Boolean)getProperty(WARN_BEFORE_MOUNT)).booleanValue();
+ }
+
+ public void setWarnBeforeMount(boolean value) {
+ putProperty(WARN_BEFORE_MOUNT, new Boolean(value), true);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsBeanInfo.java b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsBeanInfo.java
new file mode 100644
index 000000000000..ac6a69d178bf
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsBeanInfo.java
@@ -0,0 +1,150 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeSettingsBeanInfo.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.options;
+
+import java.awt.Image;
+import java.awt.Component;
+import javax.swing.event.ChangeListener;
+import javax.swing.event.ChangeEvent;
+import java.beans.*;
+
+import org.openide.ErrorManager;
+import org.openide.util.NbBundle;
+import org.openide.util.Utilities;
+
+import org.openoffice.idesupport.OfficeInstallation;
+import org.openoffice.netbeans.modules.office.wizard.SelectPathPanel;
+
+/** Description of {@link OfficeSettings}.
+ *
+ * @author tomaso
+ */
+public class OfficeSettingsBeanInfo extends SimpleBeanInfo {
+
+ public PropertyDescriptor[] getPropertyDescriptors() {
+ try {
+ PropertyDescriptor[] props = new PropertyDescriptor[] {
+ new PropertyDescriptor(OfficeSettings.OFFICE_DIRECTORY,
+ OfficeSettings.class,
+ "get" + OfficeSettings.OFFICE_DIRECTORY,
+ "set" + OfficeSettings.OFFICE_DIRECTORY),
+ new PropertyDescriptor(OfficeSettings.WARN_BEFORE_DOC_DEPLOY,
+ OfficeSettings.class,
+ "get" + OfficeSettings.WARN_BEFORE_DOC_DEPLOY,
+ "set" + OfficeSettings.WARN_BEFORE_DOC_DEPLOY),
+ new PropertyDescriptor(OfficeSettings.WARN_BEFORE_PARCEL_DELETE,
+ OfficeSettings.class,
+ "get" + OfficeSettings.WARN_BEFORE_PARCEL_DELETE,
+ "set" + OfficeSettings.WARN_BEFORE_PARCEL_DELETE),
+ new PropertyDescriptor(OfficeSettings.WARN_AFTER_DIR_DEPLOY,
+ OfficeSettings.class,
+ "get" + OfficeSettings.WARN_AFTER_DIR_DEPLOY,
+ "set" + OfficeSettings.WARN_AFTER_DIR_DEPLOY),
+ new PropertyDescriptor(OfficeSettings.WARN_BEFORE_MOUNT,
+ OfficeSettings.class,
+ "get" + OfficeSettings.WARN_BEFORE_MOUNT,
+ "set" + OfficeSettings.WARN_BEFORE_MOUNT)
+ };
+
+ props[0].setDisplayName(NbBundle.getMessage(
+ OfficeSettingsBeanInfo.class, "PROP_OfficeDirectory"));
+ props[0].setShortDescription(NbBundle.getMessage(
+ OfficeSettingsBeanInfo.class, "HINT_OfficeDirectory"));
+ props[0].setPropertyEditorClass(OfficeDirectoryEditor.class);
+
+ props[1].setDisplayName(NbBundle.getMessage(
+ OfficeSettingsBeanInfo.class, "PROP_WarnBeforeDocDeploy"));
+ props[1].setShortDescription(NbBundle.getMessage(
+ OfficeSettingsBeanInfo.class, "HINT_WarnBeforeDocDeploy"));
+ props[1].setHidden(true);
+
+ props[2].setDisplayName(NbBundle.getMessage(
+ OfficeSettingsBeanInfo.class, "PROP_WarnAfterDirDeploy"));
+ props[2].setShortDescription(NbBundle.getMessage(
+ OfficeSettingsBeanInfo.class, "HINT_WarnAfterDirDeploy"));
+ props[2].setHidden(true);
+
+ props[3].setDisplayName(NbBundle.getMessage(
+ OfficeSettingsBeanInfo.class, "PROP_WarnBeforeMount"));
+ props[3].setShortDescription(NbBundle.getMessage(
+ OfficeSettingsBeanInfo.class, "HINT_WarnBeforeMount"));
+ props[3].setHidden(true);
+
+ return props;
+ }
+ catch (IntrospectionException ie) {
+ ErrorManager.getDefault().notify(ie);
+ return null;
+ }
+ }
+
+ public Image getIcon(int type) {
+ if (type == BeanInfo.ICON_COLOR_16x16 || type == BeanInfo.ICON_MONO_16x16) {
+ return Utilities.loadImage("/org/openoffice/netbeans/modules/office/options/OfficeSettingsIcon.gif");
+ } else {
+ return Utilities.loadImage("/org/openoffice/netbeans/modules/office/options/OfficeSettingsIcon32.gif");
+ }
+ }
+
+ public static class OfficeDirectoryEditor extends PropertyEditorSupport
+ implements ChangeListener {
+
+ private SelectPathPanel panel;
+
+ public String getAsText () {
+ return ((OfficeInstallation)getValue()).getPath();
+ }
+
+ public void setAsText (String path) {
+ OfficeInstallation oi = new OfficeInstallation(path);
+
+ if (!oi.supportsFramework())
+ throw new IllegalArgumentException(path +
+ " is not a valid Office install");
+ else
+ setValue (oi);
+ }
+
+ public Component getCustomEditor() {
+ panel = new SelectPathPanel();
+ panel.addChangeListener(this);
+ return panel.getComponent();
+ }
+
+ public boolean supportsCustomEditor() {
+ return true;
+ }
+
+ public void stateChanged(ChangeEvent evt) {
+ setValue(panel.getSelectedPath());
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsIcon.gif b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsIcon.gif
new file mode 100644
index 000000000000..9bed8526705b
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsIcon.gif
Binary files differ
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsIcon32.gif b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsIcon32.gif
new file mode 100644
index 000000000000..65bfc82bc25f
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettingsIcon32.gif
Binary files differ
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/AppStorage.html b/scripting/java/org/openoffice/netbeans/modules/office/resources/AppStorage.html
new file mode 100644
index 000000000000..ee576e74ce61
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/AppStorage.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+
+<HTML>
+ <HEAD>
+ <TITLE></TITLE>
+ </HEAD>
+ <BODY>
+ <P>
+This wizard will let you mount the Office Application scripts directory
+ </BODY>
+</HTML>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/AppStorage.settings b/scripting/java/org/openoffice/netbeans/modules/office/resources/AppStorage.settings
new file mode 100644
index 000000000000..b682273020b3
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/AppStorage.settings
@@ -0,0 +1,7 @@
+<?xml version="1.0"?>
+<!DOCTYPE settings PUBLIC "-//NetBeans//DTD Session settings 1.0//EN" "http://www.netbeans.org/dtds/sessionsettings-1_0.dtd">
+<settings version="1.0">
+ <module name="org.openoffice.netbeans.modules.office/1"/>
+ <instanceof class="org.openide.filesystems.FileSystem"/>
+ <instance class="org.netbeans.core.ExLocalFileSystem"/>
+</settings>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/Bundle.properties b/scripting/java/org/openoffice/netbeans/modules/office/resources/Bundle.properties
new file mode 100644
index 000000000000..58989c2506b7
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/Bundle.properties
@@ -0,0 +1,23 @@
+Templates/OfficeScripting=Office Scripting
+Templates/OfficeScripting/parcel.xml=Script Parcel Descriptor
+Services/MIMEResolver/org-netbeans-modules-office-mime-resolver.xml=Script Parcel Descriptor File
+Templates=Templates
+Templates/OfficeScripting/HelloWorld=Hello World Example Script
+
+Templates/Mount/org-openoffice-netbeans-modules-office-resources-AppStorage.settings=Office Application Scripts
+Templates/Mount/org-openoffice-netbeans-modules-office-resources-OpenOfficeDocFileSystem.settings=OpenOffice.org document
+
+UI/Services/IDEConfiguration/ServerAndExternalToolSettings/org-openoffice-netbeans-modules-office-options-OfficeSettings.instance=Office Settings
+
+Services/org-openoffice-netbeans-modules-office-resources-OfficeSettings.settings=Office Settings
+
+PROP_OfficeDirectory=Office Installation Directory
+
+HINT_OfficeDirectory=Path to directory where Office is installed
+
+Templates/OfficeScripting/Parcel=Parcel Recipe
+Templates/OfficeScripting/EmptyScript=Empty Script
+Templates/OfficeScripting/EmptyScript/Empty.java=Java
+Templates/OfficeScripting/EmptyScript/Empty.bsh=BeanShell
+
+Menu/Help/office-scripting.url=&Office Scripting Framework Site
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/EmptyParcel.html b/scripting/java/org/openoffice/netbeans/modules/office/resources/EmptyParcel.html
new file mode 100644
index 000000000000..f3c478c42aa3
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/EmptyParcel.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+
+<HTML>
+ <HEAD>
+ <TITLE></TITLE>
+ </HEAD>
+ <BODY>
+ <P>
+This allows you to create an Empty Office Script.
+ </BODY>
+</HTML>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeIcon.gif b/scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeIcon.gif
new file mode 100644
index 000000000000..ec7507ef9e54
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeIcon.gif
Binary files differ
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeIcon32.gif b/scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeIcon32.gif
new file mode 100644
index 000000000000..94fdab1eba0c
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeIcon32.gif
Binary files differ
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeSettings.settings b/scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeSettings.settings
new file mode 100644
index 000000000000..df98da11659b
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/OfficeSettings.settings
@@ -0,0 +1,9 @@
+<?xml version="1.0"?>
+<!DOCTYPE settings PUBLIC "-//NetBeans//DTD Session settings 1.0//EN" "http://www.netbeans.org/dtds/sessionsettings-1_0.dtd">
+<settings version="1.0">
+ <module name="org.openoffice.netbeans.modules.office"/>
+ <instanceof class="org.openide.util.SharedClassObject"/>
+ <instanceof class="org.openide.util.SystemOption"/>
+ <instanceof class="org.openoffice.netbeans.modules.office.options.OfficeSettings"/>
+ <instance class="org.openoffice.netbeans.modules.office.options.OfficeSettings"/>
+</settings>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystem.html b/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystem.html
new file mode 100644
index 000000000000..5a879388bb28
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystem.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+
+<HTML>
+ <HEAD>
+ <TITLE></TITLE>
+ </HEAD>
+ <BODY>
+ <P>
+This allows you to mount OpenOffice.org document.
+ </BODY>
+</HTML>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystem.settings b/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystem.settings
new file mode 100644
index 000000000000..32a5bd490be1
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystem.settings
@@ -0,0 +1,7 @@
+<?xml version="1.0"?>
+<!DOCTYPE settings PUBLIC "-//NetBeans//DTD Session settings 1.0//EN" "http://www.netbeans.org/dtds/sessionsettings-1_0.dtd">
+<settings version="1.0">
+ <module name="org.openoffice.netbeans.modules.office/1"/>
+ <instanceof class="org.openide.filesystems.FileSystem"/>
+ <instance class="org.openoffice.netbeans.modules.office.filesystem.OpenOfficeDocFileSystem"/>
+</settings>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystemIcon.png b/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystemIcon.png
new file mode 100644
index 000000000000..a441019346f9
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystemIcon.png
Binary files differ
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystemIcon32.png b/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystemIcon32.png
new file mode 100644
index 000000000000..1b2ee21e6d9c
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystemIcon32.png
Binary files differ
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/ParcelIcon.gif b/scripting/java/org/openoffice/netbeans/modules/office/resources/ParcelIcon.gif
new file mode 100644
index 000000000000..a889c2614edf
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/ParcelIcon.gif
Binary files differ
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/ScriptParcel.html b/scripting/java/org/openoffice/netbeans/modules/office/resources/ScriptParcel.html
new file mode 100644
index 000000000000..c0f489032b9c
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/ScriptParcel.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+
+<HTML>
+ <HEAD>
+ <TITLE></TITLE>
+ </HEAD>
+ <BODY>
+ <P>
+This allows you to create a Hello World example Office Script.
+ </BODY>
+</HTML>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/ScriptParcelDescriptor.html b/scripting/java/org/openoffice/netbeans/modules/office/resources/ScriptParcelDescriptor.html
new file mode 100644
index 000000000000..d753d5dfe926
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/ScriptParcelDescriptor.html
@@ -0,0 +1,11 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+
+<HTML>
+ <HEAD>
+ <TITLE></TITLE>
+ </HEAD>
+ <BODY>
+ <P>
+This allows you to create a Office Script Parcel Descriptor File.
+ </BODY>
+</HTML>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/layer.xml b/scripting/java/org/openoffice/netbeans/modules/office/resources/layer.xml
new file mode 100644
index 000000000000..86b834d0d065
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/layer.xml
@@ -0,0 +1,98 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE filesystem PUBLIC "-//NetBeans//DTD Filesystem 1.1//EN" "http://www.netbeans.org/dtds/filesystem-1_1.dtd">
+<filesystem>
+ <folder name="Templates">
+ <attr name="SystemFileSystem.localizingBundle" stringvalue="org.openoffice.netbeans.modules.office.resources.Bundle"/>
+
+ <folder name="OfficeScripting">
+ <attr name="SystemFileSystem.localizingBundle" stringvalue="org.openoffice.netbeans.modules.office.resources.Bundle"/>
+ <folder name="Parcel">
+ <attr boolvalue="true" name="template"/>
+ <attr name="SystemFileSystem.localizingBundle" stringvalue="org.openoffice.netbeans.modules.office.resources.Bundle"/>
+ <attr name="SystemFileSystem.icon" urlvalue="nbresloc:/org/openoffice/netbeans/modules/office/resources/OfficeIcon.gif"/>
+ <attr name="templateWizardURL" urlvalue="nbresloc:/org/openoffice/netbeans/modules/office/resources/EmptyParcel.html"/>
+ <attr name="templateWizardIterator" newvalue="org.openoffice.netbeans.modules.office.wizard.ParcelContentsIterator"/>
+ <folder name="Contents">
+ <file name="parcel-descriptor.xml" url="templates/EmptyParcelDescriptor.xml_"/>
+ <!-- file name="Empty.java" url="templates/Empty.java_"/ -->
+ </folder>
+ </folder>
+ <folder name="EmptyScript">
+ <attr name="SystemFileSystem.localizingBundle" stringvalue="org.openoffice.netbeans.modules.office.resources.Bundle"/>
+ <file name="Empty.java" url="templates/Empty.java_">
+ <attr name="template" boolvalue="true"/>
+ <attr name="SystemFileSystem.localizingBundle" stringvalue="org.openoffice.netbeans.modules.office.resources.Bundle"/>
+ <attr name="templateWizardIterator" newvalue="org.openoffice.netbeans.modules.office.wizard.JavaScriptIterator"/>
+ </file>
+ <file name="Empty.bsh" url="templates/Empty.bsh_">
+ <attr name="template" boolvalue="true"/>
+ <attr name="SystemFileSystem.localizingBundle" stringvalue="org.openoffice.netbeans.modules.office.resources.Bundle"/>
+ </file>
+ </folder>
+ </folder>
+ <attr boolvalue="true" name="Ant/OfficeScripting"/>
+ <attr boolvalue="true" name="OfficeScripting/Other"/>
+
+ <!-- OpenOfficeDoc FileSystem BEGIN: -->
+ <!-- Uncomment to enable writable mounting of Office Documents
+ <folder name="Mount">
+ <attr name="org-netbeans-core-ExLocalFileSystem.settings/org-openoffice-netbeans-modules-office-resources-OpenOfficeDocFileSystem.settings"
+ boolvalue="true"/>
+ <attr name="org-openoffice-netbeans-modules-office-resources-OpenOfficeDocFileSystem.settings/VCS"
+ boolvalue="true"/>
+
+ <file name="org-openoffice-netbeans-modules-office-resources-OpenOfficeDocFileSystem.settings"
+ url="OpenOfficeDocFileSystem.settings">
+ <attr name="template"
+ boolvalue="true"/>
+ <attr name="SystemFileSystem.localizingBundle"
+ stringvalue="org.openoffice.netbeans.modules.office.resources.Bundle"/>
+ <attr name="SystemFileSystem.icon"
+ urlvalue="nbresloc:/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystemIcon.png"/>
+ <attr name="templateWizardIterator"
+ methodvalue="org.netbeans.core.ui.MountNode.iterator"/>
+ <attr name="templateWizardURL"
+ urlvalue="nbresloc:/org/openoffice/netbeans/modules/office/resources/OpenOfficeDocFileSystem.html"/>
+ </file>
+ </folder>
+ -->
+ <!-- OpenOfficeDoc FileSystem END: -->
+ </folder>
+
+ <folder name="Services">
+ <folder name="MIMEResolver">
+ <file name="org-netbeans-modules-office-mime-resolver.xml" url="mime-resolver.xml">
+ <attr name="SystemFileSystem.localizingBundle" stringvalue="org.openoffice.netbeans.modules.office.resources.Bundle"/>
+ <attr name="SystemFileSystem.icon" urlvalue="nbresloc:/org/openoffice/netbeans/modules/office/resources/OfficeIcon.gif"/>
+ </file>
+ </folder>
+ <file name="org-openoffice-netbeans-modules-office-resources-OfficeSettings.settings" url="OfficeSettings.settings">
+ <attr name="SystemFileSystem.localizingBundle" stringvalue="org.openoffice.netbeans.modules.office.resources.Bundle"/>
+ <attr name="SystemFileSystem.icon" urlvalue="nbresloc:/org/openoffice/netbeans/modules/office/resources/OfficeIcon.gif"/>
+ </file>
+ </folder>
+
+ <folder name="Menu">
+ <folder name="Help">
+ <attr name="submit-feedback-link.url/office-scripting.url" boolvalue="true"/>
+ <file name="office-scripting.url" url="office-scripting.url">
+ <attr name="SystemFileSystem.localizingBundle" stringvalue="org.openoffice.netbeans.modules.office.resources.Bundle"/>
+ <attr name="SystemFileSystem.icon" urlvalue="nbresloc:/org/openoffice/netbeans/modules/office/resources/webLink.gif"/>
+ </file>
+ </folder>
+ </folder>
+
+ <folder name="UI">
+ <folder name="Services">
+ <folder name="IDEConfiguration">
+ <folder name="ServerAndExternalToolSettings">
+ <file name="org-openoffice-netbeans-modules-office-resources-OfficeSettings.shadow">
+ <attr name="originalFile" stringvalue="Services/org-openoffice-netbeans-modules-office-resources-OfficeSettings.settings"/>
+ </file>
+ </folder>
+ </folder>
+ </folder>
+ </folder>
+
+ <attr boolvalue="true" name="Templates/Services"/>
+</filesystem>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/mime-resolver.xml b/scripting/java/org/openoffice/netbeans/modules/office/resources/mime-resolver.xml
new file mode 100644
index 000000000000..3e0f3053a81e
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/mime-resolver.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE MIME-resolver PUBLIC "-//NetBeans//DTD MIME Resolver 1.0//EN" "http://www.netbeans.org/dtds/mime-resolver-1_0.dtd">
+
+<MIME-resolver>
+
+ <!-- Resolve according to root element: -->
+ <file>
+ <ext name="xml"/>
+ <resolver mime="text/x-parcel+xml">
+ <xml-rule>
+ <element name="parcel"/>
+ </xml-rule>
+ </resolver>
+ </file>
+
+</MIME-resolver>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/office-scripting.url b/scripting/java/org/openoffice/netbeans/modules/office/resources/office-scripting.url
new file mode 100644
index 000000000000..f7be83c0eae4
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/office-scripting.url
@@ -0,0 +1 @@
+http://framework.openoffice.org/scripting/netbeans-devguide.html
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/Empty.bsh_ b/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/Empty.bsh_
new file mode 100644
index 000000000000..9354dba121b6
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/Empty.bsh_
@@ -0,0 +1,24 @@
+// If using XComponentContext need to uncomment import directive below:
+// import com.sun.star.uno.XComponentContext;
+
+// If using XDesktop need to uncomment import directive below:
+// import com.sun.star.frame.XDesktop;
+
+// If using XComponent need to uncomment import directive below:
+// import com.sun.star.frame.XModel;
+
+import drafts.com.sun.star.script.framework.runtime.XScriptContext;
+
+/* Use the XScriptContext variable "context" to access the document for
+ which this script was invoked. This variable will be initialised
+ automatically by the Scripting Framework when the script is invoked.
+
+ Methods available are:
+
+ context.getDocument() returns XModel
+ context.getDesktop() returns XDesktop
+ context.getComponentContext() returns XComponentContext
+*/
+
+// Uncomment to get the current document model
+// xmodel = context.getDocument();
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/Empty.java_ b/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/Empty.java_
new file mode 100644
index 000000000000..cf997b0f1082
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/Empty.java_
@@ -0,0 +1,27 @@
+// If using XComponentContext need to uncomment import directive below:
+// import com.sun.star.uno.XComponentContext;
+
+// If using XDesktop need to uncomment import directive below:
+// import com.sun.star.frame.XDesktop;
+
+// If using XComponent need to uncomment import directive below:
+// import com.sun.star.frame.XModel;
+
+import drafts.com.sun.star.script.framework.runtime.XScriptContext;
+
+public class Empty {
+
+ public void doMethod(XScriptContext xSc) {
+
+ /* Methods available from XScriptContext:
+ xSc.getDocument() returns XModel
+ xSc.getDesktop() returns XDesktop
+ xSc.getComponentContext() returns XComponentContext
+ */
+
+ // Uncomment to get the current document as a component
+ // XComponent xcomponent = xSc.getDocument();
+
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/EmptyParcelDescriptor.xml_ b/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/EmptyParcelDescriptor.xml_
new file mode 100644
index 000000000000..7c016c322e0a
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/EmptyParcelDescriptor.xml_
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel language="Java" xmlns:parcel="scripting.dtd">
+</parcel>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/HelloWorld.java_ b/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/HelloWorld.java_
new file mode 100644
index 000000000000..36e66aeeb20e
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/HelloWorld.java_
@@ -0,0 +1,41 @@
+// If using XMultiServiceFactory need to uncomment import directive below:
+//import com.sun.star.lang.XMultiServiceFactory;
+
+// If using XDesktop need to uncomment import directive below:
+//import com.sun.star.frame.XDesktop;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.*;
+import com.sun.star.text.*;
+
+import drafts.com.sun.star.script.framework.runtime.XScriptContext;
+
+
+public class HelloWorld {
+
+ public void printHello(XScriptContext xSc) {
+
+ /* Methods available from XScriptContext:
+ xSc.getDocument() returns XModel
+ xSc.getDesktop() returns XDesktop
+ xSc.getMultiComponentFactory() returns XMultiComponentFactory
+ */
+
+ // Getting the current document as a component
+ XComponent xcomponent = xSc.getDocument();
+
+ // Getting the text document object
+ XTextDocument xtextdocument = (XTextDocument) UnoRuntime.queryInterface(
+XTextDocument.class, xcomponent);
+
+ //Getting the text object
+ XText oText = xtextdocument.getText();
+
+ //Create a cursor object
+ XTextCursor oCursor = oText.createTextCursor();
+
+ // Print out Hello World
+ oText.insertString( oCursor, "**** HELLO ****", false );
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/ParcelDescriptor.xml_ b/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/ParcelDescriptor.xml_
new file mode 100644
index 000000000000..81ffce04e37d
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/templates/ParcelDescriptor.xml_
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<parcel>
+ <script language="Java" deploymentdir="java/HelloWorld">
+ <logicalname value="HelloWorld.printHello"/>
+ <languagename value="HelloWorld.printHello" location="HelloWorld.class"/>
+ </script>
+</parcel>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/resources/webLink.gif b/scripting/java/org/openoffice/netbeans/modules/office/resources/webLink.gif
new file mode 100755
index 000000000000..ae40f9af595f
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/resources/webLink.gif
Binary files differ
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/FrameworkJarChecker.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/FrameworkJarChecker.java
new file mode 100644
index 000000000000..eae95b6e9dd6
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/FrameworkJarChecker.java
@@ -0,0 +1,143 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: FrameworkJarChecker.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.beans.PropertyVetoException;
+
+import org.openide.filesystems.Repository;
+import org.openide.filesystems.FileSystem;
+import org.openide.filesystems.JarFileSystem;
+
+import org.openoffice.idesupport.SVersionRCFile;
+import org.openoffice.netbeans.modules.office.options.OfficeSettings;
+
+public class FrameworkJarChecker {
+
+ public static void mountDependencies() {
+ String unoilPath = SVersionRCFile.getPathForUnoil(
+ OfficeSettings.getDefault().getOfficeDirectory().getPath());
+
+ if (unoilPath == null)
+ return;
+
+ File unoilFile = new File(unoilPath + File.separator + "unoil.jar");
+ JarFileSystem jfs = new JarFileSystem();
+ try {
+ jfs.setJarFile(unoilFile);
+ }
+ catch (IOException ioe) {
+ return;
+ }
+ catch (PropertyVetoException pve) {
+ return;
+ }
+
+ FileSystem result;
+ try {
+ result =
+ Repository.getDefault().findFileSystem(jfs.getSystemName());
+ }
+ catch(Exception exp) {
+ result = null;
+ }
+ finally {
+ jfs.removeNotify();
+ }
+
+ if(result == null) {
+ // warnBeforeMount();
+ JarFileSystem newjfs = new JarFileSystem();
+ try {
+ newjfs.setJarFile(unoilFile);
+ }
+ catch (IOException ioe) {
+ return;
+ }
+ catch (PropertyVetoException pve) {
+ return;
+ }
+ Repository.getDefault().addFileSystem(newjfs);
+ newjfs.setHidden(true);
+ }
+ }
+
+ public static void unmountDependencies() {
+ String unoilPath = SVersionRCFile.getPathForUnoil(
+ OfficeSettings.getDefault().getOfficeDirectory().getPath());
+
+ if (unoilPath == null)
+ return;
+
+ File unoilFile = new File(unoilPath + File.separator + "unoil.jar");
+ JarFileSystem jfs = new JarFileSystem();
+ try {
+ jfs.setJarFile(unoilFile);
+ }
+ catch (IOException ioe) {
+ return;
+ }
+ catch (PropertyVetoException pve) {
+ return;
+ }
+
+ FileSystem result;
+ try {
+ result =
+ Repository.getDefault().findFileSystem(jfs.getSystemName());
+ if(result != null)
+ Repository.getDefault().removeFileSystem(result);
+ }
+ catch(Exception exp) {
+ }
+ }
+
+ private static void warnBeforeMount() {
+ OfficeSettings settings = OfficeSettings.getDefault();
+
+ if (settings.getWarnBeforeMount() == false)
+ return;
+
+ String message = "The Office Scripting Framework support jar file " +
+ "is not mounted, so Office scripts will not compile. NetBeans " +
+ "is going to mount this jar file automatically.";
+
+ String prompt = "Show this message in future.";
+
+ NagDialog warning = NagDialog.createInformationDialog(
+ message, prompt, true);
+
+ if (warning.getState() == false) {
+ settings.setWarnBeforeMount(false);
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/ManifestParser.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/ManifestParser.java
new file mode 100644
index 000000000000..9b64258a1663
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/ManifestParser.java
@@ -0,0 +1,100 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ManifestParser.java,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.utils;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.IOException;
+import java.io.File;
+
+import org.w3c.dom.Document;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXParseException;
+
+import org.openide.xml.XMLUtil;
+
+import com.sun.star.script.framework.container.XMLParser;
+import org.openoffice.netbeans.modules.office.options.OfficeSettings;
+import org.openoffice.idesupport.OfficeInstallation;
+
+public class ManifestParser implements XMLParser {
+
+ private static ManifestParser parser = null;
+
+ private ManifestParser() {
+ }
+
+ public static ManifestParser getManifestParser() {
+ if (parser == null) {
+ synchronized(ManifestParser.class) {
+ if (parser == null)
+ parser = new ManifestParser();
+ }
+ }
+ return parser;
+ }
+
+ public Document parse(InputStream inputStream) {
+ InputSource is;
+ Document result = null;
+
+ try {
+ OfficeInstallation oi = OfficeSettings.getDefault().getOfficeDirectory();
+ String id = oi.getURL("share/dtd/officedocument/1_0/");
+
+ is = new InputSource(inputStream);
+ is.setSystemId(id);
+
+ result = XMLUtil.parse(is, false, false, null, null);
+ }
+ catch (IOException ioe) {
+ System.out.println("IO Error parsing stream.");
+ return null;
+ }
+ catch (SAXParseException spe) {
+ System.out.println("Sax Error parsing stream: " + spe.getMessage());
+ System.out.println("\tPublicId: " + spe.getPublicId());
+ System.out.println("\tSystemId: " + spe.getSystemId());
+ return null;
+ }
+ catch (SAXException se) {
+ System.out.println("Sax Error parsing stream: " + se.getMessage());
+ return null;
+ }
+
+ return result;
+ }
+
+ public void write(Document doc, OutputStream out) throws IOException {
+ XMLUtil.write(doc, out, "");
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/NagDialog.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/NagDialog.java
new file mode 100644
index 000000000000..4befc9f089b9
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/NagDialog.java
@@ -0,0 +1,130 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: NagDialog.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.utils;
+
+import java.awt.BorderLayout;
+import java.awt.Dimension;
+
+import javax.swing.JPanel;
+import javax.swing.JOptionPane;
+import javax.swing.JCheckBox;
+import javax.swing.border.EmptyBorder;
+
+import org.openide.TopManager;
+import org.openide.NotifyDescriptor;
+
+public class NagDialog {
+
+ private NotifyDescriptor descriptor;
+ private JPanel panel;
+ private JCheckBox checkbox;
+
+ private NagDialog(String message, String prompt, boolean initialState,
+ int type) {
+ initUI(message, prompt, initialState, type);
+ }
+
+ public static NagDialog createInformationDialog(
+ String message, String prompt, boolean initialState) {
+ NagDialog result = new NagDialog(
+ message, prompt, initialState, JOptionPane.INFORMATION_MESSAGE);
+
+ result.setDescriptor(new NotifyDescriptor.Message(result.getPanel(),
+ NotifyDescriptor.PLAIN_MESSAGE));
+
+ return result;
+ }
+
+ public static NagDialog createConfirmationDialog(
+ String message, String prompt, boolean initialState) {
+ NagDialog result = new NagDialog(
+ message, prompt, initialState, JOptionPane.QUESTION_MESSAGE);
+
+ result.setDescriptor(new NotifyDescriptor.Confirmation(
+ result.getPanel(), NotifyDescriptor.OK_CANCEL_OPTION,
+ NotifyDescriptor.PLAIN_MESSAGE));
+
+ return result;
+ }
+
+ public boolean show() {
+ TopManager.getDefault().notify(descriptor);
+
+ if (descriptor.getValue() == NotifyDescriptor.OK_OPTION)
+ return true;
+ else
+ return false;
+ }
+
+ public boolean getState() {
+ return checkbox.isSelected();
+ }
+
+ private JPanel getPanel() {
+ return this.panel;
+ }
+
+ private void setDescriptor(NotifyDescriptor descriptor) {
+ this.descriptor = descriptor;
+ }
+
+ private void initUI(String message, String prompt, boolean initialState,
+ int type) {
+
+ this.panel = new JPanel();
+ JOptionPane optionPane = new JOptionPane(message, type, 0, null,
+ new Object[0], null)
+ {
+ public int getMaxCharactersPerLineCount() {
+ return 100;
+ }
+ };
+ optionPane.setUI(new javax.swing.plaf.basic.BasicOptionPaneUI() {
+ public Dimension getMinimumOptionPaneSize() {
+ if (minimumSize == null) {
+ return new Dimension(MinimumWidth, 50);
+ }
+ return new Dimension(minimumSize.width, 50);
+ }
+ });
+ optionPane.setWantsInput(false);
+
+ JPanel checkPanel = new JPanel();
+ checkbox = new JCheckBox(prompt, initialState);
+ checkPanel.setLayout(new BorderLayout());
+ checkPanel.setBorder(new EmptyBorder(0, 20, 0, 0));
+ checkPanel.add(checkbox, BorderLayout.WEST);
+
+ this.panel.setLayout(new BorderLayout());
+ this.panel.add(optionPane, BorderLayout.CENTER);
+ this.panel.add(checkPanel, BorderLayout.SOUTH);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/OfficeModule.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/OfficeModule.java
new file mode 100644
index 000000000000..ddc5672f1dc4
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/OfficeModule.java
@@ -0,0 +1,71 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: OfficeModule.java,v $
+ * $Revision: 1.7 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.utils;
+
+import org.openide.TopManager;
+import org.openide.WizardDescriptor;
+import org.openide.NotifyDescriptor;
+import org.openide.modules.ModuleInstall;
+
+import com.sun.star.script.framework.container.XMLParserFactory;
+import org.openoffice.idesupport.OfficeInstallation;
+import org.openoffice.netbeans.modules.office.wizard.InstallationPathDescriptor;
+import org.openoffice.netbeans.modules.office.options.OfficeSettings;
+
+public class OfficeModule extends ModuleInstall {
+
+ private static final long serialVersionUID = -8499324854301243852L;
+
+ public void installed () {
+ WizardDescriptor wiz = new InstallationPathDescriptor();
+ TopManager.getDefault().createDialog(wiz).show();
+
+ if(wiz.getValue() == NotifyDescriptor.OK_OPTION) {
+ OfficeInstallation oi = (OfficeInstallation)
+ wiz.getProperty(InstallationPathDescriptor.PROP_INSTALLPATH);
+
+ OfficeSettings settings = OfficeSettings.getDefault();
+ settings.setOfficeDirectory(oi);
+ }
+ FrameworkJarChecker.mountDependencies();
+ XMLParserFactory.setParser(ManifestParser.getManifestParser());
+ }
+
+ public void restored () {
+ FrameworkJarChecker.mountDependencies();
+ XMLParserFactory.setParser(ManifestParser.getManifestParser());
+ }
+
+ public boolean closing () {
+ FrameworkJarChecker.unmountDependencies();
+ return true;
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/PackageRemover.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/PackageRemover.java
new file mode 100644
index 000000000000..88170dbe194b
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/PackageRemover.java
@@ -0,0 +1,109 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: PackageRemover.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.utils;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.IOException;
+
+import org.openoffice.idesupport.zip.ParcelZipper;
+
+public class PackageRemover {
+ private PackageRemover() {
+ }
+
+ public static void removeDeclaration(File source) throws IOException {
+ File tmp = new File(source.getAbsolutePath() + ".tmp");
+
+ BufferedReader in = new BufferedReader(new FileReader(source));
+ BufferedWriter out = new BufferedWriter(new FileWriter(tmp));
+
+ try {
+ String line;
+ while ((line = in.readLine()) != null) {
+ if (line.startsWith("package")) {
+ String newDeclaration = evaluate(line);
+ if (newDeclaration != null) {
+ out.write(newDeclaration, 0, newDeclaration.length());
+ out.newLine();
+ }
+ }
+ else {
+ out.write(line, 0, line.length());
+ out.newLine();
+ }
+ }
+ }
+ finally {
+ if (in != null) {
+ in.close();
+ }
+ if (out != null) {
+ out.close();
+ }
+ }
+
+ if (source.delete() == false) {
+ tmp.delete();
+ throw new IOException("Could not overwrite " + source);
+ }
+ else {
+ tmp.renameTo(source);
+ }
+ }
+
+ public static String evaluate(String line) {
+
+ int idx = line.indexOf(ParcelZipper.CONTENTS_DIRNAME);
+ if (idx == -1)
+ return line;
+
+ idx = idx + ParcelZipper.CONTENTS_DIRNAME.length();
+ if (line.charAt(idx) == '.')
+ return "package " + line.substring(idx + 1);;
+
+ return null;
+ }
+
+ public static void main(String[] args) {
+ File source = new File(args[0]);
+
+ try {
+ removeDeclaration(source);
+ }
+ catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/utils/ZipMounter.java b/scripting/java/org/openoffice/netbeans/modules/office/utils/ZipMounter.java
new file mode 100644
index 000000000000..500449010372
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/utils/ZipMounter.java
@@ -0,0 +1,95 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ZipMounter.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.utils;
+
+import java.io.*;
+import java.util.zip.*;
+import java.beans.PropertyVetoException;
+
+import org.openide.filesystems.FileSystem;
+import org.openide.filesystems.Repository;
+
+import org.openoffice.netbeans.modules.office.filesystem.OpenOfficeDocFileSystem;
+
+public class ZipMounter
+{
+ private static ZipMounter mounter = null;
+
+ private ZipMounter() {
+ }
+
+ public static ZipMounter getZipMounter() {
+ if (mounter == null) {
+ synchronized(ZipMounter.class) {
+ if (mounter == null)
+ mounter = new ZipMounter();
+ }
+ }
+ return mounter;
+ }
+
+ public void mountZipFile(File zipfile)
+ throws IOException, PropertyVetoException
+ {
+ if (zipfile != null) {
+ addDocumentToRepository(zipfile, true);
+ }
+ }
+
+ private FileSystem addDocumentToRepository(File rootFile, boolean writeable)
+ throws IOException, PropertyVetoException
+ {
+ Repository repo = Repository.getDefault();
+ OpenOfficeDocFileSystem oofs;
+ oofs = (OpenOfficeDocFileSystem)getMountedDocument(rootFile);
+ if(oofs != null)
+ repo.removeFileSystem(oofs);
+ oofs = new OpenOfficeDocFileSystem();
+ oofs.setDocument(rootFile);
+ repo.addFileSystem(oofs);
+ return oofs;
+ }
+
+ /** @return FileSystem which has given jar file as its root or
+ * null if no such file system could be found in repository */
+ private FileSystem getMountedDocument(File rootFile)
+ {
+ if (rootFile == null)
+ return null;
+ FileSystem oofs = null;
+ try {
+ oofs = Repository.getDefault().findFileSystem(
+ OpenOfficeDocFileSystem.computeSystemName(rootFile));
+ } catch(Exception exp) {
+ }
+ return oofs;
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/Bundle.properties b/scripting/java/org/openoffice/netbeans/modules/office/wizard/Bundle.properties
new file mode 100644
index 000000000000..0e4f2bd100c7
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/Bundle.properties
@@ -0,0 +1,26 @@
+# Window System API
+
+# TopComponent
+LBL_component_name=<name of component>
+#LBL_mode_name=<name of mode>
+#LBL_workspace_name=<name of workspace>
+
+# WizardDescriptor
+# Dialog title:
+TITLE_wizard=Select Path to OpenOffice.org Installation
+
+# WizardDescriptor.Iterator
+# Label the sequence #. Appears at top of pane:
+# e.g. "Panel Name (1 of 3)"
+TITLE_x_of_y={0} of {1}
+# Provide list of steps to show in left pane:
+#LBL_step_1=Select First Thing
+#LBL_step_2=Configure Details
+
+# WizardDescriptor.Panel
+# Will appear in dialog title; see above
+TITLE_ParcelPropertiesVisualPanel=Parcel Recipe Properties
+TITLE_SelectPathVisualPanel=Path to OpenOffice.org
+
+# CallableSystemAction
+LBL_Action=Run Action
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/Bundle_en_US.properties b/scripting/java/org/openoffice/netbeans/modules/office/wizard/Bundle_en_US.properties
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/Bundle_en_US.properties
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathDescriptor.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathDescriptor.java
new file mode 100644
index 000000000000..f7c057cf48b3
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathDescriptor.java
@@ -0,0 +1,72 @@
+/*
+ * InstallationPathDescriptor.java
+ *
+ * Created on February 12, 2003
+ */
+
+package org.openoffice.netbeans.modules.office.wizard;
+
+import java.awt.Dimension;
+import java.awt.Toolkit;
+import java.net.URL;
+import java.net.MalformedURLException;
+
+import org.openide.TopManager;
+import org.openide.WizardDescriptor;
+import org.openide.util.NbBundle;
+
+/** A wizard descriptor.
+ *
+ * @author tomaso
+ */
+public class InstallationPathDescriptor extends WizardDescriptor {
+
+ private final InstallationPathIterator iterator;
+ public static final String PROP_INSTALLPATH = "INSTALLPATH";
+
+ /** Make a descriptor suited to use InstallationPathIterator.
+ * Sets up various wizard properties to follow recommended
+ * style guidelines.
+ */
+ public InstallationPathDescriptor() {
+ this(new InstallationPathIterator());
+ }
+ private InstallationPathDescriptor(InstallationPathIterator iterator) {
+ super(iterator);
+ this.iterator = iterator;
+ // Set title for the dialog:
+ setTitle(NbBundle.getMessage(InstallationPathDescriptor.class, "TITLE_wizard"));
+ // Make the left pane appear:
+ putProperty("WizardPanel_autoWizardStyle", Boolean.TRUE); // NOI18N
+ // Make the left pane show list of steps etc.:
+ putProperty("WizardPanel_contentDisplayed", Boolean.TRUE); // NOI18N
+ // Number the steps.
+ // putProperty("WizardPanel_contentNumbered", Boolean.TRUE); // NOI18N
+ /*
+ // Optional: make nonmodal.
+ setModal(false);
+ // (If you make the wizard nonmodal, you will call it differently;
+ // see InstallationPathAction for instructions.)
+ // Optional: show a help tab with special info about the pane:
+ putProperty("WizardPanel_helpDisplayed", Boolean.TRUE); // NOI18N
+ // Optional: set the size of the left pane explicitly:
+ putProperty("WizardPanel_leftDimension", new Dimension(100, 400)); // NOI18N
+ // Optional: if you want a special background image for the left pane:
+ try {
+ putProperty("WizardPanel_image", // NOI18N
+ Toolkit.getDefaultToolkit().getImage
+ (new URL("nbresloc:/org/openoffice/netbeans/modules/office/wizard/InstallationPathImage.gif"))); // NOI18N
+ } catch (MalformedURLException mfue) {
+ throw new IllegalStateException(mfue.toString());
+ }
+ */
+ }
+
+ // Called when user moves forward or backward etc.:
+ protected void updateState() {
+ super.updateState();
+ putProperty("WizardPanel_contentData", iterator.getSteps()); // NOI18N
+ putProperty("WizardPanel_contentSelectedIndex", new Integer(iterator.getIndex())); // NOI18N
+ }
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathIterator.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathIterator.java
new file mode 100644
index 000000000000..323175d4c5b8
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/InstallationPathIterator.java
@@ -0,0 +1,136 @@
+/*
+ * InstallationPathIterator.java
+ *
+ * Created on February 12, 2003
+ */
+
+package org.openoffice.netbeans.modules.office.wizard;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import org.openide.WizardDescriptor;
+import org.openide.util.NbBundle;
+
+/** A wizard iterator (sequence of panels).
+ * Used to create a wizard. Create one or more
+ * panels from template as needed too.
+ *
+ * @author tomaso
+ */
+public class InstallationPathIterator implements WizardDescriptor.Iterator {
+
+ // You should define what panels you want to use here:
+
+ protected WizardDescriptor.Panel[] createPanels() {
+ return new WizardDescriptor.Panel[] {
+ new SelectPathPanel()
+ };
+ }
+
+ // And the list of step names:
+
+ protected String[] createSteps() {
+ return new String[] {
+ "Select OpenOffice.org Installation"
+ };
+ }
+
+ // --- The rest probably does not need to be touched. ---
+
+ // Keep track of the panels and selected panel:
+
+ private transient int index = 0;
+ // Also package-accessible to descriptor:
+ protected final int getIndex() {
+ return index;
+ }
+ private transient WizardDescriptor.Panel[] panels = null;
+ protected final WizardDescriptor.Panel[] getPanels() {
+ if (panels == null) {
+ panels = createPanels();
+ }
+ return panels;
+ }
+
+ // Also the list of steps in the left pane:
+
+ private transient String[] steps = null;
+ // Also package-accessible to descriptor:
+ protected final String[] getSteps() {
+ if (steps == null) {
+ steps = createSteps();
+ }
+ return steps;
+ }
+
+ // --- WizardDescriptor.Iterator METHODS: ---
+ // Note that this is very similar to WizardDescriptor.Iterator, but with a
+ // few more options for customization. If you e.g. want to make panels appear
+ // or disappear dynamically, go ahead.
+
+ public String name() {
+ return NbBundle.getMessage(InstallationPathIterator.class, "TITLE_x_of_y",
+ new Integer(index + 1), new Integer(getPanels().length));
+ }
+
+ public boolean hasNext() {
+ return index < getPanels().length - 1;
+ }
+ public boolean hasPrevious() {
+ return index > 0;
+ }
+ public void nextPanel() {
+ if (!hasNext()) throw new NoSuchElementException();
+ index++;
+ }
+ public void previousPanel() {
+ if (!hasPrevious()) throw new NoSuchElementException();
+ index--;
+ }
+ public WizardDescriptor.Panel current() {
+ return getPanels()[index];
+ }
+
+ // If nothing unusual changes in the middle of the wizard, simply:
+ public final void addChangeListener(ChangeListener l) {}
+ public final void removeChangeListener(ChangeListener l) {}
+ // If something changes dynamically (besides moving between panels),
+ // e.g. the number of panels changes in response to user input, then
+ // uncomment the following and call when needed:
+ // fireChangeEvent();
+ /*
+ private transient Set listeners = new HashSet(1); // Set<ChangeListener>
+ public final void addChangeListener(ChangeListener l) {
+ synchronized (listeners) {
+ listeners.add(l);
+ }
+ }
+ public final void removeChangeListener(ChangeListener l) {
+ synchronized (listeners) {
+ listeners.remove(l);
+ }
+ }
+ protected final void fireChangeEvent() {
+ Iterator it;
+ synchronized (listeners) {
+ it = new HashSet(listeners).iterator();
+ }
+ ChangeEvent ev = new ChangeEvent(this);
+ while (it.hasNext()) {
+ ((ChangeListener)it.next()).stateChanged(ev);
+ }
+ }
+ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ listeners = new HashSet(1);
+ }
+ */
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/JavaScriptIterator.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/JavaScriptIterator.java
new file mode 100644
index 000000000000..114decafc614
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/JavaScriptIterator.java
@@ -0,0 +1,253 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: JavaScriptIterator.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.wizard;
+
+import java.awt.Component;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import javax.swing.JComponent;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import org.openide.ErrorManager;
+import org.openide.TopManager;
+import org.openide.NotifyDescriptor;
+import org.openide.WizardDescriptor;
+import org.openide.cookies.OpenCookie;
+import org.openide.cookies.SourceCookie;
+import org.openide.loaders.*;
+import org.openide.util.NbBundle;
+import org.openide.filesystems.*;
+
+import org.openoffice.idesupport.zip.ParcelZipper;
+import org.openoffice.netbeans.modules.office.loader.ParcelFolder;
+import org.openoffice.netbeans.modules.office.filesystem.OpenOfficeDocFileSystem;
+import org.openoffice.netbeans.modules.office.utils.PackageRemover;
+
+/** A template wizard iterator (sequence of panels).
+ * Used to fill in the second and subsequent panels in the New wizard.
+ * Associate this to a template inside a layer using the
+ * Sequence of Panels extra property.
+ * Create one or more panels from template as needed too.
+ *
+ * @author tomaso
+ */
+public class JavaScriptIterator implements TemplateWizard.Iterator {
+
+
+ // private static final long serialVersionUID = ...L;
+
+ // You should define what panels you want to use here:
+
+ protected WizardDescriptor.Panel[] createPanels() {
+ return new WizardDescriptor.Panel[] {
+ // keep the default 2nd panel:
+ wiz.targetChooser(),
+ };
+ }
+
+ // And the list of step names:
+
+ protected String[] createSteps() {
+ return new String[] {
+ null,
+ };
+ }
+
+ private DataFolder checkTarget(DataFolder folder) {
+ FileObject fo = folder.getPrimaryFile();
+
+ try {
+ FileSystem fs = fo.getFileSystem();
+
+ if (fs instanceof OpenOfficeDocFileSystem && fo.isRoot()) {
+ FileObject scripts =
+ fo.getFileObject(OpenOfficeDocFileSystem.SCRIPTS_ROOT);
+ if (scripts == null)
+ scripts =
+ fo.createFolder(OpenOfficeDocFileSystem.SCRIPTS_ROOT);
+
+ FileObject javafolder = scripts.getFileObject("java");
+ if (javafolder == null)
+ javafolder = scripts.createFolder("java");
+
+ DataFolder subfolder = new DataFolder(javafolder);
+ return subfolder;
+ }
+ }
+ catch (IOException ioe) {
+ /* do nothing, we will just return the folder we were passed in */
+ }
+ return folder;
+ }
+
+ public Set instantiate(TemplateWizard wiz) throws IOException {
+ String name = wiz.getTargetName();
+ DataFolder targetFolder = wiz.getTargetFolder();
+ targetFolder = checkTarget(targetFolder);
+
+ DataObject template = wiz.getTemplate();
+ DataObject result;
+ if (name == null) {
+ // Default name.
+ result = template.createFromTemplate(targetFolder);
+ } else {
+ result = template.createFromTemplate(targetFolder, name);
+ }
+
+ FileObject tmp = result.getPrimaryFile();
+ if (tmp.getExt().equals("java")) {
+ try {
+ PackageRemover.removeDeclaration(FileUtil.toFile(tmp));
+
+ // IssueZilla 11986 - rename the FileObject
+ // so the JavaNode is resynchronized
+ tmp.rename(tmp.lock(), tmp.getName(), tmp.getExt());
+ }
+ catch (IOException ioe) {
+ NotifyDescriptor d = new NotifyDescriptor.Message(
+ "Error removing package declaration from file: " +
+ tmp.getNameExt() +
+ ". You should manually remove this declaration " +
+ "before building the Parcel Recipe");
+ TopManager.getDefault().notify(d);
+ }
+ }
+
+ return Collections.singleton(result);
+ }
+
+ // --- The rest probably does not need to be touched. ---
+
+ private transient int index;
+ private transient WizardDescriptor.Panel[] panels;
+ private transient TemplateWizard wiz;
+
+ // You can keep a reference to the TemplateWizard which can
+ // provide various kinds of useful information such as
+ // the currently selected target name.
+ // Also the panels will receive wiz as their "settings" object.
+ public void initialize(TemplateWizard wiz) {
+ this.wiz = wiz;
+ index = 0;
+ panels = createPanels();
+ // Make sure list of steps is accurate.
+ String[] steps = createSteps();
+ for (int i = 0; i < panels.length; i++) {
+ Component c = panels[i].getComponent();
+ if (steps[i] == null) {
+ // Default step name to component name of panel.
+ // Mainly useful for getting the name of the target
+ // chooser to appear in the list of steps.
+ steps[i] = c.getName();
+ }
+ if (c instanceof JComponent) { // assume Swing components
+ JComponent jc = (JComponent)c;
+ // Step #.
+ jc.putClientProperty("WizardPanel_contentSelectedIndex", new Integer(i)); // NOI18N
+ // Step name (actually the whole list for reference).
+ jc.putClientProperty("WizardPanel_contentData", steps); // NOI18N
+ }
+ }
+ }
+ public void uninitialize(TemplateWizard wiz) {
+ this.wiz = null;
+ panels = null;
+ }
+
+ // --- WizardDescriptor.Iterator METHODS: ---
+ // Note that this is very similar to WizardDescriptor.Iterator, but with a
+ // few more options for customization. If you e.g. want to make panels appear
+ // or disappear dynamically, go ahead.
+
+ public String name() {
+ return "";
+ }
+
+ public boolean hasNext() {
+ return index < panels.length - 1;
+ }
+ public boolean hasPrevious() {
+ return index > 0;
+ }
+ public void nextPanel() {
+ if (!hasNext()) throw new NoSuchElementException();
+ index++;
+ }
+ public void previousPanel() {
+ if (!hasPrevious()) throw new NoSuchElementException();
+ index--;
+ }
+ public WizardDescriptor.Panel current() {
+ return panels[index];
+ }
+
+ // If nothing unusual changes in the middle of the wizard, simply:
+ public final void addChangeListener(ChangeListener l) {}
+ public final void removeChangeListener(ChangeListener l) {}
+ // If something changes dynamically (besides moving between panels),
+ // e.g. the number of panels changes in response to user input, then
+ // uncomment the following and call when needed:
+ // fireChangeEvent();
+ /*
+ private transient Set listeners = new HashSet(1); // Set<ChangeListener>
+ public final void addChangeListener(ChangeListener l) {
+ synchronized(listeners) {
+ listeners.add(l);
+ }
+ }
+ public final void removeChangeListener(ChangeListener l) {
+ synchronized(listeners) {
+ listeners.remove(l);
+ }
+ }
+ protected final void fireChangeEvent() {
+ Iterator it;
+ synchronized (listeners) {
+ it = new HashSet(listeners).iterator();
+ }
+ ChangeEvent ev = new ChangeEvent(this);
+ while (it.hasNext()) {
+ ((ChangeListener)it.next()).stateChanged(ev);
+ }
+ }
+ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ listeners = new HashSet(1);
+ }
+ */
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelContentsIterator.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelContentsIterator.java
new file mode 100644
index 000000000000..77048506dd5d
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelContentsIterator.java
@@ -0,0 +1,257 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ParcelContentsIterator.java,v $
+ * $Revision: 1.10 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package org.openoffice.netbeans.modules.office.wizard;
+
+import java.awt.Component;
+import java.io.File;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import javax.swing.JComponent;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import org.openide.TopManager;
+import org.openide.NotifyDescriptor;
+import org.openide.WizardDescriptor;
+import org.openide.cookies.OpenCookie;
+import org.openide.cookies.SourceCookie;
+import org.openide.loaders.*;
+import org.openide.util.NbBundle;
+import org.openide.filesystems.*;
+
+import com.sun.star.script.framework.container.ParcelDescriptor;
+import org.openoffice.idesupport.zip.ParcelZipper;
+import org.openoffice.netbeans.modules.office.loader.ParcelFolder;
+import org.openoffice.netbeans.modules.office.loader.ParcelContentsFolder;
+import org.openoffice.netbeans.modules.office.filesystem.OpenOfficeDocFileSystem;
+
+/** A template wizard iterator (sequence of panels).
+ * Used to fill in the second and subsequent panels in the New wizard.
+ * Associate this to a template inside a layer using the
+ * Sequence of Panels extra property.
+ * Create one or more panels from template as needed too.
+ *
+ * @author tomaso
+ */
+public class ParcelContentsIterator implements TemplateWizard.Iterator {
+
+
+ // private static final long serialVersionUID = ...L;
+
+ // You should define what panels you want to use here:
+
+ public static final String PROP_LANGUAGE =
+ ParcelFolder.LANGUAGE_ATTRIBUTE;
+
+ protected WizardDescriptor.Panel[] createPanels() {
+ return new WizardDescriptor.Panel[] {
+ // keep the default 2nd panel:
+ // wiz.targetChooser(),
+ new ParcelPropertiesPanel(),
+ };
+ }
+
+ // And the list of step names:
+
+ protected String[] createSteps() {
+ return new String[] {
+ // null,
+ "Parcel Properties",
+ };
+ }
+
+ private DataFolder checkTarget(DataFolder folder) {
+ FileObject fo = folder.getPrimaryFile();
+
+ try {
+ FileSystem fs = fo.getFileSystem();
+
+ if (fs instanceof OpenOfficeDocFileSystem && fo.isRoot()) {
+ FileObject scripts =
+ fo.getFileObject(OpenOfficeDocFileSystem.SCRIPTS_ROOT);
+ if (scripts == null)
+ scripts =
+ fo.createFolder(OpenOfficeDocFileSystem.SCRIPTS_ROOT);
+
+ FileObject javafolder = scripts.getFileObject("java");
+ if (javafolder == null)
+ javafolder = scripts.createFolder("java");
+
+ DataFolder subfolder = new DataFolder(javafolder);
+ return subfolder;
+ }
+ }
+ catch (IOException ioe) {
+ /* do nothing, we will just return the folder we were passed in */
+ }
+ return folder;
+ }
+
+ public Set instantiate(TemplateWizard wiz) throws IOException {
+ String name = wiz.getTargetName();
+ DataFolder targetFolder = wiz.getTargetFolder();
+ targetFolder = checkTarget(targetFolder);
+
+ String language = (String)wiz.getProperty(PROP_LANGUAGE);
+
+ DataObject template = wiz.getTemplate();
+ DataObject result;
+ if (name == null) {
+ // Default name.
+ result = template.createFromTemplate(targetFolder);
+ } else {
+ result = template.createFromTemplate(targetFolder, name);
+ }
+
+ FileObject recipe = result.getPrimaryFile();
+
+ FileObject contents =
+ recipe.getFileObject(ParcelZipper.CONTENTS_DIRNAME);
+
+ if (contents != null) {
+ File f = FileUtil.toFile(contents);
+ ParcelDescriptor pd = ParcelDescriptor.createParcelDescriptor(f);
+ pd.setLanguage(language);
+ pd.write();
+
+ DataFolder parent = DataFolder.findFolder(contents);
+ ParcelContentsFolder.createEmptyScript(parent, language);
+ }
+
+ return Collections.singleton(result);
+ }
+
+ // --- The rest probably does not need to be touched. ---
+
+ private transient int index;
+ private transient WizardDescriptor.Panel[] panels;
+ private transient TemplateWizard wiz;
+
+ // You can keep a reference to the TemplateWizard which can
+ // provide various kinds of useful information such as
+ // the currently selected target name.
+ // Also the panels will receive wiz as their "settings" object.
+ public void initialize(TemplateWizard wiz) {
+ this.wiz = wiz;
+ index = 0;
+ panels = createPanels();
+ // Make sure list of steps is accurate.
+ String[] steps = createSteps();
+ for (int i = 0; i < panels.length; i++) {
+ Component c = panels[i].getComponent();
+ if (steps[i] == null) {
+ // Default step name to component name of panel.
+ // Mainly useful for getting the name of the target
+ // chooser to appear in the list of steps.
+ steps[i] = c.getName();
+ }
+ if (c instanceof JComponent) { // assume Swing components
+ JComponent jc = (JComponent)c;
+ // Step #.
+ jc.putClientProperty("WizardPanel_contentSelectedIndex", new Integer(i)); // NOI18N
+ // Step name (actually the whole list for reference).
+ jc.putClientProperty("WizardPanel_contentData", steps); // NOI18N
+ }
+ }
+ }
+ public void uninitialize(TemplateWizard wiz) {
+ this.wiz = null;
+ panels = null;
+ }
+
+ // --- WizardDescriptor.Iterator METHODS: ---
+ // Note that this is very similar to WizardDescriptor.Iterator, but with a
+ // few more options for customization. If you e.g. want to make panels appear
+ // or disappear dynamically, go ahead.
+
+ public String name() {
+ return "";
+ }
+
+ public boolean hasNext() {
+ return index < panels.length - 1;
+ }
+ public boolean hasPrevious() {
+ return index > 0;
+ }
+ public void nextPanel() {
+ if (!hasNext()) throw new NoSuchElementException();
+ index++;
+ }
+ public void previousPanel() {
+ if (!hasPrevious()) throw new NoSuchElementException();
+ index--;
+ }
+ public WizardDescriptor.Panel current() {
+ return panels[index];
+ }
+
+ // If nothing unusual changes in the middle of the wizard, simply:
+ public final void addChangeListener(ChangeListener l) {}
+ public final void removeChangeListener(ChangeListener l) {}
+ // If something changes dynamically (besides moving between panels),
+ // e.g. the number of panels changes in response to user input, then
+ // uncomment the following and call when needed:
+ // fireChangeEvent();
+ /*
+ private transient Set listeners = new HashSet(1); // Set<ChangeListener>
+ public final void addChangeListener(ChangeListener l) {
+ synchronized(listeners) {
+ listeners.add(l);
+ }
+ }
+ public final void removeChangeListener(ChangeListener l) {
+ synchronized(listeners) {
+ listeners.remove(l);
+ }
+ }
+ protected final void fireChangeEvent() {
+ Iterator it;
+ synchronized (listeners) {
+ it = new HashSet(listeners).iterator();
+ }
+ ChangeEvent ev = new ChangeEvent(this);
+ while (it.hasNext()) {
+ ((ChangeListener)it.next()).stateChanged(ev);
+ }
+ }
+ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
+ in.defaultReadObject();
+ listeners = new HashSet(1);
+ }
+ */
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesPanel.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesPanel.java
new file mode 100644
index 000000000000..704bb6f66aed
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesPanel.java
@@ -0,0 +1,117 @@
+/*
+ * ParcelPropertiesPanel.java
+ *
+ * Created on January 15, 2003
+ */
+
+package org.openoffice.netbeans.modules.office.wizard;
+
+import java.awt.Component;
+import java.net.URL;
+import java.net.MalformedURLException;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import org.openide.WizardDescriptor;
+import org.openide.loaders.TemplateWizard;
+import org.openide.util.HelpCtx;
+import org.openide.util.NbBundle;
+
+/** A single panel descriptor for a wizard.
+ * You probably want to make a wizard iterator to hold it.
+ *
+ * @author tomaso
+ */
+public class ParcelPropertiesPanel implements WizardDescriptor.FinishPanel {
+
+ /** The visual component that displays this panel.
+ * If you need to access the component from this class,
+ * just use getComponent().
+ */
+ private ParcelPropertiesVisualPanel component;
+
+ /** Create the wizard panel descriptor. */
+ public ParcelPropertiesPanel() {
+ }
+
+ // Get the visual component for the panel. In this template, the component
+ // is kept separate. This can be more efficient: if the wizard is created
+ // but never displayed, or not all panels are displayed, it is better to
+ // create only those which really need to be visible.
+ public Component getComponent() {
+ if (component == null) {
+ component = new ParcelPropertiesVisualPanel(this);
+ }
+ return component;
+ }
+
+ public HelpCtx getHelp() {
+ // Show no Help button for this panel:
+ return HelpCtx.DEFAULT_HELP;
+ // If you have context help:
+ // return new HelpCtx(ParcelPropertiesPanel.class);
+ }
+
+ public boolean isValid() {
+ // If it is always OK to press Next or Finish, then:
+ return true;
+ // If it depends on some condition (form filled out...), then:
+ // return someCondition();
+ // and when this condition changes (last form field filled in...) then:
+ // fireChangeEvent();
+ // and uncomment the complicated stuff below.
+ }
+
+ public final void addChangeListener(ChangeListener l) {}
+ public final void removeChangeListener(ChangeListener l) {}
+ /*
+ private final Set listeners = new HashSet(1); // Set<ChangeListener>
+ public final void addChangeListener(ChangeListener l) {
+ synchronized (listeners) {
+ listeners.add(l);
+ }
+ }
+ public final void removeChangeListener(ChangeListener l) {
+ synchronized (listeners) {
+ listeners.remove(l);
+ }
+ }
+ protected final void fireChangeEvent() {
+ Iterator it;
+ synchronized (listeners) {
+ it = new HashSet(listeners).iterator();
+ }
+ ChangeEvent ev = new ChangeEvent(this);
+ while (it.hasNext()) {
+ ((ChangeListener)it.next()).stateChanged(ev);
+ }
+ }
+ */
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setLanguage(String language) {
+ this.language = language;
+ }
+
+ private String language = "Java";
+ private String name = null;
+
+ // You can use a settings object to keep track of state.
+ // Normally the settings object will be the WizardDescriptor,
+ // so you can use WizardDescriptor.getProperty & putProperty
+ // to store information entered by the user.
+ public void readSettings(Object settings) {
+ }
+
+ public void storeSettings(Object settings) {
+ TemplateWizard wiz = (TemplateWizard)settings;
+ wiz.setTargetName(name);
+ wiz.putProperty(ParcelContentsIterator.PROP_LANGUAGE, language);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.form b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.form
new file mode 100644
index 000000000000..0bfb183f5047
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.form
@@ -0,0 +1,74 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.0" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <Properties>
+ <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
+ <Dimension value="[500, 300]"/>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,75,0,0,1,-112"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Parcel Recipe Name"/>
+ </Properties>
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="0" gridY="0" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="12" insetsLeft="12" insetsBottom="11" insetsRight="2" anchor="17" weightX="0.0" weightY="0.0"/>
+ </Constraint>
+ </Constraints>
+ </Component>
+ <Component class="javax.swing.JTextField" name="recipeName">
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="recipeNameActionPerformed"/>
+ <EventHandler event="focusGained" listener="java.awt.event.FocusListener" parameters="java.awt.event.FocusEvent" handler="recipeNameFocusGained"/>
+ <EventHandler event="focusLost" listener="java.awt.event.FocusListener" parameters="java.awt.event.FocusEvent" handler="recipeNameFocusLost"/>
+ </Events>
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="1" gridY="0" gridWidth="0" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="12" insetsLeft="0" insetsBottom="11" insetsRight="11" anchor="10" weightX="1.0" weightY="0.0"/>
+ </Constraint>
+ </Constraints>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Initial Script Language"/>
+ </Properties>
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="0" gridY="1" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="12" insetsBottom="11" insetsRight="12" anchor="17" weightX="0.0" weightY="0.0"/>
+ </Constraint>
+ </Constraints>
+ </Component>
+ <Component class="javax.swing.JComboBox" name="languagesComboBox">
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="languagesComboBoxActionPerformed"/>
+ </Events>
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_InitCodePre" type="java.lang.String" value=""/>
+ <AuxValue name="JavaCodeGenerator_CreateCodePre" type="java.lang.String" value=""/>
+ <AuxValue name="JavaCodeGenerator_SerializeTo" type="java.lang.String" value=""/>
+ <AuxValue name="JavaCodeGenerator_CreateCodePost" type="java.lang.String" value=""/>
+ <AuxValue name="JavaCodeGenerator_CodeGeneration" type="java.lang.Integer" value="0"/>
+ </AuxValues>
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="1" gridY="1" gridWidth="0" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="11" insetsRight="11" anchor="17" weightX="0.0" weightY="0.0"/>
+ </Constraint>
+ </Constraints>
+ </Component>
+ <Container class="javax.swing.JPanel" name="jPanel1">
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="-1" gridY="-1" gridWidth="1" gridHeight="1" fill="3" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="1.0"/>
+ </Constraint>
+ </Constraints>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.DesignFlowLayout"/>
+ </Container>
+ </SubComponents>
+</Form>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.java
new file mode 100644
index 000000000000..fa3ea085dadb
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualPanel.java
@@ -0,0 +1,157 @@
+/*
+ * ParcelPropertiesVisualPanel.java
+ *
+ * Created on January 15, 2003
+ */
+
+package org.openoffice.netbeans.modules.office.wizard;
+
+import org.openide.util.NbBundle;
+
+/** A single panel for a wizard - the GUI portion.
+ *
+ * @author tomaso
+ */
+public class ParcelPropertiesVisualPanel extends javax.swing.JPanel {
+
+ /** The wizard panel descriptor associated with this GUI panel.
+ * If you need to fire state changes or something similar, you can
+ * use this handle to do so.
+ */
+ private final ParcelPropertiesPanel panel;
+
+ /** Create the wizard panel and set up some basic properties. */
+ public ParcelPropertiesVisualPanel(ParcelPropertiesPanel panel) {
+ this.panel = panel;
+ initComponents();
+
+ languagesComboBox.addItem("Java");
+ languagesComboBox.addItem("BeanShell");
+
+ // Provide a name in the title bar.
+ setName(NbBundle.getMessage(ParcelPropertiesVisualPanel.class, "TITLE_ParcelPropertiesVisualPanel"));
+ /*
+ // Optional: provide a special description for this pane.
+ // You must have turned on WizardDescriptor.WizardPanel_helpDisplayed
+ // (see descriptor in standard iterator template for an example of this).
+ try {
+ putClientProperty("WizardPanel_helpURL", // NOI18N
+ new URL("nbresloc:/org/openoffice/netbeans/modules/office/wizard/ParcelPropertiesVisualHelp.html")); // NOI18N
+ } catch (MalformedURLException mfue) {
+ throw new IllegalStateException(mfue.toString());
+ }
+ */
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ private void initComponents() {//GEN-BEGIN:initComponents
+ java.awt.GridBagConstraints gridBagConstraints;
+
+ jLabel1 = new javax.swing.JLabel();
+ recipeName = new javax.swing.JTextField();
+ jLabel2 = new javax.swing.JLabel();
+ languagesComboBox = new javax.swing.JComboBox();
+ jPanel1 = new javax.swing.JPanel();
+
+ setLayout(new java.awt.GridBagLayout());
+
+ setPreferredSize(new java.awt.Dimension(500, 300));
+ jLabel1.setText("Parcel Recipe Name");
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.gridx = 0;
+ gridBagConstraints.gridy = 0;
+ gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
+ gridBagConstraints.insets = new java.awt.Insets(12, 12, 11, 2);
+ add(jLabel1, gridBagConstraints);
+
+ recipeName.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ recipeNameActionPerformed(evt);
+ }
+ });
+
+ recipeName.addFocusListener(new java.awt.event.FocusAdapter() {
+ public void focusGained(java.awt.event.FocusEvent evt) {
+ recipeNameFocusGained(evt);
+ }
+ public void focusLost(java.awt.event.FocusEvent evt) {
+ recipeNameFocusLost(evt);
+ }
+ });
+
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.gridx = 1;
+ gridBagConstraints.gridy = 0;
+ gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
+ gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
+ gridBagConstraints.weightx = 1.0;
+ gridBagConstraints.insets = new java.awt.Insets(12, 0, 11, 11);
+ add(recipeName, gridBagConstraints);
+
+ jLabel2.setText("Initial Script Language");
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.gridx = 0;
+ gridBagConstraints.gridy = 1;
+ gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
+ gridBagConstraints.insets = new java.awt.Insets(0, 12, 11, 12);
+ add(jLabel2, gridBagConstraints);
+
+ languagesComboBox.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ languagesComboBoxActionPerformed(evt);
+ }
+ });
+
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.gridx = 1;
+ gridBagConstraints.gridy = 1;
+ gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
+ gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
+ gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
+ gridBagConstraints.insets = new java.awt.Insets(0, 0, 11, 11);
+ add(languagesComboBox, gridBagConstraints);
+
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
+ gridBagConstraints.weighty = 1.0;
+ add(jPanel1, gridBagConstraints);
+
+ }//GEN-END:initComponents
+
+ private void recipeNameFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_recipeNameFocusGained
+ recipeName.selectAll();
+ }//GEN-LAST:event_recipeNameFocusGained
+
+ private void recipeNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_recipeNameFocusLost
+ changeName();
+ }//GEN-LAST:event_recipeNameFocusLost
+
+ private void languagesComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_languagesComboBoxActionPerformed
+ String language = (String)languagesComboBox.getSelectedItem();
+ panel.setLanguage(language);
+ }//GEN-LAST:event_languagesComboBoxActionPerformed
+
+ private void recipeNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_recipeNameActionPerformed
+ changeName();
+ }//GEN-LAST:event_recipeNameActionPerformed
+
+ private void changeName() {
+ String name = recipeName.getText().trim();
+ if (name.equals(""))
+ name = null;
+ panel.setName(name);
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JTextField recipeName;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JPanel jPanel1;
+ private javax.swing.JComboBox languagesComboBox;
+ // End of variables declaration//GEN-END:variables
+
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathPanel.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathPanel.java
new file mode 100644
index 000000000000..77f1c0f8b2e5
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathPanel.java
@@ -0,0 +1,123 @@
+/*
+ * SelectPathPanel.java
+ *
+ * Created on February 12, 2003
+ */
+
+package org.openoffice.netbeans.modules.office.wizard;
+
+import java.awt.Component;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import javax.swing.event.ChangeEvent;
+import javax.swing.event.ChangeListener;
+
+import org.openide.WizardDescriptor;
+import org.openide.util.HelpCtx;
+import org.openide.util.NbBundle;
+
+import org.openoffice.netbeans.modules.office.options.OfficeSettings;
+import org.openoffice.idesupport.OfficeInstallation;
+import org.openoffice.idesupport.SVersionRCFile;
+
+/** A single panel descriptor for a wizard.
+ * You probably want to make a wizard iterator to hold it.
+ *
+ * @author tomaso
+ */
+public class SelectPathPanel implements WizardDescriptor.Panel /* .FinishPanel */ {
+
+ /** The visual component that displays this panel.
+ * If you need to access the component from this class,
+ * just use getComponent().
+ */
+ private SelectPathVisualPanel component;
+ private OfficeInstallation office;
+
+ /** Create the wizard panel descriptor. */
+ public SelectPathPanel() {
+ office = OfficeSettings.getDefault().getOfficeDirectory();
+
+ if (office == null) {
+ try {
+ office = SVersionRCFile.createInstance().getDefaultVersion();
+ }
+ catch (java.io.IOException ioe) {}
+ }
+ }
+
+ // Get the visual component for the panel. In this template, the component
+ // is kept separate. This can be more efficient: if the wizard is created
+ // but never displayed, or not all panels are displayed, it is better to
+ // create only those which really need to be visible.
+ public Component getComponent() {
+ if (component == null) {
+ component = new SelectPathVisualPanel(this);
+ }
+ return component;
+ }
+
+ public HelpCtx getHelp() {
+ // Show no Help button for this panel:
+ return HelpCtx.DEFAULT_HELP;
+ // If you have context help:
+ // return new HelpCtx(SelectPathPanel.class);
+ }
+
+ public boolean isValid() {
+ // If it is always OK to press Next or Finish, then:
+ return true;
+ // If it depends on some condition (form filled out...), then:
+ // return someCondition();
+ // and when this condition changes (last form field filled in...) then:
+ // fireChangeEvent();
+ // and uncomment the complicated stuff below.
+ }
+
+ // public final void addChangeListener(ChangeListener l) {}
+ // public final void removeChangeListener(ChangeListener l) {}
+
+ private final Set listeners = new HashSet(1); // Set<ChangeListener>
+ public final void addChangeListener(ChangeListener l) {
+ synchronized (listeners) {
+ listeners.add(l);
+ }
+ }
+ public final void removeChangeListener(ChangeListener l) {
+ synchronized (listeners) {
+ listeners.remove(l);
+ }
+ }
+ protected final void fireChangeEvent() {
+ Iterator it;
+ synchronized (listeners) {
+ it = new HashSet(listeners).iterator();
+ }
+ ChangeEvent ev = new ChangeEvent(this);
+ while (it.hasNext()) {
+ ((ChangeListener)it.next()).stateChanged(ev);
+ }
+ }
+
+ public void setSelectedPath(OfficeInstallation oi) {
+ this.office = oi;
+ fireChangeEvent();
+ }
+
+ public OfficeInstallation getSelectedPath() {
+ return office;
+ }
+
+ // You can use a settings object to keep track of state.
+ // Normally the settings object will be the WizardDescriptor,
+ // so you can use WizardDescriptor.getProperty & putProperty
+ // to store information entered by the user.
+ public void readSettings(Object settings) {
+ }
+
+ public void storeSettings(Object settings) {
+ WizardDescriptor wiz = (WizardDescriptor)settings;
+ wiz.putProperty(InstallationPathDescriptor.PROP_INSTALLPATH, office);
+ }
+}
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.form b/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.form
new file mode 100644
index 000000000000..b054e349f390
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.form
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+
+<Form version="1.0" type="org.netbeans.modules.form.forminfo.JPanelFormInfo">
+ <Properties>
+ <Property name="preferredSize" type="java.awt.Dimension" editor="org.netbeans.beaninfo.editors.DimensionEditor">
+ <Dimension value="[600, 300]"/>
+ </Property>
+ </Properties>
+ <AuxValues>
+ <AuxValue name="designerSize" type="java.awt.Dimension" value="-84,-19,0,5,115,114,0,18,106,97,118,97,46,97,119,116,46,68,105,109,101,110,115,105,111,110,65,-114,-39,-41,-84,95,68,20,2,0,2,73,0,6,104,101,105,103,104,116,73,0,5,119,105,100,116,104,120,112,0,0,1,27,0,0,2,1"/>
+ </AuxValues>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout"/>
+ <SubComponents>
+ <Component class="javax.swing.JLabel" name="jLabel1">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Installations Detected"/>
+ </Properties>
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="0" gridY="0" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="12" insetsLeft="12" insetsBottom="11" insetsRight="2" anchor="17" weightX="0.0" weightY="0.0"/>
+ </Constraint>
+ </Constraints>
+ </Component>
+ <Component class="javax.swing.JTextField" name="installPath">
+ <Properties>
+ <Property name="editable" type="boolean" value="false"/>
+ </Properties>
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="1" gridY="1" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="12" insetsLeft="0" insetsBottom="11" insetsRight="11" anchor="10" weightX="1.0" weightY="0.0"/>
+ </Constraint>
+ </Constraints>
+ </Component>
+ <Component class="javax.swing.JLabel" name="jLabel2">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Installation Directory"/>
+ </Properties>
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="0" gridY="1" gridWidth="1" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="12" insetsLeft="12" insetsBottom="11" insetsRight="12" anchor="10" weightX="0.0" weightY="0.0"/>
+ </Constraint>
+ </Constraints>
+ </Component>
+ <Component class="javax.swing.JComboBox" name="installationsComboBox">
+ <AuxValues>
+ <AuxValue name="JavaCodeGenerator_InitCodePre" type="java.lang.String" value=""/>
+ <AuxValue name="JavaCodeGenerator_CreateCodePre" type="java.lang.String" value=""/>
+ <AuxValue name="JavaCodeGenerator_SerializeTo" type="java.lang.String" value=""/>
+ <AuxValue name="JavaCodeGenerator_CreateCodePost" type="java.lang.String" value=""/>
+ <AuxValue name="JavaCodeGenerator_CodeGeneration" type="java.lang.Integer" value="0"/>
+ </AuxValues>
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="1" gridY="0" gridWidth="1" gridHeight="1" fill="2" ipadX="0" ipadY="0" insetsTop="11" insetsLeft="0" insetsBottom="11" insetsRight="11" anchor="17" weightX="0.0" weightY="0.0"/>
+ </Constraint>
+ </Constraints>
+ </Component>
+ <Container class="javax.swing.JPanel" name="jPanel1">
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="-1" gridY="2" gridWidth="1" gridHeight="1" fill="3" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="1.0"/>
+ </Constraint>
+ </Constraints>
+
+ <Layout class="org.netbeans.modules.form.compat2.layouts.DesignFlowLayout"/>
+ </Container>
+ <Component class="javax.swing.JButton" name="browseButton">
+ <Properties>
+ <Property name="text" type="java.lang.String" value="Browse..."/>
+ </Properties>
+ <Events>
+ <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="browseButtonActionPerformed"/>
+ </Events>
+ <Constraints>
+ <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout" value="org.netbeans.modules.form.compat2.layouts.DesignGridBagLayout$GridBagConstraintsDescription">
+ <GridBagConstraints gridX="2" gridY="1" gridWidth="0" gridHeight="1" fill="0" ipadX="0" ipadY="0" insetsTop="0" insetsLeft="0" insetsBottom="0" insetsRight="0" anchor="10" weightX="0.0" weightY="0.0"/>
+ </Constraint>
+ </Constraints>
+ </Component>
+ </SubComponents>
+</Form>
diff --git a/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.java b/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.java
new file mode 100644
index 000000000000..b39cd4452d4c
--- /dev/null
+++ b/scripting/java/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualPanel.java
@@ -0,0 +1,196 @@
+/*
+ * SelectPathVisualPanel.java
+ *
+ * Created on February 12, 2003
+ */
+
+package org.openoffice.netbeans.modules.office.wizard;
+
+import java.util.Hashtable;
+import java.util.Enumeration;
+import java.io.File;
+import java.io.IOException;
+import javax.swing.JFileChooser;
+
+import org.openide.util.NbBundle;
+import org.openoffice.idesupport.SVersionRCFile;
+import org.openoffice.idesupport.OfficeInstallation;
+import org.openoffice.netbeans.modules.office.options.OfficeSettings;
+
+/** A single panel for a wizard - the GUI portion.
+ *
+ * @author tomaso
+ */
+public class SelectPathVisualPanel extends javax.swing.JPanel {
+
+ /** The wizard panel descriptor associated with this GUI panel.
+ * If you need to fire state changes or something similar, you can
+ * use this handle to do so.
+ */
+ private final SelectPathPanel panel;
+
+ /** Create the wizard panel and set up some basic properties. */
+ public SelectPathVisualPanel(SelectPathPanel panel) {
+ this.panel = panel;
+ initComponents();
+ OfficeInstallation orig = panel.getSelectedPath();
+
+ try {
+ Enumeration enumer = SVersionRCFile.createInstance().getVersions();
+
+ while (enumer.hasMoreElements()) {
+ OfficeInstallation oi = (OfficeInstallation)enumer.nextElement();
+ installationsComboBox.addItem(oi);
+ }
+ }
+ catch (IOException ioe) {
+ installationsComboBox.addItem("<empty>");
+ }
+
+ if (orig != null) {
+ installationsComboBox.setSelectedItem(orig);
+ installPath.setText(orig.getPath());
+ }
+
+ installationsComboBox.addActionListener(
+ new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ installationsComboBoxActionPerformed(evt);
+ }
+ }
+ );
+
+ // Provide a name in the title bar.
+ setName(NbBundle.getMessage(SelectPathVisualPanel.class, "TITLE_SelectPathVisualPanel"));
+ /*
+ // Optional: provide a special description for this pane.
+ // You must have turned on WizardDescriptor.WizardPanel_helpDisplayed
+ // (see descriptor in standard iterator template for an example of this).
+ try {
+ putClientProperty("WizardPanel_helpURL", // NOI18N
+ new URL("nbresloc:/org/openoffice/netbeans/modules/office/wizard/SelectPathVisualHelp.html")); // NOI18N
+ } catch (MalformedURLException mfue) {
+ throw new IllegalStateException(mfue.toString());
+ }
+ */
+ }
+
+ private void installationsComboBoxActionPerformed(
+ java.awt.event.ActionEvent evt) {
+
+ OfficeInstallation oi =
+ (OfficeInstallation)installationsComboBox.getSelectedItem();
+
+ installPath.setText(oi.getPath());
+ panel.setSelectedPath(oi);
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ private void initComponents() {//GEN-BEGIN:initComponents
+ java.awt.GridBagConstraints gridBagConstraints;
+
+ jLabel1 = new javax.swing.JLabel();
+ installPath = new javax.swing.JTextField();
+ jLabel2 = new javax.swing.JLabel();
+ installationsComboBox = new javax.swing.JComboBox();
+ jPanel1 = new javax.swing.JPanel();
+ browseButton = new javax.swing.JButton();
+
+ setLayout(new java.awt.GridBagLayout());
+
+ setPreferredSize(new java.awt.Dimension(600, 300));
+ jLabel1.setText("Installations Detected");
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.gridx = 0;
+ gridBagConstraints.gridy = 0;
+ gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
+ gridBagConstraints.insets = new java.awt.Insets(12, 12, 11, 2);
+ add(jLabel1, gridBagConstraints);
+
+ installPath.setEditable(false);
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.gridx = 1;
+ gridBagConstraints.gridy = 1;
+ gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
+ gridBagConstraints.weightx = 1.0;
+ gridBagConstraints.insets = new java.awt.Insets(12, 0, 11, 11);
+ add(installPath, gridBagConstraints);
+
+ jLabel2.setText("Installation Directory");
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.gridx = 0;
+ gridBagConstraints.gridy = 1;
+ gridBagConstraints.insets = new java.awt.Insets(12, 12, 11, 12);
+ add(jLabel2, gridBagConstraints);
+
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.gridx = 1;
+ gridBagConstraints.gridy = 0;
+ gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
+ gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
+ gridBagConstraints.insets = new java.awt.Insets(11, 0, 11, 11);
+ add(installationsComboBox, gridBagConstraints);
+
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.gridy = 2;
+ gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
+ gridBagConstraints.weighty = 1.0;
+ add(jPanel1, gridBagConstraints);
+
+ browseButton.setText("Browse...");
+ browseButton.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ browseButtonActionPerformed(evt);
+ }
+ });
+
+ gridBagConstraints = new java.awt.GridBagConstraints();
+ gridBagConstraints.gridx = 2;
+ gridBagConstraints.gridy = 1;
+ gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
+ add(browseButton, gridBagConstraints);
+
+ }//GEN-END:initComponents
+
+ private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
+ // Add your handling code here:
+ File target = null;
+
+ JFileChooser chooser = new JFileChooser();
+ chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+ int result = chooser.showDialog(null, null);
+
+ if (result == JFileChooser.APPROVE_OPTION) {
+ target = chooser.getSelectedFile();
+
+ String path;
+ try {
+ path = target.getCanonicalPath();
+ }
+ catch (IOException ioe) {
+ path = target.getAbsolutePath();
+ }
+
+ OfficeInstallation oi = new OfficeInstallation(path, path);
+
+ if (oi.supportsFramework()) {
+ installPath.setText(path);
+ panel.setSelectedPath(oi);
+ }
+ }
+
+ }//GEN-LAST:event_browseButtonActionPerformed
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JTextField installPath;
+ private javax.swing.JButton browseButton;
+ private javax.swing.JComboBox installationsComboBox;
+ private javax.swing.JLabel jLabel2;
+ private javax.swing.JLabel jLabel1;
+ private javax.swing.JPanel jPanel1;
+ // End of variables declaration//GEN-END:variables
+}
diff --git a/scripting/prj/build.lst b/scripting/prj/build.lst
new file mode 100644
index 000000000000..26b905b1abd6
--- /dev/null
+++ b/scripting/prj/build.lst
@@ -0,0 +1,13 @@
+tc scripting : bridges rdbmaker vcl xmlscript basic sfx2 rhino BSH:beanshell javaunohelper NULL
+tc scripting usr1 - all tc1_mkout NULL
+tc scripting\inc nmake - all tc1_inc NULL
+tc scripting\source\provider nmake - all tc1_scriptingprovider tc1_inc NULL
+tc scripting\source\basprov nmake - all tc1_scriptingbasprov tc1_inc NULL
+tc scripting\source\dlgprov nmake - all tc1_scriptingdlgprov tc1_inc NULL
+tc scripting\source\stringresource nmake - all tc1_scriptingstringresource tc1_inc NULL
+tc scripting\source\pyprov nmake - all tc1_scriptingpyprov tc1_inc NULL
+tc scripting\source\protocolhandler nmake - all tc1_scriptingprotocolhandler tc1_scriptingprovider tc1_inc NULL
+tc scripting\java nmake - all tc1_scriptingjava tc1_scriptingprovider tc1_scriptingprotocolhandler NULL
+tc scripting\examples\java nmake - all tc1_scriptingexamplesjava tc1_scriptingjava NULL
+tc scripting\examples nmake - all tc1_scriptingexamples tc1_scriptingexamplesjava tc1_inc NULL
+tc scripting\util nmake - all tc1_scriptingutil tc1_scriptingprovider tc1_scriptingprotocolhandler tc1_scriptingbasprov tc1_scriptingstringresource tc1_scriptingpyprov tc1_scriptingjava tc1_scriptingexamplesjava tc1_scriptingexamples NULL
diff --git a/scripting/prj/d.lst b/scripting/prj/d.lst
new file mode 100644
index 000000000000..ef216fe84f8a
--- /dev/null
+++ b/scripting/prj/d.lst
@@ -0,0 +1,17 @@
+mkdir: %_DEST%\inc%_EXT%\scripting
+mkdir: %_DEST%\lib%_EXT%\pyuno
+mkdir: %_DEST%\bin%_EXT%\pyuno
+
+..\%__SRC%\bin\*.dll %_DEST%\bin%_EXT%\*
+..\%__SRC%\bin\*.zip %COMMON_DEST%\pck%_EXT%\*
+..\%__SRC%\class\*.jar %_DEST%\bin%_EXT%\*
+..\%__SRC%\lib\*.so %_DEST%\lib%_EXT%\*
+..\%__SRC%\bin\*.py %_DEST%\bin%_EXT%\pyuno\*
+..\%__SRC%\lib\*.py %_DEST%\lib%_EXT%\pyuno\*
+..\%__SRC%\lib\*.dylib %_DEST%\lib%_EXT%\*.dylib
+
+..\%__SRC%\bin\*.rdb %_DEST%\rdb%_EXT%\*
+
+..\source\storage\storage.xml %_DEST%\xml%_EXT%\storage.xml
+
+..\%__SRC%\lib\lib*static*.dylib %_DEST%\lib%_EXT%\lib*static*.dylib
diff --git a/scripting/source/basprov/baslibnode.cxx b/scripting/source/basprov/baslibnode.cxx
new file mode 100644
index 000000000000..69fa00f150ab
--- /dev/null
+++ b/scripting/source/basprov/baslibnode.cxx
@@ -0,0 +1,151 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: baslibnode.cxx,v $
+ * $Revision: 1.10 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include "baslibnode.hxx"
+#include "basmodnode.hxx"
+#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
+#include <vos/mutex.hxx>
+#include <vcl/svapp.hxx>
+#include <basic/basmgr.hxx>
+#include <basic/sbstar.hxx>
+
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::script;
+
+
+//.........................................................................
+namespace basprov
+{
+//.........................................................................
+
+ // =============================================================================
+ // BasicLibraryNodeImpl
+ // =============================================================================
+
+ BasicLibraryNodeImpl::BasicLibraryNodeImpl( const Reference< XComponentContext >& rxContext,
+ const ::rtl::OUString& sScriptingContext, BasicManager* pBasicManager,
+ const Reference< script::XLibraryContainer >& xLibContainer, const ::rtl::OUString& sLibName, bool isAppScript )
+ :m_xContext( rxContext )
+ ,m_sScriptingContext( sScriptingContext )
+ ,m_pBasicManager( pBasicManager )
+ ,m_xLibContainer( xLibContainer )
+ ,m_sLibName( sLibName )
+ ,m_bIsAppScript( isAppScript )
+ {
+ if ( m_xLibContainer.is() )
+ {
+ Any aElement = m_xLibContainer->getByName( m_sLibName );
+ aElement >>= m_xLibrary;
+ }
+ }
+
+ // -----------------------------------------------------------------------------
+
+ BasicLibraryNodeImpl::~BasicLibraryNodeImpl()
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+ // XBrowseNode
+ // -----------------------------------------------------------------------------
+
+ ::rtl::OUString BasicLibraryNodeImpl::getName( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ return m_sLibName;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Sequence< Reference< browse::XBrowseNode > > BasicLibraryNodeImpl::getChildNodes( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ Sequence< Reference< browse::XBrowseNode > > aChildNodes;
+
+ if ( m_xLibContainer.is() && m_xLibContainer->hasByName( m_sLibName ) && !m_xLibContainer->isLibraryLoaded( m_sLibName ) )
+ m_xLibContainer->loadLibrary( m_sLibName );
+
+ if ( m_pBasicManager )
+ {
+ StarBASIC* pBasic = m_pBasicManager->GetLib( m_sLibName );
+ if ( pBasic && m_xLibrary.is() )
+ {
+ Sequence< ::rtl::OUString > aNames = m_xLibrary->getElementNames();
+ sal_Int32 nCount = aNames.getLength();
+ const ::rtl::OUString* pNames = aNames.getConstArray();
+ aChildNodes.realloc( nCount );
+ Reference< browse::XBrowseNode >* pChildNodes = aChildNodes.getArray();
+
+ for ( sal_Int32 i = 0 ; i < nCount ; ++i )
+ {
+ SbModule* pModule = pBasic->FindModule( pNames[i] );
+ if ( pModule )
+ pChildNodes[i] = static_cast< browse::XBrowseNode* >( new BasicModuleNodeImpl( m_xContext, m_sScriptingContext, pModule, m_bIsAppScript ) );
+ }
+ }
+ }
+
+ return aChildNodes;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Bool BasicLibraryNodeImpl::hasChildNodes( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ sal_Bool bReturn = sal_False;
+ if ( m_xLibrary.is() )
+ bReturn = m_xLibrary->hasElements();
+
+ return bReturn;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Int16 BasicLibraryNodeImpl::getType( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ return browse::BrowseNodeTypes::CONTAINER;
+ }
+
+ // -----------------------------------------------------------------------------
+
+//.........................................................................
+} // namespace basprov
+//.........................................................................
diff --git a/scripting/source/basprov/baslibnode.hxx b/scripting/source/basprov/baslibnode.hxx
new file mode 100644
index 000000000000..de1f047534d0
--- /dev/null
+++ b/scripting/source/basprov/baslibnode.hxx
@@ -0,0 +1,90 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: baslibnode.hxx,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef SCRIPTING_BASLIBNODE_HXX
+#define SCRIPTING_BASLIBNODE_HXX
+
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/script/XLibraryContainer.hpp>
+#include <com/sun/star/script/browse/XBrowseNode.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <cppuhelper/implbase1.hxx>
+
+class BasicManager;
+
+
+//.........................................................................
+namespace basprov
+{
+//.........................................................................
+
+ // ----------------------------------------------------
+ // class BasicLibraryNodeImpl
+ // ----------------------------------------------------
+
+ typedef ::cppu::WeakImplHelper1<
+ ::com::sun::star::script::browse::XBrowseNode > BasicLibraryNodeImpl_BASE;
+
+
+ class BasicLibraryNodeImpl : public BasicLibraryNodeImpl_BASE
+ {
+ private:
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
+ ::rtl::OUString m_sScriptingContext;
+ BasicManager* m_pBasicManager;
+ ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer > m_xLibContainer;
+ ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xLibrary;
+ ::rtl::OUString m_sLibName;
+ bool m_bIsAppScript;
+
+ public:
+ BasicLibraryNodeImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,
+ const ::rtl::OUString& sScriptingContext,
+ BasicManager* pBasicManager,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >& xLibContainer,
+ const ::rtl::OUString& sLibName, bool isAppScript=true );
+ virtual ~BasicLibraryNodeImpl();
+
+ // XBrowseNode
+ virtual ::rtl::OUString SAL_CALL getName( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > > SAL_CALL getChildNodes( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL hasChildNodes( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Int16 SAL_CALL getType( )
+ throw (::com::sun::star::uno::RuntimeException);
+ };
+
+//.........................................................................
+} // namespace basprov
+//.........................................................................
+
+#endif // SCRIPTING_BASLIBNODE_HXX
diff --git a/scripting/source/basprov/basmethnode.cxx b/scripting/source/basprov/basmethnode.cxx
new file mode 100644
index 000000000000..02058517743c
--- /dev/null
+++ b/scripting/source/basprov/basmethnode.cxx
@@ -0,0 +1,361 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: basmethnode.cxx,v $
+ * $Revision: 1.14 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include "basmethnode.hxx"
+#include <com/sun/star/beans/PropertyAttribute.hpp>
+#include <com/sun/star/frame/XDesktop.hpp>
+#include <com/sun/star/frame/XDispatchHelper.hpp>
+#include <com/sun/star/frame/XDispatchProvider.hpp>
+#include <com/sun/star/lang/XMultiComponentFactory.hpp>
+#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
+#include <vos/mutex.hxx>
+#include <vcl/svapp.hxx>
+#include <basic/sbstar.hxx>
+#include <basic/sbmeth.hxx>
+#include <basic/sbmod.hxx>
+
+#include <util/MiscUtils.hxx>
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::beans;
+using namespace ::comphelper;
+using namespace ::com::sun::star::script;
+using namespace ::sf_misc;
+
+#define BASPROV_PROPERTY_ID_URI 1
+#define BASPROV_PROPERTY_ID_EDITABLE 2
+
+#define BASPROV_PROPERTY_URI ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "URI" ) )
+#define BASPROV_PROPERTY_EDITABLE ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Editable" ) )
+
+#define BASPROV_DEFAULT_ATTRIBS() PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT | PropertyAttribute::READONLY
+
+
+//.........................................................................
+namespace basprov
+{
+//.........................................................................
+
+ // =============================================================================
+ // BasicMethodNodeImpl
+ // =============================================================================
+
+ BasicMethodNodeImpl::BasicMethodNodeImpl( const Reference< XComponentContext >& rxContext,
+ const ::rtl::OUString& sScriptingContext, SbMethod* pMethod, bool isAppScript )
+ : ::scripting_helper::OBroadcastHelperHolder( m_aMutex )
+ ,OPropertyContainer( GetBroadcastHelper() )
+ ,m_xContext( rxContext )
+ ,m_sScriptingContext( sScriptingContext )
+ ,m_pMethod( pMethod )
+ ,m_bIsAppScript( isAppScript )
+ ,m_bEditable( sal_True )
+ {
+ if ( m_pMethod )
+ {
+ SbModule* pModule = m_pMethod->GetModule();
+ if ( pModule )
+ {
+ StarBASIC* pBasic = static_cast< StarBASIC* >( pModule->GetParent() );
+ if ( pBasic )
+ {
+ m_sURI = ::rtl::OUString::createFromAscii( "vnd.sun.star.script:" );
+ m_sURI += pBasic->GetName();
+ m_sURI += ::rtl::OUString::createFromAscii( "." );
+ m_sURI += pModule->GetName();
+ m_sURI += ::rtl::OUString::createFromAscii( "." );
+ m_sURI += m_pMethod->GetName();
+ m_sURI += ::rtl::OUString::createFromAscii( "?language=Basic&location=" );
+ if ( m_bIsAppScript )
+ m_sURI += ::rtl::OUString::createFromAscii( "application" );
+ else
+ m_sURI += ::rtl::OUString::createFromAscii( "document" );
+ }
+ }
+ }
+
+ registerProperty( BASPROV_PROPERTY_URI, BASPROV_PROPERTY_ID_URI, BASPROV_DEFAULT_ATTRIBS(), &m_sURI, ::getCppuType( &m_sURI ) );
+ registerProperty( BASPROV_PROPERTY_EDITABLE, BASPROV_PROPERTY_ID_EDITABLE, BASPROV_DEFAULT_ATTRIBS(), &m_bEditable, ::getCppuType( &m_bEditable ) );
+ }
+
+ // -----------------------------------------------------------------------------
+
+ BasicMethodNodeImpl::~BasicMethodNodeImpl()
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+ // XInterface
+ // -----------------------------------------------------------------------------
+
+ IMPLEMENT_FORWARD_XINTERFACE2( BasicMethodNodeImpl, BasicMethodNodeImpl_BASE, OPropertyContainer )
+
+ // -----------------------------------------------------------------------------
+ // XTypeProvider
+ // -----------------------------------------------------------------------------
+
+ IMPLEMENT_FORWARD_XTYPEPROVIDER2( BasicMethodNodeImpl, BasicMethodNodeImpl_BASE, OPropertyContainer )
+
+ // -----------------------------------------------------------------------------
+ // XBrowseNode
+ // -----------------------------------------------------------------------------
+
+ ::rtl::OUString BasicMethodNodeImpl::getName( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ ::rtl::OUString sMethodName;
+ if ( m_pMethod )
+ sMethodName = m_pMethod->GetName();
+
+ return sMethodName;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Sequence< Reference< browse::XBrowseNode > > BasicMethodNodeImpl::getChildNodes( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ return Sequence< Reference< browse::XBrowseNode > >();
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Bool BasicMethodNodeImpl::hasChildNodes( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ return sal_False;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Int16 BasicMethodNodeImpl::getType( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ return browse::BrowseNodeTypes::SCRIPT;
+ }
+
+ // -----------------------------------------------------------------------------
+ // OPropertySetHelper
+ // -----------------------------------------------------------------------------
+
+ ::cppu::IPropertyArrayHelper& BasicMethodNodeImpl::getInfoHelper( )
+ {
+ return *getArrayHelper();
+ }
+
+ // -----------------------------------------------------------------------------
+ // OPropertyArrayUsageHelper
+ // -----------------------------------------------------------------------------
+
+ ::cppu::IPropertyArrayHelper* BasicMethodNodeImpl::createArrayHelper( ) const
+ {
+ Sequence< Property > aProps;
+ describeProperties( aProps );
+ return new ::cppu::OPropertyArrayHelper( aProps );
+ }
+
+ // -----------------------------------------------------------------------------
+ // XPropertySet
+ // -----------------------------------------------------------------------------
+
+ Reference< XPropertySetInfo > BasicMethodNodeImpl::getPropertySetInfo( ) throw (RuntimeException)
+ {
+ Reference< XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
+ return xInfo;
+ }
+
+ // -----------------------------------------------------------------------------
+ // XInvocation
+ // -----------------------------------------------------------------------------
+
+ Reference< XIntrospectionAccess > BasicMethodNodeImpl::getIntrospection( ) throw (RuntimeException)
+ {
+ return Reference< XIntrospectionAccess >();
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Any BasicMethodNodeImpl::invoke( const ::rtl::OUString& aFunctionName, const Sequence< Any >& aParams,
+ Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam )
+ throw (IllegalArgumentException, script::CannotConvertException,
+ reflection::InvocationTargetException, RuntimeException)
+ {
+ (void)aParams;
+ (void)aOutParamIndex;
+ (void)aOutParam;
+
+ if ( aFunctionName == BASPROV_PROPERTY_EDITABLE )
+ {
+ ::rtl::OUString sDocURL, sLibName, sModName;
+ USHORT nLine1 = 0, nLine2;
+
+ if ( !m_bIsAppScript )
+ {
+ Reference< frame::XModel > xModel = MiscUtils::tDocUrlToModel( m_sScriptingContext );
+
+ if ( xModel.is() )
+ {
+ sDocURL = xModel->getURL();
+ if ( sDocURL.getLength() == 0 )
+ {
+ Sequence < PropertyValue > aProps = xModel->getArgs();
+ sal_Int32 nProps = aProps.getLength();
+ const PropertyValue* pProps = aProps.getConstArray();
+ for ( sal_Int32 i = 0; i < nProps; ++i )
+ {
+ // TODO: according to MBA the property 'Title' may change in future
+ if ( pProps[i].Name == ::rtl::OUString::createFromAscii( "Title" ) )
+ {
+ pProps[i].Value >>= sDocURL;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if ( m_pMethod )
+ {
+ m_pMethod->GetLineRange( nLine1, nLine2 );
+ SbModule* pModule = m_pMethod->GetModule();
+ if ( pModule )
+ {
+ sModName = pModule->GetName();
+ StarBASIC* pBasic = static_cast< StarBASIC* >( pModule->GetParent() );
+ if ( pBasic )
+ sLibName = pBasic->GetName();
+ }
+ }
+
+ if ( m_xContext.is() )
+ {
+ Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager() );
+
+ if ( xSMgr.is() )
+ {
+ Reference< frame::XDesktop > xDesktop( xSMgr->createInstanceWithContext(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.Desktop" ) ), m_xContext ), UNO_QUERY );
+
+ if ( xDesktop.is() )
+ {
+ Reference < frame::XDispatchProvider > xProv( xDesktop->getCurrentFrame(), UNO_QUERY );
+
+ if ( xProv.is() )
+ {
+ Reference< frame::XDispatchHelper > xHelper( xSMgr->createInstanceWithContext(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.DispatchHelper" ) ), m_xContext ), UNO_QUERY );
+
+ if ( xHelper.is() )
+ {
+ Sequence < PropertyValue > aArgs(7);
+ aArgs[0].Name = ::rtl::OUString::createFromAscii( "Document" );
+ aArgs[0].Value <<= sDocURL;
+ aArgs[1].Name = ::rtl::OUString::createFromAscii( "LibName" );
+ aArgs[1].Value <<= sLibName;
+ aArgs[2].Name = ::rtl::OUString::createFromAscii( "Name" );
+ aArgs[2].Value <<= sModName;
+ aArgs[3].Name = ::rtl::OUString::createFromAscii( "Type" );
+ aArgs[3].Value <<= ::rtl::OUString::createFromAscii( "Module" );
+ aArgs[4].Name = ::rtl::OUString::createFromAscii( "Line" );
+ aArgs[4].Value <<= static_cast< sal_uInt32 >( nLine1 );
+ xHelper->executeDispatch( xProv, ::rtl::OUString::createFromAscii( ".uno:BasicIDEAppear" ), ::rtl::OUString(), 0, aArgs );
+ }
+ }
+ }
+ }
+ }
+ }
+ else
+ {
+ throw IllegalArgumentException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicMethodNodeImpl::invoke: function name not supported!" ) ),
+ Reference< XInterface >(), 1 );
+ }
+
+ return Any();
+ }
+
+ // -----------------------------------------------------------------------------
+
+ void BasicMethodNodeImpl::setValue( const ::rtl::OUString& aPropertyName, const Any& aValue )
+ throw (UnknownPropertyException, script::CannotConvertException,
+ reflection::InvocationTargetException, RuntimeException)
+ {
+ (void)aPropertyName;
+ (void)aValue;
+
+ throw UnknownPropertyException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicMethodNodeImpl::setValue: property name is unknown!" ) ),
+ Reference< XInterface >() );
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Any BasicMethodNodeImpl::getValue( const ::rtl::OUString& aPropertyName ) throw (UnknownPropertyException, RuntimeException)
+ {
+ (void)aPropertyName;
+
+ throw UnknownPropertyException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicMethodNodeImpl::getValue: property name is unknown!" ) ),
+ Reference< XInterface >() );
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Bool BasicMethodNodeImpl::hasMethod( const ::rtl::OUString& aName ) throw (RuntimeException)
+ {
+ sal_Bool bReturn = sal_False;
+ if ( aName == BASPROV_PROPERTY_EDITABLE )
+ bReturn = sal_True;
+
+ return bReturn;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Bool BasicMethodNodeImpl::hasProperty( const ::rtl::OUString& aName ) throw (RuntimeException)
+ {
+ (void)aName;
+
+ return sal_False;
+ }
+
+ // -----------------------------------------------------------------------------
+
+//.........................................................................
+} // namespace basprov
+//.........................................................................
diff --git a/scripting/source/basprov/basmethnode.hxx b/scripting/source/basprov/basmethnode.hxx
new file mode 100644
index 000000000000..e36545636e08
--- /dev/null
+++ b/scripting/source/basprov/basmethnode.hxx
@@ -0,0 +1,135 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: basmethnode.hxx,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef SCRIPTING_BASMETHNODE_HXX
+#define SCRIPTING_BASMETHNODE_HXX
+
+#include "bcholder.hxx"
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/script/XInvocation.hpp>
+#include <com/sun/star/script/browse/XBrowseNode.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <comphelper/proparrhlp.hxx>
+#include <comphelper/propertycontainer.hxx>
+#include <comphelper/uno3.hxx>
+#include <cppuhelper/implbase2.hxx>
+
+
+class SbMethod;
+
+
+//.........................................................................
+namespace basprov
+{
+//.........................................................................
+
+ // ----------------------------------------------------
+ // class BasicMethodNodeImpl
+ // ----------------------------------------------------
+
+ typedef ::cppu::WeakImplHelper2<
+ ::com::sun::star::script::browse::XBrowseNode,
+ ::com::sun::star::script::XInvocation > BasicMethodNodeImpl_BASE;
+
+ class BasicMethodNodeImpl : public BasicMethodNodeImpl_BASE,
+ public ::scripting_helper::OMutexHolder,
+ public ::scripting_helper::OBroadcastHelperHolder,
+ public ::comphelper::OPropertyContainer,
+ public ::comphelper::OPropertyArrayUsageHelper< BasicMethodNodeImpl >
+ {
+ private:
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
+ ::rtl::OUString m_sScriptingContext;
+ SbMethod* m_pMethod;
+ bool m_bIsAppScript;
+
+ // properties
+ ::rtl::OUString m_sURI;
+ sal_Bool m_bEditable;
+
+ protected:
+ // OPropertySetHelper
+ virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper( );
+
+ // OPropertyArrayUsageHelper
+ virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
+
+ public:
+ BasicMethodNodeImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,
+ const ::rtl::OUString& sScriptingContext,
+ SbMethod* pMethod, bool isAppScript = true );
+ virtual ~BasicMethodNodeImpl();
+
+ // XInterface
+ DECLARE_XINTERFACE()
+
+ // XTypeProvider
+ DECLARE_XTYPEPROVIDER()
+
+ // XBrowseNode
+ virtual ::rtl::OUString SAL_CALL getName( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > > SAL_CALL getChildNodes( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL hasChildNodes( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Int16 SAL_CALL getType( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XPropertySet
+ virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XInvocation
+ virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess > SAL_CALL getIntrospection( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Any SAL_CALL invoke(
+ const ::rtl::OUString& aFunctionName,
+ const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aParams,
+ ::com::sun::star::uno::Sequence< sal_Int16 >& aOutParamIndex,
+ ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aOutParam )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::script::CannotConvertException,
+ ::com::sun::star::reflection::InvocationTargetException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )
+ throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::script::CannotConvertException,
+ ::com::sun::star::reflection::InvocationTargetException, ::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Any SAL_CALL getValue( const ::rtl::OUString& aPropertyName )
+ throw (::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL hasMethod( const ::rtl::OUString& aName )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL hasProperty( const ::rtl::OUString& aName )
+ throw (::com::sun::star::uno::RuntimeException);
+ };
+
+//.........................................................................
+} // namespace basprov
+//.........................................................................
+
+#endif // SCRIPTING_BASMETHNODE_HXX
diff --git a/scripting/source/basprov/basmodnode.cxx b/scripting/source/basprov/basmodnode.cxx
new file mode 100644
index 000000000000..79bd22017993
--- /dev/null
+++ b/scripting/source/basprov/basmodnode.cxx
@@ -0,0 +1,148 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: basmodnode.cxx,v $
+ * $Revision: 1.11 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include "basmodnode.hxx"
+#include "basmethnode.hxx"
+#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
+#include <vos/mutex.hxx>
+#include <vcl/svapp.hxx>
+#include <basic/sbx.hxx>
+#include <basic/sbstar.hxx>
+#include <basic/sbmod.hxx>
+#include <basic/sbmeth.hxx>
+
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::script;
+
+
+//.........................................................................
+namespace basprov
+{
+//.........................................................................
+
+ // =============================================================================
+ // BasicModuleNodeImpl
+ // =============================================================================
+
+ BasicModuleNodeImpl::BasicModuleNodeImpl( const Reference< XComponentContext >& rxContext,
+ const ::rtl::OUString& sScriptingContext, SbModule* pModule, bool isAppScript )
+ :m_xContext( rxContext )
+ ,m_sScriptingContext( sScriptingContext )
+ ,m_pModule( pModule )
+ ,m_bIsAppScript( isAppScript )
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+
+ BasicModuleNodeImpl::~BasicModuleNodeImpl()
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+ // XBrowseNode
+ // -----------------------------------------------------------------------------
+
+ ::rtl::OUString BasicModuleNodeImpl::getName( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ ::rtl::OUString sModuleName;
+ if ( m_pModule )
+ sModuleName = m_pModule->GetName();
+
+ return sModuleName;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Sequence< Reference< browse::XBrowseNode > > BasicModuleNodeImpl::getChildNodes( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ Sequence< Reference< browse::XBrowseNode > > aChildNodes;
+
+ if ( m_pModule )
+ {
+ SbxArray* pMethods = m_pModule->GetMethods();
+ if ( pMethods )
+ {
+ sal_Int32 nCount = pMethods->Count();
+ aChildNodes.realloc( nCount );
+ Reference< browse::XBrowseNode >* pChildNodes = aChildNodes.getArray();
+
+ for ( sal_Int32 i = 0; i < nCount; ++i )
+ {
+ SbMethod* pMethod = static_cast< SbMethod* >( pMethods->Get( static_cast< USHORT >( i ) ) );
+ if ( pMethod )
+ pChildNodes[i] = static_cast< browse::XBrowseNode* >( new BasicMethodNodeImpl( m_xContext, m_sScriptingContext, pMethod, m_bIsAppScript ) );
+ }
+ }
+ }
+
+ return aChildNodes;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Bool BasicModuleNodeImpl::hasChildNodes( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ sal_Bool bReturn = sal_False;
+ if ( m_pModule )
+ {
+ SbxArray* pMethods = m_pModule->GetMethods();
+ if ( pMethods && pMethods->Count() > 0 )
+ bReturn = sal_True;
+ }
+
+ return bReturn;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Int16 BasicModuleNodeImpl::getType( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ return browse::BrowseNodeTypes::CONTAINER;
+ }
+
+ // -----------------------------------------------------------------------------
+
+//.........................................................................
+} // namespace basprov
+//.........................................................................
diff --git a/scripting/source/basprov/basmodnode.hxx b/scripting/source/basprov/basmodnode.hxx
new file mode 100644
index 000000000000..c880ae5315d2
--- /dev/null
+++ b/scripting/source/basprov/basmodnode.hxx
@@ -0,0 +1,84 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: basmodnode.hxx,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef SCRIPTING_BASMODNODE_HXX
+#define SCRIPTING_BASMODNODE_HXX
+
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/script/browse/XBrowseNode.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <cppuhelper/implbase1.hxx>
+
+class SbModule;
+
+
+//.........................................................................
+namespace basprov
+{
+//.........................................................................
+
+ // ----------------------------------------------------
+ // class BasicModuleNodeImpl
+ // ----------------------------------------------------
+
+ typedef ::cppu::WeakImplHelper1<
+ ::com::sun::star::script::browse::XBrowseNode > BasicModuleNodeImpl_BASE;
+
+
+ class BasicModuleNodeImpl : public BasicModuleNodeImpl_BASE
+ {
+ private:
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
+ ::rtl::OUString m_sScriptingContext;
+ SbModule* m_pModule;
+ bool m_bIsAppScript;
+
+ public:
+ BasicModuleNodeImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,
+ const ::rtl::OUString& sScriptingContext,
+ SbModule* pModule, bool isAppScript = true );
+ virtual ~BasicModuleNodeImpl();
+
+ // XBrowseNode
+ virtual ::rtl::OUString SAL_CALL getName( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > > SAL_CALL getChildNodes( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL hasChildNodes( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Int16 SAL_CALL getType( )
+ throw (::com::sun::star::uno::RuntimeException);
+ };
+
+//.........................................................................
+} // namespace basprov
+//.........................................................................
+
+#endif // SCRIPTING_BASMODNODE_HXX
diff --git a/scripting/source/basprov/basprov.cxx b/scripting/source/basprov/basprov.cxx
new file mode 100644
index 000000000000..447ea68468fd
--- /dev/null
+++ b/scripting/source/basprov/basprov.cxx
@@ -0,0 +1,609 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: basprov.cxx,v $
+ * $Revision: 1.21.6.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include "basprov.hxx"
+#include "basscript.hxx"
+#include "baslibnode.hxx"
+#include <com/sun/star/frame/XModel.hpp>
+#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
+#include <com/sun/star/script/provider/ScriptFrameworkErrorType.hpp>
+#include <com/sun/star/document/XEmbeddedScripts.hpp>
+
+#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
+#include <cppuhelper/implementationentry.hxx>
+#endif
+#include <rtl/uri.hxx>
+#include <osl/process.h>
+#include <osl/file.hxx>
+#include <vos/mutex.hxx>
+#include <vcl/svapp.hxx>
+#include <basic/sbx.hxx>
+#include <basic/basmgr.hxx>
+#include <basic/basicmanagerrepository.hxx>
+#include <basic/sbstar.hxx>
+#include <basic/sbmod.hxx>
+#include <basic/sbmeth.hxx>
+#include <sfx2/app.hxx>
+#include <sfx2/objsh.hxx>
+
+#include <com/sun/star/util/XMacroExpander.hpp>
+#include <com/sun/star/script/XLibraryContainer2.hpp>
+#include <com/sun/star/uri/XUriReference.hpp>
+#include <com/sun/star/uri/XUriReferenceFactory.hpp>
+#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
+
+#include <util/util.hxx>
+#include <util/MiscUtils.hxx>
+
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::script;
+using namespace ::com::sun::star::document;
+using namespace ::sf_misc;
+
+//.........................................................................
+namespace basprov
+{
+//.........................................................................
+
+ // =============================================================================
+ // component operations
+ // =============================================================================
+
+ static ::rtl::OUString getImplementationName_BasicProviderImpl()
+ {
+ static ::rtl::OUString* pImplName = 0;
+ if ( !pImplName )
+ {
+ ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
+ if ( !pImplName )
+ {
+ static ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.scripting.ScriptProviderForBasic" ) );
+ pImplName = &aImplName;
+ }
+ }
+ return *pImplName;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ static Sequence< ::rtl::OUString > getSupportedServiceNames_BasicProviderImpl()
+ {
+ static Sequence< ::rtl::OUString >* pNames = 0;
+ if ( !pNames )
+ {
+ ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
+ if ( !pNames )
+ {
+ static Sequence< ::rtl::OUString > aNames(4);
+ aNames.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.script.provider.ScriptProviderForBasic" ) );
+ aNames.getArray()[1] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.script.provider.LanguageScriptProvider" ) );
+ aNames.getArray()[2] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.script.provider.ScriptProvider" ) );
+ aNames.getArray()[3] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.script.browse.BrowseNode" ) );
+ pNames = &aNames;
+ }
+ }
+ return *pNames;
+ }
+
+ // =============================================================================
+ // BasicProviderImpl
+ // =============================================================================
+
+ BasicProviderImpl::BasicProviderImpl( const Reference< XComponentContext >& xContext )
+ :m_pAppBasicManager( 0 )
+ ,m_pDocBasicManager( 0 )
+ ,m_xLibContainerApp( 0 )
+ ,m_xLibContainerDoc( 0 )
+ ,m_xContext( xContext )
+ ,m_bIsAppScriptCtx( true )
+ ,m_bIsUserCtx(true)
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+
+ BasicProviderImpl::~BasicProviderImpl()
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+
+ bool BasicProviderImpl::isLibraryShared( const Reference< script::XLibraryContainer >& rxLibContainer, const ::rtl::OUString& rLibName )
+ {
+ bool bIsShared = false;
+
+ Reference< script::XLibraryContainer2 > xLibContainer( rxLibContainer, UNO_QUERY );
+ if ( xLibContainer.is() && xLibContainer->hasByName( rLibName ) && xLibContainer->isLibraryLink( rLibName ) )
+ {
+ ::rtl::OUString aFileURL;
+ if ( m_xContext.is() )
+ {
+ Reference< uri::XUriReferenceFactory > xUriFac;
+ Reference< lang::XMultiComponentFactory > xSMgr( m_xContext->getServiceManager() );
+ if ( xSMgr.is() )
+ {
+ xUriFac.set( xSMgr->createInstanceWithContext( ::rtl::OUString::createFromAscii(
+ "com.sun.star.uri.UriReferenceFactory" ), m_xContext ), UNO_QUERY );
+ }
+
+ if ( xUriFac.is() )
+ {
+ ::rtl::OUString aLinkURL( xLibContainer->getLibraryLinkURL( rLibName ) );
+ Reference< uri::XUriReference > xUriRef( xUriFac->parse( aLinkURL ), UNO_QUERY );
+
+ if ( xUriRef.is() )
+ {
+ ::rtl::OUString aScheme = xUriRef->getScheme();
+ if ( aScheme.equalsIgnoreAsciiCaseAscii( "file" ) )
+ {
+ aFileURL = aLinkURL;
+ }
+ else if ( aScheme.equalsIgnoreAsciiCaseAscii( "vnd.sun.star.pkg" ) )
+ {
+ ::rtl::OUString aAuthority = xUriRef->getAuthority();
+ if ( aAuthority.matchIgnoreAsciiCaseAsciiL( RTL_CONSTASCII_STRINGPARAM( "vnd.sun.star.expand:" ) ) )
+ {
+ ::rtl::OUString aDecodedURL( aAuthority.copy( sizeof ( "vnd.sun.star.expand:" ) - 1 ) );
+ aDecodedURL = ::rtl::Uri::decode( aDecodedURL, rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8 );
+ Reference<util::XMacroExpander> xMacroExpander(
+ m_xContext->getValueByName(
+ ::rtl::OUString::createFromAscii( "/singletons/com.sun.star.util.theMacroExpander" ) ),
+ UNO_QUERY );
+ if ( xMacroExpander.is() )
+ aFileURL = xMacroExpander->expandMacros( aDecodedURL );
+ }
+ }
+ }
+ }
+ }
+
+ if ( aFileURL.getLength() )
+ {
+ osl::DirectoryItem aFileItem;
+ osl::FileStatus aFileStatus( FileStatusMask_FileURL );
+ OSL_VERIFY( osl::DirectoryItem::get( aFileURL, aFileItem ) == osl::FileBase::E_None );
+ OSL_VERIFY( aFileItem.getFileStatus( aFileStatus ) == osl::FileBase::E_None );
+ ::rtl::OUString aCanonicalFileURL( aFileStatus.getFileURL() );
+
+ ::rtl::OUString aSearchURL1( RTL_CONSTASCII_USTRINGPARAM( "share/basic" ) );
+ ::rtl::OUString aSearchURL2( RTL_CONSTASCII_USTRINGPARAM( "share/uno_packages" ) );
+ if( aCanonicalFileURL.indexOf( aSearchURL1 ) != -1 || aCanonicalFileURL.indexOf( aSearchURL2 ) != -1 )
+ bIsShared = true;
+ }
+ }
+
+ return bIsShared;
+ }
+
+ // -----------------------------------------------------------------------------
+ // XServiceInfo
+ // -----------------------------------------------------------------------------
+
+ ::rtl::OUString BasicProviderImpl::getImplementationName( ) throw (RuntimeException)
+ {
+ return getImplementationName_BasicProviderImpl();
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Bool BasicProviderImpl::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
+ {
+ Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
+ const ::rtl::OUString* pNames = aNames.getConstArray();
+ const ::rtl::OUString* pEnd = pNames + aNames.getLength();
+ for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
+ ;
+
+ return pNames != pEnd;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Sequence< ::rtl::OUString > BasicProviderImpl::getSupportedServiceNames( ) throw (RuntimeException)
+ {
+ return getSupportedServiceNames_BasicProviderImpl();
+ }
+
+ // -----------------------------------------------------------------------------
+ // XInitialization
+ // -----------------------------------------------------------------------------
+
+ void BasicProviderImpl::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException)
+ {
+ // TODO
+
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ if ( aArguments.getLength() != 1 )
+ {
+ throw IllegalArgumentException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicProviderImpl::initialize: incorrect argument count." ) ),
+ *this,
+ 1
+ );
+ }
+
+ Reference< frame::XModel > xModel;
+
+ m_xInvocationContext.set( aArguments[0], UNO_QUERY );;
+ if ( m_xInvocationContext.is() )
+ {
+ xModel.set( m_xInvocationContext->getScriptContainer(), UNO_QUERY );
+ if ( !xModel.is() )
+ {
+ throw IllegalArgumentException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicProviderImpl::initialize: unable to determine the document model from the script invocation context." ) ),
+ *this,
+ 1
+ );
+ }
+ }
+ else
+ {
+ if ( !( aArguments[0] >>= m_sScriptingContext ) )
+ {
+ throw IllegalArgumentException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicProviderImpl::initialize: incorrect argument type " ) ).concat( aArguments[0].getValueTypeName() ),
+ *this,
+ 1
+ );
+ }
+
+ ::rtl::OUString sDoc = OUSTR("vnd.sun.star.tdoc");
+ if ( m_sScriptingContext.indexOf( sDoc ) == 0 )
+ {
+ xModel = MiscUtils::tDocUrlToModel( m_sScriptingContext );
+ // TODO: use ScriptingContantsPool for SCRIPTING_DOC_REF
+ }
+ }
+
+ if ( xModel.is() )
+ {
+ Reference< XEmbeddedScripts > xDocumentScripts( xModel, UNO_QUERY );
+ if ( xDocumentScripts.is() )
+ {
+ m_pDocBasicManager = ::basic::BasicManagerRepository::getDocumentBasicManager( xModel );
+ m_xLibContainerDoc.set( xDocumentScripts->getBasicLibraries(), UNO_QUERY );
+ OSL_ENSURE( m_pDocBasicManager && m_xLibContainerDoc.is(),
+ "BasicProviderImpl::initialize: invalid BasicManager, or invalid script container!" );
+ }
+ m_bIsAppScriptCtx = false;
+ }
+ else
+ {
+ // Provider has been created with application context for user
+ // or share
+ if ( !m_sScriptingContext.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "user" ) ) )
+ {
+ m_bIsUserCtx = false;
+ }
+ else
+ {
+ /*
+ throw RuntimeException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BasicProviderImpl::initialize: no scripting context!" ) ),
+ Reference< XInterface >() );
+ */
+ }
+ }
+
+ // TODO
+ if ( !m_pAppBasicManager )
+ m_pAppBasicManager = SFX_APP()->GetBasicManager();
+
+ if ( !m_xLibContainerApp.is() )
+ m_xLibContainerApp = Reference< script::XLibraryContainer >( SFX_APP()->GetBasicContainer(), UNO_QUERY );
+ }
+
+ // -----------------------------------------------------------------------------
+
+ // XScriptProvider
+ // -----------------------------------------------------------------------------
+
+ Reference < provider::XScript > BasicProviderImpl::getScript( const ::rtl::OUString& scriptURI )
+ throw ( provider::ScriptFrameworkErrorException, RuntimeException)
+ {
+ // TODO
+
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ Reference< provider::XScript > xScript;
+ Reference< lang::XMultiComponentFactory > xMcFac ( m_xContext->getServiceManager() );
+ Reference< uri::XUriReferenceFactory > xFac (
+ xMcFac->createInstanceWithContext( rtl::OUString::createFromAscii(
+ "com.sun.star.uri.UriReferenceFactory"), m_xContext ) , UNO_QUERY );
+
+ if ( !xFac.is() )
+ {
+ throw provider::ScriptFrameworkErrorException(
+ OUSTR( "Failed to instantiate UriReferenceFactory" ), Reference< XInterface >(),
+ scriptURI, OUSTR("Basic"),
+ provider::ScriptFrameworkErrorType::UNKNOWN );
+ }
+
+ Reference< uri::XUriReference > uriRef(
+ xFac->parse( scriptURI ), UNO_QUERY );
+
+ Reference < uri::XVndSunStarScriptUrl > sfUri( uriRef, UNO_QUERY );
+
+ if ( !uriRef.is() || !sfUri.is() )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "BasicProviderImpl::getScript: failed to parse URI: " );
+ errorMsg = errorMsg.concat( scriptURI );
+ throw provider::ScriptFrameworkErrorException(
+ errorMsg, Reference< XInterface >(),
+ scriptURI, OUSTR("Basic"),
+ provider::ScriptFrameworkErrorType::MALFORMED_URL );
+ }
+
+
+ ::rtl::OUString aDescription = sfUri->getName();
+ ::rtl::OUString aLocation = sfUri->getParameter(
+ ::rtl::OUString::createFromAscii( "location" ) );
+
+ sal_Int32 nIndex = 0;
+ ::rtl::OUString aLibrary = aDescription.getToken( 0, (sal_Unicode)'.', nIndex );
+ ::rtl::OUString aModule;
+ if ( nIndex != -1 )
+ aModule = aDescription.getToken( 0, (sal_Unicode)'.', nIndex );
+ ::rtl::OUString aMethod;
+ if ( nIndex != -1 )
+ aMethod = aDescription.getToken( 0, (sal_Unicode)'.', nIndex );
+
+ if ( aLibrary.getLength() != 0 && aModule.getLength() != 0 && aMethod.getLength() != 0 && aLocation.getLength() != 0 )
+ {
+ BasicManager* pBasicMgr = NULL;
+ if ( aLocation.equals( ::rtl::OUString::createFromAscii("document") ) )
+ {
+ pBasicMgr = m_pDocBasicManager;
+ }
+ else if ( aLocation.equals( ::rtl::OUString::createFromAscii("application") ) )
+ {
+ pBasicMgr = m_pAppBasicManager;
+ }
+
+ if ( pBasicMgr )
+ {
+ StarBASIC* pBasic = pBasicMgr->GetLib( aLibrary );
+ if ( !pBasic )
+ {
+ USHORT nId = pBasicMgr->GetLibId( aLibrary );
+ if ( nId != LIB_NOTFOUND )
+ {
+ pBasicMgr->LoadLib( nId );
+ pBasic = pBasicMgr->GetLib( aLibrary );
+ }
+ }
+ if ( pBasic )
+ {
+ SbModule* pModule = pBasic->FindModule( aModule );
+ if ( pModule )
+ {
+ SbxArray* pMethods = pModule->GetMethods();
+ if ( pMethods )
+ {
+ SbMethod* pMethod = static_cast< SbMethod* >( pMethods->Find( aMethod, SbxCLASS_METHOD ) );
+ if ( pMethod )
+ {
+ if ( m_pDocBasicManager == pBasicMgr )
+ xScript = new BasicScriptImpl( aDescription, pMethod, *m_pDocBasicManager, m_xInvocationContext );
+ else
+ xScript = new BasicScriptImpl( aDescription, pMethod );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if ( !xScript.is() )
+ {
+ ::rtl::OUStringBuffer aMessage;
+ aMessage.appendAscii( "The following Basic script could not be found:\n" );
+ aMessage.appendAscii( "library: '" ).append( aLibrary ).appendAscii( "'\n" );
+ aMessage.appendAscii( "module: '" ).append( aModule ).appendAscii( "'\n" );
+ aMessage.appendAscii( "method: '" ).append( aMethod ).appendAscii( "'\n" );
+ aMessage.appendAscii( "location: '" ).append( aLocation ).appendAscii( "'\n" );
+ throw provider::ScriptFrameworkErrorException(
+ aMessage.makeStringAndClear(),
+ Reference< XInterface >(),
+ scriptURI, OUSTR("Basic"),
+ provider::ScriptFrameworkErrorType::NO_SUCH_SCRIPT );
+ }
+
+ return xScript;
+ }
+
+ // -----------------------------------------------------------------------------
+ // XBrowseNode
+ // -----------------------------------------------------------------------------
+
+ ::rtl::OUString BasicProviderImpl::getName( ) throw (RuntimeException)
+ {
+ // TODO
+
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ return ::rtl::OUString::createFromAscii( "Basic" );
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Sequence< Reference< browse::XBrowseNode > > BasicProviderImpl::getChildNodes( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ Reference< script::XLibraryContainer > xLibContainer;
+ BasicManager* pBasicManager = NULL;
+
+ if ( m_bIsAppScriptCtx )
+ {
+ xLibContainer = m_xLibContainerApp;
+ pBasicManager = m_pAppBasicManager;
+ }
+ else
+ {
+ xLibContainer = m_xLibContainerDoc;
+ pBasicManager = m_pDocBasicManager;
+ }
+
+ Sequence< Reference< browse::XBrowseNode > > aChildNodes;
+
+ if ( pBasicManager && xLibContainer.is() )
+ {
+ Sequence< ::rtl::OUString > aLibNames = xLibContainer->getElementNames();
+ sal_Int32 nLibCount = aLibNames.getLength();
+ const ::rtl::OUString* pLibNames = aLibNames.getConstArray();
+ aChildNodes.realloc( nLibCount );
+ Reference< browse::XBrowseNode >* pChildNodes = aChildNodes.getArray();
+ sal_Int32 childsFound = 0;
+
+ for ( sal_Int32 i = 0 ; i < nLibCount ; ++i )
+ {
+ bool bCreate = false;
+ if ( m_bIsAppScriptCtx )
+ {
+ bool bShared = isLibraryShared( xLibContainer, pLibNames[i] );
+ if ( ( m_bIsUserCtx && !bShared ) || ( !m_bIsUserCtx && bShared ) )
+ bCreate = true;
+ }
+ else
+ {
+ bCreate = true;
+ }
+ if ( bCreate )
+ {
+ pChildNodes[childsFound++] = static_cast< browse::XBrowseNode* >( new BasicLibraryNodeImpl(
+ m_xContext, m_sScriptingContext, pBasicManager, xLibContainer, pLibNames[i], m_bIsAppScriptCtx ) );
+ }
+ }
+
+ if ( childsFound != nLibCount )
+ aChildNodes.realloc( childsFound );
+ }
+
+ return aChildNodes;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Bool BasicProviderImpl::hasChildNodes( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ sal_Bool bReturn = sal_False;
+ Reference< script::XLibraryContainer > xLibContainer;
+ if ( m_bIsAppScriptCtx )
+ {
+ xLibContainer = m_xLibContainerApp;
+ }
+ else
+ {
+ xLibContainer = m_xLibContainerDoc;
+ }
+ if ( xLibContainer.is() )
+ bReturn = xLibContainer->hasElements();
+
+ return bReturn;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Int16 BasicProviderImpl::getType( ) throw (RuntimeException)
+ {
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ return browse::BrowseNodeTypes::CONTAINER;
+ }
+
+ // =============================================================================
+ // component operations
+ // =============================================================================
+
+ static Reference< XInterface > SAL_CALL create_BasicProviderImpl(
+ Reference< XComponentContext > const & xContext )
+ SAL_THROW( () )
+ {
+ return static_cast< lang::XTypeProvider * >( new BasicProviderImpl( xContext ) );
+ }
+
+ // -----------------------------------------------------------------------------
+
+ static struct ::cppu::ImplementationEntry s_component_entries [] =
+ {
+ {
+ create_BasicProviderImpl, getImplementationName_BasicProviderImpl,
+ getSupportedServiceNames_BasicProviderImpl, ::cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ { 0, 0, 0, 0, 0, 0 }
+ };
+
+ // -----------------------------------------------------------------------------
+
+//.........................................................................
+} // namespace basprov
+//.........................................................................
+
+
+// =============================================================================
+// component exports
+// =============================================================================
+
+extern "C"
+{
+ SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment(
+ const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
+ {
+ (void)ppEnv;
+
+ *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
+ }
+
+ SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo(
+ lang::XMultiServiceFactory * pServiceManager, registry::XRegistryKey * pRegistryKey )
+ {
+ return ::cppu::component_writeInfoHelper(
+ pServiceManager, pRegistryKey, ::basprov::s_component_entries );
+ }
+
+ SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory(
+ const sal_Char * pImplName, lang::XMultiServiceFactory * pServiceManager,
+ registry::XRegistryKey * pRegistryKey )
+ {
+ return ::cppu::component_getFactoryHelper(
+ pImplName, pServiceManager, pRegistryKey, ::basprov::s_component_entries );
+ }
+}
diff --git a/scripting/source/basprov/basprov.hxx b/scripting/source/basprov/basprov.hxx
new file mode 100644
index 000000000000..afb09dbd7984
--- /dev/null
+++ b/scripting/source/basprov/basprov.hxx
@@ -0,0 +1,118 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: basprov.hxx,v $
+ * $Revision: 1.11 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef SCRIPTING_BASPROV_HXX
+#define SCRIPTING_BASPROV_HXX
+
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XInitialization.hpp>
+#include <com/sun/star/script/XLibraryContainer.hpp>
+#include <com/sun/star/script/browse/XBrowseNode.hpp>
+#include <com/sun/star/script/provider/XScriptProvider.hpp>
+#include <com/sun/star/document/XScriptInvocationContext.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <cppuhelper/implbase4.hxx>
+
+class BasicManager;
+
+
+//.........................................................................
+namespace basprov
+{
+//.........................................................................
+
+ // ----------------------------------------------------
+ // class BasicProviderImpl
+ // ----------------------------------------------------
+
+ typedef ::cppu::WeakImplHelper4<
+ ::com::sun::star::lang::XServiceInfo,
+ ::com::sun::star::lang::XInitialization,
+ ::com::sun::star::script::provider::XScriptProvider,
+ ::com::sun::star::script::browse::XBrowseNode > BasicProviderImpl_BASE;
+
+
+ class BasicProviderImpl : public BasicProviderImpl_BASE
+ {
+ private:
+ BasicManager* m_pAppBasicManager;
+ BasicManager* m_pDocBasicManager;
+ ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer > m_xLibContainerApp;
+ ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer > m_xLibContainerDoc;
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
+ ::com::sun::star::uno::Reference< ::com::sun::star::document::XScriptInvocationContext > m_xInvocationContext;
+ ::rtl::OUString m_sScriptingContext;
+ bool m_bIsAppScriptCtx;
+ bool m_bIsUserCtx;
+ ::rtl::OUString m_sCtxLocation;
+
+ bool isLibraryShared(
+ const ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >& rxLibContainer,
+ const ::rtl::OUString& rLibName );
+
+ public:
+ BasicProviderImpl(
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext );
+ virtual ~BasicProviderImpl();
+
+ // XServiceInfo
+ virtual ::rtl::OUString SAL_CALL getImplementationName( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XInitialization
+ virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+ // XScriptProvider
+ virtual ::com::sun::star::uno::Reference < ::com::sun::star::script::provider::XScript > SAL_CALL getScript(
+ const ::rtl::OUString& scriptURI )
+ throw ( ::com::sun::star::script::provider::ScriptFrameworkErrorException, ::com::sun::star::uno::RuntimeException);
+
+ // XBrowseNode
+ virtual ::rtl::OUString SAL_CALL getName( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::script::browse::XBrowseNode > > SAL_CALL getChildNodes( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL hasChildNodes( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Int16 SAL_CALL getType( )
+ throw (::com::sun::star::uno::RuntimeException);
+ };
+
+//.........................................................................
+} // namespace basprov
+//.........................................................................
+
+#endif // SCRIPTING_BASPROV_HXX
diff --git a/scripting/source/basprov/basprov.map b/scripting/source/basprov/basprov.map
new file mode 100644
index 000000000000..737cddbfe3df
--- /dev/null
+++ b/scripting/source/basprov/basprov.map
@@ -0,0 +1,9 @@
+OOO_1.1 {
+ global:
+ component_getImplementationEnvironment;
+ component_getFactory;
+ component_writeInfo;
+
+ local:
+ *;
+};
diff --git a/scripting/source/basprov/basprov.xml b/scripting/source/basprov/basprov.xml
new file mode 100644
index 000000000000..0ae341cce157
--- /dev/null
+++ b/scripting/source/basprov/basprov.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE module-description PUBLIC "-//StarOffice//DTD ComponentDescription 1.0//EN" "module-description.dtd">
+<module-description xmlns:xlink="http://www.w3.org/1999/xlink">
+
+ <module-name>basprov</module-name>
+
+ <component-description>
+ <author>Thomas Benisch</author>
+ <name>com.sun.star.comp.scripting.ScriptProviderForBasic</name>
+ <description>script provider for Basic</description>
+ <loader-name>com.sun.star.loader.SharedLibrary</loader-name>
+ <language>c++</language>
+ <status value="drafts"/>
+ <supported-service>com.sun.star.script.provider.ScriptProviderForBasic</supported-service>
+ <type>com.sun.star.beans.XPropertySet</type>
+ <type>com.sun.star.frame.XModel</type>
+ <type>com.sun.star.lang.IllegalArgumentException</type>
+ <type>com.sun.star.lang.XInitialization</type>
+ <type>com.sun.star.lang.XServiceInfo</type>
+ <type>com.sun.star.reflection.InvocationTargetException</type>
+ <type>com.sun.star.script.CannotConvertException</type>
+ <type>com.sun.star.uno.Exception</type>
+ <type>com.sun.star.uno.RuntimeException</type>
+ <type>com.sun.star.uno.XComponentContext</type>
+ <type>com.sun.star.script.browse.BrowseNodeTypes</type>
+ <type>com.sun.star.script.browse.XBrowseNode</type>
+ <type>com.sun.star.script.provider.XScript</type>
+ <type>com.sun.star.script.provider.XScriptProvider</type>
+ <type> com.sun.star.uri.XUriReference </type>
+ <type> com.sun.star.uri.XUriReferenceFactory </type>
+ <type> com.sun.star.uri.XVndSunStarScriptUrl </type>
+ </component-description>
+
+ <project-build-dependency>sfx2</project-build-dependency>
+ <project-build-dependency>basic</project-build-dependency>
+ <project-build-dependency>svtools</project-build-dependency>
+ <project-build-dependency>tools</project-build-dependency>
+ <project-build-dependency>cppuhelper</project-build-dependency>
+ <project-build-dependency>cppu</project-build-dependency>
+ <project-build-dependency>sal</project-build-dependency>
+
+ <runtime-module-dependency>sfx2</runtime-module-dependency>
+ <runtime-module-dependency>sb</runtime-module-dependency>
+ <runtime-module-dependency>svt</runtime-module-dependency>
+ <runtime-module-dependency>tl</runtime-module-dependency>
+ <runtime-module-dependency>cppuhelper3$(COM)</runtime-module-dependency>
+ <runtime-module-dependency>cppu3</runtime-module-dependency>
+ <runtime-module-dependency>sal3</runtime-module-dependency>
+
+</module-description>
diff --git a/scripting/source/basprov/basscript.cxx b/scripting/source/basprov/basscript.cxx
new file mode 100644
index 000000000000..64b775cccebf
--- /dev/null
+++ b/scripting/source/basprov/basscript.cxx
@@ -0,0 +1,229 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: basscript.cxx,v $
+ * $Revision: 1.16.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include "basscript.hxx"
+#include <vos/mutex.hxx>
+#include <vcl/svapp.hxx>
+#include <basic/sbx.hxx>
+#include <basic/sbstar.hxx>
+#include <basic/sbmod.hxx>
+#include <basic/sbmeth.hxx>
+#include <basic/basmgr.hxx>
+#include <com/sun/star/script/provider/ScriptFrameworkErrorType.hpp>
+
+#include <map>
+
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::script;
+using namespace ::com::sun::star::document;
+
+extern ::com::sun::star::uno::Any sbxToUnoValue( SbxVariable* pVar );
+extern void unoToSbxValue( SbxVariable* pVar, const ::com::sun::star::uno::Any& aValue );
+
+
+//.........................................................................
+namespace basprov
+{
+//.........................................................................
+
+ typedef ::std::map< sal_Int16, Any, ::std::less< sal_Int16 > > OutParamMap;
+
+ // =============================================================================
+ // BasicScriptImpl
+ // =============================================================================
+
+ // -----------------------------------------------------------------------------
+
+ BasicScriptImpl::BasicScriptImpl( const ::rtl::OUString& funcName, SbMethodRef xMethod )
+ :m_xMethod( xMethod )
+ ,m_funcName( funcName )
+ ,m_documentBasicManager( NULL )
+ ,m_xDocumentScriptContext()
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+
+ BasicScriptImpl::BasicScriptImpl( const ::rtl::OUString& funcName, SbMethodRef xMethod,
+ BasicManager& documentBasicManager, const Reference< XScriptInvocationContext >& documentScriptContext )
+ :m_xMethod( xMethod )
+ ,m_funcName( funcName )
+ ,m_documentBasicManager( &documentBasicManager )
+ ,m_xDocumentScriptContext( documentScriptContext )
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+ BasicScriptImpl::~BasicScriptImpl()
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+ // XScript
+ // -----------------------------------------------------------------------------
+
+ Any BasicScriptImpl::invoke( const Sequence< Any >& aParams, Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam )
+ throw ( provider::ScriptFrameworkErrorException, reflection::InvocationTargetException, uno::RuntimeException)
+ {
+ // TODO: throw CannotConvertException
+ // TODO: check length of aOutParamIndex, aOutParam
+
+ ::vos::OGuard aGuard( Application::GetSolarMutex() );
+
+ Any aReturn;
+
+ if ( m_xMethod )
+ {
+ // check if compiled
+ SbModule* pModule = static_cast< SbModule* >( m_xMethod->GetParent() );
+ if ( pModule && !pModule->IsCompiled() )
+ pModule->Compile();
+
+ // check number of parameters
+ sal_Int32 nParamsCount = aParams.getLength();
+ SbxInfo* pInfo = m_xMethod->GetInfo();
+ if ( pInfo )
+ {
+ sal_Int32 nSbxOptional = 0;
+ USHORT n = 1;
+ for ( const SbxParamInfo* pParamInfo = pInfo->GetParam( n ); pParamInfo; pParamInfo = pInfo->GetParam( ++n ) )
+ {
+ if ( ( pParamInfo->nFlags & SBX_OPTIONAL ) != 0 )
+ ++nSbxOptional;
+ else
+ nSbxOptional = 0;
+ }
+ sal_Int32 nSbxCount = n - 1;
+ if ( nParamsCount < nSbxCount - nSbxOptional )
+ {
+ throw provider::ScriptFrameworkErrorException(
+ ::rtl::OUString(
+ RTL_CONSTASCII_USTRINGPARAM(
+ "wrong number of parameters!" ) ),
+ Reference< XInterface >(),
+ m_funcName,
+ ::rtl::OUString(
+ RTL_CONSTASCII_USTRINGPARAM( "Basic" ) ),
+ provider::ScriptFrameworkErrorType::NO_SUCH_SCRIPT );
+ }
+ }
+
+ // set parameters
+ SbxArrayRef xSbxParams;
+ if ( nParamsCount > 0 )
+ {
+ xSbxParams = new SbxArray;
+ const Any* pParams = aParams.getConstArray();
+ for ( sal_Int32 i = 0; i < nParamsCount; ++i )
+ {
+ SbxVariableRef xSbxVar = new SbxVariable( SbxVARIANT );
+ unoToSbxValue( static_cast< SbxVariable* >( xSbxVar ), pParams[i] );
+ xSbxParams->Put( xSbxVar, static_cast< USHORT >( i ) + 1 );
+
+ // Enable passing by ref
+ if ( xSbxVar->GetType() != SbxVARIANT )
+ xSbxVar->SetFlag( SBX_FIXED );
+ }
+ }
+ if ( xSbxParams.Is() )
+ m_xMethod->SetParameters( xSbxParams );
+
+ // call method
+ SbxVariableRef xReturn = new SbxVariable;
+ ErrCode nErr = SbxERR_OK;
+ {
+ // if it's a document-based script, temporarily reset ThisComponent to the script invocation context
+ Any aOldThisComponent;
+ if ( m_documentBasicManager && m_xDocumentScriptContext.is() )
+ aOldThisComponent = m_documentBasicManager->SetGlobalUNOConstant( "ThisComponent", makeAny( m_xDocumentScriptContext ) );
+
+ nErr = m_xMethod->Call( xReturn );
+
+ if ( m_documentBasicManager && m_xDocumentScriptContext.is() )
+ m_documentBasicManager->SetGlobalUNOConstant( "ThisComponent", aOldThisComponent );
+ }
+ if ( nErr != SbxERR_OK )
+ {
+ // TODO: throw InvocationTargetException ?
+ }
+
+ // get output parameters
+ if ( xSbxParams.Is() )
+ {
+ SbxInfo* pInfo_ = m_xMethod->GetInfo();
+ if ( pInfo_ )
+ {
+ OutParamMap aOutParamMap;
+ for ( USHORT n = 1, nCount = xSbxParams->Count(); n < nCount; ++n )
+ {
+ const SbxParamInfo* pParamInfo = pInfo_->GetParam( n );
+ if ( pParamInfo && ( pParamInfo->eType & SbxBYREF ) != 0 )
+ {
+ SbxVariable* pVar = xSbxParams->Get( n );
+ if ( pVar )
+ {
+ SbxVariableRef xVar = pVar;
+ aOutParamMap.insert( OutParamMap::value_type( n - 1, sbxToUnoValue( xVar ) ) );
+ }
+ }
+ }
+ sal_Int32 nOutParamCount = aOutParamMap.size();
+ aOutParamIndex.realloc( nOutParamCount );
+ aOutParam.realloc( nOutParamCount );
+ sal_Int16* pOutParamIndex = aOutParamIndex.getArray();
+ Any* pOutParam = aOutParam.getArray();
+ for ( OutParamMap::iterator aIt = aOutParamMap.begin(); aIt != aOutParamMap.end(); ++aIt, ++pOutParamIndex, ++pOutParam )
+ {
+ *pOutParamIndex = aIt->first;
+ *pOutParam = aIt->second;
+ }
+ }
+ }
+
+ // get return value
+ aReturn = sbxToUnoValue( xReturn );
+
+ // reset parameters
+ m_xMethod->SetParameters( NULL );
+ }
+
+ return aReturn;
+ }
+
+ // -----------------------------------------------------------------------------
+
+//.........................................................................
+} // namespace basprov
+//.........................................................................
diff --git a/scripting/source/basprov/basscript.hxx b/scripting/source/basprov/basscript.hxx
new file mode 100644
index 000000000000..83796e98582a
--- /dev/null
+++ b/scripting/source/basprov/basscript.hxx
@@ -0,0 +1,92 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: basscript.hxx,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef SCRIPTING_BASSCRIPT_HXX
+#define SCRIPTING_BASSCRIPT_HXX
+
+#include <com/sun/star/script/provider/XScript.hpp>
+#include <com/sun/star/document/XScriptInvocationContext.hpp>
+#include <cppuhelper/implbase1.hxx>
+#include <basic/sbmeth.hxx>
+
+
+class BasicManager;
+
+//.........................................................................
+namespace basprov
+{
+//.........................................................................
+
+ // ----------------------------------------------------
+ // class BasicScriptImpl
+ // ----------------------------------------------------
+
+ typedef ::cppu::WeakImplHelper1<
+ ::com::sun::star::script::provider::XScript > BasicScriptImpl_BASE;
+
+
+ class BasicScriptImpl : public BasicScriptImpl_BASE
+ {
+ private:
+ SbMethodRef m_xMethod;
+ ::rtl::OUString m_funcName;
+ BasicManager* m_documentBasicManager;
+ ::com::sun::star::uno::Reference< ::com::sun::star::document::XScriptInvocationContext >
+ m_xDocumentScriptContext;
+
+ public:
+ BasicScriptImpl(
+ const ::rtl::OUString& funcName,
+ SbMethodRef xMethod
+ );
+ BasicScriptImpl(
+ const ::rtl::OUString& funcName,
+ SbMethodRef xMethod,
+ BasicManager& documentBasicManager,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::document::XScriptInvocationContext >& documentScriptContext
+ );
+ virtual ~BasicScriptImpl();
+
+ // XScript
+ virtual ::com::sun::star::uno::Any SAL_CALL invoke(
+ const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aParams,
+ ::com::sun::star::uno::Sequence< sal_Int16 >& aOutParamIndex,
+ ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aOutParam )
+ throw (
+ ::com::sun::star::script::provider::ScriptFrameworkErrorException,
+ ::com::sun::star::reflection::InvocationTargetException,
+ ::com::sun::star::uno::RuntimeException );
+ };
+
+//.........................................................................
+} // namespace basprov
+//.........................................................................
+
+#endif // SCRIPTING_BASSCRIPT_HXX
diff --git a/scripting/source/basprov/makefile.mk b/scripting/source/basprov/makefile.mk
new file mode 100644
index 000000000000..2b6fe7faa305
--- /dev/null
+++ b/scripting/source/basprov/makefile.mk
@@ -0,0 +1,77 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.9 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+PRJ=..$/..
+
+PRJNAME=scripting
+TARGET=basprov
+ENABLE_EXCEPTIONS=TRUE
+VISIBILITY_HIDDEN=TRUE
+COMP1TYPELIST=$(TARGET)
+
+# --- Settings -----------------------------------------------------
+
+.INCLUDE : settings.mk
+DLLPRE =
+
+# ------------------------------------------------------------------
+
+SLOFILES= \
+ $(SLO)$/basprov.obj \
+ $(SLO)$/basscript.obj \
+ $(SLO)$/baslibnode.obj \
+ $(SLO)$/basmodnode.obj \
+ $(SLO)$/basmethnode.obj
+
+SHL1TARGET= $(TARGET)$(DLLPOSTFIX).uno
+SHL1IMPLIB= i$(TARGET)
+
+SHL1VERSIONMAP=$(TARGET).map
+SHL1DEF=$(MISC)$/$(SHL1TARGET).def
+DEF1NAME=$(SHL1TARGET)
+
+SHL1STDLIBS= \
+ $(SFX2LIB) \
+ $(BASICLIB) \
+ $(VCLLIB) \
+ $(TOOLSLIB) \
+ $(UCBHELPERLIB) \
+ $(COMPHELPERLIB) \
+ $(CPPUHELPERLIB) \
+ $(CPPULIB) \
+ $(SALLIB)
+
+SHL1DEPN=
+SHL1LIBS=$(SLB)$/$(TARGET).lib
+
+# --- Targets ------------------------------------------------------
+
+.INCLUDE : target.mk
diff --git a/scripting/source/dlgprov/dlgevtatt.cxx b/scripting/source/dlgprov/dlgevtatt.cxx
new file mode 100644
index 000000000000..6a6b6dbbbb4a
--- /dev/null
+++ b/scripting/source/dlgprov/dlgevtatt.cxx
@@ -0,0 +1,677 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: dlgevtatt.cxx,v $
+ * $Revision: 1.15 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include "dlgevtatt.hxx"
+
+#ifndef SCRIPTING_DLGPROV_HXX
+#include "dlgprov.hxx"
+#endif
+#include <sfx2/sfx.hrc>
+#include <sfx2/app.hxx>
+#ifndef _MSGBOX_HXX //autogen
+#include <vcl/msgbox.hxx>
+#endif
+#include <com/sun/star/awt/XControl.hpp>
+#include <com/sun/star/awt/XDialogEventHandler.hpp>
+#include <com/sun/star/awt/XContainerWindowEventHandler.hpp>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/script/ScriptEventDescriptor.hpp>
+#include <com/sun/star/script/XScriptEventsSupplier.hpp>
+#include <com/sun/star/script/provider/XScriptProvider.hpp>
+#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
+#include <com/sun/star/script/provider/XScriptProviderSupplier.hpp>
+#include <com/sun/star/lang/NoSuchMethodException.hpp>
+#include <com/sun/star/reflection/XIdlMethod.hpp>
+#include <com/sun/star/beans/MethodConcept.hpp>
+#include <com/sun/star/beans/XMaterialHolder.hpp>
+#ifdef FAKE_VBA_EVENT_SUPPORT
+#include <ooo/vba/XVBAToOOEventDescGen.hpp>
+#endif
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::awt;
+using namespace ::com::sun::star::beans;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::script;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::script;
+using namespace ::com::sun::star::reflection;
+
+
+//.........................................................................
+namespace dlgprov
+{
+
+ class DialogSFScriptListenerImpl : public DialogScriptListenerImpl
+ {
+ protected:
+ Reference< frame::XModel > m_xModel;
+ virtual void firing_impl( const script::ScriptEvent& aScriptEvent, uno::Any* pRet );
+ public:
+ DialogSFScriptListenerImpl( const Reference< XComponentContext >& rxContext, const Reference< frame::XModel >& rxModel ) : DialogScriptListenerImpl( rxContext ), m_xModel( rxModel ) {}
+ };
+
+ class DialogLegacyScriptListenerImpl : public DialogSFScriptListenerImpl
+ {
+ protected:
+ virtual void firing_impl( const script::ScriptEvent& aScriptEvent, uno::Any* pRet );
+ public:
+ DialogLegacyScriptListenerImpl( const Reference< XComponentContext >& rxContext, const Reference< frame::XModel >& rxModel ) : DialogSFScriptListenerImpl( rxContext, rxModel ){}
+ };
+
+ class DialogUnoScriptListenerImpl : public DialogSFScriptListenerImpl
+ {
+ Reference< awt::XControl > m_xControl;
+ Reference< XInterface > m_xHandler;
+ Reference< beans::XIntrospectionAccess > m_xIntrospectionAccess;
+ bool m_bDialogProviderMode;
+
+ virtual void firing_impl( const script::ScriptEvent& aScriptEvent, uno::Any* pRet );
+
+ public:
+ DialogUnoScriptListenerImpl( const Reference< XComponentContext >& rxContext,
+ const Reference< frame::XModel >& rxModel,
+ const Reference< awt::XControl >& rxControl,
+ const Reference< XInterface >& rxHandler,
+ const Reference< beans::XIntrospectionAccess >& rxIntrospectionAccess,
+ bool bDialogProviderMode ); // false: ContainerWindowProvider mode
+
+ };
+
+#ifdef FAKE_VBA_EVENT_SUPPORT
+ class DialogVBAScriptListenerImpl : public DialogScriptListenerImpl
+ {
+ protected:
+ rtl::OUString msDialogCodeName;
+ Reference< script::XScriptListener > mxListener;
+ virtual void firing_impl( const script::ScriptEvent& aScriptEvent, uno::Any* pRet );
+ public:
+ DialogVBAScriptListenerImpl( const Reference< XComponentContext >& rxContext, const Reference< awt::XControl >& rxControl, const Reference< frame::XModel >& xModel );
+ };
+
+ DialogVBAScriptListenerImpl::DialogVBAScriptListenerImpl( const Reference< XComponentContext >& rxContext, const Reference< awt::XControl >& rxControl, const Reference< frame::XModel >& xModel ) : DialogScriptListenerImpl( rxContext )
+ {
+ Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager() );
+ if ( xSMgr.is() )
+ {
+ Sequence< Any > args(1);
+ args[0] <<= xModel;
+ mxListener = Reference< XScriptListener >( xSMgr->createInstanceWithArgumentsAndContext( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ooo.vba.EventListener" ) ), args, m_xContext ), UNO_QUERY );
+ }
+ if ( rxControl.is() )
+ {
+ Reference< XPropertySet > xProps( rxControl->getModel(), UNO_QUERY );
+ try
+ {
+ xProps->getPropertyValue( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Name") ) ) >>= msDialogCodeName;
+ }
+ catch ( Exception& ) {}
+ }
+
+ }
+
+ void DialogVBAScriptListenerImpl::firing_impl( const script::ScriptEvent& aScriptEvent, uno::Any* )
+ {
+ if ( aScriptEvent.ScriptType.equals( rtl::OUString::createFromAscii("VBAInterop") ) && mxListener.is() )
+ {
+ ScriptEvent aScriptEventCopy( aScriptEvent );
+ aScriptEventCopy.ScriptCode = msDialogCodeName;
+ try
+ {
+ mxListener->firing( aScriptEventCopy );
+ }
+ catch( Exception& ) {}
+ }
+ }
+#endif
+
+//.........................................................................
+
+ // =============================================================================
+ // DialogEventsAttacherImpl
+ // =============================================================================
+
+ DialogEventsAttacherImpl::DialogEventsAttacherImpl( const Reference< XComponentContext >& rxContext, const Reference< frame::XModel >& rxModel, const Reference< awt::XControl >& rxControl, const Reference< XInterface >& rxHandler, const Reference< beans::XIntrospectionAccess >& rxIntrospect, bool bProviderMode, const Reference< script::XScriptListener >& rxRTLListener )
+ :m_xContext( rxContext )
+ {
+ // key listeners by protocol when ScriptType = 'Script'
+ // otherwise key is the ScriptType e.g. StarBasic
+ if ( rxRTLListener.is() ) // set up handler for RTL_BASIC
+ listernersForTypes[ rtl::OUString::createFromAscii("StarBasic") ] = rxRTLListener;
+ else
+ listernersForTypes[ rtl::OUString::createFromAscii("StarBasic") ] = new DialogLegacyScriptListenerImpl( rxContext, rxModel );
+ // handler for Script & ::rtl::OUString::createFromAscii( "vnd.sun.star.UNO:" )
+ listernersForTypes[ rtl::OUString::createFromAscii("vnd.sun.star.UNO") ] = new DialogUnoScriptListenerImpl( rxContext, rxModel, rxControl, rxHandler, rxIntrospect, bProviderMode );
+ listernersForTypes[ rtl::OUString::createFromAscii("vnd.sun.star.script") ] = new DialogSFScriptListenerImpl( rxContext, rxModel );
+#ifdef FAKE_VBA_EVENT_SUPPORT
+ listernersForTypes[ rtl::OUString::createFromAscii("VBAInterop") ] = new DialogVBAScriptListenerImpl( rxContext, rxControl, rxModel );
+#endif
+ }
+
+ // -----------------------------------------------------------------------------
+
+ DialogEventsAttacherImpl::~DialogEventsAttacherImpl()
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+ Reference< script::XScriptListener >
+ DialogEventsAttacherImpl::getScriptListenerForKey( const rtl::OUString& sKey ) throw ( RuntimeException )
+ {
+ ListenerHash::iterator it = listernersForTypes.find( sKey );
+ if ( it == listernersForTypes.end() )
+ throw RuntimeException(); // more text info here please
+ return it->second;
+ }
+#ifdef FAKE_VBA_EVENT_SUPPORT
+ Reference< XScriptEventsSupplier > DialogEventsAttacherImpl::getFakeVbaEventsSupplier( const Reference< XControl >& xControl )
+ {
+ Reference< XScriptEventsSupplier > xEventsSupplier;
+ Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager() );
+ if ( xSMgr.is() )
+ {
+ Reference< ooo::vba::XVBAToOOEventDescGen > xVBAToOOEvtDesc( xSMgr->createInstanceWithContext( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ooo.vba.VBAToOOEventDesc" ) ), m_xContext ), UNO_QUERY );
+ if ( xVBAToOOEvtDesc.is() )
+ xEventsSupplier.set( xVBAToOOEvtDesc->getEventSupplier( xControl ), UNO_QUERY );
+
+ }
+ return xEventsSupplier;
+ }
+#endif
+
+ // -----------------------------------------------------------------------------
+ void SAL_CALL DialogEventsAttacherImpl::attachEventsToControl( const Reference< XControl>& xControl, const Reference< XScriptEventsSupplier >& xEventsSupplier, const Any& Helper )
+ {
+ if ( xEventsSupplier.is() )
+ {
+ Reference< container::XNameContainer > xEventCont = xEventsSupplier->getEvents();
+
+ Reference< XControlModel > xControlModel = xControl->getModel();
+ if ( xEventCont.is() )
+ {
+ Sequence< ::rtl::OUString > aNames = xEventCont->getElementNames();
+ const ::rtl::OUString* pNames = aNames.getConstArray();
+ sal_Int32 nNameCount = aNames.getLength();
+
+ for ( sal_Int32 j = 0; j < nNameCount; ++j )
+ {
+ ScriptEventDescriptor aDesc;
+
+ Any aElement = xEventCont->getByName( pNames[ j ] );
+ aElement >>= aDesc;
+ rtl::OUString sKey = aDesc.ScriptType;
+ if ( aDesc.ScriptType.equals( rtl::OUString::createFromAscii("Script" ) ) || aDesc.ScriptType.equals( rtl::OUString::createFromAscii("UNO" ) ) )
+ {
+ sal_Int32 nIndex = aDesc.ScriptCode.indexOf( ':' );
+ sKey = aDesc.ScriptCode.copy( 0, nIndex );
+ }
+ Reference< XAllListener > xAllListener =
+ new DialogAllListenerImpl( getScriptListenerForKey( sKey ), aDesc.ScriptType, aDesc.ScriptCode );
+
+ // try first to attach event to the ControlModel
+ bool bSuccess = false;
+ try
+ {
+ Reference< XEventListener > xListener_ = m_xEventAttacher->attachSingleEventListener(
+ xControlModel, xAllListener, Helper, aDesc.ListenerType,
+ aDesc.AddListenerParam, aDesc.EventMethod );
+
+ if ( xListener_.is() )
+ bSuccess = true;
+ }
+ catch ( IllegalArgumentException& )
+ {
+ }
+ catch ( IntrospectionException& )
+ {
+ }
+ catch ( CannotCreateAdapterException& )
+ {
+ }
+ catch ( ServiceNotRegisteredException& )
+ {
+ }
+
+ try
+ {
+ // if we had no success, try to attach to the control
+ if ( !bSuccess )
+ {
+ Reference< XEventListener > xListener_ = m_xEventAttacher->attachSingleEventListener(
+ xControl, xAllListener, Helper, aDesc.ListenerType,
+ aDesc.AddListenerParam, aDesc.EventMethod );
+ }
+ }
+ catch( IllegalArgumentException& )
+ {
+ }
+ catch( IntrospectionException& )
+ {
+ }
+ catch( CannotCreateAdapterException& )
+ {
+ }
+ catch( ServiceNotRegisteredException& )
+ {
+ }
+ }
+ }
+ }
+ }
+
+ // -----------------------------------------------------------------------------
+ // XScriptEventsAttacher
+ // -----------------------------------------------------------------------------
+
+ void SAL_CALL DialogEventsAttacherImpl::attachEvents( const Sequence< Reference< XInterface > >& Objects,
+ const com::sun::star::uno::Reference<com::sun::star::script::XScriptListener>&,
+ const Any& Helper )
+ throw (IllegalArgumentException, IntrospectionException, CannotCreateAdapterException,
+ ServiceNotRegisteredException, RuntimeException)
+ {
+ // get EventAttacher
+ {
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ if ( !m_xEventAttacher.is() )
+ {
+ Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager() );
+ if ( xSMgr.is() )
+ {
+ m_xEventAttacher = Reference< XEventAttacher >( xSMgr->createInstanceWithContext(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.script.EventAttacher" ) ), m_xContext ), UNO_QUERY );
+
+ if ( !m_xEventAttacher.is() )
+ throw ServiceNotRegisteredException();
+ }
+ else
+ {
+ throw RuntimeException();
+ }
+
+ }
+ }
+
+ // go over all objects
+ const Reference< XInterface >* pObjects = Objects.getConstArray();
+ sal_Int32 nObjCount = Objects.getLength();
+ for ( sal_Int32 i = 0; i < nObjCount; ++i )
+ {
+ // We know that we have to do with instances of XControl.
+ // Otherwise this is not the right implementation for
+ // XScriptEventsAttacher and we have to give up.
+ Reference< XControl > xControl( pObjects[ i ], UNO_QUERY );
+ if ( !xControl.is() )
+ throw IllegalArgumentException();
+
+ // get XEventsSupplier from control model
+ Reference< XControlModel > xControlModel = xControl->getModel();
+ Reference< XScriptEventsSupplier > xEventsSupplier( xControlModel, UNO_QUERY );
+ attachEventsToControl( xControl, xEventsSupplier, Helper );
+#ifdef FAKE_VBA_EVENT_SUPPORT
+ xEventsSupplier.set( getFakeVbaEventsSupplier( xControl ) );
+ attachEventsToControl( xControl, xEventsSupplier, Helper );
+#endif
+ }
+ }
+
+
+ // =============================================================================
+ // DialogAllListenerImpl
+ // =============================================================================
+
+ DialogAllListenerImpl::DialogAllListenerImpl( const Reference< XScriptListener >& rxListener,
+ const ::rtl::OUString& rScriptType, const ::rtl::OUString& rScriptCode )
+ :m_xScriptListener( rxListener )
+ ,m_sScriptType( rScriptType )
+ ,m_sScriptCode( rScriptCode )
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+
+ DialogAllListenerImpl::~DialogAllListenerImpl()
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+
+ void DialogAllListenerImpl::firing_impl( const AllEventObject& Event, Any* pRet )
+ {
+ ScriptEvent aScriptEvent;
+ aScriptEvent.Source = (OWeakObject *)this; // get correct XInterface
+ aScriptEvent.ListenerType = Event.ListenerType;
+ aScriptEvent.MethodName = Event.MethodName;
+ aScriptEvent.Arguments = Event.Arguments;
+ aScriptEvent.Helper = Event.Helper;
+ aScriptEvent.ScriptType = m_sScriptType;
+ aScriptEvent.ScriptCode = m_sScriptCode;
+
+ if ( m_xScriptListener.is() )
+ {
+ if ( pRet )
+ *pRet = m_xScriptListener->approveFiring( aScriptEvent );
+ else
+ m_xScriptListener->firing( aScriptEvent );
+ }
+ }
+
+ // -----------------------------------------------------------------------------
+ // XEventListener
+ // -----------------------------------------------------------------------------
+
+ void DialogAllListenerImpl::disposing(const EventObject& ) throw ( RuntimeException )
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+ // XAllListener
+ // -----------------------------------------------------------------------------
+
+ void DialogAllListenerImpl::firing( const AllEventObject& Event ) throw ( RuntimeException )
+ {
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ firing_impl( Event, NULL );
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Any DialogAllListenerImpl::approveFiring( const AllEventObject& Event )
+ throw ( reflection::InvocationTargetException, RuntimeException )
+ {
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ Any aReturn;
+ firing_impl( Event, &aReturn );
+ return aReturn;
+ }
+
+
+ // =============================================================================
+ // DialogScriptListenerImpl
+ // =============================================================================
+
+ DialogUnoScriptListenerImpl::DialogUnoScriptListenerImpl( const Reference< XComponentContext >& rxContext,
+ const Reference< ::com::sun::star::frame::XModel >& rxModel,
+ const Reference< ::com::sun::star::awt::XControl >& rxControl,
+ const Reference< ::com::sun::star::uno::XInterface >& rxHandler,
+ const Reference< ::com::sun::star::beans::XIntrospectionAccess >& rxIntrospectionAccess,
+ bool bDialogProviderMode )
+ : DialogSFScriptListenerImpl( rxContext, rxModel )
+ ,m_xControl( rxControl )
+ ,m_xHandler( rxHandler )
+ ,m_xIntrospectionAccess( rxIntrospectionAccess )
+ ,m_bDialogProviderMode( bDialogProviderMode )
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+
+ DialogScriptListenerImpl::~DialogScriptListenerImpl()
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+ void DialogSFScriptListenerImpl::firing_impl( const ScriptEvent& aScriptEvent, Any* pRet )
+ {
+ try
+ {
+ Reference< provider::XScriptProvider > xScriptProvider;
+ if ( m_xModel.is() )
+ {
+ Reference< provider::XScriptProviderSupplier > xSupplier( m_xModel, UNO_QUERY );
+ OSL_ENSURE( xSupplier.is(), "DialogScriptListenerImpl::firing_impl: failed to get script provider supplier" );
+ if ( xSupplier.is() )
+ xScriptProvider.set( xSupplier->getScriptProvider() );
+ }
+ else
+ {
+ OSL_ASSERT( m_xContext.is() );
+ if ( m_xContext.is() )
+ {
+ Reference< provider::XScriptProviderFactory > xFactory(
+ m_xContext->getValueByName(
+ ::rtl::OUString::createFromAscii( "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory" ) ),
+ UNO_QUERY );
+ OSL_ENSURE( xFactory.is(), "SFURL_firing_impl: failed to get master script provider factory" );
+ if ( xFactory.is() )
+ {
+ Any aCtx;
+ aCtx <<= ::rtl::OUString::createFromAscii( "user" );
+ xScriptProvider.set( xFactory->createScriptProvider( aCtx ), UNO_QUERY );
+ }
+ }
+ }
+
+ OSL_ENSURE( xScriptProvider.is(), "DialogScriptListenerImpl::firing_impl: failed to get script provider" );
+
+ if ( xScriptProvider.is() )
+ {
+ Reference< provider::XScript > xScript = xScriptProvider->getScript( aScriptEvent.ScriptCode );
+ OSL_ENSURE( xScript.is(), "DialogScriptListenerImpl::firing_impl: failed to get script" );
+
+ if ( xScript.is() )
+ {
+ Sequence< Any > aInParams;
+ Sequence< sal_Int16 > aOutParamsIndex;
+ Sequence< Any > aOutParams;
+
+ // get arguments for script
+ aInParams = aScriptEvent.Arguments;
+
+ Any aResult = xScript->invoke( aInParams, aOutParamsIndex, aOutParams );
+ if ( pRet )
+ *pRet = aResult;
+ }
+ }
+ }
+ catch ( RuntimeException& e )
+ {
+ OSL_TRACE( "DialogScriptListenerImpl::firing_impl: caught RuntimeException reason %s",
+ ::rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }
+ catch ( Exception& e )
+ {
+ OSL_TRACE( "DialogScriptListenerImpl::firing_impl: caught Exception reason %s",
+ ::rtl::OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }
+ }
+
+ void DialogLegacyScriptListenerImpl::firing_impl( const ScriptEvent& aScriptEvent, Any* pRet )
+ {
+ ::rtl::OUString sScriptURL;
+ ::rtl::OUString sScriptCode( aScriptEvent.ScriptCode );
+
+ if ( aScriptEvent.ScriptType.compareToAscii( "StarBasic" ) == 0 )
+ {
+ // StarBasic script: convert ScriptCode to scriptURL
+ sal_Int32 nIndex = sScriptCode.indexOf( ':' );
+ if ( nIndex >= 0 && nIndex < sScriptCode.getLength() )
+ {
+ sScriptURL = ::rtl::OUString::createFromAscii( "vnd.sun.star.script:" );
+ sScriptURL += sScriptCode.copy( nIndex + 1 );
+ sScriptURL += ::rtl::OUString::createFromAscii( "?language=Basic&location=" );
+ sScriptURL += sScriptCode.copy( 0, nIndex );
+ }
+ ScriptEvent aSFScriptEvent( aScriptEvent );
+ aSFScriptEvent.ScriptCode = sScriptURL;
+ DialogSFScriptListenerImpl::firing_impl( aSFScriptEvent, pRet );
+ }
+ }
+
+ void DialogUnoScriptListenerImpl::firing_impl( const ScriptEvent& aScriptEvent, Any* pRet )
+ {
+ static ::rtl::OUString sUnoURLScheme = ::rtl::OUString::createFromAscii( "vnd.sun.star.UNO:" );
+
+ ::rtl::OUString sScriptCode( aScriptEvent.ScriptCode );
+ ::rtl::OUString aMethodName = aScriptEvent.ScriptCode.copy( sUnoURLScheme.getLength() );
+
+ const Any* pArguments = aScriptEvent.Arguments.getConstArray();
+ Any aEventObject = pArguments[0];
+
+ bool bHandled = false;
+ if( m_xHandler.is() )
+ {
+ if( m_bDialogProviderMode )
+ {
+ Reference< XDialogEventHandler > xDialogEventHandler( m_xHandler, UNO_QUERY );
+ if( xDialogEventHandler.is() )
+ {
+ Reference< XDialog > xDialog( m_xControl, UNO_QUERY );
+ bHandled = xDialogEventHandler->callHandlerMethod( xDialog, aEventObject, aMethodName );
+ }
+ }
+ else
+ {
+ Reference< XContainerWindowEventHandler > xContainerWindowEventHandler( m_xHandler, UNO_QUERY );
+ if( xContainerWindowEventHandler.is() )
+ {
+ Reference< XWindow > xWindow( m_xControl, UNO_QUERY );
+ bHandled = xContainerWindowEventHandler->callHandlerMethod( xWindow, aEventObject, aMethodName );
+ }
+ }
+ }
+
+ Any aRet;
+ if( !bHandled && m_xIntrospectionAccess.is() )
+ {
+ try
+ {
+ // Methode ansprechen
+ const Reference< XIdlMethod >& rxMethod = m_xIntrospectionAccess->
+ getMethod( aMethodName, MethodConcept::ALL - MethodConcept::DANGEROUS );
+
+ Reference< XMaterialHolder > xMaterialHolder =
+ Reference< XMaterialHolder >::query( m_xIntrospectionAccess );
+ Any aHandlerObject = xMaterialHolder->getMaterial();
+
+ Sequence< Reference< XIdlClass > > aParamTypeSeq = rxMethod->getParameterTypes();
+ sal_Int32 nParamCount = aParamTypeSeq.getLength();
+ if( nParamCount == 0 )
+ {
+ Sequence<Any> args;
+ rxMethod->invoke( aHandlerObject, args );
+ bHandled = true;
+ }
+ else if( nParamCount == 2 )
+ {
+ // Signature check automatically done by reflection
+ Sequence<Any> Args(2);
+ Any* pArgs = Args.getArray();
+ if( m_bDialogProviderMode )
+ {
+ Reference< XDialog > xDialog( m_xControl, UNO_QUERY );
+ pArgs[0] <<= xDialog;
+ }
+ else
+ {
+ Reference< XWindow > xWindow( m_xControl, UNO_QUERY );
+ pArgs[0] <<= xWindow;
+ }
+ pArgs[1] = aEventObject;
+ aRet = rxMethod->invoke( aHandlerObject, Args );
+ bHandled = true;
+ }
+ }
+ catch( com::sun::star::lang::IllegalArgumentException& )
+ {}
+ catch( com::sun::star::lang::NoSuchMethodException& )
+ {}
+ catch( com::sun::star::reflection::InvocationTargetException& )
+ {}
+ }
+
+ if( bHandled )
+ {
+ if( pRet )
+ *pRet = aRet;
+ }
+ else
+ {
+ ResMgr* pResMgr = SFX_APP()->GetSfxResManager();
+ if( pResMgr )
+ {
+ String aRes( ResId(STR_ERRUNOEVENTBINDUNG, *pResMgr) );
+ ::rtl::OUString aQuoteChar( RTL_CONSTASCII_USTRINGPARAM( "\"" ) );
+
+ ::rtl::OUString aOURes = aRes;
+ sal_Int32 nIndex = aOURes.indexOf( '%' );
+
+ ::rtl::OUString aOUFinal;
+ aOUFinal += aOURes.copy( 0, nIndex );
+ aOUFinal += aQuoteChar;
+ aOUFinal += aMethodName;
+ aOUFinal += aQuoteChar;
+ aOUFinal += aOURes.copy( nIndex + 2 );
+
+ ErrorBox( NULL, WinBits( WB_OK ), aOUFinal ).Execute();
+ }
+ }
+ }
+
+ // -----------------------------------------------------------------------------
+ // XEventListener
+ // -----------------------------------------------------------------------------
+
+ void DialogScriptListenerImpl::disposing(const EventObject& ) throw ( RuntimeException )
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+ // XScriptListener
+ // -----------------------------------------------------------------------------
+
+ void DialogScriptListenerImpl::firing( const ScriptEvent& aScriptEvent ) throw ( RuntimeException )
+ {
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ firing_impl( aScriptEvent, NULL );
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Any DialogScriptListenerImpl::approveFiring( const ScriptEvent& aScriptEvent )
+ throw ( reflection::InvocationTargetException, RuntimeException )
+ {
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ Any aReturn;
+ firing_impl( aScriptEvent, &aReturn );
+ return aReturn;
+ }
+
+ // -----------------------------------------------------------------------------
+
+//.........................................................................
+} // namespace dlgprov
+//.........................................................................
diff --git a/scripting/source/dlgprov/dlgevtatt.hxx b/scripting/source/dlgprov/dlgevtatt.hxx
new file mode 100644
index 000000000000..b52cb41b9dd7
--- /dev/null
+++ b/scripting/source/dlgprov/dlgevtatt.hxx
@@ -0,0 +1,167 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: dlgevtatt.hxx,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef SCRIPTING_DLGEVTATT_HXX
+#define SCRIPTING_DLGEVTATT_HXX
+
+#include <com/sun/star/frame/XModel.hpp>
+#include <com/sun/star/script/XAllListener.hpp>
+#include <com/sun/star/script/XEventAttacher.hpp>
+#include <com/sun/star/script/XScriptEventsAttacher.hpp>
+#include <com/sun/star/script/XScriptListener.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/awt/XControl.hpp>
+#ifndef _COM_SUN_STAR_BEANS_XINTROSPECTION_HPP_
+#include <com/sun/star/beans/XIntrospectionAccess.hpp>
+#endif
+#include <cppuhelper/implbase1.hxx>
+
+#include <com/sun/star/script/XScriptEventsSupplier.hpp>
+
+#include <hash_map>
+//.........................................................................
+namespace dlgprov
+{
+//.........................................................................
+
+ // =============================================================================
+ // class DialogEventsAttacherImpl
+ // =============================================================================
+ typedef std::hash_map< rtl::OUString,
+ ::com::sun::star::uno::Reference< ::com::sun::star::script::XScriptListener >,
+ ::rtl::OUStringHash,
+ ::std::equal_to< ::rtl::OUString > > ListenerHash;
+
+ typedef ::cppu::WeakImplHelper1<
+ ::com::sun::star::script::XScriptEventsAttacher > DialogEventsAttacherImpl_BASE;
+
+
+ class DialogEventsAttacherImpl : public DialogEventsAttacherImpl_BASE
+ {
+ private:
+ ListenerHash listernersForTypes;
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
+ ::com::sun::star::uno::Reference< ::com::sun::star::script::XEventAttacher > m_xEventAttacher;
+ ::com::sun::star::uno::Reference< ::com::sun::star::script::XScriptListener > getScriptListenerForKey( const rtl::OUString& sScriptName ) throw ( ::com::sun::star::uno::RuntimeException );
+#ifdef FAKE_VBA_EVENT_SUPPORT
+ ::com::sun::star::uno::Reference< ::com::sun::star::script::XScriptEventsSupplier > getFakeVbaEventsSupplier( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl>& xControl );
+#endif
+ void SAL_CALL attachEventsToControl( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl>& xControl, const ::com::sun::star::uno::Reference< ::com::sun::star::script::XScriptEventsSupplier >& events, const ::com::sun::star::uno::Any& Helper );
+ public:
+ DialogEventsAttacherImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xModel,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& xControl,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xHandler,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess >& xIntrospect,
+ bool bProviderMode,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::script::XScriptListener >& xRTLListener );
+ virtual ~DialogEventsAttacherImpl();
+
+ // XScriptEventsAttacher
+ virtual void SAL_CALL attachEvents( const ::com::sun::star::uno::Sequence<
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >& Objects,
+ const com::sun::star::uno::Reference<com::sun::star::script::XScriptListener>&,
+ const ::com::sun::star::uno::Any& Helper )
+ throw (::com::sun::star::lang::IllegalArgumentException,
+ ::com::sun::star::beans::IntrospectionException,
+ ::com::sun::star::script::CannotCreateAdapterException,
+ ::com::sun::star::lang::ServiceNotRegisteredException,
+ ::com::sun::star::uno::RuntimeException);
+ };
+
+
+ // =============================================================================
+ // class DialogAllListenerImpl
+ // =============================================================================
+
+ typedef ::cppu::WeakImplHelper1<
+ ::com::sun::star::script::XAllListener > DialogAllListenerImpl_BASE;
+
+
+ class DialogAllListenerImpl : public DialogAllListenerImpl_BASE
+ {
+ private:
+ ::com::sun::star::uno::Reference< ::com::sun::star::script::XScriptListener > m_xScriptListener;
+ ::rtl::OUString m_sScriptType;
+ ::rtl::OUString m_sScriptCode;
+
+ virtual void firing_impl( const ::com::sun::star::script::AllEventObject& Event, ::com::sun::star::uno::Any* pRet );
+
+ public:
+ DialogAllListenerImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::script::XScriptListener >& rxListener,
+ const ::rtl::OUString& rScriptType, const ::rtl::OUString& rScriptCode );
+ virtual ~DialogAllListenerImpl();
+
+ // XEventListener
+ virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XAllListener
+ virtual void SAL_CALL firing( const ::com::sun::star::script::AllEventObject& Event )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Any SAL_CALL approveFiring( const ::com::sun::star::script::AllEventObject& Event )
+ throw (::com::sun::star::reflection::InvocationTargetException, ::com::sun::star::uno::RuntimeException);
+ };
+
+
+ // =============================================================================
+ // class DialogScriptListenerImpl
+ // =============================================================================
+
+ typedef ::cppu::WeakImplHelper1<
+ ::com::sun::star::script::XScriptListener > DialogScriptListenerImpl_BASE;
+
+
+ class DialogScriptListenerImpl : public DialogScriptListenerImpl_BASE
+ {
+ protected:
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
+ virtual void firing_impl( const ::com::sun::star::script::ScriptEvent& aScriptEvent, ::com::sun::star::uno::Any* pRet ) = 0;
+ public:
+ DialogScriptListenerImpl( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext ) : m_xContext( rxContext ) {}
+ virtual ~DialogScriptListenerImpl();
+
+ // XEventListener
+ virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XScriptListener
+ virtual void SAL_CALL firing( const ::com::sun::star::script::ScriptEvent& aScriptEvent )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Any SAL_CALL approveFiring( const ::com::sun::star::script::ScriptEvent& aScriptEvent )
+ throw (::com::sun::star::reflection::InvocationTargetException, ::com::sun::star::uno::RuntimeException);
+ };
+
+
+//.........................................................................
+} // namespace dlgprov
+//.........................................................................
+
+#endif // SCRIPTING_DLGEVT_HXX
diff --git a/scripting/source/dlgprov/dlgprov.cxx b/scripting/source/dlgprov/dlgprov.cxx
new file mode 100644
index 000000000000..1bb78ded543e
--- /dev/null
+++ b/scripting/source/dlgprov/dlgprov.cxx
@@ -0,0 +1,843 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: dlgprov.cxx,v $
+ * $Revision: 1.17 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#ifndef SCRIPTING_DLGPROV_HXX
+#include "dlgprov.hxx"
+#endif
+#include "dlgevtatt.hxx"
+#include <com/sun/star/awt/XControlContainer.hpp>
+#include <com/sun/star/awt/XWindowPeer.hpp>
+#ifndef _COM_SUN_STAR_IO_XINPUTSTREAMPROVIDER_HXX_
+#include <com/sun/star/io/XInputStreamProvider.hpp>
+#endif
+#include <com/sun/star/lang/XMultiComponentFactory.hpp>
+#include <com/sun/star/script/XLibraryContainer.hpp>
+#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
+#include <cppuhelper/implementationentry.hxx>
+#endif
+#include <com/sun/star/beans/XIntrospection.hpp>
+#include <com/sun/star/resource/XStringResourceSupplier.hpp>
+#include <com/sun/star/resource/XStringResourceManager.hpp>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
+#include "com/sun/star/resource/XStringResourceWithLocation.hpp"
+#include <com/sun/star/document/XEmbeddedScripts.hpp>
+#include <sfx2/app.hxx>
+#include <sfx2/objsh.hxx>
+#include <xmlscript/xmldlg_imexp.hxx>
+#include <tools/urlobj.hxx>
+#include <comphelper/namedvaluecollection.hxx>
+
+#include <com/sun/star/uri/XUriReference.hpp>
+#include <com/sun/star/uri/XUriReferenceFactory.hpp>
+#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
+#include <com/sun/star/uri/XVndSunStarExpandUrl.hpp>
+#include <com/sun/star/util/XMacroExpander.hpp>
+
+#include <util/MiscUtils.hxx>
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::awt;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::script;
+using namespace ::com::sun::star::beans;
+using namespace ::com::sun::star::document;
+using namespace ::sf_misc;
+
+//.........................................................................
+namespace dlgprov
+{
+//.........................................................................
+
+static ::rtl::OUString aResourceResolverPropName = ::rtl::OUString::createFromAscii( "ResourceResolver" );
+ // =============================================================================
+ // component operations
+ // =============================================================================
+
+ static ::rtl::OUString getImplementationName_DialogProviderImpl()
+ {
+ static ::rtl::OUString* pImplName = 0;
+ if ( !pImplName )
+ {
+ ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
+ if ( !pImplName )
+ {
+ static ::rtl::OUString aImplName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.scripting.DialogProvider" ) );
+ pImplName = &aImplName;
+ }
+ }
+ return *pImplName;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ static Sequence< ::rtl::OUString > getSupportedServiceNames_DialogProviderImpl()
+ {
+ static Sequence< ::rtl::OUString >* pNames = 0;
+ if ( !pNames )
+ {
+ ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
+ if ( !pNames )
+ {
+ static Sequence< ::rtl::OUString > aNames(3);
+ aNames.getArray()[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.DialogProvider" ) );
+ aNames.getArray()[1] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.DialogProvider2" ) );
+ aNames.getArray()[2] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.ContainerWindowProvider" ) );
+ pNames = &aNames;
+ }
+ }
+ return *pNames;
+ }
+
+
+ // =============================================================================
+ // mutex
+ // =============================================================================
+
+ ::osl::Mutex& getMutex()
+ {
+ static ::osl::Mutex* s_pMutex = 0;
+ if ( !s_pMutex )
+ {
+ ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
+ if ( !s_pMutex )
+ {
+ static ::osl::Mutex s_aMutex;
+ s_pMutex = &s_aMutex;
+ }
+ }
+ return *s_pMutex;
+ }
+
+
+ // =============================================================================
+ // DialogProviderImpl
+ // =============================================================================
+
+ DialogProviderImpl::DialogProviderImpl( const Reference< XComponentContext >& rxContext )
+ :m_xContext( rxContext )
+ ,m_xModel( 0 )
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+
+ DialogProviderImpl::~DialogProviderImpl()
+ {
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Reference< resource::XStringResourceManager > getStringResourceFromDialogLibrary
+ ( Reference< container::XNameContainer > xDialogLib )
+ {
+ Reference< resource::XStringResourceManager > xStringResourceManager;
+ if( xDialogLib.is() )
+ {
+ Reference< resource::XStringResourceSupplier > xStringResourceSupplier( xDialogLib, UNO_QUERY );
+ if( xStringResourceSupplier.is() )
+ {
+ Reference< resource::XStringResourceResolver >
+ xStringResourceResolver = xStringResourceSupplier->getStringResource();
+
+ xStringResourceManager =
+ Reference< resource::XStringResourceManager >( xStringResourceResolver, UNO_QUERY );
+ }
+ }
+ return xStringResourceManager;
+ }
+
+ Reference< container::XNameContainer > DialogProviderImpl::createControlModel() throw ( Exception )
+ {
+ Reference< XMultiComponentFactory > xSMgr_( m_xContext->getServiceManager(), UNO_QUERY_THROW );
+ Reference< container::XNameContainer > xControlModel( xSMgr_->createInstanceWithContext( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.UnoControlDialogModel" ) ), m_xContext ), UNO_QUERY_THROW );
+ return xControlModel;
+ }
+
+ Reference< container::XNameContainer > DialogProviderImpl::createDialogModel(
+ const Reference< io::XInputStream >& xInput,
+ const Reference< resource::XStringResourceManager >& xStringResourceManager,
+ const Any &aDialogSourceURL) throw ( Exception )
+ {
+ Reference< container::XNameContainer > xDialogModel( createControlModel() );
+
+ ::rtl::OUString aDlgSrcUrlPropName( RTL_CONSTASCII_USTRINGPARAM( "DialogSourceURL" ) );
+ Reference< beans::XPropertySet > xDlgPropSet( xDialogModel, UNO_QUERY );
+ xDlgPropSet->setPropertyValue( aDlgSrcUrlPropName, aDialogSourceURL );
+
+ ::xmlscript::importDialogModel( xInput, xDialogModel, m_xContext );
+ // Set resource property
+ if( xStringResourceManager.is() )
+ {
+ Reference< beans::XPropertySet > xDlgPSet( xDialogModel, UNO_QUERY );
+ Any aStringResourceManagerAny;
+ aStringResourceManagerAny <<= xStringResourceManager;
+ xDlgPSet->setPropertyValue( aResourceResolverPropName, aStringResourceManagerAny );
+ }
+
+ return xDialogModel;
+ }
+
+ Reference< XControlModel > DialogProviderImpl::createDialogModelForBasic() throw ( Exception )
+ {
+ if ( !m_BasicInfo.get() )
+ // shouln't get here
+ throw RuntimeException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("No information to create dialog" ) ), Reference< XInterface >() );
+ Reference< resource::XStringResourceManager > xStringResourceManager = getStringResourceFromDialogLibrary( m_BasicInfo->mxDlgLib );
+
+ rtl::OUString aURL(RTL_CONSTASCII_USTRINGPARAM("" ));
+ Any aDialogSourceURL;
+ aDialogSourceURL <<= aURL;
+ Reference< XControlModel > xCtrlModel( createDialogModel( m_BasicInfo->mxInput, xStringResourceManager, aDialogSourceURL ), UNO_QUERY_THROW );
+ return xCtrlModel;
+ }
+
+ Reference< XControlModel > DialogProviderImpl::createDialogModel( const ::rtl::OUString& sURL )
+ {
+
+ ::rtl::OUString aURL( sURL );
+
+ // parse URL
+ // TODO: use URL parsing class
+ // TODO: decoding of location
+ Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager(), UNO_QUERY );
+
+ if ( !xSMgr.is() )
+ {
+ throw RuntimeException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DialogProviderImpl::getDialogModel: Couldn't instantiate MultiComponent factory" ) ),
+ Reference< XInterface >() );
+ }
+
+ Reference< uri::XUriReferenceFactory > xFac (
+ xSMgr->createInstanceWithContext( rtl::OUString::createFromAscii(
+ "com.sun.star.uri.UriReferenceFactory"), m_xContext ) , UNO_QUERY );
+
+ if ( !xFac.is() )
+ {
+ throw RuntimeException(
+ ::rtl::OUString::createFromAscii( "DialogProviderImpl::getDialogModel(), could not instatiate UriReferenceFactory." ),
+ Reference< XInterface >() );
+ }
+
+ // i75778: Support non-script URLs
+ Reference< io::XInputStream > xInput;
+ Reference< container::XNameContainer > xDialogLib;
+
+ // Accept file URL to single dialog
+ bool bSingleDialog = false;
+
+ Reference< util::XMacroExpander > xMacroExpander(
+ m_xContext->getValueByName(
+ ::rtl::OUString::createFromAscii( "/singletons/com.sun.star.util.theMacroExpander" ) ),
+ UNO_QUERY_THROW );
+
+ Reference< uri::XUriReference > uriRef;
+ for (;;)
+ {
+ uriRef = Reference< uri::XUriReference >( xFac->parse( aURL ), UNO_QUERY );
+ if ( !uriRef.is() )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "DialogProviderImpl::getDialogModel: failed to parse URI: " );
+ errorMsg += aURL;
+ throw IllegalArgumentException( errorMsg,
+ Reference< XInterface >(), 1 );
+ }
+ Reference < uri::XVndSunStarExpandUrl > sxUri( uriRef, UNO_QUERY );
+ if( !sxUri.is() )
+ break;
+
+ aURL = sxUri->expand( xMacroExpander );
+ }
+
+ Reference < uri::XVndSunStarScriptUrl > sfUri( uriRef, UNO_QUERY );
+ if( !sfUri.is() )
+ {
+ bSingleDialog = true;
+
+ // Try any other URL with SimpleFileAccess
+ Reference< ::com::sun::star::ucb::XSimpleFileAccess > xSFI =
+ Reference< ::com::sun::star::ucb::XSimpleFileAccess >( xSMgr->createInstanceWithContext
+ ( ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ), m_xContext ), UNO_QUERY );
+
+ try
+ {
+ xInput = xSFI->openFileRead( aURL );
+ }
+ catch( Exception& )
+ {}
+ }
+ else
+ {
+ ::rtl::OUString sDescription = sfUri->getName();
+
+ sal_Int32 nIndex = 0;
+
+ ::rtl::OUString sLibName = sDescription.getToken( 0, (sal_Unicode)'.', nIndex );
+ ::rtl::OUString sDlgName;
+ if ( nIndex != -1 )
+ sDlgName = sDescription.getToken( 0, (sal_Unicode)'.', nIndex );
+
+ ::rtl::OUString sLocation = sfUri->getParameter(
+ ::rtl::OUString::createFromAscii( "location" ) );
+
+
+ // get dialog library container
+ // TODO: dialogs in packages
+ Reference< XLibraryContainer > xLibContainer;
+
+ if ( sLocation == ::rtl::OUString::createFromAscii( "application" ) )
+ {
+ xLibContainer = Reference< XLibraryContainer >( SFX_APP()->GetDialogContainer(), UNO_QUERY );
+ }
+ else if ( sLocation == ::rtl::OUString::createFromAscii( "document" ) )
+ {
+ Reference< XEmbeddedScripts > xDocumentScripts( m_xModel, UNO_QUERY );
+ if ( xDocumentScripts.is() )
+ {
+ xLibContainer.set( xDocumentScripts->getDialogLibraries(), UNO_QUERY );
+ OSL_ENSURE( xLibContainer.is(),
+ "DialogProviderImpl::createDialogModel: invalid dialog container!" );
+ }
+ }
+ else
+ {
+ Sequence< ::rtl::OUString > aOpenDocsTdocURLs( MiscUtils::allOpenTDocUrls( m_xContext ) );
+ const ::rtl::OUString* pTdocURL = aOpenDocsTdocURLs.getConstArray();
+ const ::rtl::OUString* pTdocURLEnd = aOpenDocsTdocURLs.getConstArray() + aOpenDocsTdocURLs.getLength();
+ for ( ; pTdocURL != pTdocURLEnd; ++pTdocURL )
+ {
+ Reference< frame::XModel > xModel( MiscUtils::tDocUrlToModel( *pTdocURL ) );
+ OSL_ENSURE( xModel.is(), "DialogProviderImpl::createDialogModel: invalid document model!" );
+ if ( !xModel.is() )
+ continue;
+
+ ::rtl::OUString sDocURL = xModel->getURL();
+ if ( sDocURL.getLength() == 0 )
+ {
+ ::comphelper::NamedValueCollection aModelArgs( xModel->getArgs() );
+ sDocURL = aModelArgs.getOrDefault( "Title", sDocURL );
+ }
+
+ if ( sLocation != sDocURL )
+ continue;
+
+ Reference< XEmbeddedScripts > xDocumentScripts( m_xModel, UNO_QUERY );
+ if ( !xDocumentScripts.is() )
+ continue;
+
+ xLibContainer.set( xDocumentScripts->getDialogLibraries(), UNO_QUERY );
+ OSL_ENSURE( xLibContainer.is(),
+ "DialogProviderImpl::createDialogModel: invalid dialog container!" );
+ }
+ }
+
+ // get input stream provider
+ Reference< io::XInputStreamProvider > xISP;
+ if ( xLibContainer.is() )
+ {
+ // load dialog library
+ if ( !xLibContainer->isLibraryLoaded( sLibName ) )
+ xLibContainer->loadLibrary( sLibName );
+
+ // get dialog library
+ if ( xLibContainer->hasByName( sLibName ) )
+ {
+ Any aElement = xLibContainer->getByName( sLibName );
+ aElement >>= xDialogLib;
+ }
+
+ if ( xDialogLib.is() )
+ {
+ // get input stream provider
+ if ( xDialogLib->hasByName( sDlgName ) )
+ {
+ Any aElement = xDialogLib->getByName( sDlgName );
+ aElement >>= xISP;
+ }
+
+ if ( !xISP.is() )
+ {
+ throw IllegalArgumentException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DialogProviderImpl::getDialogModel: dialog not found!" ) ),
+ Reference< XInterface >(), 1 );
+ }
+ }
+ else
+ {
+ throw IllegalArgumentException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DialogProviderImpl::getDialogModel: library not found!" ) ),
+ Reference< XInterface >(), 1 );
+ }
+ }
+ else
+ {
+ throw IllegalArgumentException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DialogProviderImpl::getDialog: library container not found!" ) ),
+ Reference< XInterface >(), 1 );
+ }
+
+ if ( xISP.is() )
+ xInput = xISP->createInputStream();
+ }
+
+ // import dialog model
+ Reference< XControlModel > xCtrlModel;
+ if ( xInput.is() && m_xContext.is() )
+ {
+ Reference< resource::XStringResourceManager > xStringResourceManager;
+ if( bSingleDialog )
+ {
+ INetURLObject aInetObj( aURL );
+ ::rtl::OUString aDlgName = aInetObj.GetBase();
+ aInetObj.removeSegment();
+ ::rtl::OUString aDlgLocation = aInetObj.GetMainURL( INetURLObject::NO_DECODE );
+ bool bReadOnly = true;
+ ::com::sun ::star::lang::Locale aLocale = Application::GetSettings().GetUILocale();
+ ::rtl::OUString aComment;
+
+ Sequence<Any> aArgs( 6 );
+ aArgs[0] <<= aDlgLocation;
+ aArgs[1] <<= bReadOnly;
+ aArgs[2] <<= aLocale;
+ aArgs[3] <<= aDlgName;
+ aArgs[4] <<= aComment;
+
+ Reference< task::XInteractionHandler > xDummyHandler;
+ aArgs[5] <<= xDummyHandler;
+ Reference< XMultiComponentFactory > xSMgr_( m_xContext->getServiceManager(), UNO_QUERY_THROW );
+ // TODO: Ctor
+ xStringResourceManager = Reference< resource::XStringResourceManager >( xSMgr_->createInstanceWithContext
+ ( ::rtl::OUString::createFromAscii( "com.sun.star.resource.StringResourceWithLocation" ),
+ m_xContext ), UNO_QUERY );
+ if( xStringResourceManager.is() )
+ {
+ Reference< XInitialization > xInit( xStringResourceManager, UNO_QUERY );
+ if( xInit.is() )
+ xInit->initialize( aArgs );
+ }
+ }
+ else if( xDialogLib.is() )
+ {
+ xStringResourceManager = getStringResourceFromDialogLibrary( xDialogLib );
+ }
+
+ Any aDialogSourceURLAny;
+ aDialogSourceURLAny <<= aURL;
+
+ Reference< container::XNameContainer > xDialogModel( createDialogModel( xInput , xStringResourceManager, aDialogSourceURLAny ), UNO_QUERY_THROW);
+
+ xCtrlModel = Reference< XControlModel >( xDialogModel, UNO_QUERY );
+ }
+ return xCtrlModel;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Reference< XControl > DialogProviderImpl::createDialogControl
+ ( const Reference< XControlModel >& rxDialogModel, const Reference< XWindowPeer >& xParent )
+ {
+ OSL_ENSURE( rxDialogModel.is(), "DialogProviderImpl::getDialogControl: no dialog model" );
+
+ Reference< XControl > xDialogControl;
+
+ if ( m_xContext.is() )
+ {
+ Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager() );
+
+ if ( xSMgr.is() )
+ {
+ xDialogControl = Reference< XControl >( xSMgr->createInstanceWithContext(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.UnoControlDialog" ) ), m_xContext ), UNO_QUERY );
+
+ if ( xDialogControl.is() )
+ {
+ // set the model
+ if ( rxDialogModel.is() )
+ xDialogControl->setModel( rxDialogModel );
+
+ // set visible
+ Reference< XWindow > xW( xDialogControl, UNO_QUERY );
+ if ( xW.is() )
+ xW->setVisible( sal_False );
+
+ // get the parent of the dialog control
+ Reference< XWindowPeer > xPeer;
+ if( xParent.is() )
+ {
+ xPeer = xParent;
+ }
+ else if ( m_xModel.is() )
+ {
+ Reference< frame::XController > xController( m_xModel->getCurrentController(), UNO_QUERY );
+ if ( xController.is() )
+ {
+ Reference< frame::XFrame > xFrame( xController->getFrame(), UNO_QUERY );
+ if ( xFrame.is() )
+ xPeer = Reference< XWindowPeer>( xFrame->getContainerWindow(), UNO_QUERY );
+ }
+ }
+
+ // create a peer
+ Reference< XToolkit> xToolkit( xSMgr->createInstanceWithContext(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.awt.Toolkit" ) ), m_xContext ), UNO_QUERY );
+ if ( xToolkit.is() )
+ xDialogControl->createPeer( xToolkit, xPeer );
+ }
+ }
+ }
+
+ return xDialogControl;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ void DialogProviderImpl::attachControlEvents(
+ const Reference< XControl >& rxControl,
+ const Reference< XInterface >& rxHandler,
+ const Reference< XIntrospectionAccess >& rxIntrospectionAccess,
+ bool bDialogProviderMode )
+ {
+ if ( rxControl.is() )
+ {
+ Reference< XControlContainer > xControlContainer( rxControl, UNO_QUERY );
+
+ if ( xControlContainer.is() )
+ {
+ Sequence< Reference< XControl > > aControls = xControlContainer->getControls();
+ const Reference< XControl >* pControls = aControls.getConstArray();
+ sal_Int32 nControlCount = aControls.getLength();
+
+ Sequence< Reference< XInterface > > aObjects( nControlCount + 1 );
+ Reference< XInterface >* pObjects = aObjects.getArray();
+ for ( sal_Int32 i = 0; i < nControlCount; ++i )
+ {
+ pObjects[i] = Reference< XInterface >( pControls[i], UNO_QUERY );
+ }
+
+ // also add the dialog control itself to the sequence
+ pObjects[nControlCount] = Reference< XInterface >( rxControl, UNO_QUERY );
+
+ Reference< XScriptEventsAttacher > xScriptEventsAttacher = new DialogEventsAttacherImpl
+ ( m_xContext, m_xModel, rxControl, rxHandler, rxIntrospectionAccess,
+ bDialogProviderMode, ( m_BasicInfo.get() ? m_BasicInfo->mxBasicRTLListener : NULL ) );
+
+ Any aHelper;
+ xScriptEventsAttacher->attachEvents( aObjects, Reference< XScriptListener >(), aHelper );
+ }
+ }
+ }
+
+ Reference< XIntrospectionAccess > DialogProviderImpl::inspectHandler( const Reference< XInterface >& rxHandler )
+ {
+ Reference< XIntrospectionAccess > xIntrospectionAccess;
+ static Reference< XIntrospection > xIntrospection;
+
+ if( !rxHandler.is() )
+ return xIntrospectionAccess;
+
+ if( !xIntrospection.is() )
+ {
+ Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager(), UNO_QUERY );
+ if ( !xSMgr.is() )
+ {
+ throw RuntimeException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DialogProviderImpl::getIntrospectionAccess: Couldn't instantiate MultiComponent factory" ) ),
+ Reference< XInterface >() );
+ }
+
+ // Get introspection service
+ Reference< XInterface > xI = xSMgr->createInstanceWithContext
+ ( rtl::OUString::createFromAscii("com.sun.star.beans.Introspection"), m_xContext );
+ if (xI.is())
+ xIntrospection = Reference< XIntrospection >::query( xI );
+ }
+
+ if( xIntrospection.is() )
+ {
+ // Do introspection
+ try
+ {
+ Any aHandlerAny;
+ aHandlerAny <<= rxHandler;
+ xIntrospectionAccess = xIntrospection->inspect( aHandlerAny );
+ }
+ catch( RuntimeException& )
+ {
+ xIntrospectionAccess.clear();
+ }
+ }
+ return xIntrospectionAccess;
+ }
+
+
+ // -----------------------------------------------------------------------------
+ // XServiceInfo
+ // -----------------------------------------------------------------------------
+
+ ::rtl::OUString DialogProviderImpl::getImplementationName( ) throw (RuntimeException)
+ {
+ return getImplementationName_DialogProviderImpl();
+ }
+
+ // -----------------------------------------------------------------------------
+
+ sal_Bool DialogProviderImpl::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
+ {
+ Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
+ const ::rtl::OUString* pNames = aNames.getConstArray();
+ const ::rtl::OUString* pEnd = pNames + aNames.getLength();
+ for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
+ ;
+
+ return pNames != pEnd;
+ }
+
+ // -----------------------------------------------------------------------------
+
+ Sequence< ::rtl::OUString > DialogProviderImpl::getSupportedServiceNames( ) throw (RuntimeException)
+ {
+ return getSupportedServiceNames_DialogProviderImpl();
+ }
+
+ // -----------------------------------------------------------------------------
+ // XInitialization
+ // -----------------------------------------------------------------------------
+
+ void DialogProviderImpl::initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException)
+ {
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ if ( aArguments.getLength() == 1 )
+ {
+ aArguments[0] >>= m_xModel;
+
+ if ( !m_xModel.is() )
+ {
+ throw RuntimeException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DialogProviderImpl::initialize: invalid argument format!" ) ),
+ Reference< XInterface >() );
+ }
+ }
+ else if ( aArguments.getLength() == 4 )
+ {
+ // call from RTL_Impl_CreateUnoDialog
+ aArguments[0] >>= m_xModel;
+ m_BasicInfo.reset( new BasicRTLParams() );
+ m_BasicInfo->mxInput.set( aArguments[ 1 ], UNO_QUERY_THROW );
+ m_BasicInfo->mxDlgLib.set( aArguments[ 2 ], UNO_QUERY_THROW );
+ // leave the possibility to optionally allow the old dialog creation
+ // to use the new XScriptListener ( which converts the old style macro
+ // to a SF url )
+ m_BasicInfo->mxBasicRTLListener.set( aArguments[ 3 ], UNO_QUERY);
+ }
+ else if ( aArguments.getLength() > 4 )
+ {
+ throw RuntimeException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DialogProviderImpl::initialize: invalid number of arguments!" ) ),
+ Reference< XInterface >() );
+ }
+ }
+
+ // -----------------------------------------------------------------------------
+ // XDialogProvider
+ // -----------------------------------------------------------------------------
+
+ static ::rtl::OUString aDecorationPropName =
+ ::rtl::OUString::createFromAscii( "Decoration" );
+ static ::rtl::OUString aTitlePropName =
+ ::rtl::OUString::createFromAscii( "Title" );
+
+ Reference < XControl > DialogProviderImpl::createDialogImpl(
+ const ::rtl::OUString& URL, const Reference< XInterface >& xHandler,
+ const Reference< XWindowPeer >& xParent, bool bDialogProviderMode )
+ throw (IllegalArgumentException, RuntimeException)
+ {
+ // if the dialog is located in a document, the document must already be open!
+
+ ::osl::MutexGuard aGuard( getMutex() );
+
+
+ // m_xHandler = xHandler;
+
+ //Reference< XDialog > xDialog;
+ Reference< XControl > xCtrl;
+ Reference< XControlModel > xCtrlMod;
+ // add support for basic RTL_FUNCTION
+ if ( m_BasicInfo.get() )
+ xCtrlMod = createDialogModelForBasic();
+ else
+ {
+ OSL_ENSURE( URL.getLength(), "DialogProviderImpl::getDialog: no URL!" );
+ xCtrlMod = createDialogModel( URL );
+ }
+ if ( xCtrlMod.is() )
+ {
+ // i83963 Force decoration
+ if( bDialogProviderMode )
+ {
+ uno::Reference< beans::XPropertySet > xDlgModPropSet( xCtrlMod, uno::UNO_QUERY );
+ if( xDlgModPropSet.is() )
+ {
+ bool bDecoration = true;
+ try
+ {
+ Any aDecorationAny = xDlgModPropSet->getPropertyValue( aDecorationPropName );
+ aDecorationAny >>= bDecoration;
+ if( !bDecoration )
+ {
+ xDlgModPropSet->setPropertyValue( aDecorationPropName, makeAny( true ) );
+ xDlgModPropSet->setPropertyValue( aTitlePropName, makeAny( ::rtl::OUString() ) );
+ }
+ }
+ catch( UnknownPropertyException& )
+ {}
+ }
+ }
+
+ xCtrl = Reference< XControl >( createDialogControl( xCtrlMod, xParent ) );
+ if ( xCtrl.is() )
+ {
+ //xDialog = Reference< XDialog >( xCtrl, UNO_QUERY );
+ Reference< XIntrospectionAccess > xIntrospectionAccess = inspectHandler( xHandler );
+ attachControlEvents( xCtrl, xHandler, xIntrospectionAccess, bDialogProviderMode );
+ }
+ }
+
+ return xCtrl;
+ }
+
+ Reference < XDialog > DialogProviderImpl::createDialog( const ::rtl::OUString& URL )
+ throw (IllegalArgumentException, RuntimeException)
+ {
+ Reference< XInterface > xDummyHandler;
+ Reference< XWindowPeer > xDummyPeer;
+ Reference < XControl > xControl = DialogProviderImpl::createDialogImpl( URL, xDummyHandler, xDummyPeer, true );
+ Reference< XDialog > xDialog( xControl, UNO_QUERY );
+ return xDialog;
+ }
+
+ Reference < XDialog > DialogProviderImpl::createDialogWithHandler(
+ const ::rtl::OUString& URL, const Reference< XInterface >& xHandler )
+ throw (IllegalArgumentException, RuntimeException)
+ {
+ if( !xHandler.is() )
+ {
+ throw IllegalArgumentException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DialogProviderImpl::createDialogWithHandler: Invalid xHandler!" ) ),
+ Reference< XInterface >(), 1 );
+ }
+ Reference< XWindowPeer > xDummyPeer;
+ Reference < XControl > xControl = DialogProviderImpl::createDialogImpl( URL, xHandler, xDummyPeer, true );
+ Reference< XDialog > xDialog( xControl, UNO_QUERY );
+ return xDialog;
+ }
+
+ Reference< XWindow > DialogProviderImpl::createContainerWindow(
+ const ::rtl::OUString& URL, const ::rtl::OUString& WindowType,
+ const Reference< XWindowPeer >& xParent, const Reference< XInterface >& xHandler )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
+ {
+ (void)WindowType; // for future use
+ if( !xParent.is() )
+ {
+ throw IllegalArgumentException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DialogProviderImpl::createContainerWindow: Invalid xParent!" ) ),
+ Reference< XInterface >(), 1 );
+ }
+ Reference < XControl > xControl = DialogProviderImpl::createDialogImpl( URL, xHandler, xParent, false );
+ Reference< XWindow> xWindow( xControl, UNO_QUERY );
+ return xWindow;
+ }
+
+
+ // =============================================================================
+ // component operations
+ // =============================================================================
+
+ static Reference< XInterface > SAL_CALL create_DialogProviderImpl(
+ Reference< XComponentContext > const & xContext )
+ SAL_THROW( () )
+ {
+ return static_cast< lang::XTypeProvider * >( new DialogProviderImpl( xContext ) );
+ }
+
+ // -----------------------------------------------------------------------------
+
+ static struct ::cppu::ImplementationEntry s_component_entries [] =
+ {
+ {
+ create_DialogProviderImpl, getImplementationName_DialogProviderImpl,
+ getSupportedServiceNames_DialogProviderImpl, ::cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ { 0, 0, 0, 0, 0, 0 }
+ };
+
+ // -----------------------------------------------------------------------------
+
+//.........................................................................
+} // namespace dlgprov
+//.........................................................................
+
+
+// =============================================================================
+// component exports
+// =============================================================================
+
+extern "C"
+{
+ void SAL_CALL component_getImplementationEnvironment(
+ const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
+ {
+ (void)ppEnv;
+
+ *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
+ }
+
+ sal_Bool SAL_CALL component_writeInfo(
+ lang::XMultiServiceFactory * pServiceManager, registry::XRegistryKey * pRegistryKey )
+ {
+ return ::cppu::component_writeInfoHelper(
+ pServiceManager, pRegistryKey, ::dlgprov::s_component_entries );
+ }
+
+ void * SAL_CALL component_getFactory(
+ const sal_Char * pImplName, lang::XMultiServiceFactory * pServiceManager,
+ registry::XRegistryKey * pRegistryKey )
+ {
+ return ::cppu::component_getFactoryHelper(
+ pImplName, pServiceManager, pRegistryKey, ::dlgprov::s_component_entries );
+ }
+}
diff --git a/scripting/source/dlgprov/dlgprov.hxx b/scripting/source/dlgprov/dlgprov.hxx
new file mode 100644
index 000000000000..46b629597dab
--- /dev/null
+++ b/scripting/source/dlgprov/dlgprov.hxx
@@ -0,0 +1,155 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: dlgprov.hxx,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef SCRIPTING_DLGPROV_HXX
+#define SCRIPTING_DLGPROV_HXX
+
+#include <com/sun/star/awt/XControl.hpp>
+#include <com/sun/star/awt/XDialog.hpp>
+#include <com/sun/star/awt/XDialogProvider2.hpp>
+#include <com/sun/star/awt/XContainerWindowProvider.hpp>
+#include <com/sun/star/frame/XModel.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XInitialization.hpp>
+#include <com/sun/star/script/XScriptEventsAttacher.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/beans/XIntrospectionAccess.hpp>
+#include <com/sun/star/container/XNameContainer.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/resource/XStringResourceManager.hpp>
+
+#include <cppuhelper/implbase4.hxx>
+#include <osl/mutex.hxx>
+#include <memory>
+
+//.........................................................................
+namespace dlgprov
+{
+//.........................................................................
+
+ // =============================================================================
+ // mutex
+ // =============================================================================
+
+ ::osl::Mutex& getMutex();
+
+
+ // =============================================================================
+ // class DialogProviderImpl
+ // =============================================================================
+
+ typedef ::cppu::WeakImplHelper4<
+ ::com::sun::star::lang::XServiceInfo,
+ ::com::sun::star::lang::XInitialization,
+ ::com::sun::star::awt::XDialogProvider2,
+ ::com::sun::star::awt::XContainerWindowProvider > DialogProviderImpl_BASE;
+
+ class DialogProviderImpl : public DialogProviderImpl_BASE
+ {
+ private:
+ struct BasicRTLParams
+ {
+ ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > mxInput;
+ ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > mxDlgLib;
+ ::com::sun::star::uno::Reference< ::com::sun::star::script::XScriptListener > mxBasicRTLListener;
+ };
+ std::auto_ptr< BasicRTLParams > m_BasicInfo;
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
+ ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > m_xModel;
+
+
+ ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > createDialogModel( const ::rtl::OUString& sURL );
+
+ ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl > createDialogControl(
+ const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel >& rxDialogModel,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& xParent );
+
+ void attachControlEvents( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControl >& rxControlContainer,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxHandler,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess >& rxIntrospectionAccess,
+ bool bDialogProviderMode );
+ ::com::sun::star::uno::Reference< ::com::sun::star::beans::XIntrospectionAccess > inspectHandler(
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxHandler );
+ // helper methods
+ ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > createControlModel() throw ( ::com::sun::star::uno::Exception );
+ ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > createDialogModel(
+ const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInput,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::resource::XStringResourceManager >& xStringResourceManager,
+ const ::com::sun::star::uno::Any &aDialogSourceURL) throw ( ::com::sun::star::uno::Exception );
+ ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlModel > createDialogModelForBasic() throw ( ::com::sun::star::uno::Exception );
+
+ // XDialogProvider / XDialogProvider2 impl method
+ virtual ::com::sun::star::uno::Reference < ::com::sun::star::awt::XControl > SAL_CALL createDialogImpl(
+ const ::rtl::OUString& URL,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xHandler,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& xParent,
+ bool bDialogProviderMode )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+
+ public:
+ DialogProviderImpl(
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext );
+ virtual ~DialogProviderImpl();
+
+ // XServiceInfo
+ virtual ::rtl::OUString SAL_CALL getImplementationName( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XInitialization
+ virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+ // XDialogProvider
+ virtual ::com::sun::star::uno::Reference < ::com::sun::star::awt::XDialog > SAL_CALL createDialog(
+ const ::rtl::OUString& URL )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+
+ // XDialogProvider2
+ virtual ::com::sun::star::uno::Reference < ::com::sun::star::awt::XDialog > SAL_CALL createDialogWithHandler(
+ const ::rtl::OUString& URL,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xHandler )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+
+ virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > SAL_CALL createContainerWindow(
+ const ::rtl::OUString& URL, const ::rtl::OUString& WindowType,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& xParent,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xHandler )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+ };
+
+//.........................................................................
+} // namespace dlgprov
+//.........................................................................
+
+#endif // SCRIPTING_DLGPROV_HXX
diff --git a/scripting/source/dlgprov/dlgprov.map b/scripting/source/dlgprov/dlgprov.map
new file mode 100644
index 000000000000..737cddbfe3df
--- /dev/null
+++ b/scripting/source/dlgprov/dlgprov.map
@@ -0,0 +1,9 @@
+OOO_1.1 {
+ global:
+ component_getImplementationEnvironment;
+ component_getFactory;
+ component_writeInfo;
+
+ local:
+ *;
+};
diff --git a/scripting/source/dlgprov/dlgprov.xml b/scripting/source/dlgprov/dlgprov.xml
new file mode 100644
index 000000000000..556cc3fe2253
--- /dev/null
+++ b/scripting/source/dlgprov/dlgprov.xml
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE module-description PUBLIC "-//StarOffice//DTD ComponentDescription 1.0//EN" "module-description.dtd">
+<module-description xmlns:xlink="http://www.w3.org/1999/xlink">
+
+ <module-name>dlgprov</module-name>
+
+ <component-description>
+ <author>Thomas Benisch</author>
+ <name>com.sun.star.comp.scripting.DialogProvider</name>
+ <description>provider for dialogs</description>
+ <loader-name>com.sun.star.loader.SharedLibrary</loader-name>
+ <language>c++</language>
+ <status value="drafts"/>
+ <supported-service>com.sun.star.awt.DialogProvider</supported-service>
+ <type>com.sun.star.awt.XControl</type>
+ <type>com.sun.star.awt.XControlContainer</type>
+ <type>com.sun.star.awt.XDialog</type>
+ <type>com.sun.star.awt.XDialogProvider</type>
+ <type>com.sun.star.awt.XWindowPeer</type>
+ <type>com.sun.star.beans.XPropertySet</type>
+ <type>com.sun.star.frame.XModel</type>
+ <type>com.sun.star.io.XInputStreamProvider</type>
+ <type>com.sun.star.lang.IllegalArgumentException</type>
+ <type>com.sun.star.lang.XInitialization</type>
+ <type>com.sun.star.lang.XMultiComponentFactory</type>
+ <type>com.sun.star.lang.XServiceInfo</type>
+ <type>com.sun.star.reflection.InvocationTargetException</type>
+ <type>com.sun.star.script.CannotConvertException</type>
+ <type>com.sun.star.script.ScriptEventDescriptor</type>
+ <type>com.sun.star.script.XAllListener</type>
+ <type>com.sun.star.script.XEventAttacher</type>
+ <type>com.sun.star.script.XLibraryContainer</type>
+ <type>com.sun.star.script.XScriptEventsAttacher</type>
+ <type>com.sun.star.script.XScriptEventsSupplier</type>
+ <type>com.sun.star.script.XScriptListener</type>
+ <type>com.sun.star.uno.Exception</type>
+ <type>com.sun.star.uno.RuntimeException</type>
+ <type>com.sun.star.uno.XComponentContext</type>
+ <type>com.sun.star.script.provider.XScript</type>
+ <type>com.sun.star.script.provider.XScriptProvider</type>
+ <type> com.sun.star.uri.XUriReference </type>
+ <type> com.sun.star.uri.XUriReferenceFactory </type>
+ <type> com.sun.star.uri.XVndSunStarScriptUrl </type>
+ </component-description>
+
+ <project-build-dependency>sfx2</project-build-dependency>
+ <project-build-dependency>xmlscript</project-build-dependency>
+ <project-build-dependency>cppuhelper</project-build-dependency>
+ <project-build-dependency>cppu</project-build-dependency>
+ <project-build-dependency>sal</project-build-dependency>
+
+ <runtime-module-dependency>sfx2</runtime-module-dependency>
+ <runtime-module-dependency>xcr</runtime-module-dependency>
+ <runtime-module-dependency>cppuhelper3$(COM)</runtime-module-dependency>
+ <runtime-module-dependency>cppu3</runtime-module-dependency>
+ <runtime-module-dependency>sal3</runtime-module-dependency>
+
+</module-description>
diff --git a/scripting/source/dlgprov/makefile.mk b/scripting/source/dlgprov/makefile.mk
new file mode 100644
index 000000000000..da1c88fdd6b9
--- /dev/null
+++ b/scripting/source/dlgprov/makefile.mk
@@ -0,0 +1,73 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.8 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+PRJ=..$/..
+
+PRJNAME=scripting
+TARGET=dlgprov
+ENABLE_EXCEPTIONS=TRUE
+COMP1TYPELIST=$(TARGET)
+
+# --- Settings -----------------------------------------------------
+
+.INCLUDE : settings.mk
+DLLPRE =
+
+# ------------------------------------------------------------------
+
+SLOFILES= \
+ $(SLO)$/dlgprov.obj \
+ $(SLO)$/dlgevtatt.obj
+
+SHL1TARGET= $(TARGET)$(DLLPOSTFIX).uno
+SHL1IMPLIB= i$(TARGET)
+
+SHL1VERSIONMAP=$(TARGET).map
+SHL1DEF=$(MISC)$/$(SHL1TARGET).def
+DEF1NAME=$(SHL1TARGET)
+
+SHL1STDLIBS= \
+ $(SFX2LIB) \
+ $(VCLLIB) \
+ $(TOOLSLIB) \
+ $(XMLSCRIPTLIB) \
+ $(CPPUHELPERLIB) \
+ $(COMPHELPERLIB) \
+ $(UCBHELPERLIB) \
+ $(CPPULIB) \
+ $(SALLIB)
+
+SHL1DEPN=
+SHL1LIBS=$(SLB)$/$(TARGET).lib
+
+# --- Targets ------------------------------------------------------
+
+.INCLUDE : target.mk
diff --git a/scripting/source/inc/bcholder.hxx b/scripting/source/inc/bcholder.hxx
new file mode 100644
index 000000000000..ed6e101cb895
--- /dev/null
+++ b/scripting/source/inc/bcholder.hxx
@@ -0,0 +1,73 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: bcholder.hxx,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef SCRIPTING_BCHOLDER_HXX
+#define SCRIPTING_BCHOLDER_HXX
+
+#include <osl/mutex.hxx>
+#include <cppuhelper/interfacecontainer.h>
+
+
+//.........................................................................
+namespace scripting_helper
+{
+//.........................................................................
+
+ // ----------------------------------------------------
+ // class OMutexHolder
+ // ----------------------------------------------------
+
+ class OMutexHolder
+ {
+ protected:
+ ::osl::Mutex m_aMutex;
+ };
+
+ // ----------------------------------------------------
+ // class OBroadcastHelperHolder
+ // ----------------------------------------------------
+
+ class OBroadcastHelperHolder
+ {
+ protected:
+ ::cppu::OBroadcastHelper m_aBHelper;
+
+ public:
+ OBroadcastHelperHolder( ::osl::Mutex& rMutex ) : m_aBHelper( rMutex ) { }
+
+ ::cppu::OBroadcastHelper& GetBroadcastHelper() { return m_aBHelper; }
+ const ::cppu::OBroadcastHelper& GetBroadcastHelper() const { return m_aBHelper; }
+ };
+
+//.........................................................................
+} // namespace scripting_helper
+//.........................................................................
+
+#endif // SCRIPTING_BCHOLDER_HXX
diff --git a/scripting/source/inc/util/MiscUtils.hxx b/scripting/source/inc/util/MiscUtils.hxx
new file mode 100644
index 000000000000..851d52ed1033
--- /dev/null
+++ b/scripting/source/inc/util/MiscUtils.hxx
@@ -0,0 +1,180 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: MiscUtils.hxx,v $
+ * $Revision: 1.12 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef _SCRIPT_FRAMEWORK_MISCUTILS_HXX_
+#define _SCRIPT_FRAMEWORK_MISCUTILS_HXX_
+
+#include <rtl/ustring.hxx>
+#include <tools/urlobj.hxx>
+
+#include <ucbhelper/content.hxx>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/frame/XModel.hpp>
+#include <com/sun/star/frame/XTransientDocumentsDocumentContentFactory.hpp>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/container/XContentEnumerationAccess.hpp>
+#include <com/sun/star/ucb/XCommandEnvironment.hpp>
+#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
+#include <com/sun/star/ucb/XContentAccess.hpp>
+#include <com/sun/star/sdbc/XResultSet.hpp>
+#include <com/sun/star/sdbc/XRow.hpp>
+#include <com/sun/star/lang/XMultiComponentFactory.hpp>
+
+
+#include "util.hxx"
+
+namespace sf_misc
+{
+// for simplification
+#define css ::com::sun::star
+
+class MiscUtils
+{
+public:
+ static css::uno::Sequence< ::rtl::OUString > allOpenTDocUrls( const css::uno::Reference< css::uno::XComponentContext >& xCtx)
+{
+ css::uno::Sequence< ::rtl::OUString > result;
+ try
+ {
+ if ( !xCtx.is() )
+ {
+ return result;
+ }
+ css::uno::Reference < css::lang::XMultiComponentFactory > xFac( xCtx->getServiceManager(), css::uno::UNO_QUERY );
+ if ( xFac.is() )
+ {
+ css::uno::Reference < com::sun::star::ucb::XSimpleFileAccess > xSFA( xFac->createInstanceWithContext( OUSTR("com.sun.star.ucb.SimpleFileAccess"), xCtx ), css::uno::UNO_QUERY );
+ if ( xSFA.is() )
+ {
+ result = xSFA->getFolderContents( OUSTR("vnd.sun.star.tdoc:/"), true );
+ }
+ }
+ }
+ catch ( css::uno::Exception& )
+ {
+ }
+ return result;
+}
+
+ static ::rtl::OUString xModelToTdocUrl( const css::uno::Reference< css::frame::XModel >& xModel,
+ const css::uno::Reference< css::uno::XComponentContext >& xContext )
+{
+ css::uno::Reference< css::lang::XMultiComponentFactory > xMCF(
+ xContext->getServiceManager() );
+ css::uno::Reference<
+ css::frame::XTransientDocumentsDocumentContentFactory > xDocFac;
+ try
+ {
+ xDocFac =
+ css::uno::Reference<
+ css::frame::XTransientDocumentsDocumentContentFactory >(
+ xMCF->createInstanceWithContext(
+ rtl::OUString(
+ RTL_CONSTASCII_USTRINGPARAM(
+ "com.sun.star.frame.TransientDocumentsDocumentContentFactory" ) ),
+ xContext ),
+ css::uno::UNO_QUERY );
+ }
+ catch ( css::uno::Exception const & )
+ {
+ // handled below
+ }
+
+ if ( xDocFac.is() )
+ {
+ try
+ {
+ css::uno::Reference< css::ucb::XContent > xContent(
+ xDocFac->createDocumentContent( xModel ) );
+ return xContent->getIdentifier()->getContentIdentifier();
+ }
+ catch ( css::lang::IllegalArgumentException const & )
+ {
+ OSL_ENSURE( false, "Invalid document model!" );
+ }
+ }
+
+ OSL_ENSURE( false, "Unable to obtain URL for document model!" );
+ return rtl::OUString();
+}
+ static css::uno::Reference< css::frame::XModel > tDocUrlToModel( const ::rtl::OUString& url )
+{
+ css::uno::Any result;
+
+ try
+ {
+ ::ucbhelper::Content root( url, NULL );
+ ::rtl::OUString propName = OUSTR("DocumentModel");
+ result = getUCBProperty( root, propName );
+ }
+ catch ( css::ucb::ContentCreationException& )
+ {
+ // carry on, empty value will be returned
+ }
+ catch ( css::uno::RuntimeException& )
+ {
+ // carry on, empty value will be returned
+ }
+
+ css::uno::Reference< css::frame::XModel > xModel(
+ result, css::uno::UNO_QUERY );
+
+ return xModel;
+}
+
+
+ static css::uno::Any getUCBProperty( ::ucbhelper::Content& content, ::rtl::OUString& prop )
+{
+ css::uno::Any result;
+ try
+ {
+ result = content.getPropertyValue( prop );
+ }
+ catch ( css::uno::Exception& )
+ {
+ }
+ return result;
+}
+
+private:
+static ::rtl::OUString parseLocationName( const ::rtl::OUString& location )
+{
+ // strip out the last leaf of location name
+ // e.g. file://dir1/dir2/Blah.sxw - > Blah.sxw
+ ::rtl::OUString temp = location;
+ INetURLObject aURLObj( temp );
+ if ( !aURLObj.HasError() )
+ temp = aURLObj.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DECODE_WITH_CHARSET );
+ return temp;
+}
+
+};
+} // namespace sf_misc
+#endif //
diff --git a/scripting/source/inc/util/scriptingconstants.hxx b/scripting/source/inc/util/scriptingconstants.hxx
new file mode 100644
index 000000000000..553711e9c8ed
--- /dev/null
+++ b/scripting/source/inc/util/scriptingconstants.hxx
@@ -0,0 +1,82 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: scriptingconstants.hxx,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#ifndef _COM_SUN_STAR_SCRIPTING_UTIL_SCRIPTINGCONSTANTS_HXX_
+#define _COM_SUN_STAR_SCRIPTING_UTIL_SCRIPTINGCONSTANTS_HXX_
+
+namespace scripting_constants
+{
+
+class ScriptingConstantsPool
+{
+public:
+ const ::rtl::OUString DOC_REF;
+ const ::rtl::OUString DOC_STORAGE_ID;
+ const ::rtl::OUString DOC_URI;
+ const ::rtl::OUString RESOLVED_STORAGE_ID;
+ const ::rtl::OUString SCRIPT_INFO;
+ const ::rtl::OUString SCRIPTSTORAGEMANAGER_SERVICE;
+ const sal_Int32 SHARED_STORAGE_ID;
+ const sal_Int32 USER_STORAGE_ID;
+ const sal_Int32 DOC_STORAGE_ID_NOT_SET;
+
+ static ScriptingConstantsPool& instance()
+ {
+ static ScriptingConstantsPool *pPool = 0;
+ if( ! pPool )
+ {
+ ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() );
+ if( ! pPool )
+ {
+ static ScriptingConstantsPool pool;
+ pPool = &pool;
+ }
+ }
+ return *pPool;
+ }
+private:
+ ScriptingConstantsPool( const ScriptingConstantsPool & );
+ ScriptingConstantsPool& operator = ( const ScriptingConstantsPool & );
+ ScriptingConstantsPool()
+ : DOC_REF( RTL_CONSTASCII_USTRINGPARAM( "SCRIPTING_DOC_REF" ) ),
+ DOC_STORAGE_ID( RTL_CONSTASCII_USTRINGPARAM(
+ "SCRIPTING_DOC_STORAGE_ID" ) ),
+ DOC_URI( RTL_CONSTASCII_USTRINGPARAM( "SCRIPTING_DOC_URI" ) ),
+ RESOLVED_STORAGE_ID( RTL_CONSTASCII_USTRINGPARAM(
+ "SCRIPTING_RESOLVED_STORAGE_ID" ) ),
+ SCRIPT_INFO( RTL_CONSTASCII_USTRINGPARAM( "SCRIPT_INFO" ) ),
+ SCRIPTSTORAGEMANAGER_SERVICE( RTL_CONSTASCII_USTRINGPARAM(
+ "/singletons/com.sun.star.script.framework.storage.theScriptStorageManager" ) ),
+ SHARED_STORAGE_ID( 0 ), USER_STORAGE_ID( 1 ),
+ DOC_STORAGE_ID_NOT_SET( -1 )
+ {}
+};
+
+}
+#endif
diff --git a/scripting/source/inc/util/util.hxx b/scripting/source/inc/util/util.hxx
new file mode 100644
index 000000000000..caf77a61b456
--- /dev/null
+++ b/scripting/source/inc/util/util.hxx
@@ -0,0 +1,52 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: util.hxx,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+
+#ifndef _COM_SUN_STAR_SCRIPTING_UTIL_UTIL_HXX_
+#define _COM_SUN_STAR_SCRIPTING_UTIL_UTIL_HXX_
+
+#include <rtl/ustrbuf.hxx>
+#include <osl/diagnose.h>
+
+#define OUSTR(x) ::rtl::OUString( ::rtl::OUString::createFromAscii(x) )
+
+namespace scripting_util
+{
+ inline void validateXRef(::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xRef, const sal_Char* Msg) throw (::com::sun::star::uno::RuntimeException)
+ {
+ OSL_ENSURE( xRef.is(), Msg );
+
+ if(!xRef.is())
+ {
+ throw ::com::sun::star::uno::RuntimeException(OUSTR(Msg), ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >());
+ }
+ }
+}
+#endif //_COM_SUN_STAR_SCRIPTING_UTIL_UTIL_HXX_
diff --git a/scripting/source/protocolhandler/exports.dxp b/scripting/source/protocolhandler/exports.dxp
new file mode 100644
index 000000000000..9630d7e06768
--- /dev/null
+++ b/scripting/source/protocolhandler/exports.dxp
@@ -0,0 +1,3 @@
+component_getImplementationEnvironment
+component_writeInfo
+component_getFactory
diff --git a/scripting/source/protocolhandler/makefile.mk b/scripting/source/protocolhandler/makefile.mk
new file mode 100644
index 000000000000..35440668f6b1
--- /dev/null
+++ b/scripting/source/protocolhandler/makefile.mk
@@ -0,0 +1,67 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.8 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+PRJ=..$/..
+
+PRJNAME= scripting
+TARGET= protocolhandler
+USE_DEFFILE= TRUE
+ENABLE_EXCEPTIONS=TRUE
+COMP1TYPELIST=$(TARGET)
+
+# --- Settings -----------------------------------------------------
+
+.INCLUDE : settings.mk
+
+# ------------------------------------------------------------------
+
+SLOFILES=\
+ $(SLO)$/scripthandler.obj\
+
+SHL1TARGET= $(TARGET)$(DLLPOSTFIX)
+
+SHL1STDLIBS= \
+ $(SFXLIB) \
+ $(CPPULIB) \
+ $(CPPUHELPERLIB) \
+ $(VCLLIB) \
+ $(SALLIB)
+
+SHL1DEPN=
+SHL1IMPLIB= i$(TARGET)
+SHL1LIBS= $(SLB)$/$(TARGET).lib
+SHL1DEF= $(MISC)$/$(SHL1TARGET).def
+
+DEF1NAME= $(SHL1TARGET)
+DEF1EXPORTFILE= exports.dxp
+
+# --- Targets ------------------------------------------------------
+
+.INCLUDE : target.mk
diff --git a/scripting/source/protocolhandler/protocolhandler.xml b/scripting/source/protocolhandler/protocolhandler.xml
new file mode 100755
index 000000000000..f9b0df36895f
--- /dev/null
+++ b/scripting/source/protocolhandler/protocolhandler.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE module-description PUBLIC "-//StarOffice//DTD ComponentDescription 1.0//EN" "module-description.dtd">
+<module-description xmlns:xlink="http://www.w3.org/1999/xlink">
+ <module-name> ScriptProtocolHandler </module-name>
+ <component-description>
+ <author> Noel Power</author>
+ <name> com.sun.star.frame.ProtocolHandler</name>
+ <description>
+ This component is part of the Scripting Framework
+</description>
+ <loader-name> com.sun.star.loader.SharedLibrary </loader-name>
+ <language> c++ </language>
+ <status value="com"/>
+ <supported-service> com.sun.star.frame.ProtocolHandler </supported-service>
+ <type> com.sun.star.frame.XDispatchProvider </type>
+ <type> com.sun.star.frame.XNotifyingDispatch </type>
+ <type> com.sun.star.lang.XServiceInfo </type>
+ <type> com.sun.star.lang.XInitialization </type>
+ <type> com.sun.star.io.IOException </type>
+ <type> com.sun.star.uri.XUriReference </type>
+ <type> com.sun.star.uri.XUriReferenceFactory </type>
+ <type> com.sun.star.uri.XVndSunStarScriptUrl </type>
+ </component-description>
+ <project-build-dependency> cppuhelper </project-build-dependency>
+ <project-build-dependency> cppu </project-build-dependency>
+ <project-build-dependency> sal </project-build-dependency>
+ <runtime-module-dependency> cppuhelper2$(COM) </runtime-module-dependency>
+ <runtime-module-dependency> cppu2 </runtime-module-dependency>
+ <runtime-module-dependency> sal2 </runtime-module-dependency>
+</module-description>
diff --git a/scripting/source/protocolhandler/scripthandler.cxx b/scripting/source/protocolhandler/scripthandler.cxx
new file mode 100644
index 000000000000..ecc7b0a96355
--- /dev/null
+++ b/scripting/source/protocolhandler/scripthandler.cxx
@@ -0,0 +1,604 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: scripthandler.cxx,v $
+ * $Revision: 1.29.6.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include "scripthandler.hxx"
+
+#include <osl/mutex.hxx>
+
+#include <com/sun/star/frame/DispatchResultEvent.hpp>
+#include <com/sun/star/frame/DispatchResultState.hpp>
+#include <com/sun/star/frame/XController.hpp>
+#include <com/sun/star/frame/XModel.hpp>
+
+#include <com/sun/star/document/XEmbeddedScripts.hpp>
+#include <com/sun/star/document/XScriptInvocationContext.hpp>
+
+#include <com/sun/star/lang/XSingleServiceFactory.hpp>
+
+#include <com/sun/star/script/provider/XScriptProviderSupplier.hpp>
+#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
+#include <com/sun/star/script/provider/ScriptFrameworkErrorType.hpp>
+
+#include <sfx2/objsh.hxx>
+#include <sfx2/frame.hxx>
+#include <sfx2/sfxdlg.hxx>
+#include <vcl/abstdlg.hxx>
+
+#include <cppuhelper/factory.hxx>
+#include <cppuhelper/exc_hlp.hxx>
+#include <util/util.hxx>
+
+#include "com/sun/star/uno/XComponentContext.hpp"
+#include "com/sun/star/uri/XUriReference.hpp"
+#include "com/sun/star/uri/XUriReferenceFactory.hpp"
+#include "com/sun/star/uri/XVndSunStarScriptUrl.hpp"
+#include "com/sun/star/beans/XPropertySet.hpp"
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::frame;
+using namespace ::com::sun::star::util;
+using namespace ::com::sun::star::beans;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::script;
+using namespace ::com::sun::star::script::provider;
+using namespace ::com::sun::star::document;
+using namespace ::scripting_util;
+
+namespace scripting_protocolhandler
+{
+
+const sal_Char * const MYSERVICENAME = "com.sun.star.frame.ProtocolHandler";
+const sal_Char * const MYIMPLNAME = "com.sun.star.comp.ScriptProtocolHandler";
+const sal_Char * MYSCHEME = "vnd.sun.star.script";
+const sal_Int32 MYSCHEME_LEN = 20;
+
+void SAL_CALL ScriptProtocolHandler::initialize(
+ const css::uno::Sequence < css::uno::Any >& aArguments )
+ throw ( css::uno::Exception )
+{
+ if ( m_bInitialised )
+ {
+ return ;
+ }
+
+ // first argument contains a reference to the frame (may be empty or the desktop,
+ // but usually it's a "real" frame)
+ if ( aArguments.getLength() &&
+ sal_False == ( aArguments[ 0 ] >>= m_xFrame ) )
+ {
+ ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::initialize: could not extract reference to the frame" );
+ throw RuntimeException( temp, Reference< XInterface >() );
+ }
+
+ validateXRef( m_xFactory,
+ "ScriptProtocolHandler::initialize: No Service Manager available" );
+ m_bInitialised = true;
+}
+
+Reference< XDispatch > SAL_CALL ScriptProtocolHandler::queryDispatch(
+ const URL& aURL, const ::rtl::OUString& sTargetFrameName, sal_Int32 nSearchFlags )
+ throw( ::com::sun::star::uno::RuntimeException )
+{
+ (void)sTargetFrameName;
+ (void)nSearchFlags;
+
+ Reference< XDispatch > xDispatcher;
+ // get scheme of url
+
+ Reference< uri::XUriReferenceFactory > xFac (
+ m_xFactory->createInstance( rtl::OUString::createFromAscii(
+ "com.sun.star.uri.UriReferenceFactory") ) , UNO_QUERY );
+ if ( xFac.is() )
+ {
+ Reference< uri::XUriReference > uriRef(
+ xFac->parse( aURL.Complete ), UNO_QUERY );
+ if ( uriRef.is() )
+ {
+ if ( uriRef->getScheme().equals( ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYSCHEME ) ) )
+ {
+ xDispatcher = this;
+ }
+ }
+ }
+
+ return xDispatcher;
+}
+
+Sequence< Reference< XDispatch > > SAL_CALL
+ScriptProtocolHandler::queryDispatches(
+const Sequence < DispatchDescriptor >& seqDescriptor )
+throw( RuntimeException )
+{
+ sal_Int32 nCount = seqDescriptor.getLength();
+ Sequence< Reference< XDispatch > > lDispatcher( nCount );
+ for ( sal_Int32 i = 0; i < nCount; ++i )
+ {
+ lDispatcher[ i ] = this->queryDispatch( seqDescriptor[ i ].FeatureURL,
+ seqDescriptor[ i ].FrameName,
+ seqDescriptor[ i ].SearchFlags );
+ }
+ return lDispatcher;
+}
+
+void SAL_CALL ScriptProtocolHandler::dispatchWithNotification(
+ const URL& aURL, const Sequence < PropertyValue >& lArgs,
+ const Reference< XDispatchResultListener >& xListener )
+ throw ( RuntimeException )
+{
+
+ sal_Bool bSuccess = sal_False;
+ Any invokeResult;
+ bool bCaughtException = FALSE;
+ Any aException;
+
+ if ( m_bInitialised )
+ {
+ try
+ {
+ bool bIsDocumentScript = ( aURL.Complete.indexOf( ::rtl::OUString::createFromAscii( "document" ) ) !=-1 );
+ // TODO: isn't this somewhat strange? This should be a test for a location=document parameter, shouldn't it?
+
+ if ( bIsDocumentScript )
+ {
+ // obtain the component for our security check
+ Reference< XEmbeddedScripts > xDocumentScripts;
+ if ( getScriptInvocation() )
+ xDocumentScripts.set( m_xScriptInvocation->getScriptContainer(), UNO_SET_THROW );
+
+ OSL_ENSURE( xDocumentScripts.is(), "ScriptProtocolHandler::dispatchWithNotification: can't do the security check!" );
+ if ( !xDocumentScripts.is() || !xDocumentScripts->getAllowMacroExecution() )
+ return;
+ }
+
+ // Creates a ScriptProvider ( if one is not created allready )
+ createScriptProvider();
+
+ Reference< provider::XScript > xFunc =
+ m_xScriptProvider->getScript( aURL.Complete );
+ validateXRef( xFunc,
+ "ScriptProtocolHandler::dispatchWithNotification: validate xFunc - unable to obtain XScript interface" );
+
+
+ Sequence< Any > inArgs( 0 );
+ Sequence< Any > outArgs( 0 );
+ Sequence< sal_Int16 > outIndex;
+
+ if ( lArgs.getLength() > 0 )
+ {
+ int argCount = 0;
+ for ( int index = 0; index < lArgs.getLength(); index++ )
+ {
+ // Sometimes we get a propertyval with name = "Referer"
+ // this is not an argument to be passed to script, so
+ // ignore.
+ if ( lArgs[ index ].Name.compareToAscii("Referer") != 0 ||
+ lArgs[ index ].Name.getLength() == 0 )
+ {
+ inArgs.realloc( ++argCount );
+ inArgs[ argCount - 1 ] = lArgs[ index ].Value;
+ }
+ }
+ }
+
+ bSuccess = sal_False;
+ while ( !bSuccess )
+ {
+ Any aFirstCaughtException;
+ try
+ {
+ invokeResult = xFunc->invoke( inArgs, outIndex, outArgs );
+ bSuccess = sal_True;
+ }
+ catch( const provider::ScriptFrameworkErrorException& se )
+ {
+ if ( !aFirstCaughtException.hasValue() )
+ aFirstCaughtException = ::cppu::getCaughtException();
+
+ if ( se.errorType != provider::ScriptFrameworkErrorType::NO_SUCH_SCRIPT )
+ // the only condition which allows us to retry is if there is no method with the
+ // given name/signature
+ ::cppu::throwException( aFirstCaughtException );
+
+ if ( inArgs.getLength() == 0 )
+ // no chance to retry if we can't strip more in-args
+ ::cppu::throwException( aFirstCaughtException );
+
+ // strip one argument, then retry
+ inArgs.realloc( inArgs.getLength() - 1 );
+ }
+ }
+ }
+ // Office doesn't handle exceptions rethrown here very well, it cores,
+ // all we can is log them and then set fail for the dispatch event!
+ // (if there is a listener of course)
+ catch ( const Exception & e )
+ {
+ aException = ::cppu::getCaughtException();
+
+ ::rtl::OUString reason = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ScriptProtocolHandler::dispatch: caught " ) );
+
+ invokeResult <<= reason.concat( aException.getValueTypeName() ).concat( e.Message );
+
+ bCaughtException = TRUE;
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ ::rtl::OUString reason = ::rtl::OUString::createFromAscii(
+ "ScriptProtocolHandler::dispatch: caught unknown exception" );
+
+ invokeResult <<= reason;
+ }
+#endif
+
+ }
+ else
+ {
+ ::rtl::OUString reason = ::rtl::OUString::createFromAscii(
+ "ScriptProtocolHandler::dispatchWithNotification failed, ScriptProtocolHandler not initialised"
+ );
+ invokeResult <<= reason;
+ }
+
+ if ( bCaughtException )
+ {
+ SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create();
+
+ if ( pFact != NULL )
+ {
+ VclAbstractDialog* pDlg =
+ pFact->CreateScriptErrorDialog( NULL, aException );
+
+ if ( pDlg != NULL )
+ {
+ pDlg->Execute();
+ delete pDlg;
+ }
+ }
+ }
+
+ if ( xListener.is() )
+ {
+ // always call dispatchFinished(), because we didn't load a document but
+ // executed a macro instead!
+ ::com::sun::star::frame::DispatchResultEvent aEvent;
+
+ aEvent.Source = static_cast< ::cppu::OWeakObject* >( this );
+ aEvent.Result = invokeResult;
+ if ( bSuccess )
+ {
+ aEvent.State = ::com::sun::star::frame::DispatchResultState::SUCCESS;
+ }
+ else
+ {
+ aEvent.State = ::com::sun::star::frame::DispatchResultState::FAILURE;
+ }
+
+ try
+ {
+ xListener->dispatchFinished( aEvent ) ;
+ }
+ catch(RuntimeException & e)
+ {
+ OSL_TRACE(
+ "ScriptProtocolHandler::dispatchWithNotification: caught RuntimeException"
+ "while dispatchFinished %s",
+ ::rtl::OUStringToOString( e.Message,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }
+ }
+}
+
+void SAL_CALL ScriptProtocolHandler::dispatch(
+const URL& aURL, const Sequence< PropertyValue >& lArgs )
+throw ( RuntimeException )
+{
+ dispatchWithNotification( aURL, lArgs, Reference< XDispatchResultListener >() );
+}
+
+void SAL_CALL ScriptProtocolHandler::addStatusListener(
+const Reference< XStatusListener >& xControl, const URL& aURL )
+throw ( RuntimeException )
+{
+ (void)xControl;
+ (void)aURL;
+
+ // implement if status is supported
+}
+
+void SAL_CALL ScriptProtocolHandler::removeStatusListener(
+const Reference< XStatusListener >& xControl, const URL& aURL )
+throw ( RuntimeException )
+{
+ (void)xControl;
+ (void)aURL;
+}
+
+bool
+ScriptProtocolHandler::getScriptInvocation()
+{
+ if ( !m_xScriptInvocation.is() && m_xFrame.is() )
+ {
+ Reference< XController > xController = m_xFrame->getController();
+ if ( xController .is() )
+ {
+ // try to obtain an XScriptInvocationContext interface, preferred from the
+ // mode, then from the controller
+ if ( !m_xScriptInvocation.set( xController->getModel(), UNO_QUERY ) )
+ m_xScriptInvocation.set( xController, UNO_QUERY );
+ }
+ }
+ return m_xScriptInvocation.is();
+}
+
+void
+ScriptProtocolHandler::createScriptProvider()
+{
+ if ( m_xScriptProvider.is() )
+ {
+ return;
+ }
+ try
+ {
+ // first, ask the component supporting the XScriptInvocationContext interface
+ // (if there is one) for a script provider
+ if ( getScriptInvocation() )
+ {
+ Reference< XScriptProviderSupplier > xSPS( m_xScriptInvocation, UNO_QUERY );
+ if ( xSPS.is() )
+ m_xScriptProvider = xSPS->getScriptProvider();
+ }
+
+ // second, ask the model in our frame
+ if ( !m_xScriptProvider.is() && m_xFrame.is() )
+ {
+ Reference< XController > xController = m_xFrame->getController();
+ if ( xController .is() )
+ {
+ Reference< XScriptProviderSupplier > xSPS( xController->getModel(), UNO_QUERY );
+ if ( xSPS.is() )
+ m_xScriptProvider = xSPS->getScriptProvider();
+ }
+ }
+
+
+ // as a fallback, ask the controller
+ if ( !m_xScriptProvider.is() && m_xFrame.is() )
+ {
+ Reference< XScriptProviderSupplier > xSPS( m_xFrame->getController(), UNO_QUERY );
+ if ( xSPS.is() )
+ m_xScriptProvider = xSPS->getScriptProvider();
+ }
+
+ if ( !m_xScriptProvider.is() )
+ {
+ Reference< XPropertySet > xProps( m_xFactory, UNO_QUERY_THROW );
+
+ ::rtl::OUString dc(
+ RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ) );
+
+ Reference< XComponentContext > xCtx(
+ xProps->getPropertyValue( dc ), UNO_QUERY_THROW );
+
+ ::rtl::OUString tmspf = ::rtl::OUString::createFromAscii(
+ "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory");
+
+ Reference< provider::XScriptProviderFactory > xFac(
+ xCtx->getValueByName( tmspf ), UNO_QUERY_THROW );
+
+ Any aContext;
+ if ( getScriptInvocation() )
+ aContext = makeAny( m_xScriptInvocation );
+ m_xScriptProvider = Reference< provider::XScriptProvider > (
+ xFac->createScriptProvider( aContext ), UNO_QUERY_THROW );
+ }
+ }
+ catch ( RuntimeException & e )
+ {
+ ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::createScriptProvider(), " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+ catch ( Exception & e )
+ {
+ ::rtl::OUString temp = OUSTR( "ScriptProtocolHandler::createScriptProvider: " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptProtocolHandler::createScriptProvider: UnknownException: " ),
+ Reference< XInterface > () );
+ }
+#endif
+
+}
+
+ScriptProtocolHandler::ScriptProtocolHandler(
+Reference< css::lang::XMultiServiceFactory > const& rFact ) :
+m_bInitialised( false ), m_xFactory( rFact )
+{
+}
+
+ScriptProtocolHandler::~ScriptProtocolHandler()
+{
+}
+
+/* XServiceInfo */
+::rtl::OUString SAL_CALL ScriptProtocolHandler::getImplementationName( )
+throw( RuntimeException )
+{
+ return impl_getStaticImplementationName();
+}
+
+/* XServiceInfo */
+sal_Bool SAL_CALL ScriptProtocolHandler::supportsService(
+const ::rtl::OUString& sServiceName )
+throw( RuntimeException )
+{
+ Sequence< ::rtl::OUString > seqServiceNames = getSupportedServiceNames();
+ const ::rtl::OUString* pArray = seqServiceNames.getConstArray();
+ for ( sal_Int32 nCounter = 0; nCounter < seqServiceNames.getLength(); nCounter++ )
+ {
+ if ( pArray[ nCounter ] == sServiceName )
+ {
+ return sal_True ;
+ }
+ }
+
+ return sal_False ;
+}
+
+/* XServiceInfo */
+Sequence< ::rtl::OUString > SAL_CALL ScriptProtocolHandler::getSupportedServiceNames()
+throw( RuntimeException )
+{
+ return impl_getStaticSupportedServiceNames();
+}
+
+/* Helper for XServiceInfo */
+Sequence< ::rtl::OUString > ScriptProtocolHandler::impl_getStaticSupportedServiceNames()
+{
+ ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
+ Sequence< ::rtl::OUString > seqServiceNames( 1 );
+ seqServiceNames.getArray() [ 0 ] =
+ ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYSERVICENAME );
+ return seqServiceNames ;
+}
+
+/* Helper for XServiceInfo */
+::rtl::OUString ScriptProtocolHandler::impl_getStaticImplementationName()
+{
+ return ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYIMPLNAME );
+}
+
+/* Helper for registry */
+Reference< XInterface > SAL_CALL ScriptProtocolHandler::impl_createInstance(
+const Reference< css::lang::XMultiServiceFactory >& xServiceManager )
+throw( RuntimeException )
+{
+ return Reference< XInterface > ( *new ScriptProtocolHandler( xServiceManager ) );
+}
+
+/* Factory for registration */
+Reference< XSingleServiceFactory > ScriptProtocolHandler::impl_createFactory(
+const Reference< XMultiServiceFactory >& xServiceManager )
+{
+ Reference< XSingleServiceFactory > xReturn (
+ cppu::createSingleFactory( xServiceManager,
+ ScriptProtocolHandler::impl_getStaticImplementationName(),
+ ScriptProtocolHandler::impl_createInstance,
+ ScriptProtocolHandler::impl_getStaticSupportedServiceNames() )
+ );
+ return xReturn;
+}
+
+} // namespace scripting_protocolhandler
+
+/* exported functions for registration */
+extern "C"
+{
+
+#undef css
+#define css ::com::sun::star
+
+ void SAL_CALL component_getImplementationEnvironment(
+ const sal_Char** ppEnvironmentTypeName, uno_Environment** ppEnvironment )
+ {
+ (void)ppEnvironment;
+
+ *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ;
+ }
+
+ sal_Bool SAL_CALL component_writeInfo( void * pServiceManager ,
+ void * pRegistryKey )
+ {
+ (void)pServiceManager;
+
+ Reference< css::registry::XRegistryKey > xKey(
+ reinterpret_cast< css::registry::XRegistryKey* >( pRegistryKey ) ) ;
+
+ ::rtl::OUString aStr = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/" ) );
+ aStr +=
+ ::scripting_protocolhandler::ScriptProtocolHandler::impl_getStaticImplementationName();
+
+ aStr += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES" ) );
+ Reference< css::registry::XRegistryKey > xNewKey = xKey->createKey( aStr );
+ xNewKey->createKey(
+ ::rtl::OUString::createFromAscii( ::scripting_protocolhandler::MYSERVICENAME )
+ );
+
+ return sal_True;
+ }
+
+ void* SAL_CALL component_getFactory( const sal_Char * pImplementationName ,
+ void * pServiceManager ,
+ void * pRegistryKey )
+ {
+ (void)pRegistryKey;
+
+ // Set default return value for this operation - if it failed.
+ void * pReturn = NULL ;
+
+ if (
+ ( pImplementationName != NULL ) &&
+ ( pServiceManager != NULL )
+ )
+ {
+ // Define variables which are used in following macros.
+ ::com::sun::star::uno::Reference<
+ ::com::sun::star::lang::XSingleServiceFactory > xFactory ;
+ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
+ xServiceManager( reinterpret_cast<
+ ::com::sun::star::lang::XMultiServiceFactory* >( pServiceManager ) ) ;
+
+ if ( ::scripting_protocolhandler::ScriptProtocolHandler::impl_getStaticImplementationName().equals(
+ ::rtl::OUString::createFromAscii( pImplementationName ) ) )
+ {
+ xFactory = ::scripting_protocolhandler::ScriptProtocolHandler::impl_createFactory( xServiceManager );
+ }
+
+ // Factory is valid - service was found.
+ if ( xFactory.is() )
+ {
+ xFactory->acquire();
+ pReturn = xFactory.get();
+ }
+ }
+
+ // Return with result of this operation.
+ return pReturn ;
+ }
+} // extern "C"
+
+
diff --git a/scripting/source/protocolhandler/scripthandler.hxx b/scripting/source/protocolhandler/scripthandler.hxx
new file mode 100644
index 000000000000..a2896e93d0bc
--- /dev/null
+++ b/scripting/source/protocolhandler/scripthandler.hxx
@@ -0,0 +1,154 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: scripthandler.hxx,v $
+ * $Revision: 1.10 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+#ifndef _FRAMEWORK_SCRIPT_SCRIPTHANDLER_HXX
+#define _FRAMEWORK_SCRIPT_SCRIPTHANDLER_HXX
+
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/frame/XDispatchProvider.hpp>
+#include <com/sun/star/frame/XNotifyingDispatch.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XInitialization.hpp>
+#include <cppuhelper/implbase4.hxx>
+#include <com/sun/star/script/provider/XScriptProvider.hpp>
+
+namespace rtl
+{
+class OUString;
+}
+
+namespace com { namespace sun { namespace star {
+
+ namespace document {
+ class XScriptInvocationContext;
+ }
+ namespace uno {
+ class Any;
+ }
+ namespace lang {
+ class XMultiServiceFactory;
+ class XSingleServiceFactory;
+ }
+ namespace frame {
+ class XFrame;
+ class XModel;
+ class XDispatch;
+ class XNotifyingDispatch;
+ class XDispatchResultListener;
+ struct DispatchDescriptor;
+ }
+ namespace beans {
+ struct PropertyValue;
+ }
+ namespace util {
+ struct URL;
+ }
+} } }
+
+namespace scripting_protocolhandler
+{
+
+namespace css = ::com::sun::star;
+
+class ScriptProtocolHandler :
+public ::cppu::WeakImplHelper4< css::frame::XDispatchProvider,
+ css::frame::XNotifyingDispatch, css::lang::XServiceInfo, css::lang::XInitialization >
+{
+private:
+ bool m_bInitialised;
+ css::uno::Reference < css::lang::XMultiServiceFactory > m_xFactory;
+ css::uno::Reference < css::frame::XFrame > m_xFrame;
+ css::uno::Reference < css::script::provider::XScriptProvider > m_xScriptProvider;
+ css::uno::Reference< css::document::XScriptInvocationContext > m_xScriptInvocation;
+
+ void createScriptProvider();
+ bool getScriptInvocation();
+
+public:
+ ScriptProtocolHandler( const css::uno::Reference <
+ css::lang::XMultiServiceFactory >& xFactory );
+ virtual ~ScriptProtocolHandler();
+
+ /* XServiceInfo */
+ virtual ::rtl::OUString SAL_CALL getImplementationName()
+ throw( css::uno::RuntimeException );
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& sServiceName )
+ throw( css::uno::RuntimeException );
+ virtual css::uno::Sequence < ::rtl::OUString > SAL_CALL getSupportedServiceNames()
+ throw( css::uno::RuntimeException );
+
+ /* Helper for XServiceInfo */
+ static css::uno::Sequence < ::rtl::OUString > impl_getStaticSupportedServiceNames();
+ static ::rtl::OUString impl_getStaticImplementationName();
+
+ /* Helper for registry */
+ static css::uno::Reference < css::uno::XInterface > SAL_CALL
+ impl_createInstance(
+ const css::uno::Reference< css::lang::XMultiServiceFactory >& xServiceManager )
+ throw( css::uno::RuntimeException );
+ static css::uno::Reference < css::lang::XSingleServiceFactory > impl_createFactory(
+ const css::uno::Reference< css::lang::XMultiServiceFactory >& xServiceManager );
+
+ /* Implementation for XDispatchProvider */
+ virtual css::uno::Reference < css::frame::XDispatch > SAL_CALL
+ queryDispatch( const css::util::URL& aURL, const ::rtl::OUString& sTargetFrameName,
+ sal_Int32 eSearchFlags ) throw( css::uno::RuntimeException ) ;
+ virtual css::uno::Sequence< css::uno::Reference < css::frame::XDispatch > > SAL_CALL
+ queryDispatches(
+ const css::uno::Sequence < css::frame::DispatchDescriptor >& seqDescriptor )
+ throw( css::uno::RuntimeException );
+
+ /* Implementation for X(Notifying)Dispatch */
+ virtual void SAL_CALL dispatchWithNotification(
+ const css::util::URL& aURL,
+ const css::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lArgs,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchResultListener >& Listener )
+ throw ( css::uno::RuntimeException );
+ virtual void SAL_CALL dispatch(
+ const css::util::URL& aURL,
+ const css::uno::Sequence< css::beans::PropertyValue >& lArgs )
+ throw ( css::uno::RuntimeException );
+ virtual void SAL_CALL addStatusListener(
+ const css::uno::Reference< css::frame::XStatusListener >& xControl,
+ const css::util::URL& aURL )
+ throw ( css::uno::RuntimeException );
+ virtual void SAL_CALL removeStatusListener(
+ const css::uno::Reference< css::frame::XStatusListener >& xControl,
+ const css::util::URL& aURL )
+ throw ( css::uno::RuntimeException );
+
+ /* Implementation for XInitialization */
+ virtual void SAL_CALL initialize(
+ const css::uno::Sequence < css::uno::Any >& aArguments )
+ throw ( css::uno::Exception );
+};
+
+}
+#endif
diff --git a/scripting/source/provider/ActiveMSPList.cxx b/scripting/source/provider/ActiveMSPList.cxx
new file mode 100644
index 000000000000..7aa295952522
--- /dev/null
+++ b/scripting/source/provider/ActiveMSPList.cxx
@@ -0,0 +1,320 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ActiveMSPList.cxx,v $
+ * $Revision: 1.16.16.1 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include <cppuhelper/implementationentry.hxx>
+#include <cppuhelper/factory.hxx>
+#include <cppuhelper/implbase1.hxx>
+#include <cppuhelper/exc_hlp.hxx>
+#include <util/scriptingconstants.hxx>
+#include <util/util.hxx>
+#include <util/MiscUtils.hxx>
+
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/util/XMacroExpander.hpp>
+#include <com/sun/star/lang/WrappedTargetRuntimeException.hpp>
+
+#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
+
+#include "MasterScriptProvider.hxx"
+#include "ActiveMSPList.hxx"
+
+#include <tools/diagnose_ex.h>
+
+using namespace com::sun::star;
+using namespace com::sun::star::uno;
+using namespace com::sun::star::script;
+using namespace ::scripting_util;
+using namespace ::sf_misc;
+
+namespace func_provider
+{
+
+ActiveMSPList::ActiveMSPList( const Reference< XComponentContext > & xContext ) : m_xContext( xContext )
+{
+ userDirString = ::rtl::OUString::createFromAscii("user");
+ shareDirString = ::rtl::OUString::createFromAscii("share");
+}
+
+ActiveMSPList::~ActiveMSPList()
+{
+}
+
+Reference< provider::XScriptProvider >
+ActiveMSPList::createNewMSP( const uno::Any& context )
+{
+ ::rtl::OUString serviceName = ::rtl::OUString::createFromAscii("com.sun.star.script.provider.MasterScriptProvider");
+ Sequence< Any > args( &context, 1 );
+
+ Reference< provider::XScriptProvider > msp(
+ m_xContext->getServiceManager()->createInstanceWithArgumentsAndContext(
+ serviceName, args, m_xContext ), UNO_QUERY );
+ return msp;
+}
+
+Reference< provider::XScriptProvider >
+ActiveMSPList::getMSPFromAnyContext( const Any& aContext )
+ SAL_THROW(( lang::IllegalArgumentException, RuntimeException ))
+{
+ Reference< provider::XScriptProvider > msp;
+ ::rtl::OUString sContext;
+ if ( aContext >>= sContext )
+ {
+ msp = getMSPFromStringContext( sContext );
+ return msp;
+ }
+
+ Reference< frame::XModel > xModel( aContext, UNO_QUERY );
+
+ Reference< document::XScriptInvocationContext > xScriptContext( aContext, UNO_QUERY );
+ if ( xScriptContext.is() )
+ {
+ try
+ {
+ // the component supports executing scripts embedded in a - possibly foreign document.
+ // Check whether this other document its the component itself.
+ if ( !xModel.is() || ( xModel != xScriptContext->getScriptContainer() ) )
+ {
+ msp = getMSPFromInvocationContext( xScriptContext );
+ return msp;
+ }
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ xModel.set( Reference< frame::XModel >() );
+ }
+ }
+
+ if ( xModel.is() )
+ {
+ sContext = MiscUtils::xModelToTdocUrl( xModel, m_xContext );
+ msp = getMSPFromStringContext( sContext );
+ return msp;
+ }
+
+ createNonDocMSPs();
+ return m_hMsps[ shareDirString ];
+}
+
+Reference< provider::XScriptProvider >
+ ActiveMSPList::getMSPFromInvocationContext( const Reference< document::XScriptInvocationContext >& xContext )
+ SAL_THROW(( lang::IllegalArgumentException, RuntimeException ))
+{
+ Reference< provider::XScriptProvider > msp;
+
+ Reference< document::XEmbeddedScripts > xScripts;
+ if ( xContext.is() )
+ xScripts.set( xContext->getScriptContainer() );
+ if ( !xScripts.is() )
+ {
+ ::rtl::OUStringBuffer buf;
+ buf.appendAscii( "Failed to create MasterScriptProvider for ScriptInvocationContext: " );
+ buf.appendAscii( "Component supporting XEmbeddScripts interface not found." );
+ throw lang::IllegalArgumentException( buf.makeStringAndClear(), NULL, 1 );
+ }
+
+ ::osl::MutexGuard guard( m_mutex );
+
+ Reference< XInterface > xNormalized( xContext, UNO_QUERY );
+ ScriptComponent_map::const_iterator pos = m_mScriptComponents.find( xNormalized );
+ if ( pos == m_mScriptComponents.end() )
+ {
+ // TODO
+ msp = createNewMSP( uno::makeAny( xContext ) );
+ addActiveMSP( xNormalized, msp );
+ }
+ else
+ {
+ msp = pos->second;
+ }
+
+ return msp;
+}
+
+Reference< provider::XScriptProvider >
+ ActiveMSPList::getMSPFromStringContext( const ::rtl::OUString& context )
+ SAL_THROW(( lang::IllegalArgumentException, RuntimeException ))
+{
+ Reference< provider::XScriptProvider > msp;
+ try
+ {
+ if ( context.indexOf( OUSTR( "vnd.sun.star.tdoc" ) ) == 0 )
+ {
+ Reference< frame::XModel > xModel( MiscUtils::tDocUrlToModel( context ) );
+
+ Reference< document::XEmbeddedScripts > xScripts( xModel, UNO_QUERY );
+ Reference< document::XScriptInvocationContext > xScriptsContext( xModel, UNO_QUERY );
+ if ( !xScripts.is() && !xScriptsContext.is() )
+ {
+ ::rtl::OUStringBuffer buf;
+ buf.appendAscii( "Failed to create MasterScriptProvider for '" );
+ buf.append ( context );
+ buf.appendAscii( "': Either XEmbeddScripts or XScriptInvocationContext need to be supported by the document." );
+ throw lang::IllegalArgumentException( buf.makeStringAndClear(), NULL, 1 );
+ }
+
+ ::osl::MutexGuard guard( m_mutex );
+ Reference< XInterface > xNormalized( xModel, UNO_QUERY );
+ ScriptComponent_map::const_iterator pos = m_mScriptComponents.find( xNormalized );
+ if ( pos == m_mScriptComponents.end() )
+ {
+ msp = createNewMSP( context );
+ addActiveMSP( xNormalized, msp );
+ }
+ else
+ {
+ msp = pos->second;
+ }
+ }
+ else
+ {
+ ::osl::MutexGuard guard( m_mutex );
+ Msp_hash::iterator h_itEnd = m_hMsps.end();
+ Msp_hash::const_iterator itr = m_hMsps.find( context );
+ if ( itr == h_itEnd )
+ {
+ msp = createNewMSP( context );
+ m_hMsps[ context ] = msp;
+ }
+ else
+ {
+ msp = m_hMsps[ context ];
+ }
+ }
+ }
+ catch( const lang::IllegalArgumentException& )
+ {
+ // allowed to leave
+ }
+ catch( const RuntimeException& )
+ {
+ // allowed to leave
+ }
+ catch( const Exception& )
+ {
+ ::rtl::OUStringBuffer aMessage;
+ aMessage.appendAscii( "Failed to create MasterScriptProvider for context '" );
+ aMessage.append ( context );
+ aMessage.appendAscii( "'." );
+ throw lang::WrappedTargetRuntimeException(
+ aMessage.makeStringAndClear(), *this, ::cppu::getCaughtException() );
+ }
+ return msp;
+}
+
+void
+ActiveMSPList::addActiveMSP( const Reference< uno::XInterface >& xComponent,
+ const Reference< provider::XScriptProvider >& msp )
+{
+ ::osl::MutexGuard guard( m_mutex );
+ Reference< XInterface > xNormalized( xComponent, UNO_QUERY );
+ ScriptComponent_map::const_iterator pos = m_mScriptComponents.find( xNormalized );
+ if ( pos == m_mScriptComponents.end() )
+ {
+ m_mScriptComponents[ xNormalized ] = msp;
+
+ // add self as listener for component disposal
+ // should probably throw from this method!!, reexamine
+ try
+ {
+ Reference< lang::XComponent > xBroadcaster =
+ Reference< lang::XComponent >( xComponent, UNO_QUERY_THROW );
+ xBroadcaster->addEventListener( this );
+ }
+ catch ( const Exception& )
+ {
+ DBG_UNHANDLED_EXCEPTION();
+ }
+ }
+}
+
+//*************************************************************************
+void SAL_CALL
+ActiveMSPList::disposing( const ::com::sun::star::lang::EventObject& Source )
+throw ( ::com::sun::star::uno::RuntimeException )
+
+{
+ try
+ {
+ Reference< XInterface > xNormalized( Source.Source, UNO_QUERY );
+ if ( xNormalized.is() )
+ {
+ ::osl::MutexGuard guard( m_mutex );
+ ScriptComponent_map::iterator pos = m_mScriptComponents.find( xNormalized );
+ if ( pos != m_mScriptComponents.end() )
+ m_mScriptComponents.erase( pos );
+ }
+ }
+ catch ( const Exception& )
+ {
+ // if we get an exception here, there is not much we can do about
+ // it can't throw as it will screw up the model that is calling dispose
+ DBG_UNHANDLED_EXCEPTION();
+ }
+}
+
+
+void
+ActiveMSPList::createNonDocMSPs()
+{
+ static bool created = false;
+ if ( created )
+ {
+ return;
+ }
+ else
+ {
+ ::osl::MutexGuard guard( m_mutex );
+ if ( created )
+ {
+ return;
+ }
+ // do creation of user and share MSPs here
+ ::rtl::OUString serviceName = ::rtl::OUString::createFromAscii("com.sun.star.script.provider.MasterScriptProvider");
+ Sequence< Any > args(1);
+
+ args[ 0 ] <<= userDirString;
+ Reference< provider::XScriptProvider > userMsp( m_xContext->getServiceManager()->createInstanceWithArgumentsAndContext( serviceName, args, m_xContext ), UNO_QUERY );
+ // should check if provider reference is valid
+ m_hMsps[ userDirString ] = userMsp;
+
+ args[ 0 ] <<= shareDirString;
+ Reference< provider::XScriptProvider > shareMsp( m_xContext->getServiceManager()->createInstanceWithArgumentsAndContext( serviceName, args, m_xContext ), UNO_QUERY );
+ // should check if provider reference is valid
+ m_hMsps[ shareDirString ] = shareMsp;
+ created = true;
+ }
+
+}
+
+
+} // namespace func_provider
+
diff --git a/scripting/source/provider/ActiveMSPList.hxx b/scripting/source/provider/ActiveMSPList.hxx
new file mode 100644
index 000000000000..81613a760d92
--- /dev/null
+++ b/scripting/source/provider/ActiveMSPList.hxx
@@ -0,0 +1,116 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ActiveMSPList.hxx,v $
+ * $Revision: 1.12 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#ifndef _FRAMEWORK_SCRIPT_PROVIDER_OPENDOCUMENTLIST_HXX_
+#define _FRAMEWORK_SCRIPT_PROVIDER_OPENDOCUMENTLIST_HXX_
+
+#include <hash_map>
+#include <map>
+
+#include <osl/mutex.hxx>
+#include <rtl/ustring.hxx>
+#include <cppuhelper/implbase1.hxx>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+
+#include <com/sun/star/lang/XEventListener.hpp>
+
+#include <com/sun/star/script/provider/XScriptProvider.hpp>
+#include <com/sun/star/script/browse/XBrowseNode.hpp>
+#include <com/sun/star/document/XScriptInvocationContext.hpp>
+
+#include <comphelper/stl_types.hxx>
+
+namespace func_provider
+{
+// for simplification
+#define css ::com::sun::star
+
+//Typedefs
+//=============================================================================
+
+
+typedef ::std::map < css::uno::Reference< css::uno::XInterface >
+ , css::uno::Reference< css::script::provider::XScriptProvider >
+ , ::comphelper::OInterfaceCompare< css::uno::XInterface >
+ > ScriptComponent_map;
+
+typedef ::std::hash_map< ::rtl::OUString,
+ css::uno::Reference< css::script::provider::XScriptProvider >,
+ ::rtl::OUStringHash,
+ ::std::equal_to< ::rtl::OUString > > Msp_hash;
+
+class ActiveMSPList : public ::cppu::WeakImplHelper1< css::lang::XEventListener >
+{
+
+public:
+
+ ActiveMSPList( const css::uno::Reference<
+ css::uno::XComponentContext > & xContext );
+ ~ActiveMSPList();
+
+ css::uno::Reference< css::script::provider::XScriptProvider >
+ getMSPFromStringContext( const ::rtl::OUString& context )
+ SAL_THROW(( css::lang::IllegalArgumentException, css::uno::RuntimeException ));
+
+ css::uno::Reference< css::script::provider::XScriptProvider >
+ getMSPFromAnyContext( const css::uno::Any& context )
+ SAL_THROW(( css::lang::IllegalArgumentException, css::uno::RuntimeException ));
+
+ css::uno::Reference< css::script::provider::XScriptProvider >
+ getMSPFromInvocationContext( const css::uno::Reference< css::document::XScriptInvocationContext >& context )
+ SAL_THROW(( css::lang::IllegalArgumentException, css::uno::RuntimeException ));
+
+ //XEventListener
+ //======================================================================
+
+ virtual void SAL_CALL disposing( const css::lang::EventObject& Source )
+ throw ( css::uno::RuntimeException );
+
+private:
+ void addActiveMSP( const css::uno::Reference< css::uno::XInterface >& xComponent,
+ const css::uno::Reference< css::script::provider::XScriptProvider >& msp );
+ css::uno::Reference< css::script::provider::XScriptProvider >
+ createNewMSP( const css::uno::Any& context );
+ css::uno::Reference< css::script::provider::XScriptProvider >
+ createNewMSP( const ::rtl::OUString& context )
+ {
+ return createNewMSP( css::uno::makeAny( context ) );
+ }
+
+ void createNonDocMSPs();
+ Msp_hash m_hMsps;
+ ScriptComponent_map m_mScriptComponents;
+ osl::Mutex m_mutex;
+ ::rtl::OUString userDirString;
+ ::rtl::OUString shareDirString;
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+};
+} // func_provider
+#endif
diff --git a/scripting/source/provider/BrowseNodeFactoryImpl.cxx b/scripting/source/provider/BrowseNodeFactoryImpl.cxx
new file mode 100644
index 000000000000..9b138c19eb95
--- /dev/null
+++ b/scripting/source/provider/BrowseNodeFactoryImpl.cxx
@@ -0,0 +1,800 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: BrowseNodeFactoryImpl.cxx,v $
+ * $Revision: 1.14 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#include <cppuhelper/weakref.hxx>
+#include <cppuhelper/implementationentry.hxx>
+#include <cppuhelper/factory.hxx>
+#include <cppuhelper/exc_hlp.hxx>
+#include <cppuhelper/implbase1.hxx>
+#include <comphelper/mediadescriptor.hxx>
+
+#include <com/sun/star/lang/XMultiComponentFactory.hpp>
+#include <com/sun/star/frame/XModel.hpp>
+#include <com/sun/star/reflection/XProxyFactory.hpp>
+
+#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
+#include <com/sun/star/script/browse/BrowseNodeFactoryViewTypes.hpp>
+#include <com/sun/star/document/XScriptInvocationContext.hpp>
+
+#include <tools/diagnose_ex.h>
+
+#include "BrowseNodeFactoryImpl.hxx"
+#include "ActiveMSPList.hxx"
+#include <util/MiscUtils.hxx>
+#include <util/util.hxx>
+
+#include <vector>
+#include <algorithm>
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::script;
+using namespace ::sf_misc;
+
+namespace browsenodefactory
+{
+class BrowseNodeAggregator :
+ public ::cppu::WeakImplHelper1< browse::XBrowseNode >
+{
+private:
+ ::rtl::OUString m_Name;
+ Sequence< Reference< browse::XBrowseNode > > m_Nodes;
+
+public:
+
+ BrowseNodeAggregator( const Reference< browse::XBrowseNode >& node )
+ {
+ m_Name = node->getName();
+ m_Nodes.realloc( 1 );
+ m_Nodes[ 0 ] = node;
+ }
+
+ ~BrowseNodeAggregator()
+ {
+ }
+
+ void addBrowseNode( const Reference< browse::XBrowseNode>& node )
+ {
+ sal_Int32 index = m_Nodes.getLength();
+
+ m_Nodes.realloc( index + 1 );
+ m_Nodes[ index ] = node;
+ }
+
+ virtual ::rtl::OUString
+ SAL_CALL getName()
+ throw ( RuntimeException )
+ {
+ return m_Name;
+ }
+
+ virtual Sequence< Reference< browse::XBrowseNode > > SAL_CALL
+ getChildNodes()
+ throw ( RuntimeException )
+ {
+ std::vector< Sequence< Reference < browse::XBrowseNode > > > seqs;
+ seqs.reserve( m_Nodes.getLength() );
+
+ sal_Int32 numChildren = 0;
+
+ for ( sal_Int32 i = 0; i < m_Nodes.getLength(); i++ )
+ {
+ Sequence< Reference < browse::XBrowseNode > > childs;
+ try
+ {
+ childs = m_Nodes[ i ]->getChildNodes();
+ seqs.push_back( childs );
+ numChildren += childs.getLength();
+ }
+ catch ( Exception& )
+ {
+ // some form of exception getting child nodes so they
+ // won't be displayed
+ }
+ }
+
+ std::vector< Sequence< Reference < browse::XBrowseNode > > >::const_iterator it = seqs.begin();
+ std::vector< Sequence< Reference < browse::XBrowseNode > > >::const_iterator it_end = seqs.end();
+
+ Sequence< Reference < browse::XBrowseNode > > result( numChildren );
+ for ( sal_Int32 index = 0; it != it_end && index < numChildren ; ++it )
+ {
+ Sequence< Reference < browse::XBrowseNode > > childs = *it;
+ for ( sal_Int32 j = 0; j < childs.getLength(); j++ )
+ {
+ result[ index++ ] = childs[ j ];
+ }
+ }
+ return result;
+ }
+
+ virtual sal_Bool SAL_CALL
+ hasChildNodes()
+ throw ( RuntimeException )
+ {
+ if ( m_Nodes.getLength() != 0 )
+ {
+ for ( sal_Int32 i = 0 ; i < m_Nodes.getLength(); i++ )
+ {
+ try
+ {
+ if ( m_Nodes[ i ]->hasChildNodes() )
+ {
+ return sal_True;
+ }
+ }
+ catch ( Exception& )
+ {
+ // some form of exception getting child nodes so move
+ // on to the next one
+ }
+ }
+ }
+
+ return sal_False;
+ }
+
+ virtual sal_Int16 SAL_CALL getType()
+ throw ( RuntimeException )
+ {
+ return browse::BrowseNodeTypes::CONTAINER;
+ }
+};
+
+
+//typedef ::std::map< ::rtl::OUString, Reference< browse::XBrowseNode > >
+typedef ::std::hash_map< ::rtl::OUString, Reference< browse::XBrowseNode >,
+ ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > >
+ BrowseNodeAggregatorHash;
+typedef ::std::vector< ::rtl::OUString > vString;
+
+
+struct alphaSort
+{
+ bool operator()( const ::rtl::OUString& a, const ::rtl::OUString& b )
+ {
+ return a.compareTo( b ) < 0;
+ }
+};
+class LocationBrowseNode :
+ public ::cppu::WeakImplHelper1< browse::XBrowseNode >
+{
+private:
+ BrowseNodeAggregatorHash* m_hBNA;
+ vString m_vStr;
+ ::rtl::OUString m_sNodeName;
+ Reference< browse::XBrowseNode > m_origNode;
+
+public:
+
+ LocationBrowseNode( const Reference< browse::XBrowseNode >& node )
+ {
+ m_sNodeName = node->getName();
+ m_hBNA = NULL;
+ m_origNode.set( node );
+ }
+
+ ~LocationBrowseNode()
+ {
+ if (m_hBNA)
+ {
+ delete m_hBNA;
+ }
+ }
+
+ // -------------------------------------------------------------------------
+ // XBrowseNode
+ // -------------------------------------------------------------------------
+
+ virtual ::rtl::OUString SAL_CALL getName()
+ throw ( RuntimeException )
+ {
+ return m_sNodeName;
+ }
+
+ virtual Sequence< Reference< browse::XBrowseNode > > SAL_CALL
+ getChildNodes()
+ throw ( RuntimeException )
+ {
+ if ( m_hBNA == NULL )
+ {
+ loadChildNodes();
+ }
+
+ Sequence< Reference< browse::XBrowseNode > > children( m_hBNA->size() );
+ sal_Int32 index = 0;
+
+ vString::const_iterator it = m_vStr.begin();
+
+ for ( ; it != m_vStr.end(); ++it, index++ )
+ {
+ children[ index ].set( m_hBNA->find( *it )->second );
+ }
+
+ return children;
+ }
+
+ virtual sal_Bool SAL_CALL hasChildNodes()
+ throw ( RuntimeException )
+ {
+ return sal_True;
+ }
+
+ virtual sal_Int16 SAL_CALL getType()
+ throw ( RuntimeException )
+ {
+ return browse::BrowseNodeTypes::CONTAINER;
+ }
+
+private:
+
+ void loadChildNodes()
+ {
+ m_hBNA = new BrowseNodeAggregatorHash();
+
+ Sequence< Reference< browse::XBrowseNode > > langNodes =
+ m_origNode->getChildNodes();
+
+ for ( sal_Int32 i = 0; i < langNodes.getLength(); i++ )
+ {
+ Reference< browse::XBrowseNode > xbn;
+ if ( langNodes[ i ]->getName().equals(::rtl::OUString::createFromAscii("uno_packages")) )
+ {
+ xbn.set( new LocationBrowseNode( langNodes[ i ] ) );
+ }
+ else
+ {
+ xbn.set( langNodes[ i ] );
+ }
+
+ Sequence< Reference< browse::XBrowseNode > > grandchildren =
+ xbn->getChildNodes();
+
+ for ( sal_Int32 j = 0; j < grandchildren.getLength(); j++ )
+ {
+ Reference< browse::XBrowseNode > grandchild(grandchildren[j]);
+
+ BrowseNodeAggregatorHash::iterator h_it =
+ m_hBNA->find( grandchild->getName() );
+
+ if ( h_it != m_hBNA->end() )
+ {
+ BrowseNodeAggregator* bna = static_cast< BrowseNodeAggregator* >( h_it->second.get() );
+ bna->addBrowseNode( grandchild );
+ }
+ else
+ {
+ Reference< browse::XBrowseNode > bna(
+ new BrowseNodeAggregator( grandchild ) );
+ (*m_hBNA)[ grandchild->getName() ].set( bna );
+ m_vStr.push_back( grandchild->getName() );
+ }
+ }
+ }
+ // sort children alpahbetically
+ ::std::sort( m_vStr.begin(), m_vStr.end(), alphaSort() );
+ }
+};
+
+namespace
+{
+
+Sequence< Reference< browse::XBrowseNode > > getAllBrowseNodes( const Reference< XComponentContext >& xCtx )
+{
+ Reference< lang::XMultiComponentFactory > mcf =
+ xCtx->getServiceManager();
+
+ Sequence< ::rtl::OUString > openDocs =
+ MiscUtils::allOpenTDocUrls( xCtx );
+
+ Reference< provider::XScriptProviderFactory > xFac;
+ sal_Int32 initialSize = openDocs.getLength() + 2;
+ sal_Int32 mspIndex = 0;
+
+ Sequence < Reference < browse::XBrowseNode > > locnBNs( initialSize );
+ try
+ {
+ xFac.set(
+ xCtx->getValueByName(
+ OUSTR("/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory") ), UNO_QUERY_THROW );
+
+ locnBNs[ mspIndex++ ] = Reference< browse::XBrowseNode >( xFac->createScriptProvider( makeAny( ::rtl::OUString::createFromAscii("user") ) ), UNO_QUERY_THROW );
+ locnBNs[ mspIndex++ ] = Reference< browse::XBrowseNode >( xFac->createScriptProvider( makeAny( ::rtl::OUString::createFromAscii("share") ) ), UNO_QUERY_THROW );
+ }
+ // TODO proper exception handling, should throw
+ catch( Exception& e )
+ {
+ (void)e;
+ OSL_TRACE("Caught Exception %s",
+ ::rtl::OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ locnBNs.realloc( mspIndex );
+ return locnBNs;
+ }
+
+ for ( sal_Int32 i = 0; i < openDocs.getLength(); i++ )
+ {
+ try
+ {
+ Reference< frame::XModel > model( MiscUtils::tDocUrlToModel( openDocs[ i ] ), UNO_QUERY_THROW );
+
+ // #i44599 Check if it's a real document or something special like Hidden/Preview
+ css::uno::Reference< css::frame::XController > xCurrentController = model->getCurrentController();
+ if( xCurrentController.is() )
+ {
+ comphelper::MediaDescriptor aMD( model->getArgs() );
+ sal_Bool bDefault = false;
+ sal_Bool bHidden = aMD.getUnpackedValueOrDefault( comphelper::MediaDescriptor::PROP_HIDDEN(), bDefault );
+ sal_Bool bPreview = aMD.getUnpackedValueOrDefault( comphelper::MediaDescriptor::PROP_PREVIEW(), bDefault );
+ if( !bHidden && !bPreview )
+ {
+ Reference< document::XEmbeddedScripts > xScripts( model, UNO_QUERY );
+ if ( xScripts.is() )
+ locnBNs[ mspIndex++ ] = Reference< browse::XBrowseNode >(
+ xFac->createScriptProvider( makeAny( model ) ), UNO_QUERY_THROW );
+ }
+ }
+ }
+ catch( const Exception& )
+ {
+ DBG_UNHANDLED_EXCEPTION();
+ }
+
+ }
+
+ Sequence < Reference < browse::XBrowseNode > > locnBNs_Return( mspIndex );
+ for ( sal_Int32 j = 0; j < mspIndex; j++ )
+ locnBNs_Return[j] = locnBNs[j];
+
+ return locnBNs_Return;
+}
+
+} // namespace
+
+typedef ::std::vector< Reference< browse::XBrowseNode > > vXBrowseNodes;
+
+struct alphaSortForBNodes
+{
+ bool operator()( const Reference< browse::XBrowseNode >& a, const Reference< browse::XBrowseNode >& b )
+ {
+ return a->getName().compareTo( b->getName() ) < 0;
+ }
+};
+
+typedef ::cppu::WeakImplHelper1< browse::XBrowseNode > t_BrowseNodeBase;
+class DefaultBrowseNode :
+ public t_BrowseNodeBase
+{
+
+private:
+ Reference< browse::XBrowseNode > m_xWrappedBrowseNode;
+ Reference< lang::XTypeProvider > m_xWrappedTypeProv;
+ Reference< XAggregation > m_xAggProxy;
+ Reference< XComponentContext > m_xCtx;
+
+ DefaultBrowseNode();
+public:
+ DefaultBrowseNode( const Reference< XComponentContext >& xCtx, const Reference< browse::XBrowseNode>& xNode ) : m_xWrappedBrowseNode( xNode ), m_xWrappedTypeProv( xNode, UNO_QUERY ), m_xCtx( xCtx, UNO_QUERY )
+ {
+ OSL_ENSURE( m_xWrappedBrowseNode.is(), "DefaultBrowseNode::DefaultBrowseNode(): No BrowseNode to wrap" );
+ OSL_ENSURE( m_xWrappedTypeProv.is(), "DefaultBrowseNode::DefaultBrowseNode(): No BrowseNode to wrap" );
+ OSL_ENSURE( m_xCtx.is(), "DefaultBrowseNode::DefaultBrowseNode(): No ComponentContext" );
+ // Use proxy factory service to create aggregatable proxy.
+ try
+ {
+ Reference< lang::XMultiComponentFactory > xMFac( m_xCtx->getServiceManager(), UNO_QUERY_THROW );
+ Reference< reflection::XProxyFactory > xProxyFac(
+ xMFac->createInstanceWithContext(
+ rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
+ "com.sun.star.reflection.ProxyFactory" ) ),
+ m_xCtx ), UNO_QUERY_THROW );
+ m_xAggProxy = xProxyFac->createProxy( m_xWrappedBrowseNode );
+ }
+ catch( uno::Exception& )
+ {
+ OSL_ENSURE( false, "DefaultBrowseNode::DefaultBrowseNode: Caught exception!" );
+ }
+ OSL_ENSURE( m_xAggProxy.is(),
+ "DefaultBrowseNode::DefaultBrowseNode: Wrapped BrowseNode cannot be aggregated!" );
+
+ if ( m_xAggProxy.is() )
+ {
+ osl_incrementInterlockedCount( &m_refCount );
+
+ /* i35609 - Fix crash on Solaris. The setDelegator call needs
+ to be in its own block to ensure that all temporary Reference
+ instances that are acquired during the call are released
+ before m_refCount is decremented again */
+ {
+ m_xAggProxy->setDelegator(
+ static_cast< cppu::OWeakObject * >( this ) );
+ }
+
+ osl_decrementInterlockedCount( &m_refCount );
+ }
+ }
+
+ ~DefaultBrowseNode()
+ {
+ if ( m_xAggProxy.is() )
+ {
+ m_xAggProxy->setDelegator( uno::Reference< uno::XInterface >() );
+ }
+ }
+
+ virtual Sequence< Reference< browse::XBrowseNode > > SAL_CALL
+ getChildNodes()
+ throw ( RuntimeException )
+ {
+ if ( hasChildNodes() )
+ {
+ vXBrowseNodes m_vNodes;
+ Sequence < Reference< browse::XBrowseNode > > nodes =
+ m_xWrappedBrowseNode->getChildNodes();
+ for ( sal_Int32 i=0; i<nodes.getLength(); i++ )
+ {
+ Reference< browse::XBrowseNode > xBrowseNode = nodes[ i ];
+ OSL_ENSURE( xBrowseNode.is(), "DefaultBrowseNode::getChildNodes(): Invalid BrowseNode" );
+ if( xBrowseNode.is() )
+ m_vNodes.push_back( new DefaultBrowseNode( m_xCtx, xBrowseNode ) );
+ }
+
+ ::std::sort( m_vNodes.begin(), m_vNodes.end(), alphaSortForBNodes() );
+ Sequence < Reference< browse::XBrowseNode > > children( m_vNodes.size() );
+ vXBrowseNodes::const_iterator it = m_vNodes.begin();
+ for ( sal_Int32 i=0; it != m_vNodes.end() && i<children.getLength(); i++, ++it )
+ {
+ children[ i ].set( *it );
+ }
+ return children;
+ }
+ else
+ {
+ // no nodes
+
+ Sequence < Reference< browse::XBrowseNode > > none;
+ return none;
+ }
+ }
+
+ virtual sal_Int16 SAL_CALL getType()
+ throw ( RuntimeException )
+ {
+ return m_xWrappedBrowseNode->getType();
+ }
+
+ virtual ::rtl::OUString
+ SAL_CALL getName()
+ throw ( RuntimeException )
+ {
+ return m_xWrappedBrowseNode->getName();
+ }
+
+ virtual sal_Bool SAL_CALL
+ hasChildNodes()
+ throw ( RuntimeException )
+ {
+ return m_xWrappedBrowseNode->hasChildNodes();
+ }
+
+ // XInterface
+ virtual Any SAL_CALL queryInterface( const Type& aType )
+ throw ( com::sun::star::uno::RuntimeException )
+ {
+ Any aRet = t_BrowseNodeBase::queryInterface( aType );
+ if ( aRet.hasValue() )
+ {
+ return aRet;
+ }
+ if ( m_xAggProxy.is() )
+ {
+ return m_xAggProxy->queryAggregation( aType );
+ }
+ else
+ {
+ return Any();
+ }
+ }
+
+ virtual void SAL_CALL acquire()
+ throw ()
+
+ {
+ osl_incrementInterlockedCount( &m_refCount );
+ }
+ virtual void SAL_CALL release()
+ throw ()
+ {
+ if ( osl_decrementInterlockedCount( &m_refCount ) == 0 )
+ {
+ delete this;
+ }
+ }
+ // XTypeProvider (implemnented by base, but needs to be overridden for
+ // delegating to aggregate)
+ virtual Sequence< Type > SAL_CALL getTypes()
+ throw ( com::sun::star::uno::RuntimeException )
+ {
+ return m_xWrappedTypeProv->getTypes();
+ }
+ virtual Sequence< sal_Int8 > SAL_CALL getImplementationId()
+ throw ( com::sun::star::uno::RuntimeException )
+ {
+ return m_xWrappedTypeProv->getImplementationId();
+
+ }
+};
+
+class DefaultRootBrowseNode :
+ public ::cppu::WeakImplHelper1< browse::XBrowseNode >
+{
+
+private:
+ vXBrowseNodes m_vNodes;
+ ::rtl::OUString m_Name;
+
+ DefaultRootBrowseNode();
+public:
+ DefaultRootBrowseNode( const Reference< XComponentContext >& xCtx )
+ {
+ Sequence < Reference< browse::XBrowseNode > > nodes =
+ getAllBrowseNodes( xCtx );
+
+ for ( sal_Int32 i=0; i<nodes.getLength(); i++ )
+ {
+ m_vNodes.push_back( new DefaultBrowseNode( xCtx, nodes[ i ] ) );
+ }
+ m_Name = ::rtl::OUString::createFromAscii( "Root" );
+ }
+
+ ~DefaultRootBrowseNode()
+ {
+ }
+
+ virtual Sequence< Reference< browse::XBrowseNode > > SAL_CALL
+ getChildNodes()
+ throw ( RuntimeException )
+ {
+ // no need to sort user, share, doc1...docN
+ //::std::sort( m_vNodes.begin(), m_vNodes.end(), alphaSortForBNodes() );
+ Sequence < Reference< browse::XBrowseNode > > children( m_vNodes.size() );
+ vXBrowseNodes::const_iterator it = m_vNodes.begin();
+ for ( sal_Int32 i=0; it != m_vNodes.end() && i<children.getLength(); i++, ++it )
+ {
+ children[ i ].set( *it );
+ }
+ return children;
+ }
+
+ virtual sal_Int16 SAL_CALL getType()
+ throw ( RuntimeException )
+ {
+ return browse::BrowseNodeTypes::ROOT;
+ }
+
+ virtual ::rtl::OUString
+ SAL_CALL getName()
+ throw ( RuntimeException )
+ {
+ return m_Name;
+ }
+
+ virtual sal_Bool SAL_CALL
+ hasChildNodes()
+ throw ( RuntimeException )
+ {
+ sal_Bool result = sal_True;
+ if ( !m_vNodes.size() )
+ {
+ result = sal_False;
+ }
+ return result;
+ }
+};
+
+
+class SelectorBrowseNode :
+ public ::cppu::WeakImplHelper1< browse::XBrowseNode >
+{
+private:
+ Reference< XComponentContext > m_xComponentContext;
+
+public:
+ SelectorBrowseNode( const Reference< XComponentContext >& xContext )
+ : m_xComponentContext( xContext )
+ {
+ }
+
+ ~SelectorBrowseNode()
+ {
+ }
+
+ virtual ::rtl::OUString SAL_CALL getName()
+ throw ( RuntimeException )
+ {
+ return ::rtl::OUString::createFromAscii( "Root" );
+ }
+
+ virtual Sequence< Reference< browse::XBrowseNode > > SAL_CALL
+ getChildNodes()
+ throw ( RuntimeException )
+ {
+
+ Sequence < Reference < browse::XBrowseNode > > locnBNs = getAllBrowseNodes( m_xComponentContext );
+
+ Sequence< Reference< browse::XBrowseNode > > children(
+ locnBNs.getLength() );
+
+ for ( sal_Int32 j = 0; j < locnBNs.getLength(); j++ )
+ {
+ children[j] = new LocationBrowseNode( locnBNs[j] );
+ }
+
+ return children;
+ }
+
+ virtual sal_Bool SAL_CALL hasChildNodes()
+ throw ( RuntimeException )
+ {
+ return sal_True; // will always be user and share
+ }
+
+ virtual sal_Int16 SAL_CALL getType()
+ throw ( RuntimeException )
+ {
+ return browse::BrowseNodeTypes::CONTAINER;
+ }
+};
+
+BrowseNodeFactoryImpl::BrowseNodeFactoryImpl(
+ Reference< XComponentContext > const & xComponentContext )
+ : m_xComponentContext( xComponentContext )
+{
+}
+
+BrowseNodeFactoryImpl::~BrowseNodeFactoryImpl()
+{
+}
+
+
+//############################################################################
+// Implementation of XBrowseNodeFactory
+//############################################################################
+
+/*
+ * The selector hierarchy is the standard hierarchy for organizers with the
+ * language nodes removed.
+ */
+Reference< browse::XBrowseNode > SAL_CALL
+BrowseNodeFactoryImpl::createView( sal_Int16 viewType )
+ throw (RuntimeException)
+{
+ switch( viewType )
+ {
+ case browse::BrowseNodeFactoryViewTypes::MACROSELECTOR:
+ return getSelectorHierarchy();
+ case browse::BrowseNodeFactoryViewTypes::MACROORGANIZER:
+ return getOrganizerHierarchy();
+ default:
+ throw RuntimeException( OUSTR("Unknown view type" ), Reference< XInterface >() );
+ }
+}
+
+Reference< browse::XBrowseNode >
+BrowseNodeFactoryImpl::getSelectorHierarchy()
+ throw (RuntimeException)
+{
+ /*if ( !m_xSelectorBrowseNode.is() )
+ {
+ m_xSelectorBrowseNode = new SelectorBrowseNode( m_xComponentContext );
+ }*/
+ return new SelectorBrowseNode( m_xComponentContext );
+}
+
+Reference< browse::XBrowseNode >
+BrowseNodeFactoryImpl::getOrganizerHierarchy()
+ throw (RuntimeException)
+{
+ Reference< browse::XBrowseNode > xRet = new DefaultRootBrowseNode( m_xComponentContext );
+ return xRet;
+}
+//############################################################################
+// Helper methods
+//############################################################################
+
+//############################################################################
+// Namespace global methods for setting up BrowseNodeFactory service
+//############################################################################
+
+Sequence< ::rtl::OUString > SAL_CALL
+bnf_getSupportedServiceNames( )
+ SAL_THROW( () )
+{
+ ::rtl::OUString str_name = ::rtl::OUString::createFromAscii(
+ "com.sun.star.script.browse.BrowseNodeFactory");
+
+ return Sequence< ::rtl::OUString >( &str_name, 1 );
+}
+
+::rtl::OUString SAL_CALL
+bnf_getImplementationName( )
+ SAL_THROW( () )
+{
+ return ::rtl::OUString::createFromAscii(
+ "com.sun.star.script.browse.BrowseNodeFactory" );
+}
+
+Reference< XInterface > SAL_CALL
+bnf_create( Reference< XComponentContext > const & xComponentContext )
+ SAL_THROW( (Exception) )
+{
+ return static_cast< ::cppu::OWeakObject * >(
+ new BrowseNodeFactoryImpl( xComponentContext ) );
+}
+
+//############################################################################
+// Implementation of XServiceInfo
+//############################################################################
+
+::rtl::OUString SAL_CALL
+BrowseNodeFactoryImpl::getImplementationName()
+ throw (RuntimeException)
+{
+ return bnf_getImplementationName();
+}
+
+Sequence< ::rtl::OUString > SAL_CALL
+BrowseNodeFactoryImpl::getSupportedServiceNames()
+ throw (RuntimeException)
+{
+ return bnf_getSupportedServiceNames();
+}
+
+sal_Bool BrowseNodeFactoryImpl::supportsService(
+ ::rtl::OUString const & serviceName )
+ throw (RuntimeException)
+{
+// check();
+
+ Sequence< ::rtl::OUString > supported_services(
+ getSupportedServiceNames() );
+
+ ::rtl::OUString const * ar = supported_services.getConstArray();
+
+ for ( sal_Int32 pos = supported_services.getLength(); pos--; )
+ {
+ if (ar[ pos ].equals( serviceName ))
+ return sal_True;
+ }
+ return sal_False;
+}
+
+} // namespace browsenodefactory
diff --git a/scripting/source/provider/BrowseNodeFactoryImpl.hxx b/scripting/source/provider/BrowseNodeFactoryImpl.hxx
new file mode 100644
index 000000000000..49327f113d13
--- /dev/null
+++ b/scripting/source/provider/BrowseNodeFactoryImpl.hxx
@@ -0,0 +1,91 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: BrowseNodeFactoryImpl.hxx,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#include <rtl/ustring.hxx>
+#include <cppuhelper/implbase2.hxx>
+
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/registry/XRegistryKey.hpp>
+
+#include <com/sun/star/script/browse/XBrowseNode.hpp>
+#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
+#include <com/sun/star/script/browse/XBrowseNodeFactory.hpp>
+
+namespace browsenodefactory
+{
+// for simplification
+#define css ::com::sun::star
+
+class BrowseNodeFactoryImpl :
+ public ::cppu::WeakImplHelper2 <
+ css::script::browse::XBrowseNodeFactory,
+ css::lang::XServiceInfo >
+{
+private:
+ css::uno::Reference< css::uno::XComponentContext > m_xComponentContext;
+ css::uno::Reference< css::script::browse::XBrowseNode > m_xSelectorBrowseNode;
+
+protected:
+ virtual ~BrowseNodeFactoryImpl();
+
+public:
+ BrowseNodeFactoryImpl(
+ css::uno::Reference< css::uno::XComponentContext > const & xComponentContext );
+
+ // XServiceInfo
+ virtual ::rtl::OUString SAL_CALL getImplementationName()
+ throw ( css::uno::RuntimeException );
+
+ virtual sal_Bool SAL_CALL
+ supportsService( ::rtl::OUString const & serviceName )
+ throw ( css::uno::RuntimeException );
+
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL
+ getSupportedServiceNames()
+ throw ( css::uno::RuntimeException );
+
+ // XBrowseNodeFactory
+ virtual css::uno::Reference< css::script::browse::XBrowseNode > SAL_CALL
+ createView( sal_Int16 viewType )
+ throw ( css::uno::RuntimeException );
+ private:
+ css::uno::Reference< css::script::browse::XBrowseNode >
+ getSelectorHierarchy()
+ throw ( css::uno::RuntimeException );
+
+ css::uno::Reference< css::script::browse::XBrowseNode >
+ getOrganizerHierarchy()
+ throw ( css::uno::RuntimeException );
+};
+
+
+} // namespace browsenodefactory
diff --git a/scripting/source/provider/MasterScriptProvider.cxx b/scripting/source/provider/MasterScriptProvider.cxx
new file mode 100755
index 000000000000..05227ba2f6d4
--- /dev/null
+++ b/scripting/source/provider/MasterScriptProvider.cxx
@@ -0,0 +1,1040 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: MasterScriptProvider.cxx,v $
+ * $Revision: 1.23 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#include <comphelper/documentinfo.hxx>
+
+#include <cppuhelper/implementationentry.hxx>
+#include <cppuhelper/exc_hlp.hxx>
+#include <cppuhelper/factory.hxx>
+#include <com/sun/star/frame/XModel.hpp>
+#include <com/sun/star/lang/EventObject.hpp>
+#include <com/sun/star/container/XContentEnumerationAccess.hpp>
+#include <com/sun/star/document/XScriptInvocationContext.hpp>
+
+#include <com/sun/star/uri/XUriReference.hpp>
+#include <com/sun/star/uri/XUriReferenceFactory.hpp>
+#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
+
+#include <com/sun/star/deployment/XPackage.hpp>
+#include <com/sun/star/script/browse/BrowseNodeTypes.hpp>
+#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
+#include <com/sun/star/script/provider/ScriptFrameworkErrorType.hpp>
+
+#include <util/scriptingconstants.hxx>
+#include <util/util.hxx>
+#include <util/MiscUtils.hxx>
+
+#include "ActiveMSPList.hxx"
+#include "MasterScriptProvider.hxx"
+#include "URIHelper.hxx"
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::script;
+using namespace ::com::sun::star::document;
+using namespace ::sf_misc;
+using namespace ::scripting_util;
+
+namespace func_provider
+{
+//*************************************************************************
+// Definitions for MasterScriptProviderFactory global methods.
+//*************************************************************************
+
+::rtl::OUString SAL_CALL mspf_getImplementationName() ;
+Reference< XInterface > SAL_CALL mspf_create( Reference< XComponentContext > const & xComponentContext );
+Sequence< ::rtl::OUString > SAL_CALL mspf_getSupportedServiceNames();
+
+
+bool endsWith( const ::rtl::OUString& target,
+ const ::rtl::OUString& item )
+{
+ sal_Int32 index = 0;
+ if ( ( index = target.indexOf( item ) ) != -1 &&
+ ( index == ( target.getLength() - item.getLength() ) ) )
+ {
+ return true;
+ }
+ return false;
+}
+//::rtl_StandardModuleCount s_moduleCount = MODULE_COUNT_INIT;
+
+/* should be available in some central location. */
+//*************************************************************************
+// XScriptProvider implementation
+//
+//*************************************************************************
+MasterScriptProvider::MasterScriptProvider( const Reference< XComponentContext > & xContext ) throw ( RuntimeException ):
+ m_xContext( xContext ), m_bIsValid( false ), m_bInitialised( false ),
+ m_bIsPkgMSP( false ), m_pPCache( 0 )
+{
+ validateXRef( m_xContext, "MasterScriptProvider::MasterScriptProvider: No context available\n" );
+ m_xMgr = m_xContext->getServiceManager();
+ validateXRef( m_xMgr,
+ "MasterScriptProvider::MasterScriptProvider: No service manager available\n" );
+ m_bIsValid = true;
+}
+
+//*************************************************************************
+MasterScriptProvider::~MasterScriptProvider()
+{
+ //s_moduleCount.modCnt.release( &s_moduleCount.modCnt );
+ if ( m_pPCache )
+ {
+ delete m_pPCache;
+ }
+ m_pPCache = 0;
+}
+
+//*************************************************************************
+void SAL_CALL MasterScriptProvider::initialize( const Sequence < Any >& args )
+throw ( Exception, RuntimeException )
+{
+ if ( m_bInitialised )
+ return;
+
+ m_bIsValid = false;
+
+ sal_Int32 len = args.getLength();
+ if ( len > 1 )
+ {
+ throw RuntimeException(
+ OUSTR( "MasterScriptProvider::initialize: invalid number of arguments" ),
+ Reference< XInterface >() );
+ }
+
+ Sequence< Any > invokeArgs( len );
+
+ if ( len != 0 )
+ {
+ // check if first parameter is a string
+ // if it is, this implies that this is a MSP created
+ // with a user or share ctx ( used for browse functionality )
+ //
+ if ( args[ 0 ] >>= m_sCtxString )
+ {
+ invokeArgs[ 0 ] = args[ 0 ];
+ if ( m_sCtxString.indexOfAsciiL( RTL_CONSTASCII_STRINGPARAM( "vnd.sun.star.tdoc" ) ) == 0 )
+ {
+ m_xModel = MiscUtils::tDocUrlToModel( m_sCtxString );
+ }
+ }
+ else if ( args[ 0 ] >>= m_xInvocationContext )
+ {
+ m_xModel.set( m_xInvocationContext->getScriptContainer(), UNO_QUERY_THROW );
+ }
+ else
+ {
+ args[ 0 ] >>= m_xModel;
+ }
+
+ if ( m_xModel.is() )
+ {
+ // from the arguments, we were able to deduce a model. That alone doesn't
+ // suffice, we also need an XEmbeddedScripts which actually indicates support
+ // for embeddeding scripts
+ Reference< XEmbeddedScripts > xScripts( m_xModel, UNO_QUERY );
+ if ( !xScripts.is() )
+ {
+ throw lang::IllegalArgumentException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
+ "The given document does not support embedding scripts into it, and cannot be associated with such a document."
+ ) ),
+ *this,
+ 1
+ );
+ }
+
+ try
+ {
+ m_sCtxString = MiscUtils::xModelToTdocUrl( m_xModel, m_xContext );
+ }
+ catch ( const Exception& )
+ {
+ Any aError( ::cppu::getCaughtException() );
+
+ ::rtl::OUStringBuffer buf;
+ buf.appendAscii( "MasterScriptProvider::initialize: caught " );
+ buf.append ( aError.getValueTypeName() );
+ buf.appendAscii( ":" );
+
+ Exception aException; aError >>= aException;
+ buf.append ( aException.Message );
+ throw lang::WrappedTargetException( buf.makeStringAndClear(), *this, aError );
+ }
+
+ if ( m_xInvocationContext.is() && m_xInvocationContext != m_xModel )
+ invokeArgs[ 0 ] <<= m_xInvocationContext;
+ else
+ invokeArgs[ 0 ] <<= m_sCtxString;
+ }
+
+ ::rtl::OUString pkgSpec = OUSTR("uno_packages");
+ sal_Int32 indexOfPkgSpec = m_sCtxString.lastIndexOf( pkgSpec );
+
+ // if contex string ends with "uno_packages"
+ if ( indexOfPkgSpec > -1 && ( m_sCtxString.match( pkgSpec, indexOfPkgSpec ) == sal_True ) )
+ {
+ m_bIsPkgMSP = sal_True;
+ }
+ else
+ {
+ m_bIsPkgMSP = sal_False;
+ }
+ }
+ else // no args
+ {
+ // use either scriping context or maybe zero args?
+ invokeArgs = Sequence< Any >( 0 ); // no arguments
+ }
+ m_sAargs = invokeArgs;
+ // don't create pkg mgr MSP for documents, not supported
+ if ( m_bIsPkgMSP == sal_False && !m_xModel.is() )
+ {
+ createPkgProvider();
+ }
+
+ m_bInitialised = true;
+ m_bIsValid = true;
+}
+
+
+//*************************************************************************
+void MasterScriptProvider::createPkgProvider()
+{
+ try
+ {
+ ::rtl::OUString loc = m_sCtxString;
+ Any location;
+ ::rtl::OUString sPkgCtx = m_sCtxString.concat( OUSTR(":uno_packages") );
+ location <<= sPkgCtx;
+
+ Reference< provider::XScriptProviderFactory > xFac(
+ m_xContext->getValueByName(
+ OUSTR( "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory") ), UNO_QUERY_THROW );
+
+ m_xMSPPkg.set(
+ xFac->createScriptProvider( location ), UNO_QUERY_THROW );
+
+ }
+ catch ( Exception& e )
+ {
+ (void)e;
+ OSL_TRACE("Exception creating MasterScriptProvider for uno_packages in context %s: %s",
+ ::rtl::OUStringToOString( m_sCtxString,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer,
+ ::rtl::OUStringToOString( e.Message,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }
+}
+
+//*************************************************************************
+Reference< provider::XScript >
+MasterScriptProvider::getScript( const ::rtl::OUString& scriptURI )
+throw ( provider::ScriptFrameworkErrorException,
+ RuntimeException )
+{
+ if ( !isValid() )
+ {
+ throw provider::ScriptFrameworkErrorException(
+ OUSTR( "MasterScriptProvider not initialised" ), Reference< XInterface >(),
+ scriptURI, OUSTR(""),
+ provider::ScriptFrameworkErrorType::UNKNOWN );
+ }
+
+ // need to get the language from the string
+
+ Reference< uri::XUriReferenceFactory > xFac (
+ m_xMgr->createInstanceWithContext( rtl::OUString::createFromAscii(
+ "com.sun.star.uri.UriReferenceFactory"), m_xContext ) , UNO_QUERY );
+ if ( !xFac.is() )
+ {
+ ::rtl::OUString message = ::rtl::OUString::createFromAscii("Failed to instantiate UriReferenceFactory");
+ throw provider::ScriptFrameworkErrorException(
+ message, Reference< XInterface >(),
+ scriptURI, ::rtl::OUString(),
+ provider::ScriptFrameworkErrorType::UNKNOWN );
+ }
+
+ Reference< uri::XUriReference > uriRef(
+ xFac->parse( scriptURI ), UNO_QUERY );
+
+ Reference < uri::XVndSunStarScriptUrl > sfUri( uriRef, UNO_QUERY );
+
+ if ( !uriRef.is() || !sfUri.is() )
+ {
+ ::rtl::OUString errorMsg = OUSTR( "Incorrect format for Script URI: " );
+ errorMsg = errorMsg.concat( scriptURI );
+ throw provider::ScriptFrameworkErrorException(
+ errorMsg, Reference< XInterface >(),
+ scriptURI, OUSTR(""),
+ provider::ScriptFrameworkErrorType::UNKNOWN );
+ }
+
+ ::rtl::OUString langKey = ::rtl::OUString::createFromAscii( "language" );
+ ::rtl::OUString locKey = ::rtl::OUString::createFromAscii( "location" );
+
+ if ( sfUri->hasParameter( langKey ) == sal_False ||
+ sfUri->hasParameter( locKey ) == sal_False ||
+ ( sfUri->getName().getLength() == 0 ) )
+ {
+ ::rtl::OUString errorMsg = OUSTR( "Incorrect format for Script URI: " );
+ errorMsg = errorMsg.concat( scriptURI );
+ throw provider::ScriptFrameworkErrorException(
+ errorMsg, Reference< XInterface >(),
+ scriptURI, OUSTR(""),
+ provider::ScriptFrameworkErrorType::UNKNOWN );
+ }
+
+ ::rtl::OUString language = sfUri->getParameter( langKey );
+ ::rtl::OUString location = sfUri->getParameter( locKey );
+
+ // if script us located in uno pkg
+ sal_Int32 index = -1;
+ ::rtl::OUString pkgTag =
+ ::rtl::OUString::createFromAscii( ":uno_packages" );
+ // for languages other than basic, scripts located in uno packages
+ // are merged into the user/share location context.
+ // For other languages the location attribute in script url has the form
+ // location = [user|share]:uno_packages or location :uno_pacakges/xxxx.uno.pkg
+ // we need to extract the value of location part from the
+ // location attribute of the script, if the script is located in an
+ // uno package then that is the location part up to and including
+ // ":uno_packages", if the script is not in an uno package then the
+ // normal value is used e.g. user or share.
+ // The value extracted will be used to determine if the script is
+ // located in the same location context as this MSP.
+ // For Basic, the language script provider can handle the execution of a
+ // script in any location context
+ if ( ( index = location.indexOf( pkgTag ) ) > -1 )
+ {
+ location = location.copy( 0, index + pkgTag.getLength() );
+ }
+
+ Reference< provider::XScript > xScript;
+
+ // If the script location is in the same location context as this
+ // MSP then delate to the lanaguage provider controlled by this MSP
+ // ** Special case is BASIC, all calls to getScript will be handled
+ // by the language script provider in the current location context
+ // even if its different
+ if ( ( location.equals( OUSTR( "document" ) )
+ && m_xModel.is()
+ )
+ || ( endsWith( m_sCtxString, location ) )
+ || ( language.equals( OUSTR( "Basic" ) ) )
+ )
+ {
+ Reference< provider::XScriptProvider > xScriptProvider;
+ ::rtl::OUStringBuffer buf( 80 );
+ buf.appendAscii( "com.sun.star.script.provider.ScriptProviderFor");
+ buf.append( language );
+ ::rtl::OUString serviceName = buf.makeStringAndClear();
+ if ( providerCache() )
+ {
+ try
+ {
+ xScriptProvider.set(
+ providerCache()->getProvider( serviceName ),
+ UNO_QUERY_THROW );
+ }
+ catch( const Exception& e )
+ {
+ throw provider::ScriptFrameworkErrorException(
+ e.Message, Reference< XInterface >(),
+ sfUri->getName(), language,
+ provider::ScriptFrameworkErrorType::NOTSUPPORTED );
+ }
+ }
+ else
+ {
+ throw provider::ScriptFrameworkErrorException(
+ OUSTR( "No LanguageProviders detected" ),
+ Reference< XInterface >(),
+ sfUri->getName(), language,
+ provider::ScriptFrameworkErrorType::NOTSUPPORTED );
+ }
+ xScript=xScriptProvider->getScript( scriptURI );
+ }
+ else
+ {
+ Reference< provider::XScriptProviderFactory > xFac_(
+ m_xContext->getValueByName(
+ OUSTR( "/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory") ), UNO_QUERY_THROW );
+
+ Reference< provider::XScriptProvider > xSP(
+ xFac_->createScriptProvider( makeAny( location ) ), UNO_QUERY_THROW );
+ xScript = xSP->getScript( scriptURI );
+ }
+
+ return xScript;
+}
+//*************************************************************************
+bool
+MasterScriptProvider::isValid()
+{
+ return m_bIsValid;
+}
+
+//*************************************************************************
+ProviderCache*
+MasterScriptProvider::providerCache()
+{
+ if ( !m_pPCache )
+ {
+ ::osl::MutexGuard aGuard( m_mutex );
+ if ( !m_pPCache )
+ {
+ ::rtl::OUString serviceName1 = OUSTR("com.sun.star.script.provider.ScriptProviderForBasic");
+ Sequence< ::rtl::OUString > blacklist(1);
+ blacklist[ 0 ] = serviceName1;
+
+ if ( !m_bIsPkgMSP )
+ {
+ m_pPCache = new ProviderCache( m_xContext, m_sAargs );
+ }
+ else
+ {
+ m_pPCache = new ProviderCache( m_xContext, m_sAargs, blacklist );
+ }
+ }
+ }
+ return m_pPCache;
+}
+
+
+//*************************************************************************
+::rtl::OUString SAL_CALL
+MasterScriptProvider::getName()
+ throw ( css::uno::RuntimeException )
+{
+ if ( !isPkgProvider() )
+ {
+ ::rtl::OUString sCtx = getContextString();
+ if ( sCtx.indexOf( OUSTR( "vnd.sun.star.tdoc" ) ) == 0 )
+ {
+ Reference< frame::XModel > xModel = m_xModel;
+ if ( !xModel.is() )
+ {
+ xModel = MiscUtils::tDocUrlToModel( sCtx );
+ }
+
+ m_sNodeName = ::comphelper::DocumentInfo::getDocumentTitle( xModel );
+ }
+ else
+ {
+ m_sNodeName = parseLocationName( getContextString() );
+ }
+ }
+ else
+ {
+ m_sNodeName = OUSTR("uno_packages");
+ }
+ return m_sNodeName;
+}
+
+//*************************************************************************
+Sequence< Reference< browse::XBrowseNode > > SAL_CALL
+MasterScriptProvider::getChildNodes()
+ throw ( css::uno::RuntimeException )
+{
+ Sequence< Reference< provider::XScriptProvider > > providers = getAllProviders();
+
+ Reference< provider::XScriptProvider > pkgProv = getPkgProvider();
+ sal_Int32 size = providers.getLength();
+ bool hasPkgs = pkgProv.is();
+ if ( hasPkgs )
+ {
+ size++;
+ }
+ Sequence< Reference< browse::XBrowseNode > > children( size );
+ sal_Int32 provIndex = 0;
+ for ( ; provIndex < providers.getLength(); provIndex++ )
+ {
+ children[ provIndex ] = Reference< browse::XBrowseNode >( providers[ provIndex ], UNO_QUERY );
+ }
+
+ if ( hasPkgs )
+ {
+ children[ provIndex ] = Reference< browse::XBrowseNode >( pkgProv, UNO_QUERY );
+
+ }
+
+ return children;
+}
+
+//*************************************************************************
+sal_Bool SAL_CALL
+MasterScriptProvider::hasChildNodes()
+ throw ( css::uno::RuntimeException )
+{
+ return sal_True;
+}
+
+//*************************************************************************
+sal_Int16 SAL_CALL
+MasterScriptProvider::getType()
+ throw ( css::uno::RuntimeException )
+{
+ return browse::BrowseNodeTypes::CONTAINER;
+}
+
+//*************************************************************************
+
+::rtl::OUString
+MasterScriptProvider::parseLocationName( const ::rtl::OUString& location )
+{
+ // strip out the last leaf of location name
+ // e.g. file://dir1/dir2/Blah.sxw - > Blah.sxw
+ ::rtl::OUString temp = location;
+ INetURLObject aURLObj( temp );
+ if ( !aURLObj.HasError() )
+ temp = aURLObj.getName( INetURLObject::LAST_SEGMENT, true, INetURLObject::DECODE_WITH_CHARSET );
+ return temp;
+}
+
+//*************************************************************************
+// Register Package
+void SAL_CALL
+MasterScriptProvider::insertByName( const ::rtl::OUString& aName, const Any& aElement ) throw ( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, css::uno::RuntimeException)
+{
+ if ( !m_bIsPkgMSP )
+ {
+ if ( m_xMSPPkg.is() )
+ {
+ Reference< container::XNameContainer > xCont( m_xMSPPkg, UNO_QUERY );
+ if ( !xCont.is() )
+ {
+ throw RuntimeException(
+ OUSTR("PackageMasterScriptProvider doesn't implement XNameContainer"),
+ Reference< XInterface >() );
+ }
+ xCont->insertByName( aName, aElement );
+ }
+ else
+ {
+ throw RuntimeException( OUSTR("PackageMasterScriptProvider is unitialised"),
+ Reference< XInterface >() );
+ }
+
+ }
+ else
+ {
+ Reference< deployment::XPackage > xPkg( aElement, UNO_QUERY );
+ if ( !xPkg.is() )
+ {
+ throw lang::IllegalArgumentException( OUSTR("Couldn't convert to XPackage"),
+ Reference < XInterface > (), 2 );
+ }
+ if ( !aName.getLength() )
+ {
+ throw lang::IllegalArgumentException( OUSTR("Name not set!!"),
+ Reference < XInterface > (), 1 );
+ }
+ // TODO for library pacakge parse the language, for the moment will try
+ // to get each provider to process the new Package, the first one the succeeds
+ // will terminate processing
+ if ( !providerCache() )
+ {
+ throw RuntimeException(
+ OUSTR("insertByName cannot instantiate "
+ "child script providers."),
+ Reference< XInterface >() );
+ }
+ Sequence < Reference< provider::XScriptProvider > > xSProviders =
+ providerCache()->getAllProviders();
+ sal_Int32 index = 0;
+
+ for ( ; index < xSProviders.getLength(); index++ )
+ {
+ Reference< container::XNameContainer > xCont( xSProviders[ index ], UNO_QUERY );
+ if ( !xCont.is() )
+ {
+ continue;
+ }
+ try
+ {
+ xCont->insertByName( aName, aElement );
+ break;
+ }
+ catch ( Exception& )
+ {
+ }
+
+ }
+ if ( index == xSProviders.getLength() )
+ {
+ // No script providers could process the package
+ ::rtl::OUString message = OUSTR("Failed to register package for ");
+ message = message.concat( aName );
+ throw lang::IllegalArgumentException( message,
+ Reference < XInterface > (), 2 );
+ }
+ }
+}
+
+//*************************************************************************
+// Revoke Package
+void SAL_CALL
+MasterScriptProvider::removeByName( const ::rtl::OUString& Name ) throw ( container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
+{
+ if ( !m_bIsPkgMSP )
+ {
+ if ( m_xMSPPkg.is() )
+ {
+ Reference< container::XNameContainer > xCont( m_xMSPPkg, UNO_QUERY );
+ if ( !xCont.is() )
+ {
+ throw RuntimeException(
+ OUSTR("PackageMasterScriptProvider doesn't implement XNameContainer"),
+ Reference< XInterface >() );
+ }
+ xCont->removeByName( Name );
+ }
+ else
+ {
+ throw RuntimeException( OUSTR("PackageMasterScriptProvider is unitialised"),
+ Reference< XInterface >() );
+ }
+
+ }
+ else
+ {
+ if ( !Name.getLength() )
+ {
+ throw lang::IllegalArgumentException( OUSTR("Name not set!!"),
+ Reference < XInterface > (), 1 );
+ }
+ // TODO for Script library pacakge url parse the language,
+ // for the moment will just try to get each provider to process remove/revoke
+ // request, the first one the succeeds will terminate processing
+
+ if ( !providerCache() )
+ {
+ throw RuntimeException(
+ OUSTR("removeByName() cannot instantiate "
+ "child script providers."),
+ Reference< XInterface >() );
+ }
+ Sequence < Reference< provider::XScriptProvider > > xSProviders =
+ providerCache()->getAllProviders();
+ sal_Int32 index = 0;
+ for ( ; index < xSProviders.getLength(); index++ )
+ {
+ Reference< container::XNameContainer > xCont( xSProviders[ index ], UNO_QUERY );
+ if ( !xCont.is() )
+ {
+ continue;
+ }
+ try
+ {
+ xCont->removeByName( Name );
+ break;
+ }
+ catch ( Exception& )
+ {
+ }
+
+ }
+ if ( index == xSProviders.getLength() )
+ {
+ // No script providers could process the package
+ ::rtl::OUString message = OUSTR("Failed to revoke package for ");
+ message = message.concat( Name );
+ throw lang::IllegalArgumentException( message,
+ Reference < XInterface > (), 1 );
+ }
+
+ }
+}
+
+//*************************************************************************
+void SAL_CALL
+MasterScriptProvider::replaceByName( const ::rtl::OUString& aName, const Any& aElement ) throw ( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
+{
+ (void)aName;
+ (void)aElement;
+
+ // TODO needs implementing
+ if ( true )
+ {
+ throw RuntimeException( OUSTR("replaceByName not implemented!!!!") ,
+ Reference< XInterface >() );
+ }
+}
+//*************************************************************************
+Any SAL_CALL
+MasterScriptProvider::getByName( const ::rtl::OUString& aName ) throw ( container::NoSuchElementException, lang::WrappedTargetException, RuntimeException)
+{
+ (void)aName;
+
+ // TODO needs to be implemented
+ Any result;
+ if ( true )
+ {
+ throw RuntimeException( OUSTR("getByName not implemented!!!!") ,
+ Reference< XInterface >() );
+ }
+ return result;
+}
+//*************************************************************************
+sal_Bool SAL_CALL
+MasterScriptProvider::hasByName( const ::rtl::OUString& aName ) throw (RuntimeException)
+{
+ sal_Bool result = sal_False;
+ if ( !m_bIsPkgMSP )
+ {
+ if ( m_xMSPPkg.is() )
+ {
+ Reference< container::XNameContainer > xCont( m_xMSPPkg, UNO_QUERY );
+ if ( !xCont.is() )
+ {
+ throw RuntimeException(
+ OUSTR("PackageMasterScriptProvider doesn't implement XNameContainer"),
+ Reference< XInterface >() );
+ }
+
+ result = xCont->hasByName( aName );
+ }
+ else
+ {
+ throw RuntimeException( OUSTR("PackageMasterScriptProvider is unitialised"),
+ Reference< XInterface >() );
+ }
+
+ }
+ else
+ {
+ if ( !aName.getLength() )
+ {
+ throw lang::IllegalArgumentException( OUSTR("Name not set!!"),
+ Reference < XInterface > (), 1 );
+ }
+ // TODO for Script library pacakge url parse the language,
+ // for the moment will just try to get each provider to see if the
+ // package exists in any provider, first one that succeed will
+ // terminate the loop
+
+ if ( !providerCache() )
+ {
+ throw RuntimeException(
+ OUSTR("removeByName() cannot instantiate "
+ "child script providers."),
+ Reference< XInterface >() );
+ }
+ Sequence < Reference< provider::XScriptProvider > > xSProviders =
+ providerCache()->getAllProviders();
+ for ( sal_Int32 index = 0; index < xSProviders.getLength(); index++ )
+ {
+ Reference< container::XNameContainer > xCont( xSProviders[ index ], UNO_QUERY );
+ if ( !xCont.is() )
+ {
+ continue;
+ }
+ try
+ {
+ result = xCont->hasByName( aName );
+ if ( result == sal_True )
+ {
+ break;
+ }
+ }
+ catch ( Exception& )
+ {
+ }
+
+ }
+ }
+ return result;
+}
+
+//*************************************************************************
+Sequence< ::rtl::OUString > SAL_CALL
+MasterScriptProvider::getElementNames( ) throw ( RuntimeException)
+{
+ // TODO needs implementing
+ Sequence< ::rtl::OUString > names;
+ if ( true )
+ {
+ throw RuntimeException( OUSTR("getElementNames not implemented!!!!") ,
+ Reference< XInterface >() );
+ }
+ return names;
+}
+//*************************************************************************
+Type SAL_CALL
+MasterScriptProvider::getElementType( ) throw ( RuntimeException)
+{
+ // TODO needs implementing
+ Type t;
+ return t;
+}
+//*************************************************************************
+sal_Bool SAL_CALL MasterScriptProvider::hasElements( ) throw ( RuntimeException)
+{
+ // TODO needs implementing
+ if ( true )
+ {
+ throw RuntimeException( OUSTR("hasElements not implemented!!!!") ,
+ Reference< XInterface >() );
+ }
+ return false;
+}
+
+//*************************************************************************
+Sequence< Reference< provider::XScriptProvider > > SAL_CALL
+MasterScriptProvider::getAllProviders() throw ( css::uno::RuntimeException )
+{
+ if ( providerCache() )
+ {
+ return providerCache()->getAllProviders();
+ }
+ else
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii(
+ "MasterScriptProvider::getAllProviders, cache not initialised");
+ throw RuntimeException( errorMsg.concat( errorMsg ),
+ Reference< XInterface >() );
+ }
+}
+
+
+//*************************************************************************
+::rtl::OUString SAL_CALL MasterScriptProvider::getImplementationName( )
+throw( RuntimeException )
+{
+ return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
+ "com.sun.star.script.provider.MasterScriptProvider" ) );
+}
+
+//*************************************************************************
+sal_Bool SAL_CALL MasterScriptProvider::supportsService( const ::rtl::OUString& serviceName )
+throw( RuntimeException )
+{
+ Sequence< ::rtl::OUString > serviceNames( getSupportedServiceNames() );
+ ::rtl::OUString const * pNames = serviceNames.getConstArray();
+ for ( sal_Int32 nPos = serviceNames.getLength(); nPos--; )
+ {
+ if ( serviceName.equals( pNames[ nPos ] ) )
+ {
+ return sal_True;
+ }
+ }
+ return sal_False;
+}
+
+//*************************************************************************
+Sequence< ::rtl::OUString > SAL_CALL MasterScriptProvider::getSupportedServiceNames( )
+throw( RuntimeException )
+{
+ ::rtl::OUString names[3];
+
+ names[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
+ "com.sun.star.script.provider.MasterScriptProvider" ) );
+ names[1] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
+ "com.sun.star.script.browse.BrowseNode" ) );
+ names[2] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
+ "com.sun.star.script.provider.ScriptProvider" ) );
+
+ return Sequence< ::rtl::OUString >( names, 3 );
+}
+
+} // namespace func_provider
+
+
+namespace browsenodefactory
+{
+::rtl::OUString SAL_CALL bnf_getImplementationName() ;
+Reference< XInterface > SAL_CALL bnf_create( Reference< XComponentContext > const & xComponentContext );
+Sequence< ::rtl::OUString > SAL_CALL bnf_getSupportedServiceNames();
+}
+
+namespace scripting_runtimemgr
+{
+//*************************************************************************
+Reference< XInterface > SAL_CALL sp_create(
+ const Reference< XComponentContext > & xCompC )
+{
+ return ( cppu::OWeakObject * ) new ::func_provider::MasterScriptProvider( xCompC );
+}
+
+//*************************************************************************
+Sequence< ::rtl::OUString > sp_getSupportedServiceNames( )
+ SAL_THROW( () )
+{
+ ::rtl::OUString names[3];
+
+ names[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
+ "com.sun.star.script.provider.MasterScriptProvider" ) );
+ names[1] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
+ "com.sun.star.script.browse.BrowseNode" ) );
+ names[2] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
+ "com.sun.star.script.provider.ScriptProvider" ) );
+
+ return Sequence< ::rtl::OUString >( names, 3 );
+}
+
+//*************************************************************************
+::rtl::OUString sp_getImplementationName( )
+SAL_THROW( () )
+{
+ return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM (
+ "com.sun.star.script.provider.MasterScriptProvider" ) );
+}
+
+// ***** registration or ScriptingFrameworkURIHelper
+Reference< XInterface > SAL_CALL urihelper_create(
+ const Reference< XComponentContext > & xCompC )
+{
+ return ( cppu::OWeakObject * )
+ new ::func_provider::ScriptingFrameworkURIHelper( xCompC );
+}
+
+Sequence< ::rtl::OUString > urihelper_getSupportedServiceNames( )
+ SAL_THROW( () )
+{
+ ::rtl::OUString serviceNameList[] = {
+ ::rtl::OUString::createFromAscii(
+ "com.sun.star.script.provider.ScriptURIHelper" ) };
+
+ Sequence< ::rtl::OUString > serviceNames = Sequence <
+ ::rtl::OUString > ( serviceNameList, 1 );
+
+ return serviceNames;
+}
+
+::rtl::OUString urihelper_getImplementationName( )
+ SAL_THROW( () )
+{
+ return ::rtl::OUString::createFromAscii(
+ "com.sun.star.script.provider.ScriptURIHelper");
+}
+
+static struct cppu::ImplementationEntry s_entries [] =
+ {
+ {
+ sp_create, sp_getImplementationName,
+ sp_getSupportedServiceNames, cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ {
+ urihelper_create,
+ urihelper_getImplementationName,
+ urihelper_getSupportedServiceNames,
+ cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ {
+ func_provider::mspf_create, func_provider::mspf_getImplementationName,
+ func_provider::mspf_getSupportedServiceNames, cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ {
+ browsenodefactory::bnf_create, browsenodefactory::bnf_getImplementationName,
+ browsenodefactory::bnf_getSupportedServiceNames, cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ { 0, 0, 0, 0, 0, 0 }
+ };
+}
+
+//############################################################################
+//#### EXPORTED ##############################################################
+//############################################################################
+
+/**
+ * Gives the environment this component belongs to.
+ */
+extern "C"
+{
+ SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment(
+ const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
+ {
+ (void)ppEnv;
+ *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
+ }
+
+ /**
+ * This function creates an implementation section in the registry and another subkey
+ *
+ * for each supported service.
+ * @param pServiceManager the service manager
+ * @param pRegistryKey the registry key
+ */
+ SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo(
+ lang::XMultiServiceFactory * pServiceManager,
+ registry::XRegistryKey * pRegistryKey )
+ {
+ if (::cppu::component_writeInfoHelper( pServiceManager, pRegistryKey,
+ ::scripting_runtimemgr::s_entries ))
+ {
+ try
+ {
+ // MasterScriptProviderFactory Mangager singleton
+ registry::XRegistryKey * pKey =
+ reinterpret_cast< registry::XRegistryKey * >(pRegistryKey);
+
+ Reference< registry::XRegistryKey >xKey = pKey->createKey(
+ OUSTR("com.sun.star.script.provider.MasterScriptProviderFactory/UNO/SINGLETONS/com.sun.star.script.provider.theMasterScriptProviderFactory"));
+ xKey->setStringValue( OUSTR("com.sun.star.script.provider.MasterScriptProviderFactory") );
+ // BrowseNodeFactory Mangager singleton
+ xKey = pKey->createKey(
+ OUSTR("com.sun.star.script.browse.BrowseNodeFactory/UNO/SINGLETONS/com.sun.star.script.browse.theBrowseNodeFactory"));
+ xKey->setStringValue( OUSTR("com.sun.star.script.browse.BrowseNodeFactory") );
+ return sal_True;
+ }
+ catch (Exception &)
+ {
+ }
+ }
+ return sal_False;
+ }
+
+ /**
+ * This function is called to get service factories for an implementation.
+ *
+ * @param pImplName name of implementation
+ * @param pServiceManager a service manager, need for component creation
+ * @param pRegistryKey the registry key for this component, need for persistent
+ * data
+ * @return a component factory
+ */
+ SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory(
+ const sal_Char * pImplName,
+ lang::XMultiServiceFactory * pServiceManager,
+ registry::XRegistryKey * pRegistryKey )
+ {
+ return ::cppu::component_getFactoryHelper( pImplName, pServiceManager,
+ pRegistryKey, ::scripting_runtimemgr::s_entries );
+ }
+}
diff --git a/scripting/source/provider/MasterScriptProvider.hxx b/scripting/source/provider/MasterScriptProvider.hxx
new file mode 100644
index 000000000000..49638473e5a5
--- /dev/null
+++ b/scripting/source/provider/MasterScriptProvider.hxx
@@ -0,0 +1,160 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: MasterScriptProvider.hxx,v $
+ * $Revision: 1.15 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
+#define _FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
+
+#include <rtl/ustring.hxx>
+
+#include <cppuhelper/implbase5.hxx>
+
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/container/XNameContainer.hpp>
+#include <com/sun/star/document/XScriptInvocationContext.hpp>
+
+#include <com/sun/star/lang/XInitialization.hpp>
+
+#include <com/sun/star/script/provider/XScriptProvider.hpp>
+#include <com/sun/star/script/browse/XBrowseNode.hpp>
+
+#include "ProviderCache.hxx"
+
+namespace func_provider
+{
+// for simplification
+#define css ::com::sun::star
+
+ typedef ::cppu::WeakImplHelper5<
+ css::script::provider::XScriptProvider,
+ css::script::browse::XBrowseNode, css::lang::XServiceInfo,
+ css::lang::XInitialization,
+ css::container::XNameContainer > t_helper;
+
+class MasterScriptProvider :
+ public t_helper
+{
+public:
+ MasterScriptProvider(
+ const css::uno::Reference< css::uno::XComponentContext >
+ & xContext ) throw( css::uno::RuntimeException );
+ ~MasterScriptProvider();
+
+ // XServiceInfo implementation
+ virtual ::rtl::OUString SAL_CALL getImplementationName( )
+ throw( css::uno::RuntimeException );
+
+ // XBrowseNode implementation
+ virtual ::rtl::OUString SAL_CALL getName()
+ throw ( css::uno::RuntimeException );
+ virtual css::uno::Sequence< css::uno::Reference< css::script::browse::XBrowseNode > > SAL_CALL getChildNodes()
+ throw ( css::uno::RuntimeException );
+ virtual sal_Bool SAL_CALL hasChildNodes()
+ throw ( css::uno::RuntimeException );
+ virtual sal_Int16 SAL_CALL getType()
+ throw ( css::uno::RuntimeException );
+ // XNameContainer
+ virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw ( css::lang::IllegalArgumentException, css::container::ElementExistException, css::lang::WrappedTargetException, css::uno::RuntimeException);
+ virtual void SAL_CALL removeByName( const ::rtl::OUString& Name ) throw ( css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
+
+ // XNameReplace
+ virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const css::uno::Any& aElement ) throw ( css::lang::IllegalArgumentException, css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
+ // XNameAccess
+ virtual css::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw ( css::container::NoSuchElementException, css::lang::WrappedTargetException, css::uno::RuntimeException);
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw ( css::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);
+
+ // XElementAccess
+ virtual css::uno::Type SAL_CALL getElementType( ) throw ( css::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL hasElements( ) throw ( css::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
+ throw( css::uno::RuntimeException );
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
+ throw( css::uno::RuntimeException );
+
+ // XScriptProvider implementation
+ virtual css::uno::Reference < css::script::provider::XScript > SAL_CALL
+ getScript( const ::rtl::OUString& scriptURI )
+ throw( css::script::provider::ScriptFrameworkErrorException,
+ css::uno::RuntimeException );
+
+ /**
+ * XInitialise implementation
+ *
+ * @param args expected to contain a single ::rtl::OUString
+ * containing the URI
+ */
+ virtual void SAL_CALL initialize( const css::uno::Sequence < css::uno::Any > & args )
+ throw ( css::uno::Exception, css::uno::RuntimeException);
+
+ // Public method to return all Language Providers in this MasterScriptProviders
+ // context.
+ css::uno::Sequence< css::uno::Reference< css::script::provider::XScriptProvider > > SAL_CALL
+ getAllProviders() throw ( css::uno::RuntimeException );
+
+ bool isPkgProvider() { return m_bIsPkgMSP; }
+ css::uno::Reference< css::script::provider::XScriptProvider > getPkgProvider() { return m_xMSPPkg; }
+ // returns context string for this provider, eg
+ ::rtl::OUString getContextString() { return m_sCtxString; }
+
+private:
+ ::rtl::OUString parseLocationName( const ::rtl::OUString& location );
+ void createPkgProvider();
+ bool isValid();
+ ::rtl::OUString getURLForModel();
+ const css::uno::Sequence< ::rtl::OUString >& getProviderNames();
+
+ ProviderCache* providerCache();
+ /* to obtain other services if needed */
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+ css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;
+ css::uno::Reference< css::frame::XModel > m_xModel;
+ css::uno::Reference< css::document::XScriptInvocationContext > m_xInvocationContext;
+ css::uno::Sequence< css::uno::Any > m_sAargs;
+ ::rtl::OUString m_sNodeName;
+
+ // This component supports XInitialization, it can be created
+ // using createInstanceXXX() or createInstanceWithArgumentsXXX using
+ // the service Mangager.
+ // Need to detect proper initialisation and validity
+ // for the object, so m_bIsValid indicates that the object is valid is set in ctor
+ // in case of createInstanceWithArgumentsXXX() called m_bIsValid is set to reset
+ // and then set to true when initialisation is complete
+ bool m_bIsValid;
+ // m_bInitialised ensure initialisation only takes place once.
+ bool m_bInitialised;
+ bool m_bIsPkgMSP;
+ css::uno::Reference< css::script::provider::XScriptProvider > m_xMSPPkg;
+ ProviderCache* m_pPCache;
+ osl::Mutex m_mutex;
+ ::rtl::OUString m_sCtxString;
+};
+} // namespace func_provider
+#endif //_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
diff --git a/scripting/source/provider/MasterScriptProviderFactory.cxx b/scripting/source/provider/MasterScriptProviderFactory.cxx
new file mode 100644
index 000000000000..7229389f5516
--- /dev/null
+++ b/scripting/source/provider/MasterScriptProviderFactory.cxx
@@ -0,0 +1,156 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: MasterScriptProviderFactory.cxx,v $
+ * $Revision: 1.11 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include <cppuhelper/weakref.hxx>
+#include <cppuhelper/implementationentry.hxx>
+#include <cppuhelper/factory.hxx>
+#include <cppuhelper/exc_hlp.hxx>
+#include <cppuhelper/implbase1.hxx>
+
+#include <util/util.hxx>
+
+#include "MasterScriptProviderFactory.hxx"
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::script;
+
+namespace func_provider
+{
+
+MasterScriptProviderFactory::MasterScriptProviderFactory(
+ Reference< XComponentContext > const & xComponentContext )
+ : m_xComponentContext( xComponentContext )
+{
+}
+
+MasterScriptProviderFactory::~MasterScriptProviderFactory()
+{
+}
+
+
+//############################################################################
+// Implementation of XScriptProviderFactory
+//############################################################################
+
+
+Reference< provider::XScriptProvider > SAL_CALL
+MasterScriptProviderFactory::createScriptProvider( const Any& context ) throw ( lang::IllegalArgumentException, RuntimeException)
+{
+ Reference< provider::XScriptProvider > xMsp( getActiveMSPList() ->getMSPFromAnyContext( context ), UNO_QUERY_THROW );
+ return xMsp;
+}
+
+//############################################################################
+// Helper methods
+//############################################################################
+
+const rtl::Reference< ActiveMSPList > &
+MasterScriptProviderFactory::getActiveMSPList() const
+{
+ if ( !m_MSPList.is() )
+ {
+ ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() );
+ if ( !m_MSPList.is() )
+ m_MSPList = new ActiveMSPList( m_xComponentContext );
+ }
+ return m_MSPList;
+}
+
+//############################################################################
+// Namespace global methods for setting up MasterScriptProviderFactory service
+//############################################################################
+
+Sequence< ::rtl::OUString > SAL_CALL
+mspf_getSupportedServiceNames( )
+ SAL_THROW( () )
+{
+ ::rtl::OUString str_name = ::rtl::OUString::createFromAscii(
+ "com.sun.star.script.provider.MasterScriptProviderFactory");
+
+ return Sequence< ::rtl::OUString >( &str_name, 1 );
+}
+
+::rtl::OUString SAL_CALL
+mspf_getImplementationName( )
+ SAL_THROW( () )
+{
+ return ::rtl::OUString::createFromAscii(
+ "com.sun.star.script.provider.MasterScriptProviderFactory");
+}
+
+Reference< XInterface > SAL_CALL
+mspf_create( Reference< XComponentContext > const & xComponentContext )
+ SAL_THROW( (Exception) )
+{
+ return static_cast< ::cppu::OWeakObject * >(
+ new MasterScriptProviderFactory( xComponentContext ) );
+}
+
+//############################################################################
+// Implementation of XServiceInfo
+//############################################################################
+
+::rtl::OUString SAL_CALL
+MasterScriptProviderFactory::getImplementationName()
+ throw (RuntimeException)
+{
+ return mspf_getImplementationName();
+}
+
+Sequence< ::rtl::OUString > SAL_CALL
+MasterScriptProviderFactory::getSupportedServiceNames()
+ throw (RuntimeException)
+{
+ return mspf_getSupportedServiceNames();
+}
+
+sal_Bool MasterScriptProviderFactory::supportsService(
+ ::rtl::OUString const & serviceName )
+ throw (RuntimeException)
+{
+// check();
+
+ Sequence< ::rtl::OUString > supported_services(
+ getSupportedServiceNames() );
+
+ ::rtl::OUString const * ar = supported_services.getConstArray();
+
+ for ( sal_Int32 pos = supported_services.getLength(); pos--; )
+ {
+ if (ar[ pos ].equals( serviceName ))
+ return true;
+ }
+ return false;
+}
+
+} // namespace browsenodefactory
diff --git a/scripting/source/provider/MasterScriptProviderFactory.hxx b/scripting/source/provider/MasterScriptProviderFactory.hxx
new file mode 100644
index 000000000000..f006442fd21d
--- /dev/null
+++ b/scripting/source/provider/MasterScriptProviderFactory.hxx
@@ -0,0 +1,88 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: MasterScriptProviderFactory.hxx,v $
+ * $Revision: 1.7 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#include "rtl/ustring.hxx"
+#include "rtl/ref.hxx"
+#include <cppuhelper/implbase2.hxx>
+
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/registry/XRegistryKey.hpp>
+
+#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
+#include <com/sun/star/script/provider/XScriptProvider.hpp>
+
+#include "ActiveMSPList.hxx"
+
+namespace func_provider
+{
+// for simplification
+#define css ::com::sun::star
+
+class MasterScriptProviderFactory :
+ public ::cppu::WeakImplHelper2 <
+ css::script::provider::XScriptProviderFactory,
+ css::lang::XServiceInfo >
+{
+private:
+
+ mutable rtl::Reference< ActiveMSPList > m_MSPList;
+
+ const css::uno::Reference< css::uno::XComponentContext > m_xComponentContext;
+
+ const rtl::Reference< ActiveMSPList > & getActiveMSPList() const;
+
+protected:
+ virtual ~MasterScriptProviderFactory();
+
+public:
+ MasterScriptProviderFactory(
+ css::uno::Reference< css::uno::XComponentContext > const & xComponentContext );
+
+ // XServiceInfo
+ virtual ::rtl::OUString SAL_CALL getImplementationName()
+ throw ( css::uno::RuntimeException );
+
+ virtual sal_Bool SAL_CALL
+ supportsService( ::rtl::OUString const & serviceName )
+ throw ( css::uno::RuntimeException );
+
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL
+ getSupportedServiceNames()
+ throw ( css::uno::RuntimeException );
+
+ // XScriptProviderFactory
+ virtual css::uno::Reference< css::script::provider::XScriptProvider >
+ SAL_CALL createScriptProvider( const css::uno::Any& context )
+ throw ( css::lang::IllegalArgumentException, css::uno::RuntimeException);
+};
+
+
+} // namespace func_provider
diff --git a/scripting/source/provider/ProviderCache.cxx b/scripting/source/provider/ProviderCache.cxx
new file mode 100644
index 000000000000..2070ab062f78
--- /dev/null
+++ b/scripting/source/provider/ProviderCache.cxx
@@ -0,0 +1,225 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ProviderCache.cxx,v $
+ * $Revision: 1.13 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include <cppuhelper/implementationentry.hxx>
+#include <cppuhelper/factory.hxx>
+
+#include <util/scriptingconstants.hxx>
+#include <util/util.hxx>
+
+#include <com/sun/star/container/XContentEnumerationAccess.hpp>
+#include "ProviderCache.hxx"
+
+using namespace com::sun::star;
+using namespace com::sun::star::uno;
+using namespace com::sun::star::script;
+using namespace ::scripting_util;
+
+namespace func_provider
+{
+
+ProviderCache::ProviderCache( const Reference< XComponentContext >& xContext, const Sequence< Any >& scriptContext )
+ throw ( RuntimeException ) : m_Sctx( scriptContext ), m_xContext( xContext )
+{
+ // initialise m_hProviderDetailsCache with details of ScriptProviders
+ // will use createContentEnumeration
+
+ m_xMgr = m_xContext->getServiceManager();
+ validateXRef( m_xMgr, "ProviderCache::ProviderCache() failed to obtain ServiceManager" );
+ populateCache();
+}
+
+
+ProviderCache::ProviderCache( const Reference< XComponentContext >& xContext, const Sequence< Any >& scriptContext, const Sequence< ::rtl::OUString >& blackList )
+ throw ( RuntimeException ) : m_sBlackList( blackList ), m_Sctx( scriptContext ), m_xContext( xContext )
+
+{
+ // initialise m_hProviderDetailsCache with details of ScriptProviders
+ // will use createContentEnumeration
+
+ m_xMgr = m_xContext->getServiceManager();
+ validateXRef( m_xMgr, "ProviderCache::ProviderCache() failed to obtain ServiceManager" );
+ populateCache();
+}
+
+ProviderCache::~ProviderCache()
+{
+}
+
+Reference< provider::XScriptProvider >
+ProviderCache::getProvider( const ::rtl::OUString& providerName )
+{
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+ Reference< provider::XScriptProvider > provider;
+ ProviderDetails_hash::iterator h_it = m_hProviderDetailsCache.find( providerName );
+ if ( h_it != m_hProviderDetailsCache.end() )
+ {
+ if ( h_it->second.provider.is() )
+ {
+ provider = h_it->second.provider;
+ }
+ else
+ {
+ // need to create provider and insert into hash
+ provider = createProvider( h_it->second );
+ }
+ }
+ return provider;
+}
+
+Sequence < Reference< provider::XScriptProvider > >
+ProviderCache::getAllProviders() throw ( RuntimeException )
+{
+ Sequence < Reference< provider::XScriptProvider > > providers ( m_hProviderDetailsCache.size() );
+ // need to create providers that haven't been created already
+ // so check what providers exist and what ones don't
+
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+ ProviderDetails_hash::iterator h_itEnd = m_hProviderDetailsCache.end();
+ ProviderDetails_hash::iterator h_it = m_hProviderDetailsCache.begin();
+ // should assert if size !> 0
+ if ( m_hProviderDetailsCache.size() )
+ {
+ sal_Int32 providerIndex = 0;
+ sal_Int32 index = 0;
+ for ( index = 0; h_it != h_itEnd; ++h_it, index++ )
+ {
+ Reference< provider::XScriptProvider > xScriptProvider = h_it->second.provider;
+ if ( xScriptProvider.is() )
+ {
+ providers[ providerIndex++ ] = xScriptProvider;
+ }
+ else
+ {
+ // create provider
+ try
+ {
+ xScriptProvider = createProvider( h_it->second );
+ providers[ providerIndex++ ] = xScriptProvider;
+ }
+ catch ( Exception& e )
+ {
+ ::rtl::OUString temp = OUSTR( "ProviderCache::getAllProviders: failed to create provider, " );
+ temp.concat( e.Message );
+ //throw RuntimeException( temp.concat( e.Message ),
+ // Reference< XInterface >() );
+ }
+ }
+ }
+
+ if ( providerIndex < index )
+ {
+ providers.realloc( providerIndex );
+ }
+
+ }
+ else
+ {
+ OSL_TRACE("no available providers, something very wrong!!!");
+ }
+ return providers;
+}
+
+void
+ProviderCache::populateCache() throw ( RuntimeException )
+{
+ // wrong name in services.rdb
+ ::rtl::OUString serviceName;
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+ try
+ {
+ ::rtl::OUString languageProviderName( RTL_CONSTASCII_USTRINGPARAM(
+ "com.sun.star.script.provider.LanguageScriptProvider" ) );
+
+ Reference< container::XContentEnumerationAccess > xEnumAccess = Reference< container::XContentEnumerationAccess >( m_xMgr, UNO_QUERY_THROW );
+ Reference< container::XEnumeration > xEnum = xEnumAccess->createContentEnumeration ( languageProviderName );
+
+ while ( xEnum->hasMoreElements() )
+ {
+
+ Reference< lang::XSingleComponentFactory > factory;
+ if ( sal_False == ( xEnum->nextElement() >>= factory ) )
+ {
+ throw new RuntimeException( ::rtl::OUString::createFromAscii( " error extracting XSingleComponentFactory from Content enumeration. " ), Reference< XInterface >() );
+ }
+ validateXRef( factory, "ProviderCache::populateCache() invalid factory" );
+ Reference< lang::XServiceInfo > xServiceInfo( factory, UNO_QUERY_THROW );
+ validateXRef( xServiceInfo, "ProviderCache::populateCache() failed to get XServiceInfo from factory" );
+
+ Sequence< ::rtl::OUString > serviceNames = xServiceInfo->getSupportedServiceNames();
+
+ if ( serviceNames.getLength() > 0 )
+ {
+ ::rtl::OUString searchString( RTL_CONSTASCII_USTRINGPARAM (
+ "com.sun.star.script.provider.ScriptProviderFor" ) );
+
+ for ( sal_Int32 index = 0; index < serviceNames.getLength(); index++ )
+ {
+ if ( serviceNames[ index ].indexOf( searchString ) == 0 && !isInBlackList( serviceNames[ index ] ) )
+ {
+ serviceName = serviceNames[ index ];
+ ProviderDetails details;
+ details.factory = factory;
+ m_hProviderDetailsCache[ serviceName ] = details;
+ break;
+ }
+ }
+ }
+ }
+ }
+ catch ( Exception e )
+ {
+ ::rtl::OUString temp = OUSTR(
+ "ProviderCache::populateCache: couldn't obtain XSingleComponentFactory for " );
+ temp.concat( serviceName );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+}
+
+Reference< provider::XScriptProvider >
+ProviderCache::createProvider( ProviderDetails& details ) throw ( RuntimeException )
+{
+ try
+ {
+ details.provider = Reference< provider::XScriptProvider >(
+ details.factory->createInstanceWithArgumentsAndContext( m_Sctx, m_xContext ), UNO_QUERY_THROW );
+ validateXRef( details.provider, "ProviderCache::createProvider, failed to create provider");
+ }
+ catch ( RuntimeException& e )
+ {
+ ::rtl::OUString temp = ::rtl::OUString::createFromAscii("ProviderCache::createProvider() Error creating provider from factory!!!");
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+
+ return details.provider;
+}
+} //end namespace
diff --git a/scripting/source/provider/ProviderCache.hxx b/scripting/source/provider/ProviderCache.hxx
new file mode 100644
index 000000000000..8438e661cca0
--- /dev/null
+++ b/scripting/source/provider/ProviderCache.hxx
@@ -0,0 +1,111 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ProviderCache.hxx,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef _FRAMEWORK_SCRIPT_PROVIDER_PROVIDERCACHE_HXX_
+#define _FRAMEWORK_SCRIPT_PROVIDER_PROVIDERCACHE_HXX_
+
+#include <hash_map>
+#include <osl/mutex.hxx>
+#include <rtl/ustring.hxx>
+#include <cppuhelper/implbase1.hxx>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XSingleServiceFactory.hpp>
+#include <com/sun/star/lang/XSingleComponentFactory.hpp>
+#include <com/sun/star/lang/XMultiComponentFactory.hpp>
+
+#include <com/sun/star/frame/XModel.hpp>
+#include <com/sun/star/script/provider/XScriptProvider.hpp>
+
+#include "ScriptingContext.hxx"
+
+namespace func_provider
+{
+// for simplification
+#define css ::com::sun::star
+
+//Typedefs
+//=============================================================================
+
+struct ProviderDetails
+{
+ //css::uno::Reference< css::lang::XSingleServiceFactory > factory;
+ css::uno::Reference< css::lang::XSingleComponentFactory > factory;
+ css::uno::Reference< css::script::provider::XScriptProvider > provider;
+};
+typedef ::std::hash_map < ::rtl::OUString, ProviderDetails , ::rtl::OUStringHash,
+ ::std::equal_to< ::rtl::OUString > > ProviderDetails_hash;
+
+
+class ProviderCache
+{
+
+public:
+ ProviderCache( const css::uno::Reference< css::uno::XComponentContext >& xContext, const css::uno::Sequence< css::uno::Any >& scriptContext )
+ throw ( css::uno::RuntimeException );
+ ProviderCache( const css::uno::Reference< css::uno::XComponentContext >& xContext, const css::uno::Sequence< css::uno::Any >& scriptContext,
+ const css::uno::Sequence< ::rtl::OUString >& blackList )
+ throw ( css::uno::RuntimeException );
+ ~ProviderCache();
+ css::uno::Reference< css::script::provider::XScriptProvider >
+ getProvider( const ::rtl::OUString& providerName );
+ css::uno::Sequence < css::uno::Reference< css::script::provider::XScriptProvider > >
+ getAllProviders() throw ( css::uno::RuntimeException );
+private:
+ void populateCache()
+ throw ( css::uno::RuntimeException );
+
+ css::uno::Reference< css::script::provider::XScriptProvider >
+ createProvider( ProviderDetails& details ) throw ( css::uno::RuntimeException );
+ bool isInBlackList( const ::rtl::OUString& serviceName )
+ {
+ if ( m_sBlackList.getLength() > 0 )
+ {
+ for ( sal_Int32 index = 0; index < m_sBlackList.getLength(); index++ )
+ {
+ if ( m_sBlackList[ index ].equals( serviceName ) )
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ css::uno::Sequence< ::rtl::OUString > m_sBlackList;
+ ProviderDetails_hash m_hProviderDetailsCache;
+ osl::Mutex m_mutex;
+ css::uno::Sequence< css::uno::Any > m_Sctx;
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+ css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;
+
+
+};
+} // func_provider
+#endif
diff --git a/scripting/source/provider/ScriptImpl.cxx b/scripting/source/provider/ScriptImpl.cxx
new file mode 100644
index 000000000000..35d9c429e5b2
--- /dev/null
+++ b/scripting/source/provider/ScriptImpl.cxx
@@ -0,0 +1,125 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptImpl.cxx,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#include <stdio.h>
+
+#include "ScriptImpl.hxx"
+#include <util/util.hxx>
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::script::framework;
+
+namespace func_provider
+{
+
+//*************************************************************************
+ScriptImpl::ScriptImpl(
+ const Reference< beans::XPropertySet > & scriptingContext,
+ const Reference< runtime::XScriptInvocation > & runtimeMgr,
+ const ::rtl::OUString& scriptURI )
+throw ( RuntimeException ) :
+ m_XScriptingContext( scriptingContext ),
+ m_RunTimeManager( runtimeMgr ),
+ m_ScriptURI( scriptURI )
+{
+ OSL_TRACE( "<!constucting a ScriptImpl>\n" );
+ validateXRef( m_XScriptingContext,
+ "ScriptImpl::ScriptImpl: No XScriptingContext\n" );
+ validateXRef( m_RunTimeManager,
+ "ScriptImpl::ScriptImpl: No XScriptInvocation\n" );
+}
+
+//*************************************************************************
+ScriptImpl::~ScriptImpl()
+{
+ OSL_TRACE( "<Destructing a ScriptImpl>\n" );
+}
+
+//*************************************************************************
+Any SAL_CALL
+ScriptImpl::invoke( const Sequence< Any >& aParams,
+ Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam )
+throw ( lang::IllegalArgumentException, script::CannotConvertException,
+ reflection::InvocationTargetException, RuntimeException )
+{
+ OSL_TRACE( "<ScriptImpl::invoke>" );
+ Any result;
+ Any anyScriptingContext;
+
+ anyScriptingContext <<= m_XScriptingContext;
+ try
+ {
+ result = m_RunTimeManager->invoke( m_ScriptURI, anyScriptingContext, aParams,
+ aOutParamIndex, aOutParam );
+ }
+ catch ( lang::IllegalArgumentException & iae )
+ {
+ ::rtl::OUString temp = OUSTR( "ScriptImpl::invoke IllegalArgumentException : " );
+ throw lang::IllegalArgumentException( temp.concat( iae.Message ),
+ Reference< XInterface > (),
+ iae.ArgumentPosition );
+ }
+ catch ( script::CannotConvertException & cce )
+ {
+ ::rtl::OUString temp = OUSTR( "ScriptImpl::invoke CannotConvertException : " );
+ throw script::CannotConvertException( temp.concat( cce.Message ),
+ Reference< XInterface > (),
+ cce.DestinationTypeClass,
+ cce.Reason,
+ cce.ArgumentIndex );
+ }
+ catch ( reflection::InvocationTargetException & ite )
+ {
+ ::rtl::OUString temp = OUSTR( "ScriptImpl::invoke InvocationTargetException : " );
+ throw reflection::InvocationTargetException( temp.concat( ite.Message ),
+ Reference< XInterface > (),
+ ite.TargetException );
+ }
+ catch ( RuntimeException & re )
+ {
+ ::rtl::OUString temp = OUSTR( "ScriptImpl::invoke RuntimeException : " );
+ throw RuntimeException( temp.concat( re.Message ),
+ Reference< XInterface > () );
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptImpl::invoke Unknown Exception caught - RuntimeException rethrown" ),
+ Reference< XInterface > () );
+ }
+#endif
+ return result;
+}
+} // namespace func_provider
diff --git a/scripting/source/provider/ScriptImpl.hxx b/scripting/source/provider/ScriptImpl.hxx
new file mode 100644
index 000000000000..64e56297bcb8
--- /dev/null
+++ b/scripting/source/provider/ScriptImpl.hxx
@@ -0,0 +1,116 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptImpl.hxx,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef _FRAMEWORK_SCRIPT_PROVIDER_FUNCTIONIMPL_HXX_
+#define _FRAMEWORK_SCRIPT_PROVIDER_FUNCTIONIMPL_HXX_
+
+#include <cppuhelper/implbase1.hxx> // helper for XInterface, XTypeProvider etc.
+#include <osl/mutex.hxx>
+
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/script/CannotConvertException.hpp>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/reflection/InvocationTargetException.hpp>
+
+#include <drafts/com/sun/star/script/framework/provider/XScript.hpp>
+#include <drafts/com/sun/star/script/framework/runtime/XScriptInvocation.hpp>
+
+namespace func_provider
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+
+class ScriptImpl :
+ public ::cppu::WeakImplHelper1 < dcsssf::provider::XScript >
+{
+
+public:
+ /*************************************************************
+ ScriptImpl Constructor
+ @param runtimeMgr which is a service that implement a XScriptInvocation
+ @param scriptURI the received ScriptURI that needs to be resolve and invoked
+ */
+ ScriptImpl(
+ const css::uno::Reference< css::beans::XPropertySet > & scriptingContext,
+ const css::uno::Reference< dcsssf::runtime::XScriptInvocation > & runtimeMgr,
+ const ::rtl::OUString& scriptURI )
+ throw ( css::uno::RuntimeException );
+
+ /*************************************************************
+ ScriptImpl Destructor
+ */
+ ~ScriptImpl();
+
+ /*************************************************************
+ Invoke
+ @param aParams all parameters; pure, out params are undefined in sequence,
+ i.e., the value has to be ignored by the callee
+ @param aOutParamIndex out indices
+ @param aOutParam out parameters
+
+ @returns
+ the value returned from the function being invoked
+
+ @throws IllegalArgumentException
+ if there is no matching script name
+
+ @throws CannotConvertException
+ if args do not match or cannot be converted the those
+ of the invokee
+
+ @throws InvocationTargetException
+ if the running script throws an exception this information is captured and
+ rethrown as this exception type.
+
+ */
+ virtual css::uno::Any SAL_CALL invoke(
+ const css::uno::Sequence< css::uno::Any > & aParams,
+ css::uno::Sequence< sal_Int16 > & aOutParamIndex,
+ css::uno::Sequence< css::uno::Any > & aOutParam )
+ throw ( css::lang::IllegalArgumentException,
+ css::script::CannotConvertException,
+ css::reflection::InvocationTargetException,
+ css::uno::RuntimeException );
+
+private:
+ css::uno::Reference< css::beans::XPropertySet > m_XScriptingContext;
+ css::uno::Reference < dcsssf::runtime::XScriptInvocation > m_RunTimeManager;
+ ::rtl::OUString m_ScriptURI;
+
+ /* copy ctor disabled, i.e. not defined */
+ ScriptImpl( const ScriptImpl& );
+ /* assignment disabled, i.e. not defined */
+ ScriptImpl& operator = ( const ScriptImpl& );
+};
+} // namespace func_provider
+#endif //_FRAMEWORK_SCRIPT_PROVIDER_FUNCTIONIMPL_HXX_
diff --git a/scripting/source/provider/ScriptingContext.cxx b/scripting/source/provider/ScriptingContext.cxx
new file mode 100755
index 000000000000..961a5b20de88
--- /dev/null
+++ b/scripting/source/provider/ScriptingContext.cxx
@@ -0,0 +1,119 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptingContext.cxx,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include <com/sun/star/beans/PropertyAttribute.hpp>
+#include <com/sun/star/frame/XModel.hpp>
+
+#include <cppuhelper/implementationentry.hxx>
+#include <cppuhelper/factory.hxx>
+
+#include <util/scriptingconstants.hxx>
+#include <util/util.hxx>
+
+#include "ScriptingContext.hxx"
+
+using namespace com::sun::star;
+using namespace com::sun::star::uno;
+#define DOC_REF_PROPID 1
+#define DOC_STORAGE_ID_PROPID 2
+#define DOC_URI_PROPID 3
+#define RESOLVED_STORAGE_ID_PROPID 4
+#define SCRIPT_INFO_PROPID 5
+#define SCRIPTINGCONTEXT_DEFAULT_ATTRIBS() beans::PropertyAttribute::TRANSIENT | beans::PropertyAttribute::MAYBEVOID
+namespace func_provider
+{
+
+//*************************************************************************
+// XScriptingContext implementation
+//
+//*************************************************************************
+ScriptingContext::ScriptingContext( const Reference< XComponentContext > & xContext ) : //ScriptingContextImpl_BASE( GetMutex()),
+ OPropertyContainer( GetBroadcastHelper() ),
+ m_xContext( xContext )
+{
+ OSL_TRACE( "< ScriptingContext ctor called >\n" );
+
+ validateXRef( m_xContext,
+ "ScriptingContext::ScriptingContext: No context available\n" );
+
+ Any nullAny;
+
+ scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
+ scripting_constants::ScriptingConstantsPool::instance();
+ registerPropertyNoMember( scriptingConstantsPool.DOC_REF, DOC_REF_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(),::getCppuType( (const Reference< css::frame::XModel >* ) NULL ), NULL ) ;
+ registerPropertyNoMember( scriptingConstantsPool.DOC_STORAGE_ID, DOC_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL ) ;
+ registerPropertyNoMember( scriptingConstantsPool.DOC_URI, DOC_URI_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const ::rtl::OUString* ) NULL ), NULL ) ;
+ registerPropertyNoMember( scriptingConstantsPool.RESOLVED_STORAGE_ID, RESOLVED_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL );
+ registerPropertyNoMember( scriptingConstantsPool.SCRIPT_INFO, SCRIPT_INFO_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType( (const sal_Int32* ) NULL ), NULL );
+}
+
+ScriptingContext::~ScriptingContext()
+{
+ OSL_TRACE( "< ScriptingContext dtor called >\n" );
+}
+// -----------------------------------------------------------------------------
+// OPropertySetHelper
+// -----------------------------------------------------------------------------
+
+::cppu::IPropertyArrayHelper& ScriptingContext::getInfoHelper( )
+{
+ return *getArrayHelper();
+}
+
+// -----------------------------------------------------------------------------
+// OPropertyArrayUsageHelper
+// -----------------------------------------------------------------------------
+
+::cppu::IPropertyArrayHelper* ScriptingContext::createArrayHelper( ) const
+{
+ Sequence< beans::Property > aProps;
+ describeProperties( aProps );
+ return new ::cppu::OPropertyArrayHelper( aProps );
+}
+// -----------------------------------------------------------------------------
+// XPropertySet
+// -----------------------------------------------------------------------------
+
+Reference< beans::XPropertySetInfo > ScriptingContext::getPropertySetInfo( ) throw (RuntimeException)
+{
+ Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
+ return xInfo;
+}
+// -----------------------------------------------------------------------------// XTypeProvider
+// -----------------------------------------------------------------------------
+IMPLEMENT_GET_IMPLEMENTATION_ID( ScriptingContext )
+
+css::uno::Sequence< css::uno::Type > SAL_CALL ScriptingContext::getTypes( ) throw (css::uno::RuntimeException)
+{
+ return OPropertyContainer::getTypes();
+}
+} // namespace func_provider
diff --git a/scripting/source/provider/ScriptingContext.hxx b/scripting/source/provider/ScriptingContext.hxx
new file mode 100644
index 000000000000..669ad39351dc
--- /dev/null
+++ b/scripting/source/provider/ScriptingContext.hxx
@@ -0,0 +1,94 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptingContext.hxx,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef _FRAMEWORK_SCRIPT_PROTOCOLHANDLER_SCRIPTING_CONTEXT_HXX_
+#define _FRAMEWORK_SCRIPT_PROTOCOLHANDLER_SCRIPTING_CONTEXT_HXX_
+
+
+#include <osl/mutex.hxx>
+#include <rtl/ustring.hxx>
+#include <cppuhelper/implbase1.hxx>
+#include <comphelper/uno3.hxx>
+#include <comphelper/propertycontainer.hxx>
+#include <comphelper/proparrhlp.hxx>
+
+#include <cppuhelper/implbase1.hxx>
+#include <cppuhelper/weak.hxx>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <comphelper/broadcasthelper.hxx>
+namespace func_provider
+{
+// for simplification
+#define css ::com::sun::star
+
+//Typedefs
+//=============================================================================
+//typedef ::cppu::WeakImplHelper1< css::beans::XPropertySet > ScriptingContextImpl_BASE;
+
+class ScriptingContext : public ::comphelper::OMutexAndBroadcastHelper, public ::comphelper::OPropertyContainer,
+ public ::comphelper::OPropertyArrayUsageHelper< ScriptingContext >, public css::lang::XTypeProvider, public ::cppu::OWeakObject
+{
+
+public:
+ ScriptingContext( const css::uno::Reference< css::uno::XComponentContext > & xContext );
+ ~ScriptingContext();
+ // XInterface
+
+ css::uno::Any SAL_CALL queryInterface( const css::uno::Type& rType )
+ throw( css::uno::RuntimeException )
+ {
+ css::uno::Any aRet( OPropertySetHelper::queryInterface( rType ) );
+ return (aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType ));
+ }
+ void SAL_CALL acquire() throw() { ::cppu::OWeakObject::acquire(); }
+ void SAL_CALL release() throw() { ::cppu::OWeakObject::release(); }
+ // XPropertySet
+ virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( )
+ throw ( css::uno::RuntimeException );
+ //XTypeProvider
+ DECLARE_XTYPEPROVIDER( )
+
+protected:
+
+ // OPropertySetHelper
+ virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper( );
+
+ // OPropertyArrayUsageHelper
+ virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
+private:
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+
+
+};
+} // func_provider
+#endif //_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_
diff --git a/scripting/source/provider/URIHelper.cxx b/scripting/source/provider/URIHelper.cxx
new file mode 100644
index 000000000000..3fcad686ac59
--- /dev/null
+++ b/scripting/source/provider/URIHelper.cxx
@@ -0,0 +1,325 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: URIHelper.cxx,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#include <com/sun/star/uri/XVndSunStarScriptUrl.hpp>
+#include <rtl/ustrbuf.hxx>
+#include "URIHelper.hxx"
+
+#define PRTSTR(x) ::rtl::OUStringToOString(x, RTL_TEXTENCODING_ASCII_US).pData->buffer
+
+namespace func_provider
+{
+
+using ::rtl::OUString;
+namespace uno = ::com::sun::star::uno;
+namespace ucb = ::com::sun::star::ucb;
+namespace lang = ::com::sun::star::lang;
+namespace uri = ::com::sun::star::uri;
+namespace script = ::com::sun::star::script;
+
+static const char SHARE[] = "share";
+static const char SHARE_URI[] =
+ "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" SAL_CONFIGFILE( "bootstrap") "::BaseInstallation}";
+
+static const char SHARE_UNO_PACKAGES[] = "share:uno_packages";
+static const char SHARE_UNO_PACKAGES_URI[] =
+ "vnd.sun.star.expand:$UNO_SHARED_PACKAGES_CACHE";
+
+static const char USER[] = "user";
+static const char USER_URI[] =
+ "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" SAL_CONFIGFILE( "bootstrap") "::UserInstallation}";
+
+static const char USER_UNO_PACKAGES[] = "user:uno_packages";
+static const char USER_UNO_PACKAGES_DIR[] =
+ "/user/uno_packages/cache";
+
+static const char DOCUMENT[] = "document";
+static const char TDOC_SCHEME[] = "vnd.sun.star.tdoc";
+
+ScriptingFrameworkURIHelper::ScriptingFrameworkURIHelper(
+ const uno::Reference< uno::XComponentContext >& xContext)
+ throw( uno::RuntimeException )
+{
+ try
+ {
+ m_xSimpleFileAccess = uno::Reference< ucb::XSimpleFileAccess >(
+ xContext->getServiceManager()->createInstanceWithContext(
+ OUString::createFromAscii(
+ "com.sun.star.ucb.SimpleFileAccess"),
+ xContext), uno::UNO_QUERY_THROW);
+ }
+ catch (uno::Exception&)
+ {
+ OSL_ENSURE(false,
+ "Scripting Framework error initialising XSimpleFileAccess");
+ }
+
+ try
+ {
+ m_xUriReferenceFactory = uno::Reference< uri::XUriReferenceFactory >(
+ xContext->getServiceManager()->createInstanceWithContext(
+ OUString::createFromAscii(
+ "com.sun.star.uri.UriReferenceFactory"),
+ xContext ), uno::UNO_QUERY_THROW );
+ }
+ catch (uno::Exception&)
+ {
+ OSL_ENSURE(false,
+ "Scripting Framework error initialising XUriReferenceFactory");
+ }
+}
+
+ScriptingFrameworkURIHelper::~ScriptingFrameworkURIHelper()
+{
+ // currently does nothing
+}
+
+void SAL_CALL
+ScriptingFrameworkURIHelper::initialize(
+ const uno::Sequence < uno::Any >& args )
+throw ( uno::Exception, uno::RuntimeException )
+{
+ if ( args.getLength() != 2 ||
+ args[0].getValueType() != ::getCppuType((const OUString*)NULL) ||
+ args[1].getValueType() != ::getCppuType((const OUString*)NULL) )
+ {
+ throw uno::RuntimeException( OUString::createFromAscii(
+ "ScriptingFrameworkURIHelper got invalid argument list" ),
+ uno::Reference< uno::XInterface >() );
+ }
+
+ if ( (args[0] >>= m_sLanguage) == sal_False ||
+ (args[1] >>= m_sLocation) == sal_False )
+ {
+ throw uno::RuntimeException( OUString::createFromAscii(
+ "ScriptingFrameworkURIHelper error parsing args" ),
+ uno::Reference< uno::XInterface >() );
+ }
+
+ SCRIPTS_PART = OUString::createFromAscii( "/Scripts/" );
+ SCRIPTS_PART = SCRIPTS_PART.concat( m_sLanguage.toAsciiLowerCase() );
+
+ if ( !initBaseURI() )
+ {
+ throw uno::RuntimeException( OUString::createFromAscii(
+ "ScriptingFrameworkURIHelper cannot find script directory"),
+ uno::Reference< uno::XInterface >() );
+ }
+}
+
+bool
+ScriptingFrameworkURIHelper::initBaseURI()
+{
+ OUString uri, test;
+ bool bAppendScriptsPart = false;
+
+ if ( m_sLocation.equalsAscii(USER))
+ {
+ test = OUString::createFromAscii(USER);
+ uri = OUString::createFromAscii(USER_URI);
+ bAppendScriptsPart = true;
+ }
+ else if ( m_sLocation.equalsAscii(USER_UNO_PACKAGES))
+ {
+ test = OUString::createFromAscii("uno_packages");
+ uri = OUString::createFromAscii(USER_URI);
+ uri = uri.concat(OUString::createFromAscii(USER_UNO_PACKAGES_DIR));
+ }
+ else if (m_sLocation.equalsAscii(SHARE))
+ {
+ test = OUString::createFromAscii(SHARE);
+ uri = OUString::createFromAscii(SHARE_URI);
+ bAppendScriptsPart = true;
+ }
+ else if (m_sLocation.equalsAscii(SHARE_UNO_PACKAGES))
+ {
+ test = OUString::createFromAscii("uno_packages");
+ uri = OUString::createFromAscii(SHARE_UNO_PACKAGES_URI);
+ }
+ else if (m_sLocation.indexOf(OUString::createFromAscii(TDOC_SCHEME)) == 0)
+ {
+ m_sBaseURI = m_sLocation.concat( SCRIPTS_PART );
+ m_sLocation = OUString::createFromAscii( DOCUMENT );
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+
+ if ( !m_xSimpleFileAccess->exists( uri ) ||
+ !m_xSimpleFileAccess->isFolder( uri ) )
+ {
+ return false;
+ }
+
+ uno::Sequence< OUString > children =
+ m_xSimpleFileAccess->getFolderContents( uri, true );
+
+ for ( sal_Int32 i = 0; i < children.getLength(); i++ )
+ {
+ OUString child = children[i];
+ sal_Int32 idx = child.lastIndexOf(test);
+
+ // OSL_TRACE("Trying: %s", PRTSTR(child));
+ // OSL_TRACE("idx=%d, testlen=%d, children=%d",
+ // idx, test.getLength(), child.getLength());
+
+ if ( idx != -1 && (idx + test.getLength()) == child.getLength() )
+ {
+ // OSL_TRACE("FOUND PATH: %s", PRTSTR(child));
+ if ( bAppendScriptsPart )
+ {
+ m_sBaseURI = child.concat( SCRIPTS_PART );
+ }
+ else
+ {
+ m_sBaseURI = child;
+ }
+ return true;
+ }
+ }
+ return false;
+}
+
+OUString
+ScriptingFrameworkURIHelper::getLanguagePart(const OUString& rStorageURI)
+{
+ OUString result;
+
+ sal_Int32 idx = rStorageURI.indexOf(m_sBaseURI);
+ sal_Int32 len = m_sBaseURI.getLength() + 1;
+
+ if ( idx != -1 )
+ {
+ result = rStorageURI.copy(idx + len);
+ result = result.replace('/', '|');
+ }
+ return result;
+}
+
+OUString
+ScriptingFrameworkURIHelper::getLanguagePath(const OUString& rLanguagePart)
+{
+ OUString result;
+ result = rLanguagePart.replace('|', '/');
+ return result;
+}
+
+OUString SAL_CALL
+ScriptingFrameworkURIHelper::getScriptURI(const OUString& rStorageURI)
+ throw( lang::IllegalArgumentException, uno::RuntimeException )
+{
+ ::rtl::OUStringBuffer buf(120);
+
+ buf.appendAscii("vnd.sun.star.script:");
+ buf.append(getLanguagePart(rStorageURI));
+ buf.appendAscii("?language=");
+ buf.append(m_sLanguage);
+ buf.appendAscii("&location=");
+ buf.append(m_sLocation);
+
+ return buf.makeStringAndClear();
+}
+
+OUString SAL_CALL
+ScriptingFrameworkURIHelper::getStorageURI(const OUString& rScriptURI)
+ throw( lang::IllegalArgumentException, uno::RuntimeException )
+{
+ OUString sLanguagePart;
+ try
+ {
+ uno::Reference < uri::XVndSunStarScriptUrl > xURI(
+ m_xUriReferenceFactory->parse( rScriptURI ), uno::UNO_QUERY_THROW );
+ sLanguagePart = xURI->getName();
+ }
+ catch ( uno::Exception& )
+ {
+ throw lang::IllegalArgumentException(
+ OUString::createFromAscii( "Script URI not valid" ),
+ uno::Reference< uno::XInterface >(), 1 );
+ }
+
+ ::rtl::OUStringBuffer buf(120);
+ buf.append(m_sBaseURI);
+ buf.append(OUString::createFromAscii("/"));
+ buf.append(getLanguagePath(sLanguagePart));
+
+ OUString result = buf.makeStringAndClear();
+
+ return result;
+}
+
+OUString SAL_CALL
+ScriptingFrameworkURIHelper::getRootStorageURI()
+ throw( uno::RuntimeException )
+{
+ return m_sBaseURI;
+}
+
+OUString SAL_CALL
+ScriptingFrameworkURIHelper::getImplementationName()
+ throw( uno::RuntimeException )
+{
+ return OUString::createFromAscii(
+ "com.sun.star.script.provider.ScriptURIHelper" );
+}
+
+sal_Bool SAL_CALL
+ScriptingFrameworkURIHelper::supportsService( const OUString& serviceName )
+ throw( uno::RuntimeException )
+{
+ OUString m_sServiceName = OUString::createFromAscii(
+ "com.sun.star.script.provider.ScriptURIHelper" );
+
+ if ( serviceName.equals( m_sServiceName ) )
+ {
+ return sal_True;
+ }
+ return sal_False;
+}
+
+uno::Sequence< ::rtl::OUString > SAL_CALL
+ScriptingFrameworkURIHelper::getSupportedServiceNames()
+ throw( uno::RuntimeException )
+{
+ ::rtl::OUString serviceNameList[] = {
+ ::rtl::OUString::createFromAscii(
+ "com.sun.star.script.provider.ScriptURIHelper" ) };
+
+ uno::Sequence< ::rtl::OUString > serviceNames = uno::Sequence <
+ ::rtl::OUString > ( serviceNameList, 1 );
+
+ return serviceNames;
+}
+}
diff --git a/scripting/source/provider/URIHelper.hxx b/scripting/source/provider/URIHelper.hxx
new file mode 100644
index 000000000000..15d596448ad3
--- /dev/null
+++ b/scripting/source/provider/URIHelper.hxx
@@ -0,0 +1,111 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: URIHelper.hxx,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef _FRAMEWORK_SCRIPT_PROVIDER_XSCRIPTURIHELPER_HXX_
+#define _FRAMEWORK_SCRIPT_PROVIDER_XSCRIPTURIHELPER_HXX_
+
+#include <com/sun/star/script/provider/XScriptURIHelper.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XInitialization.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
+#include <com/sun/star/uri/XUriReferenceFactory.hpp>
+
+#include <rtl/ustring.hxx>
+#include <cppuhelper/implbase3.hxx>
+
+namespace func_provider
+{
+
+#define css ::com::sun::star
+
+class ScriptingFrameworkURIHelper :
+ public ::cppu::WeakImplHelper3<
+ css::script::provider::XScriptURIHelper,
+ css::lang::XServiceInfo,
+ css::lang::XInitialization >
+{
+private:
+
+ css::uno::Reference< css::ucb::XSimpleFileAccess > m_xSimpleFileAccess;
+ css::uno::Reference<css::uri::XUriReferenceFactory> m_xUriReferenceFactory;
+
+ ::rtl::OUString m_sLanguage;
+ ::rtl::OUString m_sLocation;
+ ::rtl::OUString m_sBaseURI;
+
+ ::rtl::OUString SCRIPTS_PART;
+
+ bool initBaseURI();
+ ::rtl::OUString getLanguagePart(const ::rtl::OUString& rStorageURI);
+ ::rtl::OUString getLanguagePath(const ::rtl::OUString& rLanguagePart);
+
+public:
+
+ ScriptingFrameworkURIHelper(
+ const css::uno::Reference< css::uno::XComponentContext >& xContext )
+ throw( css::uno::RuntimeException );
+
+ ~ScriptingFrameworkURIHelper();
+
+ virtual void SAL_CALL
+ initialize( const css::uno::Sequence < css::uno::Any > & args )
+ throw ( css::uno::Exception, css::uno::RuntimeException);
+
+ virtual ::rtl::OUString SAL_CALL
+ getRootStorageURI()
+ throw ( ::com::sun::star::uno::RuntimeException );
+
+ virtual ::rtl::OUString SAL_CALL
+ getScriptURI( const ::rtl::OUString& rStorageURI )
+ throw( css::lang::IllegalArgumentException,
+ css::uno::RuntimeException );
+
+ virtual ::rtl::OUString SAL_CALL
+ getStorageURI( const ::rtl::OUString& rScriptURI )
+ throw( css::lang::IllegalArgumentException,
+ css::uno::RuntimeException );
+
+ virtual ::rtl::OUString SAL_CALL
+ getImplementationName()
+ throw( css::uno::RuntimeException );
+
+ virtual sal_Bool SAL_CALL
+ supportsService( const ::rtl::OUString& ServiceName )
+ throw( css::uno::RuntimeException );
+
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL
+ getSupportedServiceNames()
+ throw( css::uno::RuntimeException );
+};
+
+} // namespace func_provider
+#endif //_FRAMEWORK_SCRIPT_PROVIDER_XSCRIPTURIHELPER_HXX_
diff --git a/scripting/source/provider/exports.dxp b/scripting/source/provider/exports.dxp
new file mode 100644
index 000000000000..9630d7e06768
--- /dev/null
+++ b/scripting/source/provider/exports.dxp
@@ -0,0 +1,3 @@
+component_getImplementationEnvironment
+component_writeInfo
+component_getFactory
diff --git a/scripting/source/provider/makefile.mk b/scripting/source/provider/makefile.mk
new file mode 100644
index 000000000000..44bae7783054
--- /dev/null
+++ b/scripting/source/provider/makefile.mk
@@ -0,0 +1,57 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.12 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+PRJ=..$/..
+
+PRJNAME= scripting
+TARGET= provider
+USE_DEFFILE= TRUE
+ENABLE_EXCEPTIONS=TRUE
+VISIBILITY_HIDDEN=TRUE
+COMP1TYPELIST=$(TARGET)
+
+# --- Settings -----------------------------------------------------
+
+.INCLUDE : settings.mk
+
+# ------------------------------------------------------------------
+
+SLOFILES=\
+ $(SLO)$/MasterScriptProvider.obj\
+ $(SLO)$/URIHelper.obj\
+ $(SLO)$/ActiveMSPList.obj\
+ $(SLO)$/ProviderCache.obj\
+ $(SLO)$/MasterScriptProviderFactory.obj\
+ $(SLO)$/BrowseNodeFactoryImpl.obj\
+
+
+# --- Targets ------------------------------------------------------
+
+.INCLUDE : target.mk
diff --git a/scripting/source/provider/provider.xml b/scripting/source/provider/provider.xml
new file mode 100755
index 000000000000..47127d879cd2
--- /dev/null
+++ b/scripting/source/provider/provider.xml
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE module-description PUBLIC "-//StarOffice//DTD ComponentDescription 1.0//EN" "module-description.dtd">
+<module-description xmlns:xlink="http://www.w3.org/1999/xlink">
+ <module-name> ScriptProvider </module-name>
+ <component-description>
+ <author> Noel Power</author>
+ <name> com.sun.star.script.provider.ScriptProvider </name>
+ <description>
+ This component is part of the Scripting Framework
+</description>
+ <loader-name> com.sun.star.loader.SharedLibrary </loader-name>
+ <language> c++ </language>
+ <status value="drafts"/>
+ <supported-service> com.sun.star.script.provider.ScriptProvider </supported-service>
+ <type> com.sun.star.beans.XPropertySet </type>
+ <type> com.sun.star.uno.Exception </type>
+ <type> com.sun.star.io.IOException </type>
+ <type> com.sun.star.io.XStream </type>
+ <type> com.sun.star.script.provider.XScript </type>
+ <type> com.sun.star.script.provider.XScriptProvider </type>
+ <type> com.sun.star.script.browse.XBrowseNode </type>
+ <type> com.sun.star.script.browse.BrowseNodeTypes </type>
+ <type> com.sun.star.uri.XUriReference </type>
+ <type> com.sun.star.uri.XUriReferenceFactory </type>
+ <type> com.sun.star.uri.XVndSunStarScriptUrl </type>
+
+ </component-description>
+ <project-build-dependency> cppuhelper </project-build-dependency>
+ <project-build-dependency> cppu </project-build-dependency>
+ <project-build-dependency> sal </project-build-dependency>
+ <runtime-module-dependency> cppuhelper2$(COM) </runtime-module-dependency>
+ <runtime-module-dependency> cppu2 </runtime-module-dependency>
+ <runtime-module-dependency> sal2 </runtime-module-dependency>
+</module-description>
diff --git a/scripting/source/pyprov/mailmerge.py b/scripting/source/pyprov/mailmerge.py
new file mode 100644
index 000000000000..75d2db533708
--- /dev/null
+++ b/scripting/source/pyprov/mailmerge.py
@@ -0,0 +1,353 @@
+# Caolan McNamara caolanm@redhat.com
+# a simple email mailmerge component
+
+# manual installation for hackers, not necessary for users
+# cp mailmerge.py /usr/lib/openoffice.org2.0/program
+# cd /usr/lib/openoffice.org2.0/program
+# ./unopkg add --shared mailmerge.py
+# edit ~/.openoffice.org2/user/registry/data/org/openoffice/Office/Writer.xcu
+# and change EMailSupported to as follows...
+# <prop oor:name="EMailSupported" oor:type="xs:boolean">
+# <value>true</value>
+# </prop>
+
+import unohelper
+import uno
+import re
+
+#to implement com::sun::star::mail::XMailServiceProvider
+
+from com.sun.star.mail import XMailServiceProvider
+from com.sun.star.mail import XMailService
+from com.sun.star.mail import XSmtpService
+from com.sun.star.mail import XConnectionListener
+from com.sun.star.mail import XAuthenticator
+from com.sun.star.mail import XMailMessage
+from com.sun.star.mail.MailServiceType import SMTP
+from com.sun.star.mail.MailServiceType import POP3
+from com.sun.star.mail.MailServiceType import IMAP
+from com.sun.star.uno import XCurrentContext
+from com.sun.star.lang import IllegalArgumentException
+from com.sun.star.lang import EventObject
+from com.sun.star.mail import SendMailMessageFailedException
+
+from email.MIMEBase import MIMEBase
+from email.Message import Message
+from email import Encoders
+from email.Header import Header
+from email.MIMEMultipart import MIMEMultipart
+from email.Utils import formatdate
+
+import sys, smtplib, imaplib, poplib
+
+dbg = False
+
+class PyMailSMTPService(unohelper.Base, XSmtpService):
+ def __init__( self, ctx ):
+ self.ctx = ctx
+ self.listeners = []
+ self.supportedtypes = ('Insecure', 'Ssl')
+ self.server = None
+ self.connectioncontext = None
+ self.notify = EventObject()
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService init"
+ def addConnectionListener(self, xListener):
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService addConnectionListener"
+ self.listeners.append(xListener)
+ def removeConnectionListener(self, xListener):
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService removeConnectionListener"
+ self.listeners.remove(xListener)
+ def getSupportedConnectionTypes(self):
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService getSupportedConnectionTypes"
+ return self.supportedtypes
+ def connect(self, xConnectionContext, xAuthenticator):
+ self.connectioncontext = xConnectionContext
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService connect"
+ server = xConnectionContext.getValueByName("ServerName")
+ if dbg:
+ print >> sys.stderr, server
+ port = xConnectionContext.getValueByName("Port")
+ if dbg:
+ print >> sys.stderr, port
+ self.server = smtplib.SMTP(server, port)
+ if dbg:
+ self.server.set_debuglevel(1)
+ connectiontype = xConnectionContext.getValueByName("ConnectionType")
+ if dbg:
+ print >> sys.stderr, connectiontype
+ if connectiontype == 'Ssl':
+ self.server.ehlo()
+ self.server.starttls()
+ self.server.ehlo()
+
+ user = xAuthenticator.getUserName()
+ password = xAuthenticator.getPassword()
+ if user != '':
+ if dbg:
+ print >> sys.stderr, 'Logging in, username of', user
+ self.server.login(user, password)
+
+ for listener in self.listeners:
+ listener.connected(self.notify)
+ def disconnect(self):
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService disconnect"
+ if self.server:
+ self.server.quit()
+ self.server = None
+ for listener in self.listeners:
+ listener.disconnected(self.notify)
+ def isConnected(self):
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService isConnected"
+ return self.server != None
+ def getCurrentConnectionContext(self):
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService getCurrentConnectionContext"
+ return self.connectioncontext
+ def sendMailMessage(self, xMailMessage):
+ COMMASPACE = ', '
+
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService sendMailMessage"
+ recipients = xMailMessage.getRecipients()
+ sendermail = xMailMessage.SenderAddress
+ sendername = xMailMessage.SenderName
+ subject = xMailMessage.Subject
+ ccrecipients = xMailMessage.getCcRecipients()
+ bccrecipients = xMailMessage.getBccRecipients()
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService subject", subject
+ print >> sys.stderr, "PyMailSMPTService from", sendername.encode('utf-8')
+ print >> sys.stderr, "PyMailSMTPService from", sendermail
+ print >> sys.stderr, "PyMailSMPTService send to", recipients
+
+ attachments = xMailMessage.getAttachments()
+
+ content = xMailMessage.Body
+ flavors = content.getTransferDataFlavors()
+ flavor = flavors[0]
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService mimetype is", flavor.MimeType
+ textbody = content.getTransferData(flavor)
+
+ textmsg = Message()
+ mimeEncoding = re.sub("charset=.*", "charset=UTF-8", flavor.MimeType)
+ textmsg['Content-Type'] = mimeEncoding
+ textmsg['MIME-Version'] = '1.0'
+ textmsg.set_payload(textbody.encode('utf-8'))
+
+ if (len(attachments)):
+ msg = MIMEMultipart()
+ msg.epilogue = ''
+ msg.attach(textmsg)
+ else:
+ msg = textmsg
+
+ hdr = Header(sendername, 'utf-8')
+ hdr.append('<'+sendermail+'>','us-ascii')
+ msg['Subject'] = subject
+ msg['From'] = hdr
+ msg['To'] = COMMASPACE.join(recipients)
+ if len(ccrecipients):
+ msg['Cc'] = COMMASPACE.join(ccrecipients)
+ if xMailMessage.ReplyToAddress != '':
+ msg['Reply-To'] = xMailMessage.ReplyToAddress
+ msg['X-Mailer'] = "OpenOffice.org 2.0 via Caolan's mailmerge component"
+
+ msg['Date'] = formatdate(localtime=True)
+
+ for attachment in attachments:
+ content = attachment.Data
+ flavors = content.getTransferDataFlavors()
+ flavor = flavors[0]
+ ctype = flavor.MimeType
+ maintype, subtype = ctype.split('/', 1)
+ msgattachment = MIMEBase(maintype, subtype)
+ data = content.getTransferData(flavor)
+ msgattachment.set_payload(data)
+ Encoders.encode_base64(msgattachment)
+ msgattachment.add_header('Content-Disposition', 'attachment', \
+ filename=attachment.ReadableName)
+ msg.attach(msgattachment)
+
+ uniquer = {}
+ for key in recipients:
+ uniquer[key] = True
+ if len(ccrecipients):
+ for key in ccrecipients:
+ uniquer[key] = True
+ if len(bccrecipients):
+ for key in bccrecipients:
+ uniquer[key] = True
+ truerecipients = uniquer.keys()
+
+ if dbg:
+ print >> sys.stderr, "PyMailSMPTService recipients are", truerecipients
+
+ self.server.sendmail(sendermail, truerecipients, msg.as_string())
+
+class PyMailIMAPService(unohelper.Base, XMailService):
+ def __init__( self, ctx ):
+ self.ctx = ctx
+ self.listeners = []
+ self.supportedtypes = ('Insecure', 'Ssl')
+ self.server = None
+ self.connectioncontext = None
+ if dbg:
+ print >> sys.stderr, "PyMailIMAPService init"
+ def addConnectionListener(self, xListener):
+ if dbg:
+ print >> sys.stderr, "PyMailIMAPService addConnectionListener"
+ self.listeners.append(xListener)
+ def removeConnectionListener(self, xListener):
+ if dbg:
+ print >> sys.stderr, "PyMailIMAPService removeConnectionListener"
+ self.listeners.remove(xListener)
+ def getSupportedConnectionTypes(self):
+ if dbg:
+ print >> sys.stderr, "PyMailIMAPService getSupportedConnectionTypes"
+ return self.supportedtypes
+ def connect(self, xConnectionContext, xAuthenticator):
+ if dbg:
+ print >> sys.stderr, "PyMailIMAPService connect"
+
+ self.connectioncontext = xConnectionContext
+ server = xConnectionContext.getValueByName("ServerName")
+ if dbg:
+ print >> sys.stderr, server
+ port = xConnectionContext.getValueByName("Port")
+ if dbg:
+ print >> sys.stderr, port
+ connectiontype = xConnectionContext.getValueByName("ConnectionType")
+ if dbg:
+ print >> sys.stderr, connectiontype
+ print >> sys.stderr, "BEFORE"
+ if connectiontype == 'Ssl':
+ self.server = imaplib.IMAP4_SSL(server, port)
+ else:
+ self.server = imaplib.IMAP4(server, port)
+ print >> sys.stderr, "AFTER"
+
+ user = xAuthenticator.getUserName()
+ password = xAuthenticator.getPassword()
+ if user != '':
+ if dbg:
+ print >> sys.stderr, 'Logging in, username of', user
+ self.server.login(user, password)
+
+ for listener in self.listeners:
+ listener.connected(self.notify)
+ def disconnect(self):
+ if dbg:
+ print >> sys.stderr, "PyMailIMAPService disconnect"
+ if self.server:
+ self.server.logout()
+ self.server = None
+ for listener in self.listeners:
+ listener.disconnected(self.notify)
+ def isConnected(self):
+ if dbg:
+ print >> sys.stderr, "PyMailIMAPService isConnected"
+ return self.server != None
+ def getCurrentConnectionContext(self):
+ if dbg:
+ print >> sys.stderr, "PyMailIMAPService getCurrentConnectionContext"
+ return self.connectioncontext
+
+class PyMailPOP3Service(unohelper.Base, XMailService):
+ def __init__( self, ctx ):
+ self.ctx = ctx
+ self.listeners = []
+ self.supportedtypes = ('Insecure', 'Ssl')
+ self.server = None
+ self.connectioncontext = None
+ if dbg:
+ print >> sys.stderr, "PyMailPOP3Service init"
+ def addConnectionListener(self, xListener):
+ if dbg:
+ print >> sys.stderr, "PyMailPOP3Service addConnectionListener"
+ self.listeners.append(xListener)
+ def removeConnectionListener(self, xListener):
+ if dbg:
+ print >> sys.stderr, "PyMailPOP3Service removeConnectionListener"
+ self.listeners.remove(xListener)
+ def getSupportedConnectionTypes(self):
+ if dbg:
+ print >> sys.stderr, "PyMailPOP3Service getSupportedConnectionTypes"
+ return self.supportedtypes
+ def connect(self, xConnectionContext, xAuthenticator):
+ if dbg:
+ print >> sys.stderr, "PyMailPOP3Service connect"
+
+ self.connectioncontext = xConnectionContext
+ server = xConnectionContext.getValueByName("ServerName")
+ if dbg:
+ print >> sys.stderr, server
+ port = xConnectionContext.getValueByName("Port")
+ if dbg:
+ print >> sys.stderr, port
+ connectiontype = xConnectionContext.getValueByName("ConnectionType")
+ if dbg:
+ print >> sys.stderr, connectiontype
+ print >> sys.stderr, "BEFORE"
+ if connectiontype == 'Ssl':
+ self.server = poplib.POP3_SSL(server, port)
+ else:
+ self.server = poplib.POP3(server, port)
+ print >> sys.stderr, "AFTER"
+
+ user = xAuthenticator.getUserName()
+ password = xAuthenticator.getPassword()
+ if dbg:
+ print >> sys.stderr, 'Logging in, username of', user
+ self.server.user(user)
+ self.server.pass_(user, password)
+
+ for listener in self.listeners:
+ listener.connected(self.notify)
+ def disconnect(self):
+ if dbg:
+ print >> sys.stderr, "PyMailPOP3Service disconnect"
+ if self.server:
+ self.server.quit()
+ self.server = None
+ for listener in self.listeners:
+ listener.disconnected(self.notify)
+ def isConnected(self):
+ if dbg:
+ print >> sys.stderr, "PyMailPOP3Service isConnected"
+ return self.server != None
+ def getCurrentConnectionContext(self):
+ if dbg:
+ print >> sys.stderr, "PyMailPOP3Service getCurrentConnectionContext"
+ return self.connectioncontext
+
+class PyMailServiceProvider(unohelper.Base, XMailServiceProvider):
+ def __init__( self, ctx ):
+ if dbg:
+ print >> sys.stderr, "PyMailServiceProvider init"
+ self.ctx = ctx
+ def create(self, aType):
+ if dbg:
+ print >> sys.stderr, "PyMailServiceProvider create with", aType
+ if aType == SMTP:
+ return PyMailSMTPService(self.ctx);
+ elif aType == POP3:
+ return PyMailPOP3Service(self.ctx);
+ elif aType == IMAP:
+ return PyMailIMAPService(self.ctx);
+ else:
+ print >> sys.stderr, "PyMailServiceProvider, unknown TYPE", aType
+
+# pythonloader looks for a static g_ImplementationHelper variable
+g_ImplementationHelper = unohelper.ImplementationHelper()
+g_ImplementationHelper.addImplementation( \
+ PyMailServiceProvider, "org.openoffice.pyuno.MailServiceProvider",
+ ("com.sun.star.mail.MailServiceProvider",),)
+
diff --git a/scripting/source/pyprov/makefile.mk b/scripting/source/pyprov/makefile.mk
new file mode 100644
index 000000000000..991d82248e65
--- /dev/null
+++ b/scripting/source/pyprov/makefile.mk
@@ -0,0 +1,53 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.10 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+PRJ=..$/..
+
+PRJNAME=scripting
+TARGET=pyprov
+
+# --- Settings -----------------------------------------------------
+
+.INCLUDE : settings.mk
+
+# ------------------------------------------------------------------
+
+
+# --- Targets ------------------------------------------------------
+ALL : ALLTAR \
+ $(DLLDEST)$/pythonscript.py \
+ $(DLLDEST)$/officehelper.py \
+ $(DLLDEST)$/mailmerge.py
+
+$(DLLDEST)$/%.py: %.py
+ cp $? $@
+
+.INCLUDE : target.mk
diff --git a/scripting/source/pyprov/officehelper.py b/scripting/source/pyprov/officehelper.py
new file mode 100644
index 000000000000..5e6bd1cd9409
--- /dev/null
+++ b/scripting/source/pyprov/officehelper.py
@@ -0,0 +1,97 @@
+### *************************************************************************
+### *
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: officehelper.py,v $
+#
+# $Revision: 1.3 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+### ************************************************************************/
+
+#
+# Translated to python from "Bootstrap.java" by Kim Kulak
+#
+
+import os
+import random
+from sys import platform
+from time import sleep
+
+import uno
+from com.sun.star.connection import NoConnectException
+from com.sun.star.uno import Exception as UnoException
+
+
+class BootstrapException(UnoException):
+ pass
+
+def bootstrap():
+ """Bootstrap OOo and PyUNO Runtime.
+ The soffice process is started opening a named pipe of random name, then the local context is used
+ to access the pipe. This function directly returns the remote component context, from whereon you can
+ get the ServiceManager by calling getServiceManager() on the returned object.
+ """
+ try:
+ # soffice script used on *ix, Mac; soffice.exe used on Windoof
+ if "UNO_PATH" in os.environ:
+ sOffice = os.environ["UNO_PATH"]
+ else:
+ sOffice = "" # lets hope for the best
+ sOffice = os.path.join(sOffice, "soffice")
+ if platform.startswith("win"):
+ sOffice += ".exe"
+
+ # Generate a random pipe name.
+ random.seed()
+ sPipeName = "uno" + str(random.random())[2:]
+
+ # Start the office proces, don't check for exit status since an exception is caught anyway if the office terminates unexpectedly.
+ cmdArray = (sOffice, "-nologo", "-nodefault", "".join(["-accept=pipe,name=", sPipeName, ";urp;"]))
+ os.spawnv(os.P_NOWAIT, sOffice, cmdArray)
+
+ # ---------
+
+ xLocalContext = uno.getComponentContext()
+ resolver = xLocalContext.ServiceManager.createInstanceWithContext(
+ "com.sun.star.bridge.UnoUrlResolver", xLocalContext)
+ sConnect = "".join(["uno:pipe,name=", sPipeName, ";urp;StarOffice.ComponentContext"])
+
+ # Wait until an office is started, but loop only nLoop times (can we do this better???)
+ nLoop = 20
+ while True:
+ try:
+ xContext = resolver.resolve(sConnect)
+ break
+ except NoConnectException:
+ nLoop -= 1
+ if nLoop <= 0:
+ raise BootstrapException("Cannot connect to soffice server.", None)
+ sleep(0.5) # Sleep 1/2 second.
+
+ except BootstrapException:
+ raise
+ except Exception, e: # Any other exception
+ raise BootstrapException("Caught exception " + str(e), None)
+
+ return xContext
diff --git a/scripting/source/pyprov/pythonscript.py b/scripting/source/pyprov/pythonscript.py
new file mode 100644
index 000000000000..6a57fa792873
--- /dev/null
+++ b/scripting/source/pyprov/pythonscript.py
@@ -0,0 +1,967 @@
+# XScript implementation for python
+import uno
+import unohelper
+import sys
+import os
+import imp
+import time
+
+class LogLevel:
+ NONE = 0
+ ERROR = 1
+ DEBUG = 2
+
+# Configuration ----------------------------------------------------
+LogLevel.use = LogLevel.NONE # production level
+#LogLevel.use = LogLevel.ERROR # for script developers
+#LogLevel.use = LogLevel.DEBUG # for script framework developers
+LOG_STDOUT = True # True, writes to stdout (difficult on windows)
+ # False, writes to user/Scripts/python/log.txt
+ENABLE_EDIT_DIALOG=False # offers a minimal editor for editing.
+#-------------------------------------------------------------------
+
+def encfile(uni):
+ return uni.encode( sys.getfilesystemencoding())
+
+def lastException2String():
+ (excType,excInstance,excTraceback) = sys.exc_info()
+ ret = str(excType) + ": "+str(excInstance) + "\n" + \
+ uno._uno_extract_printable_stacktrace( excTraceback )
+ return ret
+
+def logLevel2String( level ):
+ ret = " NONE"
+ if level == LogLevel.ERROR:
+ ret = "ERROR"
+ elif level >= LogLevel.DEBUG:
+ ret = "DEBUG"
+ return ret
+
+def getLogTarget():
+ ret = sys.stdout
+ if not LOG_STDOUT:
+ try:
+ pathSubst = uno.getComponentContext().ServiceManager.createInstance(
+ "com.sun.star.util.PathSubstitution" )
+ userInstallation = pathSubst.getSubstituteVariableValue( "user" )
+ if len( userInstallation ) > 0:
+ systemPath = uno.fileUrlToSystemPath( userInstallation + "/Scripts/python/log.txt" )
+ ret = file( systemPath , "a" )
+ except Exception,e:
+ print "Exception during creation of pythonscript logfile: "+ lastException2String() + "\n, delagating log to stdout\n"
+ return ret
+
+class Logger(LogLevel):
+ def __init__(self , target ):
+ self.target = target
+
+ def isDebugLevel( self ):
+ return self.use >= self.DEBUG
+
+ def debug( self, msg ):
+ if self.isDebugLevel():
+ self.log( self.DEBUG, msg )
+
+ def isErrorLevel( self ):
+ return self.use >= self.ERROR
+
+ def error( self, msg ):
+ if self.isErrorLevel():
+ self.log( self.ERROR, msg )
+
+ def log( self, level, msg ):
+ if self.use >= level:
+ try:
+ self.target.write(
+ time.asctime() +
+ " [" +
+ logLevel2String( level ) +
+ "] " +
+ encfile(msg) +
+ "\n" )
+ self.target.flush()
+ except Exception,e:
+ print "Error during writing to stdout: " +lastException2String() + "\n"
+
+log = Logger( getLogTarget() )
+
+log.debug( "pythonscript loading" )
+
+#from com.sun.star.lang import typeOfXServiceInfo, typeOfXTypeProvider
+from com.sun.star.uno import RuntimeException
+from com.sun.star.lang import XServiceInfo
+from com.sun.star.io import IOException
+from com.sun.star.ucb import CommandAbortedException, XCommandEnvironment, XProgressHandler
+from com.sun.star.task import XInteractionHandler
+from com.sun.star.beans import XPropertySet
+from com.sun.star.container import XNameContainer
+from com.sun.star.xml.sax import XDocumentHandler, InputSource
+from com.sun.star.uno import Exception as UnoException
+from com.sun.star.script import XInvocation
+from com.sun.star.awt import XActionListener
+
+from com.sun.star.script.provider import XScriptProvider, XScript, XScriptContext, ScriptFrameworkErrorException
+from com.sun.star.script.browse import XBrowseNode
+from com.sun.star.script.browse.BrowseNodeTypes import SCRIPT, CONTAINER, ROOT
+from com.sun.star.util import XModifyListener
+
+LANGUAGENAME = "Python"
+GLOBAL_SCRIPTCONTEXT_NAME = "XSCRIPTCONTEXT"
+CALLABLE_CONTAINER_NAME = "g_exportedScripts"
+
+# pythonloader looks for a static g_ImplementationHelper variable
+g_ImplementationHelper = unohelper.ImplementationHelper()
+g_implName = "org.openoffice.pyuno.LanguageScriptProviderFor"+LANGUAGENAME
+
+
+
+BLOCK_SIZE = 65536
+def readTextFromStream( inputStream ):
+ # read the file
+ code = uno.ByteSequence( "" )
+ while True:
+ read,out = inputStream.readBytes( None , BLOCK_SIZE )
+ code = code + out
+ if read < BLOCK_SIZE:
+ break
+ return code.value
+
+def toIniName( str ):
+ # TODO: what is the official way to get to know whether i am on the windows platform ?
+ if( hasattr(sys , "dllhandle") ):
+ return str + ".ini"
+ return str + "rc"
+
+
+""" definition: storageURI is the system dependent, absolute file url, where the script is stored on disk
+ scriptURI is the system independent uri
+"""
+class MyUriHelper:
+
+ def __init__( self, ctx, location ):
+ self.s_UriMap = \
+ { "share" : "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" + toIniName( "bootstrap") + "::BaseInstallation}/share/Scripts/python" , \
+ "share:uno_packages" : "vnd.sun.star.expand:$UNO_SHARED_PACKAGES_CACHE/uno_packages", \
+ "user" : "vnd.sun.star.expand:${$BRAND_BASE_DIR/program/" + toIniName( "bootstrap") + "::UserInstallation}/user/Scripts/python" , \
+ "user:uno_packages" : "vnd.sun.star.expand:$UNO_USER_PACKAGES_CACHE/uno_packages" }
+ self.m_uriRefFac = ctx.ServiceManager.createInstanceWithContext("com.sun.star.uri.UriReferenceFactory",ctx)
+ if location.startswith( "vnd.sun.star.tdoc" ):
+ self.m_baseUri = location + "/Scripts/python"
+ self.m_scriptUriLocation = "document"
+ else:
+ self.m_baseUri = expandUri( self.s_UriMap[location] )
+ self.m_scriptUriLocation = location
+ log.isDebugLevel() and log.debug( "initialized urihelper with baseUri="+self.m_baseUri + ",m_scriptUriLocation="+self.m_scriptUriLocation )
+
+ def getRootStorageURI( self ):
+ return self.m_baseUri
+
+ def getStorageURI( self, scriptURI ):
+ return self.scriptURI2StorageUri(scriptURI)
+
+ def getScriptURI( self, storageURI ):
+ return self.storageURI2ScriptUri(storageURI)
+
+ def storageURI2ScriptUri( self, storageURI ):
+ if not storageURI.startswith( self.m_baseUri ):
+ message = "pythonscript: storage uri '" + storageURI + "' not in base uri '" + self.m_baseUri + "'"
+ log.isDebugLevel() and log.debug( message )
+ raise RuntimeException( message )
+
+ ret = "vnd.sun.star.script:" + \
+ storageURI[len(self.m_baseUri)+1:].replace("/","|") + \
+ "?language=" + LANGUAGENAME + "&location=" + self.m_scriptUriLocation
+ log.isDebugLevel() and log.debug( "converting storageURI="+storageURI + " to scriptURI=" + ret )
+ return ret
+
+ def scriptURI2StorageUri( self, scriptURI ):
+ try:
+ myUri = self.m_uriRefFac.parse(scriptURI)
+ ret = self.m_baseUri + "/" + myUri.getName().replace( "|", "/" )
+ log.isDebugLevel() and log.debug( "converting scriptURI="+scriptURI + " to storageURI=" + ret )
+ return ret
+ except UnoException, e:
+ log.error( "error during converting scriptURI="+scriptURI + ": " + e.Message)
+ raise RuntimeException( "pythonscript:scriptURI2StorageUri: " +e.getMessage(), None )
+ except Exception, e:
+ log.error( "error during converting scriptURI="+scriptURI + ": " + str(e))
+ raise RuntimeException( "pythonscript:scriptURI2StorageUri: " + str(e), None )
+
+
+class ModuleEntry:
+ def __init__( self, lastRead, module ):
+ self.lastRead = lastRead
+ self.module = module
+
+def hasChanged( oldDate, newDate ):
+ return newDate.Year > oldDate.Year or \
+ newDate.Month > oldDate.Month or \
+ newDate.Day > oldDate.Day or \
+ newDate.Hours > oldDate.Hours or \
+ newDate.Minutes > oldDate.Minutes or \
+ newDate.Seconds > oldDate.Seconds or \
+ newDate.HundredthSeconds > oldDate.HundredthSeconds
+
+def ensureSourceState( code ):
+ if not code.endswith( "\n" ):
+ code = code + "\n"
+ code = code.replace( "\r", "" )
+ return code
+
+
+def checkForPythonPathBesideScript( url ):
+ if url.startswith( "file:" ):
+ path = unohelper.fileUrlToSystemPath( url+"/pythonpath.zip" );
+ log.log( LogLevel.DEBUG, "checking for existence of " + path )
+ if 1 == os.access( encfile(path), os.F_OK) and not path in sys.path:
+ log.log( LogLevel.DEBUG, "adding " + path + " to sys.path" )
+ sys.path.append( path )
+
+ path = unohelper.fileUrlToSystemPath( url+"/pythonpath" );
+ log.log( LogLevel.DEBUG, "checking for existence of " + path )
+ if 1 == os.access( encfile(path), os.F_OK) and not path in sys.path:
+ log.log( LogLevel.DEBUG, "adding " + path + " to sys.path" )
+ sys.path.append( path )
+
+
+class ScriptContext(unohelper.Base):
+ def __init__( self, ctx, doc ):
+ self.ctx = ctx
+ self.doc = doc
+
+ # XScriptContext
+ def getDocument(self):
+ return self.getDesktop().getCurrentComponent()
+
+ def getDesktop(self):
+ return self.ctx.ServiceManager.createInstanceWithContext(
+ "com.sun.star.frame.Desktop", self.ctx )
+
+ def getComponentContext(self):
+ return self.ctx
+
+#----------------------------------
+# Global Module Administration
+# does not fit together with script
+# engine lifetime management
+#----------------------------------
+#g_scriptContext = ScriptContext( uno.getComponentContext(), None )
+#g_modules = {}
+#def getModuleByUrl( url, sfa ):
+# entry = g_modules.get(url)
+# load = True
+# lastRead = sfa.getDateTimeModified( url )
+# if entry:
+# if hasChanged( entry.lastRead, lastRead ):
+# log.isDebugLevel() and log.debug("file " + url + " has changed, reloading")
+# else:
+# load = False
+#
+# if load:
+# log.isDebugLevel() and log.debug( "opening >" + url + "<" )
+#
+# code = readTextFromStream( sfa.openFileRead( url ) )
+
+ # execute the module
+# entry = ModuleEntry( lastRead, imp.new_module("ooo_script_framework") )
+# entry.module.__dict__[GLOBAL_SCRIPTCONTEXT_NAME] = g_scriptContext
+# entry.module.__file__ = url
+# exec code in entry.module.__dict__
+# g_modules[ url ] = entry
+# log.isDebugLevel() and log.debug( "mapped " + url + " to " + str( entry.module ) )
+# return entry.module
+
+class ProviderContext:
+ def __init__( self, storageType, sfa, uriHelper, scriptContext ):
+ self.storageType = storageType
+ self.sfa = sfa
+ self.uriHelper = uriHelper
+ self.scriptContext = scriptContext
+ self.modules = {}
+ self.rootUrl = None
+ self.mapPackageName2Path = None
+
+ def getTransientPartFromUrl( self, url ):
+ rest = url.replace( self.rootUrl , "",1 ).replace( "/","",1)
+ return rest[0:rest.find("/")]
+
+ def getPackageNameFromUrl( self, url ):
+ rest = url.replace( self.rootUrl , "",1 ).replace( "/","",1)
+ start = rest.find("/") +1
+ return rest[start:rest.find("/",start)]
+
+
+ def removePackageByUrl( self, url ):
+ items = self.mapPackageName2Path.items()
+ for i in items:
+ if url in i[1].pathes:
+ self.mapPackageName2Path.pop(i[0])
+ break
+
+ def addPackageByUrl( self, url ):
+ packageName = self.getPackageNameFromUrl( url )
+ transientPart = self.getTransientPartFromUrl( url )
+ log.isDebugLevel() and log.debug( "addPackageByUrl : " + packageName + ", " + transientPart + "("+url+")" + ", rootUrl="+self.rootUrl )
+ if self.mapPackageName2Path.has_key( packageName ):
+ package = self.mapPackageName2Path[ packageName ]
+ package.pathes = package.pathes + (url, )
+ else:
+ package = Package( (url,), transientPart)
+ self.mapPackageName2Path[ packageName ] = package
+
+ def isUrlInPackage( self, url ):
+ values = self.mapPackageName2Path.values()
+ for i in values:
+# print "checking " + url + " in " + str(i.pathes)
+ if url in i.pathes:
+ return True
+# print "false"
+ return False
+
+ def setPackageAttributes( self, mapPackageName2Path, rootUrl ):
+ self.mapPackageName2Path = mapPackageName2Path
+ self.rootUrl = rootUrl
+
+ def getPersistentUrlFromStorageUrl( self, url ):
+ # package name is the second directory
+ ret = url
+ if self.rootUrl:
+ pos = len( self.rootUrl) +1
+ ret = url[0:pos]+url[url.find("/",pos)+1:len(url)]
+ log.isDebugLevel() and log.debug( "getPersistentUrlFromStorageUrl " + url + " -> "+ ret)
+ return ret
+
+ def getStorageUrlFromPersistentUrl( self, url):
+ ret = url
+ if self.rootUrl:
+ pos = len(self.rootUrl)+1
+ packageName = url[pos:url.find("/",pos+1)]
+ package = self.mapPackageName2Path[ packageName ]
+ ret = url[0:pos]+ package.transientPathElement + "/" + url[pos:len(url)]
+ log.isDebugLevel() and log.debug( "getStorageUrlFromPersistentUrl " + url + " -> "+ ret)
+ return ret
+
+ def getModuleByUrl( self, url ):
+ entry = self.modules.get(url)
+ load = True
+ lastRead = self.sfa.getDateTimeModified( url )
+ if entry:
+ if hasChanged( entry.lastRead, lastRead ):
+ log.isDebugLevel() and log.debug( "file " + url + " has changed, reloading" )
+ else:
+ load = False
+
+ if load:
+ log.isDebugLevel() and log.debug( "opening >" + url + "<" )
+
+ src = readTextFromStream( self.sfa.openFileRead( url ) )
+ checkForPythonPathBesideScript( url[0:url.rfind('/')] )
+ src = ensureSourceState( src )
+
+ # execute the module
+ entry = ModuleEntry( lastRead, imp.new_module("ooo_script_framework") )
+ entry.module.__dict__[GLOBAL_SCRIPTCONTEXT_NAME] = self.scriptContext
+
+ code = None
+ if url.startswith( "file:" ):
+ code = compile( src, encfile(uno.fileUrlToSystemPath( url ) ), "exec" )
+ else:
+ code = compile( src, url, "exec" )
+ exec code in entry.module.__dict__
+ entry.module.__file__ = url
+ self.modules[ url ] = entry
+ log.isDebugLevel() and log.debug( "mapped " + url + " to " + str( entry.module ) )
+ return entry.module
+
+#--------------------------------------------------
+def isScript( candidate ):
+ ret = False
+ if isinstance( candidate, type(isScript) ):
+ ret = True
+ return ret
+
+#-------------------------------------------------------
+class ScriptBrowseNode( unohelper.Base, XBrowseNode , XPropertySet, XInvocation, XActionListener ):
+ def __init__( self, provCtx, uri, fileName, funcName, func ):
+ self.fileName = fileName
+ self.funcName = funcName
+ self.provCtx = provCtx
+ self.func = func
+ self.uri = uri
+
+ def getName( self ):
+ return self.funcName
+
+ def getChildNodes(self):
+ return ()
+
+ def hasChildNodes(self):
+ return False
+
+ def getType( self):
+ return SCRIPT
+
+ def getPropertyValue( self, name ):
+ ret = None
+ try:
+ if name == "URI":
+ ret = self.provCtx.uriHelper.getScriptURI(
+ self.provCtx.getPersistentUrlFromStorageUrl( self.uri + "$" + self.funcName ) )
+ elif name == "Description":
+ ret = getattr( self.func, "__doc__", None )
+ elif name == "Editable" and ENABLE_EDIT_DIALOG:
+ ret = not self.provCtx.sfa.isReadOnly( self.uri )
+
+ log.isDebugLevel() and log.debug( "ScriptBrowseNode.getPropertyValue called for " + name + ", returning " + str(ret) )
+ except Exception,e:
+ log.error( "ScriptBrowseNode.getPropertyValue error " + lastException2String())
+ raise
+
+ return ret
+ def setPropertyValue( self, name, value ):
+ log.isDebugLevel() and log.debug( "ScriptBrowseNode.setPropertyValue called " + name + "=" +str(value ) )
+ def getPropertySetInfo( self ):
+ log.isDebugLevel() and log.debug( "ScriptBrowseNode.getPropertySetInfo called " )
+ return None
+
+ def getIntrospection( self ):
+ return None
+
+ def invoke( self, name, params, outparamindex, outparams ):
+ if name == "Editable":
+ servicename = "com.sun.star.awt.DialogProvider"
+ ctx = self.provCtx.scriptContext.getComponentContext()
+ dlgprov = ctx.ServiceManager.createInstanceWithContext(
+ servicename, ctx )
+
+ self.editor = dlgprov.createDialog(
+ "vnd.sun.star.script:" +
+ "ScriptBindingLibrary.MacroEditor?location=application")
+
+ code = readTextFromStream(self.provCtx.sfa.openFileRead(self.uri))
+ code = ensureSourceState( code )
+ self.editor.getControl("EditorTextField").setText(code)
+
+ self.editor.getControl("RunButton").setActionCommand("Run")
+ self.editor.getControl("RunButton").addActionListener(self)
+ self.editor.getControl("SaveButton").setActionCommand("Save")
+ self.editor.getControl("SaveButton").addActionListener(self)
+
+ self.editor.execute()
+
+ return None
+
+ def actionPerformed( self, event ):
+ try:
+ if event.ActionCommand == "Run":
+ code = self.editor.getControl("EditorTextField").getText()
+ code = ensureSourceState( code )
+ mod = imp.new_module("ooo_script_framework")
+ mod.__dict__[GLOBAL_SCRIPTCONTEXT_NAME] = self.provCtx.scriptContext
+ exec code in mod.__dict__
+ values = mod.__dict__.get( CALLABLE_CONTAINER_NAME , None )
+ if not values:
+ values = mod.__dict__.values()
+
+ for i in values:
+ if isScript( i ):
+ i()
+ break
+
+ elif event.ActionCommand == "Save":
+ toWrite = uno.ByteSequence(
+ str(
+ self.editor.getControl("EditorTextField").getText().encode(
+ sys.getdefaultencoding())) )
+ copyUrl = self.uri + ".orig"
+ self.provCtx.sfa.move( self.uri, copyUrl )
+ out = self.provCtx.sfa.openFileWrite( self.uri )
+ out.writeBytes( toWrite )
+ out.close()
+ self.provCtx.sfa.kill( copyUrl )
+# log.isDebugLevel() and log.debug("Save is not implemented yet")
+# text = self.editor.getControl("EditorTextField").getText()
+# log.isDebugLevel() and log.debug("Would save: " + text)
+ except Exception,e:
+ # TODO: add an error box here !
+ log.error( lastException2String() )
+
+
+ def setValue( self, name, value ):
+ return None
+
+ def getValue( self, name ):
+ return None
+
+ def hasMethod( self, name ):
+ return False
+
+ def hasProperty( self, name ):
+ return False
+
+
+#-------------------------------------------------------
+class FileBrowseNode( unohelper.Base, XBrowseNode ):
+ def __init__( self, provCtx, uri , name ):
+ self.provCtx = provCtx
+ self.uri = uri
+ self.name = name
+ self.module = None
+
+ def getName( self ):
+ return self.name
+
+ def getChildNodes(self):
+ ret = ()
+ try:
+ self.module = self.provCtx.getModuleByUrl( self.uri )
+ values = self.module.__dict__.get( CALLABLE_CONTAINER_NAME , None )
+
+ # no g_exportedScripts, export every function
+ if not isinstance(values, type(())):
+ values = self.module.__dict__.values()
+
+ scriptNodeList = []
+ for i in values:
+ if isScript( i ):
+ scriptNodeList.append(
+ ScriptBrowseNode(
+ self.provCtx, self.uri, self.name, i.__name__, i ))
+ ret = tuple( scriptNodeList )
+ # must compile !
+ log.isDebugLevel() and log.debug( "returning " +str(len(ret)) + " ScriptChildNodes on " + self.uri )
+ except Exception, e:
+ text = lastException2String()
+ log.error( "Error while evaluating " + self.uri + ":" + text )
+ raise
+ return ret
+
+ def hasChildNodes(self):
+ try:
+ return len(self.getChildNodes()) > 0
+ except Exception, e:
+ return False
+
+ def getType( self):
+ return CONTAINER
+
+
+
+class DirBrowseNode( unohelper.Base, XBrowseNode ):
+ def __init__( self, provCtx, name, rootUrl ):
+ self.provCtx = provCtx
+ self.name = name
+ self.rootUrl = rootUrl
+
+ def getName( self ):
+ return self.name
+
+ def getChildNodes( self ):
+ try:
+ log.isDebugLevel() and log.debug( "DirBrowseNode.getChildNodes called for " + self.rootUrl )
+ contents = self.provCtx.sfa.getFolderContents( self.rootUrl, True )
+ browseNodeList = []
+ for i in contents:
+ if i.endswith( ".py" ):
+ log.isDebugLevel() and log.debug( "adding filenode " + i )
+ browseNodeList.append(
+ FileBrowseNode( self.provCtx, i, i[i.rfind("/")+1:len(i)-3] ) )
+ elif self.provCtx.sfa.isFolder( i ) and not i.endswith("/pythonpath"):
+ log.isDebugLevel() and log.debug( "adding DirBrowseNode " + i )
+ browseNodeList.append( DirBrowseNode( self.provCtx, i[i.rfind("/")+1:len(i)],i))
+ return tuple( browseNodeList )
+ except Exception, e:
+ text = lastException2String()
+ log.error( "DirBrowseNode error: " + str(e) + " while evaluating " + self.rootUrl)
+ log.error( text)
+ return ()
+
+ def hasChildNodes( self ):
+ return True
+
+ def getType( self ):
+ return CONTAINER
+
+ def getScript( self, uri ):
+ log.debug( "DirBrowseNode getScript " + uri + " invoked" )
+ raise IllegalArgumentException( "DirBrowseNode couldn't instantiate script " + uri , self , 0 )
+
+
+class ManifestHandler( XDocumentHandler, unohelper.Base ):
+ def __init__( self, rootUrl ):
+ self.rootUrl = rootUrl
+
+ def startDocument( self ):
+ self.urlList = []
+
+ def endDocument( self ):
+ pass
+
+ def startElement( self , name, attlist):
+ if name == "manifest:file-entry":
+ if attlist.getValueByName( "manifest:media-type" ) == "application/vnd.sun.star.framework-script":
+ self.urlList.append(
+ self.rootUrl + "/" + attlist.getValueByName( "manifest:full-path" ) )
+
+ def endElement( self, name ):
+ pass
+
+ def characters ( self, chars ):
+ pass
+
+ def ignoreableWhitespace( self, chars ):
+ pass
+
+ def setDocumentLocator( self, locator ):
+ pass
+
+def isPyFileInPath( sfa, path ):
+ ret = False
+ contents = sfa.getFolderContents( path, True )
+ for i in contents:
+ if sfa.isFolder(i):
+ ret = isPyFileInPath(sfa,i)
+ else:
+ if i.endswith(".py"):
+ ret = True
+ if ret:
+ break
+ return ret
+
+# extracts META-INF directory from
+def getPathesFromPackage( rootUrl, sfa ):
+ ret = ()
+ try:
+ fileUrl = rootUrl + "/META-INF/manifest.xml"
+ inputStream = sfa.openFileRead( fileUrl )
+ parser = uno.getComponentContext().ServiceManager.createInstance( "com.sun.star.xml.sax.Parser" )
+ handler = ManifestHandler( rootUrl )
+ parser.setDocumentHandler( handler )
+ parser.parseStream( InputSource( inputStream , "", fileUrl, fileUrl ) )
+ for i in tuple(handler.urlList):
+ if not isPyFileInPath( sfa, i ):
+ handler.urlList.remove(i)
+ ret = tuple( handler.urlList )
+ except UnoException, e:
+ text = lastException2String()
+ log.debug( "getPathesFromPackage " + fileUrl + " Exception: " +text )
+ pass
+ return ret
+
+
+class Package:
+ def __init__( self, pathes, transientPathElement ):
+ self.pathes = pathes
+ self.transientPathElement = transientPathElement
+
+class DummyInteractionHandler( unohelper.Base, XInteractionHandler ):
+ def __init__( self ):
+ pass
+ def handle( self, event):
+ log.isDebugLevel() and log.debug( "pythonscript: DummyInteractionHandler.handle " + str( event ) )
+
+class DummyProgressHandler( unohelper.Base, XProgressHandler ):
+ def __init__( self ):
+ pass
+
+ def push( self,status ):
+ log.isDebugLevel() and log.debug( "pythonscript: DummyProgressHandler.push " + str( status ) )
+ def update( self,status ):
+ log.isDebugLevel() and log.debug( "pythonscript: DummyProgressHandler.update " + str( status ) )
+ def pop( self ):
+ log.isDebugLevel() and log.debug( "pythonscript: DummyProgressHandler.push " + str( event ) )
+
+class CommandEnvironment(unohelper.Base, XCommandEnvironment):
+ def __init__( self ):
+ self.progressHandler = DummyProgressHandler()
+ self.interactionHandler = DummyInteractionHandler()
+ def getInteractionHandler( self ):
+ return self.interactionHandler
+ def getProgressHandler( self ):
+ return self.progressHandler
+
+#maybe useful for debugging purposes
+#class ModifyListener( unohelper.Base, XModifyListener ):
+# def __init__( self ):
+# pass
+# def modified( self, event ):
+# log.isDebugLevel() and log.debug( "pythonscript: ModifyListener.modified " + str( event ) )
+# def disposing( self, event ):
+# log.isDebugLevel() and log.debug( "pythonscript: ModifyListener.disposing " + str( event ) )
+
+def mapStorageType2PackageContext( storageType ):
+ ret = storageType
+ if( storageType == "share:uno_packages" ):
+ ret = "shared"
+ if( storageType == "user:uno_packages" ):
+ ret = "user"
+ return ret
+
+def getPackageName2PathMap( sfa, storageType ):
+ ret = {}
+ packageManagerFactory = uno.getComponentContext().getValueByName(
+ "/singletons/com.sun.star.deployment.thePackageManagerFactory" )
+ packageManager = packageManagerFactory.getPackageManager(
+ mapStorageType2PackageContext(storageType))
+# packageManager.addModifyListener( ModifyListener() )
+ log.isDebugLevel() and log.debug( "pythonscript: getPackageName2PathMap start getDeployedPackages" )
+ packages = packageManager.getDeployedPackages(
+ packageManager.createAbortChannel(), CommandEnvironment( ) )
+ log.isDebugLevel() and log.debug( "pythonscript: getPackageName2PathMap end getDeployedPackages (" + str(len(packages))+")" )
+
+ for i in packages:
+ log.isDebugLevel() and log.debug( "inspecting package " + i.Name + "("+i.Identifier.Value+")" )
+ transientPathElement = penultimateElement( i.URL )
+ j = expandUri( i.URL )
+ pathes = getPathesFromPackage( j, sfa )
+ if len( pathes ) > 0:
+ # map package name to url, we need this later
+ log.isErrorLevel() and log.error( "adding Package " + transientPathElement + " " + str( pathes ) )
+ ret[ lastElement( j ) ] = Package( pathes, transientPathElement )
+ return ret
+
+def penultimateElement( aStr ):
+ lastSlash = aStr.rindex("/")
+ penultimateSlash = aStr.rindex("/",0,lastSlash-1)
+ return aStr[ penultimateSlash+1:lastSlash ]
+
+def lastElement( aStr):
+ return aStr[ aStr.rfind( "/" )+1:len(aStr)]
+
+class PackageBrowseNode( unohelper.Base, XBrowseNode ):
+ def __init__( self, provCtx, name, rootUrl ):
+ self.provCtx = provCtx
+ self.name = name
+ self.rootUrl = rootUrl
+
+ def getName( self ):
+ return self.name
+
+ def getChildNodes( self ):
+ items = self.provCtx.mapPackageName2Path.items()
+ browseNodeList = []
+ for i in items:
+ if len( i[1].pathes ) == 1:
+ browseNodeList.append(
+ DirBrowseNode( self.provCtx, i[0], i[1].pathes[0] ))
+ else:
+ for j in i[1].pathes:
+ browseNodeList.append(
+ DirBrowseNode( self.provCtx, i[0]+"."+lastElement(j), j ) )
+ return tuple( browseNodeList )
+
+ def hasChildNodes( self ):
+ return len( self.mapPackageName2Path ) > 0
+
+ def getType( self ):
+ return CONTAINER
+
+ def getScript( self, uri ):
+ log.debug( "DirBrowseNode getScript " + uri + " invoked" )
+ raise IllegalArgumentException( "PackageBrowseNode couldn't instantiate script " + uri , self , 0 )
+
+
+
+
+class PythonScript( unohelper.Base, XScript ):
+ def __init__( self, func, mod ):
+ self.func = func
+ self.mod = mod
+ def invoke(self, args, out, outindex ):
+ log.isDebugLevel() and log.debug( "PythonScript.invoke " + str( args ) )
+ try:
+ ret = self.func( *args )
+ except UnoException,e:
+ # UNO Exception continue to fly ...
+ text = lastException2String()
+ complete = "Error during invoking function " + \
+ str(self.func.__name__) + " in module " + \
+ self.mod.__file__ + " (" + text + ")"
+ log.isDebugLevel() and log.debug( complete )
+ # some people may beat me up for modifying the exception text,
+ # but otherwise office just shows
+ # the type name and message text with no more information,
+ # this is really bad for most users.
+ e.Message = e.Message + " (" + complete + ")"
+ raise
+ except Exception,e:
+ # General python exception are converted to uno RuntimeException
+ text = lastException2String()
+ complete = "Error during invoking function " + \
+ str(self.func.__name__) + " in module " + \
+ self.mod.__file__ + " (" + text + ")"
+ log.isDebugLevel() and log.debug( complete )
+ raise RuntimeException( complete , self )
+ log.isDebugLevel() and log.debug( "PythonScript.invoke ret = " + str( ret ) )
+ return ret, (), ()
+
+def expandUri( uri ):
+ if uri.startswith( "vnd.sun.star.expand:" ):
+ uri = uri.replace( "vnd.sun.star.expand:", "",1)
+ uri = uno.getComponentContext().getByName(
+ "/singletons/com.sun.star.util.theMacroExpander" ).expandMacros( uri )
+ if uri.startswith( "file:" ):
+ uri = uno.absolutize("",uri) # necessary to get rid of .. in uri
+ return uri
+
+#--------------------------------------------------------------
+class PythonScriptProvider( unohelper.Base, XBrowseNode, XScriptProvider, XNameContainer):
+ def __init__( self, ctx, *args ):
+ if log.isDebugLevel():
+ mystr = ""
+ for i in args:
+ if len(mystr) > 0:
+ mystr = mystr +","
+ mystr = mystr + str(i)
+ log.debug( "Entering PythonScriptProvider.ctor" + mystr )
+
+ storageType = ""
+ if isinstance(args[0],unicode ):
+ storageType = args[0]
+ else:
+ storageType = args[0].SCRIPTING_DOC_URI
+ isPackage = storageType.endswith( ":uno_packages" )
+
+ try:
+# urlHelper = ctx.ServiceManager.createInstanceWithArgumentsAndContext(
+# "com.sun.star.script.provider.ScriptURIHelper", (LANGUAGENAME, storageType), ctx)
+ urlHelper = MyUriHelper( ctx, storageType )
+ log.isDebugLevel() and log.debug( "got urlHelper " + str( urlHelper ) )
+
+ rootUrl = expandUri( urlHelper.getRootStorageURI() )
+ log.isDebugLevel() and log.debug( storageType + " transformed to " + rootUrl )
+
+ ucbService = "com.sun.star.ucb.SimpleFileAccess"
+ sfa = ctx.ServiceManager.createInstanceWithContext( ucbService, ctx )
+ if not sfa:
+ log.debug("PythonScriptProvider couldn't instantiate " +ucbService)
+ raise RuntimeException(
+ "PythonScriptProvider couldn't instantiate " +ucbService, self)
+ self.provCtx = ProviderContext(
+ storageType, sfa, urlHelper, ScriptContext( uno.getComponentContext(), None ) )
+ if isPackage:
+ mapPackageName2Path = getPackageName2PathMap( sfa, storageType )
+ self.provCtx.setPackageAttributes( mapPackageName2Path , rootUrl )
+ self.dirBrowseNode = PackageBrowseNode( self.provCtx, LANGUAGENAME, rootUrl )
+ else:
+ self.dirBrowseNode = DirBrowseNode( self.provCtx, LANGUAGENAME, rootUrl )
+
+ except Exception, e:
+ text = lastException2String()
+ log.debug( "PythonScriptProvider could not be instantiated because of : " + text )
+ raise e
+
+ def getName( self ):
+ return self.dirBrowseNode.getName()
+
+ def getChildNodes( self ):
+ return self.dirBrowseNode.getChildNodes()
+
+ def hasChildNodes( self ):
+ return self.dirBrowseNode.hasChildNodes()
+
+ def getType( self ):
+ return self.dirBrowseNode.getType()
+
+ def getScript( self, uri ):
+ log.debug( "DirBrowseNode getScript " + uri + " invoked" )
+
+ raise IllegalArgumentException( "DirBrowseNode couldn't instantiate script " + uri , self , 0 )
+
+ def getScript( self, scriptUri ):
+ try:
+ log.isDebugLevel() and log.debug( "getScript " + scriptUri + " invoked")
+
+ storageUri = self.provCtx.getStorageUrlFromPersistentUrl(
+ self.provCtx.uriHelper.getStorageURI(scriptUri) );
+ log.isDebugLevel() and log.debug( "getScript: storageUri = " + storageUri)
+ fileUri = storageUri[0:storageUri.find( "$" )]
+ funcName = storageUri[storageUri.find( "$" )+1:len(storageUri)]
+
+ mod = self.provCtx.getModuleByUrl( fileUri )
+ log.isDebugLevel() and log.debug( " got mod " + str(mod) )
+
+ func = mod.__dict__[ funcName ]
+
+ log.isDebugLevel() and log.debug( "got func " + str( func ) )
+ return PythonScript( func, mod )
+ except Exception, e:
+ text = lastException2String()
+ log.error( text )
+ raise ScriptFrameworkErrorException( text, self, scriptUri, LANGUAGENAME, 0 )
+
+
+ # XServiceInfo
+ def getSupportedServices( self ):
+ return g_ImplementationHelper.getSupportedServices(g_implName)
+
+ def supportsService( self, ServiceName ):
+ return g_ImplementationHelper.supportsService( g_implName, ServiceName )
+
+ def getImplementationName(self):
+ return g_implName
+
+ def getByName( self, name ):
+ log.debug( "getByName called" + str( name ))
+ return None
+
+
+ def getElementNames( self ):
+ log.debug( "getElementNames called")
+ return ()
+
+ def hasByName( self, name ):
+ try:
+ log.debug( "hasByName called " + str( name ))
+ uri = expandUri(name)
+ ret = self.provCtx.isUrlInPackage( uri )
+ log.debug( "hasByName " + uri + " " +str( ret ) )
+ return ret
+ except Exception, e:
+ text = lastException2String()
+ log.debug( "Error in hasByName:" + text )
+ return False
+
+ def removeByName( self, name ):
+ log.debug( "removeByName called" + str( name ))
+ uri = expandUri( name )
+ if self.provCtx.isUrlInPackage( uri ):
+ self.provCtx.removePackageByUrl( uri )
+ else:
+ log.debug( "removeByName unknown uri " + str( name ) + ", ignoring" )
+ raise NoSuchElementException( uri + "is not in package" , self )
+ log.debug( "removeByName called" + str( uri ) + " successful" )
+
+ def insertByName( self, name, value ):
+ log.debug( "insertByName called " + str( name ) + " " + str( value ))
+ uri = expandUri( name )
+ if isPyFileInPath( self.provCtx.sfa, uri ):
+ self.provCtx.addPackageByUrl( uri )
+ else:
+ # package is no python package ...
+ log.debug( "insertByName: no python files in " + str( uri ) + ", ignoring" )
+ raise IllegalArgumentException( uri + " does not contain .py files", self, 1 )
+ log.debug( "insertByName called " + str( uri ) + " successful" )
+
+ def replaceByName( self, name, value ):
+ log.debug( "replaceByName called " + str( name ) + " " + str( value ))
+ removeByName( name )
+ insertByName( name )
+ log.debug( "replaceByName called" + str( uri ) + " successful" )
+
+ def getElementType( self ):
+ log.debug( "getElementType called" )
+ return uno.getTypeByName( "void" )
+
+ def hasElements( self ):
+ log.debug( "hasElements got called")
+ return False
+
+g_ImplementationHelper.addImplementation( \
+ PythonScriptProvider,g_implName, \
+ ("com.sun.star.script.provider.LanguageScriptProvider",
+ "com.sun.star.script.provider.ScriptProviderFor"+ LANGUAGENAME,),)
+
+
+log.debug( "pythonscript finished intializing" )
+
diff --git a/scripting/source/runtimemgr/ScriptExecDialog.hrc b/scripting/source/runtimemgr/ScriptExecDialog.hrc
new file mode 100644
index 000000000000..b66c5154e6d3
--- /dev/null
+++ b/scripting/source/runtimemgr/ScriptExecDialog.hrc
@@ -0,0 +1,31 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptExecDialog.hrc,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#define DLG_SCRIPTEXEC 1000
diff --git a/scripting/source/runtimemgr/ScriptExecDialog.src b/scripting/source/runtimemgr/ScriptExecDialog.src
new file mode 100644
index 000000000000..49ab1a7af185
--- /dev/null
+++ b/scripting/source/runtimemgr/ScriptExecDialog.src
@@ -0,0 +1,39 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptExecDialog.src,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#include "ScriptExecDialog.hrc"
+
+QueryBox DLG_SCRIPTEXEC
+{
+ Buttons = WB_YES_NO ;
+ DefButton = WB_DEF_YES ;
+ Title = "Script execution" ;
+ Message = "You are about to execute a script. Do you want to execute this script?" ;
+};
diff --git a/scripting/source/runtimemgr/ScriptNameResolverImpl.cxx b/scripting/source/runtimemgr/ScriptNameResolverImpl.cxx
new file mode 100644
index 000000000000..c1e650f1507a
--- /dev/null
+++ b/scripting/source/runtimemgr/ScriptNameResolverImpl.cxx
@@ -0,0 +1,663 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptNameResolverImpl.cxx,v $
+ * $Revision: 1.31 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#include <vector>
+#include <stdlib.h>
+
+#include <cppuhelper/implementationentry.hxx>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/security/AccessControlException.hpp>
+
+#include <util/util.hxx>
+#include <util/scriptingconstants.hxx>
+
+#include <drafts/com/sun/star/script/framework/storage/XScriptStorageManager.hpp>
+#include <drafts/com/sun/star/script/framework/security/XScriptSecurity.hpp>
+
+#include "ScriptNameResolverImpl.hxx"
+#include "ScriptRuntimeManager.hxx"
+
+using namespace ::rtl;
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::drafts::com::sun::star::script::framework;
+
+namespace scripting_runtimemgr
+{
+
+const sal_Char* const LANGUAGE_TO_RESOLVE_ON[] = { "All" }; // should be configurable
+OUString nrs_implName = OUString::createFromAscii(
+ "drafts.com.sun.star.script.framework.runtime.DefaultScriptNameResolver" );
+OUString nrs_serviceName = OUString::createFromAscii(
+ "drafts.com.sun.star.script.framework.runtime.DefaultScriptNameResolver" );
+Sequence< OUString > nrs_serviceNames = Sequence< OUString >( &nrs_serviceName, 1 );
+
+const char* const SCRIPTSTORAGEMANAGER_SERVICE =
+ "/singletons/drafts.com.sun.star.script.framework.storage.theScriptStorageManager";
+
+extern ::rtl_StandardModuleCount s_moduleCount;
+
+// define storages to search
+static ::std::vector< sal_Int32 >* m_pSearchIDs = NULL;
+
+//*************************************************************************
+ScriptNameResolverImpl::ScriptNameResolverImpl(
+ const Reference< XComponentContext > & xContext ) :
+ m_xContext( xContext )
+{
+ OSL_TRACE( "< ScriptNameResolverImpl ctor called >\n" );
+ validateXRef( m_xContext, "ScriptNameResolverImpl::ScriptNameResolverImpl: invalid context" );
+ m_xMultiComFac = m_xContext->getServiceManager();
+
+ validateXRef( m_xMultiComFac, "ScriptNameResolverImpl::ScriptNameResolverImpl: invalid XMultiComponentFactory " );
+
+ if( !m_pSearchIDs )
+ {
+ osl::Guard< osl::Mutex > aGuard( m_mutex );
+ if( !m_pSearchIDs )
+ {
+ scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
+ scripting_constants::ScriptingConstantsPool::instance();
+ m_pSearchIDs = new ::std::vector< sal_Int32 >();
+ m_pSearchIDs->push_back( scriptingConstantsPool.DOC_STORAGE_ID_NOT_SET );
+ m_pSearchIDs->push_back( scriptingConstantsPool.USER_STORAGE_ID );
+ m_pSearchIDs->push_back( scriptingConstantsPool.SHARED_STORAGE_ID );
+ }
+ }
+
+ s_moduleCount.modCnt.acquire( &s_moduleCount.modCnt );
+}
+
+//*************************************************************************
+ScriptNameResolverImpl::~ScriptNameResolverImpl()
+{
+ OSL_TRACE( "< ScriptNameResolverImpl dtor called >\n" );
+ s_moduleCount.modCnt.release( &s_moduleCount.modCnt );
+}
+
+//*************************************************************************
+Reference< storage::XScriptInfo > ScriptNameResolverImpl::resolve(
+const ::rtl::OUString & scriptURI, Any& invocationCtx )
+throw ( lang::IllegalArgumentException, script::CannotConvertException, RuntimeException )
+{
+
+ Reference< storage::XScriptInfo > resolvedName;
+ Reference< beans::XPropertySet > xPropSetScriptingContext;
+ scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
+ scripting_constants::ScriptingConstantsPool::instance();
+
+ OSL_TRACE( "ScriptNameResolverImpl::resolve: in resolve - start" );
+
+ if ( sal_False == ( invocationCtx >>= xPropSetScriptingContext ) )
+ {
+ throw RuntimeException( OUSTR(
+ "ScriptNameResolverImpl::resolve : unable to get XScriptingContext from param" ),
+ Reference< XInterface > () );
+ }
+
+ Any any;
+ OUString docUri;
+ sal_Int32 filesysScriptStorageID = -1;
+ Reference < storage::XScriptStorageManager > xScriptStorageMgr;
+ sal_Int32 docSid;
+ try
+ {
+ any = xPropSetScriptingContext->getPropertyValue(
+ scriptingConstantsPool.DOC_URI );
+ OSL_TRACE( "ScriptNameResolverImpl::resolve: in resolve - got anyUri" );
+ if ( sal_False == ( any >>= docUri ) )
+ {
+ throw RuntimeException( OUSTR(
+ "ScriptNameResolverImpl::resolve : unable to get doc Uri from xPropSetScriptingContext" ),
+ Reference< XInterface > () );
+ }
+ any = xPropSetScriptingContext->getPropertyValue(
+ scriptingConstantsPool.DOC_STORAGE_ID );
+ if ( sal_False == ( any >>= docSid ) )
+ {
+ throw RuntimeException( OUSTR(
+ "ScriptNameResolverImpl::resolve : unable to get doc storage id from xPropSetScriptingContext" ),
+ Reference< XInterface > () );
+ }
+ }
+ catch ( Exception & e )
+ {
+ OUString temp = OUSTR(
+ "ScriptNameResolverImpl::resolve : problem with getPropertyValue" );
+ throw RuntimeException( temp.concat( e.Message ),
+ Reference< XInterface > () );
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ throw RuntimeException( OUSTR(
+ "ScriptNameResolverImpl::resolve Unknown Exception caught - RuntimeException rethrown" ),
+ Reference< XInterface > () );
+ }
+#endif
+
+
+ ::rtl::OString docUriO(
+ ::rtl::OUStringToOString( docUri , RTL_TEXTENCODING_ASCII_US ) );
+ OSL_TRACE(
+ "ScriptNameResolverImpl::resolve: *** >>> DOC URI: %s, doc sid is %d\n",
+ docUriO.pData->buffer, docSid );
+
+
+ OSL_TRACE( "ScriptNameResolverImpl::resolve Starting..." );
+ OUString docString = OUString::createFromAscii( "location=document" );
+ OUString userString = OUString::createFromAscii( "location=user" );
+ OUString shareString = OUString::createFromAscii( "location=share" );
+ OUString filesysString = OUString::createFromAscii( "location=filesystem" );
+
+ // initialise vector with doc, user and share
+
+ // m_pSearchIDs is initialised as follows,
+ // m_pSearchIDs [ 0 ] empty
+ // m_pSearchIDs [ 1 ] user storage id
+ // m_pSearchIDs [ 2 ] share " "
+
+ ::std::vector< sal_Int32 > m_vSearchIDs = *m_pSearchIDs;
+ m_vSearchIDs[ 0 ] = docSid;
+
+ if ( scriptURI.indexOf( docString ) != -1 )
+ {
+ OSL_TRACE("Full resolution available, search document");
+ // search in document
+ m_vSearchIDs.resize( 1 );
+ }
+ else if ( scriptURI.indexOf( userString ) != -1 )
+ {
+ OSL_TRACE("Full resolution available, search user");
+ // search in user
+ m_vSearchIDs[ 0 ] = ( *m_pSearchIDs )[ 1 ];
+ m_vSearchIDs.resize( 1 );
+ }
+ else if ( scriptURI.indexOf( shareString ) != -1 )
+ {
+ OSL_TRACE("Full resolution available, search share");
+ // search in share
+ m_vSearchIDs[ 0 ] = ( *m_pSearchIDs )[ 2 ];
+ m_vSearchIDs.resize( 1 );
+ }
+ else if ( scriptURI.indexOf( filesysString ) != -1 )
+ {
+ OSL_TRACE("Full resolution available, create & search filesystem");
+ OUString filesysURL;
+ try
+ {
+ filesysURL = getFilesysURL( scriptURI );
+ }
+ catch ( lang::IllegalArgumentException & e )
+ {
+ OUString temp = OUSTR( "ScriptNameResolverImpl::resolve: " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+ Reference< XInterface > xInterface = m_xMultiComFac->createInstanceWithContext(
+ ::rtl::OUString::createFromAscii(
+ "com.sun.star.ucb.SimpleFileAccess" ), m_xContext );
+ validateXRef( xInterface,
+ "ScriptProvider::initialise: cannot get SimpleFileAccess Service\n" );
+ Reference < ucb::XSimpleFileAccess > xSimpleFileAccess = Reference <
+ ucb::XSimpleFileAccess > ( xInterface, UNO_QUERY_THROW );
+
+ // do we need to encode this? hope not.
+ OSL_TRACE( ">>>> About to create storage for %s",
+ ::rtl::OUStringToOString( filesysURL,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ // ask storage manager to create storage
+ try
+ {
+ // need to get the ScriptStorageManager
+ Any a = m_xContext->getValueByName(
+ scriptingConstantsPool.SCRIPTSTORAGEMANAGER_SERVICE );
+ if ( sal_False == ( a >>= xScriptStorageMgr ) )
+ {
+ OUString temp = OUSTR( "ScriptNameResolverImpl::resolve: failed to get ScriptStorageManager" );
+ throw RuntimeException( temp, Reference< XInterface >() );
+ // need to throw
+ }
+ validateXRef( xScriptStorageMgr, "Cannot get ScriptStorageManager" );
+ filesysScriptStorageID =
+ xScriptStorageMgr->createScriptStorageWithURI(
+ xSimpleFileAccess, filesysURL );
+ OSL_TRACE( ">>>> Created storage %d - for %s ",
+ filesysScriptStorageID, ::rtl::OUStringToOString(
+ filesysURL, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }
+ catch ( RuntimeException & e )
+ {
+ OUString temp = OUSTR( "ScriptNameResolverImpl::resolve: " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+ m_vSearchIDs[ 0 ] = filesysScriptStorageID;
+ m_vSearchIDs.resize( 1 );
+ }
+ else
+ {
+ OSL_TRACE("Only partial uri available, search doc, user & share");
+ // is this illegal or do we search in a default way
+ // if we get to here a uri has been passed in that has:
+ // a) not got a location specified
+ // b) an illegal location
+
+ // detect illegal location
+ if ( scriptURI.indexOf( OUString::createFromAscii( "location=" ) ) != -1 )
+ {
+ OSL_TRACE(
+ "ScriptNameResolver::resolve, throwing IllegalArgException" );
+ throw lang::IllegalArgumentException(
+ OUSTR( "invalid URI: " ).concat( scriptURI ),
+ Reference < XInterface > (), 1 );
+
+ }
+ // leave vSearchIDs take care of the search...
+ }
+
+ ::std::vector< sal_Int32 >::const_iterator iter;
+ ::std::vector< sal_Int32 >::const_iterator iterEnd = m_vSearchIDs.end();
+
+ for ( iter = m_vSearchIDs.begin() ; iter != iterEnd; ++iter )
+ {
+ try
+ {
+ OSL_TRACE( "** about to resolve from storage using id %d from vector of size %d",
+ *iter, m_vSearchIDs.size() );
+ if ( ( resolvedName = resolveURIFromStorageID( *iter, docUri, scriptURI ) ).is() )
+ {
+ OSL_TRACE( "found match in uri from storage %d", *iter );
+ xPropSetScriptingContext->setPropertyValue(
+ scriptingConstantsPool.RESOLVED_STORAGE_ID, makeAny(*iter) );
+ break;
+ }
+
+ }
+ catch ( css::security::AccessControlException & e )
+ {
+ // no execute permission
+ OSL_TRACE( "ScriptNameResolverImpl::resolve : AccessControlException " );
+ continue;
+ }
+ catch ( beans::UnknownPropertyException & e )
+ {
+ OUString temp = OUSTR(
+ "ScriptNameResolverImpl::resolve : UnknownPropertyException" );
+ throw RuntimeException( temp.concat( e.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( beans::PropertyVetoException & e )
+ {
+ OUString temp = OUSTR(
+ "ScriptNameResolverImpl::resolve : PropertyVetoException " );
+ throw RuntimeException( temp.concat( e.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( lang::IllegalArgumentException & e )
+ {
+ OUString temp = OUSTR(
+ "ScriptNameResolverImpl::resolve : IllegalArgumentException " );
+ throw lang::IllegalArgumentException( temp.concat( e.Message ),
+ Reference< XInterface > (), e.ArgumentPosition );
+ }
+ catch ( lang::WrappedTargetException & e )
+ {
+ OUString temp = OUSTR(
+ "ScriptNameResolverImpl::resolve : WrappedTargetException " );
+ throw RuntimeException( temp.concat( e.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( Exception & e )
+ {
+ OSL_TRACE(
+ "Exception thrown by storage %d, failed to match uri: %s",
+ *iter,
+ ::rtl::OUStringToOString( e.Message,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ OUString temp = OUSTR(
+ "ScriptNameResolverImpl::resolve : unknown exception" );
+ throw RuntimeException( temp.concat( e.Message ),
+ Reference< XInterface > () );
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ OSL_TRACE(
+ "unknown exception thrown by storage %d, failed to match uri",
+ *iter );
+ OUString temp = OUSTR(
+ "ScriptNameResolverImpl::resolve Unknown exception caught - RuntimeException rethrown" );
+ throw RuntimeException( temp,
+ Reference< XInterface > () );
+ }
+#endif
+
+ }
+ if ( !resolvedName.is() )
+ {
+ if( filesysScriptStorageID > 2 )
+ {
+ // get the filesys storage and dispose of it
+ Reference< XInterface > xScriptStorage =
+ xScriptStorageMgr->getScriptStorage( filesysScriptStorageID );
+ validateXRef( xScriptStorage,
+ "ScriptNameResolverImpl::getStorageInstance: cannot get Script Storage service" );
+ Reference< storage::XScriptInfoAccess > xScriptInfoAccess = Reference<
+ storage::XScriptInfoAccess > ( xScriptStorage, UNO_QUERY_THROW );
+ validateXRef( xScriptInfoAccess,
+ "ScriptNameResolverImpl::resolveURIFromStorageID: cannot get XScriptInfoAccess" );
+ Sequence< Reference< storage::XScriptInfo > > results =
+ xScriptInfoAccess->getAllImplementations( );
+ Reference < lang::XEventListener > xEL_ScriptStorageMgr =
+ Reference< lang::XEventListener >
+ ( xScriptStorageMgr ,UNO_QUERY_THROW );
+ validateXRef( xEL_ScriptStorageMgr, "ScriptNameResolverImpl::resolve: can't get ScriptStorageManager XEventListener interface when trying to dispose of filesystem storage" );
+ lang::EventObject event( results[ 0 ] );
+ xEL_ScriptStorageMgr->disposing( event );
+ }
+ throw lang::IllegalArgumentException( OUSTR(
+ "ScriptNameResolverImpl::resolve: no script found for uri=" ).concat( scriptURI ),
+ Reference< XInterface > (), 0 );
+ }
+ return resolvedName;
+}
+
+//*************************************************************************
+OUString SAL_CALL
+ScriptNameResolverImpl::getImplementationName( )
+throw( RuntimeException )
+{
+ return nrs_implName;
+}
+
+//*************************************************************************
+sal_Bool SAL_CALL
+ScriptNameResolverImpl::supportsService( const OUString& serviceName )
+throw( RuntimeException )
+{
+ OUString const * pNames = nrs_serviceNames.getConstArray();
+ for ( sal_Int32 nPos = nrs_serviceNames.getLength(); nPos--; )
+ {
+ if ( serviceName.equals( pNames[ nPos ] ) )
+ {
+ return sal_True;
+ }
+ }
+ return sal_False;
+}
+
+//*************************************************************************
+
+Reference< storage::XScriptInfo >
+ScriptNameResolverImpl::resolveURIFromStorageID
+( sal_Int32 sid, const ::rtl::OUString & docURI,
+ const ::rtl::OUString& scriptURI )
+SAL_THROW ( ( lang::IllegalArgumentException, css::security::AccessControlException, RuntimeException ) )
+{
+ Reference< storage::XScriptInfo > resolvedScriptInfo;
+ scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
+ scripting_constants::ScriptingConstantsPool::instance();
+ if ( sid == scriptingConstantsPool.DOC_STORAGE_ID_NOT_SET )
+ {
+ OSL_TRACE( "@@@@ **** ScriptNameResolverImpl::resolve DOC_STORAGE_ID_NOT_SET" );
+ return resolvedScriptInfo;
+ }
+ try
+ {
+ OUString permissionURI = docURI;
+ OUString filesysString = OUString::createFromAscii( "location=filesystem" );
+ if ( scriptURI.indexOf( filesysString ) != -1 )
+ {
+ // in the case of filesys scripts we're checking whether the
+ // location of the script, rather than the location of the document,
+ // has execute permission
+ try
+ {
+ permissionURI = getFilesysURL( scriptURI );
+ }
+ catch ( lang::IllegalArgumentException & e )
+ {
+ OUString temp = OUSTR( "ScriptNameResolverImpl::resolveFromURI: " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+ }
+ Reference< storage::XScriptInfoAccess > storage = getStorageInstance( sid, permissionURI );
+ validateXRef( storage,
+ "ScriptNameResolverImpl::resolveURIFromStorageID: cannot get XScriptInfoAccess" );
+ Sequence< Reference< storage::XScriptInfo > > results =
+ storage->getImplementations( scriptURI );
+
+ const sal_Int32 length = results.getLength();
+
+ if ( !length )
+ {
+ return resolvedScriptInfo;
+ }
+
+ OSL_TRACE( "ScriptNameResolverImpl::resolve Got some results..." );
+ // if we get results, just return first in list,
+ // storage has already matched language, function name etc. if
+ // that information was in the uri
+ resolvedScriptInfo = results[ 0 ];
+ }
+ catch ( css::security::AccessControlException & ace )
+ {
+ OUString temp = OUSTR(
+ "ScriptRuntimeManager::resolveURIFromStorageID AccessControlException: " );
+ throw css::security::AccessControlException( temp.concat( ace.Message ),
+ Reference< XInterface > (),
+ ace.LackingPermission );
+ }
+ catch ( lang::IllegalArgumentException & iae )
+ {
+ OUString temp = OUSTR(
+ "ScriptRuntimeManager::resolveURIFromStorageID IllegalArgumentException: " );
+ throw lang::IllegalArgumentException( temp.concat( iae.Message ),
+ Reference< XInterface > (),
+ iae.ArgumentPosition );
+ }
+ catch ( RuntimeException & re )
+ {
+ OUString temp = OUSTR(
+ "ScriptRuntimeManager::resolveURIFromStorageID RuntimeException: " );
+ throw RuntimeException( temp.concat( re.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( Exception & e )
+ {
+ OUString temp = OUSTR(
+ "ScriptNameResolverImpl::resolveURIFromStorageID : Exception caught - RuntimeException rethrown" );
+ throw RuntimeException( temp.concat( e.Message ),
+ Reference< XInterface > () );
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ throw RuntimeException( OUSTR(
+ "ScriptNameResolverImpl::resolveURIFromStorageID Unknown exception caught - RuntimeException rethrown" ),
+ Reference< XInterface > () );
+ }
+#endif
+ return resolvedScriptInfo;
+}
+//*************************************************************************
+
+Reference< storage::XScriptInfoAccess >
+
+ScriptNameResolverImpl::getStorageInstance( sal_Int32 sid,
+const ::rtl::OUString & permissionURI ) SAL_THROW ( ( RuntimeException, css::security::AccessControlException, lang::IllegalArgumentException ) )
+{
+ Reference< storage::XScriptInfoAccess > xScriptInfoAccess;
+ try
+ {
+ Reference< XInterface > xInterface;
+
+ Any a = m_xContext->getValueByName(
+ OUString::createFromAscii( SCRIPTSTORAGEMANAGER_SERVICE ) );
+ if ( sal_False == ( a >>= xInterface ) )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptNameResolverImpl::getStorageInstance: could not obtain ScriptStorageManager singleton" ),
+ Reference< XInterface >() );
+ }
+ validateXRef( xInterface,
+ "ScriptNameResolverImpl::getStorageInstance: cannot get Storage service" );
+ // check that we have permissions for this storage
+ Reference< dcsssf::security::XScriptSecurity > xScriptSecurity( xInterface, UNO_QUERY_THROW );
+ validateXRef( xScriptSecurity,
+ "ScriptNameResolverImpl::getStorageInstance: cannot get Script Security service" );
+ scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
+ scripting_constants::ScriptingConstantsPool::instance();
+ // if we dealing with a document storage (ie. not user or share
+ // we need to check the permission
+ if( ( sid != scriptingConstantsPool.USER_STORAGE_ID ) &&
+ ( sid != scriptingConstantsPool.SHARED_STORAGE_ID ) )
+ {
+ xScriptSecurity->checkPermission( permissionURI,
+ OUString::createFromAscii( "execute" ) );
+ // if we get here, the checkPermission hasn't thrown an
+ // AccessControlException, ie. permission has been granted
+ OSL_TRACE( "ScriptNameResolverImpl::getStorageInstance: got execute permission for ID=%d", sid );
+ }
+ Reference< storage::XScriptStorageManager > xScriptStorageManager( xInterface, UNO_QUERY_THROW );
+ validateXRef( xScriptStorageManager,
+ "ScriptNameResolverImpl::getStorageInstance: cannot get Script Storage Manager service" );
+ Reference< XInterface > xScriptStorage =
+ xScriptStorageManager->getScriptStorage( sid );
+ validateXRef( xScriptStorage,
+ "ScriptNameResolverImpl::getStorageInstance: cannot get Script Storage service" );
+ xScriptInfoAccess = Reference<
+ storage::XScriptInfoAccess > ( xScriptStorage, UNO_QUERY_THROW );
+ }
+ catch ( lang::IllegalArgumentException & e )
+ {
+ OUString temp = OUSTR( "ScriptNameResolverImpl::getStorageInstance: " );
+ throw lang::IllegalArgumentException( temp.concat( e.Message ),
+ Reference< XInterface >(), e.ArgumentPosition );
+ }
+ catch ( css::security::AccessControlException & e )
+ {
+ OUString temp = OUSTR( "ScriptNameResolverImpl::getStorageInstance: AccessControlException " );
+ throw css::security::AccessControlException( temp.concat( e.Message ), Reference< XInterface >(), e.LackingPermission );
+ }
+ catch ( RuntimeException & re )
+ {
+ OUString temp = OUSTR( "ScriptNameResolverImpl::getStorageInstance: " );
+ throw RuntimeException( temp.concat( re.Message ), Reference< XInterface >() );
+ }
+ catch ( Exception & e )
+ {
+ OUString temp = OUSTR( "ScriptNameResolverImpl::getStorageInstance: " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+ return xScriptInfoAccess;
+}
+//*************************************************************************
+OUString
+ScriptNameResolverImpl::getFilesysURL( const OUString & scriptURI )
+throw( lang::IllegalArgumentException )
+{
+ OUString filePath;
+ OUString fileName;
+ OUString filesysString = OUString::createFromAscii( "location=filesystem" );
+ sal_Int32 locationPos = scriptURI.indexOf( filesysString );
+ // expect location=filesys:file:///foo/bar/myscript.bsh etc
+ // except the file url at this point is encoded
+ // so we should be ok searching for the '&'
+ sal_Int32 filesysStrLen = filesysString.getLength() + 1;
+ sal_Int32 endOfLocn = scriptURI.indexOf( '&', locationPos );
+ if (endOfLocn == -1 )
+ {
+ filePath = scriptURI.copy( locationPos + filesysString.getLength() + 1 );
+ }
+ else
+ {
+ filePath = scriptURI.copy( locationPos + filesysStrLen,
+ endOfLocn - locationPos - filesysStrLen );
+ }
+ //file name shoul also be encoded so again ok to search for '&'
+ OUString functionKey = OUString::createFromAscii( "function=" );
+ sal_Int32 functionKeyLength = functionKey.getLength();
+ sal_Int32 functionNamePos = scriptURI.indexOf( functionKey );
+ if ( functionNamePos > 0 )
+ {
+ sal_Int32 endOfFn = scriptURI.indexOf( '&', functionNamePos );
+ if ( endOfFn == -1 )
+ {
+ fileName = scriptURI.copy( functionNamePos + functionKeyLength );
+ }
+ else
+ {
+ fileName = scriptURI.copy( functionNamePos + functionKeyLength,
+ endOfFn - functionNamePos - functionKeyLength );
+ }
+ }
+ else
+ {
+ // we need to throw
+ OUString temp = OUSTR( "ScriptNameResolverImpl::getFilesysURL: error getting the filesysURL" );
+ throw lang::IllegalArgumentException( temp, Reference< XInterface >(), 0 );
+ }
+ filePath+=fileName;
+ OSL_TRACE( "ScriptNameResolverImpl::getFilesysURL: filesys URL = %s",
+ ::rtl::OUStringToOString( filePath,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ return filePath;
+}
+//*************************************************************************
+Sequence<OUString> SAL_CALL
+ScriptNameResolverImpl::getSupportedServiceNames( )
+throw( RuntimeException )
+{
+ return nrs_serviceNames;
+}
+
+//*************************************************************************
+Reference< XInterface > SAL_CALL scriptnri_create(
+ Reference< XComponentContext > const & xComponentContext )
+SAL_THROW( ( Exception ) )
+{
+ return ( cppu::OWeakObject * ) new ScriptNameResolverImpl( xComponentContext );
+}
+
+//*************************************************************************
+Sequence< OUString > scriptnri_getSupportedServiceNames() SAL_THROW( () )
+{
+ return nrs_serviceNames;
+}
+
+//*************************************************************************
+OUString scriptnri_getImplementationName() SAL_THROW( () )
+{
+ return nrs_implName;
+}
+} // namespace scripting_runtimemgr
diff --git a/scripting/source/runtimemgr/ScriptNameResolverImpl.hxx b/scripting/source/runtimemgr/ScriptNameResolverImpl.hxx
new file mode 100644
index 000000000000..6ca95f8a5973
--- /dev/null
+++ b/scripting/source/runtimemgr/ScriptNameResolverImpl.hxx
@@ -0,0 +1,113 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptNameResolverImpl.hxx,v $
+ * $Revision: 1.15 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+#ifndef _FRAMEWORK_SCRIPT_SCRIPTNAMERESOLVERIMPL_HXX_
+#define _FRAMEWORK_SCRIPT_SCRIPTNAMERESOLVERIMPL_HXX_
+
+#include <cppuhelper/implbase1.hxx> // helper for XInterface, XTypeProvider etc.
+
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/script/CannotConvertException.hpp>
+#include <com/sun/star/reflection/InvocationTargetException.hpp>
+
+#include <drafts/com/sun/star/script/framework/runtime/XScriptNameResolver.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfoAccess.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfo.hpp>
+
+namespace scripting_runtimemgr
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+class ScriptNameResolverImpl : public
+ ::cppu::WeakImplHelper1 < dcsssf::runtime::XScriptNameResolver >
+{
+public:
+ /**********************************************
+ ScriptNameResolverImpl Constructor
+ @param the current context
+ */
+ ScriptNameResolverImpl(
+ const css::uno::Reference< css::uno::XComponentContext > & xContext );
+ ~ScriptNameResolverImpl();
+
+ // XServiceInfo implementation
+ virtual ::rtl::OUString SAL_CALL getImplementationName()
+ throw( css::uno::RuntimeException );
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
+ throw( css::uno::RuntimeException );
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
+ throw( css::uno::RuntimeException );
+
+ /**********************************************
+ resolve method
+ @param scriptURI this is the given ScriptURI
+ @param invocationCtx the invocation context contains the
+ documentStorageID and document reference for use in script name
+ resolving. On full name resolution it sets the resolvedScriptStorageID to
+ the actual storage location of the fully resolved script. May or may not * be the
+ same as the documentStorageID.
+ @exception CannotResolveScriptNameException
+ @exception IllegalArgumentException
+ @exception NullPointerException
+ @return the resolved XScriptURI
+ */
+ css::uno::Reference < dcsssf::storage::XScriptInfo > SAL_CALL resolve(
+ const ::rtl::OUString & scriptURI,
+ css::uno::Any& invocationCtx )
+ throw( css::script::CannotConvertException, css::lang::IllegalArgumentException,
+ css::uno::RuntimeException );
+private:
+ css::uno::Reference < dcsssf::storage::XScriptInfo >
+ resolveURIFromStorageID( sal_Int32 sid, const rtl::OUString & docURI,
+ const ::rtl::OUString & nameToResolve )
+ SAL_THROW ( ( css::lang::IllegalArgumentException, css::uno::RuntimeException ) );
+ css::uno::Reference< dcsssf::storage::XScriptInfoAccess >
+ getStorageInstance( sal_Int32 sid, const rtl::OUString & permissionURI)
+ SAL_THROW ( ( css::uno::RuntimeException ) );
+ ::rtl::OUString
+ ScriptNameResolverImpl::getFilesysURL( const ::rtl::OUString & scriptURI )
+ throw( css::lang::IllegalArgumentException );
+
+ /**********************************************
+ Reference< XComponentContext > m_xContext
+ to obtain other services if needed
+ */
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+ css::uno::Reference< css::lang::XMultiComponentFactory > m_xMultiComFac;
+ ::osl::Mutex m_mutex;
+
+};
+} // scripting_runtimemgr
+
+#endif //_FRAMEWORK_SCRIPT_SCRIPTNAMERESOLVERIMPL_HXX_
diff --git a/scripting/source/runtimemgr/ScriptRuntimeManager.cxx b/scripting/source/runtimemgr/ScriptRuntimeManager.cxx
new file mode 100755
index 000000000000..19bbca4ca55e
--- /dev/null
+++ b/scripting/source/runtimemgr/ScriptRuntimeManager.cxx
@@ -0,0 +1,569 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptRuntimeManager.cxx,v $
+ * $Revision: 1.22 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#ifndef _VCL_MSGBOX_HXX
+#include <vcl/msgbox.hxx>
+#endif
+
+#include "ScriptExecDialog.hrc"
+
+#include <util/scriptingconstants.hxx>
+
+#include <cppuhelper/implementationentry.hxx>
+
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/lang/XEventListener.hpp>
+#include <com/sun/star/lang/EventObject.hpp>
+
+#include "ScriptNameResolverImpl.hxx"
+#include "ScriptRuntimeManager.hxx"
+#include <util/util.hxx>
+#include <util/scriptingconstants.hxx>
+
+using namespace ::rtl;
+using namespace ::osl;
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::drafts::com::sun::star::script::framework;
+
+namespace scripting_runtimemgr
+{
+
+static OUString s_implName = ::rtl::OUString::createFromAscii(
+ "drafts.com.sun.star.script.framework.runtime.ScriptRuntimeManager" );
+static OUString s_serviceName = ::rtl::OUString::createFromAscii(
+ "drafts.com.sun.star.script.framework.runtime.ScriptRuntimeManager" );
+static Sequence< OUString > s_serviceNames = Sequence< OUString >( &s_serviceName, 1 );
+
+::rtl_StandardModuleCount s_moduleCount = MODULE_COUNT_INIT;
+
+//*************************************************************************
+// ScriptRuntimeManager Constructor
+ScriptRuntimeManager::ScriptRuntimeManager(
+ const Reference< XComponentContext > & xContext ) :
+ m_xContext( xContext )
+{
+ OSL_TRACE( "< ScriptRuntimeManager ctor called >\n" );
+ validateXRef( m_xContext,
+ "ScriptRuntimeManager::ScriptRuntimeManager: invalid context" );
+ m_xMgr = m_xContext->getServiceManager();
+ validateXRef( m_xMgr,
+ "ScriptRuntimeManager::ScriptRuntimeManager: cannot get ServiceManager" );
+ s_moduleCount.modCnt.acquire( &s_moduleCount.modCnt );
+ // test
+ //scripting_securitymgr::ScriptSecurityManager ssm(xContext);
+}
+
+//*************************************************************************
+// ScriptRuntimeManager Destructor
+ScriptRuntimeManager::~ScriptRuntimeManager()
+{
+ OSL_TRACE( "< ScriptRuntimeManager dtor called >\n" );
+ s_moduleCount.modCnt.release( &s_moduleCount.modCnt );
+}
+
+//*************************************************************************
+// Get the proper XScriptInvocation
+Reference< runtime::XScriptInvocation > SAL_CALL ScriptRuntimeManager::getScriptRuntime(
+const Reference< XInterface >& scriptInfo )
+throw( RuntimeException )
+{
+ OSL_TRACE( "** ==> ScriptRuntimeManager in getScriptRuntime\n" );
+
+ Reference< runtime::XScriptInvocation > xScriptInvocation;
+
+ try
+ {
+ Reference< XInterface > xInterface;
+
+ Reference< storage::XScriptInfo > sinfo =
+ Reference< storage::XScriptInfo >( scriptInfo, UNO_QUERY_THROW );
+
+ OUStringBuffer *buf = new OUStringBuffer(80);
+ buf->appendAscii("/singletons/drafts.com.sun.star.script.framework.runtime.theScriptRuntimeFor");
+ buf->append(sinfo->getLanguage());
+
+ Any a = m_xContext->getValueByName(buf->makeStringAndClear());
+
+ if ( sal_False == ( a >>= xInterface ) )
+ {
+ throw RuntimeException(
+ sinfo->getLanguage().concat( OUSTR( " runtime support is not installed for this language" ) ),
+ Reference< XInterface >() );
+ }
+ validateXRef( xInterface,
+ "ScriptRuntimeManager::GetScriptRuntime: cannot get appropriate ScriptRuntime Service"
+ );
+ xScriptInvocation = Reference< runtime::XScriptInvocation >( xInterface, UNO_QUERY_THROW );
+ }
+ catch ( Exception & e )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::GetScriptRuntime: " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+
+ return xScriptInvocation;
+}
+
+//*************************************************************************
+// Get the proper XScriptNameResolver
+Reference< runtime::XScriptNameResolver > SAL_CALL
+ScriptRuntimeManager::getScriptNameResolver()
+throw( RuntimeException )
+{
+ OSL_TRACE( "** ==> ScriptRuntimeManager in getScriptNameResolver\n" );
+ Reference< runtime::XScriptNameResolver > xScriptNameResolver;
+
+ try
+ {
+ Reference< XInterface > xInterface = m_xMgr->createInstanceWithContext(
+ OUString::createFromAscii(
+ "drafts.com.sun.star.script.framework.runtime.DefaultScriptNameResolver" ),
+ m_xContext );
+ validateXRef( xInterface,
+ "ScriptRuntimeManager::GetScriptRuntime: cannot get instance of DefaultScriptNameResolver" );
+ xScriptNameResolver = Reference< runtime::XScriptNameResolver >( xInterface, UNO_QUERY_THROW );
+ }
+ catch ( Exception & e )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::GetScriptNameResolver: " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+ return xScriptNameResolver;
+}
+
+//*************************************************************************
+// XScriptInvocation implementation
+Any SAL_CALL ScriptRuntimeManager::invoke(
+ const ::rtl::OUString & scriptURI,
+ const Any& invocationCtx, const Sequence< Any >& aParams,
+ Sequence< sal_Int16 >& aOutParamIndex, Sequence< Any >& aOutParam )
+ throw ( lang::IllegalArgumentException, script::CannotConvertException,
+ reflection::InvocationTargetException, RuntimeException )
+{
+ OSL_TRACE( "** ==> ScriptRuntimeManager in runtimemgr invoke\n" );
+
+ Any results;
+ scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
+ scripting_constants::ScriptingConstantsPool::instance();
+
+ // Initialise resolved context with invocation context,
+ // the resolved context (resolvedCtx will be modified by the
+ // resolve method to contain the storage where the script code is
+ // stored
+ Any resolvedCtx = invocationCtx;
+
+ try
+ {
+ Reference< storage::XScriptInfo > resolvedScript = resolve( scriptURI,
+ resolvedCtx );
+ validateXRef( resolvedScript, "ScriptRuntimeManager::invoke: No resolvedURI" );
+
+ Reference< beans::XPropertySet > xPropSetResolvedCtx;
+ if ( sal_False == ( resolvedCtx >>= xPropSetResolvedCtx ) )
+ {
+ throw RuntimeException( OUSTR(
+ "ScriptRuntimeManager::invoke : unable to get XPropSetScriptingContext from param" ),
+ Reference< XInterface > () );
+ }
+
+ Any any = xPropSetResolvedCtx->getPropertyValue(
+ scriptingConstantsPool.RESOLVED_STORAGE_ID );
+ sal_Int32 resolvedSid;
+ if ( sal_False == ( any >>= resolvedSid ) )
+ {
+ throw RuntimeException( OUSTR(
+ "ScriptRuntimeManager::invoke : unable to get resolved storage id from xPropSetResolvedCtx" ),
+ Reference< XInterface > () );
+ }
+
+ OSL_TRACE("Storage sid is: %d\n", resolvedSid);
+
+ // modifying the XPropertySet on the resolved Context to contain the
+ // full script info
+ Any aResolvedScript;
+ aResolvedScript <<= resolvedScript;
+
+ xPropSetResolvedCtx->setPropertyValue( scriptingConstantsPool.SCRIPT_INFO,
+ aResolvedScript );
+
+ Reference< runtime::XScriptInvocation > xScriptInvocation =
+ getScriptRuntime( resolvedScript );
+ validateXRef( xScriptInvocation,
+ "ScriptRuntimeManager::invoke: cannot get instance of language specific runtime." );
+
+ // the scriptURI is currently passed to the language-dept runtime but
+ // is not used (may be useful in the future?). All of the script info
+ // is contained as a property(SCRIPT_INFO) within the resolvedCtx
+ results = xScriptInvocation->invoke( scriptURI, resolvedCtx, aParams,
+ aOutParamIndex, aOutParam );
+
+ // need to dispose of filesystem storage
+ OUString filesysString = OUString::createFromAscii(
+ "location=filesystem" );
+ if ( scriptURI.indexOf( filesysString ) != -1 )
+ {
+ Any a = m_xContext->getValueByName(
+ scriptingConstantsPool.SCRIPTSTORAGEMANAGER_SERVICE );
+ Reference < lang::XEventListener > xEL_ScriptStorageManager;
+ if ( sal_False == ( a >>= xEL_ScriptStorageManager ) )
+ {
+ throw RuntimeException( OUSTR( "ScriptRuntimeManager::invoke: can't get ScriptStorageManager XEventListener interface when trying to dispose of filesystem storage" ),
+ Reference< XInterface > () );
+ }
+ validateXRef( xEL_ScriptStorageManager, "Cannot get XEventListener from ScriptStorageManager" );
+ lang::EventObject event(resolvedScript);
+ xEL_ScriptStorageManager->disposing( event );
+ }
+ }
+ catch ( lang::IllegalArgumentException & iae )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::invoke IllegalArgumentException: " );
+ throw lang::IllegalArgumentException( temp.concat( iae.Message ),
+ Reference< XInterface > (),
+ iae.ArgumentPosition );
+ }
+ catch ( script::CannotConvertException & cce )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::invoke CannotConvertException: " );
+ throw script::CannotConvertException( temp.concat( cce.Message ),
+ Reference< XInterface > (),
+ cce.DestinationTypeClass, cce.Reason,
+ cce.ArgumentIndex );
+ }
+ catch ( reflection::InvocationTargetException & ite )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::invoke InvocationTargetException: " );
+ throw reflection::InvocationTargetException( temp.concat( ite.Message ),
+ Reference< XInterface > (), ite.TargetException );
+ }
+ catch ( beans::UnknownPropertyException & e )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::invoke UnknownPropertyException: " );
+ throw RuntimeException( temp.concat( e.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( lang::WrappedTargetException & e )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::invoke WrappedTargetException : " );
+ throw RuntimeException( temp.concat( e.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( RuntimeException & re )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::invoke RuntimeException: " );
+ throw RuntimeException( temp.concat( re.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( Exception & e )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::invoke Exception: " );
+ throw RuntimeException( temp.concat( e.Message ),
+ Reference< XInterface > () );
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ throw RuntimeException( OUSTR( "ScriptRuntimeManager::invoke UnknownException: " ),
+ Reference< XInterface > () );
+ }
+#endif
+ OSL_TRACE( "** ==> ScriptRuntimeManager returned from invoke: %s\n", ::rtl::OUStringToOString( results.getValueTypeName(), RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ return results;
+}
+
+//*************************************************************************
+// XScriptNameResolver implementation
+Reference< storage::XScriptInfo > SAL_CALL
+ScriptRuntimeManager::resolve( const ::rtl::OUString& scriptURI,
+ Any& invocationCtx )
+throw( lang::IllegalArgumentException, script::CannotConvertException, RuntimeException )
+{
+ OSL_TRACE( "** ==> ScriptRuntimeManager in resolve\n" );
+ Reference< storage::XScriptInfo > resolvedURI;
+
+ Reference< runtime::XScriptNameResolver > xScriptNameResolver = getScriptNameResolver();
+ validateXRef( xScriptNameResolver,
+ "ScriptRuntimeManager::resolve: No ScriptNameResolver" );
+
+ try
+ {
+ resolvedURI = xScriptNameResolver->resolve( scriptURI, invocationCtx );
+ }
+ catch ( lang::IllegalArgumentException & iae )
+ {
+ OUString temp =
+ OUSTR( "ScriptRuntimeManager::resolve IllegalArgumentException: " );
+ throw lang::IllegalArgumentException( temp.concat( iae.Message ),
+ Reference< XInterface > (),
+ iae.ArgumentPosition );
+ }
+ catch ( script::CannotConvertException & cce )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::resolve CannotConvertException: " );
+ throw script::CannotConvertException( temp.concat( cce.Message ),
+ Reference< XInterface > (),
+ cce.DestinationTypeClass, cce.Reason,
+ cce.ArgumentIndex );
+ }
+ catch ( RuntimeException & re )
+ {
+ OUString temp = OUSTR( "ScriptRuntimeManager::resolve RuntimeException: " );
+ throw RuntimeException( temp.concat( re.Message ),
+ Reference< XInterface > () );
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptRuntimeManager::resolve UnknownException: " ),
+ Reference< XInterface > () );
+ }
+#endif
+
+ return resolvedURI;
+}
+
+//*************************************************************************
+OUString SAL_CALL ScriptRuntimeManager::getImplementationName( )
+throw( RuntimeException )
+{
+ return s_implName;
+}
+
+//*************************************************************************
+sal_Bool SAL_CALL ScriptRuntimeManager::supportsService( const OUString& serviceName )
+throw( RuntimeException )
+{
+ OUString const * pNames = s_serviceNames.getConstArray();
+ for ( sal_Int32 nPos = s_serviceNames.getLength(); nPos--; )
+ {
+ if ( serviceName.equals( pNames[ nPos ] ) )
+ {
+ return sal_True;
+ }
+ }
+ return sal_False;
+}
+
+//*************************************************************************
+Sequence<OUString> SAL_CALL ScriptRuntimeManager::getSupportedServiceNames( )
+throw( RuntimeException )
+{
+ return s_serviceNames;
+}
+
+//*************************************************************************
+static Reference< XInterface > SAL_CALL srm_create(
+ const Reference< XComponentContext > & xCompC )
+{
+ return ( cppu::OWeakObject * ) new ScriptRuntimeManager( xCompC );
+}
+
+//*************************************************************************
+static Sequence<OUString> srm_getSupportedServiceNames( )
+SAL_THROW( () )
+{
+ return s_serviceNames;
+}
+
+//*************************************************************************
+static OUString srm_getImplementationName( )
+SAL_THROW( () )
+{
+ return s_implName;
+}
+
+//*************************************************************************
+Reference< XInterface > SAL_CALL scriptnri_create(
+ Reference< XComponentContext > const & xComponentContext )
+SAL_THROW( ( Exception ) );
+
+//*************************************************************************
+Sequence< OUString > scriptnri_getSupportedServiceNames() SAL_THROW( () );
+
+//*************************************************************************
+OUString scriptnri_getImplementationName() SAL_THROW( () );
+
+//******************** ScriptStorageMangaer defines ***********************
+Reference< XInterface > SAL_CALL ssm_create(
+ Reference< XComponentContext > const & xComponentContext )
+SAL_THROW( ( Exception ) );
+//*************************************************************************
+Sequence< OUString > ssm_getSupportedServiceNames() SAL_THROW( () );
+//*************************************************************************
+OUString ssm_getImplementationName() SAL_THROW( () );
+//*************************************************************************
+
+//************ Script Provider defines ************************************
+Reference< XInterface > SAL_CALL sp_create( const Reference< XComponentContext > & xCompC );
+//******************** ScriptProvider defines ***************************
+Sequence< OUString > sp_getSupportedServiceNames( ) SAL_THROW( () );
+//*************************************************************************
+OUString sp_getImplementationName( ) SAL_THROW( () );
+//*************************************************************************
+
+//************ ScriptStorage defines **************************************
+Reference< XInterface > SAL_CALL ss_create( const Reference< XComponentContext > & xCompC );
+//******************** ScriptProvider defines ***************************
+Sequence< OUString > ss_getSupportedServiceNames( ) SAL_THROW( () );
+//*************************************************************************
+OUString ss_getImplementationName( ) SAL_THROW( () );
+//*************************************************************************
+
+
+static struct cppu::ImplementationEntry s_entries [] =
+ {
+ {
+ srm_create, srm_getImplementationName,
+ srm_getSupportedServiceNames, cppu::createSingleComponentFactory,
+ &s_moduleCount.modCnt, 0
+ },
+ {
+ scriptnri_create, scriptnri_getImplementationName,
+ scriptnri_getSupportedServiceNames, cppu::createSingleComponentFactory,
+ &s_moduleCount.modCnt, 0
+ },
+ {
+ ssm_create, ssm_getImplementationName,
+ ssm_getSupportedServiceNames, cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ {
+ ss_create, ss_getImplementationName,
+ ss_getSupportedServiceNames, cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ {
+ sp_create, sp_getImplementationName,
+ sp_getSupportedServiceNames, cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ { 0, 0, 0, 0, 0, 0 }
+ };
+} // Namespace
+
+//#######################################################################################
+//#### EXPORTED #########################################################################
+//#######################################################################################
+
+/**
+ * Gives the environment this component belongs to.
+ */
+extern "C"
+{
+ void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName,
+ uno_Environment ** ppEnv )
+ {
+ *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
+ }
+
+ /**
+ * This function creates an implementation section in the registry and another subkey
+ *
+ * for each supported service.
+ * @param pServiceManager the service manager
+ * @param pRegistryKey the registry key
+ */
+ sal_Bool SAL_CALL component_writeInfo( lang::XMultiServiceFactory * pServiceManager,
+ registry::XRegistryKey * pRegistryKey )
+ {
+ if (::cppu::component_writeInfoHelper( pServiceManager, pRegistryKey,
+ ::scripting_runtimemgr::s_entries ))
+ {
+ try
+ {
+ // register RuntimeManager singleton
+
+ registry::XRegistryKey * pKey =
+ reinterpret_cast< registry::XRegistryKey * >(pRegistryKey);
+
+ Reference< registry::XRegistryKey > xKey(
+ pKey->createKey(
+
+ OUSTR("drafts.com.sun.star.script.framework.runtime.ScriptRuntimeManager/UNO/SINGLETONS/drafts.com.sun.star.script.framework.runtime.theScriptRuntimeManager")));
+ xKey->setStringValue( OUSTR("drafts.com.sun.star.script.framework.runtime.ScriptRuntimeManager") );
+
+ // ScriptStorage Mangaer singleton
+
+ xKey = pKey->createKey(
+ OUSTR("drafts.com.sun.star.script.framework.storage.ScriptStorageManager/UNO/SINGLETONS/drafts.com.sun.star.script.framework.storage.theScriptStorageManager"));
+ xKey->setStringValue( OUSTR("drafts.com.sun.star.script.framework.storage.ScriptStorageManager") );
+ // Singleton entries are not handled by the setup process
+ // below is the only alternative at the momement which
+ // is to programmatically do this.
+
+ // "Java" Runtime singleton entry
+
+ xKey = pKey->createKey(
+ OUSTR("com.sun.star.scripting.runtime.java.ScriptRuntimeForJava$_ScriptRuntimeForJava/UNO/SINGLETONS/drafts.com.sun.star.script.framework.runtime.theScriptRuntimeForJava"));
+ xKey->setStringValue( OUSTR("drafts.com.sun.star.script.framework.runtime.ScriptRuntimeForJava") );
+
+ // "JavaScript" Runtime singleton entry
+
+ xKey = pKey->createKey(
+ OUSTR("com.sun.star.scripting.runtime.javascript.ScriptRuntimeForJavaScript$_ScriptRuntimeForJavaScript/UNO/SINGLETONS/drafts.com.sun.star.script.framework.runtime.theScriptRuntimeForJavaScript"));
+ xKey->setStringValue( OUSTR("drafts.com.sun.star.script.framework.runtime.ScriptRuntimeForJavaScript") );
+
+ // "BeanShell" Runtime singleton entry
+
+ xKey = pKey->createKey(
+ OUSTR("com.sun.star.scripting.runtime.beanshell.ScriptRuntimeForBeanShell$_ScriptRuntimeForBeanShell/UNO/SINGLETONS/drafts.com.sun.star.script.framework.runtime.theScriptRuntimeForBeanShell"));
+ xKey->setStringValue( OUSTR("drafts.com.sun.star.script.framework.runtime.ScriptRuntimeForBeanShell") );
+
+ return sal_True;
+ }
+ catch (Exception & exc)
+ {
+ }
+ }
+ return sal_False;
+ }
+
+ /**
+ * This function is called to get service factories for an implementation.
+ *
+ * @param pImplName name of implementation
+ * @param pServiceManager a service manager, need for component creation
+ * @param pRegistryKey the registry key for this component, need for persistent
+ * data
+ * @return a component factory
+ */
+ void * SAL_CALL component_getFactory( const sal_Char * pImplName,
+ lang::XMultiServiceFactory * pServiceManager,
+ registry::XRegistryKey * pRegistryKey )
+ {
+ return ::cppu::component_getFactoryHelper( pImplName, pServiceManager,
+ pRegistryKey, ::scripting_runtimemgr::s_entries );
+ }
+}
diff --git a/scripting/source/runtimemgr/ScriptRuntimeManager.hxx b/scripting/source/runtimemgr/ScriptRuntimeManager.hxx
new file mode 100644
index 000000000000..07197be2319f
--- /dev/null
+++ b/scripting/source/runtimemgr/ScriptRuntimeManager.hxx
@@ -0,0 +1,152 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptRuntimeManager.hxx,v $
+ * $Revision: 1.12 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+
+#ifndef _FRAMEWORK_SCRIPT_SCRIPTRUNTIMEMANAGER_HXX_
+#define _FRAMEWORK_SCRIPT_SCRIPTRUNTIMEMANAGER_HXX_
+
+#include <osl/mutex.hxx>
+
+#include <cppuhelper/implbase3.hxx>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/lang/XMultiComponentFactory.hpp>
+#include <com/sun/star/script/CannotConvertException.hpp>
+#include <com/sun/star/reflection/InvocationTargetException.hpp>
+
+#include <drafts/com/sun/star/script/framework/runtime/XScriptInvocation.hpp>
+#include <drafts/com/sun/star/script/framework/runtime/XScriptNameResolver.hpp>
+
+namespace scripting_runtimemgr
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+/**
+ * Class responsible for managing the various ScriptRuntime implementations.
+ */
+class ScriptRuntimeManager : public
+ ::cppu::WeakImplHelper3< dcsssf::runtime::XScriptInvocation, css::lang::XServiceInfo,
+ dcsssf::runtime::XScriptNameResolver >
+{
+public:
+ explicit ScriptRuntimeManager(
+ const css::uno::Reference< css::uno::XComponentContext > & xContext );
+ ~ScriptRuntimeManager();
+
+
+ // XServiceInfo implementation
+ virtual ::rtl::OUString SAL_CALL getImplementationName()
+ throw( css::uno::RuntimeException );
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
+ throw( css::uno::RuntimeException );
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
+ throw( css::uno::RuntimeException );
+
+ /**
+ * implements XScriptInvocation, invokes the script named in scriptURI
+ * (resolving it first, if necessary), with the args passed.
+ *
+ * @param scriptURI the URI, which may not be fully qualified, for the
+ * script to be invoked
+ *
+ *************************************************************
+ Invoke
+ @param scriptUri script uri describing the script
+ @param invocationCtx
+ the invocation context contains the documentStorageID and document reference
+ for use in script name resolving
+
+ @param aParams all parameters; pure, out params are undefined in sequence,
+ i.e., the value has to be ignored by the callee
+ @param aOutParamIndex out indices
+ @param aOutParam out parameters
+
+ @returns
+ the value returned from the function being invoked
+
+ @throws IllegalArgumentException
+ if there is no matching script name
+
+ @throws CannotConvertException
+ if args do not match or cannot be converted the those
+ of the invokee
+
+ @throws InvocationTargetException
+ if the running script throws an exception this information is captured and
+ rethrown as this exception type.
+
+ */
+ virtual css::uno::Any SAL_CALL invoke(
+ const ::rtl::OUString & scriptUri,
+ const css::uno::Any& invocationCtx,
+ const css::uno::Sequence< css::uno::Any >& aParams,
+ css::uno::Sequence< sal_Int16 >& aOutParamIndex,
+ css::uno::Sequence< css::uno::Any >& aOutParam )
+ throw ( css::lang::IllegalArgumentException,
+ css::script::CannotConvertException,
+ css::reflection::InvocationTargetException,
+ css::uno::RuntimeException );
+
+ /**
+ * implements XScriptNameResolver, attempts to resolve the script URI
+ * passed in
+ *
+ * @param scriptURI the URI to be resolved
+ * @param invocationCtx the invocation context contains the
+ * documentStorageID and document reference for use in script name
+ * resolving. On full name resolution it sets the resolvedScriptStorageID to
+ * the actual storage location of the fully resolved script. May or may not * be the
+ same as the documentStorageID.
+ * @return the resolved URI
+ */
+ virtual css::uno::Reference< dcsssf::storage::XScriptInfo > SAL_CALL resolve(
+ const ::rtl::OUString& scriptUri,
+ css::uno::Any& invocationCtx )
+ throw( css::lang::IllegalArgumentException, css::script::CannotConvertException,
+ css::uno::RuntimeException );
+
+private:
+ css::uno::Reference< dcsssf::runtime::XScriptInvocation > SAL_CALL getScriptRuntime(
+ const css::uno::Reference< css::uno::XInterface > & scriptInfo )
+ throw( css::uno::RuntimeException );
+ css::uno::Reference< dcsssf::runtime::XScriptNameResolver > SAL_CALL getScriptNameResolver()
+ throw( css::uno::RuntimeException );
+
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+ css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;
+ ::osl::Mutex m_mutex;
+};
+} // scripting_runtimemgr
+
+#endif //_FRAMEWORK_SCRIPT_SCRIPTRUNTIMEMANAGER_HXX_
diff --git a/scripting/source/runtimemgr/StorageBridge.cxx b/scripting/source/runtimemgr/StorageBridge.cxx
new file mode 100644
index 000000000000..0fe05265c420
--- /dev/null
+++ b/scripting/source/runtimemgr/StorageBridge.cxx
@@ -0,0 +1,155 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: StorageBridge.cxx,v $
+ * $Revision: 1.10 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#include <com/sun/star/lang/XMultiComponentFactory.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptStorageManager.hpp>
+
+#include "StorageBridge.hxx"
+#include <util/util.hxx>
+
+using namespace ::rtl;
+using namespace ::osl;
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::drafts::com::sun::star::script::framework;
+
+namespace scripting_runtimemgr
+{
+
+const char* const SCRIPTIMPLACCESS_SERVICE =
+ "drafts.com.sun.star.script.framework.storage.StorageProxy";
+const char* const SCRIPTSTORAGEMANAGER_SERVICE =
+ "/singletons/drafts.com.sun.star.script.framework.storage.theScriptStorageManager";
+const int STORAGEID = 0;
+const int STORAGEPROXY = 0;
+
+
+//*************************************************************************
+// StorageBridge Constructor
+StorageBridge::StorageBridge( const Reference< XComponentContext >& xContext,
+ sal_Int32 sid ) : m_xContext( xContext ), m_sid( sid )
+{
+ validateXRef( m_xContext, "StorageBridge::StorageBridge: invalid context" );
+ try
+ {
+ initStorage();
+ }
+ catch ( RuntimeException & re )
+ {
+ OUString temp = OUSTR( "StorageBridge::StorageBridge(salIn32&): " );
+ throw RuntimeException( temp.concat( re.Message ), Reference< XInterface >() );
+ }
+}
+
+//*************************************************************************
+void
+StorageBridge::initStorage() throw ( ::com::sun::star::uno::RuntimeException )
+{
+ try
+ {
+ Reference< lang::XMultiComponentFactory > xMultiComFac =
+ m_xContext->getServiceManager();
+ validateXRef( xMultiComFac,
+ "StorageBridge::StorageBridge: cannot get multicomponentfactory from multiservice factory" );
+ Reference< XInterface > temp;
+
+ Any a = m_xContext->getValueByName(
+ OUString::createFromAscii( SCRIPTSTORAGEMANAGER_SERVICE ) );
+ if ( sal_False == ( a >>= temp ) )
+ {
+ throw RuntimeException(
+ OUSTR( "StorageBridge::StorageBridge: could not obtain ScriptStorageManager singleton" ),
+ Reference< XInterface >() );
+ }
+ validateXRef( temp,
+ "StorageBridge::StorageBridge: cannot get Storage service" );
+ Reference< storage::XScriptStorageManager > xScriptStorageManager( temp, UNO_QUERY_THROW );
+ validateXRef( xScriptStorageManager,
+ "StorageBridge::StorageBridge: cannot get Script Storage Manager service" );
+ Reference< XInterface > xScriptStorage =
+ xScriptStorageManager->getScriptStorage( m_sid );
+ validateXRef( xScriptStorage,
+ "StorageBridge::StorageBridge: cannot get Script Storage service" );
+ m_xScriptInfoAccess =
+ Reference< storage::XScriptInfoAccess > ( xScriptStorage, UNO_QUERY_THROW );
+ }
+ catch ( RuntimeException & re )
+ {
+ OUString temp = OUSTR( "StorageBridge::StorageBridge: " );
+ throw RuntimeException( temp.concat( re.Message ), Reference< XInterface >() );
+ }
+ catch ( Exception & e )
+ {
+ OUString temp = OUSTR( "StorageBridge::StorageBridge: " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+}
+//*************************************************************************
+Sequence< ::rtl::OUString >
+StorageBridge::getScriptLogicalNames()
+throw ( lang::IllegalArgumentException,
+ RuntimeException )
+{
+ OSL_TRACE( "In StorageBridge getScriptLogicalNames...\n" );
+ Sequence < ::rtl::OUString > results;
+ try
+ {
+ results = m_xScriptInfoAccess->getScriptLogicalNames();
+ }
+ catch ( Exception e )
+ {
+ OUString temp = OUSTR( "StorageBridge::getScriptLogicalNames: " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+ return results;
+}
+
+//*************************************************************************
+Sequence < Reference< storage::XScriptInfo > >
+StorageBridge::getImplementations( const ::rtl::OUString& queryURI )
+throw ( lang::IllegalArgumentException, RuntimeException )
+{
+ OSL_TRACE( "In StorageBridge getImplementations...\n" );
+ Sequence < Reference< storage::XScriptInfo > > results;
+ try
+ {
+ results = m_xScriptInfoAccess->getImplementations( queryURI );
+ }
+ catch ( Exception e )
+ {
+ OUString temp = OUSTR( "StorageBridge::getImplementations: " );
+ throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
+ }
+ return results;
+}
+}// namespace
diff --git a/scripting/source/runtimemgr/StorageBridge.hxx b/scripting/source/runtimemgr/StorageBridge.hxx
new file mode 100644
index 000000000000..7a3547d04553
--- /dev/null
+++ b/scripting/source/runtimemgr/StorageBridge.hxx
@@ -0,0 +1,88 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: StorageBridge.hxx,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+
+#ifndef _FRAMEWORK_SCRIPT_STORAGEBRIDGE_HXX_
+#define _FRAMEWORK_SCRIPT_STORAGEBRIDGE_HXX_
+
+#include <cppuhelper/implbase1.hxx>
+#include <com/sun/star/uno/XComponentContext.hpp>
+
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfoAccess.hpp>
+#include "StorageBridgeFactory.hxx"
+
+namespace scripting_runtimemgr
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+class StorageBridge : public ::cppu::WeakImplHelper1< dcsssf::storage::XScriptInfoAccess >
+{
+ friend class StorageBridgeFactory;
+public:
+ //XScriptInfoAccess
+ //=========================================================================
+ /**
+ * Get the implementations for a given URI
+ *
+ * @param queryURI
+ * The URI to get the implementations for
+ *
+ * @return XScriptURI
+ * The URIs of the implementations
+ */
+ virtual css::uno::Sequence< css::uno::Reference< dcsssf::storage::XScriptInfo > >
+ SAL_CALL getImplementations(
+ const ::rtl::OUString& queryURI )
+ throw ( css::lang::IllegalArgumentException,
+ css::uno::RuntimeException );
+ //=========================================================================
+ /**
+ * Get the all logical names stored in this storage
+ *
+ * @return sequence < ::rtl::OUString >
+ * The logical names
+ */
+ virtual css::uno::Sequence< ::rtl::OUString >
+ SAL_CALL getScriptLogicalNames()
+ throw ( css::lang::IllegalArgumentException, css::uno::RuntimeException );
+private:
+ StorageBridge( const css::uno::Reference< css::uno::XComponentContext >& xContext,
+ sal_Int32 sid );
+
+ void initStorage() throw ( css::uno::RuntimeException );
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+ css::uno::Reference< dcsssf::storage::XScriptInfoAccess > m_xScriptInfoAccess;
+ sal_Int32 m_sid;
+};
+}
+
+#endif //_COM_SUN_STAR_SCRIPTING_STORAGEBRIDGE_HXX_
diff --git a/scripting/source/runtimemgr/StorageBridgeFactory.cxx b/scripting/source/runtimemgr/StorageBridgeFactory.cxx
new file mode 100644
index 000000000000..afcaa905d982
--- /dev/null
+++ b/scripting/source/runtimemgr/StorageBridgeFactory.cxx
@@ -0,0 +1,72 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: StorageBridgeFactory.cxx,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+
+#include "StorageBridgeFactory.hxx"
+
+#include "StorageBridge.hxx"
+
+using namespace ::drafts::com::sun::star::script::framework;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star;
+
+namespace scripting_runtimemgr
+{
+
+//*************************************************************************
+StorageBridgeFactory::StorageBridgeFactory(
+ const Reference< XComponentContext >& xContext ) :
+ m_xContext( xContext )
+{}
+
+
+
+//*************************************************************************
+// StorageBridge is a bridge between us an storage, the StorageBridge implements the
+// XScriptInfoAccess
+// interface, it allows both the "real" storage and a java test storage component to be
+// configured.
+// @param location contains a url for the document.
+// @returns a storage instance for the location "location".
+// @see StorageBridge.cxx for flag "STORAGEPROXY", set to use java "test" component or
+// use "real" storage.
+
+Reference< storage::XScriptInfoAccess >
+StorageBridgeFactory::getStorageInstance( sal_Int32 sid )
+{
+
+ Reference< storage::XScriptInfoAccess > storage = new StorageBridge( m_xContext,
+ sid ) ;
+ return storage;
+}
+} //scripting_runtimemgr
diff --git a/scripting/source/runtimemgr/StorageBridgeFactory.hxx b/scripting/source/runtimemgr/StorageBridgeFactory.hxx
new file mode 100644
index 000000000000..bda09861887b
--- /dev/null
+++ b/scripting/source/runtimemgr/StorageBridgeFactory.hxx
@@ -0,0 +1,61 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: StorageBridgeFactory.hxx,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+
+#ifndef _FRAMEWORK_SCRIPT_STORAGEBRIDGEFACTORY_HXX_
+#define _FRAMEWORK_SCRIPT_STORAGEBRIDGEFACTORY_HXX_
+
+#include <rtl/ustring>
+
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/uno/Reference.hxx>
+
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfoAccess.hpp>
+
+namespace scripting_runtimemgr
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+class StorageBridgeFactory
+{
+
+public:
+ explicit StorageBridgeFactory(
+ const css::uno::Reference < css::uno::XComponentContext > & xContext );
+ css::uno::Reference < dcsssf::storage::XScriptInfoAccess >
+ getStorageInstance( sal_Int32 sid );
+private:
+ StorageBridgeFactory(); // No definition for default ctor
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+};
+} // scripting_runtimemgr
+#endif //_FRAMEWORK_SCRIPT_NAMERESOLVER_HXX_
diff --git a/scripting/source/runtimemgr/exports.dxp b/scripting/source/runtimemgr/exports.dxp
new file mode 100644
index 000000000000..9630d7e06768
--- /dev/null
+++ b/scripting/source/runtimemgr/exports.dxp
@@ -0,0 +1,3 @@
+component_getImplementationEnvironment
+component_writeInfo
+component_getFactory
diff --git a/scripting/source/runtimemgr/makefile.mk b/scripting/source/runtimemgr/makefile.mk
new file mode 100644
index 000000000000..9c9822bf22cc
--- /dev/null
+++ b/scripting/source/runtimemgr/makefile.mk
@@ -0,0 +1,52 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.13 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+PRJ=..$/..
+
+PRJNAME= scripting
+TARGET= runtimemgr
+USE_DEFFILE= TRUE
+ENABLE_EXCEPTIONS=TRUE
+COMP1TYPELIST=$(TARGET)
+
+# --- Settings -----------------------------------------------------
+
+.INCLUDE : settings.mk
+
+# ------------------------------------------------------------------
+
+SLOFILES=\
+ $(SLO)$/ScriptNameResolverImpl.obj\
+ $(SLO)$/ScriptRuntimeManager.obj \
+
+
+# --- Targets ------------------------------------------------------
+
+.INCLUDE : target.mk
diff --git a/scripting/source/runtimemgr/runtimemgr.xml b/scripting/source/runtimemgr/runtimemgr.xml
new file mode 100755
index 000000000000..d2bfeb26e736
--- /dev/null
+++ b/scripting/source/runtimemgr/runtimemgr.xml
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE module-description PUBLIC "-//StarOffice//DTD ComponentDescription 1.0//EN" "module-description.dtd">
+<module-description xmlns:xlink="http://www.w3.org/1999/xlink">
+ <module-name> ScriptRuntimeManager </module-name>
+ <component-description>
+ <author> Alexis Ledoux</author>
+ <name> drafts.com.sun.star.script.framework.ScriptRuntimeManager </name>
+ <description>
+ This component is part of the Scripting Framework
+</description>
+ <loader-name> com.sun.star.loader.SharedLibrary </loader-name>
+ <language> c++ </language>
+ <status value="final"/>
+ <supported-service> drafts.com.sun.star.script.framework.ScriptRuntimeManager </supported-service>
+ <type> com.sun.star.lang.XSingleServiceFactory </type>
+ <type> com.sun.star.lang.XMultiComponentFactory </type>
+ <type> com.sun.star.lang.XSingleComponentFactory </type>
+ <type> com.sun.star.uno.XNamingService </type>
+ <type> com.sun.star.uno.XWeak </type>
+ <type> com.sun.star.lang.XMain </type>
+ <type> com.sun.star.uno.XAggregation </type>
+ <type> com.sun.star.lang.XMultiServiceFactory </type>
+ <type> com.sun.star.lang.XTypeProvider </type>
+ <type> com.sun.star.registry.XSimpleRegistry </type>
+ <type> com.sun.star.loader.XImplementationLoader </type>
+ <type> com.sun.star.registry.XImplementationRegistration </type>
+ <type> com.sun.star.lang.XComponent </type>
+ <type> com.sun.star.connection.XAcceptor </type>
+ <type> com.sun.star.connection.XConnector </type>
+ <type> com.sun.star.container.XHierarchicalNameAccess </type>
+ <type> com.sun.star.lang.XServiceInfo </type>
+ <type> com.sun.star.io.XOutputStream </type>
+ <type> drafts.com.sun.star.script.framework.storage.XScriptInfoAccess </type>
+ <type> drafts.com.sun.star.script.framework.storage.XScriptStorageManager </type>
+ <type> drafts.com.sun.star.script.framework.runtime.XScriptInvocation </type>
+ <type> drafts.com.sun.star.script.framework.runtime.XScriptNameResolver </type>
+ </component-description>
+ <project-build-dependency> cppuhelper </project-build-dependency>
+ <project-build-dependency> cppu </project-build-dependency>
+ <project-build-dependency> sal </project-build-dependency>
+ <runtime-module-dependency> cppuhelper$(UDK_MAJOR)$(COM) </runtime-module-dependency>
+ <runtime-module-dependency> salhelper$(UDK_MAJOR)$(COM) </runtime-module-dependency>
+ <runtime-module-dependency> cppu$(UDK_MAJOR) </runtime-module-dependency>
+ <runtime-module-dependency> reg$(UDK_MAJOR) </runtime-module-dependency>
+ <runtime-module-dependency> store$(UDK_MAJOR) </runtime-module-dependency>
+ <runtime-module-dependency> sal$(UDK_MAJOR) </runtime-module-dependency>
+</module-description>
diff --git a/scripting/source/storage/ScriptData.hxx b/scripting/source/storage/ScriptData.hxx
new file mode 100644
index 000000000000..43ab8805c54b
--- /dev/null
+++ b/scripting/source/storage/ScriptData.hxx
@@ -0,0 +1,94 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptData.hxx,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef _SCRIPTING_STORAGE_SCRIPTDATA_HXX_
+#define _SCRIPTING_STORAGE_SCRIPTDATA_HXX_
+
+#include <vector>
+#include <hash_map>
+
+#include <cppu/macros.hxx>
+#include <rtl/ustring.hxx>
+
+
+
+namespace scripting_impl
+{
+
+typedef ::std::pair< ::rtl::OUString, ::rtl::OUString > str_pair;
+typedef ::std::vector< str_pair > props_vec;
+typedef ::std::hash_map< ::rtl::OUString, props_vec, ::rtl::OUStringHash,
+ ::std::equal_to< ::rtl::OUString > > strpairvec_map;
+typedef ::std::hash_map< ::rtl::OUString, ::std::pair< ::rtl::OUString,
+ ::rtl::OUString >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > strpair_map;
+typedef ::std::hash_map< ::rtl::OUString, ::std::pair< props_vec, strpairvec_map >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > filesets_map;
+
+struct ScriptData
+{
+
+ inline ScriptData::ScriptData() SAL_THROW( () )
+ : parcelURI()
+ , language()
+ , locales()
+ , functionname()
+ , logicalname()
+ , languagedepprops()
+ , filesets()
+ {
+ }
+
+ inline ScriptData::ScriptData( const ::rtl::OUString __parcelURI,
+ const ::rtl::OUString& __language,
+ const strpair_map& __locales,
+ const ::rtl::OUString& __functionname,
+ const ::rtl::OUString& __logicalname,
+ const props_vec& __languagedepprops,
+ const filesets_map& __filesets ) SAL_THROW( () )
+ : parcelURI( __parcelURI )
+ , language( __language )
+ , locales( __locales )
+ , functionname( __functionname )
+ , logicalname( __logicalname )
+ , languagedepprops( __languagedepprops )
+ , filesets( __filesets )
+ {
+ }
+
+ ::rtl::OUString parcelURI;
+ ::rtl::OUString language;
+ strpair_map locales;
+ ::rtl::OUString functionname;
+ ::rtl::OUString logicalname;
+ props_vec languagedepprops;
+ filesets_map filesets;
+};
+} // namespace scripting_impl
+#endif // _SCRIPTING_STORAGE_ScriptData_HXX_
+
diff --git a/scripting/source/storage/ScriptElement.cxx b/scripting/source/storage/ScriptElement.cxx
new file mode 100644
index 000000000000..07c00305225e
--- /dev/null
+++ b/scripting/source/storage/ScriptElement.cxx
@@ -0,0 +1,164 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptElement.cxx,v $
+ * $Revision: 1.10 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#include "ScriptElement.hxx"
+#include <util/util.hxx>
+
+using namespace ::rtl;
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+
+typedef ::std::vector < ::std::pair < ::rtl::OUString, bool > > dependencies_vec;
+typedef ::std::vector < ::std::pair < ::rtl::OUString, ::rtl::OUString > > deliveries_vec;
+
+namespace scripting_impl
+{
+
+//*************************************************************************
+/**
+ Construct a ScriptElement from a ScriptData object
+
+ @param sII
+ the ScriptDataObject
+*/
+ScriptElement::ScriptElement( ScriptData & sII ) :
+ XMLElement( OUSTR( "parcel" ) ),
+ m_sII( sII )
+{
+ OSL_TRACE( "ScriptElement ctor called\n" );
+
+ addAttribute( OUSTR( "language" ), sII.language );
+ addAttribute( OUSTR( "xmlns:parcel" ), OUSTR( "scripting.dtd" ) );
+ XMLElement* xScriptElt = new XMLElement( OUSTR( "script" ) );
+ xScriptElt->addAttribute( OUSTR( "language" ), sII.language );
+ Reference < xml::sax::XAttributeList > xal( xScriptElt );
+ addSubElement( xal );
+
+ strpair_map::const_iterator mp_it = sII.locales.begin();
+ strpair_map::const_iterator mp_itend = sII.locales.end();
+
+ for( ; mp_it != mp_itend; ++mp_it )
+ {
+ XMLElement* xel = new XMLElement( OUSTR( "locale" ) );
+ xel->addAttribute( OUSTR( "lang" ), mp_it->first );
+
+ {
+ XMLElement* subxel = new XMLElement( OUSTR( "displayname" ) );
+ subxel->addAttribute( OUSTR( "value" ), mp_it->second.first );
+ Reference < xml::sax::XAttributeList > subxattl( subxel );
+ xel->addSubElement( subxattl );
+ }
+ {
+ XMLElement* subxel = new XMLElement( OUSTR( "description" ),
+ mp_it->second.second );
+ Reference< xml::sax::XAttributeList > subxattl( subxel );
+ xel->addSubElement( subxattl );
+ }
+
+ Reference < xml::sax::XAttributeList > xal( xel );
+ xScriptElt->addSubElement( xal );
+ }
+
+ {
+ XMLElement* xel = new XMLElement( OUSTR( "functionname" ) );
+ xel->addAttribute( OUSTR( "value" ), sII.functionname );
+ Reference < xml::sax::XAttributeList > xal( xel );
+ xScriptElt->addSubElement( xal );
+ }
+
+ {
+ XMLElement* xel = new XMLElement( OUSTR( "logicalname" ) );
+ xel->addAttribute( OUSTR( "value" ), sII.logicalname );
+ Reference < xml::sax::XAttributeList > xal( xel );
+ xScriptElt->addSubElement( xal );
+ }
+
+ props_vec::const_iterator vp_it = sII.languagedepprops.begin();
+ props_vec::const_iterator vp_itend = sII.languagedepprops.end();
+
+ if ( vp_it != vp_itend )
+ {
+ XMLElement* xel = new XMLElement( OUSTR( "languagedepprops" ) );
+
+ for( ; vp_it != vp_itend ; ++vp_it )
+ {
+ XMLElement* subxel = new XMLElement( OUSTR( "prop" ) );
+ subxel->addAttribute( OUSTR( "name" ), vp_it->first );
+ subxel->addAttribute( OUSTR( "value" ), vp_it->second );
+ Reference < xml::sax::XAttributeList > subxattl( subxel );
+ xel->addSubElement( subxattl );
+ }
+
+ Reference < xml::sax::XAttributeList > xal( xel );
+ xScriptElt->addSubElement( xal );
+ }
+
+ filesets_map::const_iterator fm_it = sII.filesets.begin();
+ filesets_map::const_iterator fm_itend = sII.filesets.end();
+
+ for( ; fm_it != fm_itend; ++fm_it )
+ {
+ XMLElement* xel = new XMLElement( OUSTR( "fileset" ) );
+ xel->addAttribute( OUSTR( "name" ), fm_it->first );
+
+ vp_it = fm_it->second.first.begin();
+ vp_itend = fm_it->second.first.end();
+
+ for( ; vp_it != vp_itend; ++vp_it )
+ {
+ XMLElement* subxel = new XMLElement( OUSTR( "prop" ) );
+ subxel->addAttribute( OUSTR( "name" ), vp_it->first );
+ subxel->addAttribute( OUSTR("value"), vp_it->second );
+ Reference < xml::sax::XAttributeList > subxattl( subxel );
+ xel->addSubElement( subxattl );
+ }
+
+ strpairvec_map::const_iterator sm_it = fm_it->second.second.begin();
+ strpairvec_map::const_iterator sm_itend = fm_it->second.second.end();
+
+ if( sm_it != sm_itend )
+ {
+ // was there a purpose for contstructing this
+ // XMLElement* subxel = new XMLElement( OUSTR( "file" ) );
+ xel->addAttribute( OUSTR( "name" ), sm_it->first );
+
+ }
+ }
+}
+
+//*************************************************************************
+ScriptElement::~ScriptElement() SAL_THROW(())
+{
+}
+
+} // namespace scripting_impl
diff --git a/scripting/source/storage/ScriptElement.hxx b/scripting/source/storage/ScriptElement.hxx
new file mode 100644
index 000000000000..77ede997832b
--- /dev/null
+++ b/scripting/source/storage/ScriptElement.hxx
@@ -0,0 +1,64 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptElement.hxx,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#ifndef _SCRIPT_FRAMEWORK_STORAGE_SCRIPT_ELEMENT_HXX_
+#define _SCRIPT_FRAMEWORK_STORAGE_SCRIPT_ELEMENT_HXX_
+
+#include <osl/mutex.hxx>
+
+#include "ScriptData.hxx"
+
+#include "XMLElement.hxx"
+
+namespace scripting_impl
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+class ScriptElement : public ::scripting_impl::XMLElement
+{
+public:
+ /**
+ Construct a ScriptElement from a ScriptData object
+
+ @param sII
+ the ScriptData Object
+ */
+ explicit ScriptElement( ScriptData & sII );
+ ~ScriptElement() SAL_THROW (());
+
+private:
+ ScriptData m_sII;
+
+};
+
+}
+
+#endif
diff --git a/scripting/source/storage/ScriptInfo.cxx b/scripting/source/storage/ScriptInfo.cxx
new file mode 100644
index 000000000000..d47bf203f301
--- /dev/null
+++ b/scripting/source/storage/ScriptInfo.cxx
@@ -0,0 +1,376 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptInfo.cxx,v $
+ * $Revision: 1.14 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include <cppuhelper/implementationentry.hxx>
+
+#include <hash_map>
+
+#include <osl/file.hxx>
+#include <cppuhelper/implbase1.hxx>
+
+#include <com/sun/star/beans/XPropertyContainer.hpp>
+#include <com/sun/star/beans/PropertyAttribute.hpp>
+
+#include <drafts/com/sun/star/script/framework/storage/XScriptStorageManager.hpp>
+
+#include <util/util.hxx>
+#include "ScriptInfo.hxx"
+
+using namespace ::rtl;
+using namespace com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::drafts::com::sun::star::script::framework;
+using namespace ::drafts::com::sun::star::script::framework::storage;
+
+namespace scripting_impl
+{
+
+typedef ::std::hash_map < ::rtl::OUString, css::uno::Any, ::rtl::OUStringHash,
+ ::std::equal_to< ::rtl::OUString > > PropertySet_hash;
+
+class PropertySetImpl : public ::cppu::WeakImplHelper1< css::beans::XPropertySet >
+{
+
+public:
+
+ PropertySetImpl();
+ ~PropertySetImpl();
+
+// XPropertySet implementation
+ virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL
+ getPropertySetInfo()
+ throw ( css::uno::RuntimeException );
+ virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName,
+ const css::uno::Any& aValue )
+ throw ( css::beans::UnknownPropertyException,
+ css::beans::PropertyVetoException,
+ css::lang::IllegalArgumentException,
+ css::lang::WrappedTargetException,
+ css::uno::RuntimeException );
+ virtual css::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )
+ throw ( css::beans::UnknownPropertyException,
+ css::lang::WrappedTargetException,
+ css::uno::RuntimeException );
+ virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName,
+ const css::uno::Reference< css::beans::XPropertyChangeListener >& xListener )
+ throw ( css::beans::UnknownPropertyException,
+ css::lang::WrappedTargetException,
+ css::uno::RuntimeException );
+ virtual void SAL_CALL removePropertyChangeListener(
+ const ::rtl::OUString& aPropertyName,
+ const css::uno::Reference< css::beans::XPropertyChangeListener >& aListener )
+ throw ( css::beans::UnknownPropertyException,
+ css::lang::WrappedTargetException,
+ css::uno::RuntimeException );
+ virtual void SAL_CALL addVetoableChangeListener(
+ const ::rtl::OUString& PropertyName,
+ const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener )
+ throw ( css::beans::UnknownPropertyException,
+ css::lang::WrappedTargetException,
+ css::uno::RuntimeException );
+ virtual void SAL_CALL removeVetoableChangeListener(
+ const ::rtl::OUString& PropertyName,
+ const css::uno::Reference< css::beans::XVetoableChangeListener >& aListener )
+ throw ( css::beans::UnknownPropertyException,
+ css::lang::WrappedTargetException,
+ css::uno::RuntimeException );
+
+private:
+ friend class ScriptInfo;
+
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+ void PropertySetImpl::privateSetPropertyValue( const ::rtl::OUString& aPropertyName, const Any& aValue )
+ throw ( beans::UnknownPropertyException, beans::PropertyVetoException,
+ lang::IllegalArgumentException, lang::WrappedTargetException,
+ RuntimeException );
+
+ osl::Mutex m_mutex;
+ PropertySet_hash m_propertyMap;
+};
+
+PropertySetImpl::PropertySetImpl()
+{
+ OSL_TRACE( "<PropertySetImpl ctor called\n" );
+}
+
+PropertySetImpl::~PropertySetImpl()
+{
+ OSL_TRACE( "<PropertySetImpl dtor called\n>" );
+}
+
+Reference< beans::XPropertySetInfo > SAL_CALL PropertySetImpl::getPropertySetInfo( )
+ throw ( RuntimeException )
+{
+ return Reference< beans::XPropertySetInfo > (); // Not supported
+}
+
+void SAL_CALL PropertySetImpl::setPropertyValue( const ::rtl::OUString& aPropertyName,
+ const Any& aValue )
+ throw ( beans::UnknownPropertyException, beans::PropertyVetoException,
+ lang::IllegalArgumentException, lang::WrappedTargetException,
+ RuntimeException )
+{
+ throw RuntimeException(
+ OUSTR( "PropertySetImpl::setPropertyValue: method not supported. Read-only PropertySet" ),
+ Reference< XInterface >() );
+}
+
+void PropertySetImpl::privateSetPropertyValue( const ::rtl::OUString& aPropertyName,
+ const Any& aValue )
+ throw ( beans::UnknownPropertyException, beans::PropertyVetoException,
+ lang::IllegalArgumentException, lang::WrappedTargetException,
+ RuntimeException )
+{
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+ m_propertyMap[ aPropertyName ] = aValue;
+}
+
+//*************************************************************************
+Any SAL_CALL PropertySetImpl::getPropertyValue( const ::rtl::OUString& PropertyName )
+ throw ( beans::UnknownPropertyException,
+ lang::WrappedTargetException, RuntimeException )
+{
+ if ( m_propertyMap.find( PropertyName ) == m_propertyMap.end() )
+ {
+ throw RuntimeException(
+
+ OUSTR( "PropertySetImpl::getPropertyValue: invalid PropertyName ").concat(
+ PropertyName),
+ Reference< XInterface >() );
+ }
+
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+ Any returnValue = m_propertyMap[ PropertyName ];
+
+ return returnValue;
+}
+
+//*************************************************************************
+void SAL_CALL PropertySetImpl::addPropertyChangeListener(
+ const ::rtl::OUString& aPropertyName,
+ const Reference< beans::XPropertyChangeListener >& xListener )
+ throw ( beans::UnknownPropertyException, lang::WrappedTargetException,
+ RuntimeException )
+{
+ throw RuntimeException(
+ OUSTR( "PropertySetImpl::addPropertyChangeListener: method not supported" ),
+ Reference< XInterface >() );
+}
+
+//*************************************************************************
+void SAL_CALL PropertySetImpl::removePropertyChangeListener(
+ const ::rtl::OUString& aPropertyName,
+ const Reference< beans::XPropertyChangeListener >& aListener )
+ throw ( beans::UnknownPropertyException, lang::WrappedTargetException,
+ RuntimeException )
+{
+ throw RuntimeException(
+ OUSTR( "PropertySetImpl::removePropertyChangeListener: method not supported" ),
+ Reference< XInterface >() );
+}
+
+//*************************************************************************
+void SAL_CALL PropertySetImpl::addVetoableChangeListener(
+ const ::rtl::OUString& PropertyName,
+ const Reference< beans::XVetoableChangeListener >& aListener )
+ throw ( beans::UnknownPropertyException, lang::WrappedTargetException,
+ RuntimeException )
+{
+ throw RuntimeException(
+ OUSTR( "PropertySetImpl::addVetoableChangeListener: method not supported" ),
+ Reference< XInterface >() );
+}
+
+//*************************************************************************
+void SAL_CALL PropertySetImpl::removeVetoableChangeListener(
+ const ::rtl::OUString& PropertyName,
+ const Reference< beans::XVetoableChangeListener >& aListener )
+ throw ( beans::UnknownPropertyException, lang::WrappedTargetException,
+ RuntimeException )
+{
+ throw RuntimeException(
+ OUSTR( "PropertySetImpl::removeVetoableChangeListener: method not supported" ),
+ Reference< XInterface >() );
+}
+
+
+//*************************************************************************
+ScriptInfo::ScriptInfo( const ScriptData & scriptData, sal_Int32 storageID )
+ : m_scriptData( scriptData ), m_storageID( storageID )
+{
+ OSL_TRACE( "< ++++++ ScriptInfo ctor called >\n" );
+ OSL_TRACE( "< ++++++ parcelURI=%s>\n",::rtl::OUStringToOString(m_scriptData.parcelURI , RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+}
+//*************************************************************************
+ScriptInfo::~ScriptInfo()
+{
+ OSL_TRACE( "< ScriptInfo dtor called >\n" );
+}
+//*************************************************************************
+OUString SAL_CALL ScriptInfo::getLogicalName( ) throw ( RuntimeException )
+{
+ OSL_TRACE( "ScriptInfo::getLogicalName() " );
+ return m_scriptData.logicalname;
+}
+
+//*************************************************************************
+OUString SAL_CALL ScriptInfo::getDescription( ) throw ( RuntimeException )
+{
+ OUString rs_desc;
+ // TDB need to determine locale here, hardcoded at the moment
+ // to english
+
+ OUString localeLang = OUString::createFromAscii( "en" );
+ strpair_map::const_iterator str_it =
+ m_scriptData.locales.find( localeLang );
+
+ if( str_it == m_scriptData.locales.end() )
+ {
+ OSL_TRACE( "No description set in meta-data" );
+ return rs_desc;
+ }
+ rs_desc = str_it->second.second;
+ return rs_desc;
+}
+
+//*************************************************************************
+OUString SAL_CALL ScriptInfo::getLanguage( ) throw ( RuntimeException )
+{
+ OSL_TRACE( "ScriptInfo::getLanguage() " );
+ return m_scriptData.language;
+}
+
+//*************************************************************************
+OUString SAL_CALL ScriptInfo::getFunctionName( ) throw ( RuntimeException )
+{
+ OSL_TRACE( "ScriptInfo::getFunctionName() " );
+ return m_scriptData.functionname;
+}
+
+//*************************************************************************
+OUString SAL_CALL ScriptInfo::getParcelURI( ) throw ( RuntimeException )
+{
+ return m_scriptData.parcelURI;
+}
+
+//*************************************************************************
+Reference< beans::XPropertySet > SAL_CALL ScriptInfo::getLanguageProperties( )
+ throw ( RuntimeException )
+{
+ PropertySetImpl* propSetImpl = new PropertySetImpl();
+ Reference< beans::XPropertySet > xPropSet = propSetImpl;
+
+ props_vec::const_iterator pv_it = m_scriptData.languagedepprops.begin();
+ props_vec::const_iterator pv_itend = m_scriptData.languagedepprops.end();
+
+ for( ; pv_it != pv_itend; ++pv_it )
+ {
+ try
+ {
+ propSetImpl->privateSetPropertyValue( pv_it->first, makeAny( pv_it->second ) );
+ }
+ catch( Exception& e )
+ {
+ OUString msg = OUSTR(
+ "ScriptInfo::getLanguage caught exception while setting property," );
+ msg = msg.concat( OUSTR( " PropertryName: " ) ).concat( pv_it->first );
+ msg = msg.concat( OUSTR( " \nException message is: " ) );
+ msg = msg.concat( e.Message );
+ throw RuntimeException( msg , Reference< XInterface >() );
+ }
+ }
+
+ return xPropSet;
+}
+//*************************************************************************
+css::uno::Sequence< ::rtl::OUString > SAL_CALL ScriptInfo::getFileSetNames()
+throw ( css::uno::RuntimeException )
+{
+ OSL_TRACE("ScriptInfo::getFileSetNames");
+ Sequence< OUString > results;
+ filesets_map::iterator fsm_it = m_scriptData.filesets.begin();
+ filesets_map::iterator fsm_itend = m_scriptData.filesets.end();
+ if( fsm_it == fsm_itend )
+ {
+ OSL_TRACE( "ScriptInfo::getFileSetNames: no filesets" );
+ return results;
+ }
+ results.realloc( m_scriptData.filesets.size() );
+ for ( sal_Int32 count = 0; fsm_it != fsm_itend; ++fsm_it )
+ {
+ OUString fileSetName = fsm_it->first;
+ OSL_TRACE( "ScriptInfo::getFileSetNames: adding name %s",
+ ::rtl::OUStringToOString( fileSetName,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ results[ count++ ] = fileSetName;
+ }
+ return results;
+}
+//*************************************************************************
+css::uno::Sequence< ::rtl::OUString > SAL_CALL
+ScriptInfo::getFilesInFileSet( const ::rtl::OUString & fileSetName )
+throw ( css::uno::RuntimeException )
+{
+ Sequence< OUString > results;
+ filesets_map::iterator fsm_it = m_scriptData.filesets.find( fileSetName );
+ filesets_map::iterator fsm_itend = m_scriptData.filesets.end();
+ if( fsm_it == fsm_itend )
+ {
+ OSL_TRACE( "ScriptInfo::getFilesInFileSet: no fileset named %s",
+ ::rtl::OUStringToOString( fileSetName,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ return results;
+ }
+
+ strpairvec_map files = fsm_it->second.second;
+ strpairvec_map::iterator spvm_it = files.begin();
+ strpairvec_map::iterator spvm_itend = files.end();
+ if( spvm_it == spvm_itend )
+ {
+ OSL_TRACE( "ScriptInfo::getFilesInFileSet: no files in fileset %s",
+ ::rtl::OUStringToOString( fileSetName,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ return results;
+ }
+ results.realloc( files.size() );
+ for( sal_Int32 count = 0; spvm_it != spvm_itend ; ++spvm_it )
+ {
+ OUString fileName = spvm_it->first;
+ OSL_TRACE( "ScriptInfo::getFilesInFileSet: adding file %s",
+ ::rtl::OUStringToOString( fileName,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ results[ count++ ] = fileName;
+ }
+ return results;
+}
+//*************************************************************************
+}
diff --git a/scripting/source/storage/ScriptInfo.hxx b/scripting/source/storage/ScriptInfo.hxx
new file mode 100644
index 000000000000..6ba4a545dd40
--- /dev/null
+++ b/scripting/source/storage/ScriptInfo.hxx
@@ -0,0 +1,78 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptInfo.hxx,v $
+ * $Revision: 1.13 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef __SCRIPT_FRAMEWORK_STORAGE_SCRIPTINFO_HXX_
+#define __SCRIPT_FRAMEWORK_STORAGE_SCRIPTINFO_HXX_
+
+#include <cppuhelper/implbase1.hxx> // helper for component factory
+
+#include <com/sun/star/beans/XPropertySet.hpp>
+
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfo.hpp>
+
+#include "ScriptData.hxx"
+
+namespace scripting_impl
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+class ScriptInfo : public ::cppu::WeakImplHelper1< dcsssf::storage::XScriptInfo >
+{
+public:
+ explicit ScriptInfo( const ScriptData & scriptData, sal_Int32 storageID );
+ virtual ~ScriptInfo();
+
+ // XScriptInfo
+ virtual ::rtl::OUString SAL_CALL getLogicalName()
+ throw ( css::uno::RuntimeException );
+ virtual ::rtl::OUString SAL_CALL getDescription()
+ throw ( css::uno::RuntimeException ) ;
+ virtual ::rtl::OUString SAL_CALL getLanguage() throw ( css::uno::RuntimeException );
+ virtual ::rtl::OUString SAL_CALL getFunctionName()
+ throw ( css::uno::RuntimeException );
+ virtual ::rtl::OUString SAL_CALL getParcelURI()
+ throw ( css::uno::RuntimeException );
+ virtual css::uno::Reference< css::beans::XPropertySet > SAL_CALL
+ getLanguageProperties() throw ( css::uno::RuntimeException );
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getFileSetNames()
+ throw ( css::uno::RuntimeException );
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL
+ getFilesInFileSet( const ::rtl::OUString & fileSetName )
+ throw ( css::uno::RuntimeException );
+
+private:
+ ScriptData m_scriptData;
+ sal_Int32 m_storageID;
+};
+
+}
+#endif // define __SCRIPTING_STORAGE...
diff --git a/scripting/source/storage/ScriptInfoImpl.hxx b/scripting/source/storage/ScriptInfoImpl.hxx
new file mode 100644
index 000000000000..6f758d24cb3b
--- /dev/null
+++ b/scripting/source/storage/ScriptInfoImpl.hxx
@@ -0,0 +1,96 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptInfoImpl.hxx,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef _SCRIPTING_STORAGE_SCRIPTINFOIMPL_HXX_
+#define _SCRIPTING_STORAGE_SCRIPTINFOIMPL_HXX_
+
+#include <vector>
+#include <map>
+
+#include <cppu/macros.hxx>
+#include <rtl/ustring.hxx>
+
+
+typedef ::std::pair< ::rtl::OUString, ::rtl::OUString > str_pair;
+typedef ::std::map< ::rtl::OUString, str_pair,
+ ::std::equal_to< ::rtl::OUString > > strpair_map;
+typedef ::std::vector< str_pair > props_vec;
+typedef ::std::map< ::rtl::OUString, ::std::pair< props_vec, strpair_map >,
+ ::std::equal_to< ::rtl::OUString > > filesets_map;
+
+namespace scripting_impl
+{
+
+struct ScriptInfoImpl
+{
+
+ inline ScriptInfoImpl::ScriptInfoImpl() SAL_THROW( () )
+ : parcelURI()
+ , language()
+ , locales()
+ , functionname()
+ , logicalname()
+ , languagedepprops()
+ , filesets()
+ {
+ }
+
+ inline ScriptInfoImpl::ScriptInfoImpl( const ::rtl::OUString __parcelURI,
+ const ::rtl::OUString& __language,
+ const strpair_map& __locales,
+ const ::rtl::OUString& __functionname,
+ const ::rtl::OUString& __logicalname,
+ const langdepprops_vec& __languagedepprops,
+ const filesets_map& __filesets ) SAL_THROW( () )
+ : parcelURI( __parcelURI )
+ , language( __language )
+ , locales( __locales )
+ , functionname( __functionname )
+ , logicalname( __logicalname )
+ , languagedepprops( __languagedepprops )
+ , filesets( __filesets )
+ {
+ }
+
+ ::rtl::OUString parcelURI;
+ ::rtl::OUString language;
+ strpair_map locales;
+ ::rtl::OUString functionname;
+ ::rtl::OUString logicalname;
+ props_vec languagedepprops;
+ filesets_map filesets;
+
+};
+
+
+} // namespace scripting_impl
+
+#endif // _SCRIPTING_STORAGE_SCRIPTINFOIMPL_HXX_
+
diff --git a/scripting/source/storage/ScriptMetadataImporter.cxx b/scripting/source/storage/ScriptMetadataImporter.cxx
new file mode 100644
index 000000000000..6b561623aa5c
--- /dev/null
+++ b/scripting/source/storage/ScriptMetadataImporter.cxx
@@ -0,0 +1,535 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptMetadataImporter.cxx,v $
+ * $Revision: 1.14 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#ifdef _DEBUG
+#include <stdio.h>
+#endif
+
+#include "ScriptMetadataImporter.hxx"
+
+#include <osl/mutex.hxx>
+
+#include <com/sun/star/xml/sax/XParser.hpp>
+#include <rtl/string.h>
+
+
+#include <util/util.hxx>
+
+using namespace ::rtl;
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+
+namespace scripting_impl
+{
+//*************************************************************************
+ScriptMetadataImporter::ScriptMetadataImporter(
+ const Reference< XComponentContext > & xContext )
+ : m_xContext( xContext )
+{
+ OSL_TRACE( "< ScriptMetadataImporter ctor called >\n" );
+ ms_localeDesc = new OUStringBuffer();
+}
+
+//*************************************************************************
+ScriptMetadataImporter::~ScriptMetadataImporter() SAL_THROW( () )
+{
+ OSL_TRACE( "< ScriptMetadataImporter dtor called >\n" );
+ delete ms_localeDesc;
+}
+
+
+//*************************************************************************
+void ScriptMetadataImporter::parseMetaData(
+ Reference< io::XInputStream > const & xInput,
+ const ::rtl::OUString & parcelURI,
+ InfoImpls_vec & io_ScriptDatas )
+ throw ( xml::sax::SAXException, io::IOException, RuntimeException )
+{
+
+ ::osl::Guard< ::osl::Mutex > aGuard( m_mutex );
+
+ mpv_ScriptDatas = &io_ScriptDatas;
+ mpv_ScriptDatas->clear();
+
+ //Set the placeholder for the parcel URI
+ ms_parcelURI = parcelURI;
+
+ //Get the parser service
+ validateXRef( m_xContext,
+ "ScriptMetadataImporter::parseMetaData: No context available" );
+
+ Reference< lang::XMultiComponentFactory > xMgr =
+ m_xContext->getServiceManager();
+
+ validateXRef( xMgr,
+ "ScriptMetadataImporter::parseMetaData: No service manager available" );
+
+ Reference< XInterface > xInterface = xMgr->createInstanceWithContext(
+ OUString::createFromAscii( "com.sun.star.xml.sax.Parser" ), m_xContext );
+
+ validateXRef( xInterface, "ScriptMetadataImporter::parseMetaData: cannot get SAX Parser" );
+ Reference< xml::sax::XParser > xParser;
+ try
+ {
+ xParser.set( xInterface ,UNO_QUERY_THROW );
+ }
+ catch (RuntimeException & re )
+ {
+ OUString msg = OUString::createFromAscii(
+ "ScriptMetadata:Importer::parserMetaData cannot get XParser" );
+ msg.concat( re.Message );
+ throw RuntimeException( msg, Reference< XInterface > () );
+ }
+
+ // xxx todo: error handler, entity resolver omitted
+ // This class is the document handler for the parser
+ Reference< xml::sax::XDocumentHandler > t_smI( this );
+ xParser->setDocumentHandler( t_smI );
+
+ //Set up the input for the parser, the XInputStream
+ xml::sax::InputSource source;
+ source.aInputStream = xInput;
+ source.sSystemId = OUSTR( "virtual file" );
+
+ OSL_TRACE( "ScriptMetadataImporter: Start the parser\n" );
+
+ try
+ {
+ xParser->parseStream( source );
+ }
+ catch ( xml::sax::SAXException & saxe )
+ {
+ OUString msg = OUString::createFromAscii(
+ "ScriptMetadata:Importer::parserMetaData SAXException" );
+ msg.concat( saxe.Message );
+ throw xml::sax::SAXException( msg, Reference< XInterface > (),
+ saxe.WrappedException );
+ }
+ catch ( io::IOException & ioe )
+ {
+ throw io::IOException( OUString::createFromAscii(
+ "ScriptMetadataImporter::parseMetaData IOException: " ) + ioe.Message,
+ Reference< XInterface > () );
+ }
+
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ throw RuntimeException( OUString::createFromAscii(
+ "ScriptMetadataImporter::parseMetadata UnknownException: " ),
+ Reference< XInterface > () );
+ }
+#endif
+
+ OSL_TRACE( "ScriptMetadataImporter: Parser finished\n ");
+
+ OSL_TRACE( "ScriptMetadataImporter: vector size is %d\n",
+ mpv_ScriptDatas->size() );
+}
+
+//*************************************************************************
+// XExtendedDocumentHandler impl
+void ScriptMetadataImporter::startCDATA()
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+ OSL_TRACE( "ScriptMetadataImporter: startCDATA()\n" );
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::endCDATA()
+ throw ( RuntimeException )
+{
+ OSL_TRACE( "ScriptMetadataImporter: endDATA()\n" );
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::comment( const ::rtl::OUString & sComment )
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+ OSL_TRACE( "ScriptMetadataImporter: comment()\n" );
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::allowLineBreak()
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+ OSL_TRACE( "ScriptMetadataImporter: allowLineBreak()\n" );
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::unknown( const ::rtl::OUString & sString )
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+ OSL_TRACE( "ScriptMetadataImporter: unknown()\n" );
+}
+
+//*************************************************************************
+// XDocumentHandler impl
+void ScriptMetadataImporter::startDocument()
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+ // Ignore for now
+ OSL_TRACE( "ScriptMetadataImporter: startDocument()\n" );
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::endDocument()
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+ // Ignore for now
+ OSL_TRACE( "ScriptMetadataImporter: endDocument()\n" );
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::startElement(
+ const ::rtl::OUString& tagName,
+ const Reference< xml::sax::XAttributeList >& xAttribs )
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+
+ OSL_TRACE( "Trace Message : ScriptMetadataImporter: startElement() %s\n",
+ ::rtl::OUStringToOString( tagName,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ ::osl::Guard< ::osl::Mutex > aGuard( m_mutex );
+
+ //Set the state of the state machine
+ setState( tagName );
+
+ //Processing the elements
+ switch( m_state )
+ {
+ case SCRIPT:
+ m_ScriptData.parcelURI = ms_parcelURI;
+ m_ScriptData.language = xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "language" ));
+ OSL_TRACE( "Trace Message: language is %s\n",
+ ::rtl::OUStringToOString( m_ScriptData.language,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ break;
+ case LOCALE:
+ ms_localeLang = xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "lang" ) );
+ OSL_TRACE( "Trace Message: Locale is %s\n",
+ ::rtl::OUStringToOString( ms_localeLang,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ break;
+ case DISPLAYNAME:
+ ms_localeDisName = xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "value" ));
+ OSL_TRACE( "Trace Message: Displyaname is %s\n",
+ ::rtl::OUStringToOString( ms_localeDisName,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ break;
+ case FUNCTIONNAME:
+ m_ScriptData.functionname = xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "value" ) );
+ OSL_TRACE( "Trace Message: Functionname is %s\n",
+ ::rtl::OUStringToOString( m_ScriptData.functionname,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ break;
+ case LOGICALNAME:
+ m_ScriptData.logicalname = xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "value" ));
+#ifdef _DEBUG
+ fprintf(stderr, "Trace Message: logicalname is %s\n",
+ ::rtl::OUStringToOString( m_ScriptData.logicalname,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+#endif
+ break;
+ case LANGDEPPROPS:
+ m_ScriptData.languagedepprops.push_back(
+ ::std::make_pair( xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "name" ) ),
+ xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "value" ) )
+ ));
+ OSL_TRACE( "Trace Message: Langdepprops is %s\t%s\n",
+ ::rtl::OUStringToOString( xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "name" ) ),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer,
+ ::rtl::OUStringToOString( xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "value" ) ),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ break;
+ case FILESET:
+ ms_filesetname = xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "name" ) );
+ OSL_TRACE( "Trace Message: filesetname is %s\n",
+ ::rtl::OUStringToOString(ms_filesetname,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ break;
+ case FILESETPROPS:
+ mv_filesetprops.push_back( ::std::make_pair(
+ xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "name" ) ),
+ xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "value" ) )
+ ));
+ OSL_TRACE( "Trace Message: filesetprops is %s\t%s\n",
+ ::rtl::OUStringToOString( xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "name" ) ),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer,
+ ::rtl::OUStringToOString( xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "value" ) ),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ break;
+ case FILES:
+ ms_filename = xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "name" ) );
+ OSL_TRACE( "Trace Message: filename is %s\n",
+ ::rtl::OUStringToOString( ms_filename,
+ RTL_TEXTENCODING_ASCII_US).pData->buffer );
+ break;
+ case FILEPROPS:
+ /**
+ mm_files.insert( strpair_pair( ms_filename,
+ str_pair( xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "name" ) ),
+ xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "value") ) )
+ )
+ );
+ */
+ mv_fileprops.push_back(str_pair( xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "name" ) ),
+ xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "value") ) ) );
+ OSL_TRACE( "Trace Message: fileprops is %s\t%s\n",
+ ::rtl::OUStringToOString( xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "name" ) ),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer,
+ ::rtl::OUStringToOString( xAttribs->getValueByName(
+ ::rtl::OUString::createFromAscii( "value" ) ),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ break;
+
+ // to prevent compiler warnings
+ case PARCEL:
+ case DESCRIPTION:
+ case LANGUAGEDEPPROPS:
+ break;
+ }
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::endElement( const ::rtl::OUString & aName )
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+
+ //The end tag of an element
+ OSL_TRACE( "ScriptMetadataImporter: endElement() %s\n",
+ ::rtl::OUStringToOString( aName,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ ::osl::Guard< ::osl::Mutex > aGuard( m_mutex );
+
+ //Set the state
+ setState( aName );
+
+
+ switch ( m_state )
+ {
+ case PARCEL:
+ break;
+ case SCRIPT:
+ // np adjust logicalName to be equal to function name
+ // as logical name concept has been removed
+ m_ScriptData.logicalname = m_ScriptData.functionname;
+ mpv_ScriptDatas->push_back( m_ScriptData );
+ m_ScriptData = ScriptData();
+ break;
+ case LOCALE:
+ m_ScriptData.locales[ ms_localeLang ] = ::std::make_pair(
+ ms_localeDisName, ms_localeDesc->makeStringAndClear().trim() );
+ break;
+ case FILESET:
+ OSL_TRACE("adding fileset %s to filesets map",
+ ::rtl::OUStringToOString( ms_filesetname,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ m_ScriptData.filesets[ ms_filesetname ] = ::std::make_pair(
+ mv_filesetprops, mm_files );
+ mm_files.clear();
+ mv_filesetprops.clear();
+ break;
+ case FILES:
+ OSL_TRACE("adding files %s to files map",
+ ::rtl::OUStringToOString( ms_filename,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ mm_files[ ms_filename ] = mv_fileprops;
+ mv_fileprops.clear();
+ break;
+ //
+ // to prevent compiler warnings
+ case DISPLAYNAME:
+ case DESCRIPTION:
+ case FUNCTIONNAME:
+ case LOGICALNAME:
+ case LANGUAGEDEPPROPS:
+ case LANGDEPPROPS:
+ case FILESETPROPS:
+ case FILEPROPS:
+ break;
+ }
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::characters( const ::rtl::OUString & aChars )
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+ OSL_TRACE( "ScriptMetadataImporter: characters()\n");
+
+ ::osl::Guard< ::osl::Mutex > aGuard( m_mutex );
+
+ switch ( m_state )
+ {
+ case DESCRIPTION:
+ //Put description into the struct
+ ms_localeDesc->append(aChars);
+ break;
+ case PARCEL:
+ case SCRIPT:
+ case LOCALE:
+ case DISPLAYNAME:
+ case FUNCTIONNAME:
+ case LOGICALNAME:
+ case LANGUAGEDEPPROPS:
+ case LANGDEPPROPS:
+ case FILESETPROPS:
+ case FILEPROPS:
+ break;
+ }
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::ignorableWhitespace(
+ const ::rtl::OUString & aWhitespaces )
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+ OSL_TRACE( "ScriptMetadataImporter: ignorableWhiteSpace()\n" );
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::processingInstruction(
+ const ::rtl::OUString & aTarget, const ::rtl::OUString & aData )
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+ OSL_TRACE( "ScriptMetadataImporter: processingInstruction()\n" );
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::setDocumentLocator(
+ const Reference< xml::sax::XLocator >& xLocator )
+ throw ( xml::sax::SAXException, RuntimeException )
+{
+ OSL_TRACE( "ScriptMetadataImporter: setDocumentLocator()\n" );
+}
+
+//*************************************************************************
+void ScriptMetadataImporter::setState( const ::rtl::OUString & tagName )
+{
+ //Set the state depending on the tag name of the current
+ //element the parser has arrived at
+ ::osl::Guard< ::osl::Mutex > aGuard( m_mutex );
+
+ if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "parcel" ) ) )
+ {
+ //Parcel tag
+ m_state = PARCEL;
+ }
+ else if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "script" ) ) )
+ {
+ m_state = SCRIPT;
+ }
+ else if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "locale" ) ) )
+ {
+ m_state = LOCALE;
+ }
+ else if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "displayname" ) ) )
+ {
+ m_state = DISPLAYNAME;
+ }
+ else if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "description" ) ) )
+ {
+ m_state = DESCRIPTION;
+ }
+ else if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "functionname" ) ) )
+ {
+ m_state = FUNCTIONNAME;
+ }
+ else if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "logicalname" ) ) )
+ {
+ m_state = LOGICALNAME;
+ }
+ else if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "languagedepprops" ) ) )
+ {
+ m_state = LANGUAGEDEPPROPS;
+ }
+ else if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "prop" ) ) )
+ {
+ if( m_state == LANGUAGEDEPPROPS )
+ {
+ m_state = LANGDEPPROPS;
+ }
+ else if( m_state == FILESET )
+ {
+ m_state = FILESETPROPS;
+ }
+ else if( m_state == FILES )
+ {
+ m_state = FILEPROPS;
+ }
+ }
+ else if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "fileset" ) ) )
+ {
+ m_state = FILESET;
+ }
+ else if( tagName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "file" ) ) )
+ {
+ m_state = FILES;
+ }
+ else
+ {
+ //If there is a tag we don't know about, throw a exception (wobbler) :)
+ ::rtl::OUString str_sax = ::rtl::OUString::createFromAscii( "No Such Tag" );
+
+ OSL_TRACE( "ScriptMetadataImporter: No Such Tag: %s\n",
+ ::rtl::OUStringToOString(
+ tagName, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ throw xml::sax::SAXException(
+ str_sax, Reference< XInterface >(), Any() );
+ }
+}
+
+}
diff --git a/scripting/source/storage/ScriptMetadataImporter.hxx b/scripting/source/storage/ScriptMetadataImporter.hxx
new file mode 100644
index 000000000000..b9cef3334054
--- /dev/null
+++ b/scripting/source/storage/ScriptMetadataImporter.hxx
@@ -0,0 +1,254 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptMetadataImporter.hxx,v $
+ * $Revision: 1.9 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#ifndef _SCRIPTING_STORAGE_SCRIPTMETADATAIMPORTER_HXX_
+#define _SCRIPTING_STORAGE_SCRIPTMETADATAIMPORTER_HXX_
+
+#include <vector>
+
+#include <rtl/ustring.h>
+#include <rtl/ustrbuf.hxx>
+#include <osl/mutex.hxx>
+#include <cppuhelper/implbase1.hxx> // helper for component factory
+
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XInitialization.hpp>
+#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+
+#include "ScriptData.hxx"
+
+namespace scripting_impl
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+typedef ::std::vector< ScriptData > InfoImpls_vec;
+typedef ::std::pair< ::rtl::OUString, ::std::pair< ::rtl::OUString,
+ ::rtl::OUString > > strpair_pair;
+
+/**
+ * Script Meta Data Importer
+ */
+class ScriptMetadataImporter : public
+ ::cppu::WeakImplHelper1< css::xml::sax::XExtendedDocumentHandler >
+{
+public:
+
+ /**
+ * This function will begin the parser and parse the meta data
+ *
+ * @param xInput The XInputStream for the parser which contains the XML
+ * @param parcelURI The parcel's URI in the document or the application
+ *
+ * @see css::io::XInputStream
+ */
+ void parseMetaData( css::uno::Reference< css::io::XInputStream >
+ const & xInput, const ::rtl::OUString & parcelURI,
+ InfoImpls_vec & io_ScriptDatas )
+ throw ( css::xml::sax::SAXException, css::io::IOException,
+ css::uno::RuntimeException );
+
+ /**
+ * Constructor for the meta-data parser
+ *
+ * @param XComponentContext
+ */
+ explicit ScriptMetadataImporter(
+ const css::uno::Reference< css::uno::XComponentContext >& );
+
+ /**
+ * Destructor for the parser
+ */
+ virtual ~ScriptMetadataImporter() SAL_THROW( () );
+
+ // XExtendedDocumentHandler impl
+ /**
+ * Function to handle the start of CDATA in XML
+ *
+ * @see com::sun::star::xml::sax::XExtendedDocumentHandler
+ */
+ virtual void SAL_CALL startCDATA()
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+ /**
+ * Function to handle the end of CDATA in XML
+ *
+ * @see com::sun::star::xml::sax::XExtendedDocumentHandler
+ */
+ virtual void SAL_CALL endCDATA() throw ( css::uno::RuntimeException );
+
+ /**
+ * Function to handle comments in XML
+ *
+ * @see com::sun::star::xml::sax::XExtendedDocumentHandler
+ */
+ virtual void SAL_CALL comment( const ::rtl::OUString & sComment )
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+ /**
+ * Function to handle line breaks in XML
+ *
+ * @see com::sun::star::xml::sax::XExtendedDocumentHandler
+ */
+ virtual void SAL_CALL allowLineBreak()
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+ /**
+ * Function to handle unknowns in XML
+ *
+ * @see com::sun::star::xml::sax::XExtendedDocumentHandler
+ */
+ virtual void SAL_CALL unknown( const ::rtl::OUString & sString )
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+ /**
+ * Function to handle the start of XML document
+ *
+ * @see com::sun::star::xml::sax::XExtendedDocumentHandler
+ */
+ // XDocumentHandler impl
+ virtual void SAL_CALL startDocument()
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+ /**
+ * Function to handle the end of the XML document
+ *
+ * @see com::sun::star::xml::sax::XDocumentHandler
+ */
+ virtual void SAL_CALL endDocument()
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+ /**
+ * Function to handle the start of an element
+ *
+ * @see com::sun::star::xml::sax::XDocumentHandler
+ */
+ virtual void SAL_CALL startElement( const ::rtl::OUString& aName,
+ const css::uno::Reference< css::xml::sax::XAttributeList > & xAttribs )
+ throw ( css::xml::sax::SAXException,
+ css::uno::RuntimeException );
+
+ /**
+ * Function to handle the end of an element
+ *
+ * @see com::sun::star::xml::sax::XDocumentHandler
+ */
+ virtual void SAL_CALL endElement( const ::rtl::OUString & aName )
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+ /**
+ * Function to handle characters in elements
+ *
+ * @see com::sun::star::xml::sax::XDocumentHandler
+ */
+ virtual void SAL_CALL characters( const ::rtl::OUString & aChars )
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+ /**
+ * Function to handle whitespace
+ *
+ * @see com::sun::star::xml::sax::XDocumentHandler
+ */
+ virtual void SAL_CALL ignorableWhitespace( const ::rtl::OUString & aWhitespaces )
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+ /**
+ * Function to handle XML processing instructions
+ *
+ * @see com::sun::star::xml::sax::XDocumentHandler
+ */
+ virtual void SAL_CALL processingInstruction(
+ const ::rtl::OUString & aTarget, const ::rtl::OUString & aData )
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+ /**
+ * Function to set the document locator
+ *
+ * @see com::sun::star::xml::sax::XDocumentHandler
+ */
+ virtual void SAL_CALL setDocumentLocator(
+ const css::uno::Reference< css::xml::sax::XLocator >& xLocator )
+ throw ( css::xml::sax::SAXException, css::uno::RuntimeException );
+
+
+
+private:
+
+ /** Vector contains the ScriptData structs */
+ InfoImpls_vec* mpv_ScriptDatas;
+
+ /** @internal */
+ osl::Mutex m_mutex;
+
+ /** @internal */
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+
+ /** Placeholder for the parcel URI */
+ ::rtl::OUString ms_parcelURI;
+
+ /** States for state machine during parsing */
+ enum { PARCEL, SCRIPT, LOCALE, DISPLAYNAME, DESCRIPTION, FUNCTIONNAME,
+ LOGICALNAME, LANGUAGEDEPPROPS, LANGDEPPROPS, FILESET, FILESETPROPS,
+ FILES, FILEPROPS } m_state;
+
+ /** Build up the struct during parsing the meta data */
+ ScriptData m_ScriptData;
+
+ /** @internal */
+ ::rtl::OUString ms_localeLang;
+ ::rtl::OUString ms_localeDisName;
+ ::rtl::OUStringBuffer *ms_localeDesc;
+
+ props_vec mv_filesetprops;
+
+ ::rtl::OUString ms_filename;
+ ::rtl::OUString ms_filesetname;
+
+ props_vec mv_fileprops;
+
+ strpairvec_map mm_files;
+
+ InfoImpls_vec mv_ScriptDatas;
+
+ /**
+ * Helper function to set the state
+ *
+ * @param tagName
+ * The current tag being processed
+ */
+ void setState(const ::rtl::OUString & tagName);
+}
+; // class ScriptMetadataImporter
+
+}
+
+#endif
diff --git a/scripting/source/storage/ScriptSecurityManager.cxx b/scripting/source/storage/ScriptSecurityManager.cxx
new file mode 100755
index 000000000000..681039b40b27
--- /dev/null
+++ b/scripting/source/storage/ScriptSecurityManager.cxx
@@ -0,0 +1,608 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptSecurityManager.cxx,v $
+ * $Revision: 1.23 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#include <com/sun/star/lang/XMultiComponentFactory.hpp>
+#include <com/sun/star/lang/XMultiServiceFactory.hpp>
+#include <com/sun/star/lang/XComponent.hpp>
+#include <com/sun/star/lang/WrappedTargetException.hpp>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/beans/PropertyValue.hpp>
+#include <com/sun/star/beans/UnknownPropertyException.hpp>
+#include <com/sun/star/container/XNameReplace.hpp>
+#include <com/sun/star/util/XChangesBatch.hpp>
+#include <com/sun/star/util/XMacroExpander.hpp>
+#include <com/sun/star/util/XStringSubstitution.hpp>
+#include <com/sun/star/awt/XDialog.hpp>
+#include <com/sun/star/security/AccessControlException.hpp>
+#include <com/sun/star/security/RuntimePermission.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptStorageManager.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfoAccess.hpp>
+#include "ScriptSecurityManager.hxx"
+#include <util/util.hxx>
+#include <util/scriptingconstants.hxx>
+
+
+using namespace ::rtl;
+using namespace ::osl;
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::drafts::com::sun::star::script::framework;
+
+// is this in the utils?
+const char* const SCRIPTSTORAGEMANAGER_SERVICE =
+ "/singletons/drafts.com.sun.star.script.framework.storage.theScriptStorageManager";
+
+namespace scripting_securitymgr
+{
+
+static OUString s_configProv = ::rtl::OUString::createFromAscii(
+ "com.sun.star.configuration.ConfigurationProvider");
+
+static OUString s_configAccess = ::rtl::OUString::createFromAscii(
+ "com.sun.star.configuration.ConfigurationAccess");
+
+static OUString s_configUpdate = ::rtl::OUString::createFromAscii(
+ "com.sun.star.configuration.ConfigurationUpdateAccess");
+
+static OUString s_securityDialog = ::rtl::OUString::createFromAscii(
+ "com.sun.star.script.framework.security.SecurityDialog");
+
+static const int PERMISSION_NEVER = 0;
+static const int PERMISSION_PATHLIST = 1;
+static const int PERMISSION_ALWAYS = 2;
+
+static const int ALLOW_RUN = 1;
+static const int ADD_TO_PATH = 2;
+
+//*************************************************************************
+// ScriptSecurityManager Constructor
+ScriptSecurityManager::ScriptSecurityManager(
+ const Reference< XComponentContext > & xContext ) throw ( RuntimeException )
+ : m_xContext( xContext)
+{
+ OSL_TRACE( "< ScriptSecurityManager ctor called >\n" );
+ validateXRef( m_xContext,
+ "ScriptSecurityManager::ScriptSecurityManager: invalid context" );
+
+ // get the service manager from the context
+ Reference< lang::XMultiComponentFactory > xMgr = m_xContext->getServiceManager();
+ validateXRef( xMgr,
+ "ScriptSecurityManager::ScriptSecurityManager: cannot get ServiceManager" );
+
+ // create an instance of the ConfigurationProvider
+ Reference< XInterface > xInterface = xMgr->createInstanceWithContext(
+ s_configProv, m_xContext );
+ validateXRef( xInterface,
+ "ScriptSecurityManager::ScriptSecurityManager: cannot get ConfigurationProvider" );
+ // create an instance of the ConfigurationAccess for accessing the
+ // scripting security settings
+ m_xConfigProvFactory = Reference < lang::XMultiServiceFactory > ( xInterface, UNO_QUERY );
+ validateXRef( m_xConfigProvFactory,
+ "ScriptSecurityManager::ScriptSecurityManager: cannot get XMultiServiceFactory interface from ConfigurationProvider" );
+
+}
+
+void ScriptSecurityManager::addScriptStorage( rtl::OUString scriptStorageURL,
+ sal_Int32 storageID)
+throw ( RuntimeException )
+{
+ Permission_Hash::const_iterator ph_it = m_permissionSettings.find( scriptStorageURL );
+ if ( ph_it != m_permissionSettings.end() )
+ {
+ OSL_TRACE( "ScriptSecurityManager::addScriptStorage: already called for %s",
+ ::rtl::OUStringToOString( scriptStorageURL,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer);
+ return;
+ }
+ StoragePerm newPerm;
+ newPerm.scriptStorageURL=scriptStorageURL;
+ newPerm.storageID=storageID;
+
+ // we err on the side of caution!!
+ newPerm.execPermission=sal_False;
+
+ //need to check if storage has any scripts
+ try
+ {
+ /* need to replace this with something better, now logical names are
+ * gone
+
+ Reference< XInterface > xInterface;
+ Any a = m_xContext->getValueByName(
+ OUString::createFromAscii( SCRIPTSTORAGEMANAGER_SERVICE ) );
+ if ( sal_False == ( a >>= xInterface ) )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager::addScriptStorage: could not obtain ScriptStorageManager singleton" ),
+ Reference< XInterface >() );
+ }
+ validateXRef( xInterface,
+ "ScriptSecurityManager::addScriptStorage: cannot get Storage service" );
+ Reference< storage::XScriptStorageManager > xScriptStorageManager(
+ xInterface, UNO_QUERY_THROW );
+ Reference< XInterface > xScriptStorage =
+ xScriptStorageManager->getScriptStorage( storageID );
+ validateXRef( xScriptStorage,
+ "ScriptNameResolverImpl::getStorageInstance: cannot get Script Storage service" );
+ Reference< storage::XScriptInfoAccess > xScriptInfoAccess =
+ Reference< storage::XScriptInfoAccess > ( xScriptStorage,
+ UNO_QUERY_THROW );
+ Sequence< ::rtl::OUString > logicalNames = xScriptInfoAccess->getScriptLogicalNames();
+ if( !logicalNames.getLength() ) // we have no logical names
+ {
+ return;
+ } */
+
+ // we have some scripts so read config & decide on that basis
+ // Setup flags: m_runMacroSetting, m_warning, m_confirmationRequired,
+ readConfiguration();
+ }
+ catch ( RuntimeException & rte )
+ {
+ OSL_TRACE( "ScriptSecurityManager::addScriptStorage: caught RuntimeException: %s",
+ ::rtl::OUStringToOString( rte.Message,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer);
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager::addScriptStorage: caught RuntimeException" ).concat( rte.Message ),
+ Reference< XInterface >() );
+ }
+
+ switch( m_runMacroSetting )
+ {
+ case PERMISSION_NEVER: // never
+ {
+ OSL_TRACE("never run");
+ break;
+ }
+ case PERMISSION_PATHLIST: // according to path list
+ {
+ OSL_TRACE("according to path");
+ // check path
+ rtl::OUString path = scriptStorageURL.copy( 0, scriptStorageURL.lastIndexOf( '/' ) );
+ OSL_TRACE( "no of elts in path list = %d",
+ (int)m_secureURL.getLength() );
+ bool match = isSecureURL( path );
+ if( match && ( m_warning == sal_True ) )
+ {
+ OSL_TRACE("path match & warning dialog");
+ int result = (int)executeStandardDialog();
+ OSL_TRACE("result = %d", (int)result);
+ if ( (result&ALLOW_RUN) == ALLOW_RUN )
+ {
+ newPerm.execPermission=sal_True;
+ }
+ break;
+ }
+ else if ( match )
+ {
+ OSL_TRACE("path match & no warning dialog");
+ newPerm.execPermission=sal_True;
+ break;
+ }
+ else if( m_confirmationRequired == sal_True )
+ {
+ OSL_TRACE("no path match & confirmation dialog");
+ int result = (int)executePathDialog( path );
+ OSL_TRACE("result = %d", (int)result);
+ if ( (result&ALLOW_RUN) == ALLOW_RUN )
+ {
+ newPerm.execPermission=sal_True;
+ }
+ if ( (result&ADD_TO_PATH) == ADD_TO_PATH )
+ {
+ /* if checkbox clicked then need to add path to registry*/
+ addToSecurePaths(path);
+ }
+ }
+ break;
+ }
+ case PERMISSION_ALWAYS: // always
+ if( m_warning == sal_True )
+ {
+ OSL_TRACE("always & warning dialog");
+ short result = executeStandardDialog();
+ if ( (result&ALLOW_RUN) == ALLOW_RUN )
+ {
+ newPerm.execPermission=sal_True;
+ }
+ }
+ else
+ {
+ OSL_TRACE("always & no warning dialog");
+ newPerm.execPermission=sal_True;
+ }
+ break;
+ default:
+ //
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager::addScriptStorage got invalid OfficeBasic setting"),
+ Reference< XInterface > ());
+ }
+
+ if ( newPerm.execPermission == sal_True )
+ {
+ OSL_TRACE("setting exec permission to true for %s",
+ ::rtl::OUStringToOString( scriptStorageURL,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }
+ else
+ {
+ OSL_TRACE("setting exec permission to false for %s",
+ ::rtl::OUStringToOString( scriptStorageURL,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }
+
+ m_permissionSettings[ scriptStorageURL ] = newPerm;
+}
+
+bool ScriptSecurityManager::isSecureURL( const OUString & path )
+{
+ bool match = false;
+ OSL_TRACE( "no of elts in path list = %d",
+ (int)m_secureURL.getLength() );
+ OSL_TRACE("document path: %s",
+ ::rtl::OUStringToOString( path,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer);
+ int length = m_secureURL.getLength();
+ for( int j = 0; j < length ; j++ )
+ {
+ OSL_TRACE("path list element: %s",
+ ::rtl::OUStringToOString( m_secureURL[j],
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer);
+#ifdef WIN32
+ OSL_TRACE("case insensitive comparison");
+ if( path.equalsIgnoreAsciiCase( m_secureURL[j] ) )
+#else
+ OSL_TRACE("case sensitive comparison");
+ if( path.equals( m_secureURL[j] ) )
+#endif
+ {
+ match = true;
+ break;
+ }
+ }
+ return match;
+}
+
+short ScriptSecurityManager::executeStandardDialog()
+throw ( RuntimeException )
+{
+ OUString dummyString;
+ return executeDialog( dummyString );
+}
+
+short ScriptSecurityManager::executePathDialog( const OUString & path )
+throw ( RuntimeException )
+{
+ return executeDialog( path );
+}
+
+short ScriptSecurityManager::executeDialog( const OUString & path )
+throw ( RuntimeException )
+{
+ Sequence < Any > aArgs;
+ if( path.getLength() != 0 )
+ {
+ OSL_TRACE("reallocing");
+ aArgs.realloc(1);
+ aArgs[ 0 ] <<= path;
+ }
+ short result;
+ try
+ {
+ Reference< lang::XMultiComponentFactory > xMgr = m_xContext->getServiceManager();
+ validateXRef( xMgr,
+ "ScriptSecurityManager::executeDialog: cannot get ServiceManager" );
+ Reference< XInterface > xInterface =
+ xMgr->createInstanceWithArgumentsAndContext( s_securityDialog,
+ aArgs, m_xContext );
+ validateXRef( xInterface, "ScriptSecurityManager::executeDialog: Can't create SecurityDialog" );
+ Reference< awt::XDialog > xDialog( xInterface, UNO_QUERY_THROW );
+ result = xDialog->execute();
+ Reference< lang::XComponent > xComponent( xInterface, UNO_QUERY_THROW );
+ validateXRef( xInterface, "ScriptSecurityManager::executeDialog: Can't get XComponent to dispose dialog" );
+ xComponent->dispose();
+ }
+ catch ( RuntimeException & rte )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager::executeDialog: caught RuntimeException: ").concat( rte.Message ),
+ Reference< XInterface > ());
+ }
+ catch ( Exception & e )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager::executeDialog: caught Exception: ").concat( e.Message ),
+ Reference< XInterface > ());
+ }
+ return result;
+}
+
+/**
+ * checks to see whether the requested ScriptPermission is allowed.
+ * This was modelled after the Java AccessController, but at this time
+ * we can't see a good reason not to return a bool, rather than throw
+ * an exception if the request is not granted (as is the case in Java).
+ */
+void ScriptSecurityManager::checkPermission( const OUString & scriptStorageURL,
+ const OUString & permissionRequest )
+ throw ( RuntimeException, lang::IllegalArgumentException, security::AccessControlException )
+{
+ if( permissionRequest.equals( OUString::createFromAscii( "execute" ) ) )
+ {
+ OSL_TRACE(
+ "ScriptSecurityManager::checkPermission: execute permission request for %s",
+ ::rtl::OUStringToOString( scriptStorageURL,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer);
+ Permission_Hash::const_iterator ph_it = m_permissionSettings.find( scriptStorageURL );
+ Permission_Hash::const_iterator ph_itend =
+ m_permissionSettings.end();
+ if ( ph_it != ph_itend )
+ {
+ if ( ph_it->second.execPermission )
+ {
+ return;
+ }
+ else
+ {
+ OSL_TRACE( "permission refused" );
+ Any aPermission;
+ security::RuntimePermission permission;
+ permission.Name = OUString::createFromAscii( "execute" ).concat( scriptStorageURL );
+ aPermission <<= permission;
+ throw security::AccessControlException(
+ OUString::createFromAscii( "ScriptSecurityManager::checkPermission: no execute permission for URL" ).concat( scriptStorageURL ),
+ Reference< XInterface > (), aPermission );
+ }
+ }
+ // we should never get here!!
+ throw lang::IllegalArgumentException( OUString::createFromAscii( "ScriptSecurityManager::checkPermission: storageURL not found" ), Reference< XInterface > (), 0 );
+ }
+ // inappropriate permission request
+ throw lang::IllegalArgumentException( OUString::createFromAscii( "ScriptSecurityManager::checkPermission: storageURL not found" ), Reference< XInterface > (), 1 );
+}
+
+void ScriptSecurityManager::removePermissionSettings ( ::rtl::OUString & scriptStorageURL )
+{
+ Permission_Hash::const_iterator ph_it =
+ m_permissionSettings.find( scriptStorageURL );
+
+ if ( ph_it == m_permissionSettings.end() )
+ {
+ OSL_TRACE( "Entry for storage url %s doesn't exist in map",
+ ::rtl::OUStringToOString( scriptStorageURL,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer);
+ return;
+ }
+
+ // erase the entry from the hash
+ m_permissionSettings.erase( scriptStorageURL );
+
+}
+
+void ScriptSecurityManager::readConfiguration()
+ throw ( RuntimeException)
+{
+ Reference< XInterface > xInterface;
+ try
+ {
+ beans::PropertyValue configPath;
+ configPath.Name = ::rtl::OUString::createFromAscii( "nodepath" );
+ configPath.Value <<= ::rtl::OUString::createFromAscii( "org.openoffice.Office.Common/Security/Scripting" );
+ Sequence < Any > aargs( 1 );
+ aargs[ 0 ] <<= configPath;
+ validateXRef( m_xConfigProvFactory,
+ "ScriptSecurityManager::readConfiguration: ConfigProviderFactory no longer valid!" );
+ xInterface = m_xConfigProvFactory->createInstanceWithArguments( s_configAccess,
+ aargs );
+ validateXRef( xInterface,
+ "ScriptSecurityManager::readConfiguration: cannot get ConfigurationAccess" );
+ // get the XPropertySet interface from the ConfigurationAccess service
+ Reference < beans::XPropertySet > xPropSet( xInterface, UNO_QUERY );
+ Any value;
+
+ value=xPropSet->getPropertyValue( OUSTR( "Confirmation" ) );
+ if ( sal_False == ( value >>= m_confirmationRequired ) )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager:readConfiguration: can't get Confirmation setting" ),
+ Reference< XInterface > () );
+ }
+ if ( m_confirmationRequired == sal_True )
+ {
+ OSL_TRACE( "ScriptSecurityManager:readConfiguration: confirmation is true" );
+ }
+ else
+ {
+ OSL_TRACE( "ScriptSecurityManager:readConfiguration: confirmation is false" );
+ }
+ value=xPropSet->getPropertyValue( OUSTR( "Warning" ) );
+ if ( sal_False == ( value >>= m_warning ) )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager:readConfiguration: can't get Warning setting" ),
+ Reference< XInterface > () );
+ }
+ if ( m_warning == sal_True )
+ {
+ OSL_TRACE( "ScriptSecurityManager:readConfiguration: warning is true" );
+ }
+ else
+ {
+ OSL_TRACE( "ScriptSecurityManager:readConfiguration: warning is false" );
+ }
+ value=xPropSet->getPropertyValue( OUSTR( "OfficeBasic" ) );
+ if ( sal_False == ( value >>= m_runMacroSetting ) )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager:readConfiguration: can't get OfficeBasic setting" ),
+ Reference< XInterface > () );
+ }
+ OSL_TRACE( "ScriptSecurityManager:readConfiguration: OfficeBasic = %d", m_runMacroSetting );
+ value=xPropSet->getPropertyValue( OUSTR( "SecureURL" ) );
+ if ( sal_False == ( value >>= m_secureURL ) )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager:readConfiguration: can't get SecureURL setting" ),
+ Reference< XInterface > () );
+ }
+ }
+ catch ( beans::UnknownPropertyException & upe )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager:readConfiguration: Attempt to read unknown property: " ).concat( upe.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( lang::WrappedTargetException & wte )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager:readConfiguration: wrapped target exception? :" ).concat( wte.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( Exception & e )
+ {
+ OSL_TRACE( "Unknown exception in readconf: %s",
+ ::rtl::OUStringToOString(e.Message ,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager:readConfiguration: exception? :" ).concat( e.Message ),
+ Reference< XInterface > () );
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ OSL_TRACE( "Completely Unknown exception in readconf!!!!!!");
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager:readConfiguration: exception? :" ),
+ Reference< XInterface > () );
+ }
+#endif
+
+ int length = m_secureURL.getLength();
+
+ // PathSubstitution needed to interpret variables found in config
+ Reference< lang::XMultiComponentFactory > xMgr = m_xContext->getServiceManager();
+ validateXRef( xMgr,
+ "ScriptSecurityManager::readConfiguration: cannot get XMultiComponentFactory" );
+ xInterface = xMgr->createInstanceWithContext(
+ ::rtl::OUString::createFromAscii(
+ "com.sun.star.util.PathSubstitution"), m_xContext);
+ validateXRef( xInterface,
+ "ScriptSecurityManager::readConfiguration: cannot get ConfigurationProvider" );
+ Reference< util::XStringSubstitution > xStringSubstitution(
+ xInterface, UNO_QUERY);
+ validateXRef( xStringSubstitution,
+ "ScriptSecurityManager::readConfiguration: cannot get ConfigurationProvider" );
+ for( int i = 0; i < length; i++ )
+ {
+ OSL_TRACE( "ScriptSecurityManager:readConfiguration path = %s",
+ ::rtl::OUStringToOString(m_secureURL[i] ,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ OSL_TRACE( "ScriptSecurityManager: subpath = %s",
+ ::rtl::OUStringToOString(
+ xStringSubstitution->substituteVariables( m_secureURL[i], true ),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ m_secureURL[i] = xStringSubstitution->substituteVariables( m_secureURL[i], true );
+ }
+#ifdef _DEBUG
+ int length2 = m_secureURL.getLength();
+ for( int j = 0; j < length2 ; j++ )
+ {
+ OSL_TRACE( "ScriptSecurityManager: path = %s",
+ ::rtl::OUStringToOString(m_secureURL[j] ,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }
+#endif
+}
+
+void ScriptSecurityManager::addToSecurePaths( const OUString & path )
+throw ( RuntimeException )
+{
+ OSL_TRACE( "--->ScriptSecurityManager::addToSecurePaths" );
+ beans::PropertyValue configPath;
+ configPath.Name = ::rtl::OUString::createFromAscii( "nodepath" );
+ configPath.Value <<= ::rtl::OUString::createFromAscii( "org.openoffice.Office.Common/Security/Scripting" );
+ Sequence < Any > aargs( 1 );
+ aargs[ 0 ] <<= configPath;
+ Reference< XInterface > xInterface = m_xConfigProvFactory->createInstanceWithArguments( s_configUpdate,
+ aargs );
+ validateXRef( xInterface,
+ "ScriptSecurityManager::addToSecurePaths: ScriptSecurityManager: cannot get ConfigurationUpdateAccess" );
+ Reference < container::XNameReplace > xNameReplace( xInterface, UNO_QUERY );
+ validateXRef( xNameReplace,
+ "ScriptSecurityManager::addToSecurePaths: ScriptSecurityManager: cannot get XNameReplace" );
+ Reference < util::XChangesBatch > xChangesBatch( xInterface, UNO_QUERY );
+ validateXRef( xChangesBatch,
+ "ScriptSecurityManager::addToSecurePaths: cannot get XChangesBatch" );
+
+ OSL_TRACE( "--->ScriptSecurityManager::addToSecurePaths: after if stuff" );
+ Reference < beans::XPropertySet > xPropSet( xInterface, UNO_QUERY );
+ css::uno::Sequence< rtl::OUString > newSecureURL;
+ Any value;
+ OUString pathListPropName = OUSTR ( "SecureURL" );
+ value=xPropSet->getPropertyValue( pathListPropName );
+ if ( sal_False == ( value >>= newSecureURL ) )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager::addToSecurePaths: can't get SecureURL setting" ),
+ Reference< XInterface > () );
+ }
+ try
+ {
+ sal_Int32 length = newSecureURL.getLength();
+ newSecureURL.realloc( length + 1 );
+ newSecureURL[ length ] = path;
+ Any aNewSecureURL;
+ aNewSecureURL <<= newSecureURL;
+ xNameReplace->replaceByName( pathListPropName, aNewSecureURL );
+ xChangesBatch->commitChanges();
+ m_secureURL = newSecureURL;
+ }
+ catch ( Exception & e )
+ {
+ OSL_TRACE( "Error updating secure paths: " );
+ throw RuntimeException(
+ OUSTR( "ScriptSecurityManager::addToSecurePaths: error updating SecureURL setting" ).concat( e.Message ),
+ Reference< XInterface > () );
+ }
+}
+
+//*************************************************************************
+// ScriptSecurityManager Destructor
+ScriptSecurityManager::~ScriptSecurityManager()
+{
+ OSL_TRACE( "< ScriptSecurityManager dtor called >\n" );
+}
+
+} // Namespace
diff --git a/scripting/source/storage/ScriptSecurityManager.hxx b/scripting/source/storage/ScriptSecurityManager.hxx
new file mode 100755
index 000000000000..2368cd1ee6ef
--- /dev/null
+++ b/scripting/source/storage/ScriptSecurityManager.hxx
@@ -0,0 +1,102 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptSecurityManager.hxx,v $
+ * $Revision: 1.13 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+
+#ifndef _FRAMEWORK_SCRIPT_SCRIPTSECURITYMANAGER_HXX_
+#define _FRAMEWORK_SCRIPT_SCRIPTSECURITYMANAGER_HXX_
+
+#include <hash_map>
+#include <rtl/ustring.hxx>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+#include <com/sun/star/security/AccessControlException.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfo.hpp>
+
+namespace scripting_securitymgr
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+struct StoragePerm {
+ rtl::OUString scriptStorageURL;
+ sal_Int32 storageID;
+ sal_Bool execPermission;
+};
+
+typedef ::std::hash_map< ::rtl::OUString, StoragePerm, ::rtl::OUStringHash,
+ ::std::equal_to< ::rtl::OUString > > Permission_Hash;
+/**
+ * Class responsible for managing the ScriptSecurity.
+ */
+class ScriptSecurityManager
+{
+public:
+ explicit ScriptSecurityManager(
+ const css::uno::Reference< css::uno::XComponentContext > & xContext )
+ throw ( css::uno::RuntimeException );
+ ~ScriptSecurityManager();
+ void addScriptStorage( rtl::OUString scriptStorageURL, sal_Int32 storageID)
+ throw ( css::uno::RuntimeException );
+/**
+ * checks to see if the requested permission can be granted
+ * checks to see whether the requested ScriptPeremission is allowed.
+ */
+ void checkPermission( const rtl::OUString & scriptStorageURL,
+ const rtl::OUString & permissionRequest )
+ throw ( css::uno::RuntimeException, css::lang::IllegalArgumentException,
+ css::security::AccessControlException );
+ void removePermissionSettings ( ::rtl::OUString & scriptStorageURL );
+private:
+ void readConfiguration() throw (css::uno::RuntimeException);
+
+ short executeDialog ( const rtl::OUString & path )
+ throw (css::uno::RuntimeException);
+ short executeStandardDialog()
+ throw ( css::uno::RuntimeException );
+ short executePathDialog(const rtl::OUString & path)
+ throw ( css::uno::RuntimeException );
+
+ void addToSecurePaths ( const rtl::OUString & path )
+ throw (css::uno::RuntimeException);
+ bool isSecureURL( const rtl::OUString & path );
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+ sal_Bool m_confirmationRequired;
+ sal_Bool m_warning;
+ sal_Int32 m_runMacroSetting;
+ css::uno::Reference< css::lang::XMultiServiceFactory > m_xConfigProvFactory;
+ css::uno::Sequence< rtl::OUString > m_secureURL;
+ Permission_Hash m_permissionSettings;
+
+};
+} // scripting_securitymgr
+
+#endif //_FRAMEWORK_SCRIPT_SCRIPTSECURITYMANAGER_HXX_
diff --git a/scripting/source/storage/ScriptStorage.cxx b/scripting/source/storage/ScriptStorage.cxx
new file mode 100644
index 000000000000..0dce68632ef8
--- /dev/null
+++ b/scripting/source/storage/ScriptStorage.cxx
@@ -0,0 +1,898 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptStorage.cxx,v $
+ * $Revision: 1.32 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include <osl/file.hxx>
+#include <osl/time.h>
+#include <cppuhelper/implementationentry.hxx>
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+#include <com/sun/star/ucb/CommandAbortedException.hpp>
+#include <com/sun/star/io/XActiveDataSource.hpp>
+#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
+#include <com/sun/star/container/XNameAccess.hpp>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/beans/PropertyValue.hpp>
+
+#include <util/util.hxx>
+#include <rtl/uri.hxx>
+
+
+#include "ScriptData.hxx"
+#include "ScriptInfo.hxx"
+#include "ScriptStorage.hxx"
+#include "ScriptElement.hxx"
+#include "ScriptMetadataImporter.hxx"
+#include "ScriptURI.hxx"
+
+using namespace ::rtl;
+using namespace ::cppu;
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::drafts::com::sun::star::script::framework;
+
+namespace scripting_impl
+{
+
+ScriptLanguages_hash* ScriptStorage::mh_scriptLangs = NULL;
+
+const sal_Char* const SERVICE_NAME =
+ "drafts.com.sun.star.script.framework.storage.ScriptStorage";
+const sal_Char* const IMPL_NAME =
+ "drafts.com.sun.star.script.framework.storage.ScriptStorage";
+
+const sal_Char * const SCRIPT_DIR = "/Scripts";
+const sal_Char * const SCRIPT_PARCEL = "/parcel-descriptor.xml";
+const sal_Char * const SCRIPT_PARCEL_NAME_ONLY = "parcel-descriptor";
+
+static OUString ss_implName = OUString::createFromAscii( IMPL_NAME );
+static OUString ss_serviceName = OUString::createFromAscii( SERVICE_NAME );
+static Sequence< OUString > ss_serviceNames =
+ Sequence< OUString >( &ss_serviceName, 1 );
+
+const sal_uInt16 NUMBER_STORAGE_INITIALIZE_ARGS = 3;
+
+//extern ::rtl_StandardModuleCount s_moduleCount;
+
+
+
+//*************************************************************************
+ScriptStorage::ScriptStorage( const Reference <
+ XComponentContext > & xContext )
+throw ( RuntimeException )
+ : m_xContext( xContext ), m_bInitialised( false )
+{
+ OSL_TRACE( "< ScriptStorage ctor called >\n" );
+
+ validateXRef( m_xContext,
+ "ScriptStorage::ScriptStorage : cannot get component context" );
+
+ m_xMgr = m_xContext->getServiceManager();
+ validateXRef( m_xMgr,
+ "ScriptStorage::ScriptStorage : cannot get service manager" );
+
+ if( !mh_scriptLangs )
+ {
+ ::osl::MutexGuard guard( ::osl::Mutex::getGlobalMutex() );
+ if( !mh_scriptLangs )
+ {
+ mh_scriptLangs = new ScriptLanguages_hash();
+ Reference< XInterface > xInterface =
+ m_xMgr->createInstanceWithContext(
+ OUString::createFromAscii(
+ "com.sun.star.configuration.ConfigurationProvider" )
+ , m_xContext );
+ validateXRef( xInterface,
+ "ScriptStorage::ScriptStorage: cannot get ConfigurationProvider" );
+ // create an instance of the ConfigurationAccess for accessing the
+ // scripting runtime settings
+ Reference< lang::XMultiServiceFactory > xConfigProvFactory =
+ Reference < lang::XMultiServiceFactory >
+ ( xInterface, UNO_QUERY_THROW );
+ validateXRef( xConfigProvFactory,
+ "ScriptStorage::ScriptStorage: cannot get XMultiServiceFactory interface from ConfigurationProvider" );
+ beans::PropertyValue configPath;
+ configPath.Name = ::rtl::OUString::createFromAscii( "nodepath" );
+ configPath.Value <<= ::rtl::OUString::createFromAscii( "org.openoffice.Office.Scripting/ScriptRuntimes" );
+ Sequence < Any > aargs( 1 );
+ aargs[ 0 ] <<= configPath;
+
+ xInterface = xConfigProvFactory->createInstanceWithArguments(
+ OUString::createFromAscii(
+ "com.sun.star.configuration.ConfigurationAccess"),
+ aargs );
+ validateXRef( xInterface,
+ "ScriptStorage::ScriptStorage: cannot get ConfigurationAccess" );
+ Reference< container::XNameAccess > xNameAccess =
+ Reference < container::XNameAccess > ( xInterface,
+ UNO_QUERY_THROW );
+ validateXRef( xNameAccess,
+ "ScriptStorage::ScriptStorage: cannot get ConfigurationAccess" );
+ Sequence< OUString > names = xNameAccess->getElementNames();
+ for( int i = 0 ; i < names.getLength() ; i++ )
+ {
+ OSL_TRACE( "Getting propertyset for Lang=%s",
+ ::rtl::OUStringToOString( names[i], RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ Reference< beans::XPropertySet > xPropSet =
+ Reference< beans::XPropertySet >( xNameAccess->getByName(names[i]),
+ UNO_QUERY_THROW );
+ validateXRef( xPropSet,
+ "ScriptStorage::ScriptStorage: cannot get XPropertySet for name" );
+ Any aProp = xPropSet->getPropertyValue(
+ OUString::createFromAscii( "SupportedFileExtensions") );
+ Sequence< OUString > extns;
+ if( sal_False == ( aProp >>= extns ) )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorage:ScriptStorage: can't get runtime extensions" ),
+ Reference< XInterface > () );
+ }
+ for( int j = 0 ; j < extns.getLength() ; j++ )
+ {
+ OSL_TRACE( "Adding Lang=%s, Extn=%s\n",
+ ::rtl::OUStringToOString( names[i], RTL_TEXTENCODING_ASCII_US ).pData->buffer,
+ ::rtl::OUStringToOString( extns[j], RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ (*mh_scriptLangs)[ extns[j] ] =
+ names[i];
+ }
+ }
+ }
+ }
+// s_moduleCount.modCnt.acquire( &s_moduleCount.modCnt );
+}
+
+//*************************************************************************
+ScriptStorage::~ScriptStorage() SAL_THROW( () )
+{
+ OSL_TRACE( "< ScriptStorage dtor called >\n" );
+// s_moduleCount.modCnt.release( &s_moduleCount.modCnt );
+}
+
+//*************************************************************************
+void
+ScriptStorage::initialize( const Sequence <Any> & args )
+throw ( RuntimeException, Exception )
+{
+ OSL_TRACE( "Entering ScriptStorage::initialize\n" );
+
+ // Should not be renitialised
+ if ( m_bInitialised )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::initalize already initialized" ),
+ Reference<XInterface> () );
+ }
+
+ { // Protect member variable writes
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+
+ // Check args
+ if ( args.getLength() != NUMBER_STORAGE_INITIALIZE_ARGS )
+ {
+ OSL_TRACE( "ScriptStorage::initialize: got wrong number of args\n" );
+ throw RuntimeException(
+ OUSTR( "Invalid number of arguments provided!" ),
+ Reference< XInterface >() );
+ }
+
+ if ( sal_False == ( args[ 0 ] >>= m_xSimpleFileAccess ) )
+ {
+ throw RuntimeException(
+ OUSTR( "Invalid XSimpleFileAccess argument provided!" ),
+ Reference< XInterface >() );
+ }
+
+ if ( sal_False == ( args[ 1 ] >>= m_scriptStorageID ) )
+ {
+ throw RuntimeException(
+ OUSTR( "Invalid ScriptStorage ID argument provided!" ),
+ Reference< XInterface >() );
+
+ }
+ if ( sal_False == ( args[ 2 ] >>= m_stringUri ) )
+ {
+ throw RuntimeException(
+ OUSTR( "Invalid String Uri argument provided!" ),
+ Reference< XInterface >() );
+ }
+ } // End - Protect member variable writes
+
+ OSL_TRACE( "uri: %s\n", ::rtl::OUStringToOString(
+ m_stringUri, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ try
+ {
+ // need to check for what???
+ // what we have is a URI for the filesystem or document
+ // we need to check of the last element in the path has an
+ // extension that is associated with a script (eg. .bsh, .js etc)
+ OUString fileExtension = getFileExtension( m_stringUri );
+ // and see if this is in our scripts map
+ ScriptLanguages_hash::iterator h_it = mh_scriptLangs->find( fileExtension );
+ if ( h_it != mh_scriptLangs->end() )
+ {
+ createForFilesystem( fileExtension );
+ }
+ else
+ {
+ create();
+ }
+ }
+ catch ( RuntimeException & re )
+ {
+ OSL_TRACE( "caught com::sun::star::uno::RuntimeException in ScriptStorage::initialize" );
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::initalize RuntimeException: " ).concat( re.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( Exception & ue )
+ {
+ OSL_TRACE( "caught com::sun::star::uno::Exception in ScriptStorage::initialize" );
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::initalize Exception: " ).concat( ue.Message ),
+ Reference< XInterface > () );
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ OSL_TRACE( "caught unknown Exception in ScriptStorage::initialize" );
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::initalize unknown exception: " ),
+ Reference< XInterface > () );
+ }
+#endif
+
+ OSL_TRACE( "Parsed the XML\n" );
+
+ m_bInitialised = true;
+}
+
+void
+ScriptStorage::create()
+throw ( RuntimeException, Exception )
+{
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+ try
+ {
+ // clear existing hashmap - rebuilding from scratch to avoid having
+ // to search for deleted elements on refresh
+ mh_implementations.clear();
+
+ OUString xStringUri(m_stringUri);
+
+ ScriptMetadataImporter* SMI = new ScriptMetadataImporter( m_xContext );
+ Reference< xml::sax::XExtendedDocumentHandler > xSMI( SMI );
+
+ validateXRef( xSMI, "ScriptStorage::create: failed to obtain valid XExtendedDocumentHandler" );
+
+ xStringUri = xStringUri.concat( ::rtl::OUString::createFromAscii(
+ SCRIPT_DIR ) );
+
+ // No Scripts directory - just return
+ if ( ! m_xSimpleFileAccess->isFolder( xStringUri ) )
+ {
+ OSL_TRACE( "ScriptStorage::initialize: no Scripts dir for this storage - install problem\n" );
+ return;
+ }
+
+ // get the list of language folders under the Scripts directory
+ Sequence< ::rtl::OUString > languageDirs =
+ m_xSimpleFileAccess->getFolderContents( xStringUri, true );
+
+ Reference< io::XInputStream > xInput;
+ sal_Int32 languageDirsLength = languageDirs.getLength();
+ for ( sal_Int32 i = 0; i < languageDirsLength ; ++i )
+ {
+ OSL_TRACE( "contains: %s\n", ::rtl::OUStringToOString(
+ languageDirs[ i ], RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ if ( ! m_xSimpleFileAccess->isFolder( languageDirs[ i ] ) )
+ {
+ continue;
+ }
+
+ //get the list of parcel folders for each language folder
+ // under Scripts
+ Sequence< ::rtl::OUString > parcelDirs =
+ m_xSimpleFileAccess->getFolderContents( languageDirs[ i ], true );
+
+ sal_Int32 parcelDirsLength = parcelDirs.getLength();
+ for ( sal_Int32 j = 0; j < parcelDirsLength ; ++j )
+ {
+ OSL_TRACE( "contains: %s\n",
+ ::rtl::OUStringToOString( parcelDirs[ j ],
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ OUString parcelFile = parcelDirs[ j ].concat(
+ ::rtl::OUString::createFromAscii( SCRIPT_PARCEL ) );
+
+ // Do not have a valid parcel.xml
+ if ( !m_xSimpleFileAccess->exists( parcelFile ) ||
+ m_xSimpleFileAccess->isFolder( parcelFile ) )
+ {
+ continue;
+ }
+ OSL_TRACE( "parcel file: %s\n",
+ ::rtl::OUStringToOString( parcelFile,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ xInput = m_xSimpleFileAccess->openFileRead( parcelFile );
+ // Failed to get input stream
+ if ( !xInput.is() )
+ {
+ continue;
+ }
+
+ OSL_TRACE( "Parse the metadata \n" );
+ Datas_vec vScriptDatas;
+ try
+ {
+ SMI->parseMetaData( xInput, parcelDirs[ j ], vScriptDatas );
+ }
+ catch ( xml::sax::SAXException & saxe )
+ {
+ if ( xInput.is() )
+ {
+ xInput->closeInput();
+ }
+ OSL_TRACE(
+ "caught com::sun::star::xml::sax::SAXException in ScriptStorage::create %s",
+ ::rtl::OUStringToOString( saxe.Message,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ continue;
+ }
+ catch ( io::IOException & ioe )
+ {
+ if ( xInput.is() )
+ {
+ xInput->closeInput();
+ }
+ OSL_TRACE(
+ "caught com::sun::star::io::IOException in ScriptStorage::create" );
+ continue;
+ }
+ xInput->closeInput();
+
+ updateMaps( vScriptDatas );
+ }
+ }
+ }
+ catch ( io::IOException & ioe )
+ {
+ //From ScriptMetadata Importer
+ OSL_TRACE( "caught com::sun::star::io::IOException in ScriptStorage::create" );
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::create IOException: " ).concat( ioe.Message ),
+ Reference< XInterface > () );
+
+ }
+ catch ( ucb::CommandAbortedException & cae )
+ {
+ OSL_TRACE( "caught com::sun::star::ucb::CommandAbortedException in ScriptStorage::create" );
+ throw RuntimeException(
+ OUSTR(
+ "ScriptStorage::create CommandAbortedException: " ).concat( cae.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( RuntimeException & re )
+ {
+ OSL_TRACE( "caught com::sun::star::uno::RuntimeException in ScriptStorage::create" );
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::create RuntimeException: " ).concat( re.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( Exception & ue )
+ {
+ OSL_TRACE( "caught com::sun::star::uno::Exception in ScriptStorage::create" );
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::create Exception: " ).concat( ue.Message ),
+ Reference< XInterface > () );
+ }
+#ifdef _DEBUG
+ catch ( ... )
+ {
+ OSL_TRACE( "caught unknown Exception in ScriptStorage::create" );
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::initalize unknown exception: " ),
+ Reference< XInterface > () );
+ }
+#endif
+
+ OSL_TRACE( "Parsed the XML\n" );
+
+ m_bInitialised = true;
+}
+
+//*************************************************************************
+// private method to create the usual data structures for scripts located
+// on the filesystem.
+// parcelURI = the path to the script
+// functionName = the full filename with extension
+// logicalName = the filename without the extension
+void
+ScriptStorage::createForFilesystem( const OUString & fileExtension )
+throw ( RuntimeException, Exception )
+{
+ // need to decode as file urls are encoded
+ OUString xStringUri = ::rtl::Uri::decode( m_stringUri,
+ rtl_UriDecodeWithCharset, RTL_TEXTENCODING_ASCII_US );
+
+ // no x-platform issues here as we are dealing with URLs
+ sal_Int32 lastFileSep = xStringUri.lastIndexOf( '/' );
+ // the char just after the filesep
+ lastFileSep += 1;
+ sal_Int32 lastFileExt = xStringUri.lastIndexOf( fileExtension );
+ OUString searchString = OUString::createFromAscii( "://" );
+ sal_Int32 searchStringLength = searchString.getLength();
+ sal_Int32 startPath = xStringUri.indexOf( searchString );
+ sal_Int32 uriLength = xStringUri.getLength();
+ OUString fileNameNoExt = xStringUri.copy( lastFileSep ,
+ lastFileExt - lastFileSep - 1 );
+ OUString fileName = xStringUri.copy( lastFileSep, uriLength - lastFileSep );
+ OUString filePath = xStringUri.copy( startPath + searchStringLength,
+ lastFileSep - startPath - searchStringLength );
+ OUString filePathWithName = xStringUri.copy( startPath + searchStringLength,
+ uriLength - startPath - searchStringLength );
+
+ ScriptData scriptData;
+ scriptData.language = mh_scriptLangs->find( fileExtension )->second;
+ OSL_TRACE( "\t language = %s", ::rtl::OUStringToOString(
+ scriptData.language, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ // do we need to encode this?
+ scriptData.functionname = fileName;
+ OSL_TRACE( "\t functionName = %s", ::rtl::OUStringToOString(
+ scriptData.functionname, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ //scriptData.functionname = ::rtl::Uri::encode( fileName,
+ //rtl_UriCharClassUricNoSlash, rtl_UriEncodeCheckEscapes,
+ //RTL_TEXTENCODING_ASCII_US );
+
+ scriptData.parcelURI = filePath;
+ OSL_TRACE( "\t parcelURI = %s", ::rtl::OUStringToOString(
+ scriptData.parcelURI, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ scriptData.logicalname = fileNameNoExt;
+ OSL_TRACE( "\t logicalName = %s", ::rtl::OUStringToOString(
+ scriptData.logicalname, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ // and now push onto the usual structures
+ ScriptFunction_hash sfh;
+ sfh[ scriptData.functionname ] = scriptData;
+ mh_implementations[ scriptData.language ] = sfh;
+ m_bInitialised = true;
+}
+
+//*************************************************************************
+// private method to return the file extension, eg. bsh, js etc
+OUString
+ScriptStorage::getFileExtension( const OUString & stringUri )
+{
+ OUString fileExtension;
+ sal_Int32 lastDot = stringUri.lastIndexOf( '.' );
+ if( lastDot > 0 ) {
+ sal_Int32 stringUriLength = stringUri.getLength();
+ fileExtension = stringUri.copy( lastDot +1 , stringUriLength - lastDot - 1 );
+ }
+ else
+ {
+ fileExtension = OUString::createFromAscii("");
+ }
+ return fileExtension;
+}
+
+//*************************************************************************
+// private method for updating hashmaps
+void
+ScriptStorage::updateMaps( const Datas_vec & vScriptDatas )
+{
+
+ Datas_vec::const_iterator it_end = vScriptDatas.end();
+ // step through the vector of ScripImplInfos returned from parse
+ for ( Datas_vec::const_iterator it = vScriptDatas.begin() ; it != it_end; ++it )
+ {
+ //find the Datas_vec for this logical name
+ ScriptData_hash::iterator h_it = mh_implementations.find( it->language );
+
+ if ( h_it == mh_implementations.end() )
+ {
+ //if it's null, need to create a new Datas_vec
+ OSL_TRACE(
+ "updateMaps: new language: %s\n", rtl::OUStringToOString(
+ it->language, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ OSL_TRACE(
+ "updateMaps: adding functionname: %s\n", rtl::OUStringToOString(
+ it->functionname, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ ScriptFunction_hash sfh;
+ sfh[ it->functionname ] = *it;
+ mh_implementations[ it->language ] = sfh;
+ }
+ else
+ {
+ OSL_TRACE(
+ "updateMaps: adding functionname: %s\n", rtl::OUStringToOString(
+ it->functionname, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ OSL_TRACE( " language name: %s\n",
+ rtl::OUStringToOString( it->functionname,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ h_it->second[ it->functionname ] = *it;
+ }
+ }
+}
+
+//*************************************************************************
+// XScriptStorageExport::save
+void
+ScriptStorage::save()
+throw ( RuntimeException )
+{
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+ Reference< io::XActiveDataSource > xSource;
+ Reference< io::XOutputStream > xOS;
+
+ // xScriptInvocation = Reference<XScriptInvocation>(xx, UNO_QUERY_THROW);
+ Reference< xml::sax::XExtendedDocumentHandler > xHandler;
+
+ OUString parcel_suffix = OUString::createFromAscii( SCRIPT_PARCEL );
+ OUString ou_parcel = OUString(
+ RTL_CONSTASCII_USTRINGPARAM( SCRIPT_PARCEL_NAME_ONLY ) );
+
+ try
+ {
+ ScriptData_hash::iterator it_end = mh_implementations.end();
+ for ( ScriptData_hash::iterator it = mh_implementations.begin() ; it != it_end; ++it )
+ {
+ ::rtl::OUString logName = it->first;
+ ScriptFunction_hash::iterator it_sfh_end = it->second.end();
+ for ( ScriptFunction_hash::iterator it_sfh = it->second.begin();
+ it_sfh != it_sfh_end ; ++it_sfh )
+ {
+ ScriptOutput_hash::const_iterator it_parcels =
+ mh_parcels.find( it_sfh->second.parcelURI );
+ if ( it_parcels == mh_parcels.end() )
+ {
+ //create new outputstream
+ OUString parcel_xml_path = it_sfh->second.parcelURI.concat(
+ parcel_suffix );
+ m_xSimpleFileAccess->kill( parcel_xml_path );
+ xOS = m_xSimpleFileAccess->openFileWrite( parcel_xml_path );
+
+ OSL_TRACE( "saving: %s\n", rtl::OUStringToOString(
+ it_sfh->second.parcelURI.concat( OUString::createFromAscii(
+ "/parcel.xml" ) ),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ Reference< XInterface > xInterface =
+ m_xMgr->createInstanceWithContext(
+ OUString::createFromAscii( "com.sun.star.xml.sax.Writer" ),
+ m_xContext );
+ validateXRef( xInterface, "ScriptStorage::save: cannot get sax.Writer" );
+ xHandler = Reference<xml::sax::XExtendedDocumentHandler>(
+ xInterface, UNO_QUERY_THROW );
+ xSource = Reference< io::XActiveDataSource >(
+ xHandler, UNO_QUERY_THROW );
+ xSource->setOutputStream( xOS );
+
+ writeMetadataHeader( xHandler );
+
+ mh_parcels[ it_sfh->second.parcelURI ] = xHandler;
+ }
+ else
+ {
+ xHandler = it_parcels->second;
+ }
+
+ ScriptElement* pSE = new ScriptElement( it_sfh->second );
+ // this is to get pSE released correctly
+ Reference < xml::sax::XAttributeList > xal( pSE );
+ pSE->dump( xHandler );
+ }
+ }
+
+ ScriptOutput_hash::const_iterator out_it_end = mh_parcels.end();
+
+ for ( ScriptOutput_hash::const_iterator out_it = mh_parcels.begin();
+ out_it != out_it_end; ++out_it )
+ {
+ out_it->second->ignorableWhitespace( ::rtl::OUString() );
+ out_it->second->endDocument();
+ xSource.set( out_it->second, UNO_QUERY );
+ Reference< io::XOutputStream > xOS = xSource->getOutputStream();
+ xOS->closeOutput();
+
+ }
+
+ // clear the hash map, as all output streams have been closed.
+ // need to re-create on next save
+ mh_parcels.clear();
+ }
+ // *** TODO - other exception handling IO etc.
+ catch ( RuntimeException & re )
+ {
+ OSL_TRACE( "caught com::sun::star::uno::RuntimeException in ScriptStorage::save" );
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::save RuntimeException: " ).concat(
+ re.Message ),
+ Reference< XInterface > () );
+ }
+}
+
+//*************************************************************************
+void
+ScriptStorage::refresh()
+throw (RuntimeException)
+{
+ OSL_TRACE("** => ScriptStorage: in refresh()\n");
+
+ // guard against concurrent refreshes
+ ::osl::Guard< ::osl::Mutex > aGuard( m_mutex );
+
+ try
+ {
+ create();
+
+ }
+ catch ( RuntimeException & re )
+ {
+ OSL_TRACE( "caught com::sun::star::uno::RuntimeException in ScriptStorage::refresh" );
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::refresh RuntimeException: " ).concat( re.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( Exception & ue )
+ {
+ OSL_TRACE( "caught com::sun::star::uno::Exception in ScriptStorage::refresh" );
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::refresh Exception: " ).concat( ue.Message ),
+ Reference< XInterface > () );
+ }
+}
+
+//*************************************************************************
+void
+ScriptStorage::writeMetadataHeader(
+ Reference <xml::sax::XExtendedDocumentHandler> & xHandler )
+{
+ xHandler->startDocument();
+ OUString aDocTypeStr( RTL_CONSTASCII_USTRINGPARAM(
+ "<!DOCTYPE parcel SYSTEM \"scripting.dtd\">" ) );
+ xHandler->unknown( aDocTypeStr );
+ xHandler->ignorableWhitespace( OUString() );
+}
+
+
+//*************************************************************************
+Sequence< ::rtl::OUString >
+ScriptStorage::getScriptLogicalNames()
+throw ( RuntimeException )
+{
+ Sequence< ::rtl::OUString > results;
+ // comment out the rest, and ultimately remove method
+ /*ScriptInfo_hash::iterator h_it = mh_implementations.begin();
+ ScriptInfo_hash::iterator h_itEnd = mh_implementations.end();
+ if ( h_it == h_itEnd )
+ {
+ OSL_TRACE( "ScriptStorage::getImplementations: EMPTY STORAGE");
+ return results;
+ }
+ results.realloc( mh_implementations.size() );
+
+ //find the implementations for the given logical name
+ try
+ {
+
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+
+ for ( sal_Int32 count = 0; h_it != h_itEnd ; ++h_it )
+ {
+ ::rtl::OUString logicalName = h_it->first;
+ OSL_TRACE( "Adding %s at index %d ", ::rtl::OUStringToOString(
+ logicalName, RTL_TEXTENCODING_ASCII_US ).pData->buffer, count);
+ results[ count++ ] = logicalName;
+ }
+
+ }
+ catch ( RuntimeException & re )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorage::getScriptLogicalNames RuntimeException: " ).concat( re.Message ),
+ Reference< XInterface > () );
+ }
+ catch ( Exception & e )
+ {
+ throw RuntimeException( OUSTR(
+ "ScriptStorage::getScriptLogicalNames Exception: " ).concat(
+ e.Message ), Reference< XInterface > () );
+ } */
+ return results;
+}
+
+//*************************************************************************
+Sequence< Reference< storage::XScriptInfo > >
+ScriptStorage::getImplementations( const ::rtl::OUString & queryURI )
+throw ( lang::IllegalArgumentException,
+ RuntimeException )
+{
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+// format is script:://[function_name]?language=[languge]&location=[location]
+// LogicalName is now not used anymore, further more the ScriptURI class
+// will be retired also and a new UNO service will be used. Additionally the
+// parcel-description will also need to be modified to remove logical name
+// ScriprtMetaDataImporter has been modified to ignore the Logical name
+// definined in the parcel-desc.xml. As an interim temp solution the Datas_vec
+// structure that is returned from ScriptMetDataImporter sets the logicalname
+// to the function name. ScriptURI class has been changed in the same way.
+//
+ Sequence< Reference< storage::XScriptInfo > > results;
+ ScriptURI scriptURI( queryURI );
+ OSL_TRACE( "getting impl for language %s, function name: %s",
+ ::rtl::OUStringToOString( scriptURI.getLanguage(),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer,
+ ::rtl::OUStringToOString( scriptURI.getFunctionName(),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ ScriptData_hash::iterator h_itEnd = mh_implementations.end();
+ ScriptData_hash::iterator h_it = mh_implementations.begin();
+ if ( h_it == h_itEnd )
+ {
+ OSL_TRACE( "ScriptStorage::getImplementations: EMPTY STORAGE" );
+ return results;
+ }
+
+ //find the implementations for the given language
+ h_it = mh_implementations.find( scriptURI.getLanguage() );
+
+ if ( h_it == h_itEnd )
+ {
+ OSL_TRACE( "ScriptStorage::getImplementations: no impls found for %s",
+ ::rtl::OUStringToOString( scriptURI.getLanguage(),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ return results;
+ }
+
+ //find the implementations for the given language
+ ScriptFunction_hash::const_iterator it_datas = h_it->second.find(
+ scriptURI.getLogicalName() );
+ ScriptFunction_hash::const_iterator it_datas_end = h_it->second.end();
+
+ if ( it_datas == it_datas_end )
+ {
+ OSL_TRACE( "ScriptStorage::getImplementations: no impls found for %s",
+ ::rtl::OUStringToOString( scriptURI.getFunctionName(),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ return results;
+ }
+
+ results.realloc( 1 );
+ ScriptData scriptData = it_datas->second;
+ OSL_TRACE( "ScriptStorage::getImplementations: impls found for %s",
+ ::rtl::OUStringToOString( scriptData.functionname,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ Reference< storage::XScriptInfo > xScriptInfo =
+ new ScriptInfo ( scriptData, m_scriptStorageID );
+ results[ 0 ] = xScriptInfo;
+
+ return results;
+}
+
+//*************************************************************************
+Sequence< Reference< storage::XScriptInfo > > SAL_CALL
+ScriptStorage::getAllImplementations() throw ( RuntimeException )
+{
+ ::osl::Guard< osl::Mutex > aGuard( m_mutex );
+ Sequence< Reference< storage::XScriptInfo > > results;
+ ScriptData_hash::iterator h_itEnd = mh_implementations.end();
+ ScriptData_hash::iterator h_it = mh_implementations.begin();
+ if ( h_it == h_itEnd )
+ {
+ OSL_TRACE( "ScriptStorage::getImplementations: EMPTY STORAGE" );
+ return results;
+ }
+
+
+ //iterate through each logical name and gather each implementation
+ //for that name
+ for ( sal_Int32 count = 0; h_it != h_itEnd; ++h_it )
+ {
+ results.realloc( h_it->second.size() + count );
+ OSL_TRACE( "Adding implementations for %s",
+ ::rtl::OUStringToOString( h_it->first,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ ScriptFunction_hash::const_iterator it_sfh = h_it->second.begin();
+ ScriptFunction_hash::const_iterator it_sfh_end = h_it->second.end();
+ OSL_TRACE( "Adding %d to sequence of impls ", h_it->second.size() );
+ for ( ; it_sfh != it_sfh_end ; ++it_sfh )
+ {
+ Reference< storage::XScriptInfo > xScriptInfo = new ScriptInfo (
+ it_sfh->second, m_scriptStorageID );
+
+ results[ count++ ] = xScriptInfo;
+ }
+ }
+ return results;
+
+}
+
+//*************************************************************************
+OUString SAL_CALL ScriptStorage::getImplementationName( )
+throw( RuntimeException )
+{
+ return ss_implName;
+}
+
+//*************************************************************************
+sal_Bool SAL_CALL ScriptStorage::supportsService( const OUString& serviceName )
+throw( RuntimeException )
+{
+ OUString const * pNames = ss_serviceNames.getConstArray();
+ for ( sal_Int32 nPos = ss_serviceNames.getLength(); nPos--; )
+ {
+ if ( serviceName.equals( pNames[ nPos ] ) )
+ {
+ return sal_True;
+ }
+ }
+ return sal_False;
+}
+
+//*************************************************************************
+Sequence<OUString> SAL_CALL ScriptStorage::getSupportedServiceNames( )
+throw( RuntimeException )
+{
+ return ss_serviceNames;
+}
+
+} // namespace scripting_impl
+
+
+namespace scripting_runtimemgr
+{
+
+//*************************************************************************
+Reference<XInterface> SAL_CALL ss_create(
+ const Reference< XComponentContext > & xCompC )
+{
+ return ( cppu::OWeakObject * ) new ::scripting_impl::ScriptStorage( xCompC );
+}
+
+//*************************************************************************
+Sequence<OUString> ss_getSupportedServiceNames( )
+SAL_THROW( () )
+{
+ return ::scripting_impl::ss_serviceNames;
+}
+
+//*************************************************************************
+OUString ss_getImplementationName( )
+SAL_THROW( () )
+{
+ return ::scripting_impl::ss_implName;
+}
+}//end namespace
diff --git a/scripting/source/storage/ScriptStorage.hxx b/scripting/source/storage/ScriptStorage.hxx
new file mode 100644
index 000000000000..2363d21ef164
--- /dev/null
+++ b/scripting/source/storage/ScriptStorage.hxx
@@ -0,0 +1,208 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptStorage.hxx,v $
+ * $Revision: 1.17 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#ifndef __SCRIPTING_STORAGE_SCRIPTSTORAGE_HXX_
+#define __SCRIPTING_STORAGE_SCRIPTSTORAGE_HXX_
+
+#include <vector>
+#include <hash_map>
+
+#include <osl/mutex.hxx>
+#include <cppuhelper/implbase5.hxx> // helper for component factory
+
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XInitialization.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/io/XOutputStream.hpp>
+#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
+#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
+
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfoAccess.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptStorageExport.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptStorageRefresh.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfo.hpp>
+
+namespace scripting_impl
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+//Typedefs
+//=============================================================================
+typedef ::std::vector< ScriptData > Datas_vec;
+//-----------------------------------------------------------------------------
+// function name -> ScriptData
+typedef ::std::hash_map < ::rtl::OUString, ScriptData, ::rtl::OUStringHash,
+ ::std::equal_to< ::rtl::OUString > > ScriptFunction_hash;
+//-----------------------------------------------------------------------------
+// language -> hash of function name -> ScriptData
+typedef ::std::hash_map < ::rtl::OUString, ScriptFunction_hash,
+ ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > >
+ScriptData_hash;
+//-----------------------------------------------------------------------------
+typedef ::std::hash_map < ::rtl::OUString,
+css::uno::Reference< css::xml::sax::XExtendedDocumentHandler >,
+::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > >
+ScriptOutput_hash;
+//-----------------------------------------------------------------------------
+typedef ::std::hash_map < ::rtl::OUString,
+::rtl::OUString, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > >
+ScriptLanguages_hash;
+
+//=============================================================================
+
+class ScriptStorage : public
+ ::cppu::WeakImplHelper5<
+ css::lang::XServiceInfo,
+ css::lang::XInitialization,
+ dcsssf::storage::XScriptInfoAccess,
+ dcsssf::storage::XScriptStorageExport,
+ dcsssf::storage::XScriptStorageRefresh >
+{
+public:
+ //Constructors and Destructors
+ //=========================================================================
+ explicit ScriptStorage(
+ const css::uno::Reference< css::uno::XComponentContext > & xContext )
+ throw ( css::uno::RuntimeException );
+ //-------------------------------------------------------------------------
+ virtual ~ScriptStorage() SAL_THROW( () );
+ //=========================================================================
+
+ // XServiceInfo impl
+ //=========================================================================
+ virtual ::rtl::OUString SAL_CALL getImplementationName()
+ throw ( css::uno::RuntimeException );
+ //-------------------------------------------------------------------------
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString & ServiceName )
+ throw ( css::uno::RuntimeException );
+ //-------------------------------------------------------------------------
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
+ throw ( css::uno::RuntimeException );
+ //-------------------------------------------------------------------------
+ static css::uno::Sequence< ::rtl::OUString > SAL_CALL
+ getSupportedServiceNames_Static();
+ //=========================================================================
+
+ // XInitialization impl
+ //=========================================================================
+ virtual void SAL_CALL
+ initialize( css::uno::Sequence< css::uno::Any > const & args )
+ throw ( css::uno::RuntimeException, css::uno::Exception );
+ //=========================================================================
+
+ //XScriptInfoAccess
+ //=========================================================================
+ /**
+ * Get the logical names for this storage
+ *
+ * @return sequence < ::rtl::OUString >
+ * The logical names
+ */
+ virtual css::uno::Sequence< ::rtl::OUString >
+ SAL_CALL getScriptLogicalNames()
+ throw ( css::uno::RuntimeException );
+
+ //=========================================================================
+ /**
+ * Get the implementations for a given URI
+ *
+ * @param queryURI
+ * The URI to get the implementations for
+ *
+ * @return sequence < XScriptInfo >
+ * The URIs of the implementations
+ */
+ virtual css::uno::Sequence< css::uno::Reference< dcsssf::storage::XScriptInfo > >
+ SAL_CALL getImplementations(
+ const ::rtl::OUString& queryURI )
+ throw ( css::lang::IllegalArgumentException, css::uno::RuntimeException );
+
+ //=========================================================================
+ /**
+ * Get all script implementations
+ *
+ *
+ * @return sequence < XScriptInfo >
+ * script implementations
+ */
+ virtual css::uno::Sequence< css::uno::Reference< dcsssf::storage::XScriptInfo > >
+ SAL_CALL getAllImplementations()
+ throw ( css::uno::RuntimeException );
+
+ //=========================================================================
+
+ /**
+ * Save the scripts stored in the ScriptStorage into the corresponding
+ * area (document or application)
+ */
+ void SAL_CALL save()
+ throw ( css::uno::RuntimeException );
+ //=========================================================================
+
+ /**
+ * Refresh the ScriptStorage from the data stored in the corresponding area
+ * (document or application).
+ */
+ void SAL_CALL refresh()
+ throw ( css::uno::RuntimeException );
+ //=========================================================================
+
+private:
+
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+ css::uno::Reference< css::ucb::XSimpleFileAccess > m_xSimpleFileAccess;
+ css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;
+
+ ::std::vector < ::rtl::OUString > mv_logicalNames;
+ static ScriptLanguages_hash* mh_scriptLangs;
+ ScriptData_hash mh_implementations;
+ ScriptOutput_hash mh_parcels;
+ sal_Int32 m_scriptStorageID;
+ ::rtl::OUString m_stringUri;
+
+ osl::Mutex m_mutex;
+ bool m_bInitialised;
+
+ void updateMaps( const Datas_vec & vScriptDatas );
+ void writeMetadataHeader(
+ css::uno::Reference < css::xml::sax::XExtendedDocumentHandler > & xExDocHandler );
+ void create ()
+ throw (css::uno::RuntimeException, css::uno::Exception);
+ void createForFilesystem ( const ::rtl::OUString & scriptLanguage )
+ throw (css::uno::RuntimeException, css::uno::Exception);
+ ::rtl::OUString getFileExtension ( const ::rtl::OUString & stringUri );
+
+}; // class ScriptingStorage
+
+} // namespace scripting_impl
+
+#endif
diff --git a/scripting/source/storage/ScriptStorageManager.cxx b/scripting/source/storage/ScriptStorageManager.cxx
new file mode 100644
index 000000000000..e3051c0656be
--- /dev/null
+++ b/scripting/source/storage/ScriptStorageManager.cxx
@@ -0,0 +1,576 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptStorageManager.cxx,v $
+ * $Revision: 1.33 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+
+#include <stdio.h>
+
+#include <cppuhelper/implementationentry.hxx>
+#include <sal/config.h>
+#include <rtl/uri.hxx>
+
+#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
+#include <com/sun/star/util/XMacroExpander.hpp>
+#include <com/sun/star/lang/XComponent.hpp>
+#include <com/sun/star/lang/XMultiComponentFactory.hpp>
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/frame/XModel.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfoAccess.hpp>
+
+#include "ScriptStorageManager.hxx"
+#include <util/util.hxx>
+#include <util/scriptingconstants.hxx>
+
+using namespace ::rtl;
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::drafts::com::sun::star::script::framework;
+
+namespace scripting_impl
+{
+
+static OUString s_implName =
+ ::rtl::OUString::createFromAscii(
+ "drafts.com.sun.star.script.framework.storage.ScriptStorageManager" );
+static OUString s_serviceName =
+ ::rtl::OUString::createFromAscii(
+ "drafts.com.sun.star.script.framework.storage.ScriptStorageManager" );
+static Sequence< OUString > s_serviceNames = Sequence< OUString >( &s_serviceName, 1 );
+
+//extern ::rtl_StandardModuleCount s_moduleCount = MODULE_COUNT_INIT;
+//extern ::rtl_StandardModuleCount s_moduleCount;
+
+
+//*************************************************************************
+// ScriptStorageManager Constructor
+ScriptStorageManager::ScriptStorageManager( const Reference<
+ XComponentContext > & xContext ) SAL_THROW ( ( RuntimeException ) )
+ : m_xContext( xContext ), m_count( 0 ), m_securityMgr( xContext )
+{
+ OSL_TRACE( "< ScriptStorageManager ctor called >\n" );
+ //s_moduleCount.modCnt.acquire( &s_moduleCount.modCnt );
+
+ validateXRef( m_xContext,
+ "ScriptStorageManager::ScriptStorageManager : cannot get component context" );
+
+ m_xMgr = m_xContext->getServiceManager();
+ validateXRef( m_xMgr,
+ "ScriptStorageManager::ScriptStorageManager : cannot get service manager" );
+
+ try
+ {
+ // obtain the macro expander singleton to use in determining the
+ // location of the application script storage
+ Any aAny = m_xContext->getValueByName( OUString::createFromAscii(
+ "/singletons/com.sun.star.util.theMacroExpander" ) );
+ Reference< util::XMacroExpander > xME;
+ if ( sal_False == ( aAny >>= xME ) )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorageManager::ScriptStorageManager: can't get XMacroExpander" ),
+ Reference< XInterface >() );
+ }
+ validateXRef( xME, "ScriptStorageManager constructor: can't get MacroExpander" );
+
+ OUString base = OUString::createFromAscii(
+ SAL_CONFIGFILE( "${$BRAND_BASE_DIR/program/bootstrap" ) );
+
+ setupAppStorage( xME,
+ base.concat( OUString::createFromAscii( "::BaseInstallation}/share" ) ),
+ OUSTR( "SHARE" ) );
+ setupAppStorage( xME,
+ base.concat( OUString::createFromAscii( "::UserInstallation}/user" ) ),
+ OUSTR( "USER" ) );
+
+ }
+ catch ( Exception & e )
+ {
+ throw RuntimeException( OUSTR( "ScriptStorageManager::ScriptStorageManager: " ).concat( e.Message ), Reference< XInterface >() );
+ }
+ OSL_ASSERT( m_count == 2 );
+}
+
+//*************************************************************************
+// ScriptStorageManager setupAppStorage
+void
+ScriptStorageManager::setupAppStorage(
+ const Reference< util::XMacroExpander > & xME,
+ const OUString & storageStr,
+ const OUString & appStr)
+SAL_THROW ( ( RuntimeException ) )
+{
+ try
+ {
+ Reference< XInterface > xInterface =
+ m_xMgr->createInstanceWithContext(
+ OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ), m_xContext );
+ validateXRef( xInterface,
+ "ScriptStorageManager constructor: can't get SimpleFileAccess XInterface" );
+ Reference< ucb::XSimpleFileAccess > xSFA( xInterface, UNO_QUERY_THROW );
+
+ setupAnyStorage( xSFA, xME->expandMacros( storageStr ), appStr );
+ }
+ catch ( Exception & e )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorageManager::setupAppStorage: " ).concat( e.Message ),
+ Reference< XInterface >() );
+ }
+}
+
+//*************************************************************************
+// ScriptStorageManager setupAnyStorage
+sal_Int32
+ScriptStorageManager::setupAnyStorage(
+ const Reference< ucb::XSimpleFileAccess > & xSFA,
+ const OUString & storageStr,
+ const OUString & origStringURI )
+SAL_THROW ( ( RuntimeException ) )
+{
+ // Required for scope of fnc to protect all access read and writes to m_count
+ ::osl::Guard< ::osl::Mutex > aGuard( m_mutex );
+ try
+ {
+
+ // create a ScriptingStorage using the SimpleFileAccess, the storageID
+ // (from the count), and the URL to the application's shared area
+ Sequence < Any > aArgs( 3 );
+ aArgs[ 0 ] <<= xSFA;
+ aArgs[ 1 ] <<= m_count;
+ aArgs[ 2 ] <<= storageStr;
+
+ OSL_TRACE( "creating storage for: %s\n",
+ ::rtl::OUStringToOString( storageStr,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ Reference< XInterface > xInterface =
+ m_xMgr->createInstanceWithArgumentsAndContext(
+ OUString::createFromAscii(
+ "drafts.com.sun.star.script.framework.storage.ScriptStorage" ),
+ aArgs, m_xContext );
+
+ validateXRef( xInterface, "ScriptStorageManager:: setupAnyStorage: Can't create ScriptStorage for share" );
+
+ // and place it in the hash_map. Increment the counter
+ m_ScriptStorageMap[ m_count++ ] = xInterface;
+ sal_Int32 sid = m_count - 1;
+
+ // create hash of original uri i.e. file:///home/users/docs/mydoc.sxw
+ // and storage id (sid) this will allow us to retrieve
+ // the sid based on the url of the document.
+ m_StorageIdOrigURIHash [ origStringURI ] = sid;
+ OSL_TRACE( "\tcreated with ID=%d\n", m_count - 1 );
+
+ }
+ catch ( Exception & e )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorageManager::setupAnyStorage: " ).concat(
+ e.Message ), Reference< XInterface >() );
+ }
+
+ return m_count -1;
+}
+
+//*************************************************************************
+// ScriptStorageManager Destructor
+ScriptStorageManager::~ScriptStorageManager()
+SAL_THROW ( () )
+{
+ OSL_TRACE( "< ScriptStorageManager dtor called >\n" );
+// s_moduleCount.modCnt.release( &s_moduleCount.modCnt );
+}
+
+//*************************************************************************
+// This method assumes that the XSimpleFileAccess knows it's on root URL
+// and can be used with relative URLs
+sal_Int32 SAL_CALL
+ScriptStorageManager::createScriptStorage(
+ const Reference< ucb::XSimpleFileAccess >& xSFA )
+throw ( RuntimeException )
+{
+ OSL_TRACE( "** ==> ScriptStorageManager in createScriptingStorage\n" );
+ validateXRef( xSFA,
+ "ScriptStorageManager::createScriptStorage: XSimpleFileAccess is not valid" );
+
+ return setupAnyStorage( xSFA, ::rtl::OUString::createFromAscii( "" ),
+ ::rtl::OUString::createFromAscii( "" ) );
+}
+
+//*************************************************************************
+sal_Int32 SAL_CALL
+ScriptStorageManager::createScriptStorageWithURI(
+ const Reference< ucb::XSimpleFileAccess >& xSFA, const OUString & cStringURI )
+throw ( RuntimeException )
+{
+ OSL_TRACE( "** ==> ScriptStorageManager in createScriptingStorageWithURI\n" );
+ validateXRef( xSFA, "ScriptStorageManager::createScriptStorage: XSimpleFileAccess is not valid" );
+
+ // related to issue 11866
+ // warning dialog gets launched when adding binding to script in doc
+ // workaround issue: no functionProvider created on doc open
+ // if NODIALOG tag, strip from stringURI, set boolean=true
+ bool displayDialog = true;
+ ::rtl::OUString dialogTag = ::rtl::OUString::createFromAscii( "NoDialog::" );
+ ::rtl::OUString stringURI = cStringURI;
+ if( stringURI.indexOf( dialogTag ) == 0 )
+ {
+ OSL_TRACE( "ScriptStorageManager::createScriptStorage: will not display security dialogs" );
+ stringURI = stringURI.copy( dialogTag.getLength() );
+ displayDialog = false;
+ }
+ sal_Int32 returnedID = getScriptStorageID(stringURI);
+
+
+ // convert file:///... url to vnd... syntax
+ ::rtl::OUString canonicalURI(
+ ::rtl::OUString::createFromAscii( "vnd.sun.star.pkg://" ) );
+ canonicalURI = canonicalURI.concat( ::rtl::Uri::encode( stringURI,
+ rtl_UriCharClassUricNoSlash, rtl_UriEncodeCheckEscapes,
+ RTL_TEXTENCODING_ASCII_US ) );
+
+ if (returnedID == -1)
+ {
+ OSL_TRACE("Creating new storage for %s",
+ ::rtl::OUStringToOString( stringURI,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ returnedID = setupAnyStorage( xSFA, canonicalURI, stringURI );
+ }
+ else
+ {
+ OSL_TRACE("Using existing storage for %s",
+ ::rtl::OUStringToOString( stringURI,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }
+
+// np - removed previous scripting framework security handling
+// now handled by modification to existing calls in sfx for basic
+//
+/* if( displayDialog )
+ {
+ try
+ {
+ OSL_TRACE("Adding to security mgr for %s",
+ ::rtl::OUStringToOString( stringURI,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ m_securityMgr.addScriptStorage( stringURI, returnedID );
+ }
+ catch ( RuntimeException & rte )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorageManager::createScriptStorageWithURI: " ).concat(
+ rte.Message ), Reference< XInterface >() );
+ }
+ }
+ else
+ {
+ OSL_TRACE("No need to security mgr for %s",
+ ::rtl::OUStringToOString( stringURI,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }*/
+ return returnedID;
+}
+
+//*************************************************************************
+Reference < XInterface > SAL_CALL
+ScriptStorageManager::getScriptStorage( sal_Int32 scriptStorageID )
+throw( RuntimeException )
+{
+ OSL_TRACE( "** ==> ScriptStorageManager in getStorageInstance\n" );
+ OSL_TRACE( "** ==> request for id=%d",scriptStorageID );
+
+ ScriptStorage_map::const_iterator itr =
+ m_ScriptStorageMap.find( scriptStorageID );
+
+ if ( itr == m_ScriptStorageMap.end() )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorageManager::getScriptStorage: invalid storage ID" ),
+ Reference< XInterface >() );
+ }
+ validateXRef( itr->second,
+ "ScriptStorageManager::getScriptStorage: Cannot get ScriptStorage from ScriptStorageHash" );
+ return itr->second;
+}
+
+//*******************************************************************
+sal_Int32 SAL_CALL
+ScriptStorageManager::getScriptStorageID( const ::rtl::OUString& origURI )
+ throw (::com::sun::star::uno::RuntimeException)
+{
+ StorageId_hash::const_iterator it = m_StorageIdOrigURIHash.find( origURI );
+
+ if ( it == m_StorageIdOrigURIHash.end() )
+ {
+ OUString message = OUSTR( "ScriptStorageManager::getScriptStorageID(): Cannot find storage for " );
+ if ( origURI.getLength() == 0 )
+ {
+ message = message.concat( OUSTR("Empty URI") );
+ }
+ else
+ {
+ message = message.concat( origURI );
+ }
+ OSL_TRACE( ::rtl::OUStringToOString( message,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ return -1;
+ }
+
+ return it->second;
+}
+
+//*******************************************************************
+void
+ScriptStorageManager::removeScriptDocURIHashEntry( const OUString & origURI )
+{
+ StorageId_hash::iterator it = m_StorageIdOrigURIHash.find( origURI );
+ if ( it == m_StorageIdOrigURIHash.end() )
+ {
+ OSL_TRACE( "ScriptStorageManager::removeScriptDocURIHashEntry: no entry to remove" );
+ return;
+ }
+
+ // remove entry for this doc url from orig uri map.
+ m_StorageIdOrigURIHash.erase( it );
+}
+
+//*******************************************************************
+void SAL_CALL
+ScriptStorageManager::refreshScriptStorage( const OUString & stringURI )
+throw( RuntimeException )
+{
+ OSL_TRACE( "** => ScriptStorageManager in refreshScriptStorage\n" );
+ OSL_TRACE( "** => refreshing URI: %s\n",
+ ::rtl::OUStringToOString(
+ stringURI, RTL_TEXTENCODING_ASCII_US ).pData->buffer);
+
+ sal_Int32 storageID = getScriptStorageID( stringURI );
+
+ if ( storageID == -1 )
+ {
+ OSL_TRACE( "** id was -1, no storage");
+ // Refreshing noexistent storage - just return
+ return;
+ }
+
+ try
+ {
+ Reference < storage::XScriptStorageRefresh > xSSR(
+ getScriptStorage( storageID ), UNO_QUERY );
+
+ xSSR->refresh();
+ }
+ catch ( RuntimeException & e )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorageManager::refreshScriptStorage: " ).concat(
+ e.Message ), Reference< XInterface >() );
+ }
+ catch ( Exception & e )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorageManager::refreshScriptStorage: " ).concat(
+ e.Message ), Reference< XInterface >() );
+ }
+}
+
+//*************************************************************************
+void SAL_CALL
+ScriptStorageManager::checkPermission( const OUString &
+scriptStorageURI, const OUString & permissionRequest )
+throw ( RuntimeException, lang::IllegalArgumentException, css::security::AccessControlException )
+{
+ try
+ {
+ m_securityMgr.checkPermission( scriptStorageURI, permissionRequest );
+ }
+ catch ( css::security::AccessControlException & e )
+ {
+ throw css::security::AccessControlException(
+ OUSTR( "ScriptStorageManager::checkPermission: AccessControlException: " ).concat(
+ e.Message ), Reference< XInterface >(), e.LackingPermission );
+ }
+ catch ( lang::IllegalArgumentException & e )
+ {
+ throw lang::IllegalArgumentException(
+ OUSTR( "ScriptStorageManager::checkPermission: IllegalArgumentException: " ).concat(
+ e.Message ), Reference< XInterface >(), e.ArgumentPosition );
+ }
+ catch ( RuntimeException & e )
+ {
+ throw RuntimeException(
+ OUSTR( "ScriptStorageManager::checkPermission: RuntimeException: " ).concat(
+ e.Message ), Reference< XInterface >() );
+ }
+}
+
+//*************************************************************************
+OUString SAL_CALL
+ScriptStorageManager::getImplementationName( )
+throw( RuntimeException )
+{
+ return s_implName;
+}
+
+//*************************************************************************
+sal_Bool SAL_CALL
+ScriptStorageManager::supportsService( const OUString& serviceName )
+throw( RuntimeException )
+{
+ OUString const * pNames = s_serviceNames.getConstArray();
+ for ( sal_Int32 nPos = s_serviceNames.getLength(); nPos--; )
+ {
+ if ( serviceName.equals( pNames[ nPos ] ) )
+ {
+ return sal_True;
+ }
+ }
+ return sal_False;
+}
+
+//*************************************************************************
+Sequence< OUString > SAL_CALL
+ScriptStorageManager::getSupportedServiceNames( )
+throw( RuntimeException )
+{
+ return s_serviceNames;
+}
+
+//*************************************************************************
+void SAL_CALL
+ScriptStorageManager::disposing( const ::com::sun::star::lang::EventObject& Source )
+throw ( ::com::sun::star::uno::RuntimeException )
+{
+ OSL_TRACE( "ScriptStorageManager::disposing started" );
+ OSL_TRACE( "event object type=%s",
+ ::rtl::OUStringToOString( getCppuType( &Source ).getTypeName(),
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ OUString storageURI;
+ bool removeSecurityPermission = true;
+ try
+ {
+ Reference< XInterface > xInterface = Source.Source;
+ // no UNO_QUERY_THROW since we want a 2nd change to query if it's
+ // not a document being disposed
+ Reference< frame::XModel > xModel = Reference< frame::XModel > ( xInterface, UNO_QUERY );
+ if( xModel.is() )
+ {
+ storageURI = xModel->getURL();
+ }
+ else
+ {
+ // UNO_QURY_THROW here since it's supposed to be either a doc
+ // or a XScriptInfo (in the case of a filesys script)
+ Reference< storage::XScriptInfo > xScriptInfo = Reference< storage::XScriptInfo > ( xInterface, UNO_QUERY_THROW );
+ storageURI = xScriptInfo->getParcelURI().concat( xScriptInfo->getFunctionName() );
+ // to save the user seeing the security dialogs every time they
+ // run the script we hang on to the permission for a given script
+ // for the lifetime of the Office
+ removeSecurityPermission = false;
+ // possibly need to encode it??
+ }
+ if ( storageURI.getLength() > 0 )
+ {
+ OSL_TRACE( "URI disposing is ... %s",
+ ::rtl::OUStringToOString( storageURI,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ }
+ }
+ catch ( RuntimeException& e )
+ {
+ OUString message =
+ OUSTR(
+ "ScriptStorageManager::disposing: can't get script context, reason = " );
+ message = message.concat( e.Message );
+ OSL_TRACE( ::rtl::OUStringToOString( message,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ return;
+ }
+
+
+ // grab storage id.
+ sal_Int32 scriptStorageID = getScriptStorageID( storageURI );
+
+ // no need to do anything if there's no doc storage
+ if( scriptStorageID == -1 )
+ {
+ return;
+ }
+
+ OSL_TRACE( "disposing storageID = %d", scriptStorageID );
+
+ // attempt to get the storage from the hash to ensure that we have a
+ // valid storageID
+ ScriptStorage_map::const_iterator itr =
+ m_ScriptStorageMap.find( scriptStorageID );
+
+ if ( itr == m_ScriptStorageMap.end() )
+ {
+ OSL_TRACE( "Entry for storage id %d doesn't exist in map", scriptStorageID );
+ return;
+ }
+
+ // erase the entry from the hash
+ m_ScriptStorageMap.erase( scriptStorageID );
+ removeScriptDocURIHashEntry( storageURI );
+ if ( removeSecurityPermission )
+ {
+ m_securityMgr.removePermissionSettings ( storageURI );
+ }
+}
+} // Namespace
+
+namespace scripting_runtimemgr
+{
+//*************************************************************************
+Reference< XInterface > SAL_CALL
+ssm_create(
+ const Reference< XComponentContext > & xCompC )
+{
+ return ( cppu::OWeakObject * ) new ::scripting_impl::ScriptStorageManager( xCompC );
+}
+
+//*************************************************************************
+Sequence< OUString >
+ssm_getSupportedServiceNames( )
+SAL_THROW( () )
+{
+ return ::scripting_impl::s_serviceNames;
+}
+
+//*************************************************************************
+OUString
+ssm_getImplementationName( )
+SAL_THROW( () )
+{
+ return ::scripting_impl::s_implName;
+}
+}
diff --git a/scripting/source/storage/ScriptStorageManager.hxx b/scripting/source/storage/ScriptStorageManager.hxx
new file mode 100644
index 000000000000..731fac062a1e
--- /dev/null
+++ b/scripting/source/storage/ScriptStorageManager.hxx
@@ -0,0 +1,228 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptStorageManager.hxx,v $
+ * $Revision: 1.19 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+
+#ifndef _DRAFTS_COM_SUN_STAR_SCRIPT_FRAMEWORK_STORAGE_SCRIPTSTORAGEMANAGER_HXX_
+#define _DRAFTS_COM_SUN_STAR_SCRIPT_FRAMEWORK_STORAGE_SCRIPTSTORAGEMANAGER_HXX_
+
+#include <hash_map>
+#include <map>
+
+#include <osl/mutex.hxx>
+#include <cppuhelper/implbase4.hxx>
+
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XEventListener.hpp>
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+#include <com/sun/star/security/AccessControlException.hpp>
+#include <com/sun/star/uno/RuntimeException.hpp>
+
+#include <drafts/com/sun/star/script/framework/storage/XScriptStorageManager.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptStorageRefresh.hpp>
+#include <drafts/com/sun/star/script/framework/storage/XScriptInfo.hpp>
+#include <drafts/com/sun/star/script/framework/security/XScriptSecurity.hpp>
+#include "ScriptSecurityManager.hxx"
+
+
+namespace scripting_impl
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+// Define a map used to store the ScriptingStorages key;d by ID
+typedef ::std::map < sal_Int32, css::uno::Reference < css::uno::XInterface > >
+ ScriptStorage_map;
+
+typedef ::std::hash_map < ::rtl::OUString, sal_Int32, ::rtl::OUStringHash>
+ StorageId_hash;
+
+class ScriptStorageManager : public
+ ::cppu::WeakImplHelper4 < dcsssf::storage::XScriptStorageManager,
+ dcsssf::security::XScriptSecurity, css::lang::XServiceInfo,
+ css::lang::XEventListener >
+{
+public:
+ explicit ScriptStorageManager(
+ const css::uno::Reference< css::uno::XComponentContext > & xContext )
+ SAL_THROW ( ( css::uno::RuntimeException ) );
+
+
+ ~ScriptStorageManager() SAL_THROW ( () );
+
+ // XServiceInfo implementation
+ //======================================================================
+ virtual ::rtl::OUString SAL_CALL getImplementationName()
+ throw( css::uno::RuntimeException );
+ //----------------------------------------------------------------------
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
+ throw( css::uno::RuntimeException );
+ //----------------------------------------------------------------------
+ virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
+ throw( css::uno::RuntimeException );
+ //======================================================================
+
+ //XScriptStorageManager
+ //======================================================================
+ /**
+ create a ScriptStorage using the XSimpleFileAccess passed as an
+ argument, and return a ID for getting the associated ScriptStorage
+
+ @params xSFA
+ an implementation of XSimpleFileAccess that knows its own base URL
+ and can thus take URLs relative to that base.
+
+ @returns an unsigned short ScriptStorage ID, which can be used in the
+ getScriptStorage method
+ */
+ virtual sal_Int32 SAL_CALL createScriptStorage(
+ const css::uno::Reference< css::ucb::XSimpleFileAccess > & xSFA )
+ throw ( css::uno::RuntimeException );
+ //----------------------------------------------------------------------
+ /**
+ create a ScriptStorage using the XSimpleFileAccess, and a string URL
+ and return a ID for getting the associated ScriptStorage
+
+ @params xSFA
+ a standard implementation of XSimpleFileAccess
+
+ @params stringURI
+ a string URI to the head of the script storage
+
+ @returns an unsigned short ScriptStorage ID, which can be used in the
+ getScriptStorage method
+ */
+ virtual sal_Int32 SAL_CALL
+ createScriptStorageWithURI(
+ const css::uno::Reference< css::ucb::XSimpleFileAccess >& xSFA,
+ const ::rtl::OUString& stringURI )
+ throw ( css::uno::RuntimeException );
+ //----------------------------------------------------------------------
+ /**
+ get a ScriptStorage component using its scriptStorageID
+
+ @params scriptStorageID
+ the usigned short returned by one of the methods above. ID=0 is
+ reserved for the application/share scripts, and ID=1 is reserved
+ for the application/user scripts
+
+ @returns an XInterface to a component that implements the ScriptStorage
+ service
+ */
+ virtual css::uno::Reference< css::uno::XInterface > SAL_CALL getScriptStorage(
+ sal_Int32 scriptStorageID )
+ throw ( css::uno::RuntimeException );
+
+ /**
+ get a ScriptStorage ID using storage URI
+
+ @param scriptStorageURI
+ the file URL for the document will retrieve storage id for the document, special treatment is reserved for the strings "USER"and "SHARE" which
+ retrieve storage id for application/user application/share areas respectively.
+
+
+ @returns as long ScriptStorage ID (-1 if no storage exists), which can be used in getScriptStorage method.
+
+ */
+
+ virtual sal_Int32 SAL_CALL getScriptStorageID( const ::rtl::OUString& scriptStorageURI )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ /**
+ refresh a storage component using its URI
+
+ @param StringURI
+ URI of storage area, for documents, url to document eg, file:///home/user/ADocument.sxw To refresh the storage for user or share area, use USER or SHARE respectively instead or a url.
+
+ */
+
+ virtual void SAL_CALL refreshScriptStorage(const ::rtl::OUString & stringURI)
+ throw ( css::uno::RuntimeException );
+ //======================================================================
+
+ //XScriptSecurity
+ //======================================================================
+ //----------------------------------------------------------------------
+ /**
+ the language independent interface for invocation
+
+ @param scriptURI
+ a string containing the script URI
+
+ @returns
+ the value returned from the function being invoked
+
+ @throws IllegalArgumentException
+ if there is no matching script name
+
+ */
+ virtual void SAL_CALL ScriptStorageManager::checkPermission(
+ const rtl::OUString & scriptStorageURI,
+ const rtl::OUString & permissionRequest )
+ throw ( css::uno::RuntimeException, css::lang::IllegalArgumentException,
+ css::security::AccessControlException );
+ //======================================================================
+
+ //XEventListener
+ //======================================================================
+
+ virtual void SAL_CALL disposing( const css::lang::EventObject& Source )
+ throw ( css::uno::RuntimeException );
+
+private:
+ ScriptStorageManager( const ScriptStorageManager & );
+ ScriptStorageManager& operator= ( const ScriptStorageManager & );
+
+ void removeScriptDocURIHashEntry( const ::rtl::OUString & origURI );
+
+ // to obtain other services if needed
+ css::uno::Reference< css::uno::XComponentContext > m_xContext;
+ css::uno::Reference< css::lang::XMultiComponentFactory > m_xMgr;
+ ::osl::Mutex m_mutex;
+ ScriptStorage_map m_ScriptStorageMap;
+ StorageId_hash m_StorageIdOrigURIHash;
+ sal_Int32 m_count;
+ scripting_securitymgr::ScriptSecurityManager m_securityMgr;
+
+ void setupAppStorage( const css::uno::Reference< css::util::XMacroExpander > & xME,
+ const ::rtl::OUString & storageStr,
+ const ::rtl::OUString & appStr)
+ SAL_THROW ( ( css::uno::RuntimeException ) );
+
+ sal_Int32 setupAnyStorage(
+ const css::uno::Reference< css::ucb::XSimpleFileAccess> & xSFA,
+ const ::rtl::OUString & storageStr,
+ const ::rtl::OUString & origStringURI )
+ SAL_THROW ( ( css::uno::RuntimeException ) );
+
+};
+} // scripting_impl
+
+#endif //_COM_SUN_STAR_SCRIPTING_STORAGE_SCRIPTSTORAGEMANAGER_HXX_
diff --git a/scripting/source/storage/ScriptURI.cxx b/scripting/source/storage/ScriptURI.cxx
new file mode 100644
index 000000000000..5225a0c8af8a
--- /dev/null
+++ b/scripting/source/storage/ScriptURI.cxx
@@ -0,0 +1,230 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptURI.cxx,v $
+ * $Revision: 1.11 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include <osl/diagnose.h>
+#include <osl/file.h>
+
+#ifdef _DEBUG
+#include <stdio.h>
+#endif
+
+//Local headers
+#include "ScriptURI.hxx"
+#include <util/util.hxx>
+
+using namespace ::rtl;
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::lang;
+
+
+namespace scripting_impl {
+
+static const OUString schema = OUString::createFromAscii( "vnd.sun.star.script://" );
+
+/**
+ * Constructor
+ *
+ * @param scriptURI the string script URI
+ */
+ScriptURI::ScriptURI( const ::rtl::OUString& scriptURI )
+ throw ( IllegalArgumentException ) : m_uri( scriptURI )
+{
+ OSL_TRACE( "received uri: %s\n",::rtl::OUStringToOString( m_uri, RTL_TEXTENCODING_ASCII_US).pData->buffer );
+ set_values( parseIt() );
+ if( !isValid() )
+ {
+ OSL_TRACE( "ScriptURI ctor: throwing IllegalArgException" );
+ throw IllegalArgumentException(
+ OUSTR( "Failed to parse invalid URI: " ).concat( scriptURI ),
+ Reference < XInterface > (), 1 );
+ }
+}
+
+/**
+ * Destuctor
+ *
+ */
+// dtor should never throw exceptions, so ensure this by specifying it
+ScriptURI::~ScriptURI() SAL_THROW( () )
+{
+ OSL_TRACE( "< ScriptURI dtor called >\n" );
+}
+
+/**
+ * This function is used to determine if this object represents a valid URI
+ *
+ */
+bool ScriptURI::isValid( ) {
+ return ( m_valid == sal_True );
+}
+
+/**
+ * This function returns the location of the script
+ *
+ */
+::rtl::OUString ScriptURI::getLocation( )
+{
+ return m_location;
+}
+
+/**
+ * This function returns the language of the script, eg. java, StarBasic,...
+ *
+ */
+::rtl::OUString ScriptURI::getLanguage( )
+{
+ return m_language;
+}
+
+/**
+ * This function returns the language dependent function name of the script
+ *
+ */
+::rtl::OUString ScriptURI::getFunctionName( )
+{
+ return m_functionName;
+}
+
+/**
+ * This function returns the language independent logical name of the script
+ *
+ */
+::rtl::OUString ScriptURI::getLogicalName( )
+{
+ return m_logicalName;
+}
+
+/**
+ * This function returns the full URI
+ *
+ */
+::rtl::OUString ScriptURI::getURI( )
+{
+ return m_uri;
+}
+
+//Private mutex guarded method for setting the members
+void ScriptURI::set_values( scripting_impl::Uri values )
+{
+ osl::Guard< ::osl::Mutex > aGuard( m_mutex );
+ m_valid = values.valid;
+ m_location = values.location;
+ m_language = values.language;
+// format is vnd.sun.star.script://[function_name]?language=[languge]&location=[location]
+// LogicalName is now not used anymore, further more the ScriptURI class
+// will be retired also and a new UNO service will be used. Additionally the
+// parcel-description will also need to be modified to remove logical name
+// In order to temporarly support the existing code functionname is
+// set to the logica name parsed by this class. So getLogicalName() and
+// getFunctionName() return identical string.
+//
+
+ m_functionName = values.logicalName;
+ m_logicalName = values.logicalName;
+
+}
+/**
+ * This is a private method used for parsing the URI received by the
+ * initialization.
+ *
+ */
+// rather naive parsing?
+Uri ScriptURI::parseIt()
+{
+ sal_Int32 schemaLen = schema.getLength();
+ scripting_impl::Uri results;
+ results.valid = sal_True;
+ //attempt to parse
+ // check that it starts vnd.sun.star.script
+ // better check for OBO errors here
+ if( m_uri.indexOf( schema ) != 0 )
+ {
+ OSL_TRACE( "wrong schema" );
+ results.valid=sal_False;
+ return results;
+ }
+
+ // substr from here to the '?' and set the logical name
+ sal_Int32 len = m_uri.indexOf( '?' );
+ if( len == -1 )
+ {
+ // no queries so just set the logical name
+ results.logicalName = m_uri.copy( schemaLen );
+ return results;
+ }
+ results.logicalName = m_uri.copy( schemaLen, len-schemaLen );
+ OSL_TRACE( "log name: %s\n", ::rtl::OUStringToOString( results.logicalName,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ len++;
+ // now get the attributes
+ OUString attr;
+ do
+ {
+ attr = m_uri.getToken( 0, '&', len );
+ OSL_TRACE( "chunk: %s\n", ::rtl::OUStringToOString( attr,
+ RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+
+ if( attr.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "language" ) )
+ == sal_True )
+ {
+ sal_Int32 len2 = attr.indexOf('=');
+ results.language = attr.copy( len2 + 1 );
+ continue;
+ }
+ else if ( attr.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "location" ) )
+ == sal_True )
+ {
+ sal_Int32 len2 = attr.indexOf( '=' );
+ results.location = attr.copy( len2 + 1 );
+ continue;
+ }
+ else if ( attr.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "function" ) )
+ == sal_True )
+ {
+ sal_Int32 len2 = attr.indexOf( '=' );
+ results.functionName = attr.copy( len2 + 1 );
+ continue;
+ }
+ else
+ {
+ OSL_TRACE( "Unknown attribute?\n" );
+ }
+ }
+ while ( len >= 0 );
+
+ // parse is good
+ return results;
+}
+
+} // namespace script_uri
diff --git a/scripting/source/storage/ScriptURI.hxx b/scripting/source/storage/ScriptURI.hxx
new file mode 100644
index 000000000000..dec46f4f40b2
--- /dev/null
+++ b/scripting/source/storage/ScriptURI.hxx
@@ -0,0 +1,123 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptURI.hxx,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef __FRAMEWORK_STORAGE_SCRIPTURI_HXX_
+#define __FRAMEWORK_STORAGE_SCRIPTURI_HXX_
+
+#include <osl/mutex.hxx>
+#include <rtl/ustring>
+
+#include <com/sun/star/lang/IllegalArgumentException.hpp>
+
+namespace scripting_impl {
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+struct Uri {
+ bool valid;
+ ::rtl::OUString uri;
+ ::rtl::OUString location;
+ ::rtl::OUString language;
+ ::rtl::OUString functionName;
+ ::rtl::OUString logicalName;
+};
+/**
+ * Helper class for dealing with script URIs.
+ */
+class ScriptURI
+{
+public:
+ ScriptURI( const ::rtl::OUString& scriptURI )
+ throw ( css::lang::IllegalArgumentException );
+ virtual ~ScriptURI() SAL_THROW ( () );
+
+ /**
+ * This function returns the location of the script
+ *
+ */
+ virtual ::rtl::OUString getLocation();
+
+ /**
+ * This function returns the language of the script, eg. java,
+ * StarBasic,...
+ *
+ */
+ virtual ::rtl::OUString getLanguage();
+
+ /**
+ * This function returns the language dependent function name of
+ * the script
+ */
+ virtual ::rtl::OUString getFunctionName();
+
+ /**
+ * This function returns the language independent logical name of
+ * the script
+ */
+ virtual ::rtl::OUString getLogicalName();
+
+ /**
+ * This function returns the full URI
+ *
+ */
+ virtual ::rtl::OUString getURI();
+
+private:
+ ::osl::Mutex m_mutex;
+
+ /** @internal */
+ sal_Bool m_valid;
+
+ //the private strings
+ /** the string representation of the this objects URI */
+ ::rtl::OUString m_uri;
+ /** the location of the script referred to by this URI */
+ ::rtl::OUString m_location;
+ /** the language of the script referred to by this URI */
+ ::rtl::OUString m_language;
+ /** the language dependent function name of the script referred to by this URI */
+ ::rtl::OUString m_functionName;
+ /** the language independent logical name of the script referred to by this URI */
+ ::rtl::OUString m_logicalName;
+
+ //attempt to parse the URI provided
+ /** @internal */
+ Uri parseIt();
+ //set the members
+ /** @internal */
+ void set_values( Uri );
+ bool isValid();
+}
+; // class ScriptURI
+
+} //namespace script_uri
+
+#endif // define __FRAMEWORK_STORAGE_SCRIPTURI_HXX_
diff --git a/scripting/source/storage/XMLElement.cxx b/scripting/source/storage/XMLElement.cxx
new file mode 100644
index 000000000000..b8093f3912a5
--- /dev/null
+++ b/scripting/source/storage/XMLElement.cxx
@@ -0,0 +1,172 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: XMLElement.cxx,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include "XMLElement.hxx"
+#include <osl/diagnose.h>
+
+using namespace rtl;
+using namespace com::sun::star;
+using namespace com::sun::star::uno;
+
+namespace scripting_impl
+{
+
+//*************************************************************************
+void XMLElement::addAttribute( OUString const & rAttrName, OUString const & rValue )
+SAL_THROW( () )
+{
+ OSL_TRACE( "XMLElement::addAttribute\n" );
+
+ _attrNames.push_back( rAttrName );
+ _attrValues.push_back( rValue );
+}
+
+//*************************************************************************
+void XMLElement::addSubElement( Reference< xml::sax::XAttributeList > const & xElem )
+SAL_THROW( () )
+{
+ OSL_TRACE( "XMLElement::addSubElement\n" );
+
+ _subElems.push_back( xElem );
+}
+
+//*************************************************************************
+Reference< xml::sax::XAttributeList > XMLElement::getSubElement( sal_Int32 nIndex )
+SAL_THROW( () )
+{
+ OSL_TRACE( "XMLElement::getSubElement\n" );
+
+ return _subElems[ ( size_t )nIndex ];
+}
+
+//*************************************************************************
+void XMLElement::dumpSubElements( Reference< xml::sax::XExtendedDocumentHandler > const & xOut )
+{
+ OSL_TRACE( "+++++ XMLElement::dumpSubElement\n" );
+
+ for ( size_t nPos = 0; nPos < _subElems.size(); ++nPos )
+ {
+ XMLElement * pElem = static_cast< XMLElement * >( _subElems[ nPos ].get() );
+ pElem->dump( xOut );
+ }
+}
+
+//*************************************************************************
+void XMLElement::dump( Reference< xml::sax::XExtendedDocumentHandler > const & xOut )
+{
+ OSL_TRACE( "XMLElement::dump" );
+
+ xOut->ignorableWhitespace( OUString() );
+ OSL_TRACE( "XMLElement::dump starting %s",::rtl::OUStringToOString(
+ _name, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+ xOut->startElement( _name, static_cast< xml::sax::XAttributeList * >( this ) );
+ // Write out CDATA
+ if( _chars.getLength() > 0 )
+ {
+ xOut->ignorableWhitespace( OUString() );
+ xOut->characters( _chars );
+ }
+ // write sub elements
+ dumpSubElements( xOut );
+ xOut->ignorableWhitespace( OUString() );
+ xOut->endElement( _name );
+ OSL_TRACE( "XMLElement::dump ending %s",::rtl::OUStringToOString(
+ _name, RTL_TEXTENCODING_ASCII_US ).pData->buffer );
+}
+
+//*************************************************************************
+// XAttributeList
+sal_Int16 XMLElement::getLength()
+throw ( RuntimeException )
+{
+ OSL_TRACE( "XMLElement::getLength\n" );
+
+ return _attrNames.size();
+}
+
+//*************************************************************************
+OUString XMLElement::getNameByIndex( sal_Int16 nPos )
+throw ( RuntimeException )
+{
+ OSL_TRACE( "XMLElement::getNameByIndex\n" );
+ OSL_ASSERT( ( size_t )nPos < _attrNames.size() );
+
+ return _attrNames[ nPos ];
+}
+
+//*************************************************************************
+OUString XMLElement::getTypeByIndex( sal_Int16 nPos )
+throw ( RuntimeException )
+{
+ OSL_TRACE( "XMLElement::getTypeByIndex\n" );
+ OSL_ASSERT( (size_t)nPos < _attrNames.size() );
+
+ // xxx todo
+ return OUString();
+}
+
+//*************************************************************************
+OUString XMLElement::getTypeByName( OUString const & rName )
+throw ( RuntimeException )
+{
+ OSL_TRACE( "XMLElement::getTypeByName\n" );
+ // xxx todo
+ return OUString();
+}
+
+//*************************************************************************
+OUString XMLElement::getValueByIndex( sal_Int16 nPos )
+throw ( RuntimeException )
+{
+ OSL_TRACE( "XMLElement::getValueByIndex\n" );
+ OSL_ASSERT( ( size_t )nPos < _attrNames.size() );
+
+ return _attrValues[ nPos ];
+}
+
+//*************************************************************************
+OUString XMLElement::getValueByName( OUString const & rName )
+throw ( RuntimeException )
+{
+ OSL_TRACE( "XMLElement::getValueByName\n" );
+
+ for ( size_t nPos = 0; nPos < _attrNames.size(); ++nPos )
+ {
+ if (_attrNames[ nPos ] == rName)
+ {
+ return _attrValues[ nPos ];
+ }
+ }
+ return OUString();
+}
+
+}
diff --git a/scripting/source/storage/XMLElement.hxx b/scripting/source/storage/XMLElement.hxx
new file mode 100644
index 000000000000..8977f16b8648
--- /dev/null
+++ b/scripting/source/storage/XMLElement.hxx
@@ -0,0 +1,143 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: XMLElement.hxx,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+#ifndef _SCRIPTING_XML_ELEMENT_HXX_
+#define _SCRIPTING_XML_ELEMENT_HXX_
+
+#include <vector>
+
+#include <cppuhelper/implbase1.hxx>
+
+#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>
+
+namespace scripting_impl
+{
+// for simplification
+#define css ::com::sun::star
+#define dcsssf ::drafts::com::sun::star::script::framework
+
+/*##################################################################################################
+
+ EXPORTING
+
+##################################################################################################*/
+
+//==================================================================================================
+class XMLElement : public ::cppu::WeakImplHelper1< css::xml::sax::XAttributeList >
+{
+public:
+ inline XMLElement( ::rtl::OUString const & name, ::rtl::OUString const & chars )
+ SAL_THROW( () )
+ : _name( name ), _chars( chars )
+ {
+ }
+
+ inline XMLElement( ::rtl::OUString const & name )
+ SAL_THROW( () )
+ : _name( name )
+ {
+ }
+
+ /** Adds a sub element of element.
+
+ @param xElem element reference
+ */
+ void SAL_CALL addSubElement(
+ css::uno::Reference< css::xml::sax::XAttributeList > const & xElem )
+ SAL_THROW( () );
+
+ /** Gets sub element of given index. The index follows order in which sub elements were added.
+
+ @param nIndex index of sub element
+ */
+ css::uno::Reference< css::xml::sax::XAttributeList > SAL_CALL getSubElement(
+ sal_Int32 nIndex )
+ SAL_THROW( () );
+
+ /** Adds an attribute to elements.
+
+ @param rAttrName qname of attribute
+ @param rValue value string of element
+ */
+ void SAL_CALL addAttribute( ::rtl::OUString const & rAttrName,
+ ::rtl::OUString const & rValue )
+ SAL_THROW( () );
+
+ /** Gets the tag name (qname) of element.
+
+ @return
+ qname of element
+ */
+ inline ::rtl::OUString SAL_CALL getName() SAL_THROW( () )
+ {
+ return _name;
+ }
+
+ /** Dumps out element (and all sub elements).
+
+ @param xOut document handler to be written to
+ */
+ void SAL_CALL dump(
+ css::uno::Reference< css::xml::sax::XExtendedDocumentHandler > const & xOut );
+ /** Dumps out sub elements (and all further sub elements).
+
+ @param xOut document handler to be written to
+ */
+ void SAL_CALL dumpSubElements(
+ css::uno::Reference< css::xml::sax::XExtendedDocumentHandler > const & xOut );
+
+ // XAttributeList
+ virtual sal_Int16 SAL_CALL getLength()
+ throw ( css::uno::RuntimeException );
+ virtual ::rtl::OUString SAL_CALL getNameByIndex( sal_Int16 nPos )
+ throw ( css::uno::RuntimeException );
+ virtual ::rtl::OUString SAL_CALL getTypeByIndex( sal_Int16 nPos )
+ throw ( css::uno::RuntimeException );
+ virtual ::rtl::OUString SAL_CALL getTypeByName( ::rtl::OUString const & rName )
+ throw ( css::uno::RuntimeException );
+ virtual ::rtl::OUString SAL_CALL getValueByIndex( sal_Int16 nPos )
+ throw ( css::uno::RuntimeException );
+ virtual ::rtl::OUString SAL_CALL getValueByName( ::rtl::OUString const & rName )
+ throw ( css::uno::RuntimeException );
+
+protected:
+ ::rtl::OUString _name;
+
+ ::rtl::OUString _chars;
+
+ ::std::vector< ::rtl::OUString > _attrNames;
+ ::std::vector< ::rtl::OUString > _attrValues;
+
+ ::std::vector< css::uno::Reference<
+ css::xml::sax::XAttributeList > > _subElems;
+};
+
+}
+
+#endif
diff --git a/scripting/source/storage/exports.dxp b/scripting/source/storage/exports.dxp
new file mode 100644
index 000000000000..9630d7e06768
--- /dev/null
+++ b/scripting/source/storage/exports.dxp
@@ -0,0 +1,3 @@
+component_getImplementationEnvironment
+component_writeInfo
+component_getFactory
diff --git a/scripting/source/storage/makefile.mk b/scripting/source/storage/makefile.mk
new file mode 100644
index 000000000000..a6f06369a3b5
--- /dev/null
+++ b/scripting/source/storage/makefile.mk
@@ -0,0 +1,57 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.7 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+PRJ=..$/..
+
+PRJNAME= scripting
+TARGET= storage
+USE_DEFFILE= TRUE
+ENABLE_EXCEPTIONS=TRUE
+COMP1TYPELIST=$(TARGET)
+
+# --- Settings -----------------------------------------------------
+
+.INCLUDE : settings.mk
+
+# ------------------------------------------------------------------
+
+SLOFILES=\
+ $(SLO)$/ScriptURI.obj\
+ $(SLO)$/ScriptStorage.obj\
+ $(SLO)$/ScriptInfo.obj\
+ $(SLO)$/ScriptMetadataImporter.obj\
+ $(SLO)$/ScriptElement.obj\
+ $(SLO)$/XMLElement.obj\
+ $(SLO)$/ScriptStorageManager.obj\
+ $(SLO)$/ScriptSecurityManager.obj\
+
+# --- Targets ------------------------------------------------------
+
+.INCLUDE : target.mk
diff --git a/scripting/source/storage/storage.xml b/scripting/source/storage/storage.xml
new file mode 100644
index 000000000000..6438dc7006b2
--- /dev/null
+++ b/scripting/source/storage/storage.xml
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE module-description PUBLIC "-//StarOffice//DTD ComponentDescription 1.0//EN" "module-description.dtd">
+<module-description xmlns:xlink="http://www.w3.org/1999/xlink">
+ <module-name>storage</module-name>
+ <component-description>
+ <author></author>
+ <name>drafts.com.sun.star.script.framework.storage.ScriptStorage</name>
+ <description></description>
+ <loader-name>com.sun.star.loader.SharedLibrary</loader-name>
+ <language>c++</language>
+ <status value="draft"/>
+ <supported-service>drafts.com.sun.star.script.framework.storage.ScriptingStorage</supported-service>
+ <type>com.sun.star.beans.XPropertySet</type>
+ <type>com.sun.star.beans.XPropertyContainer</type>
+ <type>com.sun.star.uno.Exception</type>
+ <type>com.sun.star.uno.XComponentContext</type>
+ <type>com.sun.star.uno.XWeak</type>
+ <type>com.sun.star.io.IOException</type>
+ <type>com.sun.star.io.XStream</type>
+ <type>com.sun.star.io.XOutputStream</type>
+ <type>com.sun.star.registry.XRegistryKey</type>
+ <type>drafts.com.sun.star.script.framework.storage.XScriptInfo</type>
+ <type>drafts.com.sun.star.script.framework.storage.XScriptInfoAccess</type>
+ <type>drafts.com.sun.star.script.framework.security.XScriptSecurity</type>
+ <type>drafts.com.sun.star.script.framework.storage.XScriptStorageExport</type>
+ <type>drafts.com.sun.star.script.framework.storage.XScriptStorageRefresh</type>
+ <type>com.sun.star.lang.XInitialization</type>
+ <type>drafts.com.sun.star.script.framework.storage.XScriptStorageManager</type>
+ <type>com.sun.star.xml.sax.XExtendedDocumentHandler</type>
+ <type>com.sun.star.xml.sax.XParser</type>
+ <type>com.sun.star.io.XInputStream</type>
+ <type>com.sun.star.ucb.XSimpleFileAccess2</type>
+ <type>com.sun.star.xml.sax.SAXException</type>
+ <type>com.sun.star.xml.sax.XAttributeList</type>
+ <type>com.sun.star.io.XActiveDataSource</type>
+ <type>com.sun.star.security.AccessControlException</type>
+ <type>com.sun.star.security.RuntimePermission</type>
+ <type>com.sun.star.lang.IllegalArgumentException</type>
+ </component-description>
+ <project-build-dependency>cppuhelper</project-build-dependency>
+ <project-build-dependency>cppu</project-build-dependency>
+ <project-build-dependency>sal</project-build-dependency>
+ <runtime-module-dependency>cppuhelper2$(COM)</runtime-module-dependency>
+ <runtime-module-dependency>cppu2</runtime-module-dependency>
+ <runtime-module-dependency>sal2</runtime-module-dependency>
+ <runtime-module-dependency>ucb</runtime-module-dependency>
+</module-description>
diff --git a/scripting/source/stringresource/makefile.mk b/scripting/source/stringresource/makefile.mk
new file mode 100644
index 000000000000..970a0c5d7b05
--- /dev/null
+++ b/scripting/source/stringresource/makefile.mk
@@ -0,0 +1,66 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.4 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+PRJ=..$/..
+
+PRJNAME=scripting
+TARGET=stringresource
+ENABLE_EXCEPTIONS=TRUE
+
+# --- Settings -----------------------------------------------------
+
+.INCLUDE : settings.mk
+DLLPRE =
+
+# ------------------------------------------------------------------
+
+SLOFILES= \
+ $(SLO)$/stringresource.obj \
+
+SHL1TARGET= $(TARGET)$(DLLPOSTFIX).uno
+SHL1IMPLIB= i$(TARGET)
+
+SHL1VERSIONMAP=$(TARGET).map
+SHL1DEF=$(MISC)$/$(SHL1TARGET).def
+DEF1NAME=$(SHL1TARGET)
+
+SHL1STDLIBS= \
+ $(TOOLSLIB) \
+ $(CPPUHELPERLIB) \
+ $(CPPULIB) \
+ $(SALLIB)
+
+SHL1DEPN=
+SHL1LIBS=$(SLB)$/$(TARGET).lib
+
+# --- Targets ------------------------------------------------------
+
+.INCLUDE : target.mk
diff --git a/scripting/source/stringresource/stringresource.cxx b/scripting/source/stringresource/stringresource.cxx
new file mode 100644
index 000000000000..4b1a4489a4a4
--- /dev/null
+++ b/scripting/source/stringresource/stringresource.cxx
@@ -0,0 +1,3088 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: stringresource.cxx,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+// MARKER(update_precomp.py): autogen include statement, do not remove
+#include "precompiled_scripting.hxx"
+#include "stringresource.hxx"
+#include <com/sun/star/io/XTextInputStream.hpp>
+#include <com/sun/star/io/XTextOutputStream.hpp>
+#include <com/sun/star/io/XActiveDataSink.hpp>
+#include <com/sun/star/io/XActiveDataSource.hpp>
+#include <com/sun/star/io/XStream.hpp>
+#include <com/sun/star/io/XSeekable.hpp>
+#include <com/sun/star/embed/ElementModes.hpp>
+#include <com/sun/star/lang/XMultiComponentFactory.hpp>
+#ifndef _CPPUHELPER_IMPLEMENTATIONENTRY_HXX_
+#include <cppuhelper/implementationentry.hxx>
+#endif
+#include <com/sun/star/beans/XPropertySet.hpp>
+#include <com/sun/star/container/XNameAccess.hpp>
+
+
+#include <rtl/ustrbuf.hxx>
+#include <rtl/strbuf.hxx>
+#include <tools/urlobj.hxx>
+
+using namespace ::com::sun::star;
+using namespace ::com::sun::star::lang;
+using namespace ::com::sun::star::uno;
+using namespace ::com::sun::star::ucb;
+using namespace ::com::sun::star::util;
+using namespace ::com::sun::star::embed;
+using namespace ::com::sun::star::container;
+
+
+//.........................................................................
+namespace stringresource
+{
+//.........................................................................
+
+// =============================================================================
+// mutex
+// =============================================================================
+
+::osl::Mutex& getMutex()
+{
+ static ::osl::Mutex* s_pMutex = 0;
+ if ( !s_pMutex )
+ {
+ ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
+ if ( !s_pMutex )
+ {
+ static ::osl::Mutex s_aMutex;
+ s_pMutex = &s_aMutex;
+ }
+ }
+ return *s_pMutex;
+}
+
+
+// =============================================================================
+// StringResourceImpl
+// =============================================================================
+
+// component operations
+static Sequence< ::rtl::OUString > getSupportedServiceNames_StringResourceImpl()
+{
+ Sequence< ::rtl::OUString > names(1);
+ names[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.resource.StringResource") );
+ return names;
+}
+
+static ::rtl::OUString getImplementationName_StringResourceImpl()
+{
+ return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.scripting.StringResource") );
+}
+
+static Reference< XInterface > SAL_CALL create_StringResourceImpl(
+ Reference< XComponentContext > const & xContext )
+ SAL_THROW( () )
+{
+ return static_cast< ::cppu::OWeakObject * >( new StringResourcePersistenceImpl( xContext ) );
+}
+
+
+// =============================================================================
+
+StringResourceImpl::StringResourceImpl( const Reference< XComponentContext >& rxContext )
+ : m_xContext( rxContext )
+ , m_pCurrentLocaleItem( NULL )
+ , m_pDefaultLocaleItem( NULL )
+ , m_bDefaultModified( false )
+ , m_aListenerContainer( getMutex() )
+ , m_bModified( false )
+ , m_bReadOnly( false )
+ , m_nNextUniqueNumericId( UNIQUE_NUMBER_NEEDS_INITIALISATION )
+{
+}
+
+// =============================================================================
+
+StringResourceImpl::~StringResourceImpl()
+{
+ for( LocaleItemVectorIt it = m_aLocaleItemVector.begin(); it != m_aLocaleItemVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ delete pLocaleItem;
+ }
+
+ for( LocaleItemVectorIt it = m_aDeletedLocaleItemVector.begin(); it != m_aDeletedLocaleItemVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ delete pLocaleItem;
+ }
+}
+
+
+// =============================================================================
+// XServiceInfo
+
+::rtl::OUString StringResourceImpl::getImplementationName( ) throw (RuntimeException)
+{
+ return getImplementationName_StringResourceImpl();
+}
+
+sal_Bool StringResourceImpl::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
+{
+ Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
+ const ::rtl::OUString* pNames = aNames.getConstArray();
+ const ::rtl::OUString* pEnd = pNames + aNames.getLength();
+ for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
+ ;
+
+ return pNames != pEnd;
+}
+
+Sequence< ::rtl::OUString > StringResourceImpl::getSupportedServiceNames( ) throw (RuntimeException)
+{
+ return getSupportedServiceNames_StringResourceImpl();
+}
+
+
+// =============================================================================
+// XModifyBroadcaster
+
+void StringResourceImpl::addModifyListener( const Reference< XModifyListener >& aListener )
+ throw (RuntimeException)
+{
+ if( !aListener.is() )
+ throw RuntimeException();
+
+ ::osl::MutexGuard aGuard( getMutex() );
+ Reference< XInterface > xIface( aListener, UNO_QUERY );
+ m_aListenerContainer.addInterface( xIface );
+}
+
+void StringResourceImpl::removeModifyListener( const Reference< XModifyListener >& aListener )
+ throw (RuntimeException)
+{
+ if( !aListener.is() )
+ throw RuntimeException();
+
+ ::osl::MutexGuard aGuard( getMutex() );
+ Reference< XInterface > xIface( aListener, UNO_QUERY );
+ m_aListenerContainer.removeInterface( xIface );
+}
+
+
+// =============================================================================
+// XStringResourceResolver
+
+::rtl::OUString StringResourceImpl::implResolveString
+ ( const ::rtl::OUString& ResourceID, LocaleItem* pLocaleItem )
+ throw (::com::sun::star::resource::MissingResourceException)
+{
+ ::rtl::OUString aRetStr;
+ bool bSuccess = false;
+ if( pLocaleItem != NULL && loadLocale( pLocaleItem ) )
+ {
+ IdToStringMap::iterator it = pLocaleItem->m_aIdToStringMap.find( ResourceID );
+ if( !( it == pLocaleItem->m_aIdToStringMap.end() ) )
+ {
+ aRetStr = (*it).second;
+ bSuccess = true;
+ }
+ }
+ if( !bSuccess )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "StringResourceImpl: No entry for ResourceID: " );
+ errorMsg.concat( ResourceID );
+ throw ::com::sun::star::resource::MissingResourceException( errorMsg, Reference< XInterface >() );
+ }
+ return aRetStr;
+}
+
+::rtl::OUString StringResourceImpl::resolveString( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ return implResolveString( ResourceID, m_pCurrentLocaleItem );
+}
+
+::rtl::OUString StringResourceImpl::resolveStringForLocale( const ::rtl::OUString& ResourceID, const Locale& locale )
+ throw ( ::com::sun::star::resource::MissingResourceException, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ LocaleItem* pLocaleItem = getItemForLocale( locale, false );
+ return implResolveString( ResourceID, pLocaleItem );
+}
+
+sal_Bool StringResourceImpl::implHasEntryForId( const ::rtl::OUString& ResourceID, LocaleItem* pLocaleItem )
+{
+ bool bSuccess = false;
+ if( pLocaleItem != NULL && loadLocale( pLocaleItem ) )
+ {
+ IdToStringMap::iterator it = pLocaleItem->m_aIdToStringMap.find( ResourceID );
+ if( !( it == pLocaleItem->m_aIdToStringMap.end() ) )
+ bSuccess = true;
+ }
+ return bSuccess;
+}
+
+sal_Bool StringResourceImpl::hasEntryForId( const ::rtl::OUString& ResourceID )
+ throw (RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ return implHasEntryForId( ResourceID, m_pCurrentLocaleItem );
+}
+
+sal_Bool StringResourceImpl::hasEntryForIdAndLocale( const ::rtl::OUString& ResourceID,
+ const Locale& locale )
+ throw (RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ LocaleItem* pLocaleItem = getItemForLocale( locale, false );
+ return implHasEntryForId( ResourceID, pLocaleItem );
+}
+
+Sequence< ::rtl::OUString > StringResourceImpl::implGetResourceIDs( LocaleItem* pLocaleItem )
+{
+ Sequence< ::rtl::OUString > aIDSeq( 0 );
+ if( pLocaleItem && loadLocale( pLocaleItem ) )
+ {
+ const IdToStringMap& rHashMap = pLocaleItem->m_aIdToStringMap;
+ sal_Int32 nResourceIDCount = rHashMap.size();
+ aIDSeq.realloc( nResourceIDCount );
+ ::rtl::OUString* pStrings = aIDSeq.getArray();
+
+ IdToStringMap::const_iterator it;
+ int iTarget = 0;
+ for( it = rHashMap.begin(); it != rHashMap.end(); it++ )
+ {
+ ::rtl::OUString aStr = (*it).first;
+ pStrings[iTarget] = aStr;
+ iTarget++;
+ }
+ }
+ return aIDSeq;
+}
+
+Sequence< ::rtl::OUString > StringResourceImpl::getResourceIDsForLocale
+ ( const Locale& locale ) throw (::com::sun::star::uno::RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ LocaleItem* pLocaleItem = getItemForLocale( locale, false );
+ return implGetResourceIDs( pLocaleItem );
+}
+
+Sequence< ::rtl::OUString > StringResourceImpl::getResourceIDs( )
+ throw (RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ return implGetResourceIDs( m_pCurrentLocaleItem );
+}
+
+Locale StringResourceImpl::getCurrentLocale()
+ throw (RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ Locale aRetLocale;
+ if( m_pCurrentLocaleItem != NULL )
+ aRetLocale = m_pCurrentLocaleItem->m_locale;
+ return aRetLocale;
+}
+
+Locale StringResourceImpl::getDefaultLocale( )
+ throw (RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ Locale aRetLocale;
+ if( m_pDefaultLocaleItem != NULL )
+ aRetLocale = m_pDefaultLocaleItem->m_locale;
+ return aRetLocale;
+}
+
+Sequence< Locale > StringResourceImpl::getLocales( )
+ throw (RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ sal_Int32 nSize = m_aLocaleItemVector.size();
+ Sequence< Locale > aLocalSeq( nSize );
+ Locale* pLocales = aLocalSeq.getArray();
+ int iTarget = 0;
+ for( LocaleItemVectorConstIt it = m_aLocaleItemVector.begin(); it != m_aLocaleItemVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ pLocales[iTarget] = pLocaleItem->m_locale;
+ iTarget++;
+ }
+ return aLocalSeq;
+}
+
+
+// =============================================================================
+// XStringResourceManager
+
+void StringResourceImpl::implCheckReadOnly( const sal_Char* pExceptionMsg )
+ throw (NoSupportException)
+{
+ if( m_bReadOnly )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( pExceptionMsg );
+ throw NoSupportException( errorMsg, Reference< XInterface >() );
+ }
+}
+
+sal_Bool StringResourceImpl::isReadOnly()
+ throw (RuntimeException)
+{
+ return m_bReadOnly;
+}
+
+void StringResourceImpl::setCurrentLocale( const Locale& locale, sal_Bool FindClosestMatch )
+ throw (IllegalArgumentException, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ LocaleItem* pLocaleItem = NULL;
+ if( FindClosestMatch )
+ pLocaleItem = getClosestMatchItemForLocale( locale );
+ else
+ pLocaleItem = getItemForLocale( locale, true );
+
+ if( pLocaleItem != NULL )
+ {
+ loadLocale( pLocaleItem );
+ m_pCurrentLocaleItem = pLocaleItem;
+
+ // Only notify without modifying
+ implNotifyListeners();
+ }
+}
+
+void StringResourceImpl::setDefaultLocale( const Locale& locale )
+ throw (IllegalArgumentException, RuntimeException,NoSupportException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ implCheckReadOnly( "StringResourceImpl::setDefaultLocale(): Read only" );
+
+ LocaleItem* pLocaleItem = getItemForLocale( locale, true );
+ if( pLocaleItem && pLocaleItem != m_pDefaultLocaleItem )
+ {
+ if( m_pDefaultLocaleItem )
+ {
+ LocaleItem* pChangedDefaultLocaleItem = new LocaleItem( m_pDefaultLocaleItem->m_locale );
+ m_aChangedDefaultLocaleVector.push_back( pChangedDefaultLocaleItem );
+ }
+
+ m_pDefaultLocaleItem = pLocaleItem;
+ m_bDefaultModified = true;
+ implModified();
+ }
+}
+
+void StringResourceImpl::implSetString( const ::rtl::OUString& ResourceID,
+ const ::rtl::OUString& Str, LocaleItem* pLocaleItem )
+{
+ if( pLocaleItem != NULL && loadLocale( pLocaleItem ) )
+ {
+ IdToStringMap& rHashMap = pLocaleItem->m_aIdToStringMap;
+
+ IdToStringMap::iterator it = rHashMap.find( ResourceID );
+ bool bNew = ( it == rHashMap.end() );
+ if( bNew )
+ {
+ IdToIndexMap& rIndexMap = pLocaleItem->m_aIdToIndexMap;
+ rIndexMap[ ResourceID ] = pLocaleItem->m_nNextIndex++;
+ implScanIdForNumber( ResourceID );
+ }
+ rHashMap[ ResourceID ] = Str;
+ pLocaleItem->m_bModified = true;
+ implModified();
+ }
+}
+
+void StringResourceImpl::setString( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str )
+ throw (NoSupportException, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ implCheckReadOnly( "StringResourceImpl::setString(): Read only" );
+ implSetString( ResourceID, Str, m_pCurrentLocaleItem );
+}
+
+void StringResourceImpl::setStringForLocale
+ ( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str, const Locale& locale )
+ throw (NoSupportException, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ implCheckReadOnly( "StringResourceImpl::setStringForLocale(): Read only" );
+ LocaleItem* pLocaleItem = getItemForLocale( locale, false );
+ implSetString( ResourceID, Str, pLocaleItem );
+}
+
+void StringResourceImpl::implRemoveId( const ::rtl::OUString& ResourceID, LocaleItem* pLocaleItem )
+ throw (::com::sun::star::resource::MissingResourceException)
+{
+ if( pLocaleItem != NULL && loadLocale( pLocaleItem ) )
+ {
+ IdToStringMap& rHashMap = pLocaleItem->m_aIdToStringMap;
+ IdToStringMap::iterator it = rHashMap.find( ResourceID );
+ if( it == rHashMap.end() )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "StringResourceImpl: No entries for ResourceID: " );
+ errorMsg.concat( ResourceID );
+ throw ::com::sun::star::resource::MissingResourceException( errorMsg, Reference< XInterface >() );
+ }
+ rHashMap.erase( it );
+ pLocaleItem->m_bModified = true;
+ implModified();
+ }
+}
+
+void StringResourceImpl::removeId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException, NoSupportException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ implCheckReadOnly( "StringResourceImpl::removeId(): Read only" );
+ implRemoveId( ResourceID, m_pCurrentLocaleItem );
+}
+
+void StringResourceImpl::removeIdForLocale( const ::rtl::OUString& ResourceID, const Locale& locale )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException, NoSupportException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ implCheckReadOnly( "StringResourceImpl::removeIdForLocale(): Read only" );
+ LocaleItem* pLocaleItem = getItemForLocale( locale, false );
+ implRemoveId( ResourceID, pLocaleItem );
+}
+
+void StringResourceImpl::newLocale( const Locale& locale )
+ throw (ElementExistException, IllegalArgumentException, RuntimeException, NoSupportException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ implCheckReadOnly( "StringResourceImpl::newLocale(): Read only" );
+
+ if( getItemForLocale( locale, false ) != NULL )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "StringResourceImpl: locale already exists" );
+ throw ElementExistException( errorMsg, Reference< XInterface >() );
+ }
+
+ // TODO?: Check if locale is valid? How?
+ bool bValid = true;
+ if( bValid )
+ {
+ LocaleItem* pLocaleItem = new LocaleItem( locale );
+ m_aLocaleItemVector.push_back( pLocaleItem );
+ pLocaleItem->m_bModified = true;
+
+ // Copy strings from default locale
+ LocaleItem* pCopyFromItem = m_pDefaultLocaleItem;
+ if( pCopyFromItem == NULL )
+ pCopyFromItem = m_pCurrentLocaleItem;
+ if( pCopyFromItem != NULL )
+ {
+ const IdToStringMap& rSourceMap = pCopyFromItem->m_aIdToStringMap;
+ IdToStringMap& rTargetMap = pLocaleItem->m_aIdToStringMap;
+ IdToStringMap::const_iterator it;
+ for( it = rSourceMap.begin(); it != rSourceMap.end(); it++ )
+ {
+ ::rtl::OUString aId = (*it).first;
+ ::rtl::OUString aStr = (*it).second;
+ rTargetMap[ aId ] = aStr;
+ }
+
+ const IdToIndexMap& rSourceIndexMap = pCopyFromItem->m_aIdToIndexMap;
+ IdToIndexMap& rTargetIndexMap = pLocaleItem->m_aIdToIndexMap;
+ IdToIndexMap::const_iterator it_index;
+ for( it_index = rSourceIndexMap.begin(); it_index != rSourceIndexMap.end(); it_index++ )
+ {
+ ::rtl::OUString aId = (*it_index).first;
+ sal_Int32 nIndex = (*it_index).second;
+ rTargetIndexMap[ aId ] = nIndex;
+ }
+ pLocaleItem->m_nNextIndex = pCopyFromItem->m_nNextIndex;
+ }
+
+ if( m_pCurrentLocaleItem == NULL )
+ m_pCurrentLocaleItem = pLocaleItem;
+
+ if( m_pDefaultLocaleItem == NULL )
+ {
+ m_pDefaultLocaleItem = pLocaleItem;
+ m_bDefaultModified = true;
+ }
+
+ implModified();
+ }
+ else
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "StringResourceImpl: Invalid locale" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 0 );
+ }
+}
+
+void StringResourceImpl::removeLocale( const Locale& locale )
+ throw (IllegalArgumentException, RuntimeException, NoSupportException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ implCheckReadOnly( "StringResourceImpl::removeLocale(): Read only" );
+
+ LocaleItem* pRemoveItem = getItemForLocale( locale, true );
+ if( pRemoveItem )
+ {
+ // Last locale?
+ sal_Int32 nLocaleCount = m_aLocaleItemVector.size();
+ if( nLocaleCount > 1 )
+ {
+ LocaleItem* pFallbackItem = NULL;
+ if( m_pCurrentLocaleItem == pRemoveItem ||
+ m_pDefaultLocaleItem == pRemoveItem )
+ {
+ for( LocaleItemVectorIt it = m_aLocaleItemVector.begin(); it != m_aLocaleItemVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem != pRemoveItem )
+ {
+ pFallbackItem = pLocaleItem;
+ break;
+ }
+ }
+ if( m_pCurrentLocaleItem == pRemoveItem )
+ {
+ sal_Bool FindClosestMatch = false;
+ setCurrentLocale( pFallbackItem->m_locale, FindClosestMatch );
+ }
+ if( m_pDefaultLocaleItem == pRemoveItem )
+ {
+ setDefaultLocale( pFallbackItem->m_locale );
+ }
+ }
+ }
+ for( LocaleItemVectorIt it = m_aLocaleItemVector.begin(); it != m_aLocaleItemVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem == pRemoveItem )
+ {
+ // Remember locale item to delete file while storing
+ m_aDeletedLocaleItemVector.push_back( pLocaleItem );
+
+ // Last locale?
+ if( nLocaleCount == 1 )
+ {
+ m_nNextUniqueNumericId = 0;
+ if( m_pDefaultLocaleItem )
+ {
+ LocaleItem* pChangedDefaultLocaleItem = new LocaleItem( m_pDefaultLocaleItem->m_locale );
+ m_aChangedDefaultLocaleVector.push_back( pChangedDefaultLocaleItem );
+ }
+ m_pCurrentLocaleItem = NULL;
+ m_pDefaultLocaleItem = NULL;
+ }
+
+ m_aLocaleItemVector.erase( it );
+
+ implModified();
+ break;
+ }
+ }
+ }
+}
+
+void StringResourceImpl::implScanIdForNumber( const ::rtl::OUString& ResourceID )
+{
+ const sal_Unicode* pSrc = ResourceID.getStr();
+ sal_Int32 nLen = ResourceID.getLength();
+
+ sal_Int32 nNumber = 0;
+ for( sal_Int32 i = 0 ; i < nLen ; i++ )
+ {
+ sal_Unicode c = pSrc[i];
+ if( c >= '0' && c <= '9' )
+ {
+ sal_uInt16 nDigitVal = c - '0';
+ nNumber = 10*nNumber + nDigitVal;
+ }
+ else
+ break;
+ }
+
+ if( m_nNextUniqueNumericId < nNumber + 1 )
+ m_nNextUniqueNumericId = nNumber + 1;
+}
+
+sal_Int32 StringResourceImpl::getUniqueNumericId( )
+ throw (RuntimeException, NoSupportException)
+{
+ if( m_nNextUniqueNumericId == UNIQUE_NUMBER_NEEDS_INITIALISATION )
+ {
+ implLoadAllLocales();
+ m_nNextUniqueNumericId = 0;
+ }
+
+ if( m_nNextUniqueNumericId < UNIQUE_NUMBER_NEEDS_INITIALISATION )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "getUniqueNumericId: Extended sal_Int32 range" );
+ throw NoSupportException( errorMsg, Reference< XInterface >() );
+ }
+ return m_nNextUniqueNumericId;
+}
+
+
+// =============================================================================
+// Private helper methods
+
+LocaleItem* StringResourceImpl::getItemForLocale
+ ( const Locale& locale, sal_Bool bException )
+ throw (::com::sun::star::lang::IllegalArgumentException)
+{
+ LocaleItem* pRetItem = NULL;
+
+ // Search for locale
+ for( LocaleItemVectorConstIt it = m_aLocaleItemVector.begin(); it != m_aLocaleItemVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem )
+ {
+ Locale& cmp_locale = pLocaleItem->m_locale;
+ if( cmp_locale.Language == locale.Language &&
+ cmp_locale.Country == locale.Country &&
+ cmp_locale.Variant == locale.Variant )
+ {
+ pRetItem = pLocaleItem;
+ break;
+ }
+ }
+ }
+
+ if( pRetItem == NULL && bException )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "StringResourceImpl: Invalid locale" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 0 );
+ }
+ return pRetItem;
+}
+
+// Returns the LocalItem for a given locale, if it exists, otherwise NULL
+// This method performes a closest match search, at least the language must match
+LocaleItem* StringResourceImpl::getClosestMatchItemForLocale( const Locale& locale )
+{
+ LocaleItem* pRetItem = NULL;
+
+ // Search for locale
+ for( sal_Int32 iPass = 0 ; iPass <= 2 ; ++iPass )
+ {
+ for( LocaleItemVectorConstIt it = m_aLocaleItemVector.begin(); it != m_aLocaleItemVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem )
+ {
+ Locale& cmp_locale = pLocaleItem->m_locale;
+ if( cmp_locale.Language == locale.Language &&
+ (iPass > 1 || cmp_locale.Country == locale.Country) &&
+ (iPass > 0 || cmp_locale.Variant == locale.Variant) )
+ {
+ pRetItem = pLocaleItem;
+ break;
+ }
+ }
+ }
+ if( pRetItem )
+ break;
+ }
+
+ return pRetItem;
+}
+
+void StringResourceImpl::implModified( void )
+{
+ m_bModified = true;
+ implNotifyListeners();
+}
+
+void StringResourceImpl::implNotifyListeners( void )
+{
+ EventObject aEvent;
+ aEvent.Source = static_cast< XInterface* >( (OWeakObject*)this );
+
+ ::cppu::OInterfaceIteratorHelper it( m_aListenerContainer );
+ while( it.hasMoreElements() )
+ {
+ Reference< XInterface > xIface = it.next();
+ Reference< XModifyListener > xListener( xIface, UNO_QUERY );
+ try
+ {
+ xListener->modified( aEvent );
+ }
+ catch(RuntimeException&)
+ {
+ it.remove();
+ }
+ }
+}
+
+
+// =============================================================================
+// Loading
+
+bool StringResourceImpl::loadLocale( LocaleItem* pLocaleItem )
+{
+ // Base implementation has nothing to load
+ (void)pLocaleItem;
+ return true;
+}
+
+void StringResourceImpl::implLoadAllLocales( void )
+{
+ // Base implementation has nothing to load
+}
+
+
+Reference< XMultiComponentFactory > StringResourceImpl::getMultiComponentFactory( void )
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ if( !m_xMCF.is() )
+ {
+ Reference< XMultiComponentFactory > xSMgr( m_xContext->getServiceManager(), UNO_QUERY );
+ if( !xSMgr.is() )
+ {
+ throw RuntimeException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StringResourceImpl::getMultiComponentFactory: Couldn't instantiate MultiComponentFactory" ) ),
+ Reference< XInterface >() );
+ }
+ m_xMCF = xSMgr;
+ }
+ return m_xMCF;
+}
+
+
+// =============================================================================
+// StringResourcePersistenceImpl
+// =============================================================================
+
+StringResourcePersistenceImpl::StringResourcePersistenceImpl( const Reference< XComponentContext >& rxContext )
+ : StringResourcePersistenceImpl_BASE( rxContext )
+{
+}
+
+// -----------------------------------------------------------------------------
+
+StringResourcePersistenceImpl::~StringResourcePersistenceImpl()
+{
+}
+
+// -----------------------------------------------------------------------------
+// XServiceInfo
+// -----------------------------------------------------------------------------
+
+::rtl::OUString StringResourcePersistenceImpl::getImplementationName( )
+ throw (RuntimeException)
+{
+ return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM
+ ( "com.sun.star.comp.scripting.StringResourceWithLocation") );
+}
+
+// -----------------------------------------------------------------------------
+
+sal_Bool StringResourcePersistenceImpl::supportsService( const ::rtl::OUString& rServiceName )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::supportsService( rServiceName );
+}
+
+// -----------------------------------------------------------------------------
+
+Sequence< ::rtl::OUString > StringResourcePersistenceImpl::getSupportedServiceNames( )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getSupportedServiceNames();
+}
+
+// -----------------------------------------------------------------------------
+// XInitialization base functionality for derived classes
+// -----------------------------------------------------------------------------
+
+static ::rtl::OUString aNameBaseDefaultStr = ::rtl::OUString::createFromAscii( "strings" );
+
+void StringResourcePersistenceImpl::implInitializeCommonParameters
+ ( const Sequence< Any >& aArguments )
+ throw (Exception, RuntimeException)
+{
+ bool bReadOnlyOk = (aArguments[1] >>= m_bReadOnly);
+ if( !bReadOnlyOk )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "XInitialization::initialize: Expected ReadOnly flag" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 1 );
+ }
+
+ com::sun::star::lang::Locale aCurrentLocale;
+ bool bLocaleOk = (aArguments[2] >>= aCurrentLocale);
+ if( !bLocaleOk )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "XInitialization::initialize: Expected Locale" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 2 );
+ }
+
+ bool bNameBaseOk = (aArguments[3] >>= m_aNameBase);
+ if( !bNameBaseOk )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "XInitialization::initialize: Expected NameBase string" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 3 );
+ }
+ if( m_aNameBase.getLength() == 0 )
+ m_aNameBase = aNameBaseDefaultStr;
+
+ bool bCommentOk = (aArguments[4] >>= m_aComment);
+ if( !bCommentOk )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "XInitialization::initialize: Expected Comment string" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 4 );
+ }
+
+ implScanLocales();
+
+ sal_Bool FindClosestMatch = true;
+ setCurrentLocale( aCurrentLocale, FindClosestMatch );
+}
+
+// -----------------------------------------------------------------------------
+// Forwarding calls to base class
+
+// XModifyBroadcaster
+void StringResourcePersistenceImpl::addModifyListener( const Reference< XModifyListener >& aListener )
+ throw (RuntimeException)
+{
+ StringResourceImpl::addModifyListener( aListener );
+}
+void StringResourcePersistenceImpl::removeModifyListener( const Reference< XModifyListener >& aListener )
+ throw (RuntimeException)
+{
+ StringResourceImpl::removeModifyListener( aListener );
+}
+
+// XStringResourceResolver
+::rtl::OUString StringResourcePersistenceImpl::resolveString( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException)
+{
+ return StringResourceImpl::resolveString( ResourceID ) ;
+}
+::rtl::OUString StringResourcePersistenceImpl::resolveStringForLocale( const ::rtl::OUString& ResourceID, const Locale& locale )
+ throw ( ::com::sun::star::resource::MissingResourceException, RuntimeException)
+{
+ return StringResourceImpl::resolveStringForLocale( ResourceID, locale );
+}
+sal_Bool StringResourcePersistenceImpl::hasEntryForId( const ::rtl::OUString& ResourceID )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::hasEntryForId( ResourceID ) ;
+}
+sal_Bool StringResourcePersistenceImpl::hasEntryForIdAndLocale( const ::rtl::OUString& ResourceID,
+ const Locale& locale )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::hasEntryForIdAndLocale( ResourceID, locale );
+}
+Locale StringResourcePersistenceImpl::getCurrentLocale()
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getCurrentLocale();
+}
+Locale StringResourcePersistenceImpl::getDefaultLocale( )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getDefaultLocale();
+}
+Sequence< Locale > StringResourcePersistenceImpl::getLocales( )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getLocales();
+}
+
+// XStringResourceManager
+sal_Bool StringResourcePersistenceImpl::isReadOnly()
+ throw (RuntimeException)
+{
+ return StringResourceImpl::isReadOnly();
+}
+void StringResourcePersistenceImpl::setCurrentLocale( const Locale& locale, sal_Bool FindClosestMatch )
+ throw (IllegalArgumentException, RuntimeException)
+{
+ StringResourceImpl::setCurrentLocale( locale, FindClosestMatch );
+}
+void StringResourcePersistenceImpl::setDefaultLocale( const Locale& locale )
+ throw (IllegalArgumentException, RuntimeException,NoSupportException)
+{
+ StringResourceImpl::setDefaultLocale( locale );
+}
+Sequence< ::rtl::OUString > StringResourcePersistenceImpl::getResourceIDs( )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getResourceIDs();
+}
+void StringResourcePersistenceImpl::setString( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str )
+ throw (NoSupportException, RuntimeException)
+{
+ StringResourceImpl::setString( ResourceID, Str );
+}
+void StringResourcePersistenceImpl::setStringForLocale
+ ( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str, const Locale& locale )
+ throw (NoSupportException, RuntimeException)
+{
+ StringResourceImpl::setStringForLocale( ResourceID, Str, locale );
+}
+Sequence< ::rtl::OUString > StringResourcePersistenceImpl::getResourceIDsForLocale
+ ( const Locale& locale ) throw (::com::sun::star::uno::RuntimeException)
+{
+ return StringResourceImpl::getResourceIDsForLocale( locale );
+}
+void StringResourcePersistenceImpl::removeId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::removeId( ResourceID );
+}
+void StringResourcePersistenceImpl::removeIdForLocale( const ::rtl::OUString& ResourceID, const Locale& locale )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::removeIdForLocale( ResourceID, locale );
+}
+void StringResourcePersistenceImpl::newLocale( const Locale& locale )
+ throw (ElementExistException, IllegalArgumentException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::newLocale( locale );
+}
+void StringResourcePersistenceImpl::removeLocale( const Locale& locale )
+ throw (IllegalArgumentException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::removeLocale( locale );
+}
+sal_Int32 StringResourcePersistenceImpl::getUniqueNumericId( )
+ throw (RuntimeException, NoSupportException)
+{
+ return StringResourceImpl::getUniqueNumericId();
+}
+
+// -----------------------------------------------------------------------------
+// XStringResourcePersistence
+
+void StringResourcePersistenceImpl::store()
+ throw (NoSupportException, Exception, RuntimeException)
+{
+}
+
+sal_Bool StringResourcePersistenceImpl::isModified( )
+ throw (RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ return m_bModified;
+}
+
+void StringResourcePersistenceImpl::setComment( const ::rtl::OUString& Comment )
+ throw (::com::sun::star::uno::RuntimeException)
+{
+ m_aComment = Comment;
+}
+
+void StringResourcePersistenceImpl::storeToStorage( const Reference< XStorage >& Storage,
+ const ::rtl::OUString& NameBase, const ::rtl::OUString& Comment )
+ throw (Exception, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ bool bUsedForStore = false;
+ bool bStoreAll = true;
+ implStoreAtStorage( NameBase, Comment, Storage, bUsedForStore, bStoreAll );
+}
+
+void StringResourcePersistenceImpl::implStoreAtStorage
+(
+ const ::rtl::OUString& aNameBase,
+ const ::rtl::OUString& aComment,
+ const Reference< ::com::sun::star::embed::XStorage >& Storage,
+ bool bUsedForStore,
+ bool bStoreAll
+)
+ throw (Exception, RuntimeException)
+{
+ // Delete files for deleted locales
+ if( bUsedForStore )
+ {
+ while( m_aDeletedLocaleItemVector.size() > 0 )
+ {
+ LocaleItemVectorIt it = m_aDeletedLocaleItemVector.begin();
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem != NULL )
+ {
+ ::rtl::OUString aStreamName = implGetFileNameForLocaleItem( pLocaleItem, m_aNameBase );
+ aStreamName += ::rtl::OUString::createFromAscii( ".properties" );
+
+ try
+ {
+ Storage->removeElement( aStreamName );
+ }
+ catch( Exception& )
+ {}
+
+ m_aDeletedLocaleItemVector.erase( it );
+ delete pLocaleItem;
+ }
+ }
+ }
+
+ for( LocaleItemVectorConstIt it = m_aLocaleItemVector.begin(); it != m_aLocaleItemVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem != NULL && (bStoreAll || pLocaleItem->m_bModified) &&
+ loadLocale( pLocaleItem ) )
+ {
+ ::rtl::OUString aStreamName = implGetFileNameForLocaleItem( pLocaleItem, aNameBase );
+ aStreamName += ::rtl::OUString::createFromAscii( ".properties" );
+
+ Reference< io::XStream > xElementStream =
+ Storage->openStreamElement( aStreamName, ElementModes::READWRITE );
+
+ ::rtl::OUString aPropName = ::rtl::OUString::createFromAscii( "MediaType" );
+ ::rtl::OUString aMime = ::rtl::OUString::createFromAscii( "text/plain" );
+
+ uno::Reference< beans::XPropertySet > xProps( xElementStream, uno::UNO_QUERY );
+ OSL_ENSURE( xProps.is(), "The StorageStream must implement XPropertySet interface!\n" );
+ if ( xProps.is() )
+ {
+ xProps->setPropertyValue( aPropName, uno::makeAny( aMime ) );
+
+ aPropName = ::rtl::OUString::createFromAscii( "UseCommonStoragePasswordEncryption" );
+ xProps->setPropertyValue( aPropName, uno::makeAny( sal_True ) );
+ }
+
+ Reference< io::XOutputStream > xOutputStream = xElementStream->getOutputStream();
+ if( xOutputStream.is() )
+ implWritePropertiesFile( pLocaleItem, xOutputStream, aComment );
+ xOutputStream->closeOutput();
+
+ if( bUsedForStore )
+ pLocaleItem->m_bModified = false;
+ }
+ }
+
+ // Delete files for changed defaults
+ if( bUsedForStore )
+ {
+ for( LocaleItemVectorIt it = m_aChangedDefaultLocaleVector.begin();
+ it != m_aChangedDefaultLocaleVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem != NULL )
+ {
+ ::rtl::OUString aStreamName = implGetFileNameForLocaleItem( pLocaleItem, m_aNameBase );
+ aStreamName += ::rtl::OUString::createFromAscii( ".default" );
+
+ try
+ {
+ Storage->removeElement( aStreamName );
+ }
+ catch( Exception& )
+ {}
+
+ delete pLocaleItem;
+ }
+ }
+ m_aChangedDefaultLocaleVector.clear();
+ }
+
+ // Default locale
+ if( m_pDefaultLocaleItem != NULL && (bStoreAll || m_bDefaultModified) )
+ {
+ ::rtl::OUString aStreamName = implGetFileNameForLocaleItem( m_pDefaultLocaleItem, aNameBase );
+ aStreamName += ::rtl::OUString::createFromAscii( ".default" );
+
+ Reference< io::XStream > xElementStream =
+ Storage->openStreamElement( aStreamName, ElementModes::READWRITE );
+
+ ::rtl::OUString aPropName = ::rtl::OUString::createFromAscii( "MediaType" );
+ ::rtl::OUString aMime = ::rtl::OUString::createFromAscii( "text/plain" );
+
+ // Only create stream without content
+ Reference< io::XOutputStream > xOutputStream = xElementStream->getOutputStream();
+ xOutputStream->closeOutput();
+
+ if( bUsedForStore )
+ m_bDefaultModified = false;
+ }
+}
+
+void StringResourcePersistenceImpl::storeToURL( const ::rtl::OUString& URL,
+ const ::rtl::OUString& NameBase, const ::rtl::OUString& Comment,
+ const Reference< ::com::sun::star::task::XInteractionHandler >& Handler )
+ throw (Exception, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ bool bUsedForStore = false;
+ bool bStoreAll = true;
+
+ Reference< XMultiComponentFactory > xMCF = getMultiComponentFactory();
+ Reference< ucb::XSimpleFileAccess > xFileAccess;
+ xFileAccess = Reference< ucb::XSimpleFileAccess >( xMCF->createInstanceWithContext
+ ( ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ),
+ m_xContext ), UNO_QUERY );
+ if( xFileAccess.is() && Handler.is() )
+ xFileAccess->setInteractionHandler( Handler );
+
+ implStoreAtLocation( URL, NameBase, Comment, xFileAccess, bUsedForStore, bStoreAll );
+}
+
+void StringResourcePersistenceImpl::implKillRemovedLocaleFiles
+(
+ const ::rtl::OUString& Location,
+ const ::rtl::OUString& aNameBase,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >& xFileAccess
+)
+ throw (Exception, RuntimeException)
+{
+ // Delete files for deleted locales
+ while( m_aDeletedLocaleItemVector.size() > 0 )
+ {
+ LocaleItemVectorIt it = m_aDeletedLocaleItemVector.begin();
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem != NULL )
+ {
+ ::rtl::OUString aCompleteFileName =
+ implGetPathForLocaleItem( pLocaleItem, aNameBase, Location );
+ if( xFileAccess->exists( aCompleteFileName ) )
+ xFileAccess->kill( aCompleteFileName );
+
+ m_aDeletedLocaleItemVector.erase( it );
+ delete pLocaleItem;
+ }
+ }
+}
+
+void StringResourcePersistenceImpl::implKillChangedDefaultFiles
+(
+ const ::rtl::OUString& Location,
+ const ::rtl::OUString& aNameBase,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >& xFileAccess
+)
+ throw (Exception, RuntimeException)
+{
+ // Delete files for changed defaults
+ for( LocaleItemVectorIt it = m_aChangedDefaultLocaleVector.begin();
+ it != m_aChangedDefaultLocaleVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem != NULL )
+ {
+ ::rtl::OUString aCompleteFileName =
+ implGetPathForLocaleItem( pLocaleItem, aNameBase, Location, true );
+ if( xFileAccess->exists( aCompleteFileName ) )
+ xFileAccess->kill( aCompleteFileName );
+
+ delete pLocaleItem;
+ }
+ }
+ m_aChangedDefaultLocaleVector.clear();
+}
+
+void StringResourcePersistenceImpl::implStoreAtLocation
+(
+ const ::rtl::OUString& Location,
+ const ::rtl::OUString& aNameBase,
+ const ::rtl::OUString& aComment,
+ const Reference< ucb::XSimpleFileAccess >& xFileAccess,
+ bool bUsedForStore,
+ bool bStoreAll,
+ bool bKillAll
+)
+ throw (Exception, RuntimeException)
+{
+ // Delete files for deleted locales
+ if( bUsedForStore || bKillAll )
+ implKillRemovedLocaleFiles( Location, aNameBase, xFileAccess );
+
+ for( LocaleItemVectorConstIt it = m_aLocaleItemVector.begin(); it != m_aLocaleItemVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem != NULL && (bStoreAll || bKillAll || pLocaleItem->m_bModified) &&
+ loadLocale( pLocaleItem ) )
+ {
+ ::rtl::OUString aCompleteFileName =
+ implGetPathForLocaleItem( pLocaleItem, aNameBase, Location );
+ if( xFileAccess->exists( aCompleteFileName ) )
+ xFileAccess->kill( aCompleteFileName );
+
+ if( !bKillAll )
+ {
+ // Create Output stream
+ Reference< io::XOutputStream > xOutputStream = xFileAccess->openFileWrite( aCompleteFileName );
+ if( xOutputStream.is() )
+ {
+ implWritePropertiesFile( pLocaleItem, xOutputStream, aComment );
+ xOutputStream->closeOutput();
+ }
+ if( bUsedForStore )
+ pLocaleItem->m_bModified = false;
+ }
+ }
+ }
+
+ // Delete files for changed defaults
+ if( bUsedForStore || bKillAll )
+ implKillChangedDefaultFiles( Location, aNameBase, xFileAccess );
+
+ // Default locale
+ if( m_pDefaultLocaleItem != NULL && (bStoreAll || bKillAll || m_bDefaultModified) )
+ {
+ ::rtl::OUString aCompleteFileName =
+ implGetPathForLocaleItem( m_pDefaultLocaleItem, aNameBase, Location, true );
+ if( xFileAccess->exists( aCompleteFileName ) )
+ xFileAccess->kill( aCompleteFileName );
+
+ if( !bKillAll )
+ {
+ // Create Output stream
+ Reference< io::XOutputStream > xOutputStream = xFileAccess->openFileWrite( aCompleteFileName );
+ if( xOutputStream.is() )
+ xOutputStream->closeOutput();
+
+ if( bUsedForStore )
+ m_bDefaultModified = false;
+ }
+ }
+}
+
+
+// -----------------------------------------------------------------------------
+// BinaryOutput, helper class for exportBinary
+
+class BinaryOutput
+{
+ Reference< XMultiComponentFactory > m_xMCF;
+ Reference< XComponentContext > m_xContext;
+ Reference< XInterface > m_xTempFile;
+ Reference< io::XOutputStream > m_xOutputStream;
+
+public:
+ BinaryOutput( Reference< XMultiComponentFactory > xMCF,
+ Reference< XComponentContext > xContext );
+
+ Reference< io::XOutputStream > getOutputStream( void )
+ { return m_xOutputStream; }
+
+ Sequence< ::sal_Int8 > closeAndGetData( void );
+
+ // Template to be used with sal_Int16 and sal_Unicode
+ template< class T >
+ void write16BitInt( T n );
+ void writeInt16( sal_Int16 n )
+ { write16BitInt( n ); }
+ void writeUnicodeChar( sal_Unicode n )
+ { write16BitInt( n ); }
+ void writeInt32( sal_Int32 n );
+ void writeString( const ::rtl::OUString& aStr );
+};
+
+BinaryOutput::BinaryOutput( Reference< XMultiComponentFactory > xMCF,
+ Reference< XComponentContext > xContext )
+ : m_xMCF( xMCF )
+ , m_xContext( xContext )
+{
+ m_xTempFile = m_xMCF->createInstanceWithContext
+ ( ::rtl::OUString::createFromAscii( "com.sun.star.io.TempFile" ), m_xContext );
+ if( m_xTempFile.is() )
+ m_xOutputStream = Reference< io::XOutputStream >( m_xTempFile, UNO_QUERY );
+}
+
+template< class T >
+void BinaryOutput::write16BitInt( T n )
+{
+ if( !m_xOutputStream.is() )
+ return;
+
+ Sequence< sal_Int8 > aSeq( 2 );
+ sal_Int8* p = aSeq.getArray();
+
+ sal_Int8 nLow = sal_Int8( n & 0xff );
+ sal_Int8 nHigh = sal_Int8( n >> 8 );
+
+ p[0] = nLow;
+ p[1] = nHigh;
+ m_xOutputStream->writeBytes( aSeq );
+}
+
+void BinaryOutput::writeInt32( sal_Int32 n )
+{
+ if( !m_xOutputStream.is() )
+ return;
+
+ Sequence< sal_Int8 > aSeq( 4 );
+ sal_Int8* p = aSeq.getArray();
+
+ for( sal_Int16 i = 0 ; i < 4 ; i++ )
+ {
+ p[i] = sal_Int8( n & 0xff );
+ n >>= 8;
+ }
+ m_xOutputStream->writeBytes( aSeq );
+}
+
+void BinaryOutput::writeString( const ::rtl::OUString& aStr )
+{
+ sal_Int32 nLen = aStr.getLength();
+ const sal_Unicode* pStr = aStr.getStr();
+
+ for( sal_Int32 i = 0 ; i < nLen ; i++ )
+ writeUnicodeChar( pStr[i] );
+
+ writeUnicodeChar( 0 );
+}
+
+Sequence< ::sal_Int8 > BinaryOutput::closeAndGetData( void )
+{
+ Sequence< ::sal_Int8 > aRetSeq;
+ if( !m_xOutputStream.is() )
+ return aRetSeq;
+
+ m_xOutputStream->closeOutput();
+
+ Reference< io::XSeekable> xSeekable( m_xTempFile, UNO_QUERY );
+ if( !xSeekable.is() )
+ return aRetSeq;
+
+ sal_Int32 nSize = (sal_Int32)xSeekable->getPosition();
+
+ Reference< io::XInputStream> xInputStream( m_xTempFile, UNO_QUERY );
+ if( !xInputStream.is() )
+ return aRetSeq;
+
+ xSeekable->seek( 0 );
+ sal_Int32 nRead = xInputStream->readBytes( aRetSeq, nSize );
+ (void)nRead;
+ OSL_ENSURE( nRead == nSize, "BinaryOutput::closeAndGetData: nRead != nSize" );
+
+ return aRetSeq;
+}
+
+
+// Binary format:
+
+// Header
+// Byte Content
+// 0 + 1 sal_Int16: Version, currently 0, low byte first
+// 2 + 3 sal_Int16: Locale count = n, low byte first
+// 4 + 5 sal_Int16: Default Locale position in Locale list, == n if none
+// 6 - 7 sal_Int32: Start index locale block 0, lowest byte first
+// (n-1) * sal_Int32: Start index locale block 1 to n, lowest byte first
+// 6 + 4*n sal_Int32: "Start index" non existing locale block n+1,
+// marks the first invalid index, kind of EOF
+
+// Locale block
+// All strings are stored as 2-Byte-0 terminated sequence
+// of 16 bit Unicode characters, each with low byte first
+// Empty strings only contain the 2-Byte-0
+
+// Members of com.sun.star.lang.Locale
+// with l1 = Locale.Language.getLength()
+// with l2 = Locale.Country.getLength()
+// with l3 = Locale.Variant.getLength()
+// pos0 = 0 Locale.Language
+// pos1 = 2 * (l1 + 1) Locale.Country
+// pos2 = pos1 + 2 * (l2 + 1) Locale.Variant
+// pos3 = pos2 + 2 * (l3 + 1)
+// pos3 Properties file written by implWritePropertiesFile
+
+Sequence< sal_Int8 > StringResourcePersistenceImpl::exportBinary( )
+ throw (RuntimeException)
+{
+ Reference< XMultiComponentFactory > xMCF = getMultiComponentFactory();
+ BinaryOutput aOut( xMCF, m_xContext );
+
+ sal_Int32 nLocaleCount = m_aLocaleItemVector.size();
+ Sequence< sal_Int8 >* pLocaleDataSeq = new Sequence< sal_Int8 >[ nLocaleCount ];
+
+ sal_Int32 iLocale = 0;
+ sal_Int32 iDefault = 0;
+ for( LocaleItemVectorConstIt it = m_aLocaleItemVector.begin();
+ it != m_aLocaleItemVector.end(); it++,iLocale++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem != NULL && loadLocale( pLocaleItem ) )
+ {
+ if( m_pDefaultLocaleItem == pLocaleItem )
+ iDefault = iLocale;
+
+ BinaryOutput aLocaleOut( m_xMCF, m_xContext );
+ implWriteLocaleBinary( pLocaleItem, aLocaleOut );
+
+ pLocaleDataSeq[iLocale] = aLocaleOut.closeAndGetData();
+ }
+ }
+
+ // Write header
+ sal_Int16 nVersion = 0;
+ sal_Int16 nLocaleCount16 = (sal_Int16)nLocaleCount;
+ sal_Int16 iDefault16 = (sal_Int16)iDefault;
+ aOut.writeInt16( nVersion );
+ aOut.writeInt16( nLocaleCount16 );
+ aOut.writeInt16( iDefault16 );
+
+ // Write data positions
+ sal_Int32 nDataPos = 6 + 4 * (nLocaleCount + 1);
+ for( iLocale = 0; iLocale < nLocaleCount; iLocale++ )
+ {
+ aOut.writeInt32( nDataPos );
+
+ Sequence< sal_Int8 >& rSeq = pLocaleDataSeq[iLocale];
+ sal_Int32 nSeqLen = rSeq.getLength();
+ nDataPos += nSeqLen;
+ }
+ // Write final position
+ aOut.writeInt32( nDataPos );
+
+ // Write data
+ Reference< io::XOutputStream > xOutputStream = aOut.getOutputStream();
+ if( xOutputStream.is() )
+ {
+ for( iLocale = 0; iLocale < nLocaleCount; iLocale++ )
+ {
+ Sequence< sal_Int8 >& rSeq = pLocaleDataSeq[iLocale];
+ xOutputStream->writeBytes( rSeq );
+ }
+ }
+
+ delete[] pLocaleDataSeq;
+
+ Sequence< sal_Int8 > aRetSeq = aOut.closeAndGetData();
+ return aRetSeq;
+}
+
+void StringResourcePersistenceImpl::implWriteLocaleBinary
+ ( LocaleItem* pLocaleItem, BinaryOutput& rOut )
+{
+ Reference< io::XOutputStream > xOutputStream = rOut.getOutputStream();
+ if( !xOutputStream.is() )
+ return;
+
+ Locale& rLocale = pLocaleItem->m_locale;
+ rOut.writeString( rLocale.Language );
+ rOut.writeString( rLocale.Country );
+ rOut.writeString( rLocale.Variant );
+ implWritePropertiesFile( pLocaleItem, xOutputStream, m_aComment );
+}
+
+// -----------------------------------------------------------------------------
+// BinaryOutput, helper class for exportBinary
+
+class BinaryInput
+{
+ Sequence< sal_Int8 > m_aData;
+ Reference< XMultiComponentFactory > m_xMCF;
+ Reference< XComponentContext > m_xContext;
+
+ const sal_Int8* m_pData;
+ sal_Int32 m_nCurPos;
+ sal_Int32 m_nSize;
+
+public:
+ BinaryInput( Sequence< ::sal_Int8 > aData, Reference< XMultiComponentFactory > xMCF,
+ Reference< XComponentContext > xContext );
+
+ Reference< io::XInputStream > getInputStreamForSection( sal_Int32 nSize );
+
+ void seek( sal_Int32 nPos );
+ sal_Int32 getPosition( void )
+ { return m_nCurPos; }
+
+ sal_Int16 readInt16( void );
+ sal_Int32 readInt32( void );
+ sal_Unicode readUnicodeChar( void );
+ ::rtl::OUString readString( void );
+};
+
+BinaryInput::BinaryInput( Sequence< ::sal_Int8 > aData, Reference< XMultiComponentFactory > xMCF,
+ Reference< XComponentContext > xContext )
+ : m_aData( aData )
+ , m_xMCF( xMCF )
+ , m_xContext( xContext )
+{
+ m_pData = m_aData.getConstArray();
+ m_nCurPos = 0;
+ m_nSize = m_aData.getLength();
+}
+
+Reference< io::XInputStream > BinaryInput::getInputStreamForSection( sal_Int32 nSize )
+{
+ Reference< io::XInputStream > xIn;
+ if( m_nCurPos + nSize <= m_nSize )
+ {
+ Reference< io::XOutputStream > xTempOut( m_xMCF->createInstanceWithContext
+ ( ::rtl::OUString::createFromAscii( "com.sun.star.io.TempFile" ), m_xContext ), UNO_QUERY );
+ if( xTempOut.is() )
+ {
+ Sequence< sal_Int8 > aSection( m_pData + m_nCurPos, nSize );
+ xTempOut->writeBytes( aSection );
+
+ Reference< io::XSeekable> xSeekable( xTempOut, UNO_QUERY );
+ if( xSeekable.is() )
+ xSeekable->seek( 0 );
+
+ xIn = Reference< io::XInputStream>( xTempOut, UNO_QUERY );
+ }
+ }
+ else
+ OSL_ENSURE( false, "BinaryInput::getInputStreamForSection(): Read past end" );
+
+ return xIn;
+}
+
+void BinaryInput::seek( sal_Int32 nPos )
+{
+ if( nPos <= m_nSize )
+ m_nCurPos = nPos;
+ else
+ OSL_ENSURE( false, "BinaryInput::seek(): Position past end" );
+}
+
+
+sal_Int16 BinaryInput::readInt16( void )
+{
+ sal_Int16 nRet = 0;
+ if( m_nCurPos + 2 <= m_nSize )
+ {
+ nRet = nRet + sal_Int16( sal_uInt8( m_pData[m_nCurPos++] ) );
+ nRet += 256 * sal_Int16( sal_uInt8( m_pData[m_nCurPos++] ) );
+ }
+ else
+ OSL_ENSURE( false, "BinaryInput::readInt16(): Read past end" );
+
+ return nRet;
+}
+
+sal_Int32 BinaryInput::readInt32( void )
+{
+ sal_Int32 nRet = 0;
+ if( m_nCurPos + 4 <= m_nSize )
+ {
+ sal_Int32 nFactor = 1;
+ for( sal_Int16 i = 0; i < 4; i++ )
+ {
+ nRet += sal_uInt8( m_pData[m_nCurPos++] ) * nFactor;
+ nFactor *= 256;
+ }
+ }
+ else
+ OSL_ENSURE( false, "BinaryInput::readInt32(): Read past end" );
+
+ return nRet;
+}
+
+sal_Unicode BinaryInput::readUnicodeChar( void )
+{
+ sal_uInt16 nRet = 0;
+ if( m_nCurPos + 2 <= m_nSize )
+ {
+ nRet = nRet + sal_uInt8( m_pData[m_nCurPos++] );
+ nRet += 256 * sal_uInt8( m_pData[m_nCurPos++] );
+ }
+ else
+ OSL_ENSURE( false, "BinaryInput::readUnicodeChar(): Read past end" );
+
+ sal_Unicode cRet = nRet;
+ return cRet;
+}
+
+::rtl::OUString BinaryInput::readString( void )
+{
+ ::rtl::OUStringBuffer aBuf;
+ sal_Unicode c;
+ do
+ {
+ c = readUnicodeChar();
+ if( c != 0 )
+ aBuf.append( c );
+ }
+ while( c != 0 );
+
+ ::rtl::OUString aRetStr = aBuf.makeStringAndClear();
+ return aRetStr;
+}
+
+void StringResourcePersistenceImpl::importBinary( const Sequence< ::sal_Int8 >& Data )
+ throw (IllegalArgumentException, RuntimeException)
+{
+ // Init: Remove all locales
+ sal_Int32 nOldLocaleCount = 0;
+ do
+ {
+ Sequence< Locale > aLocaleSeq = getLocales();
+ nOldLocaleCount = aLocaleSeq.getLength();
+ if( nOldLocaleCount > 0 )
+ {
+ Locale aLocale = aLocaleSeq[0];
+ removeLocale( aLocale );
+ }
+ }
+ while( nOldLocaleCount > 0 );
+
+ // Import data
+ Reference< XMultiComponentFactory > xMCF = getMultiComponentFactory();
+ BinaryInput aIn( Data, xMCF, m_xContext );
+
+ sal_Int32 nVersion = aIn.readInt16();
+ (void)nVersion;
+ sal_Int32 nLocaleCount = aIn.readInt16();
+ sal_Int32 iDefault = aIn.readInt16();
+ (void)iDefault;
+
+ sal_Int32* pPositions = new sal_Int32[nLocaleCount + 1];
+ for( sal_Int32 i = 0; i < nLocaleCount + 1; i++ )
+ pPositions[i] = aIn.readInt32();
+
+ // Import locales
+ LocaleItem* pUseAsDefaultItem = NULL;
+ for( sal_Int32 i = 0; i < nLocaleCount; i++ )
+ {
+ sal_Int32 nPos = pPositions[i];
+ aIn.seek( nPos );
+
+ Locale aLocale;
+ aLocale.Language = aIn.readString();
+ aLocale.Country = aIn.readString();
+ aLocale.Variant = aIn.readString();
+
+ sal_Int32 nAfterStringPos = aIn.getPosition();
+ sal_Int32 nSize = pPositions[i+1] - nAfterStringPos;
+ Reference< io::XInputStream > xInput = aIn.getInputStreamForSection( nSize );
+ if( xInput.is() )
+ {
+ LocaleItem* pLocaleItem = new LocaleItem( aLocale );
+ if( iDefault == i )
+ pUseAsDefaultItem = pLocaleItem;
+ m_aLocaleItemVector.push_back( pLocaleItem );
+ implReadPropertiesFile( pLocaleItem, xInput );
+ }
+ }
+
+ if( pUseAsDefaultItem != NULL )
+ setDefaultLocale( pUseAsDefaultItem->m_locale );
+
+ delete[] pPositions;
+}
+
+
+// =============================================================================
+// Private helper methods
+
+bool checkNamingSceme( const ::rtl::OUString& aName, const ::rtl::OUString& aNameBase,
+ Locale& aLocale )
+{
+ bool bSuccess = false;
+
+ sal_Int32 nNameLen = aName.getLength();
+ sal_Int32 nNameBaseLen = aNameBase.getLength();
+
+ // Name has to start with NameBase followed
+ // by a '_' and at least one more character
+ if( aName.indexOf( aNameBase ) == 0 && nNameBaseLen < nNameLen-1 &&
+ aName.getStr()[nNameBaseLen] == '_' )
+ {
+ bSuccess = true;
+
+ sal_Int32 iStart = nNameBaseLen + 1;
+ sal_Int32 iNext_ = aName.indexOf( '_', iStart );
+ if( iNext_ != -1 && iNext_ < nNameLen-1 )
+ {
+ aLocale.Language = aName.copy( iStart, iNext_ - iStart );
+
+ iStart = iNext_ + 1;
+ iNext_ = aName.indexOf( '_', iStart );
+ if( iNext_ != -1 && iNext_ < nNameLen-1 )
+ {
+ aLocale.Country = aName.copy( iStart, iNext_ - iStart );
+ aLocale.Variant = aName.copy( iNext_ + 1 );
+ }
+ else
+ aLocale.Country = aName.copy( iStart );
+ }
+ else
+ aLocale.Language = aName.copy( iStart );
+ }
+ return bSuccess;
+}
+
+void StringResourcePersistenceImpl::implLoadAllLocales( void )
+{
+ for( LocaleItemVectorIt it = m_aLocaleItemVector.begin(); it != m_aLocaleItemVector.end(); it++ )
+ {
+ LocaleItem* pLocaleItem = *it;
+ if( pLocaleItem != NULL )
+ loadLocale( pLocaleItem );
+ }
+}
+
+// Scan locale properties files helper
+void StringResourcePersistenceImpl::implScanLocaleNames( const Sequence< ::rtl::OUString >& aContentSeq )
+{
+ Locale aDefaultLocale;
+ bool bDefaultFound = false;
+
+ sal_Int32 nCount = aContentSeq.getLength();
+ const ::rtl::OUString* pFiles = aContentSeq.getConstArray();
+ for( int i = 0 ; i < nCount ; i++ )
+ {
+ ::rtl::OUString aCompleteName = pFiles[i];
+ rtl::OUString aPureName;
+ rtl::OUString aExtension;
+ sal_Int32 iDot = aCompleteName.lastIndexOf( '.' );
+ sal_Int32 iSlash = aCompleteName.lastIndexOf( '/' );
+ if( iDot != -1 )
+ {
+ sal_Int32 iCopyFrom = (iSlash != -1) ? iSlash + 1 : 0;
+ aPureName = aCompleteName.copy( iCopyFrom, iDot-iCopyFrom );
+ aExtension = aCompleteName.copy( iDot + 1 );
+ }
+
+ if( aExtension.equalsAscii( "properties" ) )
+ {
+ //rtl::OUString aName = aInetObj.getBase();
+ Locale aLocale;
+
+ if( checkNamingSceme( aPureName, m_aNameBase, aLocale ) )
+ {
+ LocaleItem* pLocaleItem = new LocaleItem( aLocale, false );
+ m_aLocaleItemVector.push_back( pLocaleItem );
+
+ if( m_pCurrentLocaleItem == NULL )
+ m_pCurrentLocaleItem = pLocaleItem;
+
+ if( m_pDefaultLocaleItem == NULL )
+ {
+ m_pDefaultLocaleItem = pLocaleItem;
+ m_bDefaultModified = true;
+ }
+ }
+ }
+ else if( !bDefaultFound && aExtension.equalsAscii( "default" ) )
+ {
+ //rtl::OUString aName = aInetObj.getBase();
+ Locale aLocale;
+
+ if( checkNamingSceme( aPureName, m_aNameBase, aDefaultLocale ) )
+ bDefaultFound = true;
+ }
+ }
+ if( bDefaultFound )
+ {
+ LocaleItem* pLocaleItem = getItemForLocale( aDefaultLocale, false );
+ if( pLocaleItem )
+ {
+ m_pDefaultLocaleItem = pLocaleItem;
+ m_bDefaultModified = false;
+ }
+ }
+}
+
+// Scan locale properties files
+void StringResourcePersistenceImpl::implScanLocales( void )
+{
+ // Dummy implementation, method not called for this
+ // base class, but pure virtual not possible-
+}
+
+bool StringResourcePersistenceImpl::loadLocale( LocaleItem* pLocaleItem )
+{
+ bool bSuccess = false;
+
+ OSL_ENSURE( pLocaleItem, "StringResourcePersistenceImpl::loadLocale(): pLocaleItem == NULL" );
+ if( pLocaleItem )
+ {
+ if( pLocaleItem->m_bLoaded )
+ {
+ bSuccess = true;
+ }
+ else
+ {
+ bSuccess = implLoadLocale( pLocaleItem );
+ pLocaleItem->m_bLoaded = true; // = bSuccess??? -> leads to more tries
+ }
+ }
+ return bSuccess;
+}
+
+bool StringResourcePersistenceImpl::implLoadLocale( LocaleItem* )
+{
+ // Dummy implementation, method not called for this
+ // base class, but pure virtual not possible-
+ return false;
+}
+
+::rtl::OUString implGetNameScemeForLocaleItem( const LocaleItem* pLocaleItem )
+{
+ static ::rtl::OUString aUnder = ::rtl::OUString::createFromAscii( "_" );
+
+ OSL_ENSURE( pLocaleItem,
+ "StringResourcePersistenceImpl::implGetNameScemeForLocaleItem(): pLocaleItem == NULL" );
+ Locale aLocale = pLocaleItem->m_locale;
+
+ ::rtl::OUString aRetStr = aUnder;
+ aRetStr += aLocale.Language;
+
+ ::rtl::OUString aCountry = aLocale.Country;
+ if( aCountry.getLength() )
+ {
+ aRetStr += aUnder;
+ aRetStr += aCountry;
+ }
+
+ ::rtl::OUString aVariant = aLocale.Variant;
+ if( aVariant.getLength() )
+ {
+ aRetStr += aUnder;
+ aRetStr += aVariant;
+ }
+ return aRetStr;
+}
+
+::rtl::OUString StringResourcePersistenceImpl::implGetFileNameForLocaleItem
+ ( LocaleItem* pLocaleItem, const ::rtl::OUString& aNameBase )
+{
+ ::rtl::OUString aFileName = aNameBase;
+ if( aFileName.getLength() == 0 )
+ aFileName = aNameBaseDefaultStr;
+
+ aFileName += implGetNameScemeForLocaleItem( pLocaleItem );
+ return aFileName;
+}
+
+::rtl::OUString StringResourcePersistenceImpl::implGetPathForLocaleItem
+ ( LocaleItem* pLocaleItem, const ::rtl::OUString& aNameBase,
+ const ::rtl::OUString& aLocation, bool bDefaultFile )
+{
+ ::rtl::OUString aFileName = implGetFileNameForLocaleItem( pLocaleItem, aNameBase );
+ INetURLObject aInetObj( aLocation );
+ aInetObj.insertName( aFileName, sal_True, INetURLObject::LAST_SEGMENT, sal_True, INetURLObject::ENCODE_ALL );
+ if( bDefaultFile )
+ aInetObj.setExtension( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("default") ) );
+ else
+ aInetObj.setExtension( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("properties") ) );
+ ::rtl::OUString aCompleteFileName = aInetObj.GetMainURL( INetURLObject::NO_DECODE );
+ return aCompleteFileName;
+}
+
+// White space according to Java property files specification in
+// http://java.sun.com/j2se/1.4.2/docs/api/java/util/Properties.html#load(java.io.InputStream)
+inline bool isWhiteSpace( sal_Unicode c )
+{
+ bool bWhite = ( c == 0x0020 || // space
+ c == 0x0009 || // tab
+ c == 0x000a || // line feed, not always handled by TextInputStream
+ c == 0x000d || // carriage return, not always handled by TextInputStream
+ c == 0x000C ); // form feed
+ return bWhite;
+}
+
+inline void skipWhites( const sal_Unicode* pBuf, sal_Int32 nLen, sal_Int32& ri )
+{
+ while( ri < nLen )
+ {
+ if( !isWhiteSpace( pBuf[ri] ) )
+ break;
+ ri++;
+ }
+}
+
+inline bool isHexDigit( sal_Unicode c, sal_uInt16& nDigitVal )
+{
+ bool bRet = true;
+ if( c >= '0' && c <= '9' )
+ nDigitVal = c - '0';
+ else if( c >= 'a' && c <= 'f' )
+ nDigitVal = c - 'a' + 10;
+ else if( c >= 'A' && c <= 'F' )
+ nDigitVal = c - 'A' + 10;
+ else
+ bRet = false;
+ return bRet;
+}
+
+sal_Unicode getEscapeChar( const sal_Unicode* pBuf, sal_Int32 nLen, sal_Int32& ri )
+{
+ sal_Int32 i = ri;
+
+ sal_Unicode cRet = 0;
+ sal_Unicode c = pBuf[i];
+ switch( c )
+ {
+ case 't':
+ cRet = 0x0009;
+ break;
+ case 'n':
+ cRet = 0x000a;
+ break;
+ case 'f':
+ cRet = 0x000c;
+ break;
+ case 'r':
+ cRet = 0x000d;
+ break;
+ case '\\':
+ cRet = '\\';
+ break;
+ case 'u':
+ {
+ // Skip multiple u
+ i++;
+ while( i < nLen && pBuf[i] == 'u' )
+ i++;
+
+ // Process hex digits
+ sal_Int32 nDigitCount = 0;
+ sal_uInt16 nDigitVal;
+ while( i < nLen && isHexDigit( pBuf[i], nDigitVal ) )
+ {
+ cRet = 16 * cRet + nDigitVal;
+
+ nDigitCount++;
+ if( nDigitCount == 4 )
+ {
+ // Write back position
+ ri = i;
+ break;
+ }
+ i++;
+ }
+ break;
+ }
+ default:
+ cRet = c;
+ }
+
+ return cRet;
+}
+
+void CheckContinueInNextLine( Reference< io::XTextInputStream > xTextInputStream,
+ ::rtl::OUString& aLine, bool& bEscapePending, const sal_Unicode*& pBuf,
+ sal_Int32& nLen, sal_Int32& i )
+{
+ if( i == nLen && bEscapePending )
+ {
+ bEscapePending = false;
+
+ if( !xTextInputStream->isEOF() )
+ {
+ aLine = xTextInputStream->readLine();
+ nLen = aLine.getLength();
+ pBuf = aLine.getStr();
+ i = 0;
+
+ skipWhites( pBuf, nLen, i );
+ }
+ }
+}
+
+bool StringResourcePersistenceImpl::implReadPropertiesFile
+ ( LocaleItem* pLocaleItem, const Reference< io::XInputStream >& xInputStream )
+{
+ if( !xInputStream.is() || pLocaleItem == NULL )
+ return false;
+
+ bool bSuccess = false;
+ Reference< XMultiComponentFactory > xMCF = getMultiComponentFactory();
+ Reference< io::XTextInputStream > xTextInputStream( xMCF->createInstanceWithContext
+ ( ::rtl::OUString::createFromAscii( "com.sun.star.io.TextInputStream" ), m_xContext ), UNO_QUERY );
+
+ if( xTextInputStream.is() )
+ {
+ Reference< io::XActiveDataSink> xActiveDataSink( xTextInputStream, UNO_QUERY );
+ if( xActiveDataSink.is() )
+ {
+ bSuccess = true;
+
+ xActiveDataSink->setInputStream( xInputStream );
+
+ ::rtl::OUString aEncodingStr = ::rtl::OUString::createFromAscii
+ ( rtl_getMimeCharsetFromTextEncoding( RTL_TEXTENCODING_ISO_8859_1 ) );
+ xTextInputStream->setEncoding( aEncodingStr );
+
+ ::rtl::OUString aLine;
+ while( !xTextInputStream->isEOF() )
+ {
+ aLine = xTextInputStream->readLine();
+
+ sal_Int32 nLen = aLine.getLength();
+ if( 0 == nLen )
+ continue;
+ const sal_Unicode* pBuf = aLine.getStr();
+ ::rtl::OUStringBuffer aBuf;
+ sal_Unicode c = 0;
+ sal_Int32 i = 0;
+
+ skipWhites( pBuf, nLen, i );
+ if( i == nLen )
+ continue; // line contains only white spaces
+
+ // Comment?
+ c = pBuf[i];
+ if( c == '#' || c == '!' )
+ continue;
+
+ // Scan key
+ ::rtl::OUString aResourceID;
+ bool bEscapePending = false;
+ bool bStrComplete = false;
+ while( i < nLen && !bStrComplete )
+ {
+ c = pBuf[i];
+ if( bEscapePending )
+ {
+ aBuf.append( getEscapeChar( pBuf, nLen, i ) );
+ bEscapePending = false;
+ }
+ else
+ {
+ if( c == '\\' )
+ {
+ bEscapePending = true;
+ }
+ else
+ {
+ if( c == ':' || c == '=' || isWhiteSpace( c ) )
+ bStrComplete = true;
+ else
+ aBuf.append( c );
+ }
+ }
+ i++;
+
+ CheckContinueInNextLine( xTextInputStream, aLine, bEscapePending, pBuf, nLen, i );
+ if( i == nLen )
+ bStrComplete = true;
+
+ if( bStrComplete )
+ aResourceID = aBuf.makeStringAndClear();
+ }
+
+ // Ignore lines with empty keys
+ if( 0 == aResourceID.getLength() )
+ continue;
+
+ // Scan value
+ skipWhites( pBuf, nLen, i );
+
+ ::rtl::OUString aValueStr;
+ bEscapePending = false;
+ bStrComplete = false;
+ while( i < nLen && !bStrComplete )
+ {
+ c = pBuf[i];
+ if( c == 0x000a || c == 0x000d ) // line feed/carriage return, not always handled by TextInputStream
+ {
+ i++;
+ }
+ else
+ {
+ if( bEscapePending )
+ {
+ aBuf.append( getEscapeChar( pBuf, nLen, i ) );
+ bEscapePending = false;
+ }
+ else if( c == '\\' )
+ bEscapePending = true;
+ else
+ aBuf.append( c );
+ i++;
+
+ CheckContinueInNextLine( xTextInputStream, aLine, bEscapePending, pBuf, nLen, i );
+ }
+ if( i == nLen )
+ bStrComplete = true;
+
+ if( bStrComplete )
+ aValueStr = aBuf.makeStringAndClear();
+ }
+
+ // Push into table
+ pLocaleItem->m_aIdToStringMap[ aResourceID ] = aValueStr;
+ implScanIdForNumber( aResourceID );
+ IdToIndexMap& rIndexMap = pLocaleItem->m_aIdToIndexMap;
+ rIndexMap[ aResourceID ] = pLocaleItem->m_nNextIndex++;
+ }
+ }
+ }
+
+ return bSuccess;
+}
+
+
+inline sal_Unicode getHexCharForDigit( sal_uInt16 nDigitVal )
+{
+ sal_Unicode cRet = ( nDigitVal < 10 ) ? ('0' + nDigitVal) : ('a' + (nDigitVal-10));
+ return cRet;
+}
+
+void implWriteCharToBuffer( ::rtl::OUStringBuffer& aBuf, sal_Unicode cu, bool bKey )
+{
+ if( cu == '\\' )
+ {
+ aBuf.append( (sal_Unicode)'\\' );
+ aBuf.append( (sal_Unicode)'\\' );
+ }
+ else if( cu == 0x000a )
+ {
+ aBuf.append( (sal_Unicode)'\\' );
+ aBuf.append( (sal_Unicode)'n' );
+ }
+ else if( cu == 0x000d )
+ {
+ aBuf.append( (sal_Unicode)'\\' );
+ aBuf.append( (sal_Unicode)'r' );
+ }
+ else if( bKey && cu == '=' )
+ {
+ aBuf.append( (sal_Unicode)'\\' );
+ aBuf.append( (sal_Unicode)'=' );
+ }
+ else if( bKey && cu == ':' )
+ {
+ aBuf.append( (sal_Unicode)'\\' );
+ aBuf.append( (sal_Unicode)':' );
+ }
+ // ISO/IEC 8859-1 range according to:
+ // http://en.wikipedia.org/wiki/ISO/IEC_8859-1
+ else if( (cu >= 0x20 && cu <= 0x7e) )
+ //TODO: Check why (cu >= 0xa0 && cu <= 0xFF)
+ //is encoded in sample properties files
+ //else if( (cu >= 0x20 && cu <= 0x7e) ||
+ // (cu >= 0xa0 && cu <= 0xFF) )
+ {
+ aBuf.append( cu );
+ }
+ else
+ {
+ // Unicode encoding
+ aBuf.append( (sal_Unicode)'\\' );
+ aBuf.append( (sal_Unicode)'u' );
+
+ sal_uInt16 nVal = cu;
+ for( sal_uInt16 i = 0 ; i < 4 ; i++ )
+ {
+ sal_uInt16 nDigit = nVal / 0x1000;
+ nVal -= nDigit * 0x1000;
+ nVal *= 0x10;
+ aBuf.append( getHexCharForDigit( nDigit ) );
+ }
+ }
+}
+
+void implWriteStringWithEncoding( const ::rtl::OUString& aStr,
+ Reference< io::XTextOutputStream > xTextOutputStream, bool bKey )
+{
+ static sal_Unicode cLineFeed = 0xa;
+
+ (void)aStr;
+ (void)xTextOutputStream;
+
+ ::rtl::OUStringBuffer aBuf;
+ sal_Int32 nLen = aStr.getLength();
+ const sal_Unicode* pSrc = aStr.getStr();
+ for( sal_Int32 i = 0 ; i < nLen ; i++ )
+ {
+ sal_Unicode cu = pSrc[i];
+ implWriteCharToBuffer( aBuf, cu, bKey );
+ // TODO?: split long lines
+ }
+ if( !bKey )
+ aBuf.append( cLineFeed );
+
+ ::rtl::OUString aWriteStr = aBuf.makeStringAndClear();
+ xTextOutputStream->writeString( aWriteStr );
+}
+
+bool StringResourcePersistenceImpl::implWritePropertiesFile( LocaleItem* pLocaleItem,
+ const Reference< io::XOutputStream >& xOutputStream, const ::rtl::OUString& aComment )
+{
+ static ::rtl::OUString aAssignmentStr = ::rtl::OUString::createFromAscii( "=" );
+ static ::rtl::OUString aLineFeedStr = ::rtl::OUString::createFromAscii( "\n" );
+
+ if( !xOutputStream.is() || pLocaleItem == NULL )
+ return false;
+
+ bool bSuccess = false;
+ Reference< XMultiComponentFactory > xMCF = getMultiComponentFactory();
+ Reference< io::XTextOutputStream > xTextOutputStream( xMCF->createInstanceWithContext
+ ( ::rtl::OUString::createFromAscii( "com.sun.star.io.TextOutputStream" ), m_xContext ), UNO_QUERY );
+
+ if( xTextOutputStream.is() )
+ {
+ Reference< io::XActiveDataSource> xActiveDataSource( xTextOutputStream, UNO_QUERY );
+ if( xActiveDataSource.is() )
+ {
+ xActiveDataSource->setOutputStream( xOutputStream );
+
+ ::rtl::OUString aEncodingStr = ::rtl::OUString::createFromAscii
+ ( rtl_getMimeCharsetFromTextEncoding( RTL_TEXTENCODING_ISO_8859_1 ) );
+ xTextOutputStream->setEncoding( aEncodingStr );
+
+ xTextOutputStream->writeString( aComment );
+ xTextOutputStream->writeString( aLineFeedStr );
+
+ const IdToStringMap& rHashMap = pLocaleItem->m_aIdToStringMap;
+ if( rHashMap.size() > 0 )
+ {
+ // Sort ids according to read order
+ const IdToIndexMap& rIndexMap = pLocaleItem->m_aIdToIndexMap;
+ IdToIndexMap::const_iterator it_index;
+
+ // Find max/min index
+ sal_Int32 nMinIndex = -1;
+ sal_Int32 nMaxIndex = -1;
+ for( it_index = rIndexMap.begin(); it_index != rIndexMap.end(); it_index++ )
+ {
+ sal_Int32 nIndex = (*it_index).second;
+ if( nMinIndex > nIndex || nMinIndex == -1 )
+ nMinIndex = nIndex;
+ if( nMaxIndex < nIndex )
+ nMaxIndex = nIndex;
+ }
+ sal_Int32 nTabSize = nMaxIndex - nMinIndex + 1;
+
+ // Create sorted array of pointers to the id strings
+ const ::rtl::OUString** pIdPtrs = new const ::rtl::OUString*[nTabSize];
+ sal_Int32 i;
+ for( i = 0 ; i < nTabSize ; i++ )
+ pIdPtrs[i] = NULL;
+ for( it_index = rIndexMap.begin(); it_index != rIndexMap.end(); it_index++ )
+ {
+ sal_Int32 nIndex = (*it_index).second;
+ pIdPtrs[nIndex - nMinIndex] = &((*it_index).first);
+ }
+
+ // Write lines in correct order
+ for( i = 0 ; i < nTabSize ; i++ )
+ {
+ const ::rtl::OUString* pStr = pIdPtrs[i];
+ if( pStr != NULL )
+ {
+ ::rtl::OUString aResourceID = *pStr;
+ IdToStringMap::const_iterator it = rHashMap.find( aResourceID );
+ if( !( it == rHashMap.end() ) )
+ {
+ implWriteStringWithEncoding( aResourceID, xTextOutputStream, true );
+ xTextOutputStream->writeString( aAssignmentStr );
+ ::rtl::OUString aValStr = (*it).second;
+ implWriteStringWithEncoding( aValStr, xTextOutputStream, false );
+ }
+ }
+ }
+
+ delete pIdPtrs;
+ }
+
+ bSuccess = true;
+ }
+ }
+ return bSuccess;
+}
+
+
+// =============================================================================
+// StringResourceWithStorageImpl
+// =============================================================================
+
+// component operations
+static Sequence< ::rtl::OUString > getSupportedServiceNames_StringResourceWithStorageImpl()
+{
+ Sequence< ::rtl::OUString > names(1);
+ names[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.resource.StringResourceWithStorage") );
+ return names;
+}
+
+static ::rtl::OUString getImplementationName_StringResourceWithStorageImpl()
+{
+ return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.scripting.StringResourceWithStorage") );
+}
+
+static Reference< XInterface > SAL_CALL create_StringResourceWithStorageImpl(
+ Reference< XComponentContext > const & xContext )
+ SAL_THROW( () )
+{
+ return static_cast< ::cppu::OWeakObject * >( new StringResourceWithStorageImpl( xContext ) );
+}
+
+// -----------------------------------------------------------------------------
+
+StringResourceWithStorageImpl::StringResourceWithStorageImpl( const Reference< XComponentContext >& rxContext )
+ : StringResourceWithStorageImpl_BASE( rxContext )
+ , m_bStorageChanged( false )
+{
+}
+
+// -----------------------------------------------------------------------------
+
+StringResourceWithStorageImpl::~StringResourceWithStorageImpl()
+{
+}
+
+// -----------------------------------------------------------------------------
+// XServiceInfo
+// -----------------------------------------------------------------------------
+
+::rtl::OUString StringResourceWithStorageImpl::getImplementationName( ) throw (RuntimeException)
+{
+ return getImplementationName_StringResourceWithStorageImpl();
+}
+
+// -----------------------------------------------------------------------------
+
+sal_Bool StringResourceWithStorageImpl::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
+{
+ Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
+ const ::rtl::OUString* pNames = aNames.getConstArray();
+ const ::rtl::OUString* pEnd = pNames + aNames.getLength();
+ for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
+ ;
+
+ return pNames != pEnd;
+}
+
+// -----------------------------------------------------------------------------
+
+Sequence< ::rtl::OUString > StringResourceWithStorageImpl::getSupportedServiceNames( ) throw (RuntimeException)
+{
+ return getSupportedServiceNames_StringResourceWithStorageImpl();
+}
+
+// -----------------------------------------------------------------------------
+// XInitialization
+// -----------------------------------------------------------------------------
+
+void StringResourceWithStorageImpl::initialize( const Sequence< Any >& aArguments )
+ throw (Exception, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ if ( aArguments.getLength() != 5 )
+ {
+ throw RuntimeException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "StringResourceWithStorageImpl::initialize: invalid number of arguments!" ) ),
+ Reference< XInterface >() );
+ }
+
+ bool bOk = (aArguments[0] >>= m_xStorage);
+ if( bOk && !m_xStorage.is() )
+ bOk = false;
+
+ if( !bOk )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "StringResourceWithStorageImpl::initialize: invalid storage" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 0 );
+ }
+
+ implInitializeCommonParameters( aArguments );
+}
+
+// -----------------------------------------------------------------------------
+// Forwarding calls to base class
+
+// XModifyBroadcaster
+void StringResourceWithStorageImpl::addModifyListener( const Reference< XModifyListener >& aListener )
+ throw (RuntimeException)
+{
+ StringResourceImpl::addModifyListener( aListener );
+}
+void StringResourceWithStorageImpl::removeModifyListener( const Reference< XModifyListener >& aListener )
+ throw (RuntimeException)
+{
+ StringResourceImpl::removeModifyListener( aListener );
+}
+
+// XStringResourceResolver
+::rtl::OUString StringResourceWithStorageImpl::resolveString( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException)
+{
+ return StringResourceImpl::resolveString( ResourceID ) ;
+}
+::rtl::OUString StringResourceWithStorageImpl::resolveStringForLocale( const ::rtl::OUString& ResourceID, const Locale& locale )
+ throw ( ::com::sun::star::resource::MissingResourceException, RuntimeException)
+{
+ return StringResourceImpl::resolveStringForLocale( ResourceID, locale );
+}
+sal_Bool StringResourceWithStorageImpl::hasEntryForId( const ::rtl::OUString& ResourceID )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::hasEntryForId( ResourceID ) ;
+}
+sal_Bool StringResourceWithStorageImpl::hasEntryForIdAndLocale( const ::rtl::OUString& ResourceID,
+ const Locale& locale )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::hasEntryForIdAndLocale( ResourceID, locale );
+}
+Sequence< ::rtl::OUString > StringResourceWithStorageImpl::getResourceIDs( )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getResourceIDs();
+}
+Sequence< ::rtl::OUString > StringResourceWithStorageImpl::getResourceIDsForLocale
+ ( const Locale& locale ) throw (::com::sun::star::uno::RuntimeException)
+{
+ return StringResourceImpl::getResourceIDsForLocale( locale );
+}
+Locale StringResourceWithStorageImpl::getCurrentLocale()
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getCurrentLocale();
+}
+Locale StringResourceWithStorageImpl::getDefaultLocale( )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getDefaultLocale();
+}
+Sequence< Locale > StringResourceWithStorageImpl::getLocales( )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getLocales();
+}
+
+// XStringResourceManager
+sal_Bool StringResourceWithStorageImpl::isReadOnly()
+ throw (RuntimeException)
+{
+ return StringResourceImpl::isReadOnly();
+}
+void StringResourceWithStorageImpl::setCurrentLocale( const Locale& locale, sal_Bool FindClosestMatch )
+ throw (IllegalArgumentException, RuntimeException)
+{
+ StringResourceImpl::setCurrentLocale( locale, FindClosestMatch );
+}
+void StringResourceWithStorageImpl::setDefaultLocale( const Locale& locale )
+ throw (IllegalArgumentException, RuntimeException,NoSupportException)
+{
+ StringResourceImpl::setDefaultLocale( locale );
+}
+void StringResourceWithStorageImpl::setString( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str )
+ throw (NoSupportException, RuntimeException)
+{
+ StringResourceImpl::setString( ResourceID, Str );
+}
+void StringResourceWithStorageImpl::setStringForLocale
+ ( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str, const Locale& locale )
+ throw (NoSupportException, RuntimeException)
+{
+ StringResourceImpl::setStringForLocale( ResourceID, Str, locale );
+}
+void StringResourceWithStorageImpl::removeId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::removeId( ResourceID );
+}
+void StringResourceWithStorageImpl::removeIdForLocale( const ::rtl::OUString& ResourceID, const Locale& locale )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::removeIdForLocale( ResourceID, locale );
+}
+void StringResourceWithStorageImpl::newLocale( const Locale& locale )
+ throw (ElementExistException, IllegalArgumentException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::newLocale( locale );
+}
+void StringResourceWithStorageImpl::removeLocale( const Locale& locale )
+ throw (IllegalArgumentException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::removeLocale( locale );
+}
+sal_Int32 StringResourceWithStorageImpl::getUniqueNumericId( )
+ throw (RuntimeException, NoSupportException)
+{
+ return StringResourceImpl::getUniqueNumericId();
+}
+
+// XStringResourcePersistence
+void StringResourceWithStorageImpl::store()
+ throw (NoSupportException, Exception, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ implCheckReadOnly( "StringResourceWithStorageImpl::store(): Read only" );
+
+ bool bUsedForStore = true;
+ bool bStoreAll = m_bStorageChanged;
+ m_bStorageChanged = false;
+ if( !m_bModified && !bStoreAll )
+ return;
+
+ implStoreAtStorage( m_aNameBase, m_aComment, m_xStorage, bUsedForStore, bStoreAll );
+ m_bModified = false;
+}
+
+sal_Bool StringResourceWithStorageImpl::isModified( )
+ throw (RuntimeException)
+{
+ return StringResourcePersistenceImpl::isModified();
+}
+void StringResourceWithStorageImpl::setComment( const ::rtl::OUString& Comment )
+ throw (::com::sun::star::uno::RuntimeException)
+{
+ StringResourcePersistenceImpl::setComment( Comment );
+}
+void StringResourceWithStorageImpl::storeToStorage( const Reference< XStorage >& Storage,
+ const ::rtl::OUString& NameBase, const ::rtl::OUString& Comment )
+ throw (Exception, RuntimeException)
+{
+ StringResourcePersistenceImpl::storeToStorage( Storage, NameBase, Comment );
+}
+void StringResourceWithStorageImpl::storeToURL( const ::rtl::OUString& URL,
+ const ::rtl::OUString& NameBase, const ::rtl::OUString& Comment,
+ const Reference< ::com::sun::star::task::XInteractionHandler >& Handler )
+ throw (Exception, RuntimeException)
+{
+ StringResourcePersistenceImpl::storeToURL( URL, NameBase, Comment, Handler );
+}
+Sequence< ::sal_Int8 > StringResourceWithStorageImpl::exportBinary( )
+ throw (RuntimeException)
+{
+ return StringResourcePersistenceImpl::exportBinary();
+}
+void StringResourceWithStorageImpl::importBinary( const Sequence< ::sal_Int8 >& Data )
+ throw (IllegalArgumentException, RuntimeException)
+{
+ StringResourcePersistenceImpl::importBinary( Data );
+}
+
+// -----------------------------------------------------------------------------
+// XStringResourceWithStorage
+
+void StringResourceWithStorageImpl::storeAsStorage( const Reference< XStorage >& Storage )
+ throw (Exception, RuntimeException)
+{
+ setStorage( Storage );
+ store();
+}
+
+void StringResourceWithStorageImpl::setStorage( const Reference< XStorage >& Storage )
+ throw (IllegalArgumentException, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ if( !Storage.is() )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii
+ ( "StringResourceWithStorageImpl::setStorage: invalid storage" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 0 );
+ }
+
+ implLoadAllLocales();
+
+ m_xStorage = Storage;
+ m_bStorageChanged = true;
+}
+
+
+// =============================================================================
+// Private helper methods
+// =============================================================================
+
+// Scan locale properties files
+void StringResourceWithStorageImpl::implScanLocales( void )
+{
+ Reference< container::XNameAccess > xNameAccess( m_xStorage, UNO_QUERY );
+ if( xNameAccess.is() )
+ {
+ Sequence< ::rtl::OUString > aContentSeq = xNameAccess->getElementNames();
+ implScanLocaleNames( aContentSeq );
+ }
+
+ implLoadAllLocales();
+}
+
+// Loading
+bool StringResourceWithStorageImpl::implLoadLocale( LocaleItem* pLocaleItem )
+{
+ bool bSuccess = false;
+ try
+ {
+ ::rtl::OUString aStreamName = implGetFileNameForLocaleItem( pLocaleItem, m_aNameBase );
+ aStreamName += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(".properties") );
+
+ Reference< io::XStream > xElementStream =
+ m_xStorage->openStreamElement( aStreamName, ElementModes::READ );
+
+ if( xElementStream.is() )
+ {
+ Reference< io::XInputStream > xInputStream = xElementStream->getInputStream();
+ if( xInputStream.is() )
+ {
+ bSuccess = StringResourcePersistenceImpl::implReadPropertiesFile( pLocaleItem, xInputStream );
+ xInputStream->closeInput();
+ }
+ }
+ }
+ catch( uno::Exception& )
+ {}
+
+ return bSuccess;
+}
+
+
+// =============================================================================
+// StringResourceWithLocationImpl
+// =============================================================================
+
+// component operations
+static Sequence< ::rtl::OUString > getSupportedServiceNames_StringResourceWithLocationImpl()
+{
+ Sequence< ::rtl::OUString > names(1);
+ names[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.resource.StringResourceWithLocation") );
+ return names;
+}
+
+static ::rtl::OUString getImplementationName_StringResourceWithLocationImpl()
+{
+ return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.scripting.StringResourceWithLocation") );
+}
+
+static Reference< XInterface > SAL_CALL create_StringResourceWithLocationImpl(
+ Reference< XComponentContext > const & xContext )
+ SAL_THROW( () )
+{
+ return static_cast< ::cppu::OWeakObject * >( new StringResourceWithLocationImpl( xContext ) );
+}
+
+// -----------------------------------------------------------------------------
+
+StringResourceWithLocationImpl::StringResourceWithLocationImpl( const Reference< XComponentContext >& rxContext )
+ : StringResourceWithLocationImpl_BASE( rxContext )
+ , m_bLocationChanged( false )
+{
+}
+
+// -----------------------------------------------------------------------------
+
+StringResourceWithLocationImpl::~StringResourceWithLocationImpl()
+{
+}
+
+// -----------------------------------------------------------------------------
+// XServiceInfo
+// -----------------------------------------------------------------------------
+
+::rtl::OUString StringResourceWithLocationImpl::getImplementationName( ) throw (RuntimeException)
+{
+ return getImplementationName_StringResourceWithLocationImpl();
+}
+
+// -----------------------------------------------------------------------------
+
+sal_Bool StringResourceWithLocationImpl::supportsService( const ::rtl::OUString& rServiceName ) throw (RuntimeException)
+{
+ Sequence< ::rtl::OUString > aNames( getSupportedServiceNames() );
+ const ::rtl::OUString* pNames = aNames.getConstArray();
+ const ::rtl::OUString* pEnd = pNames + aNames.getLength();
+ for ( ; pNames != pEnd && !pNames->equals( rServiceName ); ++pNames )
+ ;
+
+ return pNames != pEnd;
+}
+
+// -----------------------------------------------------------------------------
+
+Sequence< ::rtl::OUString > StringResourceWithLocationImpl::getSupportedServiceNames( ) throw (RuntimeException)
+{
+ return getSupportedServiceNames_StringResourceWithLocationImpl();
+}
+
+// -----------------------------------------------------------------------------
+// XInitialization
+// -----------------------------------------------------------------------------
+
+void StringResourceWithLocationImpl::initialize( const Sequence< Any >& aArguments )
+ throw (Exception, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ if ( aArguments.getLength() != 6 )
+ {
+ throw RuntimeException(
+ ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM
+ ( "XInitialization::initialize: invalid number of arguments!" ) ),
+ Reference< XInterface >() );
+ }
+
+ bool bOk = (aArguments[0] >>= m_aLocation);
+ sal_Int32 nLen = m_aLocation.getLength();
+ if( bOk && nLen == 0 )
+ {
+ bOk = false;
+ }
+ else
+ {
+ if( m_aLocation.getStr()[nLen - 1] != '/' )
+ m_aLocation += ::rtl::OUString::createFromAscii( "/" );
+ }
+
+ if( !bOk )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "XInitialization::initialize: invalid URL" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 0 );
+ }
+
+
+ bOk = (aArguments[5] >>= m_xInteractionHandler);
+ if( !bOk )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii( "StringResourceWithStorageImpl::initialize: invalid type" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 5 );
+ }
+
+ implInitializeCommonParameters( aArguments );
+}
+
+// -----------------------------------------------------------------------------
+// Forwarding calls to base class
+
+// XModifyBroadcaster
+void StringResourceWithLocationImpl::addModifyListener( const Reference< XModifyListener >& aListener )
+ throw (RuntimeException)
+{
+ StringResourceImpl::addModifyListener( aListener );
+}
+void StringResourceWithLocationImpl::removeModifyListener( const Reference< XModifyListener >& aListener )
+ throw (RuntimeException)
+{
+ StringResourceImpl::removeModifyListener( aListener );
+}
+
+// XStringResourceResolver
+::rtl::OUString StringResourceWithLocationImpl::resolveString( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException)
+{
+ return StringResourceImpl::resolveString( ResourceID ) ;
+}
+::rtl::OUString StringResourceWithLocationImpl::resolveStringForLocale( const ::rtl::OUString& ResourceID, const Locale& locale )
+ throw ( ::com::sun::star::resource::MissingResourceException, RuntimeException)
+{
+ return StringResourceImpl::resolveStringForLocale( ResourceID, locale );
+}
+sal_Bool StringResourceWithLocationImpl::hasEntryForId( const ::rtl::OUString& ResourceID )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::hasEntryForId( ResourceID ) ;
+}
+sal_Bool StringResourceWithLocationImpl::hasEntryForIdAndLocale( const ::rtl::OUString& ResourceID,
+ const Locale& locale )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::hasEntryForIdAndLocale( ResourceID, locale );
+}
+Sequence< ::rtl::OUString > StringResourceWithLocationImpl::getResourceIDs( )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getResourceIDs();
+}
+Sequence< ::rtl::OUString > StringResourceWithLocationImpl::getResourceIDsForLocale
+ ( const Locale& locale ) throw (::com::sun::star::uno::RuntimeException)
+{
+ return StringResourceImpl::getResourceIDsForLocale( locale );
+}
+Locale StringResourceWithLocationImpl::getCurrentLocale()
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getCurrentLocale();
+}
+Locale StringResourceWithLocationImpl::getDefaultLocale( )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getDefaultLocale();
+}
+Sequence< Locale > StringResourceWithLocationImpl::getLocales( )
+ throw (RuntimeException)
+{
+ return StringResourceImpl::getLocales();
+}
+
+// XStringResourceManager
+sal_Bool StringResourceWithLocationImpl::isReadOnly()
+ throw (RuntimeException)
+{
+ return StringResourceImpl::isReadOnly();
+}
+void StringResourceWithLocationImpl::setCurrentLocale( const Locale& locale, sal_Bool FindClosestMatch )
+ throw (IllegalArgumentException, RuntimeException)
+{
+ StringResourceImpl::setCurrentLocale( locale, FindClosestMatch );
+}
+void StringResourceWithLocationImpl::setDefaultLocale( const Locale& locale )
+ throw (IllegalArgumentException, RuntimeException,NoSupportException)
+{
+ StringResourceImpl::setDefaultLocale( locale );
+}
+void StringResourceWithLocationImpl::setString( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str )
+ throw (NoSupportException, RuntimeException)
+{
+ StringResourceImpl::setString( ResourceID, Str );
+}
+void StringResourceWithLocationImpl::setStringForLocale
+ ( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str, const Locale& locale )
+ throw (NoSupportException, RuntimeException)
+{
+ StringResourceImpl::setStringForLocale( ResourceID, Str, locale );
+}
+void StringResourceWithLocationImpl::removeId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::removeId( ResourceID );
+}
+void StringResourceWithLocationImpl::removeIdForLocale( const ::rtl::OUString& ResourceID, const Locale& locale )
+ throw (::com::sun::star::resource::MissingResourceException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::removeIdForLocale( ResourceID, locale );
+}
+void StringResourceWithLocationImpl::newLocale( const Locale& locale )
+ throw (ElementExistException, IllegalArgumentException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::newLocale( locale );
+}
+void StringResourceWithLocationImpl::removeLocale( const Locale& locale )
+ throw (IllegalArgumentException, RuntimeException, NoSupportException)
+{
+ StringResourceImpl::removeLocale( locale );
+}
+sal_Int32 StringResourceWithLocationImpl::getUniqueNumericId( )
+ throw (RuntimeException, NoSupportException)
+{
+ return StringResourceImpl::getUniqueNumericId();
+}
+
+// XStringResourcePersistence
+void StringResourceWithLocationImpl::store()
+ throw (NoSupportException, Exception, RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ implCheckReadOnly( "StringResourceWithLocationImpl::store(): Read only" );
+
+ bool bUsedForStore = true;
+ bool bStoreAll = m_bLocationChanged;
+ m_bLocationChanged = false;
+ if( !m_bModified && !bStoreAll )
+ return;
+
+ Reference< ucb::XSimpleFileAccess > xFileAccess = getFileAccess();
+ implStoreAtLocation( m_aLocation, m_aNameBase, m_aComment,
+ xFileAccess, bUsedForStore, bStoreAll );
+ m_bModified = false;
+}
+
+sal_Bool StringResourceWithLocationImpl::isModified( )
+ throw (RuntimeException)
+{
+ return StringResourcePersistenceImpl::isModified();
+}
+void StringResourceWithLocationImpl::setComment( const ::rtl::OUString& Comment )
+ throw (::com::sun::star::uno::RuntimeException)
+{
+ StringResourcePersistenceImpl::setComment( Comment );
+}
+void StringResourceWithLocationImpl::storeToStorage( const Reference< XStorage >& Storage,
+ const ::rtl::OUString& NameBase, const ::rtl::OUString& Comment )
+ throw (Exception, RuntimeException)
+{
+ StringResourcePersistenceImpl::storeToStorage( Storage, NameBase, Comment );
+}
+void StringResourceWithLocationImpl::storeToURL( const ::rtl::OUString& URL,
+ const ::rtl::OUString& NameBase, const ::rtl::OUString& Comment,
+ const Reference< ::com::sun::star::task::XInteractionHandler >& Handler )
+ throw (Exception, RuntimeException)
+{
+ StringResourcePersistenceImpl::storeToURL( URL, NameBase, Comment, Handler );
+}
+Sequence< ::sal_Int8 > StringResourceWithLocationImpl::exportBinary( )
+ throw (RuntimeException)
+{
+ return StringResourcePersistenceImpl::exportBinary();
+}
+void StringResourceWithLocationImpl::importBinary( const Sequence< ::sal_Int8 >& Data )
+ throw (IllegalArgumentException, RuntimeException)
+{
+ StringResourcePersistenceImpl::importBinary( Data );
+}
+
+// -----------------------------------------------------------------------------
+// XStringResourceWithLocation
+
+// XStringResourceWithLocation
+void StringResourceWithLocationImpl::storeAsURL( const ::rtl::OUString& URL )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException)
+{
+ setURL( URL );
+ store();
+}
+
+void StringResourceWithLocationImpl::setURL( const ::rtl::OUString& URL )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+ implCheckReadOnly( "StringResourceWithLocationImpl::setURL(): Read only" );
+
+ sal_Int32 nLen = URL.getLength();
+ if( nLen == 0 )
+ {
+ ::rtl::OUString errorMsg = ::rtl::OUString::createFromAscii
+ ( "StringResourceWithLocationImpl::setURL: invalid URL" );
+ throw IllegalArgumentException( errorMsg, Reference< XInterface >(), 0 );
+ }
+
+ implLoadAllLocales();
+
+ // Delete files at old location
+ bool bUsedForStore = false;
+ bool bStoreAll = false;
+ bool bKillAll = true;
+ implStoreAtLocation( m_aLocation, m_aNameBase, m_aComment,
+ getFileAccess(), bUsedForStore, bStoreAll, bKillAll );
+
+ m_aLocation = URL;
+ m_bLocationChanged = true;
+}
+
+
+// =============================================================================
+// Private helper methods
+// =============================================================================
+
+// Scan locale properties files
+void StringResourceWithLocationImpl::implScanLocales( void )
+{
+ const Reference< ucb::XSimpleFileAccess > xFileAccess = getFileAccess();
+ if( xFileAccess.is() && xFileAccess->isFolder( m_aLocation ) )
+ {
+ Sequence< ::rtl::OUString > aContentSeq = xFileAccess->getFolderContents( m_aLocation, false );
+ implScanLocaleNames( aContentSeq );
+ }
+}
+
+// Loading
+bool StringResourceWithLocationImpl::implLoadLocale( LocaleItem* pLocaleItem )
+{
+ bool bSuccess = false;
+
+ const Reference< ucb::XSimpleFileAccess > xFileAccess = getFileAccess();
+ if( xFileAccess.is() )
+ {
+ ::rtl::OUString aCompleteFileName =
+ implGetPathForLocaleItem( pLocaleItem, m_aNameBase, m_aLocation );
+
+ Reference< io::XInputStream > xInputStream;
+ try
+ {
+ xInputStream = xFileAccess->openFileRead( aCompleteFileName );
+ }
+ catch( Exception& )
+ {}
+ if( xInputStream.is() )
+ {
+ bSuccess = StringResourcePersistenceImpl::implReadPropertiesFile( pLocaleItem, xInputStream );
+ xInputStream->closeInput();
+ }
+ }
+
+ return bSuccess;
+}
+
+const Reference< ucb::XSimpleFileAccess > StringResourceWithLocationImpl::getFileAccess( void )
+{
+ ::osl::MutexGuard aGuard( getMutex() );
+
+ if( !m_xSFI.is() )
+ {
+ Reference< XMultiComponentFactory > xMCF = getMultiComponentFactory();
+ m_xSFI = Reference< ucb::XSimpleFileAccess >( xMCF->createInstanceWithContext
+ ( ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ), m_xContext ), UNO_QUERY );
+
+ if( m_xSFI.is() && m_xInteractionHandler.is() )
+ m_xSFI->setInteractionHandler( m_xInteractionHandler );
+ }
+ return m_xSFI;
+}
+
+
+// =============================================================================
+// component export operations
+// =============================================================================
+
+static struct ::cppu::ImplementationEntry s_component_entries [] =
+{
+ {
+ create_StringResourceImpl, getImplementationName_StringResourceImpl,
+ getSupportedServiceNames_StringResourceImpl,
+ ::cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ {
+ create_StringResourceWithLocationImpl, getImplementationName_StringResourceWithLocationImpl,
+ getSupportedServiceNames_StringResourceWithLocationImpl,
+ ::cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ {
+ create_StringResourceWithStorageImpl, getImplementationName_StringResourceWithStorageImpl,
+ getSupportedServiceNames_StringResourceWithStorageImpl,
+ ::cppu::createSingleComponentFactory,
+ 0, 0
+ },
+ { 0, 0, 0, 0, 0, 0 }
+};
+
+
+//.........................................................................
+} // namespace dlgprov
+//.........................................................................
+
+
+// =============================================================================
+// component exports
+// =============================================================================
+
+extern "C"
+{
+ void SAL_CALL component_getImplementationEnvironment(
+ const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv )
+ {
+ (void)ppEnv;
+
+ *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
+ }
+
+ sal_Bool SAL_CALL component_writeInfo(
+ lang::XMultiServiceFactory * pServiceManager, registry::XRegistryKey * pRegistryKey )
+ {
+ return ::cppu::component_writeInfoHelper(
+ pServiceManager, pRegistryKey, ::stringresource::s_component_entries );
+ }
+
+ void * SAL_CALL component_getFactory(
+ const sal_Char * pImplName, lang::XMultiServiceFactory * pServiceManager,
+ registry::XRegistryKey * pRegistryKey )
+ {
+ return ::cppu::component_getFactoryHelper(
+ pImplName, pServiceManager, pRegistryKey, ::stringresource::s_component_entries );
+ }
+}
diff --git a/scripting/source/stringresource/stringresource.hxx b/scripting/source/stringresource/stringresource.hxx
new file mode 100644
index 000000000000..e5e3a7c12a35
--- /dev/null
+++ b/scripting/source/stringresource/stringresource.hxx
@@ -0,0 +1,691 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: stringresource.hxx,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+#ifndef SCRIPTING_DLGPROV_HXX
+#define SCRIPTING_DLGPROV_HXX
+
+#ifndef _COM_SUN_STAR_AWT_XSTRINGRESOURCEWITHSTORAGE_HPP_
+#include <com/sun/star/resource/XStringResourceWithStorage.hpp>
+#endif
+#ifndef _COM_SUN_STAR_AWT_XSTRINGRESOURCEWITHSTORAGE_HPP_
+#include <com/sun/star/resource/XStringResourceWithLocation.hpp>
+#endif
+#include <com/sun/star/lang/XServiceInfo.hpp>
+#include <com/sun/star/lang/XInitialization.hpp>
+#include <com/sun/star/uno/XComponentContext.hpp>
+#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
+#include <com/sun/star/io/XInputStream.hpp>
+#include <com/sun/star/io/XOutputStream.hpp>
+#include <cppuhelper/implbase1.hxx>
+#include <cppuhelper/implbase2.hxx>
+#include <cppuhelper/interfacecontainer.hxx>
+#include <osl/mutex.hxx>
+
+#include <vector>
+#include <hash_map>
+
+//.........................................................................
+namespace stringresource
+{
+//.........................................................................
+
+// =============================================================================
+// mutex
+// =============================================================================
+
+::osl::Mutex& getMutex();
+
+
+// =============================================================================
+// class stringresourceImpl
+// =============================================================================
+
+// Hashtable to map string ids to string
+struct hashName_Impl
+{
+ size_t operator()(const ::rtl::OUString Str) const
+ {
+ return (size_t)Str.hashCode();
+ }
+};
+
+struct eqName_Impl
+{
+ sal_Bool operator()(const ::rtl::OUString Str1, const ::rtl::OUString Str2) const
+ {
+ return ( Str1 == Str2 );
+ }
+};
+
+typedef std::hash_map
+<
+ ::rtl::OUString,
+ ::rtl::OUString,
+ hashName_Impl,
+ eqName_Impl
+>
+IdToStringMap;
+
+typedef std::hash_map
+<
+ ::rtl::OUString,
+ sal_Int32,
+ hashName_Impl,
+ eqName_Impl
+>
+IdToIndexMap;
+
+
+struct LocaleItem
+{
+ ::com::sun::star::lang::Locale m_locale;
+ IdToStringMap m_aIdToStringMap;
+ IdToIndexMap m_aIdToIndexMap;
+ sal_Int32 m_nNextIndex;
+ bool m_bLoaded;
+ bool m_bModified;
+
+ LocaleItem( ::com::sun::star::lang::Locale locale, bool bLoaded=true )
+ : m_locale( locale )
+ , m_nNextIndex( 0 )
+ , m_bLoaded( bLoaded )
+ , m_bModified( false )
+ {}
+};
+
+typedef std::vector< LocaleItem* > LocaleItemVector;
+typedef std::vector< LocaleItem* >::iterator LocaleItemVectorIt;
+typedef std::vector< LocaleItem* >::const_iterator LocaleItemVectorConstIt;
+
+typedef ::cppu::WeakImplHelper2<
+ ::com::sun::star::lang::XServiceInfo,
+ ::com::sun::star::resource::XStringResourceManager > StringResourceImpl_BASE;
+
+class StringResourceImpl : public StringResourceImpl_BASE
+{
+protected:
+ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > m_xContext;
+ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiComponentFactory > m_xMCF;
+
+ LocaleItem* m_pCurrentLocaleItem;
+ LocaleItem* m_pDefaultLocaleItem;
+ bool m_bDefaultModified;
+
+ ::cppu::OInterfaceContainerHelper m_aListenerContainer;
+
+ LocaleItemVector m_aLocaleItemVector;
+ LocaleItemVector m_aDeletedLocaleItemVector;
+ LocaleItemVector m_aChangedDefaultLocaleVector;
+
+ bool m_bModified;
+ bool m_bReadOnly;
+
+ sal_Int32 m_nNextUniqueNumericId;
+
+ // Scans ResourceID to start with number and adapt m_nNextUniqueNumericId
+ void implScanIdForNumber( const ::rtl::OUString& ResourceID );
+ const static sal_Int32 UNIQUE_NUMBER_NEEDS_INITIALISATION = -1;
+
+ // Checks read only status and throws exception if it's true
+ void implCheckReadOnly( const sal_Char* pExceptionMsg )
+ throw (::com::sun::star::lang::NoSupportException);
+
+ // Return the context's MultiComponentFactory
+ ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiComponentFactory >
+ getMultiComponentFactory( void );
+
+ // Returns the LocalItem for a given locale, if it exists, otherwise NULL
+ // This method compares the locales exactly, no closest match search is performed
+ LocaleItem* getItemForLocale( const ::com::sun::star::lang::Locale& locale, sal_Bool bException )
+ throw (::com::sun::star::lang::IllegalArgumentException);
+
+ // Returns the LocalItem for a given locale, if it exists, otherwise NULL
+ // This method performes a closest match search, at least the language must match
+ LocaleItem* getClosestMatchItemForLocale( const ::com::sun::star::lang::Locale& locale );
+
+ void implModified( void );
+ void implNotifyListeners( void );
+
+ //=== Impl methods for ...ForLocale methods ===
+ ::rtl::OUString SAL_CALL implResolveString( const ::rtl::OUString& ResourceID, LocaleItem* pLocaleItem )
+ throw (::com::sun::star::resource::MissingResourceException);
+ ::sal_Bool implHasEntryForId( const ::rtl::OUString& ResourceID, LocaleItem* pLocaleItem );
+ ::com::sun::star::uno::Sequence< ::rtl::OUString > implGetResourceIDs( LocaleItem* pLocaleItem );
+ void implSetString( const ::rtl::OUString& ResourceID,
+ const ::rtl::OUString& Str, LocaleItem* pLocaleItem );
+ void implRemoveId( const ::rtl::OUString& ResourceID, LocaleItem* pLocaleItem )
+ throw (::com::sun::star::resource::MissingResourceException);
+
+ // Method to load a locale if necessary, returns true if loading was
+ // successful. Default implementation in base class just returns true.
+ virtual bool loadLocale( LocaleItem* pLocaleItem );
+
+ virtual void implLoadAllLocales( void );
+
+public:
+ StringResourceImpl(
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext );
+ virtual ~StringResourceImpl();
+
+ // XServiceInfo
+ virtual ::rtl::OUString SAL_CALL getImplementationName( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XModifyBroadcaster
+ virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XStringResourceResolver
+ virtual ::rtl::OUString SAL_CALL resolveString( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException);
+ virtual ::rtl::OUString SAL_CALL resolveStringForLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw ( ::com::sun::star::resource::MissingResourceException,
+ ::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL hasEntryForId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL hasEntryForIdAndLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getResourceIDs( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getResourceIDsForLocale
+ ( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::lang::Locale SAL_CALL getCurrentLocale( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::lang::Locale SAL_CALL getDefaultLocale( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > SAL_CALL getLocales( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XStringResourceManager
+ virtual ::sal_Bool SAL_CALL isReadOnly()
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setCurrentLocale( const ::com::sun::star::lang::Locale& locale, ::sal_Bool FindClosestMatch )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setDefaultLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL setString( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str )
+ throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setStringForLocale( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL removeIdForLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL newLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::container::ElementExistException, ::com::sun::star::lang::IllegalArgumentException,
+ ::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual ::sal_Int32 SAL_CALL getUniqueNumericId( )
+ throw (::com::sun::star::lang::NoSupportException,
+ ::com::sun::star::uno::RuntimeException);
+ };
+
+typedef ::cppu::ImplInheritanceHelper1<
+ StringResourceImpl,
+ ::com::sun::star::resource::XStringResourcePersistence > StringResourcePersistenceImpl_BASE;
+
+class BinaryOutput;
+class BinaryInput;
+
+class StringResourcePersistenceImpl : public StringResourcePersistenceImpl_BASE
+{
+protected:
+ ::rtl::OUString m_aNameBase;
+ ::rtl::OUString m_aComment;
+
+ void SAL_CALL implInitializeCommonParameters
+ ( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+ // Scan locale properties files
+ virtual void implScanLocales( void );
+
+ // Method to load a locale if necessary, returns true if loading was successful
+ virtual bool loadLocale( LocaleItem* pLocaleItem );
+
+ // does the actual loading
+ virtual bool implLoadLocale( LocaleItem* pLocaleItem );
+
+ virtual void implLoadAllLocales( void );
+
+ void implScanLocaleNames( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aContentSeq );
+ ::rtl::OUString implGetFileNameForLocaleItem( LocaleItem* pLocaleItem, const ::rtl::OUString& aNameBase );
+ ::rtl::OUString implGetPathForLocaleItem( LocaleItem* pLocaleItem, const ::rtl::OUString& aNameBase,
+ const ::rtl::OUString& aLocation, bool bDefaultFile=false );
+
+ bool implReadPropertiesFile( LocaleItem* pLocaleItem,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInput );
+
+ bool implWritePropertiesFile( LocaleItem* pLocaleItem, const ::com::sun::star::uno::Reference
+ < ::com::sun::star::io::XOutputStream >& xOutputStream, const ::rtl::OUString& aComment );
+
+ void implWriteLocaleBinary( LocaleItem* pLocaleItem, BinaryOutput& rOut );
+
+ void implStoreAtStorage
+ (
+ const ::rtl::OUString& aNameBase,
+ const ::rtl::OUString& aComment,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage,
+ bool bUsedForStore,
+ bool bStoreAll
+ )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+ void implKillRemovedLocaleFiles
+ (
+ const ::rtl::OUString& Location,
+ const ::rtl::OUString& aNameBase,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >& xFileAccess
+ )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+ void implKillChangedDefaultFiles
+ (
+ const ::rtl::OUString& Location,
+ const ::rtl::OUString& aNameBase,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >& xFileAccess
+ )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+ void implStoreAtLocation
+ (
+ const ::rtl::OUString& Location,
+ const ::rtl::OUString& aNameBase,
+ const ::rtl::OUString& aComment,
+ const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess >& xFileAccess,
+ bool bUsedForStore,
+ bool bStoreAll,
+ bool bKillAll = false
+ )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+public:
+ StringResourcePersistenceImpl(
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext );
+ virtual ~StringResourcePersistenceImpl();
+
+ // XServiceInfo
+ virtual ::rtl::OUString SAL_CALL getImplementationName( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XModifyBroadcaster
+ virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XStringResourceResolver
+ virtual ::rtl::OUString SAL_CALL resolveString( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException);
+ virtual ::rtl::OUString SAL_CALL resolveStringForLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw ( ::com::sun::star::resource::MissingResourceException,
+ ::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL hasEntryForId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL hasEntryForIdAndLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getResourceIDs( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getResourceIDsForLocale
+ ( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::lang::Locale SAL_CALL getCurrentLocale( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::lang::Locale SAL_CALL getDefaultLocale( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > SAL_CALL getLocales( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XStringResourceManager
+ virtual ::sal_Bool SAL_CALL isReadOnly()
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setCurrentLocale( const ::com::sun::star::lang::Locale& locale, ::sal_Bool FindClosestMatch )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setDefaultLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL setString( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str )
+ throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setStringForLocale( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL removeIdForLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL newLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::container::ElementExistException, ::com::sun::star::lang::IllegalArgumentException,
+ ::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual ::sal_Int32 SAL_CALL getUniqueNumericId( )
+ throw (::com::sun::star::lang::NoSupportException,
+ ::com::sun::star::uno::RuntimeException);
+
+ // XStringResourcePersistence
+ virtual void SAL_CALL store( )
+ throw (::com::sun::star::lang::NoSupportException,
+ ::com::sun::star::uno::Exception,
+ ::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL isModified( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setComment( const ::rtl::OUString& Comment )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL storeToStorage
+ ( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage,
+ const ::rtl::OUString& NameBase, const ::rtl::OUString& Comment )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL storeToURL( const ::rtl::OUString& URL, const ::rtl::OUString& NameBase,
+ const ::rtl::OUString& Comment, const ::com::sun::star::uno::Reference
+ < ::com::sun::star::task::XInteractionHandler >& Handler )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::sal_Int8 > SAL_CALL exportBinary( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL importBinary( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& Data )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+};
+
+
+typedef ::cppu::ImplInheritanceHelper2<
+ StringResourcePersistenceImpl,
+ ::com::sun::star::lang::XInitialization,
+ ::com::sun::star::resource::XStringResourceWithStorage > StringResourceWithStorageImpl_BASE;
+
+class StringResourceWithStorageImpl : public StringResourceWithStorageImpl_BASE
+{
+ ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > m_xStorage;
+ bool m_bStorageChanged;
+
+ virtual void implScanLocales( void );
+ virtual bool implLoadLocale( LocaleItem* pLocaleItem );
+
+public:
+ StringResourceWithStorageImpl(
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext );
+ virtual ~StringResourceWithStorageImpl();
+
+ // XServiceInfo
+ virtual ::rtl::OUString SAL_CALL getImplementationName( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XInitialization
+ virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+ // XModifyBroadcaster
+ virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XStringResourceResolver
+ virtual ::rtl::OUString SAL_CALL resolveString( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException);
+ virtual ::rtl::OUString SAL_CALL resolveStringForLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw ( ::com::sun::star::resource::MissingResourceException,
+ ::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL hasEntryForId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL hasEntryForIdAndLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getResourceIDs( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getResourceIDsForLocale
+ ( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::lang::Locale SAL_CALL getCurrentLocale( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::lang::Locale SAL_CALL getDefaultLocale( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > SAL_CALL getLocales( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XStringResourceManager
+ virtual ::sal_Bool SAL_CALL isReadOnly()
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setCurrentLocale( const ::com::sun::star::lang::Locale& locale, ::sal_Bool FindClosestMatch )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setDefaultLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL setString( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str )
+ throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setStringForLocale( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL removeIdForLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL newLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::container::ElementExistException, ::com::sun::star::lang::IllegalArgumentException,
+ ::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual ::sal_Int32 SAL_CALL getUniqueNumericId( )
+ throw (::com::sun::star::lang::NoSupportException,
+ ::com::sun::star::uno::RuntimeException);
+
+ // XStringResourcePersistence
+ virtual void SAL_CALL store( )
+ throw (::com::sun::star::lang::NoSupportException,
+ ::com::sun::star::uno::Exception,
+ ::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL isModified( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setComment( const ::rtl::OUString& Comment )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL storeToStorage
+ ( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage,
+ const ::rtl::OUString& NameBase, const ::rtl::OUString& Comment )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL storeToURL( const ::rtl::OUString& URL, const ::rtl::OUString& NameBase,
+ const ::rtl::OUString& Comment, const ::com::sun::star::uno::Reference
+ < ::com::sun::star::task::XInteractionHandler >& Handler )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::sal_Int8 > SAL_CALL exportBinary( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL importBinary( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& Data )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+
+ // XStringResourceWithStorage
+ virtual void SAL_CALL storeAsStorage
+ ( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setStorage
+ ( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+};
+
+
+typedef ::cppu::ImplInheritanceHelper2<
+ StringResourcePersistenceImpl,
+ ::com::sun::star::lang::XInitialization,
+ ::com::sun::star::resource::XStringResourceWithLocation > StringResourceWithLocationImpl_BASE;
+
+class StringResourceWithLocationImpl : public StringResourceWithLocationImpl_BASE
+{
+ ::rtl::OUString m_aLocation;
+ bool m_bLocationChanged;
+ com::sun::star::uno::Reference< com::sun::star::ucb::XSimpleFileAccess > m_xSFI;
+ com::sun::star::uno::Reference< com::sun::star::task::XInteractionHandler > m_xInteractionHandler;
+
+ const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XSimpleFileAccess > getFileAccess( void );
+
+ virtual void implScanLocales( void );
+ virtual bool implLoadLocale( LocaleItem* pLocaleItem );
+
+public:
+ StringResourceWithLocationImpl(
+ const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& rxContext );
+ virtual ~StringResourceWithLocationImpl();
+
+ // XServiceInfo
+ virtual ::rtl::OUString SAL_CALL getImplementationName( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XInitialization
+ virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+
+ // XModifyBroadcaster
+ virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XStringResourceResolver
+ virtual ::rtl::OUString SAL_CALL resolveString( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException);
+ virtual ::rtl::OUString SAL_CALL resolveStringForLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw ( ::com::sun::star::resource::MissingResourceException,
+ ::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL hasEntryForId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL hasEntryForIdAndLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getResourceIDs( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getResourceIDsForLocale
+ ( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::lang::Locale SAL_CALL getCurrentLocale( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::lang::Locale SAL_CALL getDefaultLocale( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::com::sun::star::lang::Locale > SAL_CALL getLocales( )
+ throw (::com::sun::star::uno::RuntimeException);
+
+ // XStringResourceManager
+ virtual ::sal_Bool SAL_CALL isReadOnly()
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setCurrentLocale( const ::com::sun::star::lang::Locale& locale, ::sal_Bool FindClosestMatch )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setDefaultLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL setString( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str )
+ throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setStringForLocale( const ::rtl::OUString& ResourceID, const ::rtl::OUString& Str,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeId( const ::rtl::OUString& ResourceID )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL removeIdForLocale( const ::rtl::OUString& ResourceID,
+ const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::resource::MissingResourceException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual void SAL_CALL newLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::container::ElementExistException, ::com::sun::star::lang::IllegalArgumentException,
+ ::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL removeLocale( const ::com::sun::star::lang::Locale& locale )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException,
+ ::com::sun::star::lang::NoSupportException);
+ virtual ::sal_Int32 SAL_CALL getUniqueNumericId( )
+ throw (::com::sun::star::lang::NoSupportException,
+ ::com::sun::star::uno::RuntimeException);
+
+ // XStringResourcePersistence
+ virtual void SAL_CALL store( )
+ throw (::com::sun::star::lang::NoSupportException,
+ ::com::sun::star::uno::Exception,
+ ::com::sun::star::uno::RuntimeException);
+ virtual ::sal_Bool SAL_CALL isModified( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setComment( const ::rtl::OUString& Comment )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL storeToStorage
+ ( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage,
+ const ::rtl::OUString& NameBase, const ::rtl::OUString& Comment )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL storeToURL( const ::rtl::OUString& URL, const ::rtl::OUString& NameBase,
+ const ::rtl::OUString& Comment, const ::com::sun::star::uno::Reference
+ < ::com::sun::star::task::XInteractionHandler >& Handler )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+ virtual ::com::sun::star::uno::Sequence< ::sal_Int8 > SAL_CALL exportBinary( )
+ throw (::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL importBinary( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& Data )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+
+ // XStringResourceWithLocation
+ virtual void SAL_CALL storeAsURL( const ::rtl::OUString& URL )
+ throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
+ virtual void SAL_CALL setURL( const ::rtl::OUString& URL )
+ throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
+};
+
+//.........................................................................
+} // namespace stringtable
+//.........................................................................
+
+#endif // SCRIPTING_DLGPROV_HXX
diff --git a/scripting/source/stringresource/stringresource.map b/scripting/source/stringresource/stringresource.map
new file mode 100644
index 000000000000..737cddbfe3df
--- /dev/null
+++ b/scripting/source/stringresource/stringresource.map
@@ -0,0 +1,9 @@
+OOO_1.1 {
+ global:
+ component_getImplementationEnvironment;
+ component_getFactory;
+ component_writeInfo;
+
+ local:
+ *;
+};
diff --git a/scripting/source/stringresource/stringresource.xml b/scripting/source/stringresource/stringresource.xml
new file mode 100644
index 000000000000..51cbf9921d8a
--- /dev/null
+++ b/scripting/source/stringresource/stringresource.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE module-description PUBLIC "-//StarOffice//DTD ComponentDescription 1.0//EN" "module-description.dtd">
+<module-description xmlns:xlink="http://www.w3.org/1999/xlink">
+
+ <module-name>stringresource</module-name>
+
+ <component-description>
+ <author>Andreas Bregas</author>
+ <name>com.sun.star.comp.scripting.StringResource</name>
+ <description>string resource</description>
+ <loader-name>com.sun.star.loader.SharedLibrary</loader-name>
+ <language>c++</language>
+ <status value="drafts"/>
+ <supported-service>com.sun.star.resource.StringResource</supported-service>
+ <supported-service>com.sun.star.resource.StringResourceWithLocation</supported-service>
+ <supported-service>com.sun.star.resource.StringResourceWithStorage</supported-service>
+ <type>com.sun.star.resource.XStringResourceWithStorage</type>
+ <type>com.sun.star.lang.IllegalArgumentException</type>
+ <type>com.sun.star.lang.XInitialization</type>
+ <type>com.sun.star.lang.XMultiComponentFactory</type>
+ <type>com.sun.star.lang.XServiceInfo</type>
+ <type>com.sun.star.uno.XComponentContext</type>
+ <type>com.sun.star.ucb.XSimpleFileAccess3</type>
+ <type>com.sun.star.io.XInputStream</type>
+ </component-description>
+
+ <project-build-dependency>cppuhelper</project-build-dependency>
+ <project-build-dependency>cppu</project-build-dependency>
+ <project-build-dependency>sal</project-build-dependency>
+
+ <runtime-module-dependency>cppuhelper3$(COM)</runtime-module-dependency>
+ <runtime-module-dependency>cppu3</runtime-module-dependency>
+ <runtime-module-dependency>sal3</runtime-module-dependency>
+ <runtime-module-dependency>ucb</runtime-module-dependency>
+
+</module-description>
diff --git a/scripting/util/ant.pmk b/scripting/util/ant.pmk
new file mode 100755
index 000000000000..927ceb249b4f
--- /dev/null
+++ b/scripting/util/ant.pmk
@@ -0,0 +1,59 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: ant.pmk,v $
+#
+# $Revision: 1.5 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+JARFILES*=../util/ant.jar
+
+# needs jdk1.2 !
+JAVAC_LIB:=$(JAVA_HOME)$/lib$/tools.jar
+
+STARDEP=@echo ANTBuild
+
+OTHER=antbuild
+OTHERTARRGET=OTHERTARGET
+SOLARDOCDIR=$(SOLARVER)$/$(INPATH)$/doc$(EXT_UPDMINOR)
+
+
+ANT=java -Xmx128m org.apache.tools.ant.Main
+.IF "$(ANT_BUILDFILE)" ==""
+ANT_BUILDFILE=build.xml
+.ENDIF
+ANTFLAGS!:=-Dprj=$(PRJ) -Dant.home=$(SOLARBINDIR)$/.. -Dsolar.doc=$(SOLARDOCDIR) -f $(ANT_BUILDFILE) $(ANTFLAGS) -Djardir=$(JARDIR) -Dsolar.jar=$(SOLARBINDIR) -Dout=$(OUT) -Dinpath=$(INPATH)
+
+.INCLUDE : ../util/target.pmk
+
+ANT_CLASSPATH:=..$/util$/xerces.jar$(PATH_SEPERATOR)..$/util$/ant.jar$(PATH_SEPERATOR)..$/util$/junit.jar
+CLASSPATH!:=$(ANT_CLASSPATH)$(CLASSPATH)
+.EXPORT : CLASSPATH
+
+antbuild .PHONY:
+ $(ANT) $(ANTFLAGS)
+
+
diff --git a/scripting/util/exports.dxp b/scripting/util/exports.dxp
new file mode 100644
index 000000000000..9630d7e06768
--- /dev/null
+++ b/scripting/util/exports.dxp
@@ -0,0 +1,3 @@
+component_getImplementationEnvironment
+component_writeInfo
+component_getFactory
diff --git a/scripting/util/makefile.mk b/scripting/util/makefile.mk
new file mode 100644
index 000000000000..82184a33dfaf
--- /dev/null
+++ b/scripting/util/makefile.mk
@@ -0,0 +1,71 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.9 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+PRJ=..
+
+ENABLE_EXCEPTIONS=TRUE
+VISIBILITY_HIDDEN=TRUE
+PRJNAME=scripting
+TARGET=scriptframe
+USE_DEFFILE= TRUE
+NO_BSYMBOLIC= TRUE
+
+# --- Settings -----------------------------------------------------
+
+.INCLUDE : settings.mk
+
+# --- Allgemein ----------------------------------------------------
+LIB1TARGET= $(SLB)$/$(TARGET).lib
+LIB1FILES= $(SLB)/provider.lib
+
+
+SHL1TARGET= $(TARGET)
+SHL1IMPLIB= $(TARGET)
+
+SHL1STDLIBS+=\
+ $(TOOLSLIB) \
+ $(CPPULIB) \
+ $(CPPUHELPERLIB) \
+ $(COMPHELPERLIB) \
+ $(UCBHELPERLIB) \
+ $(SALLIB)
+
+
+SHL1LIBS= $(SLB)$/$(TARGET).lib
+
+SHL1DEF= $(MISC)$/$(SHL1TARGET).def
+
+DEF1NAME =$(SHL1TARGET)
+DEF1EXPORTFILE= exports.dxp
+# --- Targets ------------------------------------------------------
+
+
+.INCLUDE : target.mk
diff --git a/scripting/util/makefile.pmk b/scripting/util/makefile.pmk
new file mode 100755
index 000000000000..b8240f7f3229
--- /dev/null
+++ b/scripting/util/makefile.pmk
@@ -0,0 +1,47 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.pmk,v $
+#
+# $Revision: 1.3 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+# --- Settings -----------------------------------------------------
+.INCLUDE : settings.mk
+
+.IF "$(J2EE_HOME)"==""
+J2EE_HOME=n:\j2sdkee1.2
+.ENDIF
+
+NODEFAULTUNO=TRUE
+NOJARDEP=TRUE
+
+javauno=TRUE
+
+JARFILES =
+
+JAVA_EXTENSIONS =
+
diff --git a/scripting/util/target.pmk b/scripting/util/target.pmk
new file mode 100755
index 000000000000..6c98ccf50032
--- /dev/null
+++ b/scripting/util/target.pmk
@@ -0,0 +1,32 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: target.pmk,v $
+#
+# $Revision: 1.3 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+.INCLUDE : target.mk
diff --git a/scripting/workben/bindings/EditDebug.xdl b/scripting/workben/bindings/EditDebug.xdl
new file mode 100644
index 000000000000..226104b2d746
--- /dev/null
+++ b/scripting/workben/bindings/EditDebug.xdl
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
+<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="EditDebugDialog" dlg:left="64" dlg:top="89" dlg:width="179" dlg:height="151" dlg:closeable="true" dlg:moveable="true" dlg:title="Edit/Debug Scripts">
+ <dlg:bulletinboard>
+ <dlg:combobox dlg:id="LocationCombo" dlg:tab-index="0" dlg:left="64" dlg:top="17" dlg:width="110" dlg:height="13" dlg:spin="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.fireLangLocComboListernerOnRet" script:language="StarBasic"/>
+ </dlg:combobox>
+ <dlg:combobox dlg:id="LanguageCombo" dlg:tab-index="1" dlg:left="64" dlg:top="33" dlg:width="110" dlg:height="13" dlg:spin="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.fireLangLocComboListernerOnRet" script:language="StarBasic"/>
+ </dlg:combobox>
+ <dlg:checkbox dlg:id="detail" dlg:tab-index="2" dlg:left="12" dlg:top="70" dlg:width="45" dlg:height="10" dlg:value="Detailed view" dlg:checked="false">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ </dlg:checkbox>
+ <dlg:menulist dlg:id="ScriptList" dlg:tab-index="3" dlg:left="64" dlg:top="50" dlg:width="110" dlg:height="44"/>
+ <dlg:button dlg:id="OK" dlg:tab-index="5" dlg:left="58" dlg:top="131" dlg:width="36" dlg:height="14" dlg:value="OK">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.DoEdit" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="Cancel" dlg:tab-index="6" dlg:left="97" dlg:top="131" dlg:width="36" dlg:height="14" dlg:value="Cancel">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuCancelButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="Help" dlg:tab-index="7" dlg:left="138" dlg:top="131" dlg:width="36" dlg:height="14" dlg:value="Help">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuHelpButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:fixedline dlg:id="FixedLine1" dlg:tab-index="8" dlg:left="42" dlg:top="6" dlg:width="131" dlg:height="7"/>
+ <dlg:text dlg:id="Label1" dlg:tab-index="9" dlg:left="5" dlg:top="6" dlg:width="36" dlg:height="9" dlg:value="Select script"/>
+ <dlg:text dlg:id="Label7" dlg:tab-index="10" dlg:left="12" dlg:top="18" dlg:width="29" dlg:height="11" dlg:value="Location"/>
+ <dlg:text dlg:id="Label8" dlg:tab-index="11" dlg:left="12" dlg:top="31" dlg:width="35" dlg:height="9" dlg:value="Language"/>
+ <dlg:text dlg:id="Label9" dlg:tab-index="12" dlg:left="12" dlg:top="53" dlg:width="24" dlg:height="14" dlg:value="Script"/>
+ <dlg:fixedline dlg:id="FixedLine2" dlg:tab-index="13" dlg:left="7" dlg:top="120" dlg:width="167" dlg:height="7"/>
+ <dlg:button dlg:id="Browse" dlg:tab-index="4" dlg:disabled="true" dlg:left="136" dlg:top="101" dlg:width="36" dlg:height="14" dlg:value="Browse...">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.DoBrowseAndEdit" script:language="StarBasic"/>
+ </dlg:button>
+ </dlg:bulletinboard>
+</dlg:window> \ No newline at end of file
diff --git a/scripting/workben/bindings/EventsBinding.xdl b/scripting/workben/bindings/EventsBinding.xdl
new file mode 100644
index 000000000000..fe980b5ddfdb
--- /dev/null
+++ b/scripting/workben/bindings/EventsBinding.xdl
@@ -0,0 +1,61 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
+<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="EventBindingDialog" dlg:left="64" dlg:top="99" dlg:width="179" dlg:height="209" dlg:closeable="true" dlg:moveable="true" dlg:title="Assign Script To Event">
+ <dlg:styles>
+ <dlg:style dlg:style-id="0" dlg:font-height="7"/>
+ </dlg:styles>
+ <dlg:bulletinboard>
+ <dlg:combobox dlg:id="LocationCombo" dlg:tab-index="0" dlg:left="63" dlg:top="19" dlg:width="108" dlg:height="12" dlg:spin="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.fireLangLocComboListernerOnRet" script:language="StarBasic"/>
+ </dlg:combobox>
+ <dlg:combobox dlg:id="LanguageCombo" dlg:tab-index="1" dlg:left="63" dlg:top="31" dlg:width="108" dlg:height="12" dlg:spin="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.fireLangLocComboListernerOnRet" script:language="StarBasic"/>
+ </dlg:combobox>
+ <dlg:checkbox dlg:id="detail" dlg:tab-index="2" dlg:left="17" dlg:top="57" dlg:width="44" dlg:height="10" dlg:value="Detailed view" dlg:checked="false">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ </dlg:checkbox>
+ <dlg:menulist dlg:id="ScriptList" dlg:tab-index="3" dlg:left="63" dlg:top="48" dlg:width="108" dlg:height="44"/>
+ <dlg:button dlg:id="Browse" dlg:tab-index="4" dlg:disabled="true" dlg:left="17" dlg:top="71" dlg:width="36" dlg:height="14" dlg:value="Browse...">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.BrowseButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:radiogroup>
+ <dlg:radio dlg:id="AllAppsOption" dlg:tab-index="5" dlg:left="12" dlg:top="107" dlg:width="51" dlg:height="10" dlg:value="All Applications">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.AppDocEventListener" script:language="StarBasic"/>
+ </dlg:radio>
+ <dlg:radio dlg:id="DocumentOption" dlg:tab-index="6" dlg:left="12" dlg:top="119" dlg:width="46" dlg:height="10" dlg:value="Document" dlg:checked="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.AppDocEventListener" script:language="StarBasic"/>
+ </dlg:radio>
+ </dlg:radiogroup>
+ <dlg:menulist dlg:id="EventList" dlg:tab-index="7" dlg:left="64" dlg:top="109" dlg:width="108" dlg:height="64">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.EventListListener" script:language="StarBasic"/>
+ </dlg:menulist>
+ <dlg:button dlg:id="Delete" dlg:tab-index="8" dlg:left="17" dlg:top="131" dlg:width="36" dlg:height="13" dlg:value="Delete">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.EventDeleteButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="NewButton" dlg:tab-index="9" dlg:left="17" dlg:top="159" dlg:width="36" dlg:height="13" dlg:value="Assign">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.EventNewButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="OK" dlg:tab-index="10" dlg:left="57" dlg:top="192" dlg:width="36" dlg:height="13" dlg:value="OK">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.EventOKButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="Cancel" dlg:tab-index="11" dlg:left="96" dlg:top="192" dlg:width="36" dlg:height="13" dlg:value="Cancel">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuCancelButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="Help" dlg:tab-index="12" dlg:left="136" dlg:top="192" dlg:width="36" dlg:height="13" dlg:value="Help">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuHelpButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:fixedline dlg:id="FixedLine2" dlg:tab-index="13" dlg:left="9" dlg:top="182" dlg:width="167" dlg:height="6"/>
+ <dlg:fixedline dlg:id="FixedLine4" dlg:tab-index="14" dlg:left="76" dlg:top="99" dlg:width="98" dlg:height="5"/>
+ <dlg:text dlg:id="Label4" dlg:tab-index="15" dlg:left="5" dlg:top="97" dlg:width="71" dlg:height="8" dlg:value="Choose Event to assign to"/>
+ <dlg:fixedline dlg:id="FixedLine1" dlg:tab-index="16" dlg:left="42" dlg:top="7" dlg:width="132" dlg:height="6"/>
+ <dlg:text dlg:id="Label1" dlg:tab-index="17" dlg:left="5" dlg:top="7" dlg:width="36" dlg:height="8" dlg:value="Select script"/>
+ <dlg:text dlg:id="Label7" dlg:tab-index="18" dlg:left="12" dlg:top="17" dlg:width="28" dlg:height="7" dlg:value="Location"/>
+ <dlg:text dlg:id="Label8" dlg:tab-index="19" dlg:left="12" dlg:top="32" dlg:width="35" dlg:height="9" dlg:value="Language"/>
+ <dlg:text dlg:id="Label9" dlg:tab-index="20" dlg:left="12" dlg:top="49" dlg:width="23" dlg:height="8" dlg:value="Script"/>
+ <dlg:text dlg:id="Label10" dlg:tab-index="21" dlg:left="103" dlg:top="-19" dlg:width="3" dlg:height="0" dlg:value="Label10"/>
+ <dlg:text dlg:style-id="0" dlg:id="AddOn" dlg:tab-index="22" dlg:disabled="true" dlg:left="17" dlg:top="144" dlg:width="38" dlg:height="10" dlg:value="[Add-on&apos;s only]"/>
+ <dlg:text dlg:id="fsonly" dlg:tab-index="23" dlg:disabled="true" dlg:left="13" dlg:top="86" dlg:width="45" dlg:height="8" dlg:value="[Filesystem only]"/>
+ </dlg:bulletinboard>
+</dlg:window> \ No newline at end of file
diff --git a/scripting/workben/bindings/HelpBinding.xdl b/scripting/workben/bindings/HelpBinding.xdl
new file mode 100644
index 000000000000..7d39670097ec
--- /dev/null
+++ b/scripting/workben/bindings/HelpBinding.xdl
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
+<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="HelpBinding" dlg:left="100" dlg:top="8" dlg:width="213" dlg:height="388" dlg:closeable="true" dlg:moveable="true" dlg:title="Office Help - Help about the Assign Script Dialogs">
+ <dlg:styles>
+ <dlg:style dlg:style-id="0" dlg:text-color="0xff"/>
+ <dlg:style dlg:style-id="1" dlg:font-height="10"/>
+ </dlg:styles>
+ <dlg:bulletinboard>
+ <dlg:text dlg:id="Label2" dlg:tab-index="0" dlg:left="14" dlg:top="6" dlg:width="179" dlg:height="12" dlg:value="Integrated Help For Scripting Framework is not currently available." dlg:multiline="true"/>
+ <dlg:text dlg:id="Label1" dlg:tab-index="1" dlg:left="14" dlg:top="24" dlg:width="185" dlg:height="34" dlg:value="Assign Script Dialogs for Menus, Keys and Events allow you to bind a script written in a supported language (currently Java and BeanShell) to a menu item, key combo, Office event or document event." dlg:multiline="true"/>
+ <dlg:text dlg:id="Label3" dlg:tab-index="2" dlg:left="14" dlg:top="66" dlg:width="185" dlg:height="26" dlg:value="The location combo box will be populated with User, Share or Document. The default value will be User which will display all scripts (with the selected language type) in the User area.&#x0a;" dlg:multiline="true"/>
+ <dlg:titledbox dlg:id="FrameControl1" dlg:tab-index="3" dlg:left="9" dlg:top="20" dlg:width="196" dlg:height="346"/>
+ <dlg:text dlg:id="Label4" dlg:tab-index="4" dlg:left="14" dlg:top="92" dlg:width="185" dlg:height="18" dlg:value="The language combo box is populated with the list of supported languages. The default language is set to Java." dlg:multiline="true"/>
+ <dlg:button dlg:id="HelpOKButton" dlg:tab-index="5" dlg:left="167" dlg:top="371" dlg:width="36" dlg:height="13" dlg:value="OK">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.HelpOKButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:text dlg:id="Label5" dlg:tab-index="6" dlg:left="14" dlg:top="144" dlg:width="185" dlg:height="34" dlg:value="In the Script combo box the script&apos;s display name will always be visible, if two or more scripts have the same display name (or if the Detailed View check box is selected) the script will be displayed as follows: display name [function name]" dlg:multiline="true"/>
+ <dlg:text dlg:id="Label6" dlg:tab-index="7" dlg:left="14" dlg:top="342" dlg:width="185" dlg:height="10" dlg:value="For further information see the User Guide at:" dlg:multiline="true"/>
+ <dlg:text dlg:style-id="0" dlg:id="Label7" dlg:tab-index="8" dlg:left="14" dlg:top="351" dlg:width="185" dlg:height="10" dlg:value="http://framework.openoffice.org/scripting/user-guide.html" dlg:multiline="true"/>
+ <dlg:text dlg:style-id="1" dlg:id="Label8" dlg:tab-index="9" dlg:left="14" dlg:top="55" dlg:width="185" dlg:height="11" dlg:value="Information common to all dialogs" dlg:multiline="true"/>
+ <dlg:text dlg:style-id="1" dlg:id="Label9" dlg:tab-index="10" dlg:left="14" dlg:top="198" dlg:width="185" dlg:height="18" dlg:value="Assign Script to Menu Dialog" dlg:multiline="true"/>
+ <dlg:text dlg:style-id="1" dlg:id="Label10" dlg:tab-index="11" dlg:left="14" dlg:top="247" dlg:width="185" dlg:height="16" dlg:value="Assign Script to Key Dialog" dlg:multiline="true"/>
+ <dlg:text dlg:style-id="1" dlg:id="Label11" dlg:tab-index="12" dlg:left="14" dlg:top="285" dlg:width="185" dlg:height="12" dlg:value="Assign Script to Event Dialog" dlg:multiline="true"/>
+ <dlg:text dlg:id="Label12" dlg:tab-index="13" dlg:left="14" dlg:top="211" dlg:width="185" dlg:height="36" dlg:value="To assign, select the Top-Level menu and Sub-Menu under which you wish to add the new script menu. Enter the script menu name and click New. To delete a script menu, select the script menu and click Delete." dlg:multiline="true"/>
+ <dlg:text dlg:id="Label13" dlg:tab-index="14" dlg:left="14" dlg:top="259" dlg:width="185" dlg:height="26" dlg:value="To assign, select the Key group and the Shortcut key, then click Assign. To delete, select the Shortcut to which the script is assigned and click Delete." dlg:multiline="true"/>
+ <dlg:text dlg:id="Label14" dlg:tab-index="15" dlg:left="14" dlg:top="297" dlg:width="185" dlg:height="42" dlg:value="To assign scripts to an event, select the Event then click Assign. Scripts can be assigned to application wide events or to the current document by selecting the appropriate application or document radio button. To delete, select the Event to which the script is assigned and click Delete." dlg:multiline="true"/>
+ <dlg:text dlg:id="Label16" dlg:tab-index="16" dlg:left="14" dlg:top="177" dlg:width="185" dlg:height="22" dlg:value="To assign a script, first you must select the script from the Script combo box, then follow the appropriate instructions below. " dlg:multiline="true"/>
+ <dlg:text dlg:id="Label15" dlg:tab-index="17" dlg:left="14" dlg:top="110" dlg:width="185" dlg:height="34" dlg:value="When the location is set to &quot;filesystem&quot;, and the language is set to something other than &quot;Java&quot;, the &quot;Browse&quot; button is enabled. This allows open a filechooser and populate the Script combo box with scripts located on the filesystem." dlg:multiline="true"/>
+ </dlg:bulletinboard>
+</dlg:window> \ No newline at end of file
diff --git a/scripting/workben/bindings/Highlight.xdl b/scripting/workben/bindings/Highlight.xdl
new file mode 100644
index 000000000000..2d65de42283e
--- /dev/null
+++ b/scripting/workben/bindings/Highlight.xdl
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
+<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="Highlight" dlg:left="68" dlg:top="23" dlg:width="135" dlg:height="48" dlg:closeable="true" dlg:moveable="true">
+ <dlg:bulletinboard>
+ <dlg:text dlg:id="Label1" dlg:tab-index="2" dlg:left="3" dlg:top="8" dlg:width="33" dlg:height="9" dlg:value="Find What:"/>
+ <dlg:textfield dlg:id="HighlightTextField" dlg:tab-index="3" dlg:left="39" dlg:top="6" dlg:width="93" dlg:height="12"/>
+ <dlg:button dlg:id="HighlightButton" dlg:tab-index="0" dlg:left="20" dlg:top="24" dlg:width="46" dlg:height="18" dlg:value="Highlight">
+ <script:event script:event-name="on-performaction" script:macro-name="vnd.sun.star.script:Highlight.ButtonPressHandler.bsh?language=BeanShell&amp;location=share" script:language="Script"/>
+ </dlg:button>
+ <dlg:button dlg:id="ExitButton" dlg:tab-index="1" dlg:left="72" dlg:top="24" dlg:width="46" dlg:height="18" dlg:value="Exit">
+ <script:event script:event-name="on-performaction" script:macro-name="vnd.sun.star.script:Highlight.ButtonPressHandler.bsh?language=BeanShell&amp;location=share" script:language="Script"/>
+ </dlg:button>
+ </dlg:bulletinboard>
+</dlg:window>
diff --git a/scripting/workben/bindings/KeyBinding.xdl b/scripting/workben/bindings/KeyBinding.xdl
new file mode 100644
index 000000000000..107adf2f1dd4
--- /dev/null
+++ b/scripting/workben/bindings/KeyBinding.xdl
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
+<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="MenuBindingDialog" dlg:left="64" dlg:top="89" dlg:width="179" dlg:height="217" dlg:closeable="true" dlg:moveable="true" dlg:title="Assign Script To Key">
+ <dlg:styles>
+ <dlg:style dlg:style-id="0" dlg:font-height="7"/>
+ </dlg:styles>
+ <dlg:bulletinboard>
+ <dlg:combobox dlg:id="LocationCombo" dlg:tab-index="0" dlg:left="64" dlg:top="18" dlg:width="108" dlg:height="12" dlg:spin="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.fireLangLocComboListernerOnRet" script:language="StarBasic"/>
+ </dlg:combobox>
+ <dlg:combobox dlg:id="LanguageCombo" dlg:tab-index="1" dlg:left="64" dlg:top="34" dlg:width="108" dlg:height="12" dlg:spin="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.fireLangLocComboListernerOnRet" script:language="StarBasic"/>
+ </dlg:combobox>
+ <dlg:checkbox dlg:id="detail" dlg:tab-index="2" dlg:left="17" dlg:top="57" dlg:width="44" dlg:height="10" dlg:value="Detailed view" dlg:checked="false">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ </dlg:checkbox>
+ <dlg:menulist dlg:id="ScriptList" dlg:tab-index="3" dlg:left="63" dlg:top="49" dlg:width="108" dlg:height="44"/>
+ <dlg:button dlg:id="Browse" dlg:tab-index="4" dlg:disabled="true" dlg:left="17" dlg:top="71" dlg:width="36" dlg:height="14" dlg:value="Browse...">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.BrowseButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:combobox dlg:id="KeyCombo" dlg:tab-index="5" dlg:left="63" dlg:top="110" dlg:width="108" dlg:height="12" dlg:spin="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.KeyComboListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.fireKeyComboListernerOnRet" script:language="StarBasic"/>
+ </dlg:combobox>
+ <dlg:menulist dlg:id="KeyList" dlg:tab-index="6" dlg:left="63" dlg:top="125" dlg:width="108" dlg:height="59">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.KeyListListener" script:language="StarBasic"/>
+ </dlg:menulist>
+ <dlg:button dlg:id="Delete" dlg:tab-index="7" dlg:left="17" dlg:top="141" dlg:width="38" dlg:height="13" dlg:value="Delete">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.KeyDeleteButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="NewButton" dlg:tab-index="8" dlg:left="17" dlg:top="171" dlg:width="38" dlg:height="13" dlg:value="Assign">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.KeyNewButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="OK" dlg:tab-index="9" dlg:left="57" dlg:top="200" dlg:width="36" dlg:height="13" dlg:value="OK">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuOKButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="Cancel" dlg:tab-index="10" dlg:left="96" dlg:top="200" dlg:width="36" dlg:height="13" dlg:value="Cancel">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuCancelButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="Help" dlg:tab-index="11" dlg:left="136" dlg:top="200" dlg:width="36" dlg:height="13" dlg:value="Help">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuHelpButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:fixedline dlg:id="FixedLine2" dlg:tab-index="12" dlg:left="9" dlg:top="190" dlg:width="167" dlg:height="6"/>
+ <dlg:fixedline dlg:id="FixedLine4" dlg:tab-index="13" dlg:left="94" dlg:top="99" dlg:width="81" dlg:height="5"/>
+ <dlg:text dlg:id="Label4" dlg:tab-index="14" dlg:left="5" dlg:top="97" dlg:width="90" dlg:height="8" dlg:value="Choose shortcut key to assign to"/>
+ <dlg:text dlg:id="Label5" dlg:tab-index="15" dlg:left="12" dlg:top="112" dlg:width="40" dlg:height="10" dlg:value="Key Group"/>
+ <dlg:text dlg:id="Label6" dlg:tab-index="16" dlg:left="12" dlg:top="127" dlg:width="40" dlg:height="10" dlg:value="Shortcut Key"/>
+ <dlg:fixedline dlg:id="FixedLine1" dlg:tab-index="17" dlg:left="43" dlg:top="7" dlg:width="132" dlg:height="6"/>
+ <dlg:text dlg:id="Label1" dlg:tab-index="18" dlg:left="5" dlg:top="7" dlg:width="36" dlg:height="8" dlg:value="Select script"/>
+ <dlg:text dlg:id="Label7" dlg:tab-index="19" dlg:left="12" dlg:top="17" dlg:width="28" dlg:height="7" dlg:value="Location"/>
+ <dlg:text dlg:id="Label8" dlg:tab-index="20" dlg:left="12" dlg:top="32" dlg:width="35" dlg:height="9" dlg:value="Language"/>
+ <dlg:text dlg:id="Label9" dlg:tab-index="21" dlg:left="12" dlg:top="49" dlg:width="23" dlg:height="8" dlg:value="Script"/>
+ <dlg:text dlg:id="Label10" dlg:tab-index="22" dlg:left="103" dlg:top="-9" dlg:width="3" dlg:height="0" dlg:value="Label10"/>
+ <dlg:text dlg:style-id="0" dlg:id="AddOn" dlg:tab-index="23" dlg:disabled="true" dlg:left="17" dlg:top="154" dlg:width="38" dlg:height="10" dlg:value="[Add-on&apos;s only]"/>
+ <dlg:text dlg:id="fsonly" dlg:tab-index="24" dlg:disabled="true" dlg:left="13" dlg:top="86" dlg:width="45" dlg:height="8" dlg:value="[Filesystem only]"/>
+ </dlg:bulletinboard>
+</dlg:window> \ No newline at end of file
diff --git a/scripting/workben/bindings/MacroEditor.xdl b/scripting/workben/bindings/MacroEditor.xdl
new file mode 100644
index 000000000000..b724bbb64add
--- /dev/null
+++ b/scripting/workben/bindings/MacroEditor.xdl
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
+<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="MacroEditor" dlg:left="105" dlg:top="117" dlg:width="240" dlg:height="320" dlg:closeable="true" dlg:moveable="true" dlg:title="Python Macro Editor">
+ <dlg:bulletinboard>
+ <dlg:button dlg:id="RunButton" dlg:tab-index="0" dlg:left="57" dlg:top="300" dlg:width="40" dlg:height="14" dlg:value="Run"/>
+ <dlg:button dlg:id="SaveButton" dlg:tab-index="1" dlg:left="100" dlg:top="300" dlg:width="40" dlg:height="14" dlg:value="Save"/>
+ <dlg:button dlg:id="CloseButton" dlg:tab-index="2" dlg:left="143" dlg:top="300" dlg:width="40" dlg:height="14" dlg:value="Close" dlg:button-type="cancel"/>
+ <dlg:textfield dlg:id="EditorTextField" dlg:tab-index="3" dlg:left="6" dlg:top="6" dlg:width="228" dlg:height="288" dlg:hscroll="true" dlg:vscroll="true" dlg:multiline="true"/>
+ </dlg:bulletinboard>
+</dlg:window>
diff --git a/scripting/workben/bindings/MenuBinding.xdl b/scripting/workben/bindings/MenuBinding.xdl
new file mode 100644
index 000000000000..b4e0b0e753de
--- /dev/null
+++ b/scripting/workben/bindings/MenuBinding.xdl
@@ -0,0 +1,65 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE dlg:window PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "dialog.dtd">
+<dlg:window xmlns:dlg="http://openoffice.org/2000/dialog" xmlns:script="http://openoffice.org/2000/script" dlg:id="MenuBindingDialog" dlg:left="64" dlg:top="89" dlg:width="179" dlg:height="236" dlg:closeable="true" dlg:moveable="true" dlg:title="Assign Script To Menu">
+ <dlg:styles>
+ <dlg:style dlg:style-id="0" dlg:font-height="7"/>
+ </dlg:styles>
+ <dlg:bulletinboard>
+ <dlg:combobox dlg:id="LocationCombo" dlg:tab-index="0" dlg:left="63" dlg:top="17" dlg:width="108" dlg:height="13" dlg:spin="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.fireLangLocComboListernerOnRet" script:language="StarBasic"/>
+ </dlg:combobox>
+ <dlg:combobox dlg:id="LanguageCombo" dlg:tab-index="1" dlg:left="63" dlg:top="32" dlg:width="108" dlg:height="13" dlg:spin="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.fireLangLocComboListernerOnRet" script:language="StarBasic"/>
+ </dlg:combobox>
+ <dlg:checkbox dlg:id="detail" dlg:tab-index="2" dlg:left="17" dlg:top="57" dlg:width="44" dlg:height="10" dlg:value="Detailed view" dlg:checked="false">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.LangLocComboListener" script:language="StarBasic"/>
+ </dlg:checkbox>
+ <dlg:menulist dlg:id="ScriptList" dlg:tab-index="3" dlg:left="63" dlg:top="49" dlg:width="108" dlg:height="44"/>
+ <dlg:button dlg:id="Browse" dlg:tab-index="4" dlg:disabled="true" dlg:left="17" dlg:top="71" dlg:width="36" dlg:height="14" dlg:value="Browse...">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.BrowseButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:combobox dlg:id="MenuCombo" dlg:tab-index="5" dlg:left="63" dlg:top="109" dlg:width="108" dlg:height="13" dlg:spin="true">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuComboListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.fireMenuComboListernerOnRet" script:language="StarBasic"/>
+ </dlg:combobox>
+ <dlg:menulist dlg:id="SubMenuList" dlg:tab-index="6" dlg:left="63" dlg:top="125" dlg:width="108" dlg:height="44">
+ <script:event script:event-name="on-itemstatechange" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.SubMenuListListener" script:language="StarBasic"/>
+ </dlg:menulist>
+ <dlg:button dlg:id="Delete" dlg:tab-index="7" dlg:left="17" dlg:top="142" dlg:width="36" dlg:height="14" dlg:value="Delete">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuDeleteButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="NewButton" dlg:tab-index="8" dlg:left="17" dlg:top="186" dlg:width="36" dlg:height="14" dlg:value="New">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuNewButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:textfield dlg:id="MenuLabelBox" dlg:tab-index="9" dlg:left="63" dlg:top="187" dlg:width="108" dlg:height="13">
+ <script:event script:event-name="on-blur" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuLabelBoxListener" script:language="StarBasic"/>
+ <script:event script:event-name="on-keydown" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuLabelBoxListener" script:language="StarBasic"/>
+ </dlg:textfield>
+ <dlg:button dlg:id="OK" dlg:tab-index="10" dlg:left="57" dlg:top="216" dlg:width="36" dlg:height="14" dlg:value="OK">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuOKButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="Cancel" dlg:tab-index="11" dlg:left="96" dlg:top="216" dlg:width="36" dlg:height="14" dlg:value="Cancel">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuCancelButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:button dlg:id="Help" dlg:tab-index="12" dlg:left="136" dlg:top="216" dlg:width="36" dlg:height="14" dlg:value="Help">
+ <script:event script:event-name="on-performaction" script:location="application" script:macro-name="ScriptBindingLibrary.ScriptBinding.MenuHelpButton" script:language="StarBasic"/>
+ </dlg:button>
+ <dlg:fixedline dlg:id="FixedLine2" dlg:tab-index="13" dlg:left="8" dlg:top="206" dlg:width="167" dlg:height="7"/>
+ <dlg:fixedline dlg:id="FixedLine3" dlg:tab-index="14" dlg:left="73" dlg:top="174" dlg:width="102" dlg:height="6"/>
+ <dlg:text dlg:id="Label2" dlg:tab-index="15" dlg:left="5" dlg:top="172" dlg:width="73" dlg:height="9" dlg:value="Assign script to new menu"/>
+ <dlg:fixedline dlg:id="FixedLine4" dlg:tab-index="16" dlg:left="75" dlg:top="99" dlg:width="100" dlg:height="6"/>
+ <dlg:text dlg:id="Label4" dlg:tab-index="17" dlg:left="5" dlg:top="97" dlg:width="75" dlg:height="8" dlg:value="Choose menu to insert after"/>
+ <dlg:text dlg:id="Label5" dlg:tab-index="18" dlg:left="12" dlg:top="111" dlg:width="40" dlg:height="11" dlg:value="Toplevel Menu"/>
+ <dlg:text dlg:id="Label6" dlg:tab-index="19" dlg:left="12" dlg:top="127" dlg:width="40" dlg:height="11" dlg:value="Sub Menu"/>
+ <dlg:fixedline dlg:id="FixedLine1" dlg:tab-index="20" dlg:left="42" dlg:top="6" dlg:width="132" dlg:height="7"/>
+ <dlg:text dlg:id="Label1" dlg:tab-index="21" dlg:left="5" dlg:top="6" dlg:width="36" dlg:height="9" dlg:value="Select script"/>
+ <dlg:text dlg:id="Label7" dlg:tab-index="22" dlg:left="12" dlg:top="17" dlg:width="28" dlg:height="7" dlg:value="Location"/>
+ <dlg:text dlg:id="Label8" dlg:tab-index="23" dlg:left="12" dlg:top="32" dlg:width="35" dlg:height="9" dlg:value="Language"/>
+ <dlg:text dlg:id="Label9" dlg:tab-index="24" dlg:left="12" dlg:top="49" dlg:width="23" dlg:height="8" dlg:value="Script"/>
+ <dlg:text dlg:style-id="0" dlg:id="AddOn" dlg:tab-index="25" dlg:disabled="true" dlg:left="17" dlg:top="156" dlg:width="38" dlg:height="11" dlg:value="[Add-on&apos;s only]"/>
+ <dlg:text dlg:id="Label10" dlg:tab-index="27" dlg:left="9" dlg:top="89" dlg:width="0" dlg:height="0" dlg:value="Label10"/>
+ <dlg:text dlg:id="fsonly" dlg:tab-index="26" dlg:disabled="true" dlg:left="13" dlg:top="86" dlg:width="45" dlg:height="8" dlg:value="[Filesystem only]"/>
+ </dlg:bulletinboard>
+</dlg:window> \ No newline at end of file
diff --git a/scripting/workben/bindings/ScriptBinding.xba b/scripting/workben/bindings/ScriptBinding.xba
new file mode 100644
index 000000000000..7f689d34f797
--- /dev/null
+++ b/scripting/workben/bindings/ScriptBinding.xba
@@ -0,0 +1,2093 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
+<script:module xmlns:script="http://openoffice.org/2000/script" script:name="ScriptBinding" script:language="StarBasic">REM ***** BASIC *****
+
+REM ----- Global Variables -----
+
+&apos;bindingDialog can refer to either KeyBinding or MenuBinding dialog
+private languages() as String
+private extensions() as Object
+private locations() as String
+private filesysScripts() as String
+private filesysCount as integer
+private bindingDialog as object
+private helpDialog as object
+&apos;Couldn&apos;t get redim to work, so scriptDisplayList is and array of arrays
+&apos;where the one and only array in scriptDisplayList is an array
+&apos;of com.sun.star.beans.PropertyValue, where Name = [logicalName][FunctionName]
+&apos;and value is ScriptStorage object
+private scriptDisplayList(0)
+private testArray() as String
+&apos;Array to store lines from the xml file
+private xmlFile() as string
+&apos;Name of the xml file [writer/calc][menubar/keybindings].xml
+private xmlFileName as string
+&apos;Number of lines in the xml file
+private numberOfLines as integer
+
+&apos;Parallel arrays to store all top-level menu names and line positions
+private menuItems() as string
+private menuItemLinePosition() as integer
+&apos;Counter for the number of top-level menus
+private menuCount as integer
+
+&apos;Parallel arrays to store all sub-menu names and line positions for a particular top-level menu
+private subMenuItems() as string
+private subMenuItemLinePosition() as integer
+&apos;Counter for the number of sub-menus
+private subMenuCount as integer
+
+&apos;Parallel arrays to store all script names and line positions
+private scriptNames() as string
+private scriptLinePosition() as integer
+&apos;Counter for the number of scripts
+private scriptCount as integer
+
+&apos;Array to store all combinations of key bindings
+private allKeyBindings() as string
+
+&apos;Array of Arrays
+&apos;KeyBindArrayOfArrays(0) contains array of &quot;SHIFT + CONTROL + F Keys&quot; data
+&apos;Similarly
+&apos;KeyBindArrayOfArrays(1) contains SHIFT + CONTROL + digits
+&apos;KeyBindArrayOfArrays(2) contains SHIFT + CONTROL + letters
+&apos;KeyBindArrayOfArrays(3) contains CONTROL + F keys
+&apos;KeyBindArrayOfArrays(4) contains CONTROL + digits
+&apos;KeyBindArrayOfArrays(5) contains CONTROL + letters
+&apos;KeyBindArrayOfArrays(6) contains SHIFT + F keys
+private KeyBindArrayOfArrays(6)
+
+&apos;Each PropertyValue represents a key, Name member contains the script (if a binding exists)
+&apos; the Value contains and integer
+&apos; 0 means no script bound
+&apos; 1 script is bound to an office function
+&apos; &gt;1 line number of entry in xmlfile array
+private keyAllocationMap(6,25) as new com.sun.star.beans.PropertyValue
+&apos;array to store key group descriptions
+private AllKeyGroupsArray(6) as String
+
+
+&apos;Array of props to store all event bindings for the Applications
+private allEventTypesApp( 14 ) as new com.sun.star.beans.PropertyValue
+&apos;Array of props to store all event bindings for the Document
+private allEventTypesDoc( 14 ) as new com.sun.star.beans.PropertyValue
+&apos;Array of props to store all event types (Name) and textual description (Value)
+private allEventTypes( 14 ) as new com.sun.star.beans.PropertyValue
+
+
+private dialogName as String
+REM ------ Storage Refresh Function ------
+
+
+sub RefreshUserScripts()
+&apos; TDB - change Menu bindings to allow user to refresh all, user, share or document script
+ RefreshAppScripts( &quot;USER&quot; )
+end sub
+
+sub RefreshAllScripts()
+ RefreshAppScripts( &quot;USER&quot; )
+ RefreshAppScripts( &quot;SHARE&quot; )
+ RefreshDocumentScripts
+end sub
+
+sub RefreshAppScripts( appName as String )
+ On Error Goto ErrorHandler
+ smgr = getProcessServiceManager()
+ context = smgr.getPropertyValue( &quot;DefaultContext&quot; )
+ scriptstoragemgr = context.getValueByName( &quot;/singletons/drafts.com.sun.star.script.framework.storage.theScriptStorageManager&quot; )
+
+ scriptstoragemgr.refreshScriptStorage( appName )
+
+ Exit sub
+
+ ErrorHandler:
+ reset
+ MsgBox (&quot;Error: Unable to refresh Java (scripts)&quot; + chr$(10) + chr$(10)+ &quot;Detail: &quot; &amp; error$ + chr$(10) + chr$(10)+ &quot;Action: Please restart Office&quot;,0,&quot;Error&quot; )
+
+end sub
+
+sub RefreshDocumentScripts()
+ On Error Goto ErrorHandler
+ smgr = getProcessServiceManager()
+ context = smgr.getPropertyValue( &quot;DefaultContext&quot; )
+ scriptstoragemgr = context.getValueByName( &quot;/singletons/drafts.com.sun.star.script.framework.storage.theScriptStorageManager&quot; )
+
+ oDocURL = ThisComponent.GetCurrentController.getModel.getURL
+
+ On Error Goto ErrorHandlerDoc
+ scriptstoragemgr.refreshScriptStorage( oDocURL )
+
+ Exit sub
+
+ ErrorHandlerDoc:
+ reset
+ &apos; Ignore document script errors as it will happen when refreshing an unsaved doc
+ Exit sub
+
+ ErrorHandler:
+ reset
+ MsgBox (&quot;Error: Unable to refresh Java (scripts)&quot; + chr$(10) + chr$(10)+ &quot;Detail: &quot; &amp; error$ + chr$(10) + chr$(10)+ &quot;Action: Please restart Office&quot;,0,&quot;Error&quot; )
+
+end sub
+
+
+REM ----- Launch Functions -----
+
+Sub createAndPopulateKeyArrays()
+ &apos;Create SHIFT + CONTROL + F keys array
+ &apos;Dim keyGroupProp as new com.sun.star.beans.PropertyValue
+
+ Dim SCFKey( 11 )
+ for FKey = 1 to 12
+ SCFKey( FKey - 1 ) = &quot;SHIFT + CONTROL + F&quot; + FKey
+ next FKey
+
+ KeyBindArrayOfArrays(0) = SCFKey()
+
+ &apos;Create SHIFT + CONTROL + digits
+ Dim SCDKey( 9 )
+ for Digit = 0 to 9
+ SCDKey( Digit ) = &quot;SHIFT + CONTROL + &quot; + Digit
+ next Digit
+ KeyBindArrayOfArrays(1) = SCDKey()
+
+ &apos;Create SHIFT + CONTROL + letters
+
+ Dim SCLKey( 25 )
+ for Alpha = 65 to 90
+ SCLKey( Alpha - 65 ) = &quot;SHIFT + CONTROL + &quot; + chr$( Alpha )
+ next Alpha
+ KeyBindArrayOfArrays(2) = SCLKey()
+
+ &apos;Create CONTROL + F keys
+ Dim CFKey( 11 )
+ for FKey = 1 to 12
+ CFKey( Fkey - 1 ) = &quot;CONTROL + F&quot; + FKey
+ next FKey
+ KeyBindArrayOfArrays(3) = CFKey()
+
+ &apos;Create CONTROL + digits
+ Dim CDKey( 9 )
+ for Digit = 0 to 9
+ CDKey( Digit ) = &quot;CONTROL + &quot; + Digit
+ next Digit
+ KeyBindArrayOfArrays(4) = CDKey()
+
+ &apos;Create CONTROL + letters
+ Dim CLKey( 25 )
+ for Alpha = 65 to 90
+ CLKey( Alpha - 65 ) = &quot;CONTROL + &quot; + chr$( Alpha )
+ next Alpha
+ KeyBindArrayOfArrays(5) = CLKey()
+
+ &apos;Create SHIFT + F Keys
+ Dim SFKey( 11 )
+ for FKey = 1 to 12
+ SFKey( Fkey - 1 ) = &quot;SHIFT + F&quot; + FKey
+ next FKey
+ KeyBindArrayOfArrays(6) = SFKey()
+
+End Sub
+
+Sub updateMapWithDisabledKeys()
+ &apos;disable CONTROL + F1 &amp;
+ keyAllocationMap( 3, 0 ).Value = 1
+ keyAllocationMap( 3, 0 ).Name = &quot;&quot;
+ &apos;disable CONTROL + F4 &amp;
+ keyAllocationMap( 3, 3 ).Value = 1
+ keyAllocationMap( 3, 3 ).Name = &quot;&quot;
+ &apos;disable CONTROL + F6
+ keyAllocationMap( 3, 5 ).Value = 1
+ keyAllocationMap( 3, 5 ).Name = &quot;&quot;
+
+
+ &apos;disable SHIFT + F1 &amp;
+ keyAllocationMap( 6, 0 ).Value = 1
+ keyAllocationMap( 6, 0 ).Name = &quot;&quot;
+ &apos;disable SHIFT + F2 &amp;
+ keyAllocationMap( 6, 1 ).Value = 1
+ keyAllocationMap( 6, 1 ).Name = &quot;&quot;
+ &apos;disable SHIFT + F6 &amp;
+ keyAllocationMap( 6, 5 ).Value = 1
+ keyAllocationMap( 6, 5 ).Name = &quot;&quot;
+
+End Sub
+
+Sub initialiseFileExtensions()
+ ReDim extensions(ubound(languages())+1) as Object
+ oConfigProvider = CreateUnoService( &quot;com.sun.star.configuration.ConfigurationProvider&quot; )
+ Dim configArgs(1) as new com.sun.star.beans.PropertyValue
+ configargs(0).Name = &quot;nodepath&quot;
+ configArgs(0).Value = &quot;org.openoffice.Office.Scripting/ScriptRuntimes&quot;
+ configargs(1).Name = &quot;lazywrite&quot;
+ configArgs(1).Value = false
+ oConfigAccess = oConfigProvider.createInstanceWithArguments(&quot;com.sun.star.configuration.ConfigurationAccess&quot;, configArgs())
+ for index = 0 to ubound(languages())
+ if(languages(index) &lt;&gt; &quot;Java&quot;) then
+ xPropSet = oConfigAccess.getByName(languages(index))
+ extns() = xPropSet.getPropertyValue(&quot;SupportedFileExtensions&quot;)
+ extensions(index) = extns()
+ endif
+ next index
+end sub
+
+Sub ExecuteEditDebug()
+
+ locations = Array ( &quot;User&quot;, &quot;Share&quot;, &quot;Document&quot;, &quot;Filesystem&quot; )
+ languages = Array ( &quot;BeanShell&quot;, &quot;JavaScript&quot; )
+ dialogName = &quot;EditDebug&quot;
+ initialiseFileExtensions()
+ bindingDialog = LoadDialog( &quot;ScriptBindingLibrary&quot;, &quot;EditDebug&quot; )
+
+ PopulateLanguageCombo()
+ PopulateLocationCombo()
+ PopulateScriptList( languages(0), locations(0) )
+
+ bindingDialog.execute()
+End Sub
+
+Sub ExecuteKeyBinding()
+ dialogName = &quot;Key&quot;
+ createAndPopulateKeyArrays()
+ updateMapWithDisabledKeys()
+ xmlFileName = GetDocumentType( &quot;Key&quot; )
+
+ if not (ReadXMLToArray( &quot;Key&quot; )) then
+ Exit Sub
+ endif
+
+ bindingDialog = LoadDialog( &quot;ScriptBindingLibrary&quot;, &quot;KeyBinding&quot; )
+ PopulateKeyBindingList(0)
+ initialiseNavigationComboArrays()
+ PopulateLanguageCombo()
+ PopulateLocationCombo()
+ PopulateScriptList( languages(0), locations(0) )
+ PopulateTopLevelKeyBindingList()
+ bindingDialog.execute()
+end Sub
+
+
+Sub initialiseNavigationComboArrays()
+ locations = Array ( &quot;User&quot;, &quot;Share&quot;, &quot;Document&quot;, &quot;Filesystem&quot; )
+ ReDim languages(0) as String
+ ReDim extensions(0) as Object
+ languages(0) = &quot;Java&quot;
+ REM extensions(0) = &quot;&quot;
+
+ &apos; Setup languages array for all supported languages
+ oServiceManager = GetProcessServiceManager()
+ svrArray = oServiceManager.getAvailableServiceNames
+
+ langCount = 1
+ for index = 0 to ubound(svrArray)
+ iPos = inStr(svrArray(index), &quot;ScriptProviderFor&quot;)
+
+ if (iPos &gt; 0) then
+ lang = Mid(svrArray(index), iPos + Len(&quot;ScriptProviderFor&quot;)
+
+ if not (lang = &quot;Java&quot;) then
+ &apos;Add to language vector
+ ReDim Preserve languages(langCount) as String
+ languages(langCount) = lang
+ langCount = langCount + 1
+ endif
+ endif
+ next index
+ initialiseFileExtensions()
+End Sub
+
+
+Sub ExecuteEventBinding
+ dialogName = &quot;Event&quot;
+ createAllEventTypes()
+ createAllEventBindings()
+
+ &apos;Populate application event bindings array (from config xml file)
+ if not (ReadXMLToArray( &quot;Event&quot; )) then
+ Exit Sub
+ endif
+ &apos;Populate document event bindings array (using Office API calls)
+ ReadEventsFromDoc()
+
+ bindingDialog = LoadDialog( &quot;ScriptBindingLibrary&quot;, &quot;EventsBinding&quot; )
+ initialiseNavigationComboArrays()
+ PopulateLanguageCombo()
+ PopulateLocationCombo()
+ PopulateScriptList( languages(0), locations(0) )
+ populateEventList( 0 )
+ EventListListener()
+ bindingDialog.execute()
+End Sub
+
+Sub ExecuteMenuBinding()
+ dialogName = &quot;Menu&quot;
+ xmlFileName = GetDocumentType( &quot;Menu&quot; )
+ if not (ReadXMLToArray( &quot;Menu&quot; )) then
+ Exit Sub
+ endif
+
+ bindingDialog = LoadDialog( &quot;ScriptBindingLibrary&quot;, &quot;MenuBinding&quot; )
+ initialiseNavigationComboArrays()
+ PopulateLanguageCombo()
+ PopulateLocationCombo()
+ PopulateScriptList( languages(0), locations(0) )
+ PopulateMenuCombo()
+ PopulateSubMenuList( 1 )
+
+ subMenuList = bindingDialog.getControl(&quot;SubMenuList&quot;)
+
+ subMenuList.selectItemPos( 0, true )
+
+ bindingDialog.execute()
+end Sub
+
+
+REM ----- Initialising functions -----
+
+
+function LoadDialog( libName as string, dialogName as string ) as object
+ dim library as object
+ dim libDialog as object
+ dim runtimeDialog as object
+ libContainer = DialogLibraries
+ libContainer.LoadLibrary( libName )
+ library = libContainer.getByName( libname )
+ libDialog = library.getByName( dialogName )
+ runtimeDialog = CreateUnoDialog( libDialog )
+ LoadDialog() = runtimeDialog
+
+end function
+
+
+function GetDocumentType( bindingType as string ) as string
+ document = StarDesktop.ActiveFrame.Controller.Model
+ Dim errornumber As Integer
+ errornumber = 111
+ Error errornumber
+ if document.SupportsService(&quot;com.sun.star.sheet.SpreadsheetDocument&quot;) then
+ if bindingType = &quot;Key&quot; then
+ GetDocumentType() = &quot;calckeybinding.xml&quot;
+ else
+ if bindingType = &quot;Menu&quot; then
+ GetDocumentType() = &quot;calcmenubar.xml&quot;
+ end if
+ end if
+ elseif document.SupportsService(&quot;com.sun.star.text.TextDocument&quot;) then
+ if bindingType = &quot;Key&quot; then
+ GetDocumentType() = &quot;writerkeybinding.xml&quot;
+ else
+ if bindingType = &quot;Menu&quot; then
+ GetDocumentType() = &quot;writermenubar.xml&quot;
+ end if
+ end if
+ elseif document.SupportsService(&quot;com.sun.star.presentation.PresentationDocument&quot;) then
+ if bindingType = &quot;Key&quot; then
+ GetDocumentType() = &quot;impresskeybinding.xml&quot;
+ else
+ if bindingType = &quot;Menu&quot; then
+ GetDocumentType() = &quot;impressmenubar.xml&quot;
+ end if
+ end if
+ elseif document.SupportsService(&quot;com.sun.star.presentation.PresentationDocument&quot;) then
+ if bindingType = &quot;Key&quot; then
+ GetDocumentType() = &quot;impresskeybinding.xml&quot;
+ else
+ if bindingType = &quot;Menu&quot; then
+ GetDocumentType() = &quot;impressmenubar.xml&quot;
+ end if
+ end if
+ elseif document.SupportsService(&quot;com.sun.star.drawing.DrawingDocument&quot;) then
+ if bindingType = &quot;Key&quot; then
+ GetDocumentType() = &quot;drawkeybinding.xml&quot;
+ else
+ if bindingType = &quot;Menu&quot; then
+ GetDocumentType() = &quot;drawmenubar.xml&quot;
+ end if
+ end if
+ else
+ MsgBox (&quot;Error: Couldn&apos;t determine configuration file type&quot; + chr$(10) + chr$(10) + &quot;Action: Please reinstall Scripting Framework&quot;,0,&quot;Error&quot; )
+ end if
+end function
+
+function lastIndexOf( targetStr as String, substr as String ) as Integer
+ copyStr = targetStr
+ while instr(copyStr, substr) &gt; 0
+ pos = instr(copyStr, substr)
+ tpos = tpos + pos
+ copyStr = mid(copyStr, pos+1, len(copyStr)-pos )
+ wend
+ lastIndexOf() = tpos
+end function
+
+function getScriptURI( selectedScript as String ) as String
+ combo = bindingDialog.getControl( &quot;LocationCombo&quot; )
+ location = combo.text
+ if ( location = &quot;User&quot; ) then
+ location = &quot;user&quot;
+ elseif ( location = &quot;Share&quot; ) then
+ location = &quot;share&quot;
+ elseif ( location = &quot;Filesystem&quot; ) then
+ location = &quot;filesystem&quot;
+ else
+ location = &quot;document&quot;
+ end if
+
+
+
+ if ( location = &quot;filesystem&quot; ) then
+ REM need to build URI here - dcf
+ combo = bindingDialog.getControl( &quot;LanguageCombo&quot; )
+ language = combo.text
+ url = selectedscript
+ pos = lastIndexOf( url, &quot;/&quot; )
+ locationPath = mid( url, 1, pos)
+ url = mid( url, pos+1, len( url ) - pos )
+ functionName = url
+ pos = lastIndexOf( url, &quot;.&quot; )
+ logicalName = mid( url, 1, pos - 1 )
+ getScriptURI() = &quot;script://&quot; + logicalName + &quot;?language=&quot; _
+ + language + &quot;&amp;amp;function=&quot; + functionName _
+ + &quot;&amp;amp;location=filesystem:&quot; + locationPath
+ else
+ Dim scriptInfo as Object
+ scripts() = scriptDisplayList(0)
+ for n = LBOUND( scripts() ) to UBOUND( scripts() )
+
+ if ( scripts( n ).Name = selectedScript ) then
+ scriptInfo = scripts( n ).Value
+ exit for
+ end if
+ next n
+ getScriptURI() = &quot;script://&quot; + scriptInfo.getLogicalName + &quot;?language=&quot; _
+ + scriptInfo.getLanguage() + &quot;&amp;amp;function=&quot; + _
+ scriptInfo.getFunctionName() + &quot;&amp;amp;location=&quot; + location
+ end if
+
+end function
+
+function GetOfficePath() as string
+ REM Error check and prompt user to manually input Office Path
+ settings = CreateUnoService( &quot;com.sun.star.frame.Settings&quot; )
+ path = settings.getByName( &quot;PathSettings&quot; )
+ unformattedOfficePath = path.getPropertyValue( &quot;UserPath&quot; )
+
+ dim officePath as string
+ const removeFromEnd = &quot;/user&quot;
+ const removeFromEndWindows = &quot;\user&quot;
+
+ REM If Solaris or Linux
+ if not ( instr( unformattedOfficePath, removeFromEnd ) = 0 ) then
+ endPosition = instr( unformattedOfficePath, removeFromEnd )
+ officePath = mid( unformattedOfficePath, 1, endPosition )
+ REM If Windows
+ else if not ( instr( unformattedOfficePath, removeFromEndWindows ) = 0 ) then
+ endPosition = instr( unformattedOfficePath, removeFromEndWindows )
+ officePath = mid( unformattedOfficePath, 1, endPosition )
+ while instr( officePath, &quot;\&quot; ) &gt; 0
+ backSlash = instr( officePath, &quot;\&quot; )
+ startPath = mid( officePath, 1, backSlash - 1 )
+ endPath = mid( officePath, backslash + 1, len( officePath ) - backSlash )
+ officePath = startPath + &quot;/&quot; + endPath
+ wend
+ else
+ MsgBox (&quot;Error: Office path not found&quot; + chr$(10) + chr$(10) + &quot;Action: Please reinstall Scripting Framework&quot;,0,&quot;Error&quot; )
+ REM Prompt user
+ end if
+ end if
+
+ GetOfficePath() = officePath
+end function
+
+
+
+REM ----- File I/O functions -----
+
+
+function ReadXMLToArray( bindingType as string ) as boolean
+ On Error Goto ErrorHandler
+ if ( bindingType = &quot;Event&quot; ) then
+ xmlfilename = &quot;eventbindings.xml&quot;
+ endif
+
+ simplefileaccess = CreateUnoService( &quot;com.sun.star.ucb.SimpleFileAccess&quot; )
+ filestream = simplefileaccess.openFileRead( &quot;file://&quot; + GetOfficePath() + &quot;user/config/soffice.cfg/&quot; + xmlFileName )
+
+ textin = CreateUnoService( &quot;com.sun.star.io.TextInputStream&quot; )
+ textin.setInputStream( filestream )
+
+ redim xmlFile( 400 ) as String
+ redim menuItems( 30 ) as String
+ redim menuItemLinePosition( 30 ) as Integer
+ redim scriptNames( 120 ) as string
+ redim scriptLinePosition( 120) as integer
+
+ lineCount = 1
+ menuCount = 1
+ scriptCount = 1
+
+ do while not textin.isEOF()
+ xmlline = textin.readLine()
+ xmlFile( lineCount ) = xmlline
+
+ const menuItemWhiteSpace = 2
+ const menuXMLTag = &quot;&lt;menu:menu&quot;
+
+ if bindingType = &quot;Menu&quot; then
+ evaluateForMenu( xmlline, lineCount )
+ elseif bindingType = &quot;Key&quot; then
+ processKeyXMLLine( lineCount, xmlline )
+ elseif bindingType = &quot;Event&quot; then
+ evaluateForEvent( xmlline, lineCount )
+ else
+ MsgBox (&quot;Error: Couldn&apos;t determine file type&quot; + chr$(10) + chr$(10) + &quot;Action: Please reinstall Scripting Framework&quot;,0,&quot;Error&quot; )
+ end if
+ lineCount = lineCount + 1
+ loop
+
+ &apos;Set global variable numberOfLines (lineCount is one too many at end of the loop)
+ numberOfLines = lineCount - 1
+ &apos;Set global variable menuCount (it is one too many at end of the loop)
+ menuCount = menuCount - 1
+
+ filestream.closeInput()
+ ReadXMLToArray( ) = true
+ Exit function
+
+ ErrorHandler:
+ reset
+ MsgBox (&quot;Error: Unable to read Star Office configuration file - &quot; + xmlFileName + chr$(10) + chr$(10) + &quot;Action: Please reinstall Scripting Framework&quot;,0,&quot;Error&quot; )
+ ReadXMLToArray( ) = false
+end function
+
+
+
+sub evaluateForMenu( xmlline as string, lineCount as integer )
+ const menuItemWhiteSpace = 2
+ const menuXMLTag = &quot;&lt;menu:menu&quot;
+ &apos;If the xml line is a top-level menu
+ if instr( xmlline, menuXMLTag ) = menuItemWhiteSpace then
+ menuLabel = ExtractLabelFromXMLLine( xmlline )
+ menuItems( menuCount ) = menuLabel
+ menuItemLinePosition( menuCount ) = lineCount
+ menuCount = menuCount + 1
+ end if
+end sub
+
+sub evaluateForEvent( xmlline as string, lineCount as integer )
+ dim eventName as String
+ &apos;if the xml line identifies a script or SB macro
+ dim scriptName as string
+ dim lineNumber as integer
+ if instr( xmlline, &quot;event:language=&quot; + chr$(34) + &quot;Script&quot; ) &gt; 0 then
+ eventName = ExtractEventNameFromXMLLine( xmlline )
+ scriptName = ExtractEventScriptFromXMLLine( xmlline )
+ lineNumber = lineCount
+ elseif instr( xmlline, &quot;event:language=&quot; + chr$(34) + &quot;StarBasic&quot; ) &gt; 0 then
+ eventName = ExtractEventNameFromXMLLine( xmlline )
+ scriptName = &quot;Allocated to Office function&quot;
+ lineNumber = 1
+ end if
+
+ &apos;Need to sequence to find the corresponding index for the event type
+ for n = 0 to ubound( allEventTypesApp() )
+ if ( eventName = allEventTypes( n ).Name ) then
+ allEventTypesApp( n ).Name = scriptName
+ allEventTypesApp( n ).Value = lineNumber
+ end if
+ next n
+end sub
+
+
+function isOKscriptProps( props() as Object, eventName as string ) as Boolean
+ On Error Goto ErrorHandler
+ props = ThisComponent.getEvents().getByName( eventName )
+ test = ubound( props() )
+ isOKscriptProps() = true
+ exit function
+
+ ErrorHandler:
+ isOKscriptProps() = false
+end function
+
+sub ReadEventsFromDoc()
+ On Error Goto ErrorHandler
+
+ eventSupplier = ThisComponent
+ for n = 0 to ubound( allEventTypes() )
+ Dim scriptProps() as Object
+ if (isOKscriptProps( scriptProps(), allEventTypes( n ).Name) ) then
+ if ( ubound( scriptProps ) &gt; 0 ) then
+ if ( scriptProps(0).Value = &quot;Script&quot; ) then
+ &apos;Script binding
+ allEventTypesDoc(n).Name = scriptProps(1).Value
+ allEventTypesDoc(n).value = 2
+ elseif( scriptProps(0).Value = &quot;StarBasic&quot; ) then
+ &apos;StarBasic macro
+ allEventTypesDoc(n).Name = &quot;Allocated to Office function&quot;
+ allEventTypesDoc(n).value = 1
+ end if
+ end if
+ end if
+ next n
+
+ exit sub
+
+ &apos; eventProps is undefined if there are no event bindings in the doc
+ ErrorHandler:
+ reset
+end sub
+
+
+sub WriteEventsToDoc()
+ On Error Goto ErrorHandler
+
+ eventSupplier = ThisComponent
+ for n = 0 to ubound( allEventTypes() )
+ scriptName = allEventTypesDoc( n ).Name
+ eventName = allEventTypes( n ).Name
+ if( allEventTypesDoc( n ).Value &gt; 1 ) then &apos;script
+ &apos;add to doc
+ AddEventToDocViaAPI( scriptName, eventName )
+ elseif( allEventTypesDoc( n ).Value = 0 ) then &apos;blank (this will &quot;remove&quot; already blank entries)
+ &apos;remove from doc
+ RemoveEventFromDocViaAPI( eventName )
+ endif
+ &apos;Otherwise it is a StarBasic binding - leave alone
+ next n
+ &apos;Mark document as modified ( should happen automatically as a result of calling the API )
+ ThisComponent.CurrentController.getModel().setModified( True )
+ exit sub
+
+ ErrorHandler:
+ reset
+ msgbox( &quot;Error calling UNO API for writing event bindings to the document&quot; )
+end sub
+
+
+sub RemoveEventFromDocViaAPI( event as string )
+ dim document as object
+ dim dispatcher as object
+ dim parser as object
+ dim url as new com.sun.star.util.URL
+
+ document = ThisComponent.CurrentController.Frame
+ parser = createUnoService(&quot;com.sun.star.util.URLTransformer&quot;)
+ dim args(0) as new com.sun.star.beans.PropertyValue
+ args(0).Name = &quot;&quot;
+ args(0).Value = event
+
+ url.Complete = &quot;script://_$ScriptFrmwrkHelper.removeEvent?&quot; _
+ + &quot;language=Java&amp;function=ScriptFrmwrkHelper.removeEvent&quot; _
+ + &quot;&amp;location=share&quot;
+
+ parser.parseStrict(url)
+ disp = document.queryDispatch(url,&quot;&quot;,0)
+ disp.dispatch(url,args())
+end sub
+
+
+sub AddEventToDocViaAPI( scriptName as string, eventName as string )
+ dim properties( 1 ) as new com.sun.star.beans.PropertyValue
+ properties( 0 ).Name = &quot;EventType&quot;
+ properties( 0 ).Value = &quot;Script&quot;
+ properties( 1 ).Name = &quot;Script&quot;
+ properties( 1 ).Value = scriptName
+
+ eventSupplier = ThisComponent
+ nameReplace = eventSupplier.getEvents()
+ nameReplace.replaceByName( eventName, properties() )
+end sub
+
+
+&apos; returns 0 for Fkey
+&apos; 1 for digit
+&apos; 2 for letter
+
+function getKeyTypeOffset( key as String ) as integer
+ length = Len( key )
+ if ( length &gt; 1 ) then
+ getKeyTypeOffset() = 0
+
+ elseif ( key &gt;= &quot;0&quot; AND key &lt;= &quot;9&quot; ) then
+ getKeyTypeOffset() = 1
+ else
+ getKeyTypeOffset() = 2
+ end if
+end function
+
+function getKeyGroupIndex( key as String, offset as Integer ) as Integer
+ &apos; Keys we are interested in are A - Z, F2 - F12, 0 - 9 anything else should
+ &apos; ensure -1 is returned
+ cutKey = mid( key,2 )
+
+ if ( cutKey &lt;&gt; &quot;&quot; ) then
+ acode = asc ( mid( cutKey,1,1) )
+ if ( acode &gt; 57 ) then
+ getKeyGroupIndex() = -1
+ exit function
+ end if
+ end if
+
+ select case offset
+ case 0:
+ num = cint( cutKey )
+ getKeyGroupIndex() = num - 1
+ exit function
+ case 1:
+ num = asc( key ) - 48
+ getKeyGroupIndex() = num
+ exit function
+ case 2:
+ num = asc( key ) - 65
+ getKeyGroupIndex() = num
+ exit function
+ end select
+ getKeyGroupIndex() = -1
+end function
+
+Sub processKeyXMLLine( lineCount as Integer, xmlline as String )
+
+ if instr( xmlline, &quot;&lt;accel:item&quot; ) &gt; 0 then
+ shift = false
+ control = false
+ if instr( xmlline, &quot;accel:shift=&quot;+chr$(34)+&quot;true&quot;+chr$(34) ) &gt; 0 then
+ shift = true
+ end if
+ if instr( xmlFile( lineCount ), &quot;accel:mod1=&quot;+chr$(34)+&quot;true&quot;+chr$(34) ) &gt; 0 then
+ control = true
+ end if
+ offsetIntoArrayOfArrays = -1 &apos;default unknown
+ if ( control AND shift ) then
+ offsetIntoArrayOfArrays = 0
+ elseif ( control ) then
+ offsetIntoArrayOfArrays = 3
+ elseif ( shift ) then
+ offsetIntoArrayOfArrays = 6
+ endif
+ &apos; Calculate which of the 7 key group arrays we need to point to
+ key = ExtractKeyCodeFromXMLLine( xmlline )
+ keyTypeOffset = getKeyTypeOffset( key )
+ offsetIntoArrayOfArrays = offsetIntoArrayOfArrays + keyTypeOffset
+
+ &apos; Calculate from the key the offset into key group array we need to point to
+ KeyGroupIndex = getKeyGroupIndex( key, keyTypeOffset )
+ if ( offsetIntoArrayOfArrays = -1 ) then
+ &apos;Unknown key group, no processing necessary
+ Exit Sub
+ end if
+ if ( KeyGroupIndex &gt; -1 ) then
+
+ &apos; Determine if a script framework binding is present or not
+ if instr( xmlline, &quot;script://&quot; ) &gt; 0 then
+ &apos; its one of ours so update its details
+ scriptName = ExtractScriptIdFromXMLLine( xmlline )
+
+ keyAllocationMap( offsetIntoArrayOfArrays, KeyGroupIndex ).Value = lineCount
+ keyAllocationMap( offsetIntoArrayOfArrays, KeyGroupIndex ).Name = scriptName
+ else
+ keyAllocationMap( offsetIntoArrayOfArrays, KeyGroupIndex ).Value = 1
+ keyAllocationMap( offsetIntoArrayOfArrays, KeyGroupIndex ).Name = &quot;&quot;
+
+ end if
+ end if
+ end if
+End Sub
+
+Sub WriteXMLFromArray()
+ On Error Goto ErrorHandler
+ cfgFile = GetOfficePath() + &quot;user/config/soffice.cfg/&quot; + xmlFileName
+ updateCfgFile( cfgFile )
+ &apos;if ( false ) then&apos; config stuff not in build yet
+ if ( true ) then
+ updateConfig( xmlFileName )
+ else
+ msgbox (&quot;Office must be restarted before your changes will take effect.&quot;+ chr$(10)+&quot;Also close the Office QuickStarter (Windows and Linux)&quot;, 48, &quot;Assign Script (Java) To Menu&quot; )
+ endif
+ Exit Sub
+
+ ErrorHandler:
+ reset
+ MsgBox (&quot;Error: Unable to write to Star Office configuration file&quot; + chr$(10) + &quot;/&quot; + GetOfficePath() + &quot;user/config/soffice.cfg/&quot; +xmlFileName + chr$(10) + chr$(10) + &quot;Action: Please make sure you have write access to this file&quot;,0,&quot;Error&quot; )
+end Sub
+
+
+Sub UpdateCfgFile ( fileName as String )
+ dim ScriptProvider as Object
+ dim Script as Object
+ dim args(1)
+ dim displayDialogFlag as boolean
+ displayDialogFlag = false
+ args(0) = ThisComponent
+ args(1) = displayDialogFlag
+
+ ScriptProvider = createUnoService(&quot;drafts.com.sun.star.script.framework.provider.MasterScriptProvider&quot;)
+ ScriptProvider.initialize( args() )
+ Script = ScriptProvider.getScript(&quot;script://_$ScriptFrmwrkHelper.updateCfgFile?&quot; _
+ + &quot;language=Java&amp;function=ScriptFrmwrkHelper.updateCfgFile&amp;location=share&quot;)
+ Dim inArgs(2)
+ Dim outArgs()
+ Dim outIndex()
+ dim localNumLines as integer
+
+ inArgs(0) = xmlFile()
+ inArgs(1) = fileName
+ inArgs(2) = numberOfLines
+ Script.invoke( inArgs(), outIndex(), outArgs() )
+End Sub
+
+sub UpdateConfig( a$ )
+ dim document as object
+ dim dispatcher as object
+ dim parser as object
+ dim disp as object
+ dim url as new com.sun.star.util.URL
+ document = ThisComponent.CurrentController.Frame
+ parser = createUnoService(&quot;com.sun.star.util.URLTransformer&quot;)
+ dim args1(0) as new com.sun.star.beans.PropertyValue
+ args1(0).Name = &quot;StreamName&quot;
+ args1(0).Value = a$
+ url.Complete = &quot;.uno:UpdateConfiguration&quot;
+ parser.parseStrict(url)
+ disp = document.queryDispatch(url,&quot;&quot;,0)
+ disp.dispatch(url,args1())
+
+End Sub
+
+
+sub AddNewEventBinding( scriptName as string, eventPosition as integer, isApp as boolean )
+ event = allEventTypes( eventPosition ).Name
+ &apos;dim scriptProp as new com.sun.star.beans.PropertyValue
+ if isApp then
+ &apos;scriptProp.Name = scriptName
+ &apos;scriptProp.Value = numberOfLines
+ allEventTypesApp( eventPosition ).Name = scriptName
+ allEventTypesApp( eventPosition ).Value = numberOfLines
+
+ newline = &quot; &lt;event:event event:name=&quot; + chr$(34) + event + chr$(34)
+ newline = newline + &quot; event:language=&quot; + chr$(34) + &quot;Script&quot; + chr$(34) + &quot; xlink:href=&quot; + chr$(34)
+ newline = newline + scriptName + chr$(34) + &quot; xlink:type=&quot; + chr$(34) + &quot;simple&quot; + chr$(34) + &quot;/&gt;&quot;
+ xmlFile( numberOfLines ) = newline
+ xmlFile( numberOfLines + 1 ) = &quot;&lt;/event:events&gt;&quot;
+ numberOfLines = numberOfLines + 1
+ else
+ &apos;scriptProp.Name = scriptName
+ &apos;scriptProp.Value = 2
+ allEventTypesDoc( eventPosition ).Name = scriptName
+ allEventTypesDoc( eventPosition ).Value = 2
+ end if
+end sub
+
+REM ----- Array update functions -----
+
+
+sub AddNewMenuBinding( newScript as string, newMenuLabel as string, newLinePosition as integer )
+ dim newXmlFile( 400 ) as string
+ dim newLineInserted as boolean
+ dim lineCounter as integer
+ lineCounter = 1
+
+ do while lineCounter &lt;= numberOfLines
+ if not newLineInserted then
+ REM If the line number is the position at which to insert the new line
+ if lineCounter = newLinePosition then
+ if( instr( xmlFile( lineCounter ), &quot;&lt;menu:menupopup&gt;&quot; ) &gt; 0 ) then
+ indent = GetMenuWhiteSpace( xmlFile( newLinePosition + 1 ) )
+ newXmlFile( lineCounter ) = xmlFile( lineCounter )
+ newXmlFile( lineCounter + 1 ) = ( indent + &quot;&lt;menu:menuitem menu:id=&quot;+chr$(34) + newScript + chr$(34)+&quot; menu:helpid=&quot;+chr$(34)+&quot;1929&quot;+chr$(34)+&quot; menu:label=&quot;+chr$(34)+ newMenuLabel + chr$(34)+&quot;/&gt;&quot; )
+ else
+ indent = GetMenuWhiteSpace( xmlFile( newLinePosition - 1 ) )
+ newXmlFile( lineCounter ) = ( indent + &quot;&lt;menu:menuitem menu:id=&quot;+chr$(34) + newScript + chr$(34)+&quot; menu:helpid=&quot;+chr$(34)+&quot;1929&quot;+chr$(34)+&quot; menu:label=&quot;+chr$(34)+ newMenuLabel + chr$(34)+&quot;/&gt;&quot; )
+ newXmlFile( lineCounter + 1 ) = xmlFile( lineCounter )
+ end if
+ REM added -1 for debug --&gt;
+ &apos; indent = GetMenuWhiteSpace( xmlFile( newLinePosition ) )
+ &apos; newXmlFile( lineCounter ) = ( indent + &quot;&lt;menu:menuitem menu:id=&quot;+chr$(34)+&quot;script://&quot; + newScript + chr$(34)+&quot; menu:helpid=&quot;+chr$(34)+&quot;1929&quot;+chr$(34)+&quot; menu:label=&quot;+chr$(34)+ newMenuLabel + chr$(34)+&quot;/&gt;&quot; )
+ &apos; newXmlFile( lineCounter + 1 ) = xmlFile( lineCounter )
+ newLineInserted = true
+ else
+ newXmlFile( lineCounter ) = xmlFile( lineCounter )
+ end if
+ else
+ REM if the new line has been inserted the read from one position behind
+ newXmlFile( lineCounter + 1 ) = xmlFile( lineCounter )
+ end if
+ lineCounter = lineCounter + 1
+ loop
+
+ numberOfLines = numberOfLines + 1
+
+ REM read the new file into the global array
+ for n = 1 to numberOfLines
+ xmlFile( n ) = newXmlFile( n )
+ next n
+
+end sub
+
+
+sub AddNewKeyBinding( scriptName as string, shift as boolean, control as boolean, key as string )
+
+ dim keyCombo as string
+ newLine = &quot; &lt;accel:item accel:code=&quot;+chr$(34)+&quot;KEY_&quot; + key +chr$(34)
+ if shift then
+ keyCombo = &quot;SHIFT + &quot;
+ newLine = newLine + &quot; accel:shift=&quot;+chr$(34)+&quot;true&quot;+chr$(34)
+ end if
+ if control then
+ keyCombo = keyCombo + &quot;CONTROL + &quot;
+ newLine = newLine + &quot; accel:mod1=&quot;+chr$(34)+&quot;true&quot;+chr$(34)
+ end if
+ keyCombo = keyCombo + key
+ newLine = newLine + &quot; xlink:href=&quot;+chr$(34)+ scriptName +chr$(34) +&quot;/&gt;&quot;
+
+ if ( control AND shift ) then
+ offsetIntoArrayOfArrays = 0
+ elseif ( control ) then
+ offsetIntoArrayOfArrays = 3
+ elseif ( shift ) then
+ offsetIntoArrayOfArrays = 6
+ endif
+
+ keyTypeOffset = getKeyTypeOffset( key )
+ offsetIntoArrayOfArrays = offsetIntoArrayOfArrays + keyTypeOffset
+ &apos; Calculate from the key the offset into key group array we need to point to
+ KeyGroupIndex = getKeyGroupIndex( key, keyTypeOffset )
+
+ &apos; if key is allready allocated to a script then just reallocate
+ if ( keyAllocationMap( offsetIntoArrayOfArrays, KeyGroupIndex ).Value &gt; 1 ) then
+
+ keyAllocationMap( offsetIntoArrayOfArrays, KeyGroupIndex ).Name = scriptName
+ &apos;replace line in xml file
+ xmlFile( keyAllocationMap( offsetIntoArrayOfArrays, KeyGroupIndex ).Value ) = newLine
+ else
+ &apos; this is a new binding, create a new line in xml file
+ for n = 1 to numberOfLines
+ if n = numberOfLines then
+ xmlFile( n ) = newLine
+ xmlFile( n + 1 ) = &quot;&lt;/accel:acceleratorlist&gt;&quot;
+ exit for
+ else
+ xmlFile( n ) = xmlFile( n )
+ end if
+ next n
+
+ keyAllocationMap( offsetIntoArrayOfArrays, KeyGroupIndex ).Value = n
+ keyAllocationMap( offsetIntoArrayOfArrays, KeyGroupIndex ).Name = scriptName
+ numberOfLines = numberOfLines + 1
+ endif
+
+end sub
+
+
+Sub RemoveBinding( lineToRemove as Integer )
+ xmlFile( lineToRemove ) = &quot;&quot;
+end Sub
+
+REM Adds or removes the starting xml line positions for each top-level menu after the menu with the added script
+sub UpdateTopLevelMenus( topLevelMenuPosition as integer, addLine as boolean )
+ for n = topLevelMenuPosition to 8
+ if addLine then
+ menuItemLinePosition( n ) = menuItemLinePosition( n ) + 1
+
+ end if
+ next n
+end sub
+
+
+REM Remove scriptNames and scriptLinePosition entries
+sub RemoveScriptNameAndPosition( keyComboPosition )
+ dim updatedScriptNames( 120 ) as string
+ dim updatedScriptLinePosition( 120 ) as integer
+ dim removedScript as boolean
+ removedScript = false
+
+ for n = 1 to scriptCount
+ if not removedScript then
+ if not( n = keyComboPosition ) then
+ updatedScriptNames( n ) = scriptNames( n )
+ else
+ removedScript = true
+ end if
+ else
+ updatedScriptNames( n - 1 ) = scriptNames( n )
+ end if
+ next n
+ scriptCount = scriptCount - 1
+
+ for n = 1 to scriptCount
+ scriptNames( n ) = updatedScriptNames( n )
+ next n
+end sub
+
+
+
+REM ----- Populating Dialog Controls -----
+
+Sub PopulateLanguageCombo()
+ langCombo = bindingDialog.getControl( &quot;LanguageCombo&quot; )
+ langCombo.removeItems( 0, langCombo.getItemCount() )
+ for n = LBOUND( languages() ) to UBOUND ( languages() )
+ langCombo.addItem( languages( n ), n )
+ next n
+ langCombo.setDropDownLineCount( n )
+ langCombo.text = langCombo.getItem( 0 )
+End Sub
+
+Sub PopulateLocationCombo()
+ dim ScriptProvider as Object
+ dim args(1)
+ dim displayDialogFlag as boolean
+ displayDialogFlag = false
+ args(0) = ThisComponent
+ args(1) = displayDialogFlag
+
+ ScriptProvider = createUnoService(&quot;drafts.com.sun.star.script.framework.provider.MasterScriptProvider&quot;)
+ ScriptProvider.initialize( args() )
+
+ locCombo = bindingDialog.getControl( &quot;LocationCombo&quot; )
+ locCombo.removeItems( 0, locCombo.getItemCount() )
+ for n = LBOUND( locations() ) to UBOUND ( locations() )
+ locCombo.addItem( locations( n ), n )
+ next n
+ locCombo.setDropDownLineCount( n )
+ locCombo.text = locCombo.getItem( 0 )
+End Sub
+
+sub PopulateScriptList( lang as String, loc as String )
+ Dim detailedView as boolean
+ detailedView = bindingDialog.Model.detail.state
+ scriptList = bindingDialog.getControl( &quot;ScriptList&quot; )
+ scriptList.removeItems( 0, scriptList.getItemCount() )
+
+ smgr = getProcessServiceManager()
+ context = smgr.getPropertyValue( &quot;DefaultContext&quot; )
+ scriptstoragemgr = context.getValueByName( &quot;/singletons/drafts.com.sun.star.script.framework.storage.theScriptStorageManager&quot; )
+ scriptLocationURI = &quot;USER&quot;
+ if ( loc = &quot;Share&quot; ) then
+ scriptLocationURI = &quot;SHARE&quot;
+ elseif ( loc = &quot;Document&quot; )then
+ document = StarDesktop.ActiveFrame.Controller.Model
+ scriptLocationURI = document.getURL()
+ elseif ( loc = &quot;Filesystem&quot; ) then
+ REM populate the list from the filesysScripts list
+ if(lang = &quot;Java&quot; ) then
+ exit sub
+ endif
+ length = UBOUND( filesysScripts() )
+ if(length = -1) then
+ exit sub
+ endif
+ for langIndex = lbound(languages()) to ubound(languages())
+ if ( lang = languages(langIndex)) then
+ extns = extensions(langIndex)
+ exit for
+ endif
+ next langIndex
+ dim locnDisplayList( length ) as new com.sun.star.beans.PropertyValue
+ for index = lbound(filesysScripts()) to ubound(filesysScripts())
+ scriptextn = filesysScripts( index )
+ pos = lastIndexOf( scriptextn, &quot;.&quot; )
+ scriptextn = mid( scriptextn, pos + 1, len( scriptextn ) - pos )
+
+ for extnsIndex = lbound(extns()) to ubound(extns())
+ extn = extns(extnsIndex)
+ if ( scriptextn = extn ) then
+ if ( detailedView ) then
+ locnDisplayList( index ).Name = filesysScripts( index )
+ locnDisplayList( index ).Value = filesysScripts( index )
+ else
+ REM replace name with simplified view
+ locnDisplayList( index ).Name = filesysScripts( index )
+ locnDisplayList( index ).Value = filesysScripts( index )
+ end if
+ scriptList.addItem( locnDisplayList( index ).Name, index )
+ exit for
+ end if
+ next extnsIndex
+ next index
+ ScriptDisplayList(0) = locnDisplayList()
+ scriptList.selectItemPos( 0, true )
+
+ REM !!!!At this point we exit the sub!!!!
+ exit sub
+
+ endif
+
+ scriptStorageID = scriptstoragemgr.getScriptStorageID( scriptLocationURI )
+ dim resultList() as Object
+ if ( scriptStorageID &gt; -1 ) then
+ storage = scriptstoragemgr.getScriptStorage( scriptStorageID )
+ implementations() = storage.getAllImplementations()
+ length = UBOUND( implementations() )
+ reservedScriptTag = &quot;_$&quot;
+ if ( length &gt; -1 ) then
+ dim tempDisplayList( length ) as new com.sun.star.beans.PropertyValue
+ for n = LBOUND( implementations() ) to UBOUND( implementations() )
+ logicalName = implementations( n ).getLogicalName()
+ firstTwoChars = LEFT( logicalName, 2 )
+ &apos;Only display scripts whose logicalnames don&apos;t begin with &quot;_$&quot;
+ if ( firstTwoChars &lt;&gt; reservedScriptTag ) then
+ if ( lang = implementations( n ).getLanguage() ) then
+ if ( detailedView ) then
+ tempDisplayList( n ).Name = logicalName _
+ + &quot; [&quot; + implementations( n ).getFunctionName() + &quot;]&quot;
+ tempDisplayList( n ).Value = implementations( n )
+ else
+ tempDisplayList( n ).Name = logicalName
+ tempDisplayList( n ).Value = implementations( n )
+ endif
+ scriptList.addItem( tempDisplayList( n ).Name, n )
+ endif
+ endif
+ next n
+ resultList = tempDisplayList()
+ endif
+ ScriptDisplayList(0) = resultList()
+ endif
+ scriptList.selectItemPos( 0, true )
+
+end sub
+
+sub PopulateMenuCombo()
+ menuComboBox = bindingDialog.getControl( &quot;MenuCombo&quot; )
+ menuComboBox.removeItems( 0, menuComboBox.getItemCount() )
+ for n = 1 to menuCount
+ menuComboBox.addItem( menuItems( n ), n - 1 )
+ next n
+ menuComboBox.setDropDownLineCount( 8 )
+ menuComboBox.text = menuComboBox.getItem( 0 )
+end sub
+
+
+sub PopulateSubMenuList( menuItemPosition as integer )
+ redim subMenuItems( 100 ) as string
+ redim subMenuItemLinePosition( 100 ) as integer
+ dim lineNumber as integer
+ const menuItemWhiteSpace = 4
+ const menuXMLTag = &quot;&lt;menu:menu&quot;
+ subMenuCount = 1
+
+ REM xmlStartLine and xmlEndLine refer to the first and last lines
+ &apos; menuItemPosition of a top-level menu ( 1=File to 8=Help ) add one line
+ xmlStartLine = menuItemLinePosition( menuItemPosition ) + 1
+
+ REM If last menu item is chosen
+ if menuItemPosition = menuCount then
+ xmlEndLine = numberOfLines
+ else
+ REM Other wise get the line before the next top-level menu begins
+ xmlEndLine = menuItemLinePosition( menuItemPosition + 1 ) - 1
+ end if
+
+ for lineNumber = xmlStartLine to xmlEndLine
+ REM Insert all sub-menus and sub-popupmenus
+ if not( instr( xmlFile( lineNumber ), menuXMLTag ) = 0 ) and instr( xmlFile( lineNumber ), &quot;menupopup&quot;) = 0 then
+ subMenuIndent = GetMenuWhiteSpace( xmlFile( lineNumber ) )
+ if subMenuIndent = &quot; &quot; then
+ subMenuIndent = &quot;&quot;
+ else
+ subMenuIndent = subMenuIndent + subMenuIndent
+ end if
+ if not( instr( xmlFile( lineNumber ), &quot;menuseparator&quot; ) = 0 ) then
+ subMenuItems( subMenuCount ) = subMenuIndent + &quot;----------------&quot;
+ else
+ subMenuName = ExtractLabelFromXMLLine( xmlFile( lineNumber ) )
+ REM Add script Name if there is one bound to menu item
+ if instr( xmlFile( lineNumber ), &quot;script://&quot; ) &gt; 0 then
+ script = ExtractScriptIdFromXMLLine( xmlFile( lineNumber ) )
+ subMenuItems( subMenuCount ) = ( subMenuIndent + subMenuName + &quot; [&quot; + script + &quot;]&quot; )
+ else
+ subMenuItems( subMenuCount ) = subMenuIndent + subMenuName
+ end if
+ end if
+ subMenuItemLinePosition( subMenuCount ) = lineNumber
+ subMenuCount = subMenuCount + 1
+ end if
+ next lineNumber
+
+ subMenuList = bindingDialog.getControl( &quot;SubMenuList&quot; )
+
+ currentPosition = subMenuList.getSelectedItemPos()
+
+ subMenuList.removeItems( 0, subMenuList.getItemCount() )
+ &apos;If there are no sub-menus i.e. a dynamically generated menu like Format
+ &apos;if subMenuCount = 1 then
+ if menuItems( menuItemPosition ) = &quot;Format&quot; then
+ subMenuList.addItem( &quot;Unable to Assign Scripts to this menu&quot;, 0 )
+ else
+ for n = 1 to subMenuCount - 1
+ subMenuList.addItem( subMenuItems( n ), n - 1 )
+ next n
+ end if
+
+ subMenuList.selectItemPos( currentPosition, true )
+
+ SubMenuListListener()
+ MenuLabelBoxListener()
+end sub
+
+
+
+sub PopulateTopLevelKeyBindingList()
+
+ allKeyGroupsArray(0) = &quot;SHIFT + CONTROL + F keys&quot;
+ allKeyGroupsArray(1) = &quot;SHIFT + CONTROL + digits&quot; &apos; CURRENTLY DISABLED
+ allKeyGroupsArray(2) = &quot;SHIFT + CONTROL + letters&quot;
+ allKeyGroupsArray(3) = &quot;CONTROL + F keys&quot;
+ allKeyGroupsArray(4) = &quot;CONTROL + digits&quot;
+ allKeyGroupsArray(5) = &quot;CONTROL + letters&quot;
+ allKeyGroupsArray(6) = &quot;SHIFT + F keys&quot;
+
+ keyCombo = bindingDialog.getControl( &quot;KeyCombo&quot; )
+ keyCombo.removeItems( 0, keyCombo.getItemCount() )
+ pos = 0
+ for n = LBOUND( allKeyGroupsArray() ) to UBOUND( allKeyGroupsArray() )
+ &apos; SHIFT + CONTROL + digits group is disabled at the moment, so skip
+ &apos; it
+ if ( n &lt;&gt; 1 ) then
+ keyCombo.addItem( allKeyGroupsArray( n ), pos )
+ pos = pos +1
+ endif
+ next n
+ keyCombo.text = keyCombo.getItem( 0 )
+end sub
+
+sub PopulateKeyBindingList( keyGroupIndex as Integer )
+ keyList = bindingDialog.getControl( &quot;KeyList&quot; )
+ selectedPos = keyList.getSelectedItemPos()
+ keyList.removeItems( 0, keyList.getItemCount() )
+
+ ShortCutKeyArray() = KeyBindArrayOfArrays( keyGroupIndex )
+
+ Dim keyProp as new com.sun.star.beans.PropertyValue
+ for n = lbound( ShortCutKeyArray() ) to ubound( ShortCutKeyArray() )
+ keyName = ShortCutKeyArray( n )
+ if ( keyAllocationMap( keyGroupIndex, n ).Value = 1 ) then
+ keyName = keyName + &quot; [Allocated to Office function]&quot;
+
+ elseif ( keyAllocationMap( keyGroupIndex, n ).Value &gt; 1 ) then
+ keyName = keyName + &quot; &quot; + keyAllocationMap( keyGroupIndex, n ).Name
+ endif
+ keyList.addItem( keyName, n )
+ next n
+
+ if ( selectedPos &lt;&gt; -1 )then
+ keyList.selectItemPos( selectedPos, true )
+ else
+ keyList.selectItemPos( 0, true )
+ end if
+ KeyListListener()
+end sub
+
+sub populateEventList( focusPosition as integer )
+ allApps = bindingDialog.getControl( &quot;AllAppsOption&quot; )
+ eventList = bindingDialog.getControl( &quot;EventList&quot; )
+ eventList.removeItems( 0, eventList.getItemCount() )
+
+ dim isApp as boolean
+ if allApps.state = true then &apos; Application event
+ isApp = true
+ else
+ isApp = false
+ end if
+
+ &apos; use allEventTypes() to fill list box
+ &apos; for each element compare with allEventTypesApp
+ dim scriptName as string
+ dim lineNumber as integer
+ for n = 0 to ubound( allEventTypes() )
+ &apos; If the line number is 1 then SB macro
+ &apos; more than 1 it is the line number of the script
+ if isApp and n &gt; 12 then
+ exit for
+ endif
+ if isApp then
+ lineNumber = allEventTypesApp( n ).Value
+ scriptName = allEventTypesApp( n ).Name
+ else
+ lineNumber = allEventTypesDoc( n ).Value
+ scriptName = allEventTypesDoc( n ).Name
+ end if
+ stringToAdd = &quot;&quot;
+ if ( lineNumber &gt;= 1 ) then
+ stringToAdd = &quot; [&quot; + scriptName + &quot;]&quot;
+ end if
+ eventList.addItem( allEventTypes( n ).Value + &quot; &quot; + stringToAdd, n )
+ next n
+
+ eventList.selectItemPos( focusPosition, true )
+end sub
+
+
+
+sub CreateAllKeyBindings()
+ reDim allKeyBindings( 105 ) as string
+ keyBindingPosition = 1
+
+ for FKey = 2 to 12
+ allKeyBindings( keyBindingPosition ) = &quot;SHIFT + CONTROL + F&quot; + FKey
+ keyBindingPosition = keyBindingPosition + 1
+ next FKey
+ for Digit = 0 to 9
+ allKeyBindings( keyBindingPosition ) = &quot;SHIFT + CONTROL + &quot; + Digit
+ keyBindingPosition = keyBindingPosition + 1
+ next Digit
+ for Alpha = 65 to 90
+ allKeyBindings( keyBindingPosition ) = &quot;SHIFT + CONTROL + &quot; + chr$( Alpha )
+ keyBindingPosition = keyBindingPosition + 1
+ next Alpha
+
+ for FKey = 2 to 12
+ allKeyBindings( keyBindingPosition ) = &quot;CONTROL + F&quot; + FKey
+ keyBindingPosition = keyBindingPosition + 1
+ next FKey
+ for Digit = 0 to 9
+ allKeyBindings( keyBindingPosition ) = &quot;CONTROL + &quot; + Digit
+ keyBindingPosition = keyBindingPosition + 1
+ next Digit
+ for Alpha = 65 to 90
+ allKeyBindings( keyBindingPosition ) = &quot;CONTROL + &quot; + chr$( Alpha )
+ keyBindingPosition = keyBindingPosition + 1
+ next Alpha
+
+ for FKey = 2 to 12
+ allKeyBindings( keyBindingPosition ) = &quot;SHIFT + F&quot; + FKey
+ keyBindingPosition = keyBindingPosition + 1
+ next FKey
+end sub
+
+
+sub createAllEventTypes()
+ allEventTypes( 0 ).Name = &quot;OnStartApp&quot;
+ allEventTypes( 0 ).Value = &quot;Start Application&quot;
+ allEventTypes( 1 ).Name = &quot;OnCloseApp&quot;
+ allEventTypes( 1 ).Value = &quot;Close Application&quot;
+ allEventTypes( 2 ).Name = &quot;OnNew&quot;
+ allEventTypes( 2 ).Value = &quot;Create Document&quot;
+ allEventTypes( 3 ).Name = &quot;OnLoad&quot;
+ allEventTypes( 3 ).Value = &quot;Open Document&quot;
+ allEventTypes( 4 ).Name = &quot;OnSaveAs&quot;
+ allEventTypes( 4 ).Value = &quot;Save Document As&quot;
+ allEventTypes( 5 ).Name = &quot;OnSaveAsDone&quot;
+ allEventTypes( 5 ).Value = &quot;Document has been saved as&quot;
+ allEventTypes( 6 ).Name = &quot;OnSave&quot;
+ allEventTypes( 6 ).Value = &quot;Save Document&quot;
+ allEventTypes( 7 ).Name = &quot;OnSaveDone&quot;
+ allEventTypes( 7 ).Value = &quot;Document has been saved&quot;
+ allEventTypes( 8 ).Name = &quot;OnPrepareUnload&quot;
+ allEventTypes( 8 ).Value = &quot;Close Document&quot;
+ allEventTypes( 9 ).Name = &quot;OnUnload&quot;
+ allEventTypes( 9 ).Value = &quot;Close Document&quot;
+ allEventTypes( 10 ).Name = &quot;OnFocus&quot;
+ allEventTypes( 10 ).Value = &quot;Activate document&quot;
+ allEventTypes( 11 ).Name = &quot;OnUnfocus&quot;
+ allEventTypes( 11 ).Value = &quot;DeActivate document&quot;
+ allEventTypes( 12 ).Name = &quot;OnPrint&quot;
+ allEventTypes( 12 ).Value = &quot;Print Document&quot;
+ REM The following are document-only events
+ allEventTypes( 13 ).Name = &quot;OnMailMerge&quot;
+ allEventTypes( 13 ).Value = &quot;Print form letters&quot;
+ allEventTypes( 14 ).Name = &quot;OnPageCountChange&quot;
+ allEventTypes( 14 ).Value = &quot;Changing the page count&quot;
+end sub
+
+
+sub createAllEventBindings()
+ &apos;dim props as new com.sun.star.beans.PropertyValue
+ &apos;props.Name = &quot;&quot; &apos;Name = script name
+ &apos;props.Value = 0 &apos;Value = 0 for empty, 1 for macro, linenumber for script
+
+ &apos; Creates all types of event bindings for both Application and Document
+ &apos; Initially both arrays have no bindings allocated to the events
+ &apos; The value for Doc is only Script/macro name (no need for line number)
+ for n = 0 to ubound( allEventTypes() )
+ allEventTypesApp( n ).Name = &quot;&quot;
+ allEventTypesApp( n ).Value = 0
+ allEventTypesDoc( n ).Name = &quot;&quot;
+ allEventTypesDoc( n ).Value = 0
+ next n
+end sub
+
+
+REM ----- Text Handling Functions -----
+
+
+function ExtractLabelFromXMLLine( XMLLine as string ) as string
+ labelStart = instr( XMLLine, &quot;label=&quot;+chr$(34)) + 7
+ labelEnd = instr( XMLLine, chr$(34)+&quot;&gt;&quot; )
+ if labelEnd = 0 then
+ labelEnd = instr( XMLLine, chr$(34)+&quot;/&gt;&quot; )
+ end if
+ labelLength = labelEnd - labelStart
+
+ menuLabelUnformatted = mid( XMLLine, labelStart, labelLength )
+ tildePosition = instr( menuLabelUnformatted, &quot;~&quot; )
+ select case tildePosition
+ case 0
+ menuLabel = menuLabelUnformatted
+ case 1
+ menuLabel = right( menuLabelUnformatted, labelLength - 1 )
+ case else
+ menuLabelLeft = left( menuLabelUnformatted, tildePosition - 1 )
+ menuLabelRight = right( menuLabelUnformatted, labelLength - tildePosition )
+ menuLabel = menuLabelLeft + menuLabelRight
+ end select
+
+ ExtractLabelFromXMLLine() = menuLabel
+end function
+
+
+function ExtractScriptIdFromXMLLine( XMLLine as string ) as string
+ idStart = instr( XMLLine, &quot;script://&quot;) + 9
+ if instr( XMLLine, chr$(34)+&quot; menu:helpid=&quot; ) = 0 then
+ idEnd = instr( XMLLIne, &quot;?location=&quot; )
+ else
+ idEnd = instr( XMLLine, &quot;&quot;+chr$(34)+&quot; menu:helpid=&quot; )
+ end if
+ idLength = idEnd - idStart
+ scriptId = mid( XMLLine, idStart, idLength )
+
+ ExtractScriptIdFromXMLLine() = scriptId
+end function
+
+function ExtractEventScriptFromXMLLine( xmlline as string )
+ if instr( xmlline, &quot;script://&quot; ) &gt; 0 then
+ idStart = instr( xmlline, &quot;script://&quot;) + 9
+ idEnd = instr( xmlline, chr$(34)+&quot; xlink:type=&quot; )
+ idLength = idEnd - idStart
+ scriptId = mid( xmlline, idStart, idLength )
+ end if
+ ExtractEventScriptFromXMLLine() = scriptId
+end function
+
+
+function ExtractEventNameFromXMLLine( xmlline as string )
+ idStart = instr( xmlline, &quot;event:name=&quot; + chr$(34) ) + 12
+ idEnd = instr( xmlline, chr$(34)+&quot; event:language&quot; )
+ idLength = idEnd - idStart
+ event = mid( xmlline, idStart, idLength )
+
+ ExtractEventNameFromXMLLine() = event
+end function
+
+function ExtractKeyCodeFromXMLLine( XMLLine as string ) as string
+ keyStart = instr( XMLLine, &quot;code=&quot;+chr$(34)+&quot;KEY_&quot;) + 10
+ keyCode = mid( XMLLine, keyStart, ( len( XMLLine ) - keyStart ) )
+ keyEnd = instr( keyCode, chr$(34) )
+ keyCode = mid( keyCode, 1, keyEnd - 1 )
+
+ ExtractKeyCodeFromXMLLine() = keyCode
+end function
+
+
+function GetMenuWhiteSpace( MenuXMLLine as string ) as string
+ whiteSpace = &quot;&quot;
+ numberOfSpaces = instr( MenuXMLLine, &quot;&lt;&quot; ) - 1
+ for i = 1 to numberOfSpaces
+ whiteSpace = whiteSpace + &quot; &quot;
+ next i
+
+ GetMenuWhiteSpace() = whiteSpace
+end function
+
+function IsAllocatedMenuItem( script as string ) as boolean
+ foundMenuItem = false
+ Allocated = false
+ count = 0
+ do
+ count = count + 1
+ if strcomp( script, subMenuItems( count ) ) = 0 then
+ foundMenuItem = true
+ end if
+ loop while not( foundMenuItem ) and count &lt; subMenuCount
+
+ linePosition = subMenuItemLinePosition( count )
+
+ if not( instr( xmlFile( linePosition ), &quot;script://&quot; ) = 0 ) then
+ Allocated = true
+ end if
+
+ isAllocatedMenuItem() = Allocated
+end Function
+
+
+function HasShiftKey( keyCombo ) as boolean
+ if instr( keyCombo, &quot;SHIFT&quot; ) = 0 then
+ hasShift = false
+ else
+ hasShift = true
+ end if
+
+ HasShiftKey = hasShift
+end function
+
+
+function HasControlKey( keyCombo ) as boolean
+ if instr( keyCombo, &quot;CONTROL&quot; ) = 0 then
+ hasControl = false
+ else
+ hasControl = true
+ end if
+
+ HasControlKey = hasControl
+end function
+
+
+function ExtractKeyFromCombo( keyString as string ) as string
+ while not( instr( keyString, &quot;+&quot; ) = 0 )
+ removeTo = instr( keyString, &quot;+ &quot; ) + 2
+ keyString = mid( keyString, removeTo, ( len( keyString ) - removeTo ) + 1 )
+ wend
+ ExtractKeyFromCombo() = keyString
+end function
+
+
+
+REM ------ Event Handling Functions (Listeners) ------
+
+
+sub KeyListListener()
+ keyShortCutList = bindingDialog.getControl( &quot;KeyList&quot; )
+ selectedShortCut = keyShortCutList.getSelectedItem()
+ combo = bindingDialog.getControl( &quot;KeyCombo&quot; )
+
+ menuScriptList = bindingDialog.getControl( &quot;ScriptList&quot; )
+ selectedScript = menuScriptList.getSelectedItem()
+
+ keyGroup = combo.text
+ dim keyGroupIndex as Integer
+ dim selectedKeyIndex as Integer
+ for n = lbound ( allKeyGroupsArray() ) to ubound ( allKeyGroupsArray() )
+ if ( allKeyGroupsArray( n ) = keyGroup )then
+ keyGroupIndex = n
+ exit for
+ end if
+ next n
+ selectedKeyIndex = keyShortCutList.getSelectedItemPos()
+
+ if keyAllocationMap( keyGroupIndex, selectedKeyIndex ).Value &gt; 1 then
+ bindingDialog.Model.Delete.enabled = true
+ bindingDialog.Model.AddOn.enabled = true
+ if selectedScript &lt;&gt; &quot;&quot; then
+ bindingDialog.Model.NewButton.enabled = true
+ endif
+
+ else
+
+ if keyAllocationMap( keyGroupIndex, selectedKeyIndex ).Value = 1 then
+ bindingDialog.Model.Delete.enabled = false
+ bindingDialog.Model.AddOn.enabled = false
+ bindingDialog.Model.NewButton.enabled = false
+ else
+ bindingDialog.Model.Delete.enabled = false
+ bindingDialog.Model.AddOn.enabled = false
+ if selectedScript &lt;&gt; &quot;&quot; then
+ bindingDialog.Model.NewButton.enabled = true
+ end if
+ end if
+ end if
+end sub
+
+
+sub SubMenuListListener()
+ scriptList = bindingDialog.getControl( &quot;ScriptList&quot; )
+ subMenuList = bindingDialog.getControl( &quot;SubMenuList&quot; )
+ selectedMenuItem = subMenuList.getSelectedItem()
+ if IsAllocatedMenuItem( selectedMenuItem ) then
+ bindingDialog.Model.Delete.enabled = true
+ bindingDialog.Model.AddOn.enabled = true
+ else
+ bindingDialog.Model.Delete.enabled = false
+ bindingDialog.Model.AddOn.enabled = false
+ end if
+end sub
+
+REM a keypress listener that in turn fires the MenuCL on a return key even only
+sub fireMenuComboListernerOnRet( eventobj as object )
+ if (eventobj.KeyCode = 1280 ) then
+ MenuComboListener()
+ endif
+end sub
+
+&apos;Populates the SubMenuList with the appropriate menu items from the Top-level menu selected from the combo box
+sub MenuComboListener()
+ combo = bindingDialog.getControl( &quot;MenuCombo&quot; )
+ newToplevelMenu = combo.text
+ counter = 0
+ do
+ counter = counter + 1
+ loop while not( newToplevelMenu = menuItems( counter ) )
+
+ PopulateSubMenuList( counter )
+end sub
+
+REM a keypress listener that in turn fires the LLCL on a return key even only
+sub fireLangLocComboListernerOnRet( eventobj as object )
+ if (eventobj.KeyCode = 1280 ) then
+ LangLocComboListener()
+ endif
+end sub
+
+sub LangLocComboListener()
+
+ combo = bindingDialog.getControl( &quot;LanguageCombo&quot; )
+ language = combo.text
+ combo = bindingDialog.getControl( &quot;LocationCombo&quot; )
+ location = combo.text
+
+ PopulateScriptList( language,location )
+
+ &apos;Enable/disable Assign button
+ scriptList = bindingDialog.getControl( &quot;ScriptList&quot; )
+ if not (dialogName = &quot;EditDebug&quot;) then
+ if scriptList.getSelectedItem() = &quot;&quot; then
+ bindingDialog.Model.NewButton.enabled = false
+ end if
+ end if
+
+ if ( location = &quot;Filesystem&quot; ) and ( language &lt;&gt; &quot;Java&quot; ) then
+ bindingDialog.Model.Browse.enabled = true
+ if not (dialogName = &quot;EditDebug&quot;) then
+ bindingDialog.Model.fsonly.enabled = true
+ end if
+ else
+ bindingDialog.Model.Browse.enabled = false
+ if not (dialogName = &quot;EditDebug&quot;) then
+ bindingDialog.Model.fsonly.enabled = false
+ end if
+ endif
+
+ &apos; extra dialog dependant processing
+ if dialogName = &quot;Menu&quot; then
+ &apos; will set New button to false if no text in LableBox
+ MenuLabelBoxListener()
+ elseif dialogName = &quot;Key&quot; then
+ &apos; will set Assigne button to false if appropriate
+ KeyListListener()
+ elseif dialogName = &quot;Event&quot; then
+ EventListListener()
+ end if
+
+end sub
+
+REM a keypress listener that in turn fires the KeyCL on a return key even only
+sub fireKeyComboListernerOnRet( eventobj as object )
+ if (eventobj.KeyCode = 1280 ) then
+ KeyComboListener()
+ endif
+end sub
+
+&apos;Populates the KeyList with the appropriate key combos from the Top-level key group selected from the combo box
+sub KeyComboListener()
+ combo = bindingDialog.getControl( &quot;KeyCombo&quot; )
+ keyGroup = combo.text
+ for n = lbound ( allKeyGroupsArray() ) to ubound ( allKeyGroupsArray() )
+ if ( allKeyGroupsArray( n ) = keyGroup )then
+ keyGroupIndex = n
+ exit for
+ end if
+ next n
+ PopulateKeyBindingList( keyGroupIndex )
+end sub
+
+
+sub MenuLabelBoxListener()
+ menuScriptList = bindingDialog.getControl( &quot;ScriptList&quot; )
+ selectedScript = menuScriptList.getSelectedItem()
+ &apos;if the SubMenuList is from a dynamically created menu (e.g. Format)
+ &apos;or if the Menu Label text box is empty
+ subMenuList = bindingDialog.getControl( &quot;SubMenuList&quot; )
+ firstItem = subMenuList.getItem( 0 )
+ if bindingDialog.Model.MenuLabelBox.text = &quot;&quot; OR firstItem = &quot;Unable to Assign Scripts to this menu&quot; OR selectedScript = &quot;&quot; then
+ bindingDialog.Model.NewButton.enabled = false
+ else
+ bindingDialog.Model.NewButton.enabled = true
+ end if
+end sub
+
+sub AppDocEventListener()
+ populateEventList( 0 )
+ EventListListener()
+end sub
+
+
+sub EventListListener()
+ on error goto ErrorHandler
+
+ eventList = bindingDialog.getControl( &quot;EventList&quot; )
+ eventPos = eventList.getSelectedItemPos()
+
+ allApps = bindingDialog.getControl( &quot;AllAppsOption&quot; )
+
+ menuScriptList = bindingDialog.getControl( &quot;ScriptList&quot; )
+ selectedScript = menuScriptList.getSelectedItem()
+
+ dim binding as integer
+ if allApps.state = true then
+ binding = allEventTypesApp( eventPos ).Value
+ else
+ binding = allEventTypesDoc( eventPos ).Value
+ endif
+
+ if ( binding &gt; 1 ) then
+ bindingDialog.Model.Delete.enabled = true
+ else
+ bindingDialog.Model.Delete.enabled = false
+ end if
+
+ if ( binding = 1 ) then
+ &apos; staroffice binding, can&apos;t assign
+ bindingDialog.Model.NewButton.enabled = false
+ elseif ( selectedScript &lt;&gt; &quot;&quot; ) then
+ bindingDialog.Model.NewButton.enabled = true
+ end if
+ exit sub
+
+ ErrorHandler:
+ reset
+ bindingDialog.Model.Delete.enabled = false
+
+end sub
+
+
+REM ------ Event Handling Functions (Buttons) ------
+
+function getFilePicker() as Object
+ REM file dialog
+ oFilePicker = CreateUnoService( &quot;com.sun.star.ui.dialogs.FilePicker&quot; )
+
+ combo = bindingDialog.getControl( &quot;LanguageCombo&quot; )
+ language = combo.text
+ currentFilter = &quot;&quot;
+
+ for langIndex = 0 to ubound(languages())
+ if( languages(langIndex) &lt;&gt; &quot;Java&quot; ) then
+ filterName = languages(langIndex) + &quot; (&quot;
+ filterVal=&quot;&quot;
+ extns = extensions(langIndex)
+ for extnIndex = lbound(extns()) to ubound(extns())
+ filterName = filterName + &quot;*.&quot; + extns(extnIndex) + &quot;,&quot;
+ filterVal = filterVal + &quot;*.&quot; + extns(extnIndex) + &quot;,&quot;
+ next extnIndex
+ filterName = left(filterName, len(filterName) -1) + &quot;)&quot;
+ filterVal = left(filterVal, len(filterVal) -1)
+ if(instr(filterName,language) = 1 ) then
+ currentFilter = filterName
+ end if
+ oFilePicker.AppendFilter(filterName, filterVal)
+ end if
+ next langIndex
+ if(len(currentFilter) &gt; 0 ) then
+ oFilePicker.SetCurrentFilter( currentFilter )
+ end if
+
+ If sFileURL = &quot;&quot; Then
+ oSettings = CreateUnoService( &quot;com.sun.star.frame.Settings&quot; )
+ oPathSettings = oSettings.getByName( &quot;PathSettings&quot; )
+ sFileURL = oPathSettings.getPropertyValue( &quot;Work&quot; )
+ End If
+
+ REM set display directory
+ oSimpleFileAccess = CreateUnoService( &quot;com.sun.star.ucb.SimpleFileAccess&quot; )
+
+ If oSimpleFileAccess.exists( sFileURL ) And oSimpleFileAccess.isFolder( sFileURL ) Then
+ oFilePicker.setDisplayDirectory( sFileURL )
+ End If
+ getFilePicker() = oFilePicker
+end function
+
+Sub DoBrowseAndEdit()
+ Dim oFilePicker As Object, oSimpleFileAccess As Object
+ Dim oSettings As Object, oPathSettings As Object
+ Dim sFileURL As String
+ Dim sFiles As Variant
+
+ oFilePicker = getFilePicker()
+ REM execute file dialog
+ If oFilePicker.execute() Then
+ sFiles = oFilePicker.getFiles()
+
+ sFileURL = sFiles(0)
+ oSimpleFileAccess = CreateUnoService( &quot;com.sun.star.ucb.SimpleFileAccess&quot; )
+ If oSimpleFileAccess.exists( sFileURL ) Then
+ for langIndex = 0 to ubound(languages())
+ If (instr(oFilePicker.GetCurrentFilter, languages(langIndex)) = 1 ) then
+ RunDebugger(languages(langIndex), sFileURL, &quot;&quot;)
+ End If
+ next langIndex
+ End If
+ bindingDialog.endExecute()
+ End If
+End Sub
+
+Sub RunDebugger(lang as String, uri as String, filename as String)
+ dim document as object
+ dim dispatcher as object
+ dim parser as object
+ dim url as new com.sun.star.util.URL
+
+ document = ThisComponent.CurrentController.Frame
+ parser = createUnoService(&quot;com.sun.star.util.URLTransformer&quot;)
+ dim args(2) as new com.sun.star.beans.PropertyValue
+ args(0).Name = &quot;language&quot;
+ args(0).Value = lang
+ args(1).Name = &quot;uri&quot;
+ args(1).Value = uri
+ args(2).Name = &quot;filename&quot;
+ args(2).Value = filename
+
+ url.Complete = &quot;script://_$DebugRunner.Debug?&quot; _
+ + &quot;language=Java&amp;function=DebugRunner.go&quot; _
+ + &quot;&amp;location=share&quot;
+
+ parser.parseStrict(url)
+ disp = document.queryDispatch(url,&quot;&quot;,0)
+ disp.dispatch(url, args())
+End Sub
+
+sub DoEdit()
+ Dim scriptInfo as Object
+
+ menuScriptList = bindingDialog.getControl( &quot;ScriptList&quot; )
+ selectedScript = menuScriptList.getSelectedItem()
+
+ if not (selectedScript = &quot;&quot;) then
+ scripts() = scriptDisplayList(0)
+ for n = LBOUND( scripts() ) to UBOUND( scripts() )
+ if ( scripts( n ).Name = selectedScript ) then
+ scriptInfo = scripts( n ).Value
+ exit for
+ end if
+ next n
+
+ RunDebugger(scriptInfo.getLanguage, scriptInfo.getParcelURI, scriptInfo.getFunctionName)
+ bindingDialog.endExecute()
+ end if
+end sub
+
+sub MenuOKButton()
+ WriteXMLFromArray()
+ bindingDialog.endExecute()
+end sub
+
+
+sub MenuCancelButton()
+ bindingDialog.endExecute()
+end sub
+
+
+sub MenuHelpButton()
+ helpDialog = LoadDialog( &quot;ScriptBindingLibrary&quot;, &quot;HelpBinding&quot; )
+ helpDialog.execute()
+end sub
+
+
+sub MenuDeleteButton()
+ subMenuList = bindingDialog.getControl( &quot;SubMenuList&quot; )
+ linePos = subMenuItemLinePosition( subMenuList.getSelectedItemPos() + 1 )
+
+ RemoveBinding( linePos )
+
+ REM Update the top-level menu&apos;s line positions
+ combo = bindingDialog.getControl( &quot;MenuCombo&quot; )
+ newToplevelMenu = combo.text
+ counter = 0
+ do
+ counter = counter + 1
+ loop while not( newToplevelMenu = menuItems( counter ) )
+ UpdateTopLevelMenus( counter + 1, false )
+
+ MenuComboListener()
+
+ subMenuList.selectItemPos( subMenuList.getSelectedItemPos(), true )
+end sub
+
+
+sub MenuNewButton()
+ menuScriptList = bindingDialog.getControl( &quot;ScriptList&quot; )
+ selectedScript = menuScriptList.getSelectedItem()
+ scriptURI = getScriptURI( selectedScript )
+ newMenuLabel = bindingDialog.Model.MenuLabelBox.text
+
+ subMenuList = bindingDialog.getControl( &quot;SubMenuList&quot; )
+
+ REM Update the top-level menu&apos;s line positions
+ combo = bindingDialog.getControl( &quot;MenuCombo&quot; )
+ newToplevelMenu = combo.text
+ counter = 0
+ do
+ counter = counter + 1
+ loop while not( newToplevelMenu = menuItems( counter ) )
+ UpdateTopLevelMenus( counter + 1, true )
+
+ REM New line position is one ahead of the selected sub menu item
+ linePos = subMenuItemLinePosition( subMenuList.getSelectedItemPos() + 1 ) + 1
+
+ AddNewMenuBinding( scriptURI, newMenuLabel, linePos )
+
+ MenuComboListener()
+ subMenuList.selectItemPos( subMenuList.getSelectedItemPos() + 1, true )
+ SubMenuListListener()
+end sub
+
+sub BrowseButton()
+ Dim oFilePicker As Object, oSimpleFileAccess As Object
+ Dim oSettings As Object, oPathSettings As Object
+ Dim sFileURL As String
+ Dim sFiles As Variant
+
+ oFilePicker = getFilePicker()
+
+ REM execute file dialog
+ If oFilePicker.execute() Then
+ sFiles = oFilePicker.getFiles()
+ sFileURL = sFiles(0)
+ oSimpleFileAccess = CreateUnoService( &quot;com.sun.star.ucb.SimpleFileAccess&quot; )
+ If oSimpleFileAccess.exists( sFileURL ) Then
+ REM add sFileURL to the list
+ ReDim preserve filesysScripts(filesysCount) as String
+ filesysScripts( filesysCount ) = sFileURL
+ filesysCount=filesysCount+1
+ &apos; if user changed filter in file picker then populate
+ &apos; language with language associated with that in file picker
+ sFilter = oFilePicker.getCurrentFilter()
+ langCombo = bindingDialog.getControl( &quot;LanguageCombo&quot; )
+ dim items() as String
+ items() = langCombo.getItems()
+ for index = lbound(items()) to ubound(items())
+ iPos = inStr(sFilter,&quot; &quot;)
+ Dim theLanguage as String
+ if( iPos &gt; 0 ) then
+ theLanguage = Left( sFilter, iPos - 1)
+ if ( theLanguage = items( index ) ) then
+ langCombo.text = items( index )
+ exit for
+ end if
+ end if
+ next index
+ End If
+ End If
+ LangLocComboListener()
+End Sub
+
+sub KeyOKButton()
+ WriteXMLFromArray()
+ bindingDialog.endExecute()
+end sub
+
+
+sub KeyCancelButton()
+ bindingDialog.endExecute()
+end sub
+
+
+sub KeyHelpButton()
+ helpDialog = LoadDialog( &quot;ScriptBindingLibrary&quot;, &quot;HelpBinding&quot; )
+ helpDialog.execute()
+end sub
+
+
+sub KeyNewButton()
+ combo = bindingDialog.getControl( &quot;KeyCombo&quot; )
+ keyGroup = combo.text
+ for n = lbound ( allKeyGroupsArray() ) to ubound ( allKeyGroupsArray() )
+ if ( allKeyGroupsArray( n ) = keyGroup )then
+ keyGroupIndex = n
+ exit for
+ end if
+ next n
+ menuScriptList = bindingDialog.getControl( &quot;ScriptList&quot; )
+ script = menuScriptList.getSelectedItem()
+ scriptURI = getScriptURI( script )
+
+ keyList = bindingDialog.getControl( &quot;KeyList&quot; )
+ keyIndex = keyList.getSelectedItemPos()
+ ShortCutKeyArray() = KeyBindArrayOfArrays( keyGroupIndex )
+ keyText = ShortCutKeyArray( keyIndex )
+
+ AddNewKeyBinding( scriptURI, HasShiftKey( keyText ), HasControlKey( keyText ), ExtractKeyFromCombo( keyText ) )
+
+ KeyComboListener()
+end sub
+
+
+sub KeyDeleteButton()
+
+ keyShortCutList = bindingDialog.getControl( &quot;KeyList&quot; )
+ selectedShortCut = keyShortCutList.getSelectedItem()
+ combo = bindingDialog.getControl( &quot;KeyCombo&quot; )
+
+ keyGroup = combo.text
+ dim keyGroupIndex as Integer
+ dim selectedKeyIndex as Integer
+ for n = lbound ( allKeyGroupsArray() ) to ubound ( allKeyGroupsArray() )
+ if ( allKeyGroupsArray( n ) = keyGroup )then
+ keyGroupIndex = n
+ exit for
+ end if
+ next n
+ selectedKeyIndex = keyShortCutList.getSelectedItemPos()
+ linePosition = keyAllocationMap( keyGroupIndex, selectedKeyIndex ).Value
+ keyAllocationMap( keyGroupIndex, selectedKeyIndex ).Value = 0
+ keyAllocationMap( keyGroupIndex, selectedKeyIndex ).Name = &quot;&quot;
+ RemoveBinding( linePosition )
+ KeyComboListener()
+end sub
+
+
+sub EventNewButton()
+ eventScriptList = bindingDialog.getControl( &quot;ScriptList&quot; )
+ selectedScript = eventScriptList.getSelectedItem()
+ scriptURI = getScriptURI( selectedScript )
+ eventList = bindingDialog.getControl( &quot;EventList&quot; )
+ eventPosition = eventList.getSelectedItemPos()
+
+ allApps = bindingDialog.getControl( &quot;AllAppsOption&quot; )
+ dim isApp as boolean
+ if allApps.state = true then &apos;Application
+ isApp = true
+ else &apos;Document
+ isApp = false
+ end if
+ AddNewEventBinding( scriptURI, eventPosition, isApp )
+
+ populateEventList( eventPosition )
+ EventListListener()
+end sub
+
+
+sub EventDeleteButton()
+ eventList = bindingDialog.getControl( &quot;EventList&quot; )
+ REM Check that combo is a script
+ eventPosition = eventList.getSelectedItemPos()
+
+ allApps = bindingDialog.getControl( &quot;AllAppsOption&quot; )
+ if allApps.state = true then &apos;Application
+ linePosition = allEventTypesApp( eventPosition ).Value
+ &apos;dim eventProp as new com.sun.star.beans.PropertyValue
+ &apos;eventProp.Name = &quot;&quot;
+ &apos;eventProp.Value = 0
+ allEventTypesApp( eventPosition ).Name = &quot;&quot;
+ allEventTypesApp( eventPosition ).Value = 0
+ RemoveBinding( linePosition )
+ else &apos;Document
+ &apos;DeleteEvent( allEventTypes( eventPosition ) )
+ allEventTypesDoc( eventPosition ).Name = &quot;&quot;
+ allEventTypesDoc( eventPosition ).Value = 0
+ end if
+
+ PopulateEventList( eventPosition )
+ EventListListener()
+end sub
+
+
+sub EventOKButton
+ WriteEventsToDoc()
+ WriteXMLFromArray()
+ bindingDialog.endExecute()
+end sub
+
+
+sub HelpOKButton()
+ helpDialog.endExecute()
+end sub
+</script:module>
diff --git a/scripting/workben/bindings/calckeybinding.xml b/scripting/workben/bindings/calckeybinding.xml
new file mode 100644
index 000000000000..3e9b7ef48689
--- /dev/null
+++ b/scripting/workben/bindings/calckeybinding.xml
@@ -0,0 +1,94 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE accel:acceleratorlist PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "accelerator.dtd">
+<accel:acceleratorlist xmlns:accel="http://openoffice.org/2001/accel" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <accel:item accel:code="KEY_END" accel:shift="true" accel:mod1="true" xlink:href="slot:26532"/>
+ <accel:item accel:code="KEY_HOME" accel:shift="true" accel:mod1="true" xlink:href="slot:26531"/>
+ <accel:item accel:code="KEY_RIGHT" accel:shift="true" accel:mod1="true" xlink:href="slot:26542"/>
+ <accel:item accel:code="KEY_LEFT" accel:shift="true" accel:mod1="true" xlink:href="slot:26541"/>
+ <accel:item accel:code="KEY_UP" accel:shift="true" accel:mod1="true" xlink:href="slot:26539"/>
+ <accel:item accel:code="KEY_DOWN" accel:shift="true" accel:mod1="true" xlink:href="slot:26540"/>
+ <accel:item accel:code="KEY_F9" accel:shift="true" accel:mod1="true" xlink:href="slot:26318"/>
+ <accel:item accel:code="KEY_F5" accel:shift="true" accel:mod1="true" xlink:href="slot:26645"/>
+ <accel:item accel:code="KEY_F2" accel:shift="true" accel:mod1="true" xlink:href="slot:26089"/>
+ <accel:item accel:code="KEY_T" accel:shift="true" accel:mod1="true" xlink:href="slot:26645"/>
+ <accel:item accel:code="KEY_R" accel:shift="true" accel:mod1="true" xlink:href="slot:26012"/>
+ <accel:item accel:code="KEY_P" accel:shift="true" accel:mod1="true" xlink:href="slot:10294"/>
+ <accel:item accel:code="KEY_F" accel:shift="true" accel:mod1="true" xlink:href="slot:26612"/>
+ <accel:item accel:code="KEY_B" accel:shift="true" accel:mod1="true" xlink:href="slot:10295"/>
+ <accel:item accel:code="KEY_6" accel:shift="true" accel:mod1="true" xlink:href="slot:26052"/>
+ <accel:item accel:code="KEY_5" accel:shift="true" accel:mod1="true" xlink:href="slot:26046"/>
+ <accel:item accel:code="KEY_4" accel:shift="true" accel:mod1="true" xlink:href="slot:26045"/>
+ <accel:item accel:code="KEY_3" accel:shift="true" accel:mod1="true" xlink:href="slot:26053"/>
+ <accel:item accel:code="KEY_2" accel:shift="true" accel:mod1="true" xlink:href="slot:26055"/>
+ <accel:item accel:code="KEY_1" accel:shift="true" accel:mod1="true" xlink:href="slot:26054"/>
+ <accel:item accel:code="KEY_DIVIDE" accel:mod1="true" xlink:href="slot:26560"/>
+ <accel:item accel:code="KEY_MULTIPLY" accel:mod1="true" xlink:href="slot:26551"/>
+ <accel:item accel:code="KEY_BACKSPACE" accel:mod1="true" xlink:href="slot:26550"/>
+ <accel:item accel:code="KEY_SPACE" accel:mod1="true" xlink:href="slot:26547"/>
+ <accel:item accel:code="KEY_PAGEDOWN" accel:mod1="true" xlink:href="slot:26543"/>
+ <accel:item accel:code="KEY_PAGEUP" accel:mod1="true" xlink:href="slot:26544"/>
+ <accel:item accel:code="KEY_END" accel:mod1="true" xlink:href="slot:5741"/>
+ <accel:item accel:code="KEY_HOME" accel:mod1="true" xlink:href="slot:5742"/>
+ <accel:item accel:code="KEY_RIGHT" accel:mod1="true" xlink:href="slot:26538"/>
+ <accel:item accel:code="KEY_LEFT" accel:mod1="true" xlink:href="slot:26537"/>
+ <accel:item accel:code="KEY_UP" accel:mod1="true" xlink:href="slot:26535"/>
+ <accel:item accel:code="KEY_DOWN" accel:mod1="true" xlink:href="slot:26536"/>
+ <accel:item accel:code="KEY_F12" accel:mod1="true" xlink:href="slot:26332"/>
+ <accel:item accel:code="KEY_F11" accel:mod1="true" xlink:href="slot:5573"/>
+ <accel:item accel:code="KEY_F8" accel:mod1="true" xlink:href="slot:26245"/>
+ <accel:item accel:code="KEY_F7" accel:mod1="true" xlink:href="slot:10245"/>
+ <accel:item accel:code="KEY_F3" accel:mod1="true" xlink:href="slot:26271"/>
+ <accel:item accel:code="KEY_F2" accel:mod1="true" xlink:href="slot:26152"/>
+ <accel:item accel:code="KEY_Z" accel:mod1="true" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_Y" accel:mod1="true" xlink:href="slot:5700"/>
+ <accel:item accel:code="KEY_U" accel:mod1="true" xlink:href="slot:10014"/>
+ <accel:item accel:code="KEY_R" accel:mod1="true" xlink:href="slot:26372"/>
+ <accel:item accel:code="KEY_L" accel:mod1="true" xlink:href="slot:26371"/>
+ <accel:item accel:code="KEY_J" accel:mod1="true" xlink:href="slot:26374"/>
+ <accel:item accel:code="KEY_I" accel:mod1="true" xlink:href="slot:10008"/>
+ <accel:item accel:code="KEY_E" accel:mod1="true" xlink:href="slot:26373"/>
+ <accel:item accel:code="KEY_D" accel:mod1="true" xlink:href="slot:26610"/>
+ <accel:item accel:code="KEY_B" accel:mod1="true" xlink:href="slot:10009"/>
+ <accel:item accel:code="KEY_5" accel:mod1="true" xlink:href="slot:10035"/>
+ <accel:item accel:code="KEY_2" accel:mod1="true" xlink:href="slot:10036"/>
+ <accel:item accel:code="KEY_1" accel:mod1="true" xlink:href="slot:10034"/>
+ <accel:item accel:code="KEY_BACKSPACE" accel:shift="true" xlink:href="slot:26549"/>
+ <accel:item accel:code="KEY_SPACE" accel:shift="true" xlink:href="slot:26548"/>
+ <accel:item accel:code="KEY_PAGEDOWN" accel:shift="true" xlink:href="slot:26525"/>
+ <accel:item accel:code="KEY_PAGEUP" accel:shift="true" xlink:href="slot:26526"/>
+ <accel:item accel:code="KEY_END" accel:shift="true" xlink:href="slot:26534"/>
+ <accel:item accel:code="KEY_HOME" accel:shift="true" xlink:href="slot:26533"/>
+ <accel:item accel:code="KEY_RIGHT" accel:shift="true" xlink:href="slot:26524"/>
+ <accel:item accel:code="KEY_LEFT" accel:shift="true" xlink:href="slot:26523"/>
+ <accel:item accel:code="KEY_UP" accel:shift="true" xlink:href="slot:26522"/>
+ <accel:item accel:code="KEY_DOWN" accel:shift="true" xlink:href="slot:26521"/>
+ <accel:item accel:code="KEY_F11" accel:shift="true" xlink:href="slot:5538"/>
+ <accel:item accel:code="KEY_F8" accel:shift="true" xlink:href="slot:26122"/>
+ <accel:item accel:code="KEY_F7" accel:shift="true" xlink:href="slot:26456"/>
+ <accel:item accel:code="KEY_F5" accel:shift="true" xlink:href="slot:26458"/>
+ <accel:item accel:code="KEY_F4" accel:shift="true" xlink:href="slot:26609"/>
+ <accel:item accel:code="KEY_REPEAT" xlink:href="slot:5702"/>
+ <accel:item accel:code="KEY_UNDO" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_INSERT" xlink:href="slot:26265"/>
+ <accel:item accel:code="KEY_BACKSPACE" xlink:href="slot:26553"/>
+ <accel:item accel:code="KEY_ESCAPE" xlink:href="slot:26557"/>
+ <accel:item accel:code="KEY_PAGEDOWN" xlink:href="slot:5735"/>
+ <accel:item accel:code="KEY_PAGEUP" xlink:href="slot:5736"/>
+ <accel:item accel:code="KEY_END" xlink:href="slot:5746"/>
+ <accel:item accel:code="KEY_HOME" xlink:href="slot:5745"/>
+ <accel:item accel:code="KEY_RIGHT" xlink:href="slot:5734"/>
+ <accel:item accel:code="KEY_LEFT" xlink:href="slot:5733"/>
+ <accel:item accel:code="KEY_UP" xlink:href="slot:5732"/>
+ <accel:item accel:code="KEY_DOWN" xlink:href="slot:5731"/>
+ <accel:item accel:code="KEY_F12" xlink:href="slot:26331"/>
+ <accel:item accel:code="KEY_F11" xlink:href="slot:5539"/>
+ <accel:item accel:code="KEY_F9" xlink:href="slot:26304"/>
+ <accel:item accel:code="KEY_F8" xlink:href="slot:26123"/>
+ <accel:item accel:code="KEY_F7" xlink:href="slot:10243"/>
+ <accel:item accel:code="KEY_F5" xlink:href="slot:10366"/>
+ <accel:item accel:code="KEY_F4" xlink:href="slot:6660"/>
+ <accel:item accel:code="KEY_F2" xlink:href="slot:26552"/>
+ <accel:item accel:code="KEY_BACKSPACE" accel:mod2="true" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_TAB" xlink:href="slot:26545"/>
+ <accel:item accel:code="KEY_TAB" accel:shift="true" xlink:href="slot:26546"/>
+</accel:acceleratorlist> \ No newline at end of file
diff --git a/scripting/workben/bindings/calcmenubar.xml b/scripting/workben/bindings/calcmenubar.xml
new file mode 100644
index 000000000000..21f6404c13a5
--- /dev/null
+++ b/scripting/workben/bindings/calcmenubar.xml
@@ -0,0 +1,319 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE menu:menubar PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "menubar.dtd">
+<menu:menubar xmlns:menu="http://openoffice.org/2001/menu" menu:id="menubar">
+ <menu:menu menu:id="slot:5510" menu:label="~File">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5537" menu:helpid="5537" menu:label="~New"/>
+ <menu:menuitem menu:id="slot:5501" menu:helpid="5501" menu:label="~Open..."/>
+ <menu:menuitem menu:id="slot:6381" menu:helpid="6381" menu:label="A~utoPilot"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5503" menu:helpid="5503" menu:label="~Close"/>
+ <menu:menuitem menu:id="slot:5505" menu:helpid="5505" menu:label="~Save"/>
+ <menu:menuitem menu:id="slot:5502" menu:helpid="5502" menu:label="Save ~As..."/>
+ <menu:menuitem menu:id="slot:5309" menu:helpid="5309" menu:label="Sa~ve All"/>
+ <menu:menuitem menu:id="slot:5508" menu:helpid="5508" menu:label="Reload"/>
+ <menu:menuitem menu:id="slot:6583" menu:helpid="6583" menu:label="Versions..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5829" menu:helpid="5829" menu:label="Expor~t..."/>
+ <menu:menuitem menu:id="slot:6673" menu:helpid="6673" menu:label="Expor~t as PDF..."/>
+ <menu:menu menu:id="slot:36" menu:label="Sen~d">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5331" menu:helpid="5331" menu:label="Document as ~E-mail..."/>
+ <menu:menuitem menu:id="slot:6672" menu:helpid="6672" menu:label="Document as P~DF Attachment..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5535" menu:helpid="5535" menu:label="Propert~ies..."/>
+ <menu:menu menu:id="slot:39" menu:label="~Templates">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5540" menu:helpid="5540" menu:label="~Organize..."/>
+ <menu:menuitem menu:id="slot:6655" menu:helpid="6655" menu:label="~Address Book Source..."/>
+ <menu:menuitem menu:id="slot:5538" menu:helpid="5538" menu:label="~Save..."/>
+ <menu:menuitem menu:id="slot:5594" menu:helpid="5594" menu:label="~Edit..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5325" menu:helpid="5325" menu:label="Pa~ge Preview"/>
+ <menu:menuitem menu:id="slot:5504" menu:helpid="5504" menu:label="~Print..."/>
+ <menu:menuitem menu:id="slot:5302" menu:helpid="5302" menu:label="P~rinter Settings..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5300" menu:helpid="5300" menu:label="E~xit"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:2" menu:label="~Edit">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5701" menu:helpid="5701" menu:label="Can&apos;t Undo"/>
+ <menu:menuitem menu:id="slot:5700" menu:helpid="5700" menu:label="Can&apos;t Restore"/>
+ <menu:menuitem menu:id="slot:5702" menu:helpid="5702" menu:label="~Repeat"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5710" menu:helpid="5710" menu:label="Cu~t"/>
+ <menu:menuitem menu:id="slot:5711" menu:helpid="5711" menu:label="~Copy"/>
+ <menu:menuitem menu:id="slot:5712" menu:helpid="5712" menu:label="~Paste"/>
+ <menu:menuitem menu:id="slot:26220" menu:helpid="26220" menu:label="Paste ~Special..."/>
+ <menu:menuitem menu:id="slot:5723" menu:helpid="5723" menu:label="Select ~All"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:37" menu:label="Chan~ges">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26238" menu:helpid="26238" menu:label="~Record"/>
+ <menu:menuitem menu:id="slot:26084" menu:helpid="26084" menu:label="~Protect Records..."/>
+ <menu:menuitem menu:id="slot:26239" menu:helpid="26239" menu:label="Sho~w..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26258" menu:helpid="26258" menu:label="~Accept or Reject..."/>
+ <menu:menuitem menu:id="slot:26259" menu:helpid="26259" menu:label="~Comments..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:6587" menu:helpid="6587" menu:label="~Merge Document..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:6586" menu:helpid="6586" menu:label="Co~mpare Document..."/>
+ <menu:menuitem menu:id="slot:5961" menu:helpid="5961" menu:label="~Find &amp; Replace..."/>
+ <menu:menuitem menu:id="slot:10366" menu:helpid="10366" menu:label="~Navigator"/>
+ <menu:menuitem menu:id="slot:26235" menu:helpid="26235" menu:label="~Headers &amp; Footers..."/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:3" menu:label="Fill">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26224" menu:helpid="26224" menu:label="~Down"/>
+ <menu:menuitem menu:id="slot:26225" menu:helpid="26225" menu:label="~Right"/>
+ <menu:menuitem menu:id="slot:26226" menu:helpid="26226" menu:label="~Up"/>
+ <menu:menuitem menu:id="slot:26227" menu:helpid="26227" menu:label="~Left"/>
+ <menu:menuitem menu:id="slot:26228" menu:helpid="26228" menu:label="~Sheet..."/>
+ <menu:menuitem menu:id="slot:26229" menu:helpid="26229" menu:label="S~eries..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:5713" menu:helpid="5713" menu:label="Delete C~ontents..."/>
+ <menu:menuitem menu:id="slot:26222" menu:helpid="26222" menu:label="Delete C~ells..."/>
+ <menu:menu menu:id="slot:38" menu:label="Shee~t">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26348" menu:helpid="26348" menu:label="~Move/Copy..."/>
+ <menu:menuitem menu:id="slot:26090" menu:helpid="26090" menu:label="~Select..."/>
+ <menu:menuitem menu:id="slot:26223" menu:helpid="26223" menu:label="~Delete..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:4" menu:label="Delete Manual Break">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26263" menu:helpid="26263" menu:label="~Row Break"/>
+ <menu:menuitem menu:id="slot:26264" menu:helpid="26264" menu:label="~Column Break"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26060" menu:helpid="26060" menu:label="Lin~ks..."/>
+ <menu:menuitem menu:id="slot:6314" menu:helpid="6314" menu:label="P~lug-in"/>
+ <menu:menuitem menu:id="slot:10371" menu:helpid="10371" menu:label="ImageMap"/>
+ <menu:menuitem menu:id="slot:5575" menu:helpid="5575" menu:label="~Object"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5" menu:label="~View">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10000" menu:helpid="10000" menu:label="~Zoom..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:6660" menu:helpid="6660" menu:label="~Data Sources"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:29" menu:label="~Toolbars">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5910" menu:helpid="5910" menu:label="~Function Bar"/>
+ <menu:menuitem menu:id="slot:5905" menu:helpid="5905" menu:label="~Object Bar"/>
+ <menu:menuitem menu:id="slot:5909" menu:helpid="5909" menu:label="Main ~Toolbar"/>
+ <menu:menuitem menu:id="slot:10360" menu:helpid="10360" menu:label="~Hyperlink Bar"/>
+ <menu:menuitem menu:id="slot:26241" menu:helpid="26241" menu:label="For~mula Bar"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5908" menu:helpid="5908" menu:label="Customi~ze..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:5920" menu:helpid="5920" menu:label="~Status Bar"/>
+ <menu:menuitem menu:id="slot:6680" menu:helpid="6680" menu:label="~Input Method Status"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26242" menu:helpid="26242" menu:label="C~olumn &amp; Row Headers"/>
+ <menu:menuitem menu:id="slot:26245" menu:helpid="26245" menu:label="~Value Highlighting"/>
+ <menu:menuitem menu:id="slot:26247" menu:helpid="26247" menu:label="~Page Break Preview"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5627" menu:helpid="5627" menu:label="F~ull Screen"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:6" menu:label="~Insert">
+ <menu:menupopup>
+ <menu:menu menu:id="slot:7" menu:label="~Manual Break">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26261" menu:helpid="26261" menu:label="~Row Break"/>
+ <menu:menuitem menu:id="slot:26262" menu:helpid="26262" menu:label="~Column Break"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:26266" menu:helpid="26266" menu:label="~Cells..."/>
+ <menu:menuitem menu:id="slot:26267" menu:helpid="26267" menu:label="~Rows"/>
+ <menu:menuitem menu:id="slot:26268" menu:helpid="26268" menu:label="Co~lumns"/>
+ <menu:menuitem menu:id="slot:26269" menu:helpid="26269" menu:label="~Sheet..."/>
+ <menu:menuitem menu:id="slot:26085" menu:helpid="26085" menu:label="E~xternal Data..."/>
+ <menu:menuitem menu:id="slot:10503" menu:helpid="10503" menu:label="S~pecial Character..."/>
+ <menu:menuitem menu:id="slot:5678" menu:helpid="5678" menu:label="~Hyperlink"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26152" menu:helpid="26152" menu:label="~Function..."/>
+ <menu:menuitem menu:id="slot:26248" menu:helpid="26248" menu:label="F~unction List"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:8" menu:label="~Names">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26271" menu:helpid="26271" menu:label="~Define..."/>
+ <menu:menuitem menu:id="slot:26272" menu:helpid="26272" menu:label="~Insert..."/>
+ <menu:menuitem menu:id="slot:26273" menu:helpid="26273" menu:label="~Create..."/>
+ <menu:menuitem menu:id="slot:26629" menu:helpid="26629" menu:label="~Labels..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:26276" menu:helpid="26276" menu:label="Not~e"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:30" menu:label="~Graphics">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10241" menu:helpid="10241" menu:label="From ~File..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:1" menu:label="~Object">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5561" menu:helpid="5561" menu:label="~OLE Object..."/>
+ <menu:menuitem menu:id="slot:5672" menu:helpid="5672" menu:label="~Plug-in..."/>
+ <menu:menuitem menu:id="slot:5676" menu:helpid="5676" menu:label="~Sound..."/>
+ <menu:menuitem menu:id="slot:5677" menu:helpid="5677" menu:label="~Video..."/>
+ <menu:menuitem menu:id="slot:5673" menu:helpid="5673" menu:label="~Applet..."/>
+ <menu:menuitem menu:id="slot:26063" menu:helpid="26063" menu:label="~Formula..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:26155" menu:helpid="26155" menu:label="Ch~art..."/>
+ <menu:menuitem menu:id="slot:5563" menu:helpid="5563" menu:label="Float~ing Frame"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5780" menu:label="F~ormat">
+ <menu:menupopup/>
+ </menu:menu>
+ <menu:menu menu:id="slot:6677" menu:label="~Tools">
+ <menu:menupopup>
+ <menu:menu menu:id="slot:31" menu:label="~Spellcheck">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10243" menu:helpid="10243" menu:label="~Check..."/>
+ <menu:menuitem menu:id="slot:12021" menu:helpid="12021" menu:label="~AutoSpellcheck"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10245" menu:helpid="10245" menu:label="~Thesaurus..."/>
+ <menu:menuitem menu:id="slot:26087" menu:helpid="26087" menu:label="~Hyphenation..."/>
+ <menu:menu menu:id="slot:15" menu:label="~Detective">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26456" menu:helpid="26456" menu:label="Trace ~Precedents"/>
+ <menu:menuitem menu:id="slot:26457" menu:helpid="26457" menu:label="~Remove Precedents"/>
+ <menu:menuitem menu:id="slot:26458" menu:helpid="26458" menu:label="~Trace Dependents"/>
+ <menu:menuitem menu:id="slot:26459" menu:helpid="26459" menu:label="Remove ~Dependents"/>
+ <menu:menuitem menu:id="slot:26461" menu:helpid="26461" menu:label="Remove ~All Traces"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26460" menu:helpid="26460" menu:label="Trace ~Error"/>
+ <menu:menuitem menu:id="slot:26469" menu:helpid="26469" menu:label="~Mark Invalid Data"/>
+ <menu:menuitem menu:id="slot:26470" menu:helpid="26470" menu:label="Refresh Tra~ces"/>
+ <menu:menuitem menu:id="slot:26471" menu:helpid="26471" menu:label="A~utoRefresh"/>
+ <menu:menuitem menu:id="slot:26462" menu:helpid="26462" menu:label="~Fill Mode"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10424" menu:helpid="10424" menu:label="~AutoCorrect..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26153" menu:helpid="26153" menu:label="~Goal Seek..."/>
+ <menu:menuitem menu:id="slot:26312" menu:helpid="26312" menu:label="Sc~enarios..."/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:16" menu:label="~Protect Document">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26306" menu:helpid="26306" menu:label="~Sheet..."/>
+ <menu:menuitem menu:id="slot:26307" menu:helpid="26307" menu:label="~Document..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:32" menu:label="Cell Co~ntents">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26304" menu:helpid="26304" menu:label="~Recalculate"/>
+ <menu:menuitem menu:id="slot:26303" menu:helpid="26303" menu:label="Auto~Calculate"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26319" menu:helpid="26319" menu:label="~AutoInput"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5960" menu:helpid="5960" menu:label="~Gallery"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10882" menu:helpid="10882" menu:label="~Data Sources..."/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:1" menu:label="~Macros">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:6669" menu:helpid="6669" menu:label="Record Macro"/>
+ <menu:menuitem menu:id="slot:5959" menu:helpid="5959" menu:label="~Macro..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10958" menu:helpid="10958" menu:label="~XML Filter Settings..."/>
+ <menu:menuitem menu:id="slot:5904" menu:helpid="5904" menu:label="~Configure..."/>
+ <menu:menu menu:id="slot:4" menu:label="Scripting Add-ons">
+ <menu:menupopup>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteMenuBinding()" menu:label="Assign Script to ~Menu..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteKeyBinding" menu:label="Assign Script to ~Key..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteEventBinding()" menu:label="Assign Script to ~Event..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteEditDebug" menu:label="Edit/De~bug Scripts..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.RefreshAllScripts()" menu:label="~Refresh All Scripts"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:31630" menu:helpid="31630" menu:label="~Options..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:10" menu:label="~Data">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26320" menu:helpid="26320" menu:label="~Define Range..."/>
+ <menu:menuitem menu:id="slot:26321" menu:helpid="26321" menu:label="Select ~Range..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26322" menu:helpid="26322" menu:label="~Sort..."/>
+ <menu:menu menu:id="slot:11" menu:label="~Filter">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26325" menu:helpid="26325" menu:label="Auto~Filter"/>
+ <menu:menuitem menu:id="slot:26323" menu:helpid="26323" menu:label="~Standard Filter..."/>
+ <menu:menuitem menu:id="slot:26324" menu:helpid="26324" menu:label="~Advanced Filter..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26326" menu:helpid="26326" menu:label="~Remove Filter"/>
+ <menu:menuitem menu:id="slot:26341" menu:helpid="26341" menu:label="~Hide AutoFilter"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:26328" menu:helpid="26328" menu:label="Sub~totals..."/>
+ <menu:menuitem menu:id="slot:26625" menu:helpid="26625" menu:label="~Validity..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26154" menu:helpid="26154" menu:label="~Multiple Operations..."/>
+ <menu:menuitem menu:id="slot:26150" menu:helpid="26150" menu:label="~Consolidate..."/>
+ <menu:menu menu:id="slot:12" menu:label="~Outline">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26329" menu:helpid="26329" menu:label="~Hide Details"/>
+ <menu:menuitem menu:id="slot:26330" menu:helpid="26330" menu:label="~Show Details"/>
+ <menu:menuitem menu:id="slot:26331" menu:helpid="26331" menu:label="~Group..."/>
+ <menu:menuitem menu:id="slot:26332" menu:helpid="26332" menu:label="~Ungroup..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26333" menu:helpid="26333" menu:label="~AutoOutline"/>
+ <menu:menuitem menu:id="slot:10234" menu:helpid="10234" menu:label="~Remove"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:13" menu:label="Data~Pilot">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:26151" menu:helpid="26151" menu:label="~Start..."/>
+ <menu:menuitem menu:id="slot:26314" menu:helpid="26314" menu:label="~Refresh"/>
+ <menu:menuitem menu:id="slot:26315" menu:helpid="26315" menu:label="~Delete"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26643" menu:helpid="26643" menu:label="R~efresh Range"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5610" menu:label="~Window">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5620" menu:helpid="5620" menu:label="~New Window"/>
+ <menu:menuitem menu:id="slot:5621" menu:helpid="5621" menu:label="Close Window"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:26069" menu:helpid="26069" menu:label="~Split"/>
+ <menu:menuitem menu:id="slot:26070" menu:helpid="26070" menu:label="~Freeze"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5410" menu:label="~Help">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5401" menu:helpid="5401" menu:label="~Contents"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5962" menu:helpid="5962" menu:label="Help ~Agent"/>
+ <menu:menuitem menu:id="slot:5404" menu:helpid="5404" menu:label="~Tips"/>
+ <menu:menuitem menu:id="slot:5403" menu:helpid="5403" menu:label="~Extended Tips"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:6683" menu:helpid="6683" menu:label="~Support"/>
+ <menu:menuitem menu:id="slot:6537" menu:helpid="6537" menu:label="~Registration..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5301" menu:helpid="5301" menu:label="A~bout OpenOffice.org..."/>
+ </menu:menupopup>
+ </menu:menu>
+</menu:menubar>
diff --git a/scripting/workben/bindings/dialog.xlb b/scripting/workben/bindings/dialog.xlb
new file mode 100644
index 000000000000..1445c98b8cab
--- /dev/null
+++ b/scripting/workben/bindings/dialog.xlb
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE library:library PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "library.dtd">
+<library:library xmlns:library="http://openoffice.org/2000/library" library:name="ScriptBindingLibrary" library:readonly="false" library:passwordprotected="false">
+ <library:element library:name="Highlight"/>
+ <library:element library:name="MacroEditor"/>
+</library:library>
diff --git a/scripting/workben/bindings/drawkeybinding.xml b/scripting/workben/bindings/drawkeybinding.xml
new file mode 100644
index 000000000000..e7d0bbf73176
--- /dev/null
+++ b/scripting/workben/bindings/drawkeybinding.xml
@@ -0,0 +1,58 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE accel:acceleratorlist PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "accelerator.dtd">
+<accel:acceleratorlist xmlns:accel="http://openoffice.org/2001/accel" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <accel:item accel:code="KEY_F8" accel:shift="true" accel:mod1="true" xlink:href="slot:10367"/>
+ <accel:item accel:code="KEY_P" accel:shift="true" accel:mod1="true" xlink:href="slot:10294"/>
+ <accel:item accel:code="KEY_N" accel:shift="true" accel:mod1="true" xlink:href="slot:5500"/>
+ <accel:item accel:code="KEY_K" accel:shift="true" accel:mod1="true" xlink:href="slot:27026"/>
+ <accel:item accel:code="KEY_G" accel:shift="true" accel:mod1="true" xlink:href="slot:10454"/>
+ <accel:item accel:code="KEY_B" accel:shift="true" accel:mod1="true" xlink:href="slot:10295"/>
+ <accel:item accel:code="KEY_SUBTRACT" accel:mod1="true" xlink:href="slot:27032"/>
+ <accel:item accel:code="KEY_ADD" accel:mod1="true" xlink:href="slot:27031"/>
+ <accel:item accel:code="KEY_INSERT" accel:mod1="true" xlink:href="slot:5711"/>
+ <accel:item accel:code="KEY_F11" accel:mod1="true" xlink:href="slot:5573"/>
+ <accel:item accel:code="KEY_F7" accel:mod1="true" xlink:href="slot:10245"/>
+ <accel:item accel:code="KEY_F3" accel:mod1="true" xlink:href="slot:27097"/>
+ <accel:item accel:code="KEY_Z" accel:mod1="true" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_Y" accel:mod1="true" xlink:href="slot:5700"/>
+ <accel:item accel:code="KEY_X" accel:mod1="true" xlink:href="slot:5710"/>
+ <accel:item accel:code="KEY_V" accel:mod1="true" xlink:href="slot:5712"/>
+ <accel:item accel:code="KEY_U" accel:mod1="true" xlink:href="slot:10014"/>
+ <accel:item accel:code="KEY_S" accel:mod1="true" xlink:href="slot:5505"/>
+ <accel:item accel:code="KEY_R" accel:mod1="true" xlink:href="slot:10029"/>
+ <accel:item accel:code="KEY_Q" accel:mod1="true" xlink:href="slot:5300"/>
+ <accel:item accel:code="KEY_P" accel:mod1="true" xlink:href="slot:5504"/>
+ <accel:item accel:code="KEY_O" accel:mod1="true" xlink:href="slot:5501"/>
+ <accel:item accel:code="KEY_L" accel:mod1="true" xlink:href="slot:10028"/>
+ <accel:item accel:code="KEY_J" accel:mod1="true" xlink:href="slot:10031"/>
+ <accel:item accel:code="KEY_I" accel:mod1="true" xlink:href="slot:10008"/>
+ <accel:item accel:code="KEY_E" accel:mod1="true" xlink:href="slot:10030"/>
+ <accel:item accel:code="KEY_C" accel:mod1="true" xlink:href="slot:5711"/>
+ <accel:item accel:code="KEY_B" accel:mod1="true" xlink:href="slot:10009"/>
+ <accel:item accel:code="KEY_5" accel:mod1="true" xlink:href="slot:10035"/>
+ <accel:item accel:code="KEY_2" accel:mod1="true" xlink:href="slot:10036"/>
+ <accel:item accel:code="KEY_1" accel:mod1="true" xlink:href="slot:10034"/>
+ <accel:item accel:code="KEY_DELETE" accel:shift="true" xlink:href="slot:5710"/>
+ <accel:item accel:code="KEY_INSERT" accel:shift="true" xlink:href="slot:5712"/>
+ <accel:item accel:code="KEY_F3" accel:shift="true" xlink:href="slot:27004"/>
+ <accel:item accel:code="KEY_REPEAT" xlink:href="slot:5702"/>
+ <accel:item accel:code="KEY_UNDO" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_PASTE" xlink:href="slot:5712"/>
+ <accel:item accel:code="KEY_COPY" xlink:href="slot:5711"/>
+ <accel:item accel:code="KEY_CUT" xlink:href="slot:5710"/>
+ <accel:item accel:code="KEY_OPEN" xlink:href="slot:5501"/>
+ <accel:item accel:code="KEY_DELETE" xlink:href="slot:5713"/>
+ <accel:item accel:code="KEY_F11" xlink:href="slot:5539"/>
+ <accel:item accel:code="KEY_F8" xlink:href="slot:10126"/>
+ <accel:item accel:code="KEY_F7" xlink:href="slot:10243"/>
+ <accel:item accel:code="KEY_F5" xlink:href="slot:10366"/>
+ <accel:item accel:code="KEY_F4" xlink:href="slot:10087"/>
+ <accel:item accel:code="KEY_F3" xlink:href="slot:27096"/>
+ <accel:item accel:code="KEY_F2" xlink:href="slot:10006"/>
+ <accel:item accel:code="KEY_BACKSPACE" accel:mod2="true" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_ADD" accel:shift="true" accel:mod1="true" xlink:href="slot:10286"/>
+ <accel:item accel:code="KEY_SUBTRACT" accel:shift="true" accel:mod1="true" xlink:href="slot:10287"/>
+ <accel:item accel:code="KEY_G" accel:shift="true" accel:mod1="true" accel:mod2="true" xlink:href="slot:10455"/>
+ <accel:item accel:code="KEY_9" accel:shift="true" accel:mod1="true" accel:mod2="true" xlink:href="slot:10703"/>
+ <accel:item accel:code="KEY_K" accel:shift="true" accel:mod1="true" accel:mod2="true" xlink:href="slot:27082"/>
+</accel:acceleratorlist> \ No newline at end of file
diff --git a/scripting/workben/bindings/drawmenubar.xml b/scripting/workben/bindings/drawmenubar.xml
new file mode 100644
index 000000000000..c1c644fe8374
--- /dev/null
+++ b/scripting/workben/bindings/drawmenubar.xml
@@ -0,0 +1,354 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE menu:menubar PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "menubar.dtd">
+<menu:menubar xmlns:menu="http://openoffice.org/2001/menu" menu:id="menubar">
+ <menu:menu menu:id="slot:5510" menu:label="~File">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5537" menu:helpid="5537" menu:label="~New"/>
+ <menu:menuitem menu:id="slot:5501" menu:helpid="5501" menu:label="~Open..."/>
+ <menu:menuitem menu:id="slot:6381" menu:helpid="6381" menu:label="A~utoPilot"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5503" menu:helpid="5503" menu:label="~Close"/>
+ <menu:menuitem menu:id="slot:5505" menu:helpid="5505" menu:label="~Save"/>
+ <menu:menuitem menu:id="slot:5502" menu:helpid="5502" menu:label="Save ~As..."/>
+ <menu:menuitem menu:id="slot:5309" menu:helpid="5309" menu:label="Sa~ve All"/>
+ <menu:menuitem menu:id="slot:5508" menu:helpid="5508" menu:label="Reload"/>
+ <menu:menuitem menu:id="slot:6583" menu:helpid="6583" menu:label="Versions..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5829" menu:helpid="5829" menu:label="~Export..."/>
+ <menu:menuitem menu:id="slot:6673" menu:helpid="6673" menu:label="Export as PDF..."/>
+ <menu:menu menu:id="slot:98" menu:label="Sen~d">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5331" menu:helpid="5331" menu:label="Document as ~E-mail..."/>
+ <menu:menuitem menu:id="slot:6672" menu:helpid="6672" menu:label="Document as P~DF Attachment..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5535" menu:helpid="5535" menu:label="Propert~ies..."/>
+ <menu:menu menu:id="slot:103" menu:label="~Templates">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5540" menu:helpid="5540" menu:label="~Organize..."/>
+ <menu:menuitem menu:id="slot:6655" menu:helpid="6655" menu:label="~Address Book Source..."/>
+ <menu:menuitem menu:id="slot:5538" menu:helpid="5538" menu:label="~Save..."/>
+ <menu:menuitem menu:id="slot:5594" menu:helpid="5594" menu:label="~Edit..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5504" menu:helpid="5504" menu:label="~Print..."/>
+ <menu:menuitem menu:id="slot:5302" menu:helpid="5302" menu:label="P~rinter Settings..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5300" menu:helpid="5300" menu:label="E~xit"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:20" menu:label="~Edit">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5701" menu:helpid="5701" menu:label="Can&apos;t Undo"/>
+ <menu:menuitem menu:id="slot:5700" menu:helpid="5700" menu:label="Can&apos;t Restore"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5710" menu:helpid="5710" menu:label="Cu~t"/>
+ <menu:menuitem menu:id="slot:5711" menu:helpid="5711" menu:label="~Copy"/>
+ <menu:menuitem menu:id="slot:5712" menu:helpid="5712" menu:label="~Paste"/>
+ <menu:menuitem menu:id="slot:27003" menu:helpid="27003" menu:label="Paste ~Special..."/>
+ <menu:menuitem menu:id="slot:5723" menu:helpid="5723" menu:label="Select ~All"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5961" menu:helpid="5961" menu:label="~Find &amp; Replace..."/>
+ <menu:menuitem menu:id="slot:10366" menu:helpid="10366" menu:label="Na~vigator"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27004" menu:helpid="27004" menu:label="Duplicat~e..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10126" menu:helpid="10126" menu:label="Poi~nts"/>
+ <menu:menuitem menu:id="slot:27301" menu:helpid="27301" menu:label="~Glue Points"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27319" menu:helpid="27319" menu:label="Cross-fading..."/>
+ <menu:menuitem menu:id="slot:27362" menu:helpid="27362" menu:label="F~ields..."/>
+ <menu:menuitem menu:id="slot:27080" menu:helpid="27080" menu:label="D~elete Slide..."/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:340" menu:label="La~yer">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27043" menu:helpid="27043" menu:label="~Insert"/>
+ <menu:menuitem menu:id="slot:27048" menu:helpid="27048" menu:label="~Modify"/>
+ <menu:menuitem menu:id="slot:27081" menu:helpid="27081" menu:label="Delete"/>
+ <menu:menuitem menu:id="slot:27269" menu:helpid="27269" menu:label="~Rename"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27005" menu:helpid="27005" menu:label="Lin~ks..."/>
+ <menu:menuitem menu:id="slot:6314" menu:helpid="6314" menu:label="P~lug-in"/>
+ <menu:menuitem menu:id="slot:10371" menu:helpid="10371" menu:label="ImageMap"/>
+ <menu:menuitem menu:id="slot:5575" menu:helpid="5575" menu:label="~Object"/>
+ <menu:menuitem menu:id="slot:27382" menu:helpid="27382" menu:label="H~yperlink..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:23" menu:label="~View">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10000" menu:helpid="10000" menu:label="~Zoom..."/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:92" menu:label="~Toolbars">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5910" menu:helpid="5910" menu:label="~Function Bar"/>
+ <menu:menuitem menu:id="slot:5905" menu:helpid="5905" menu:label="~Object Bar"/>
+ <menu:menuitem menu:id="slot:5909" menu:helpid="5909" menu:label="Main ~Toolbar"/>
+ <menu:menuitem menu:id="slot:10360" menu:helpid="10360" menu:label="~Hyperlink Bar"/>
+ <menu:menuitem menu:id="slot:5911" menu:helpid="5911" menu:label="Optio~n Bar"/>
+ <menu:menuitem menu:id="slot:10417" menu:helpid="10417" menu:label="~Color Bar"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5908" menu:helpid="5908" menu:label="Customi~ze..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:27040" menu:helpid="27040" menu:label="~Rulers"/>
+ <menu:menuitem menu:id="slot:5920" menu:helpid="5920" menu:label="~Status Bar"/>
+ <menu:menuitem menu:id="slot:6680" menu:helpid="6680" menu:label="~Input Method Status"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:100" menu:label="~Display Quality">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27366" menu:helpid="27366" menu:label="~Color"/>
+ <menu:menuitem menu:id="slot:27367" menu:helpid="27367" menu:label="~Grayscale"/>
+ <menu:menuitem menu:id="slot:27368" menu:helpid="27368" menu:label="~Black and White"/>
+ <menu:menuitem menu:id="slot:27400" menu:helpid="27400" menu:label="~High Contrast"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:27327" menu:helpid="27327" menu:label="~Preview"/>
+ <menu:menu menu:id="slot:101" menu:label="Pre~view Mode">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27369" menu:helpid="27369" menu:label="~Color"/>
+ <menu:menuitem menu:id="slot:27370" menu:helpid="27370" menu:label="~Grayscale"/>
+ <menu:menuitem menu:id="slot:27371" menu:helpid="27371" menu:label="~Black and White"/>
+ <menu:menuitem menu:id="slot:27401" menu:helpid="27401" menu:label="~High Contrast"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27049" menu:helpid="27049" menu:label="S~lide"/>
+ <menu:menuitem menu:id="slot:27050" menu:helpid="27050" menu:label="La~yer"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:338" menu:label="~Grid">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27322" menu:helpid="27322" menu:label="~Visible Grid"/>
+ <menu:menuitem menu:id="slot:27154" menu:helpid="27154" menu:label="Snap to Grid"/>
+ <menu:menuitem menu:id="slot:27323" menu:helpid="27323" menu:label="Grid to ~Front"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:339" menu:label="~Snap Lines">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27324" menu:helpid="27324" menu:label="~Snap Lines Visible"/>
+ <menu:menuitem menu:id="slot:27152" menu:helpid="27152" menu:label="Snap to Snap Lines"/>
+ <menu:menuitem menu:id="slot:27325" menu:helpid="27325" menu:label="Snap Lines to Front"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5627" menu:helpid="5627" menu:label="F~ull Screen"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:21" menu:label="~Insert">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27014" menu:helpid="27014" menu:label="Slid~e"/>
+ <menu:menuitem menu:id="slot:27342" menu:helpid="27342" menu:label="D~uplicate Slide"/>
+ <menu:menuitem menu:id="slot:27043" menu:helpid="27043" menu:label="~Layer..."/>
+ <menu:menuitem menu:id="slot:27038" menu:helpid="27038" menu:label="~Insert Snap Point/Line..."/>
+ <menu:menu menu:id="slot:99" menu:label="Fiel~ds">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27358" menu:helpid="27358" menu:label="~Date (fixed)"/>
+ <menu:menuitem menu:id="slot:27357" menu:helpid="27357" menu:label="Dat~e (variable)"/>
+ <menu:menuitem menu:id="slot:27360" menu:helpid="27360" menu:label="~Time (fixed)"/>
+ <menu:menuitem menu:id="slot:27359" menu:helpid="27359" menu:label="T~ime (variable)"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27364" menu:helpid="27364" menu:label="~Author"/>
+ <menu:menuitem menu:id="slot:27361" menu:helpid="27361" menu:label="~Page Number"/>
+ <menu:menuitem menu:id="slot:27363" menu:helpid="27363" menu:label="~File Name"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:27019" menu:helpid="27019" menu:label="S~pecial Character..."/>
+ <menu:menuitem menu:id="slot:5678" menu:helpid="5678" menu:label="~Hyperlink"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:1" menu:label="Scan">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10331" menu:helpid="10331" menu:label="~Select Source..."/>
+ <menu:menuitem menu:id="slot:10332" menu:helpid="10332" menu:label="~Request..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10217" menu:helpid="10217" menu:label="Sp~readsheet"/>
+ <menu:menuitem menu:id="slot:10241" menu:helpid="10241" menu:label="~Graphics..."/>
+ <menu:menu menu:id="slot:2" menu:label="~Object">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5561" menu:helpid="5561" menu:label="~OLE Object..."/>
+ <menu:menuitem menu:id="slot:5672" menu:helpid="5672" menu:label="~Plug-in..."/>
+ <menu:menuitem menu:id="slot:5676" menu:helpid="5676" menu:label="~Sound..."/>
+ <menu:menuitem menu:id="slot:5677" menu:helpid="5677" menu:label="~Video..."/>
+ <menu:menuitem menu:id="slot:5673" menu:helpid="5673" menu:label="~Applet..."/>
+ <menu:menuitem menu:id="slot:27106" menu:helpid="27106" menu:label="~Formula..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10140" menu:helpid="10140" menu:label="Chart"/>
+ <menu:menuitem menu:id="slot:5563" menu:helpid="5563" menu:label="Float~ing Frame..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27015" menu:helpid="27015" menu:label="~File..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:22" menu:label="F~ormat">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10456" menu:helpid="10456" menu:label="~Default"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10143" menu:helpid="10143" menu:label="L~ine..."/>
+ <menu:menuitem menu:id="slot:10142" menu:helpid="10142" menu:label="A~rea..."/>
+ <menu:menuitem menu:id="slot:27281" menu:helpid="27281" menu:label="Te~xt..."/>
+ <menu:menuitem menu:id="slot:10087" menu:helpid="10087" menu:label="Position and Si~ze..."/>
+ <menu:menuitem menu:id="slot:10613" menu:helpid="10613" menu:label="Con~trol..."/>
+ <menu:menuitem menu:id="slot:10614" menu:helpid="10614" menu:label="For~m..."/>
+ <menu:menuitem menu:id="slot:27320" menu:helpid="27320" menu:label="Dimen~sions..."/>
+ <menu:menuitem menu:id="slot:27338" menu:helpid="27338" menu:label="~Connector..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10296" menu:helpid="10296" menu:label="C~haracter..."/>
+ <menu:menuitem menu:id="slot:10156" menu:helpid="10156" menu:label="~Numbering/Bullets..."/>
+ <menu:menu menu:id="slot:1" menu:label="Case/Characters">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10912" menu:helpid="10912" menu:label="~Uppercase"/>
+ <menu:menuitem menu:id="slot:10913" menu:helpid="10913" menu:label="~Lowercase"/>
+ <menu:menuitem menu:id="slot:10914" menu:helpid="10914" menu:label="H~alf-width"/>
+ <menu:menuitem menu:id="slot:10915" menu:helpid="10915" menu:label="Full-width"/>
+ <menu:menuitem menu:id="slot:10916" menu:helpid="10916" menu:label="~Hiragana"/>
+ <menu:menuitem menu:id="slot:10917" menu:helpid="10917" menu:label="~Katakana"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10297" menu:helpid="10297" menu:label="P~aragraph..."/>
+ <menu:menuitem menu:id="slot:27002" menu:helpid="27002" menu:label="~Page..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27048" menu:helpid="27048" menu:label="~Layer..."/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:95" menu:label="Styl~es">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5573" menu:helpid="5573" menu:label="~Catalog..."/>
+ <menu:menuitem menu:id="slot:27064" menu:helpid="27064" menu:label="~Slide Design..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:5539" menu:helpid="5539" menu:label="St~ylist"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10256" menu:helpid="10256" menu:label="F~ontwork"/>
+ <menu:menuitem menu:id="slot:10644" menu:helpid="10644" menu:label="~3D Effects"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:6677" menu:label="~Tools">
+ <menu:menupopup>
+ <menu:menu menu:id="slot:94" menu:label="~Spellcheck">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10243" menu:helpid="10243" menu:label="~Check..."/>
+ <menu:menuitem menu:id="slot:12021" menu:helpid="12021" menu:label="~AutoSpellcheck"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10245" menu:helpid="10245" menu:label="~Thesaurus..."/>
+ <menu:menuitem menu:id="slot:27340" menu:helpid="27340" menu:label="~Hyphenation"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10424" menu:helpid="10424" menu:label="~AutoCorrect..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5960" menu:helpid="5960" menu:label="~Gallery"/>
+ <menu:menuitem menu:id="slot:10350" menu:helpid="10350" menu:label="~Eyedropper"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:1" menu:label="~Macros">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:6669" menu:helpid="6669" menu:label="Record Macro"/>
+ <menu:menuitem menu:id="slot:5959" menu:helpid="5959" menu:label="~Macro..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10958" menu:helpid="10958" menu:label="~XML Filter Settings..."/>
+ <menu:menuitem menu:id="slot:5904" menu:helpid="5904" menu:label="~Configure..."/>
+ <menu:menu menu:id="slot:4" menu:label="Scripting Add-ons">
+ <menu:menupopup>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteMenuBinding()" menu:label="Assign Script to ~Menu..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteKeyBinding" menu:label="Assign Script to ~Key..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteEventBinding()" menu:label="Assign Script to ~Event..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteEditDebug" menu:label="Edit/De~bug Scripts..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.RefreshAllScripts()" menu:label="~Refresh All Scripts"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:31630" menu:helpid="31630" menu:label="~Options..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:24" menu:label="~Modify">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10129" menu:helpid="10129" menu:label="~Rotate"/>
+ <menu:menu menu:id="slot:1" menu:label="~Flip">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27034" menu:helpid="27034" menu:label="~Vertically"/>
+ <menu:menuitem menu:id="slot:27035" menu:helpid="27035" menu:label="~Horizontally"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:2" menu:label="~Convert">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27036" menu:helpid="27036" menu:label="To ~Curve"/>
+ <menu:menuitem menu:id="slot:27037" menu:helpid="27037" menu:label="To ~Polygon"/>
+ <menu:menuitem menu:id="slot:27381" menu:helpid="27381" menu:label="To C~ontour"/>
+ <menu:menuitem menu:id="slot:10648" menu:helpid="10648" menu:label="To 3~D"/>
+ <menu:menuitem menu:id="slot:10649" menu:helpid="10649" menu:label="To 3D ~Rotation Object"/>
+ <menu:menuitem menu:id="slot:27378" menu:helpid="27378" menu:label="To ~Bitmap"/>
+ <menu:menuitem menu:id="slot:27379" menu:helpid="27379" menu:label="To ~Metafile"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:96" menu:label="~Arrange">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10286" menu:helpid="10286" menu:label="~Bring to Front"/>
+ <menu:menuitem menu:id="slot:27031" menu:helpid="27031" menu:label="Bring ~Forward"/>
+ <menu:menuitem menu:id="slot:27032" menu:helpid="27032" menu:label="Send Back~ward"/>
+ <menu:menuitem menu:id="slot:10287" menu:helpid="10287" menu:label="~Send to Back"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27326" menu:helpid="27326" menu:label="In Front of ~Object"/>
+ <menu:menuitem menu:id="slot:27116" menu:helpid="27116" menu:label="Be~hind Object"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27117" menu:helpid="27117" menu:label="~Reverse"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:3" menu:label="A~lignment">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10131" menu:helpid="10131" menu:label="~Left"/>
+ <menu:menuitem menu:id="slot:10132" menu:helpid="10132" menu:label="~Centered"/>
+ <menu:menuitem menu:id="slot:10133" menu:helpid="10133" menu:label="~Right"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10134" menu:helpid="10134" menu:label="~Top"/>
+ <menu:menuitem menu:id="slot:10135" menu:helpid="10135" menu:label="C~enter"/>
+ <menu:menuitem menu:id="slot:10136" menu:helpid="10136" menu:label="~Bottom"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:5683" menu:helpid="5683" menu:label="~Distribution..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27027" menu:helpid="27027" menu:label="~Name Object..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10454" menu:helpid="10454" menu:label="~Group"/>
+ <menu:menuitem menu:id="slot:10455" menu:helpid="10455" menu:label="~Ungroup"/>
+ <menu:menuitem menu:id="slot:27096" menu:helpid="27096" menu:label="~Enter Group"/>
+ <menu:menuitem menu:id="slot:27097" menu:helpid="27097" menu:label="E~xit Group"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27026" menu:helpid="27026" menu:label="Comb~ine"/>
+ <menu:menuitem menu:id="slot:27082" menu:helpid="27082" menu:label="~Split"/>
+ <menu:menu menu:id="slot:4" menu:label="~Shapes">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5679" menu:helpid="5679" menu:label="~Merge"/>
+ <menu:menuitem menu:id="slot:5680" menu:helpid="5680" menu:label="~Subtract"/>
+ <menu:menuitem menu:id="slot:5681" menu:helpid="5681" menu:label="I~ntersect"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27093" menu:helpid="27093" menu:label="C~onnect"/>
+ <menu:menuitem menu:id="slot:27094" menu:helpid="27094" menu:label="~Break"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5610" menu:label="~Window">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5620" menu:helpid="5620" menu:label="~New Window"/>
+ <menu:menuitem menu:id="slot:5621" menu:helpid="5621" menu:label="Close Window"/>
+ <menu:menuseparator/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5410" menu:label="~Help">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5401" menu:helpid="5401" menu:label="~Contents"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5962" menu:helpid="5962" menu:label="Help ~Agent"/>
+ <menu:menuitem menu:id="slot:5404" menu:helpid="5404" menu:label="~Tips"/>
+ <menu:menuitem menu:id="slot:5403" menu:helpid="5403" menu:label="~Extended Tips"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:6683" menu:helpid="6683" menu:label="~Support"/>
+ <menu:menuitem menu:id="slot:6537" menu:helpid="6537" menu:label="~Registration..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5301" menu:helpid="5301" menu:label="A~bout OpenOffice.org..."/>
+ </menu:menupopup>
+ </menu:menu>
+</menu:menubar>
diff --git a/scripting/workben/bindings/eventbindings.xml b/scripting/workben/bindings/eventbindings.xml
new file mode 100644
index 000000000000..96a5ddfeaa5c
--- /dev/null
+++ b/scripting/workben/bindings/eventbindings.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE event:events PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "event.dtd">
+<event:events xmlns:event="http://openoffice.org/2001/event" xmlns:xlink="http://www.w3.org/1999/xlink">
+</event:events>
diff --git a/scripting/workben/bindings/impresskeybinding.xml b/scripting/workben/bindings/impresskeybinding.xml
new file mode 100644
index 000000000000..25430801fc77
--- /dev/null
+++ b/scripting/workben/bindings/impresskeybinding.xml
@@ -0,0 +1,62 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE accel:acceleratorlist PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "accelerator.dtd">
+<accel:acceleratorlist xmlns:accel="http://openoffice.org/2001/accel" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <accel:item accel:code="KEY_F8" accel:shift="true" accel:mod1="true" xlink:href="slot:10367"/>
+ <accel:item accel:code="KEY_P" accel:shift="true" accel:mod1="true" xlink:href="slot:10294"/>
+ <accel:item accel:code="KEY_N" accel:shift="true" accel:mod1="true" xlink:href="slot:5500"/>
+ <accel:item accel:code="KEY_K" accel:shift="true" accel:mod1="true" xlink:href="slot:27026"/>
+ <accel:item accel:code="KEY_G" accel:shift="true" accel:mod1="true" xlink:href="slot:10454"/>
+ <accel:item accel:code="KEY_B" accel:shift="true" accel:mod1="true" xlink:href="slot:10295"/>
+ <accel:item accel:code="KEY_SUBTRACT" accel:mod1="true" xlink:href="slot:27032"/>
+ <accel:item accel:code="KEY_ADD" accel:mod1="true" xlink:href="slot:27031"/>
+ <accel:item accel:code="KEY_INSERT" accel:mod1="true" xlink:href="slot:5711"/>
+ <accel:item accel:code="KEY_F12" accel:mod1="true" xlink:href="slot:27009"/>
+ <accel:item accel:code="KEY_F11" accel:mod1="true" xlink:href="slot:5573"/>
+ <accel:item accel:code="KEY_F7" accel:mod1="true" xlink:href="slot:10245"/>
+ <accel:item accel:code="KEY_F3" accel:mod1="true" xlink:href="slot:27097"/>
+ <accel:item accel:code="KEY_F2" accel:mod1="true" xlink:href="slot:10157"/>
+ <accel:item accel:code="KEY_Z" accel:mod1="true" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_Y" accel:mod1="true" xlink:href="slot:5700"/>
+ <accel:item accel:code="KEY_X" accel:mod1="true" xlink:href="slot:5710"/>
+ <accel:item accel:code="KEY_V" accel:mod1="true" xlink:href="slot:5712"/>
+ <accel:item accel:code="KEY_U" accel:mod1="true" xlink:href="slot:10014"/>
+ <accel:item accel:code="KEY_S" accel:mod1="true" xlink:href="slot:5505"/>
+ <accel:item accel:code="KEY_R" accel:mod1="true" xlink:href="slot:10029"/>
+ <accel:item accel:code="KEY_Q" accel:mod1="true" xlink:href="slot:5300"/>
+ <accel:item accel:code="KEY_P" accel:mod1="true" xlink:href="slot:5504"/>
+ <accel:item accel:code="KEY_O" accel:mod1="true" xlink:href="slot:5501"/>
+ <accel:item accel:code="KEY_L" accel:mod1="true" xlink:href="slot:10028"/>
+ <accel:item accel:code="KEY_J" accel:mod1="true" xlink:href="slot:10031"/>
+ <accel:item accel:code="KEY_I" accel:mod1="true" xlink:href="slot:10008"/>
+ <accel:item accel:code="KEY_E" accel:mod1="true" xlink:href="slot:10030"/>
+ <accel:item accel:code="KEY_C" accel:mod1="true" xlink:href="slot:5711"/>
+ <accel:item accel:code="KEY_B" accel:mod1="true" xlink:href="slot:10009"/>
+ <accel:item accel:code="KEY_5" accel:mod1="true" xlink:href="slot:10035"/>
+ <accel:item accel:code="KEY_2" accel:mod1="true" xlink:href="slot:10036"/>
+ <accel:item accel:code="KEY_1" accel:mod1="true" xlink:href="slot:10034"/>
+ <accel:item accel:code="KEY_DELETE" accel:shift="true" xlink:href="slot:5710"/>
+ <accel:item accel:code="KEY_INSERT" accel:shift="true" xlink:href="slot:5712"/>
+ <accel:item accel:code="KEY_F3" accel:shift="true" xlink:href="slot:27004"/>
+ <accel:item accel:code="KEY_REPEAT" xlink:href="slot:5702"/>
+ <accel:item accel:code="KEY_UNDO" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_PASTE" xlink:href="slot:5712"/>
+ <accel:item accel:code="KEY_COPY" xlink:href="slot:5711"/>
+ <accel:item accel:code="KEY_CUT" xlink:href="slot:5710"/>
+ <accel:item accel:code="KEY_OPEN" xlink:href="slot:5501"/>
+ <accel:item accel:code="KEY_DELETE" xlink:href="slot:5713"/>
+ <accel:item accel:code="KEY_F12" xlink:href="slot:27010"/>
+ <accel:item accel:code="KEY_F11" xlink:href="slot:5539"/>
+ <accel:item accel:code="KEY_F9" xlink:href="slot:10157"/>
+ <accel:item accel:code="KEY_F8" xlink:href="slot:10126"/>
+ <accel:item accel:code="KEY_F7" xlink:href="slot:10243"/>
+ <accel:item accel:code="KEY_F5" xlink:href="slot:10366"/>
+ <accel:item accel:code="KEY_F4" xlink:href="slot:10087"/>
+ <accel:item accel:code="KEY_F3" xlink:href="slot:27096"/>
+ <accel:item accel:code="KEY_F2" xlink:href="slot:10006"/>
+ <accel:item accel:code="KEY_BACKSPACE" accel:mod2="true" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_ADD" accel:shift="true" accel:mod1="true" xlink:href="slot:10286"/>
+ <accel:item accel:code="KEY_SUBTRACT" accel:shift="true" accel:mod1="true" xlink:href="slot:10287"/>
+ <accel:item accel:code="KEY_G" accel:shift="true" accel:mod1="true" accel:mod2="true" xlink:href="slot:10455"/>
+ <accel:item accel:code="KEY_9" accel:shift="true" accel:mod1="true" accel:mod2="true" xlink:href="slot:10703"/>
+ <accel:item accel:code="KEY_K" accel:shift="true" accel:mod1="true" accel:mod2="true" xlink:href="slot:27082"/>
+</accel:acceleratorlist> \ No newline at end of file
diff --git a/scripting/workben/bindings/impressmenubar.xml b/scripting/workben/bindings/impressmenubar.xml
new file mode 100644
index 000000000000..ec51390d0411
--- /dev/null
+++ b/scripting/workben/bindings/impressmenubar.xml
@@ -0,0 +1,328 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE menu:menubar PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "menubar.dtd">
+<menu:menubar xmlns:menu="http://openoffice.org/2001/menu" menu:id="menubar">
+ <menu:menu menu:id="slot:5510" menu:label="~File">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5537" menu:helpid="5537" menu:label="~New"/>
+ <menu:menuitem menu:id="slot:5501" menu:helpid="5501" menu:label="~Open..."/>
+ <menu:menuitem menu:id="slot:6381" menu:helpid="6381" menu:label="A~utoPilot"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5503" menu:helpid="5503" menu:label="~Close"/>
+ <menu:menuitem menu:id="slot:5505" menu:helpid="5505" menu:label="~Save"/>
+ <menu:menuitem menu:id="slot:5502" menu:helpid="5502" menu:label="Save ~As..."/>
+ <menu:menuitem menu:id="slot:5309" menu:helpid="5309" menu:label="Sa~ve All"/>
+ <menu:menuitem menu:id="slot:5508" menu:helpid="5508" menu:label="Reload"/>
+ <menu:menuitem menu:id="slot:6583" menu:helpid="6583" menu:label="Versions..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5829" menu:helpid="5829" menu:label="~Export..."/>
+ <menu:menuitem menu:id="slot:6673" menu:helpid="6673" menu:label="Export as PDF..."/>
+ <menu:menu menu:id="slot:98" menu:label="Sen~d">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5331" menu:helpid="5331" menu:label="Document as ~E-mail..."/>
+ <menu:menuitem menu:id="slot:6672" menu:helpid="6672" menu:label="Document as P~DF Attachment..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5535" menu:helpid="5535" menu:label="Propert~ies..."/>
+ <menu:menu menu:id="slot:103" menu:label="~Templates">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5540" menu:helpid="5540" menu:label="~Organize..."/>
+ <menu:menuitem menu:id="slot:6655" menu:helpid="6655" menu:label="~Address Book Source..."/>
+ <menu:menuitem menu:id="slot:5538" menu:helpid="5538" menu:label="~Save..."/>
+ <menu:menuitem menu:id="slot:5594" menu:helpid="5594" menu:label="~Edit..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5504" menu:helpid="5504" menu:label="~Print..."/>
+ <menu:menuitem menu:id="slot:5302" menu:helpid="5302" menu:label="P~rinter Settings..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5300" menu:helpid="5300" menu:label="E~xit"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:20" menu:label="~Edit">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5701" menu:helpid="5701" menu:label="Can&apos;t Undo"/>
+ <menu:menuitem menu:id="slot:5700" menu:helpid="5700" menu:label="Can&apos;t Restore"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5710" menu:helpid="5710" menu:label="Cu~t"/>
+ <menu:menuitem menu:id="slot:5711" menu:helpid="5711" menu:label="~Copy"/>
+ <menu:menuitem menu:id="slot:5712" menu:helpid="5712" menu:label="~Paste"/>
+ <menu:menuitem menu:id="slot:27003" menu:helpid="27003" menu:label="Paste ~Special..."/>
+ <menu:menuitem menu:id="slot:5723" menu:helpid="5723" menu:label="Select ~All"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5961" menu:helpid="5961" menu:label="~Find &amp; Replace..."/>
+ <menu:menuitem menu:id="slot:10366" menu:helpid="10366" menu:label="Na~vigator"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27004" menu:helpid="27004" menu:label="Duplicat~e..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10126" menu:helpid="10126" menu:label="Poi~nts"/>
+ <menu:menuitem menu:id="slot:27301" menu:helpid="27301" menu:label="~Glue Points"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27362" menu:helpid="27362" menu:label="F~ields..."/>
+ <menu:menuitem menu:id="slot:27080" menu:helpid="27080" menu:label="D~elete Slide..."/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:340" menu:label="La~yer">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27043" menu:helpid="27043" menu:label="~Insert"/>
+ <menu:menuitem menu:id="slot:27048" menu:helpid="27048" menu:label="~Modify"/>
+ <menu:menuitem menu:id="slot:27081" menu:helpid="27081" menu:label="Delete"/>
+ <menu:menuitem menu:id="slot:27269" menu:helpid="27269" menu:label="~Rename"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27005" menu:helpid="27005" menu:label="Lin~ks..."/>
+ <menu:menuitem menu:id="slot:6314" menu:helpid="6314" menu:label="P~lug-in"/>
+ <menu:menuitem menu:id="slot:10371" menu:helpid="10371" menu:label="ImageMap"/>
+ <menu:menuitem menu:id="slot:5575" menu:helpid="5575" menu:label="~Object"/>
+ <menu:menuitem menu:id="slot:27382" menu:helpid="27382" menu:label="H~yperlink..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:23" menu:label="~View">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10000" menu:helpid="10000" menu:label="~Zoom..."/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:92" menu:label="~Toolbars">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5910" menu:helpid="5910" menu:label="~Function Bar"/>
+ <menu:menuitem menu:id="slot:5905" menu:helpid="5905" menu:label="~Object Bar"/>
+ <menu:menuitem menu:id="slot:5909" menu:helpid="5909" menu:label="Main ~Toolbar"/>
+ <menu:menuitem menu:id="slot:10360" menu:helpid="10360" menu:label="~Hyperlink Bar"/>
+ <menu:menuitem menu:id="slot:5911" menu:helpid="5911" menu:label="Optio~n Bar"/>
+ <menu:menuitem menu:id="slot:5928" menu:helpid="5928" menu:label="~Presentation"/>
+ <menu:menuitem menu:id="slot:10417" menu:helpid="10417" menu:label="~Color Bar"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5908" menu:helpid="5908" menu:label="Customi~ze..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:27040" menu:helpid="27040" menu:label="~Rulers"/>
+ <menu:menuitem menu:id="slot:5920" menu:helpid="5920" menu:label="~Status Bar"/>
+ <menu:menuitem menu:id="slot:6680" menu:helpid="6680" menu:label="~Input Method Status"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:91" menu:label="Wor~kspace">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27009" menu:helpid="27009" menu:label="~Drawing View"/>
+ <menu:menuitem menu:id="slot:27010" menu:helpid="27010" menu:label="~Outline View"/>
+ <menu:menuitem menu:id="slot:27011" menu:helpid="27011" menu:label="~Slides View"/>
+ <menu:menuitem menu:id="slot:27069" menu:helpid="27069" menu:label="~Notes View"/>
+ <menu:menuitem menu:id="slot:27070" menu:helpid="27070" menu:label="~Handout View"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:100" menu:label="~Display Quality">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27366" menu:helpid="27366" menu:label="~Color"/>
+ <menu:menuitem menu:id="slot:27367" menu:helpid="27367" menu:label="~Grayscale"/>
+ <menu:menuitem menu:id="slot:27368" menu:helpid="27368" menu:label="~Black and White"/>
+ <menu:menuitem menu:id="slot:27400" menu:helpid="27400" menu:label="~High Contrast"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27327" menu:helpid="27327" menu:label="~Preview"/>
+ <menu:menu menu:id="slot:101" menu:label="Pre~view Mode">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27369" menu:helpid="27369" menu:label="~Color"/>
+ <menu:menuitem menu:id="slot:27370" menu:helpid="27370" menu:label="~Grayscale"/>
+ <menu:menuitem menu:id="slot:27371" menu:helpid="27371" menu:label="~Black and White"/>
+ <menu:menuitem menu:id="slot:27401" menu:helpid="27401" menu:label="~High Contrast"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27049" menu:helpid="27049" menu:label="S~lide"/>
+ <menu:menu menu:id="slot:97" menu:label="~Master">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27348" menu:helpid="27348" menu:label="~Drawing"/>
+ <menu:menuitem menu:id="slot:27351" menu:helpid="27351" menu:label="~Title"/>
+ <menu:menuitem menu:id="slot:27350" menu:helpid="27350" menu:label="~Notes"/>
+ <menu:menuitem menu:id="slot:27349" menu:helpid="27349" menu:label="~Handout"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:27050" menu:helpid="27050" menu:label="La~yer"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:338" menu:label="~Grid">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27322" menu:helpid="27322" menu:label="~Visible Grid"/>
+ <menu:menuitem menu:id="slot:27154" menu:helpid="27154" menu:label="Snap to Grid"/>
+ <menu:menuitem menu:id="slot:27323" menu:helpid="27323" menu:label="Grid to ~Front"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:339" menu:label="~Snap Lines">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27324" menu:helpid="27324" menu:label="~Snap Lines Visible"/>
+ <menu:menuitem menu:id="slot:27152" menu:helpid="27152" menu:label="Snap to Snap Lines"/>
+ <menu:menuitem menu:id="slot:27325" menu:helpid="27325" menu:label="Snap Lines to Front"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5627" menu:helpid="5627" menu:label="F~ull Screen"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:21" menu:label="~Insert">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27014" menu:helpid="27014" menu:label="Slid~e..."/>
+ <menu:menuitem menu:id="slot:27342" menu:helpid="27342" menu:label="D~uplicate Slide"/>
+ <menu:menuitem menu:id="slot:27343" menu:helpid="27343" menu:label="E~xpand Slide"/>
+ <menu:menuitem menu:id="slot:27344" menu:helpid="27344" menu:label="Su~mmary Slide"/>
+ <menu:menu menu:id="slot:99" menu:label="Fiel~ds">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:27358" menu:helpid="27358" menu:label="~Date (fixed)"/>
+ <menu:menuitem menu:id="slot:27357" menu:helpid="27357" menu:label="Dat~e (variable)"/>
+ <menu:menuitem menu:id="slot:27360" menu:helpid="27360" menu:label="~Time (fixed)"/>
+ <menu:menuitem menu:id="slot:27359" menu:helpid="27359" menu:label="T~ime (variable)"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27364" menu:helpid="27364" menu:label="~Author"/>
+ <menu:menuitem menu:id="slot:27361" menu:helpid="27361" menu:label="~Page Number"/>
+ <menu:menuitem menu:id="slot:27363" menu:helpid="27363" menu:label="~File Name"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:27019" menu:helpid="27019" menu:label="S~pecial Character..."/>
+ <menu:menuitem menu:id="slot:5678" menu:helpid="5678" menu:label="~Hyperlink"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:1" menu:label="Scan">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10331" menu:helpid="10331" menu:label="~Select Source..."/>
+ <menu:menuitem menu:id="slot:10332" menu:helpid="10332" menu:label="~Request..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10217" menu:helpid="10217" menu:label="Sp~readsheet"/>
+ <menu:menuitem menu:id="slot:10241" menu:helpid="10241" menu:label="~Graphics..."/>
+ <menu:menu menu:id="slot:2" menu:label="~Object">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5561" menu:helpid="5561" menu:label="~OLE Object..."/>
+ <menu:menuitem menu:id="slot:5672" menu:helpid="5672" menu:label="~Plug-in..."/>
+ <menu:menuitem menu:id="slot:5676" menu:helpid="5676" menu:label="~Sound..."/>
+ <menu:menuitem menu:id="slot:5677" menu:helpid="5677" menu:label="~Video..."/>
+ <menu:menuitem menu:id="slot:5673" menu:helpid="5673" menu:label="~Applet..."/>
+ <menu:menuitem menu:id="slot:27106" menu:helpid="27106" menu:label="~Formula..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10140" menu:helpid="10140" menu:label="Chart"/>
+ <menu:menuitem menu:id="slot:5563" menu:helpid="5563" menu:label="Float~ing Frame..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27015" menu:helpid="27015" menu:label="~File..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:22" menu:label="F~ormat">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10456" menu:helpid="10456" menu:label="~Default"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10143" menu:helpid="10143" menu:label="L~ine..."/>
+ <menu:menuitem menu:id="slot:10142" menu:helpid="10142" menu:label="A~rea..."/>
+ <menu:menuitem menu:id="slot:27281" menu:helpid="27281" menu:label="Te~xt..."/>
+ <menu:menuitem menu:id="slot:10087" menu:helpid="10087" menu:label="Position and Si~ze..."/>
+ <menu:menuitem menu:id="slot:10613" menu:helpid="10613" menu:label="Con~trol..."/>
+ <menu:menuitem menu:id="slot:10614" menu:helpid="10614" menu:label="For~m..."/>
+ <menu:menuitem menu:id="slot:27320" menu:helpid="27320" menu:label="Dimen~sions..."/>
+ <menu:menuitem menu:id="slot:27338" menu:helpid="27338" menu:label="~Connector..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10296" menu:helpid="10296" menu:label="C~haracter..."/>
+ <menu:menuitem menu:id="slot:10156" menu:helpid="10156" menu:label="~Numbering/Bullets..."/>
+ <menu:menu menu:id="slot:1" menu:label="Case/Characters">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10912" menu:helpid="10912" menu:label="~Uppercase"/>
+ <menu:menuitem menu:id="slot:10913" menu:helpid="10913" menu:label="~Lowercase"/>
+ <menu:menuitem menu:id="slot:10914" menu:helpid="10914" menu:label="H~alf-width"/>
+ <menu:menuitem menu:id="slot:10915" menu:helpid="10915" menu:label="Full-width"/>
+ <menu:menuitem menu:id="slot:10916" menu:helpid="10916" menu:label="~Hiragana"/>
+ <menu:menuitem menu:id="slot:10917" menu:helpid="10917" menu:label="~Katakana"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10297" menu:helpid="10297" menu:label="P~aragraph..."/>
+ <menu:menuitem menu:id="slot:27002" menu:helpid="27002" menu:label="~Page..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27046" menu:helpid="27046" menu:label="Modify ~Layout..."/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:95" menu:label="Styl~es">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5573" menu:helpid="5573" menu:label="~Catalog..."/>
+ <menu:menuitem menu:id="slot:27064" menu:helpid="27064" menu:label="~Slide Design..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:5539" menu:helpid="5539" menu:label="St~ylist"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10256" menu:helpid="10256" menu:label="F~ontwork"/>
+ <menu:menuitem menu:id="slot:10644" menu:helpid="10644" menu:label="~3D Effects"/>
+ <menu:menu menu:id="slot:102" menu:label="~Group">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10454" menu:helpid="10454" menu:label="~Group"/>
+ <menu:menuitem menu:id="slot:10455" menu:helpid="10455" menu:label="~Ungroup"/>
+ <menu:menuitem menu:id="slot:27096" menu:helpid="27096" menu:label="~Edit Group"/>
+ <menu:menuitem menu:id="slot:27097" menu:helpid="27097" menu:label="E~xit group"/>
+ </menu:menupopup>
+ </menu:menu>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:6677" menu:label="~Tools">
+ <menu:menupopup>
+ <menu:menu menu:id="slot:94" menu:label="~Spellcheck">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10243" menu:helpid="10243" menu:label="~Check..."/>
+ <menu:menuitem menu:id="slot:12021" menu:helpid="12021" menu:label="~AutoSpellcheck"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10245" menu:helpid="10245" menu:label="~Thesaurus..."/>
+ <menu:menuitem menu:id="slot:27340" menu:helpid="27340" menu:label="~Hyphenation"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10424" menu:helpid="10424" menu:label="~AutoCorrect..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5960" menu:helpid="5960" menu:label="~Gallery"/>
+ <menu:menuitem menu:id="slot:10350" menu:helpid="10350" menu:label="~Eyedropper"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:1" menu:label="~Macros">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:6669" menu:helpid="6669" menu:label="Record Macro"/>
+ <menu:menuitem menu:id="slot:5959" menu:helpid="5959" menu:label="~Macro..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10958" menu:helpid="10958" menu:label="~XML Filter Settings..."/>
+ <menu:menuitem menu:id="slot:5904" menu:helpid="5904" menu:label="~Configure..."/>
+ <menu:menu menu:id="slot:4" menu:label="Scripting Add-ons">
+ <menu:menupopup>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteMenuBinding()" menu:label="Assign Script to ~Menu..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteKeyBinding" menu:label="Assign Script to ~Key..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteEventBinding()" menu:label="Assign Script to ~Event..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteEditDebug" menu:label="Edit/De~bug Scripts..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.RefreshAllScripts()" menu:label="~Refresh All Scripts"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:31630" menu:helpid="31630" menu:label="~Options..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:26" menu:label="~Slide Show">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10157" menu:helpid="10157" menu:label="Slide Sho~w"/>
+ <menu:menuitem menu:id="slot:10159" menu:helpid="10159" menu:label="~Rehearse Timings"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27339" menu:helpid="27339" menu:label="~Slide Show Settings..."/>
+ <menu:menuitem menu:id="slot:27365" menu:helpid="27365" menu:label="~Custom Slide Show..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27334" menu:helpid="27334" menu:label="Slide ~Transition"/>
+ <menu:menuitem menu:id="slot:10161" menu:helpid="10161" menu:label="~Show/Hide Slide"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:27062" menu:helpid="27062" menu:label="~Animation"/>
+ <menu:menuitem menu:id="slot:27328" menu:helpid="27328" menu:label="~Effects"/>
+ <menu:menuitem menu:id="slot:27063" menu:helpid="27063" menu:label="~Interaction..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5610" menu:label="~Window">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5620" menu:helpid="5620" menu:label="~New Window"/>
+ <menu:menuitem menu:id="slot:5621" menu:helpid="5621" menu:label="Close Window"/>
+ <menu:menuseparator/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5410" menu:label="~Help">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5401" menu:helpid="5401" menu:label="~Contents"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5962" menu:helpid="5962" menu:label="Help ~Agent"/>
+ <menu:menuitem menu:id="slot:5404" menu:helpid="5404" menu:label="~Tips"/>
+ <menu:menuitem menu:id="slot:5403" menu:helpid="5403" menu:label="~Extended Tips"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:6683" menu:helpid="6683" menu:label="~Support"/>
+ <menu:menuitem menu:id="slot:6537" menu:helpid="6537" menu:label="~Registration..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5301" menu:helpid="5301" menu:label="A~bout OpenOffice.org..."/>
+ </menu:menupopup>
+ </menu:menu>
+</menu:menubar>
diff --git a/scripting/workben/bindings/manifest.xml b/scripting/workben/bindings/manifest.xml
new file mode 100644
index 000000000000..093d19ff37a8
--- /dev/null
+++ b/scripting/workben/bindings/manifest.xml
@@ -0,0 +1,14 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE manifest:manifest PUBLIC "-//OpenOffice.org//DTD Manifest 1.0//EN" "Manifest.dtd">
+<manifest:manifest xmlns:manifest="http://openoffice.org/2001/manifest">
+ <manifest:file-entry manifest:media-type="" manifest:full-path="/"/>
+ <manifest:file-entry manifest:media-type="" manifest:full-path="writermenubar.xml"/>
+ <manifest:file-entry manifest:media-type="" manifest:full-path="writerkeybinding.xml"/>
+ <manifest:file-entry manifest:media-type="" manifest:full-path="calcmenubar.xml"/>
+ <manifest:file-entry manifest:media-type="" manifest:full-path="calckeybinding.xml"/>
+ <manifest:file-entry manifest:media-type="" manifest:full-path="impressmenubar.xml"/>
+ <manifest:file-entry manifest:media-type="" manifest:full-path="impresskeybinding.xml"/>
+ <manifest:file-entry manifest:media-type="" manifest:full-path="drawmenubar.xml"/>
+ <manifest:file-entry manifest:media-type="" manifest:full-path="drawkeybinding.xml"/>
+ <manifest:file-entry manifest:media-type="" manifest:full-path="eventbindings.xml"/>
+</manifest:manifest> \ No newline at end of file
diff --git a/scripting/workben/bindings/script.xlb b/scripting/workben/bindings/script.xlb
new file mode 100644
index 000000000000..33eb114b5b64
--- /dev/null
+++ b/scripting/workben/bindings/script.xlb
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE library:library PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "library.dtd">
+<library:library xmlns:library="http://openoffice.org/2000/library" library:name="ScriptBindingLibrary" library:readonly="false" library:passwordprotected="false">
+</library:library>
diff --git a/scripting/workben/bindings/writerkeybinding.xml b/scripting/workben/bindings/writerkeybinding.xml
new file mode 100644
index 000000000000..65c7ceef42e7
--- /dev/null
+++ b/scripting/workben/bindings/writerkeybinding.xml
@@ -0,0 +1,101 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE accel:acceleratorlist PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "accelerator.dtd">
+<accel:acceleratorlist xmlns:accel="http://openoffice.org/2001/accel" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <accel:item accel:code="KEY_DELETE" accel:shift="true" accel:mod1="true" xlink:href="slot:20927"/>
+ <accel:item accel:code="KEY_BACKSPACE" accel:shift="true" accel:mod1="true" xlink:href="slot:20928"/>
+ <accel:item accel:code="KEY_RETURN" accel:shift="true" accel:mod1="true" xlink:href="slot:20305"/>
+ <accel:item accel:code="KEY_PAGEDOWN" accel:shift="true" accel:mod1="true" xlink:href="slot:20963"/>
+ <accel:item accel:code="KEY_END" accel:shift="true" accel:mod1="true" xlink:href="slot:20808"/>
+ <accel:item accel:code="KEY_HOME" accel:shift="true" accel:mod1="true" xlink:href="slot:20807"/>
+ <accel:item accel:code="KEY_RIGHT" accel:shift="true" accel:mod1="true" xlink:href="slot:20821"/>
+ <accel:item accel:code="KEY_LEFT" accel:shift="true" accel:mod1="true" xlink:href="slot:20822"/>
+ <accel:item accel:code="KEY_UP" accel:shift="true" accel:mod1="true" xlink:href="slot:20947"/>
+ <accel:item accel:code="KEY_DOWN" accel:shift="true" accel:mod1="true" xlink:href="slot:20948"/>
+ <accel:item accel:code="KEY_F12" accel:shift="true" accel:mod1="true" xlink:href="slot:20137"/>
+ <accel:item accel:code="KEY_F11" accel:shift="true" accel:mod1="true" xlink:href="slot:5556"/>
+ <accel:item accel:code="KEY_F9" accel:shift="true" accel:mod1="true" xlink:href="slot:20143"/>
+ <accel:item accel:code="KEY_F5" accel:shift="true" accel:mod1="true" xlink:href="slot:20659"/>
+ <accel:item accel:code="KEY_T" accel:shift="true" accel:mod1="true" xlink:href="slot:20559"/>
+ <accel:item accel:code="KEY_R" accel:shift="true" accel:mod1="true" xlink:href="slot:20201"/>
+ <accel:item accel:code="KEY_P" accel:shift="true" accel:mod1="true" xlink:href="slot:20411"/>
+ <accel:item accel:code="KEY_I" accel:shift="true" accel:mod1="true" xlink:href="slot:20989"/>
+ <accel:item accel:code="KEY_F" accel:shift="true" accel:mod1="true" xlink:href="slot:20150"/>
+ <accel:item accel:code="KEY_D" accel:shift="true" accel:mod1="true" xlink:href="slot:10951"/>
+ <accel:item accel:code="KEY_B" accel:shift="true" accel:mod1="true" xlink:href="slot:20412"/>
+ <accel:item accel:code="KEY_A" accel:shift="true" accel:mod1="true" xlink:href="slot:10950"/>
+ <accel:item accel:code="KEY_MULTIPLY" accel:mod1="true" xlink:href="slot:20127"/>
+ <accel:item accel:code="KEY_SUBTRACT" accel:mod1="true" xlink:href="slot:20343"/>
+ <accel:item accel:code="KEY_ADD" accel:mod1="true" xlink:href="slot:20615"/>
+ <accel:item accel:code="KEY_DELETE" accel:mod1="true" xlink:href="slot:20929"/>
+ <accel:item accel:code="KEY_BACKSPACE" accel:mod1="true" xlink:href="slot:20930"/>
+ <accel:item accel:code="KEY_SPACE" accel:mod1="true" xlink:href="slot:20344"/>
+ <accel:item accel:code="KEY_RETURN" accel:mod1="true" xlink:href="slot:20323"/>
+ <accel:item accel:code="KEY_PAGEDOWN" accel:mod1="true" xlink:href="slot:20961"/>
+ <accel:item accel:code="KEY_PAGEUP" accel:mod1="true" xlink:href="slot:20960"/>
+ <accel:item accel:code="KEY_END" accel:mod1="true" xlink:href="slot:20908"/>
+ <accel:item accel:code="KEY_HOME" accel:mod1="true" xlink:href="slot:20907"/>
+ <accel:item accel:code="KEY_RIGHT" accel:mod1="true" xlink:href="slot:20921"/>
+ <accel:item accel:code="KEY_LEFT" accel:mod1="true" xlink:href="slot:20922"/>
+ <accel:item accel:code="KEY_F12" accel:mod1="true" xlink:href="slot:20330"/>
+ <accel:item accel:code="KEY_F11" accel:mod1="true" xlink:href="slot:5573"/>
+ <accel:item accel:code="KEY_F10" accel:mod1="true" xlink:href="slot:20224"/>
+ <accel:item accel:code="KEY_F9" accel:mod1="true" xlink:href="slot:20226"/>
+ <accel:item accel:code="KEY_F8" accel:mod1="true" xlink:href="slot:20225"/>
+ <accel:item accel:code="KEY_F7" accel:mod1="true" xlink:href="slot:20603"/>
+ <accel:item accel:code="KEY_F3" accel:mod1="true" xlink:href="slot:20620"/>
+ <accel:item accel:code="KEY_F2" accel:mod1="true" xlink:href="slot:20308"/>
+ <accel:item accel:code="KEY_Z" accel:mod1="true" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_Y" accel:mod1="true" xlink:href="slot:5700"/>
+ <accel:item accel:code="KEY_U" accel:mod1="true" xlink:href="slot:10014"/>
+ <accel:item accel:code="KEY_R" accel:mod1="true" xlink:href="slot:10029"/>
+ <accel:item accel:code="KEY_L" accel:mod1="true" xlink:href="slot:10028"/>
+ <accel:item accel:code="KEY_J" accel:mod1="true" xlink:href="slot:10031"/>
+ <accel:item accel:code="KEY_I" accel:mod1="true" xlink:href="slot:10008"/>
+ <accel:item accel:code="KEY_E" accel:mod1="true" xlink:href="slot:10030"/>
+ <accel:item accel:code="KEY_D" accel:mod1="true" xlink:href="slot:20405"/>
+ <accel:item accel:code="KEY_B" accel:mod1="true" xlink:href="slot:10009"/>
+ <accel:item accel:code="KEY_5" accel:mod1="true" xlink:href="slot:10035"/>
+ <accel:item accel:code="KEY_2" accel:mod1="true" xlink:href="slot:10036"/>
+ <accel:item accel:code="KEY_1" accel:mod1="true" xlink:href="slot:10034"/>
+ <accel:item accel:code="KEY_BACKSPACE" accel:shift="true" xlink:href="slot:20942"/>
+ <accel:item accel:code="KEY_RETURN" accel:shift="true" xlink:href="slot:20318"/>
+ <accel:item accel:code="KEY_PAGEDOWN" accel:shift="true" xlink:href="slot:20830"/>
+ <accel:item accel:code="KEY_PAGEUP" accel:shift="true" xlink:href="slot:20829"/>
+ <accel:item accel:code="KEY_END" accel:shift="true" xlink:href="slot:20806"/>
+ <accel:item accel:code="KEY_HOME" accel:shift="true" xlink:href="slot:20805"/>
+ <accel:item accel:code="KEY_RIGHT" accel:shift="true" xlink:href="slot:20802"/>
+ <accel:item accel:code="KEY_LEFT" accel:shift="true" xlink:href="slot:20801"/>
+ <accel:item accel:code="KEY_UP" accel:shift="true" xlink:href="slot:20803"/>
+ <accel:item accel:code="KEY_DOWN" accel:shift="true" xlink:href="slot:20804"/>
+ <accel:item accel:code="KEY_F12" accel:shift="true" xlink:href="slot:20138"/>
+ <accel:item accel:code="KEY_F11" accel:shift="true" xlink:href="slot:5555"/>
+ <accel:item accel:code="KEY_F9" accel:shift="true" xlink:href="slot:20129"/>
+ <accel:item accel:code="KEY_F8" accel:shift="true" xlink:href="slot:20939"/>
+ <accel:item accel:code="KEY_F5" accel:shift="true" xlink:href="slot:20958"/>
+ <accel:item accel:code="KEY_REPEAT" xlink:href="slot:5702"/>
+ <accel:item accel:code="KEY_UNDO" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_INSERT" xlink:href="slot:10221"/>
+ <accel:item accel:code="KEY_BACKSPACE" xlink:href="slot:20926"/>
+ <accel:item accel:code="KEY_ESCAPE" xlink:href="slot:20941"/>
+ <accel:item accel:code="KEY_RETURN" xlink:href="slot:20303"/>
+ <accel:item accel:code="KEY_PAGEDOWN" xlink:href="slot:20938"/>
+ <accel:item accel:code="KEY_PAGEUP" xlink:href="slot:20937"/>
+ <accel:item accel:code="KEY_END" xlink:href="slot:20906"/>
+ <accel:item accel:code="KEY_HOME" xlink:href="slot:20905"/>
+ <accel:item accel:code="KEY_RIGHT" xlink:href="slot:20902"/>
+ <accel:item accel:code="KEY_LEFT" xlink:href="slot:20901"/>
+ <accel:item accel:code="KEY_UP" xlink:href="slot:20903"/>
+ <accel:item accel:code="KEY_DOWN" xlink:href="slot:20904"/>
+ <accel:item accel:code="KEY_F12" xlink:href="slot:20144"/>
+ <accel:item accel:code="KEY_F11" xlink:href="slot:5539"/>
+ <accel:item accel:code="KEY_F9" xlink:href="slot:20126"/>
+ <accel:item accel:code="KEY_F8" xlink:href="slot:20940"/>
+ <accel:item accel:code="KEY_F7" xlink:href="slot:20622"/>
+ <accel:item accel:code="KEY_F5" xlink:href="slot:10366"/>
+ <accel:item accel:code="KEY_F3" xlink:href="slot:20628"/>
+ <accel:item accel:code="KEY_F2" xlink:href="slot:20128"/>
+ <accel:item accel:code="KEY_BACKSPACE" accel:mod2="true" xlink:href="slot:5701"/>
+ <accel:item accel:code="KEY_UP" accel:mod1="true" accel:mod2="true" xlink:href="slot:20134"/>
+ <accel:item accel:code="KEY_DOWN" accel:mod1="true" accel:mod2="true" xlink:href="slot:20135"/>
+ <accel:item accel:code="KEY_SUBTRACT" accel:shift="true" accel:mod1="true" xlink:href="slot:20385"/>
+</accel:acceleratorlist> \ No newline at end of file
diff --git a/scripting/workben/bindings/writermenubar.xml b/scripting/workben/bindings/writermenubar.xml
new file mode 100644
index 000000000000..086520486271
--- /dev/null
+++ b/scripting/workben/bindings/writermenubar.xml
@@ -0,0 +1,281 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE menu:menubar PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "menubar.dtd">
+<menu:menubar xmlns:menu="http://openoffice.org/2001/menu" menu:id="menubar">
+ <menu:menu menu:id="slot:5510" menu:label="~File">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5537" menu:helpid="5537" menu:label="~New"/>
+ <menu:menuitem menu:id="slot:5501" menu:helpid="5501" menu:label="~Open..."/>
+ <menu:menuitem menu:id="slot:6381" menu:helpid="6381" menu:label="A~utoPilot"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5503" menu:helpid="5503" menu:label="~Close"/>
+ <menu:menuitem menu:id="slot:5505" menu:helpid="5505" menu:label="~Save"/>
+ <menu:menuitem menu:id="slot:5502" menu:helpid="5502" menu:label="Save ~As..."/>
+ <menu:menuitem menu:id="slot:5309" menu:helpid="5309" menu:label="Sa~ve All"/>
+ <menu:menuitem menu:id="slot:5508" menu:helpid="5508" menu:label="Re~load"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:6583" menu:helpid="6583" menu:label="V~ersions..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5829" menu:helpid="5829" menu:label="Expor~t..."/>
+ <menu:menuitem menu:id="slot:6673" menu:helpid="6673" menu:label="Expor~t as PDF..."/>
+ <menu:menu menu:id="slot:1" menu:label="Sen~d">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5331" menu:helpid="5331" menu:label="Document as ~E-mail..."/>
+ <menu:menuitem menu:id="slot:6672" menu:helpid="6672" menu:label="Document as P~DF Attachment..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20004" menu:helpid="20004" menu:label="Create Master ~Document"/>
+ <menu:menuitem menu:id="slot:20040" menu:helpid="20040" menu:label="Create ~HTML Document"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20036" menu:helpid="20036" menu:label="Outline to ~Presentation"/>
+ <menu:menuitem menu:id="slot:20037" menu:helpid="20037" menu:label="Outline to ~Clipboard"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:21612" menu:helpid="21612" menu:label="Create A~utoAbstract..."/>
+ <menu:menuitem menu:id="slot:21613" menu:helpid="21613" menu:label="AutoAbst~ract to Presentation..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5535" menu:helpid="5535" menu:label="Propert~ies..."/>
+ <menu:menu menu:id="slot:2" menu:label="~Templates">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5540" menu:helpid="5540" menu:label="~Organize..."/>
+ <menu:menuitem menu:id="slot:6655" menu:helpid="6655" menu:label="~Address Book Source..."/>
+ <menu:menuitem menu:id="slot:5538" menu:helpid="5538" menu:label="~Save..."/>
+ <menu:menuitem menu:id="slot:5594" menu:helpid="5594" menu:label="~Edit..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5325" menu:helpid="5325" menu:label="Pa~ge Preview"/>
+ <menu:menuitem menu:id="slot:5504" menu:helpid="5504" menu:label="~Print..."/>
+ <menu:menuitem menu:id="slot:5302" menu:helpid="5302" menu:label="P~rinter Settings..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5300" menu:helpid="5300" menu:label="E~xit"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:1" menu:label="~Edit">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5701" menu:helpid="5701" menu:label="Can&apos;t ~Undo"/>
+ <menu:menuitem menu:id="slot:5700" menu:helpid="5700" menu:label="~Can&apos;t Restore"/>
+ <menu:menuitem menu:id="slot:5702" menu:helpid="5702" menu:label="~Repeat"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5710" menu:helpid="5710" menu:label="Cu~t"/>
+ <menu:menuitem menu:id="slot:5711" menu:helpid="5711" menu:label="~Copy"/>
+ <menu:menuitem menu:id="slot:5712" menu:helpid="5712" menu:label="~Paste"/>
+ <menu:menuitem menu:id="slot:20114" menu:helpid="20114" menu:label="Paste ~Special..."/>
+ <menu:menuitem menu:id="slot:20989" menu:helpid="20989" menu:label="~Select Text"/>
+ <menu:menuitem menu:id="slot:5723" menu:helpid="5723" menu:label="Select ~All"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:1" menu:label="Chan~ges">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:21825" menu:helpid="21825" menu:label="~Record"/>
+ <menu:menuitem menu:id="slot:21823" menu:helpid="21823" menu:label="~Protect Records..."/>
+ <menu:menuitem menu:id="slot:21826" menu:helpid="21826" menu:label="~Show"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:21829" menu:helpid="21829" menu:label="~Accept or Reject..."/>
+ <menu:menuitem menu:id="slot:21827" menu:helpid="21827" menu:label="~Comment..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:6587" menu:helpid="6587" menu:label="~Merge Document..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:6586" menu:helpid="6586" menu:label="Compar~e Document..."/>
+ <menu:menuitem menu:id="slot:5961" menu:helpid="5961" menu:label="~Find &amp; Replace..."/>
+ <menu:menuitem menu:id="slot:10366" menu:helpid="10366" menu:label="~Navigator"/>
+ <menu:menuitem menu:id="slot:20620" menu:helpid="20620" menu:label="AutoTe~xt..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20309" menu:helpid="20309" menu:label="Exc~hange Database..."/>
+ <menu:menuitem menu:id="slot:20104" menu:helpid="20104" menu:label="F~ields..."/>
+ <menu:menuitem menu:id="slot:20162" menu:helpid="20162" menu:label="Footnote~..."/>
+ <menu:menuitem menu:id="slot:20123" menu:helpid="20123" menu:label="Index Entr~y..."/>
+ <menu:menuitem menu:id="slot:21833" menu:helpid="21833" menu:label="~Bibliography Entry..."/>
+ <menu:menuitem menu:id="slot:21835" menu:helpid="21835" menu:label="H~yperlink"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20109" menu:helpid="20109" menu:label="Lin~ks..."/>
+ <menu:menuitem menu:id="slot:6314" menu:helpid="6314" menu:label="P~lug-in"/>
+ <menu:menuitem menu:id="slot:10371" menu:helpid="10371" menu:label="I~mageMap"/>
+ <menu:menuitem menu:id="slot:5575" menu:helpid="5575" menu:label="~Object"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:2" menu:label="~View">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10000" menu:helpid="10000" menu:label="~Zoom..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:6660" menu:helpid="6660" menu:label="~Data Sources"/>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:1" menu:label="~Toolbars">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5910" menu:helpid="5910" menu:label="~Function Bar"/>
+ <menu:menuitem menu:id="slot:5905" menu:helpid="5905" menu:label="~Object Bar"/>
+ <menu:menuitem menu:id="slot:5909" menu:helpid="5909" menu:label="Main ~Toolbar"/>
+ <menu:menuitem menu:id="slot:10360" menu:helpid="10360" menu:label="~Hyperlink Bar"/>
+ <menu:menuitem menu:id="slot:20128" menu:helpid="20128" menu:label="Fo~rmula Bar"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5908" menu:helpid="5908" menu:label="Customi~ze..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:20211" menu:helpid="20211" menu:label="~Ruler"/>
+ <menu:menuitem menu:id="slot:5920" menu:helpid="5920" menu:label="~Status Bar"/>
+ <menu:menuitem menu:id="slot:6680" menu:helpid="6680" menu:label="~Input Method Status"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20214" menu:helpid="20214" menu:label="Te~xt Boundaries"/>
+ <menu:menuitem menu:id="slot:20225" menu:helpid="20225" menu:label="Fie~ld Shadings"/>
+ <menu:menuitem menu:id="slot:20226" menu:helpid="20226" menu:label="~Fields"/>
+ <menu:menuitem menu:id="slot:20224" menu:helpid="20224" menu:label="~Nonprinting Characters"/>
+ <menu:menuitem menu:id="slot:20242" menu:helpid="20242" menu:label="~Hidden Paragraphs"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:6313" menu:helpid="6313" menu:label="~Online Layout"/>
+ <menu:menuitem menu:id="slot:5627" menu:helpid="5627" menu:label="F~ull Screen"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:3" menu:label="~Insert">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:20304" menu:helpid="20304" menu:label="Manual ~Break..."/>
+ <menu:menu menu:id="slot:1" menu:label="Fiel~ds">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:20392" menu:helpid="20392" menu:label="~Date"/>
+ <menu:menuitem menu:id="slot:20393" menu:helpid="20393" menu:label="~Time"/>
+ <menu:menuitem menu:id="slot:20394" menu:helpid="20394" menu:label="~Page Number"/>
+ <menu:menuitem menu:id="slot:20395" menu:helpid="20395" menu:label="Page ~Count"/>
+ <menu:menuitem menu:id="slot:20396" menu:helpid="20396" menu:label="~Subject"/>
+ <menu:menuitem menu:id="slot:20397" menu:helpid="20397" menu:label="~Title"/>
+ <menu:menuitem menu:id="slot:20398" menu:helpid="20398" menu:label="~Author"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20308" menu:helpid="20308" menu:label="~Other..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:20328" menu:helpid="20328" menu:label="S~pecial Character..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20345" menu:helpid="20345" menu:label="~Section..."/>
+ <menu:menuitem menu:id="slot:5678" menu:helpid="5678" menu:label="~Hyperlink"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:21413" menu:helpid="21413" menu:label="He~ader"/>
+ <menu:menuitem menu:id="slot:21414" menu:helpid="21414" menu:label="Foote~r"/>
+ <menu:menuitem menu:id="slot:20312" menu:helpid="20312" menu:label="Footnote~..."/>
+ <menu:menuitem menu:id="slot:20310" menu:helpid="20310" menu:label="Captio~n..."/>
+ <menu:menuitem menu:id="slot:20302" menu:helpid="20302" menu:label="Bookmar~k..."/>
+ <menu:menuitem menu:id="slot:20313" menu:helpid="20313" menu:label="~Cross-reference..."/>
+ <menu:menuitem menu:id="slot:20329" menu:helpid="20329" menu:label="Not~e..."/>
+ <menu:menuitem menu:id="slot:21410" menu:helpid="21410" menu:label="S~cript..."/>
+ <menu:menu menu:id="slot:2" menu:label="Inde~xes and Tables">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:20335" menu:helpid="20335" menu:label="~Entry..."/>
+ <menu:menuitem menu:id="slot:21420" menu:helpid="21420" menu:label="~Indexes and Tables..."/>
+ <menu:menuitem menu:id="slot:21421" menu:helpid="21421" menu:label="~Bibliography Entry..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:21050" menu:helpid="21050" menu:label="En~velope..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20334" menu:helpid="20334" menu:label="Fra~me..."/>
+ <menu:menuitem menu:id="slot:20330" menu:helpid="20330" menu:label="~Table..."/>
+ <menu:menuitem menu:id="slot:21411" menu:helpid="21411" menu:label="Hori~zontal Ruler..."/>
+ <menu:menu menu:id="slot:3" menu:label="~Graphics">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10241" menu:helpid="10241" menu:label="From ~File..."/>
+ <menu:menu menu:id="slot:1" menu:label="Scan">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:10331" menu:helpid="10331" menu:label="~Select Source..."/>
+ <menu:menuitem menu:id="slot:10332" menu:helpid="10332" menu:label="~Request..."/>
+ </menu:menupopup>
+ </menu:menu>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:4" menu:label="~Object">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5561" menu:helpid="5561" menu:label="~OLE Object..."/>
+ <menu:menuitem menu:id="slot:5672" menu:helpid="5672" menu:label="~Plug-in..."/>
+ <menu:menuitem menu:id="slot:5676" menu:helpid="5676" menu:label="~Sound..."/>
+ <menu:menuitem menu:id="slot:5677" menu:helpid="5677" menu:label="~Video..."/>
+ <menu:menuitem menu:id="slot:5673" menu:helpid="5673" menu:label="~Applet..."/>
+ <menu:menuitem menu:id="slot:20369" menu:helpid="20369" menu:label="~Formula"/>
+ <menu:menuitem menu:id="slot:10140" menu:helpid="10140" menu:label="~Chart..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:5563" menu:helpid="5563" menu:label="Float~ing Frame"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5532" menu:helpid="5532" menu:label="~File..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5780" menu:label="F~ormat">
+ <menu:menupopup/>
+ </menu:menu>
+ <menu:menu menu:id="slot:6677" menu:label="~Tools">
+ <menu:menupopup>
+ <menu:menu menu:id="slot:1" menu:label="~Spellcheck">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:20622" menu:helpid="20622" menu:label="~Check..."/>
+ <menu:menuitem menu:id="slot:12021" menu:helpid="12021" menu:label="~AutoSpellcheck"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10959" menu:helpid="10959" menu:label="Hangul/Han~ja Conversion"/>
+ <menu:menuitem menu:id="slot:20603" menu:helpid="20603" menu:label="~Thesaurus..."/>
+ <menu:menuitem menu:id="slot:20605" menu:helpid="20605" menu:label="~Hyphenation..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10424" menu:helpid="10424" menu:label="~AutoCorrect/AutoFormat..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20612" menu:helpid="20612" menu:label="Outline ~Numbering..."/>
+ <menu:menuitem menu:id="slot:20602" menu:helpid="20602" menu:label="~Line Numbering..."/>
+ <menu:menuitem menu:id="slot:20468" menu:helpid="20468" menu:label="~Footnotes..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5960" menu:helpid="5960" menu:label="~Gallery"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:10880" menu:helpid="10880" menu:label="~Bibliography Database"/>
+ <menu:menuitem menu:id="slot:10882" menu:helpid="10882" menu:label="~Data Sources..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20364" menu:helpid="20364" menu:label="~Mail Merge..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20500" menu:helpid="20500" menu:label="Te~xt &lt;-&gt; Table..."/>
+ <menu:menuitem menu:id="slot:20614" menu:helpid="20614" menu:label="So~rt..."/>
+ <menu:menuitem menu:id="slot:20615" menu:helpid="20615" menu:label="Calculat~e"/>
+ <menu:menu menu:id="slot:2" menu:label="~Update">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:21828" menu:helpid="21828" menu:label="~Update All"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:20126" menu:helpid="20126" menu:label="~Fields"/>
+ <menu:menuitem menu:id="slot:21824" menu:helpid="21824" menu:label="~Links"/>
+ <menu:menuitem menu:id="slot:21834" menu:helpid="21834" menu:label="All ~Charts"/>
+ <menu:menuitem menu:id="slot:20654" menu:helpid="20654" menu:label="Current ~Index"/>
+ <menu:menuitem menu:id="slot:20653" menu:helpid="20653" menu:label="~All Indexes and Tables"/>
+ <menu:menuitem menu:id="slot:20161" menu:helpid="20161" menu:label="Page Formatting"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuseparator/>
+ <menu:menu menu:id="slot:3" menu:label="~Macros">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:6669" menu:helpid="6669" menu:label="Record Macro"/>
+ <menu:menuitem menu:id="slot:5959" menu:helpid="5959" menu:label="~Macro..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:10958" menu:helpid="10958" menu:label="~XML Filter Settings..."/>
+ <menu:menuitem menu:id="slot:5904" menu:helpid="5904" menu:label="~Configure..."/>
+ <menu:menu menu:id="slot:4" menu:label="Scripting Add-ons">
+ <menu:menupopup>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteMenuBinding()" menu:label="Assign Script to ~Menu..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteKeyBinding" menu:label="Assign Script to ~Key..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteEventBinding()" menu:label="Assign Script to ~Event..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.ExecuteEditDebug" menu:label="Edit/De~bug Scripts..."/>
+ <menu:menuitem menu:id="macro:///ScriptBindingLibrary.ScriptBinding.RefreshAllScripts()" menu:label="~Refresh All Scripts"/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menuitem menu:id="slot:31630" menu:helpid="31630" menu:label="~Options..."/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5610" menu:label="~Window">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5620" menu:helpid="5620" menu:label="~New Window"/>
+ <menu:menuitem menu:id="slot:5621" menu:helpid="5621" menu:label="~Close Window"/>
+ <menu:menuseparator/>
+ </menu:menupopup>
+ </menu:menu>
+ <menu:menu menu:id="slot:5410" menu:label="~Help">
+ <menu:menupopup>
+ <menu:menuitem menu:id="slot:5401" menu:helpid="5401" menu:label="~Contents"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5962" menu:helpid="5962" menu:label="Help ~Agent"/>
+ <menu:menuitem menu:id="slot:5404" menu:helpid="5404" menu:label="~Tips"/>
+ <menu:menuitem menu:id="slot:5403" menu:helpid="5403" menu:label="~Extended Tips"/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:6683" menu:helpid="6683" menu:label="~Support"/>
+ <menu:menuitem menu:id="slot:6537" menu:helpid="6537" menu:label="~Registration..."/>
+ <menu:menuseparator/>
+ <menu:menuitem menu:id="slot:5301" menu:helpid="5301" menu:label="A~bout OpenOffice.org..."/>
+ </menu:menupopup>
+ </menu:menu>
+</menu:menubar>
diff --git a/scripting/workben/build.xml b/scripting/workben/build.xml
new file mode 100755
index 000000000000..2c8cedda8dc8
--- /dev/null
+++ b/scripting/workben/build.xml
@@ -0,0 +1,401 @@
+<!--
+
+ DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+
+ Copyright 2008 by Sun Microsystems, Inc.
+
+ OpenOffice.org - a multi-platform office productivity suite
+
+ $RCSfile: build.xml,v $
+
+ $Revision: 1.31.20.1 $
+
+ This file is part of OpenOffice.org.
+
+ OpenOffice.org is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License version 3
+ only, as published by the Free Software Foundation.
+
+ OpenOffice.org is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License version 3 for more details
+ (a copy is included in the LICENSE file that accompanied this code).
+
+ You should have received a copy of the GNU Lesser General Public License
+ version 3 along with OpenOffice.org. If not, see
+ <http://www.openoffice.org/license.html>
+ for a copy of the LGPLv3 License.
+
+-->
+<project name="Scipting Framework Installer" default="jar" basedir=".">
+
+ <!-- =================== Environmental Properties ======================= -->
+
+ <property name="prj" value=".."/>
+ <property file="${prj}/java/build.env"/>
+ <property name="build.compiler" value="classic"/>
+ <property name="optimize" value="on"/>
+ <property name="debug" value="on"/>
+ <property name="installerclasses" value="${out}/class/sframeworkinstall"/>
+ <property name="jardir" value="${out}/class"/>
+ <property name="bindir" value="${out}/bin"/>
+ <property name="sfversion" value="0.3"/>
+ <property name="installerjarname" value="SFrameworkInstall.jar"/>
+ <property environment="env"/>
+
+ <!-- ==================== classpath setting ============================ -->
+ <path id="idlclasspath">
+ <pathelement location="${solar.jar}/unoil.jar"/>
+ <!-- <pathelement location="${prj}/../unoil/${inpath}/class/unoil.jar"/> -->
+ <pathelement location="${solar.jar}/jurt.jar"/>
+ <pathelement location="${solar.jar}/juh.jar"/>
+ <pathelement location="${solar.jar}/java_uno.jar"/>
+ <pathelement location="${solar.jar}/ridl.jar"/>
+ </path>
+ <path id="scriptexampleclasspath">
+ <pathelement location="${solar.jar}/unoil.jar"/>
+ <!-- pathelement location="${prj}/../unoil/${inpath}/class/unoil.jar"/ -->
+ <pathelement location="${solar.jar}/jurt.jar"/>
+ <pathelement location="${solar.jar}/juh.jar"/>
+ <pathelement location="${solar.jar}/java_uno.jar"/>
+ <pathelement location="${solar.jar}/ridl.jar"/>
+ <pathelement location="${out}/class/ScriptRuntimeForJava.jar"/>
+ </path>
+
+ <path id="debuggerclasspath">
+ <pathelement location="${out}/class/ScriptRuntimeForJava.jar"/>
+ <pathelement location="${solar.jar}/ridl.jar"/>
+ <pathelement location="${solar.jar}/unoil.jar"/>
+ <pathelement location="${out}/class/jsruntime/skip_registration/js.jar"/>
+ <pathelement location="${install.dir}/bsh-1.2b7.jar"/>
+ </path>
+ <!-- ===================== Set up build conditionals ========================= -->
+ <target name="product.test">
+ <condition property="noproext">
+ <equals arg1="$${env.PROEXT}" arg2="${env.PROEXT}"/>
+ </condition>
+ </target>
+ <target name="nonproduct.set" if="noproext">
+ <echo message="non-product build"/>
+ <property name="proext" value=""/>
+ </target>
+ <target name="product.set" unless="noproext">
+ <echo message="product build"/>
+ <property name="proext" value="${env.PROEXT}"/>
+ </target>
+ <target name="build.conditions" depends="product.test,nonproduct.set,product.set">
+ <condition property="win9.build">
+ <available file="${prj}/wntmsci9${proext}"/>
+ </condition>
+ <condition property="win8.build">
+ <available file="${prj}/wntmsci8${proext}"/>
+ </condition>
+ <condition property="win7.build">
+ <available file="${prj}/wntmsci7${proext}"/>
+ </condition>
+ <condition property="linx86.build">
+ <available file="${prj}/unxlngi5${proext}"/>
+ </condition>
+ <condition property="solsparc.build">
+ <available file="${prj}/unxsols4${proext}"/>
+ </condition>
+ <!-- <condition property="openoffice.build">
+ </condition> -->
+ </target>
+ <!-- ===================== Build the examples ========================= -->
+ <target name="buildexamples">
+
+ <mkdir dir="${out}/class/examples/java/debugger"/>
+ <javac srcdir="${prj}/examples/java/debugger"
+ destdir="${out}/class/examples/java/debugger"
+ includes="*.java"
+ classpathref="debuggerclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="on"/>
+
+ <copy todir="${out}/class/examples/java/debugger">
+ <fileset dir="${prj}/examples/java/debugger">
+ <include name="**/*.java"/>
+ <include name="*.xml"/>
+ </fileset>
+ </copy>
+
+ <jar jarfile="${out}/class/examples/java/debugger/debugger.jar"
+ basedir="${out}/class/examples/java/debugger" includes="*.class">
+ <manifest>
+ <attribute name="Built-By" value="Sun Microsystems"/>
+ <attribute name="ScriptFramework-Version" value="${sfversion}"/>
+ </manifest>
+ </jar>
+
+ <delete>
+ <fileset dir="${out}/class/examples/java/debugger" includes="*.class"/>
+ </delete>
+
+ <mkdir dir="${out}/class/examples/java/Highlight"/>
+ <javac srcdir="${prj}/examples/java/" destdir="${out}/class/examples/java/Highlight/"
+ includes="**/Highlight*.java" classpathref="idlclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="on"/>
+ <copy todir="${out}/class/examples/java/Highlight/">
+ <fileset dir="${prj}/examples/java/">
+ <include name="**/Highlight*.java"/>
+ </fileset>
+ </copy>
+ <copy file="${prj}/examples/java/HighlightTextParcel.xml" tofile="${out}/class/examples/java/Highlight/parcel-descriptor.xml"/>
+ <jar jarfile="${out}/class/examples/java/Highlight/Highlight.jar"
+ basedir="${out}/class/examples/java/Highlight"
+ includes="**/*.java,**/*.class,**/*.xml"
+ excludes="${out}/class/examples/java/Highlight/Highlight.jar">
+ <manifest>
+ <attribute name="Built-By" value="Sun Microsystems"/>
+ <attribute name="ScriptFramework-Version" value="${sfversion}"/>
+ </manifest>
+ </jar>
+ <mkdir dir="${out}/class/examples/java/MemoryUsage"/>
+ <javac srcdir="${prj}/examples/java/" destdir="${out}/class/examples/java/MemoryUsage/"
+ includes="**/MemoryUsage.java" classpathref="idlclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="on"/>
+ <copy file="${prj}/examples/java/MemoryUsage.java" todir="${out}/class/examples/java/MemoryUsage/"/>
+ <copy file="${prj}/examples/java/MemoryUsageParcel.xml" tofile="${out}/class/examples/java/MemoryUsage/parcel-descriptor.xml"/>
+ <copy file="${prj}/examples/java/MemoryUsage.java" todir="${out}/class/examples/java/MemoryUsage/"/>
+ <copy file="${prj}/examples/java/ExampleSpreadSheet.sxc" todir="${out}/class/examples/java/MemoryUsage/"/>
+
+ <mkdir dir="${out}/class/examples/java/ScriptFrmwrkHelper"/>
+ <javac srcdir="${prj}/examples/java/" destdir="${out}/class/examples/java/ScriptFrmwrkHelper/"
+ includes="**/ScriptFrmwrkHelper.java" classpathref="scriptexampleclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="on"/>
+ <copy todir="${out}/class/examples/java/ScriptFrmwrkHelper/">
+ <fileset dir="${prj}/examples/java/">
+ <include name="**/ScriptFrmwrkHelper.java"/>
+ </fileset>
+ </copy>
+ <copy file="${prj}/examples/java/ScriptFrameWkHelperParcel.xml" tofile="${out}/class/examples/java/ScriptFrmwrkHelper/parcel-descriptor.xml"/>
+ <jar jarfile="${out}/class/examples/java/ScriptFrmwrkHelper/ScriptFrmwrkHelper.jar"
+ basedir="${out}/class/examples/java/ScriptFrmwrkHelper"
+ includes="**/*.java,**/*.class,**/*.xml"
+ excludes="${out}/class/examples/java/ScriptFrmwrkHelper/ScriptFrmwrkHelper.jar">
+ <manifest>
+ <attribute name="Built-By" value="Sun Microsystems"/>
+ <attribute name="ScriptFramework-Version" value="${sfversion}"/>
+ </manifest>
+ </jar>
+ <mkdir dir="${out}/class/examples/beanshell"/>
+ <copy todir="${out}/class/examples/beanshell">
+ <fileset dir="${prj}/examples/beanshell" includes="**"/>
+ </copy>
+ <mkdir dir="${out}/class/examples/javascript"/>
+ <copy todir="${out}/class/examples/javascript">
+ <fileset dir="${prj}/examples/javascript" includes="**"/>
+ </copy>
+ </target>
+
+ <!-- ===================== Build UNO package ========================= -->
+ <target name="buildunopackage_win9" depends="build.conditions" if="win9.build">
+ <mkdir dir="${out}/class/sframeworkinstall/sframework"/>
+ <mkdir dir="${out}/class/sframework"/>
+ <copy file="${solar.bin}/ScriptFramework.rdb"
+ todir="${out}/class/sframework/"/>
+ <copy file="${out}/class/ScriptRuntimeForJava.jar"
+ todir="${out}/class/sframework/"/>
+ <copy file="${out}/class/ScriptFramework.jar"
+ todir="${out}/class/sframework/"/>
+ <mkdir dir="${out}/class/sframework/windows.plt"/>
+ <copy todir="${out}/class/sframework/windows.plt">
+ <fileset dir="${prj}/wntmsci9${proext}/bin/">
+ <include name="**/*.dll"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${out}/class/sframework/skip_registration"/>
+ <copy file="${solar.jar}/unoil.jar"
+ todir="${out}/class/sframework/skip_registration"/>
+ </target>
+ <target name="buildunopackage_win8" depends="build.conditions" if="win8.build">
+ <mkdir dir="${out}/class/sframeworkinstall/sframework"/>
+ <mkdir dir="${out}/class/sframework"/>
+ <copy file="${solar.bin}/ScriptFramework.rdb"
+ todir="${out}/class/sframework/"/>
+ <copy file="${out}/class/ScriptRuntimeForJava.jar"
+ todir="${out}/class/sframework/"/>
+ <copy file="${out}/class/ScriptFramework.jar"
+ todir="${out}/class/sframework/"/>
+ <mkdir dir="${out}/class/sframework/windows.plt"/>
+ <copy todir="${out}/class/sframework/windows.plt">
+ <fileset dir="${prj}/wntmsci8${proext}/bin/">
+ <include name="**/*.dll"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${out}/class/sframework/skip_registration"/>
+ <copy file="${solar.jar}/unoil.jar"
+ todir="${out}/class/sframework/skip_registration"/>
+ </target>
+<!-- <target name="buildunopackage_win7" depends="build.conditions" if="win7.build">
+ <mkdir dir="${out}/class/sframeworkinstall/sframework"/>
+ <mkdir dir="${out}/class/sframework"/>
+ <copy file="${solar.bin}/ScriptFramework.rdb"
+ todir="${out}/class/sframework/"/>
+ <copy file="${out}/class/ScriptRuntimeForJava.jar"
+ todir="${out}/class/sframework/"/>
+ <copy file="${out}/class/ScriptFramework.jar"
+ todir="${out}/class/sframework/"/>
+ <mkdir dir="${out}/class/sframework/windows.plt"/>
+ <copy todir="${out}/class/sframework/windows.plt">
+ <fileset dir="${prj}/wntmsci7${proext}/bin/">
+ <include name="**/*.dll"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${out}/class/sframework/skip_registration"/>
+ <copy file="${solar.jar}/unoil.jar"
+ todir="${out}/class/sframework/skip_registration"/>
+ </target> -->
+ <target name="buildunopackage_linux" depends="build.conditions" if="linx86.build">
+ <mkdir dir="${out}/class/sframeworkinstall/sframework"/>
+ <mkdir dir="${out}/class/sframework"/>
+ <copy file="${solar.bin}/ScriptFramework.rdb"
+ todir="${out}/class/sframework/"/>
+ <copy file="${out}/class/ScriptRuntimeForJava.jar"
+ todir="${out}/class/sframework/"/>
+ <copy file="${out}/class/ScriptFramework.jar"
+ todir="${out}/class/sframework/"/>
+ <mkdir dir="${out}/class/sframework/linux_x86.plt"/>
+ <copy todir="${out}/class/sframework/linux_x86.plt">
+ <fileset dir="${prj}/unxlngi5${proext}/lib/">
+ <include name="**/lib*.so"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${out}/class/sframework/skip_registration"/>
+ <copy file="${solar.jar}/unoil.jar"
+ todir="${out}/class/sframework/skip_registration"/>
+ </target>
+ <target name="buildunopackage_solaris" depends="build.conditions" if="solsparc.build">
+ <mkdir dir="${out}/class/sframeworkinstall/sframework"/>
+ <mkdir dir="${out}/class/sframework"/>
+ <copy file="${solar.bin}/ScriptFramework.rdb"
+ todir="${out}/class/sframework/"/>
+ <copy file="${out}/class/ScriptRuntimeForJava.jar"
+ todir="${out}/class/sframework/"/>
+ <copy file="${out}/class/ScriptFramework.jar"
+ todir="${out}/class/sframework/"/>
+ <mkdir dir="${out}/class/sframework/solaris_sparc.plt"/>
+ <copy todir="${out}/class/sframework/solaris_sparc.plt">
+ <fileset dir="${prj}/unxsols4${proext}/lib/">
+ <include name="**/lib*.so"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${out}/class/sframework/skip_registration"/>
+ <copy file="${solar.jar}/unoil.jar"
+ todir="${out}/class/sframework/skip_registration"/>
+ </target>
+ <target name="buildunopackage" depends="buildunopackage_win8,buildunopackage_linux,buildunopackage_solaris">
+ <!-- <target name="buildunopackage" depends="buildunopackage_win9,buildunopackage_win7,buildunopackage_linux,buildunopackage_solaris"> -->
+ <copy file="installer/ProtocolHandler.xcu"
+ todir="${out}/class/sframework/"/>
+ <zip zipfile="${out}/class/sframeworkinstall/sframework/ooscriptframe.zip"
+ basedir="${out}/class/sframework">
+ </zip>
+ </target>
+
+ <!-- ================== Build JavaScript UNO package ===================== -->
+ <target name="buildjsuno">
+ <mkdir dir="${out}/class/sframeworkinstall/sframework"/>
+
+ <mkdir dir="${out}/class/jsruntime"/>
+ <mkdir dir="${out}/class/jsruntime/skip_registration"/>
+ <mkdir dir="${out}/class/jsruntimetmp"/>
+
+ <copy file="${out}/class/ScriptRuntimeForJavaScript.jar"
+ todir="${out}/class/jsruntime/"/>
+ <copy file="installer/Scripting.JavaScript.xcu"
+ tofile="${out}/class/jsruntime/Scripting.xcu"/>
+
+ <unzip src="${install.dir}/js.jar"
+ dest="${out}/class/jsruntimetmp"/>
+
+ <javac srcdir="${prj}/examples/java/debugger"
+ destdir="${out}/class/jsruntimetmp"
+ includes="rhino/Main.java" classpathref="debuggerclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="on"/>
+
+ <zip destfile="${out}/class/jsruntime/skip_registration/js.jar"
+ basedir="${out}/class/jsruntimetmp" includes="**"/>
+
+ <zip zipfile="${out}/class/sframeworkinstall/sframework/jsruntime.zip"
+ basedir="${out}/class/jsruntime">
+ </zip>
+ </target>
+
+ <!-- =================== Build BeanShell UNO package ===================== -->
+ <target name="buildbshuno">
+ <mkdir dir="${out}/class/bshruntime"/>
+ <copy file="${out}/class/ScriptRuntimeForBeanShell.jar"
+ todir="${out}/class/bshruntime/"/>
+ <copy file="installer/Scripting.BeanShell.xcu"
+ tofile="${out}/class/bshruntime/Scripting.xcu"/>
+ <mkdir dir="${out}/class/bshruntime/skip_registration"/>
+ <copy file="${install.dir}/bsh-1.2b7.jar"
+ todir="${out}/class/bshruntime/skip_registration"/>
+ <zip zipfile="${out}/class/sframeworkinstall/sframework/bshruntime.zip"
+ basedir="${out}/class/bshruntime">
+ </zip>
+ </target>
+
+ <!-- ========= Package schema, scripts, dialogs & examples =========== -->
+ <target name="packagedialogsandexamples" depends="buildexamples">
+ <mkdir dir="${out}/class/sframeworkinstall/schema"/>
+ <copy file="installer/Scripting.xcs"
+ todir="${out}/class/sframeworkinstall/schema/"/>
+ <mkdir dir="${out}/class/sframeworkinstall/bindingdialog"/>
+ <copy todir="${out}/class/sframeworkinstall/bindingdialog">
+ <fileset dir="bindings/">
+ <include name="**/*.x*"/>
+ </fileset>
+ </copy>
+ <mkdir dir="${out}/class/sframeworkinstall/examples"/>
+ <copy todir="${out}/class/sframeworkinstall/examples">
+ <fileset dir="${out}/class/examples/"/>
+ </copy>
+ </target>
+
+ <!-- ===================== Package IDEs ================================== -->
+ <target name="packageide">
+ <mkdir dir="${out}/class/sframeworkinstall/ide"/>
+ <copy todir="${out}/class/sframeworkinstall/ide">
+ <fileset dir="${out}/class/">
+ <include name="idesupport.jar"/>
+ <include name="office.jar"/>
+ </fileset>
+ </copy>
+ </target>
+
+ <!-- ======================== Compile Classes ========================== -->
+ <target name="compileinstaller">
+ <mkdir dir="${installerclasses}"/>
+ <javac srcdir="installer/" destdir="${installerclasses}"
+ includes="**/*.java" classpathref="idlclasspath"
+ debug="${debug}" optimize="${optimize}" deprecation="on"/>
+ <copy file="installer/sidebar.jpg" todir="${out}/class/sframeworkinstall/installer"/>
+ </target>
+
+ <!-- ===================== jar ========================= -->
+ <target name="jar" depends="buildunopackage,buildbshuno,buildjsuno,compileinstaller,packagedialogsandexamples,packageide">
+ <jar jarfile="${jardir}/${installerjarname}"
+ basedir="${installerclasses}">
+ <manifest>
+ <attribute name="Built-By" value="Sun Microsystems"/>
+ <attribute name="ScriptFramework-Version" value="${sfversion}"/>
+ <attribute name="Main-Class" value="installer.InstallWizard"/>
+ </manifest>
+ </jar>
+ </target>
+
+ <!-- ====================== Clean Generated Files ===================== -->
+ <target name="clean">
+ <delete dir="${scriptingclasses}"/>
+ <delete dir="${storageclasses}"/>
+ <delete dir="${jardir}/${scriptingjarname}"/>
+ </target>
+
+ <!-- ========================= All In One Build ======================= -->
+ <target name="all" depends="clean,jar"/>
+
+
+</project>
diff --git a/scripting/workben/data/ExampleSpreadSheetLatest.sxc b/scripting/workben/data/ExampleSpreadSheetLatest.sxc
new file mode 100644
index 000000000000..7be6c0d4be05
--- /dev/null
+++ b/scripting/workben/data/ExampleSpreadSheetLatest.sxc
Binary files differ
diff --git a/scripting/workben/data/doc_with_beanshell_scripts.sxw b/scripting/workben/data/doc_with_beanshell_scripts.sxw
new file mode 100644
index 000000000000..f0066610d577
--- /dev/null
+++ b/scripting/workben/data/doc_with_beanshell_scripts.sxw
Binary files differ
diff --git a/scripting/workben/data/doc_with_one_script.sxw b/scripting/workben/data/doc_with_one_script.sxw
new file mode 100644
index 000000000000..7445f4afca47
--- /dev/null
+++ b/scripting/workben/data/doc_with_one_script.sxw
Binary files differ
diff --git a/scripting/workben/data/doc_with_two_scripts.sxw b/scripting/workben/data/doc_with_two_scripts.sxw
new file mode 100644
index 000000000000..23a12ac9f86a
--- /dev/null
+++ b/scripting/workben/data/doc_with_two_scripts.sxw
Binary files differ
diff --git a/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.protocolhandler.Dispatch.csv b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.protocolhandler.Dispatch.csv
new file mode 100644
index 000000000000..614260db95c3
--- /dev/null
+++ b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.protocolhandler.Dispatch.csv
@@ -0,0 +1,5 @@
+"Dispatch";"drafts::com::sun::star::frame::XDispatchProvider";"queryDispatch()"
+"Dispatch";"drafts::com::sun::star::frame::XDispatchProvider";"queryDispatches()"
+"Dispatch";"drafts::com::sun::star::frame::XDispatch";"dispatch()"
+"Dispatch";"drafts::com::sun::star::frame::XDispatch";"addStatusListener()"
+"Dispatch";"drafts::com::sun::star::frame::XDispatch";"removeStatusListener()"
diff --git a/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.provider.Function.csv b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.provider.Function.csv
new file mode 100644
index 000000000000..87327525908a
--- /dev/null
+++ b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.provider.Function.csv
@@ -0,0 +1 @@
+"Function";"drafts::com::sun::star::script::framework::provider::XFunction";"invoke()"
diff --git a/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.provider.FunctionProvider.csv b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.provider.FunctionProvider.csv
new file mode 100644
index 000000000000..0f1c41772cfb
--- /dev/null
+++ b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.provider.FunctionProvider.csv
@@ -0,0 +1 @@
+"FunctionProvider";"drafts::com::sun::star::script::framework::provider::XFunctionProvider";"getFunction()"
diff --git a/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.runtime.ScriptRuntimeManager.csv b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.runtime.ScriptRuntimeManager.csv
new file mode 100755
index 000000000000..0bff1a1a89b7
--- /dev/null
+++ b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.runtime.ScriptRuntimeManager.csv
@@ -0,0 +1,2 @@
+"ScriptRuntimeManager";"drafts::com::sun::star::script::framework::runtime::XScriptNameResolver";"resolve()"
+"ScriptRuntimeManager";"drafts::com::sun::star::script::framework::runtime::XScriptInvocation";"invoke()"
diff --git a/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptInfo.csv b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptInfo.csv
new file mode 100644
index 000000000000..79e8c91e19c1
--- /dev/null
+++ b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptInfo.csv
@@ -0,0 +1,8 @@
+"ScriptInfo";"drafts::com::sun::star::script::framework::storage::XScriptInfo";"getLogicalName()"
+"ScriptInfo";"drafts::com::sun::star::script::framework::storage::XScriptInfo";"getParcelURI()"
+"ScriptInfo";"drafts::com::sun::star::script::framework::storage::XScriptInfo";"getLanguage()"
+"ScriptInfo";"drafts::com::sun::star::script::framework::storage::XScriptInfo";"getFunctionName()"
+"ScriptInfo";"drafts::com::sun::star::script::framework::storage::XScriptInfo";"getLanguageProperties()"
+"ScriptInfo";"drafts::com::sun::star::script::framework::storage::XScriptInfo";"getFileSetNames()"
+"ScriptInfo";"drafts::com::sun::star::script::framework::storage::XScriptInfo";"getFilesInFileSet()"
+"ScriptInfo";"drafts::com::sun::star::script::framework::storage::XScriptInfo";"getDescription()"
diff --git a/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptStorage.csv b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptStorage.csv
new file mode 100644
index 000000000000..69628462fedb
--- /dev/null
+++ b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptStorage.csv
@@ -0,0 +1,4 @@
+"ScriptStorage";"drafts::com::sun::star::script::framework::storage::XScriptInfoAccess";"getScriptLogicalNames()"
+"ScriptStorage";"drafts::com::sun::star::script::framework::storage::XScriptInfoAccess";"getImplementations()"
+"ScriptStorage";"drafts::com::sun::star::script::framework::storage::XScriptInfoAccess";"getAllImplementations()"
+"ScriptStorage";"drafts::com::sun::star::script::framework::storage::XScriptStorageRefresh";"refresh()"
diff --git a/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptStorageManager.csv b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptStorageManager.csv
new file mode 100644
index 000000000000..6e255c869f67
--- /dev/null
+++ b/scripting/workben/data/objdsc/drafts.com.sun.star.script.framework.storage.ScriptStorageManager.csv
@@ -0,0 +1,6 @@
+"ScriptStorageManager";"drafts::com::sun::star::script::framework::storage::XScriptStorageManager";"createScriptStorage()"
+"ScriptStorageManager";"drafts::com::sun::star::script::framework::storage::XScriptStorageManager";"createScriptStorageWithURI()"
+"ScriptStorageManager";"drafts::com::sun::star::script::framework::storage::XScriptStorageManager";"getScriptStorage()"
+"ScriptStorageManager";"drafts::com::sun::star::script::framework::storage::XScriptStorageManager";"refreshScriptStorage()"
+"ScriptStorageManager";"drafts::com::sun::star::script::framework::security::XScriptSecurity";"checkPermission()"
+"ScriptStorageManager";"::com::sun::star::lang::XEventListener";"disposing()"
diff --git a/scripting/workben/data/script_in_class_file.sxw b/scripting/workben/data/script_in_class_file.sxw
new file mode 100644
index 000000000000..ddb44c14d2d3
--- /dev/null
+++ b/scripting/workben/data/script_in_class_file.sxw
Binary files differ
diff --git a/scripting/workben/data/script_in_jar_file.sxw b/scripting/workben/data/script_in_jar_file.sxw
new file mode 100644
index 000000000000..93b10494d266
--- /dev/null
+++ b/scripting/workben/data/script_in_jar_file.sxw
Binary files differ
diff --git a/scripting/workben/data/share_scripts.zip b/scripting/workben/data/share_scripts.zip
new file mode 100644
index 000000000000..7c7fec622930
--- /dev/null
+++ b/scripting/workben/data/share_scripts.zip
Binary files differ
diff --git a/scripting/workben/data/testdata/Function.csv b/scripting/workben/data/testdata/Function.csv
new file mode 100644
index 000000000000..b924c86f4bd6
--- /dev/null
+++ b/scripting/workben/data/testdata/Function.csv
@@ -0,0 +1,4 @@
+_invoke;description=Try to find and invoke a valid user level XFunction;logicalname=script://HighlightText.showForm;expected=success
+_invoke;description=Try to invoke a valid beanshell XFunction that returns an Integer;logicalname=script://returns-Integer;returntype=java.lang.Integer;expected=success
+_invoke;description=Try to invoke a valid beanshell XFunction that returns a String;logicalname=script://returns-String;returntype=java.lang.String;returnvalue=testing;expected=success
+_invoke;description=Try to invoke a valid beanshell XFunction that returns a Frame;logicalname=script://returns-Frame;expected=com.sun.star.uno.RuntimeException
diff --git a/scripting/workben/data/testdata/FunctionProvider.csv b/scripting/workben/data/testdata/FunctionProvider.csv
new file mode 100644
index 000000000000..88dcfae118e3
--- /dev/null
+++ b/scripting/workben/data/testdata/FunctionProvider.csv
@@ -0,0 +1 @@
+_getFunction;description=Try to get a valid XFunction;logicalname=script://MemoryUtils.MemUsage;expected=XFunction.class
diff --git a/scripting/workben/data/testdata/ScriptInfo.csv b/scripting/workben/data/testdata/ScriptInfo.csv
new file mode 100644
index 000000000000..a5fab2ad5d16
--- /dev/null
+++ b/scripting/workben/data/testdata/ScriptInfo.csv
@@ -0,0 +1,8 @@
+_getLogicalName;description=Try to get a logical name;expected=MemoryUtils.MemUsage
+_getParcelURI;description=Try to get a parcel URI;expected=ExampleSpreadSheetLatest.sxc/Scripts/java/MemoryUsage
+_getLanguage;description=Try to get language;expected=Java
+_getFunctionName;description=Try to get a function name;expected=MemoryUsage.updateMemoryUsage
+_getLanguageProperties;description=Try to get language properties;expected=MemUsage.jar
+_getFileSetNames;description=Try to get fileset names;expected=delivered
+_getFilesInFileSet;description=Try to get files in fileset;expected=google.jar
+_getDescription;description=Try to get description;expected=Show JVM memory usage stats
diff --git a/scripting/workben/data/testdata/ScriptRuntimeManager.csv b/scripting/workben/data/testdata/ScriptRuntimeManager.csv
new file mode 100644
index 000000000000..b5d049b5f425
--- /dev/null
+++ b/scripting/workben/data/testdata/ScriptRuntimeManager.csv
@@ -0,0 +1,8 @@
+_resolve;description=Try to resolve a valid document URI;location=script_in_class_file.sxw;logicalname=script://doc.jsuite.testMethod;expected=XScriptInfo.class
+_resolve;description=Try to resolve a valid user URI;location=user;logicalname=script://user.jsuite.test;expected=XScriptInfo.class
+_resolve;description=Try to resolve a valid share URI;location=share;logicalname=script://share.jsuite.test;expected=XScriptInfo.class
+_resolve;description=Try to resolve an invalid URI;location=user;logicalname=scrpit://user.jsuite.test;expected=com.sun.star.lang.IllegalArgumentException
+_resolve;description=Try to resolve a valid but non existent URI;location=user;logicalname=script://non.existent.test;expected=null
+_invoke;description=Try to invoke a valid user level URI;location=user;context=null;logicalname=script://user.jsuite.test;expected=success
+_invoke;description=Try to invoke a valid user level URI with a valid context;location=user;context=xscriptcontext_test_document.sxw;logicalname=script://xscriptcontext.jsuite.test;expected=success
+_invoke;description=Try to invoke a valid user level script in a jar file;location=user;context=null;logicalname=script://jarscript.jsuite.test;expected=success
diff --git a/scripting/workben/data/testdata/ScriptStorage.csv b/scripting/workben/data/testdata/ScriptStorage.csv
new file mode 100644
index 000000000000..a5b4589e6f64
--- /dev/null
+++ b/scripting/workben/data/testdata/ScriptStorage.csv
@@ -0,0 +1,4 @@
+_getScriptLogicalNames;description=Try to get logical names;expected=MemoryUtils.MemUsage
+_getImplementations;description=Try to get a valid implementation;logicalname=script://MemoryUtils.MemUsage?location=document;expected=MemoryUtils.MemUsage
+_getAllImplementations;description=Try to get all valid implementations;location=doc_with_beanshell_scripts.sxw;expected=returns-Integer,returns-String,returns-Frame
+_refresh;description=Try calling refresh;expected=success
diff --git a/scripting/workben/data/testdata/ScriptStorageManager.csv b/scripting/workben/data/testdata/ScriptStorageManager.csv
new file mode 100644
index 000000000000..9dc2a9b67bf2
--- /dev/null
+++ b/scripting/workben/data/testdata/ScriptStorageManager.csv
@@ -0,0 +1,18 @@
+_createScriptStorage;description=Try to create a ScriptStorage;expected=success
+_createScriptStorageWithURI;description=Try to create a document ScriptStorage;location=script_in_class_file.sxw;expected=XScriptInfoAccess.class
+_getScriptStorage;description=Try to get application share ScriptStorage;location=share;expected=XScriptInfoAccess.class
+_getScriptStorage;description=Try to get application user ScriptStorage;location=user;expected=XScriptInfoAccess.class
+_refreshScriptStorage;description=Try to refresh non-existent ScriptStorage;location=non-existent;expected=success
+_refreshScriptStorage;description=Try to refresh valid document ScriptStorage;location=script_in_class_file.sxw;expected=success
+_checkPermission;description=Try to get permssion when run macro is set to never;location=check_perms_file1.sxw;runmacro=never;pathlist=false;confirm=false;warning=false;dialog=false;checkbox=false;buttonName=Run;checkpath=false;expected=com.sun.star.security.AccessControlException
+_checkPermission;description=Try to get permssion when run macro is set to always, and no warning dialog;location=check_perms_file2.sxw;runmacro=always;pathlist=false;confirm=false;warning=false;dialog=false;checkbox=false;buttonName=Run;checkpath=false;expected=true
+_checkPermission;description=Try to get permssion when run macro is set to always, warning dialog, and run button pressed;location=check_perms_file3.sxw;runmacro=always;pathlist=false;confirm=false;warning=true;dialog=true;checkbox=false;buttonName=Run;checkpath=false;expected=true
+_checkPermission;description=Try to get permssion when run macro is set to always, warning dialog, and do not run button pressed;location=check_perms_file4.sxw;runmacro=always;pathlist=false;confirm=false;warning=true;dialog=true;checkbox=false;buttonName=Do Not Run;checkpath=false;expected=com.sun.star.security.AccessControlException
+_checkPermission;description=Try to get permssion when run macro is set to according to path list, doc in path, no warning dialog, and no confirmation;location=check_perms_file5.sxw;runmacro=pathlist;pathlist=true;confirm=false;warning=false;dialog=false;checkbox=false;buttonName=Do Not Run;checkpath=false;expected=true
+_checkPermission;description=Try to get permssion when run macro is set to according to path list, doc not in path, no warning dialog, and no confirmation;location=check_perms_file6.sxw;runmacro=pathlist;pathlist=false;confirm=false;warning=false;dialog=false;checkbox=false;buttonName=Do Not Run;checkpath=false;expected=com.sun.star.security.AccessControlException
+_checkPermission;description=Try to get permssion when run macro is set to according to path list, doc in path, warning dialog, run button pressed;location=check_perms_file7.sxw;runmacro=pathlist;pathlist=true;confirm=false;warning=true;dialog=true;checkbox=false;buttonName=Run;checkpath=false;expected=true
+_checkPermission;description=Try to get permssion when run macro is set to according to path list, doc in path, warning dialog, do not run button pressed;location=check_perms_file8.sxw;runmacro=pathlist;pathlist=true;confirm=false;warning=true;dialog=true;checkbox=false;buttonName=Do Not Run;checkpath=false;expected=com.sun.star.security.AccessControlException
+_checkPermission;description=Try to get permssion when run macro is set to according to path list, doc not in path, warning dialog, confirm dialog, checkbox not checked, run button pressed;location=check_perms_file9.sxw;runmacro=pathlist;pathlist=false;confirm=true;warning=true;dialog=true;checkbox=false;buttonName=Run;checkpath=true;expected=true
+_checkPermission;description=Try to get permssion when run macro is set to according to path list, doc not in path, warning dialog, confirm dialog, checkbox checked, run button pressed;location=check_perms_file10.sxw;runmacro=pathlist;pathlist=true;confirm=true;warning=true;dialog=true;checkbox=true;buttonName=Run;checkpath=true;expected=true
+_checkPermission;description=Try to get permssion when run macro is set to according to path list, doc not in path, warning dialog, confirm dialog, checkbox not checked, do not run button pressed;location=check_perms_file11.sxw;runmacro=pathlist;pathlist=false;confirm=true;warning=true;dialog=true;checkbox=false;buttonName=Do Not Run;checkpath=true;expected=com.sun.star.security.AccessControlException
+_checkPermission;description=Try to get permssion when run macro is set to according to path list, doc not in path, warning dialog, confirm dialog, checkbox checked, do not run button pressed;location=check_perms_file12.sxw;runmacro=pathlist;pathlist=false;confirm=true;warning=true;dialog=true;checkbox=true;buttonName=Do Not Run;checkpath=true;expected=com.sun.star.security.AccessControlException
diff --git a/scripting/workben/data/user_scripts.zip b/scripting/workben/data/user_scripts.zip
new file mode 100644
index 000000000000..f5eed7657365
--- /dev/null
+++ b/scripting/workben/data/user_scripts.zip
Binary files differ
diff --git a/scripting/workben/data/xscriptcontext_test_document.sxw b/scripting/workben/data/xscriptcontext_test_document.sxw
new file mode 100644
index 000000000000..da6dafb0b805
--- /dev/null
+++ b/scripting/workben/data/xscriptcontext_test_document.sxw
Binary files differ
diff --git a/scripting/workben/ifc/scripting/ScriptingUtils.java b/scripting/workben/ifc/scripting/ScriptingUtils.java
new file mode 100644
index 000000000000..9d86ce6f0197
--- /dev/null
+++ b/scripting/workben/ifc/scripting/ScriptingUtils.java
@@ -0,0 +1,127 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptingUtils.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package ifc.script.framework;
+
+import java.io.File;
+import drafts.com.sun.star.script.framework.storage.XScriptStorageManager;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.XInterface;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.uno.XComponentContext;
+
+public class ScriptingUtils {
+ private XScriptStorageManager storageManager;
+ private static ScriptingUtils utils;
+
+ private ScriptingUtils() {
+ }
+
+ public static ScriptingUtils getDefault() {
+ if (utils == null) {
+ synchronized (ScriptingUtils.class) {
+ if (utils == null)
+ utils = new ScriptingUtils();
+ }
+ }
+ return utils;
+ }
+
+ public static void cleanUserDir() {
+ }
+
+ public static void cleanShareDir() {
+ }
+
+ public Object getScriptStorage(XMultiServiceFactory xMSF, String location) {
+ int id = getStorageId(xMSF, location);
+ return storageManager.getScriptStorage(id);
+ }
+
+ public int getStorageId(XMultiServiceFactory xMSF, String location) {
+
+ if (location.equals("share"))
+ return 0;
+
+ if (location.equals("user"))
+ return 1;
+
+ XSimpleFileAccess access = null;
+ String uri = util.utils.getFullTestURL(location);
+
+ if (storageManager == null) {
+ try {
+ XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(
+ XPropertySet.class, xMSF);
+
+ XComponentContext xContext = (XComponentContext)
+ UnoRuntime.queryInterface(XComponentContext.class,
+ xProp.getPropertyValue("DefaultContext"));
+
+ XInterface ifc = (XInterface)
+ xContext.getValueByName("/singletons/drafts.com.sun.star." +
+ "script.framework.storage.theScriptStorageManager");
+
+ storageManager = (XScriptStorageManager)
+ UnoRuntime.queryInterface(XScriptStorageManager.class, ifc);
+ }
+ catch( Exception e ) {
+ return -1;
+ }
+ }
+
+ access = getXSimpleFileAccess(xMSF);
+ if (access == null)
+ return -1;
+
+ int id = storageManager.createScriptStorageWithURI(access, uri);
+
+ return id;
+ }
+
+ public XSimpleFileAccess getXSimpleFileAccess(XMultiServiceFactory xMSF) {
+ XSimpleFileAccess access = null;
+
+ try {
+ Object fa =
+ xMSF.createInstance("com.sun.star.ucb.SimpleFileAccess");
+
+ access = (XSimpleFileAccess)
+ UnoRuntime.queryInterface(XSimpleFileAccess.class, fa);
+ }
+ catch (com.sun.star.uno.Exception e) {
+ return null;
+ }
+ return access;
+ }
+}
diff --git a/scripting/workben/ifc/scripting/SecurityDialogUtil.java b/scripting/workben/ifc/scripting/SecurityDialogUtil.java
new file mode 100644
index 000000000000..862dce7ff322
--- /dev/null
+++ b/scripting/workben/ifc/scripting/SecurityDialogUtil.java
@@ -0,0 +1,179 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: SecurityDialogUtil.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+package ifc.script.framework;
+
+import com.sun.star.awt.*;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XInterface;
+
+import drafts.com.sun.star.accessibility.*;
+import drafts.com.sun.star.awt.XExtendedToolkit;
+
+// Jsuite classes
+import util.AccessibilityTools;
+import util.dbg;
+/**
+* Thread that pushes the buttons or checkbox
+* on the message box that is on top.
+*/
+public class SecurityDialogUtil extends Thread {
+
+private XMultiServiceFactory xMSF = null;
+private String errorMsg;
+private boolean errorHappened;
+private String btnName;
+private boolean checkBox;
+
+/**
+ * Constructor.
+ * @param xMSF A MultiServiceFactory.
+ * @param log The log writer.
+ */
+public SecurityDialogUtil(XMultiServiceFactory xMSF, String btnName, boolean checkBox )
+{
+ this.xMSF = xMSF;
+ this.btnName = btnName;
+ this.checkBox = checkBox;
+ errorMsg = "";
+ errorHappened=false;
+}
+
+/**
+ * Returns the error message that occured while
+ * accessing and pressing the button.
+ * @return Error message.
+ */
+public String getErrorMessage()
+{
+ return errorMsg;
+}
+
+/**
+ * Is there an error message available?
+ * @return true, if an error happened
+ */
+public boolean hasErrorMessage()
+{
+ return !errorMsg.equals("");
+}
+
+/**
+ * Press the named button in the currently visible dialog box.
+ */
+public void run()
+{
+ // wait for the message box to appear
+ try
+ {
+ Thread.currentThread().sleep(4000) ;
+ }
+ catch (InterruptedException e)
+ {
+ System.err.println("While waiting :" + e.getMessage()) ;
+ }
+
+ // access the message box
+
+ XAccessibleContext xCon = null;
+ try
+ {
+ XInterface x = (XInterface) xMSF.createInstance(
+ "com.sun.star.awt.Toolkit") ;
+ XExtendedToolkit tk =
+ (XExtendedToolkit)UnoRuntime.queryInterface(
+ XExtendedToolkit.class,x);
+ AccessibilityTools at = new AccessibilityTools();
+ XWindow xWindow = (XWindow)UnoRuntime.queryInterface(
+ XWindow.class,tk.getActiveTopWindow());
+ XAccessible xRoot = at.getAccessibleObject(xWindow);
+ xCon = xRoot.getAccessibleContext();
+ }
+ catch (Exception e)
+ {
+ errorMsg="Exception while using Accessibility\n"+
+ e.getMessage();
+ return;
+ }
+ // get the button
+ XInterface oObj = null;
+ try
+ {
+ /* System.err.println("Name of the AccessibleContext:\n\t"+
+ xCon.getAccessibleName()); */
+ int count = xCon.getAccessibleChildCount();
+ // System.err.println("Number of children: "+count);
+ for (int i=0; i<count; i++) {
+ XAccessible xAcc = xCon.getAccessibleChild(i);
+ String name =
+ xAcc.getAccessibleContext().getAccessibleName();
+ // System.out.println("Child "+i+": "+ name);
+ // check for button
+ if ( name.equals( btnName ) && ( UnoRuntime.queryInterface(
+ XButton.class, xAcc ) != null ) )
+ {
+ // System.out.println("Child "+i+": "+ name);
+ oObj = xAcc.getAccessibleContext();
+ }
+ // check for checkbox
+ if ( checkBox && ( UnoRuntime.queryInterface( XCheckBox.class, xAcc ) != null ) )
+ {
+ // want to do this action now
+ // probably equates to toggle cb
+ XAccessibleAction xAction =
+ (XAccessibleAction)UnoRuntime.queryInterface(
+ XAccessibleAction.class, xAcc.getAccessibleContext());
+ xAction.doAccessibleAction(0);
+
+ // might be worth using oObj2 to double check the new state??
+ }
+ }
+ if (oObj == null) {
+ errorMsg="No button has been found:\n"+
+ "No action is triggered.";
+ return;
+ }
+ // press button
+ XAccessibleAction xAction =
+ (XAccessibleAction)UnoRuntime.queryInterface(
+ XAccessibleAction.class, oObj);
+ xAction.doAccessibleAction(0);
+ }
+ catch(com.sun.star.lang.IndexOutOfBoundsException e) {
+ errorMsg="Exception\n"+
+ e.getMessage();
+ }
+}
+
+}
+
+
+
+
diff --git a/scripting/workben/ifc/scripting/_XFunction.java b/scripting/workben/ifc/scripting/_XFunction.java
new file mode 100644
index 000000000000..00d36b9e7e78
--- /dev/null
+++ b/scripting/workben/ifc/scripting/_XFunction.java
@@ -0,0 +1,172 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: _XFunction.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package ifc.script.framework.provider;
+
+import drafts.com.sun.star.script.framework.provider.XFunction;
+import drafts.com.sun.star.script.framework.provider.XFunctionProvider;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.XInterface;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.uno.Exception;
+import com.sun.star.beans.XPropertySet;
+
+import java.io.PrintWriter;
+import lib.MultiMethodTest;
+import lib.StatusException;
+import lib.Parameters;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+public class _XFunction extends MultiMethodTest {
+
+ public XFunction oObj = null;
+ public XFunctionProvider oProvider = null;
+
+ /**
+ * Retrieves object relation.
+ */
+ public void before() throws StatusException {
+ log.println("getting provider");
+ oProvider = (XFunctionProvider) tEnv.getObjRelation("provider");
+ if (oProvider == null)
+ log.println("it's null");
+ else
+ log.println("it's not null");
+ }
+
+ public void _invoke() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_invoke");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ result &= runInvokeTest((Parameters)tests.next());
+ }
+ }
+ else {
+ result = false;
+ }
+
+ tRes.tested("invoke()", result);
+ }
+
+ private boolean runInvokeTest(Parameters testdata) {
+ String description = testdata.get("description");
+ String logicalname = testdata.get("logicalname");
+
+ String expreturntype = testdata.get("returntype");
+ String expreturnvalue = testdata.get("returnvalue");
+ String gotreturntype = "null";
+ String gotreturnvalue = "null";
+
+ String location = testdata.get("location");
+
+ String expected = testdata.get("expected");
+ String output = "";
+ boolean result = true;
+
+ log.println(testdata.get("description"));
+
+ try{
+ Object[] aParams = new Object[0];
+ short[][] aOutParamIndex = new short[1][];
+ aOutParamIndex[0] = new short[0];
+ Object[][] aOutParam = new Object[1][];
+ aOutParam[0] = new Object[0];
+
+ XFunction func = oProvider.getFunction(logicalname);
+ if (func == null) {
+ log.println("Couldn't get XFunction for:" + logicalname);
+ return false;
+ }
+
+ Object ret = func.invoke( aParams, aOutParamIndex, aOutParam );
+
+ if (ret != null) {
+ gotreturntype = ret.getClass().getName();
+ gotreturnvalue = ret.toString();
+ }
+
+ output = "success";
+ }
+ catch (com.sun.star.lang.IllegalArgumentException iae) {
+ log.println("Couldn't invoke script:" + iae);
+ output = "com.sun.star.lang.IllegalArgumentException";
+ }
+ catch (com.sun.star.script.CannotConvertException cce) {
+ log.println("Couldn't invoke script:" + cce);
+ output = "com.sun.star.script.CannotConvertException";
+ }
+ catch (com.sun.star.reflection.InvocationTargetException ite) {
+ log.println("Couldn't invoke script:" + ite);
+ output = "com.sun.star.reflection.InvocationTargetException";
+ }
+ catch (com.sun.star.uno.RuntimeException re) {
+ log.println("Couldn't invoke script:" + re);
+ output = "com.sun.star.uno.RuntimeException";
+ }
+ catch(java.lang.Exception e){
+ log.println("Couldn't invoke script:" + e);
+ output = "java.lang.Exception";
+ }
+
+ if (expreturntype != null) {
+ log.println("expected return type: " + expreturntype +
+ ", got return type: " + gotreturntype);
+
+ if (!gotreturntype.equals(expreturntype))
+ result = false;
+ }
+
+ if (expreturnvalue != null) {
+ log.println("expected return value: " + expreturnvalue +
+ ", got return value: " + gotreturnvalue);
+
+ if (!gotreturnvalue.equals(expreturnvalue))
+ result = false;
+ }
+
+ log.println("expected: " + expected + ", output: " + output);
+ if (!output.equals(expected))
+ result = false;
+
+ return result;
+ }
+}
diff --git a/scripting/workben/ifc/scripting/_XFunctionProvider.java b/scripting/workben/ifc/scripting/_XFunctionProvider.java
new file mode 100644
index 000000000000..1b4545684171
--- /dev/null
+++ b/scripting/workben/ifc/scripting/_XFunctionProvider.java
@@ -0,0 +1,104 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: _XFunctionProvider.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package ifc.script.framework.provider;
+
+import drafts.com.sun.star.script.framework.provider.XFunctionProvider;
+import drafts.com.sun.star.script.framework.provider.XFunction;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.XInterface;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.uno.Exception;
+import com.sun.star.beans.XPropertySet;
+
+import java.io.PrintWriter;
+import lib.MultiMethodTest;
+import lib.StatusException;
+import lib.Parameters;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+public class _XFunctionProvider extends MultiMethodTest {
+
+ public XFunctionProvider oObj = null;
+
+ /**
+ * Retrieves object relation.
+ */
+ public void before() throws StatusException {
+ }
+
+ public void _getFunction() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getFunction");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ result &= runGetFunctionTest((Parameters)tests.next());
+ }
+ }
+ else {
+ result = false;
+ }
+
+ tRes.tested("getFunction()", result);
+ }
+
+ private boolean runGetFunctionTest(Parameters testdata) {
+ String description = testdata.get("description");
+ String logicalname = testdata.get("logicalname");
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ XFunction function = oObj.getFunction(logicalname);
+
+ if (function == null)
+ output = "null";
+ else
+ output = "XFunction.class";
+
+ log.println("expected: " + expected + ", output: " + output);
+ if (output.equals(expected))
+ return true;
+ else
+ return false;
+ }
+}
diff --git a/scripting/workben/ifc/scripting/_XScriptInfo.java b/scripting/workben/ifc/scripting/_XScriptInfo.java
new file mode 100644
index 000000000000..b736c39e7bdd
--- /dev/null
+++ b/scripting/workben/ifc/scripting/_XScriptInfo.java
@@ -0,0 +1,334 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: _XScriptInfo.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package ifc.script.framework.storage;
+
+import drafts.com.sun.star.script.framework.storage.XScriptStorageManager;
+import drafts.com.sun.star.script.framework.storage.XScriptInfoAccess;
+import drafts.com.sun.star.script.framework.storage.XScriptInfo;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.XInterface;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.uno.Exception;
+import com.sun.star.beans.XPropertySet;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+import java.io.PrintWriter;
+import lib.Parameters;
+import lib.MultiMethodTest;
+import lib.StatusException;
+
+public class _XScriptInfo extends MultiMethodTest {
+
+ public XScriptInfo oObj = null;
+
+ /**
+ * Retrieves object relation.
+ */
+ public void before() throws StatusException {
+ }
+
+ public void _getLogicalName() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getLogicalName");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ output = oObj.getLogicalName();
+
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+ }
+ else {
+ result = false;
+ }
+
+ tRes.tested("getLogicalName()", result);
+ }
+
+ public void _getParcelURI() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getParcelURI");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ output = oObj.getParcelURI();
+
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.endsWith(expected);
+ }
+ }
+ else {
+ result = false;
+ }
+ tRes.tested("getParcelURI()", result);
+ }
+
+ public void _getLanguage() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getLanguage");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ output = oObj.getLanguage();
+
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+ }
+ else {
+ result = false;
+ }
+ tRes.tested("getLanguage()", result);
+ }
+
+ public void _getFunctionName() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getFunctionName");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ output = oObj.getFunctionName();
+
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+ }
+ else {
+ result = false;
+ }
+ tRes.tested("getFunctionName()", result);
+ }
+
+ public void _getLanguageProperties() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getLanguageProperties");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ try {
+ XPropertySet langProps = oObj.getLanguageProperties();
+ output = (String)langProps.getPropertyValue("classpath");
+
+ if (output == null)
+ output = "null";
+ }
+ catch( com.sun.star.uno.Exception e) {
+ log.println("caught UNO Exception:" + e);
+ output = "com.sun.star.uno.Exception";
+ }
+
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+ }
+ else {
+ result = false;
+ }
+ tRes.tested("getLanguageProperties()", true);
+ }
+
+ public void _getFileSetNames() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getFileSetNames");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ String[] fileSets = oObj.getFileSetNames();
+
+ if (fileSets == null)
+ output = "null";
+ else if (fileSets.length != 1)
+ output = "WrongNumberOfFileSets";
+ else
+ output = fileSets[0];
+
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+ }
+ else {
+ result = false;
+ }
+ tRes.tested("getFileSetNames()", result);
+ }
+
+ public void _getFilesInFileSet() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getFilesInFileSet");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ String[] filesInFileSet =
+ oObj.getFilesInFileSet(oObj.getFileSetNames()[0]);
+
+ if (filesInFileSet == null)
+ output = "null";
+ else if (filesInFileSet.length != 1)
+ output = "WrongNumberOfFilesInFileSet";
+ else
+ output = filesInFileSet[0];
+
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+ }
+ else {
+ result = false;
+ }
+ tRes.tested("getFilesInFileSet()", result);
+ }
+
+ public void _getDescription() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getDescription");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ output = oObj.getDescription();
+
+ if (output == null)
+ output = "null";
+ else if (output.length() == 0)
+ output = "empty";
+
+ log.println("expected: [" + expected + "], output: [" +
+ output + "]");
+ result &= output.equals(expected);
+ }
+ }
+ else {
+ result = false;
+ }
+
+ tRes.tested("getDescription()", result);
+ }
+}
diff --git a/scripting/workben/ifc/scripting/_XScriptInfoAccess.java b/scripting/workben/ifc/scripting/_XScriptInfoAccess.java
new file mode 100644
index 000000000000..243dd2c8fbd7
--- /dev/null
+++ b/scripting/workben/ifc/scripting/_XScriptInfoAccess.java
@@ -0,0 +1,231 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: _XScriptInfoAccess.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package ifc.script.framework.storage;
+
+import ifc.script.framework.ScriptingUtils;
+
+import drafts.com.sun.star.script.framework.storage.XScriptInfoAccess;
+import drafts.com.sun.star.script.framework.storage.XScriptInfo;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.XInterface;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.uno.Exception;
+import com.sun.star.beans.XPropertySet;
+
+import java.io.PrintWriter;
+import lib.MultiMethodTest;
+import lib.StatusException;
+import lib.Parameters;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+public class _XScriptInfoAccess extends MultiMethodTest {
+
+ public XScriptInfoAccess oObj = null;
+
+ /**
+ * Retrieves object relation.
+ */
+ public void before() throws StatusException {
+ }
+
+ public void _getScriptLogicalNames() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getScriptLogicalNames");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ result &= runGetScriptLogicalNamesTest((Parameters)tests.next());
+ }
+ }
+ else {
+ result = false;
+ }
+
+ tRes.tested("getScriptLogicalNames()", result);
+ }
+
+ private boolean runGetScriptLogicalNamesTest(Parameters testdata) {
+ String description = testdata.get("description");
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ // try {
+ log.println("In _XScriptInfoAccess.getScriptLogicalNames()");
+ String[] logicalNames = oObj.getScriptLogicalNames();
+
+ if (logicalNames == null)
+ output = "null";
+ else if (logicalNames.length == 0)
+ output = "empty";
+ else {
+ for (int i = 0; i < logicalNames.length; i++) {
+ if (logicalNames[i].equals(expected)) {
+ output = logicalNames[i];
+ break;
+ }
+ }
+ }
+ // }
+ // catch (com.sun.star.uno.Exception e) {
+ // log.println("Caught UNO Exception :" + e);
+ // output = "com.sun.star.uno.Exception";
+ // }
+
+ log.println("expected: " + expected + ", output: " + output);
+ if (output.equals(expected))
+ return true;
+ else
+ return false;
+ }
+
+ public void _getImplementations() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getImplementations");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ result &= runGetImplementationsTest((Parameters)tests.next());
+ }
+ }
+ else {
+ result = false;
+ }
+
+ tRes.tested("getImplementations()", result);
+ }
+
+ private boolean runGetImplementationsTest(Parameters testdata) {
+ String description = testdata.get("description");
+ String logicalname = testdata.get("logicalname");
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ // performs a basic check to see if 1 match (XScriptInfo) is returned
+ // the XScriptInfo object is tested more completely in _XScriptInfo
+ // which is drive from ScriptInfo
+
+ try {
+ XScriptInfo[] impls = oObj.getImplementations(logicalname);
+
+ // should only be one match
+ if (impls == null)
+ output = "null";
+ else if (impls.length == 0)
+ output = "empty";
+ else
+ output = impls[0].getLogicalName();
+ }
+ catch (com.sun.star.uno.Exception e) {
+ log.println("Caught UNO Exception:" + e);
+ output = "com.sun.star.uno.Exception";
+ }
+
+ log.println("expected: " + expected + ", output: " + output);
+ if (output.equals(expected))
+ return true;
+ else
+ return false;
+ }
+
+ public void _getAllImplementations() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getAllImplementations");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ result &= runGetAllImplementationsTest((Parameters)tests.next());
+ }
+ }
+ else {
+ result = false;
+ }
+
+ tRes.tested("getAllImplementations()", result);
+ }
+
+ private boolean runGetAllImplementationsTest(Parameters testdata) {
+ String description = testdata.get("description");
+ String location = testdata.get("location");
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ Object obj = ScriptingUtils.getDefault().getScriptStorage(
+ tParam.getMSF(), location);
+
+ XScriptInfoAccess access = (XScriptInfoAccess)
+ UnoRuntime.queryInterface(XScriptInfoAccess.class, obj);
+
+ XScriptInfo[] impls = access.getAllImplementations();
+
+ if (impls == null || impls.length == 0) {
+ output = "empty";
+ }
+ else {
+ for (int i = 0; i < impls.length - 1; i++)
+ output += impls[i].getLogicalName() + ",";
+ output += impls[impls.length - 1].getLogicalName();
+ }
+
+ log.println("expected: " + expected + ", output: " + output);
+ if (output.equals(expected))
+ return true;
+ else
+ return false;
+ }
+}
diff --git a/scripting/workben/ifc/scripting/_XScriptInvocation.java b/scripting/workben/ifc/scripting/_XScriptInvocation.java
new file mode 100644
index 000000000000..8d2812dd4dff
--- /dev/null
+++ b/scripting/workben/ifc/scripting/_XScriptInvocation.java
@@ -0,0 +1,235 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: _XScriptInvocation.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package ifc.script.framework.runtime;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Collection;
+
+import drafts.com.sun.star.script.framework.runtime.XScriptInvocation;
+import drafts.com.sun.star.script.framework.storage.XScriptStorageManager;
+
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XInterface;
+import com.sun.star.frame.XModel;
+
+import lib.MultiMethodTest;
+import lib.StatusException;
+import lib.Parameters;
+import util.SOfficeFactory;
+
+public class _XScriptInvocation extends MultiMethodTest {
+
+ public XScriptInvocation oObj = null;
+ private XScriptStorageManager storageManager = null;
+
+ /**
+ * Retrieves object relation.
+ */
+ public void before() throws StatusException {
+ }
+
+ public void after() throws StatusException {
+ }
+
+ public void _invoke() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_invoke");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ result &= runInvokeTest((Parameters)tests.next());
+ }
+ }
+ else {
+ result = false;
+ }
+
+ tRes.tested("invoke()", result);
+ }
+
+ private boolean runInvokeTest(Parameters testdata) {
+ String description = testdata.get("description");
+ String logicalname = testdata.get("logicalname");
+ String context = testdata.get("context");
+ String location = testdata.get("location");
+ String expected = testdata.get("expected");
+ String output = "";
+
+ int storageId = getStorageId(location);
+
+ XModel ctx = null;
+ if (!context.equals("null"))
+ ctx = loadDocument(context);
+
+ HashMap map = new HashMap();
+ map.put("SCRIPTING_DOC_STORAGE_ID", new Integer(storageId));
+ map.put("SCRIPTING_DOC_URI", "hahaha");
+ if (ctx != null)
+ map.put("SCRIPTING_DOC_REF", ctx);
+
+ Parameters params = new Parameters(map);
+ Object[] args = new Object[0];
+
+ Object[][] result = new Object[1][0];
+ result[0] = new Object[0];
+
+ short[][] num = new short[1][0];
+ num[0] = new short[0];
+
+ log.println(description + ": " + logicalname);
+
+ try {
+ Object ret = oObj.invoke(logicalname, params, args, num, result);
+ log.println("return type is: " + ret.getClass().getName() +
+ ", value is: " + ret.toString());
+ output = "success";
+ }
+ catch (com.sun.star.lang.IllegalArgumentException iae) {
+ log.println("Couldn't invoke script:" + iae);
+ output = "com.sun.star.lang.IllegalArgumentException";
+ }
+ catch (com.sun.star.script.CannotConvertException cce) {
+ log.println("Couldn't invoke script:" + cce);
+ output = "com.sun.star.script.CannotConvertException";
+ }
+ catch (com.sun.star.reflection.InvocationTargetException ite) {
+ log.println("Couldn't invoke script:" + ite);
+ output = "com.sun.star.reflection.InvocationTargetException";
+ }
+ catch (com.sun.star.uno.RuntimeException re) {
+ log.println("Couldn't invoke script:" + re);
+ output = "com.sun.star.uno.RuntimeException";
+ }
+
+ if (ctx != null)
+ ctx.dispose();
+
+ log.println("expected: " + expected + ", output: " + output);
+ if (output.equals(expected))
+ return true;
+ else
+ return false;
+ }
+
+ private int getStorageId(String location) {
+
+ if (location.equals("share"))
+ return 0;
+
+ if (location.equals("user"))
+ return 1;
+
+ XSimpleFileAccess access = null;
+ String uri = util.utils.getFullTestURL(location);
+
+ if (storageManager == null) {
+ try {
+ XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(
+ XPropertySet.class, tParam.getMSF());
+
+ XComponentContext xContext = (XComponentContext)
+ UnoRuntime.queryInterface(XComponentContext.class,
+ xProp.getPropertyValue("DefaultContext"));
+
+ XInterface ifc = (XInterface)
+ xContext.getValueByName("/singletons/drafts.com.sun.star." +
+ "script.framework.storage.theScriptStorageManager");
+
+ storageManager = (XScriptStorageManager)
+ UnoRuntime.queryInterface(XScriptStorageManager.class, ifc);
+ }
+ catch( Exception e ) {
+ return -1;
+ }
+ }
+
+ access = getXSimpleFileAccess();
+ if (access == null)
+ return -1;
+
+ int id = storageManager.createScriptStorageWithURI(access, uri);
+
+ return id;
+ }
+
+ private XSimpleFileAccess getXSimpleFileAccess() {
+ XSimpleFileAccess access = null;
+
+ try {
+ Object fa = tParam.getMSF().createInstance(
+ "com.sun.star.ucb.SimpleFileAccess");
+
+ access = (XSimpleFileAccess)
+ UnoRuntime.queryInterface(XSimpleFileAccess.class, fa);
+ }
+ catch (com.sun.star.uno.Exception e) {
+ return null;
+ }
+ return access;
+ }
+
+ private XModel loadDocument(String name) {
+ XModel model = null;
+ SOfficeFactory factory = SOfficeFactory.getFactory(tParam.getMSF());
+
+ String fullname = util.utils.getFullTestURL(name);
+
+ try {
+ Object obj = factory.loadDocument(fullname);
+ model = (XModel) UnoRuntime.queryInterface(XModel.class, obj);
+ }
+ catch (com.sun.star.lang.IllegalArgumentException iae) {
+ return null;
+ }
+ catch (Exception e) {
+ return null;
+ }
+
+ try {
+ Thread.sleep(5000);
+ }
+ catch (InterruptedException ie) {
+ }
+
+ return model;
+ }
+}
diff --git a/scripting/workben/ifc/scripting/_XScriptNameResolver.java b/scripting/workben/ifc/scripting/_XScriptNameResolver.java
new file mode 100644
index 000000000000..40d729214288
--- /dev/null
+++ b/scripting/workben/ifc/scripting/_XScriptNameResolver.java
@@ -0,0 +1,189 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: _XScriptNameResolver.java,v $
+ * $Revision: 1.7 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package ifc.script.framework.runtime;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Collection;
+
+import drafts.com.sun.star.script.framework.runtime.XScriptNameResolver;
+import drafts.com.sun.star.script.framework.storage.XScriptInfo;
+import drafts.com.sun.star.script.framework.storage.XScriptStorageManager;
+
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XInterface;
+
+import lib.MultiMethodTest;
+import lib.StatusException;
+import lib.Parameters;
+
+public class _XScriptNameResolver extends MultiMethodTest {
+
+ public XScriptNameResolver oObj = null;
+ private XScriptStorageManager storageManager = null;
+
+ /**
+ * Retrieves object relation.
+ */
+ public void before() throws StatusException {
+ }
+
+ public void _resolve() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_resolve");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ result &= runResolveTest((Parameters)tests.next());
+ }
+ }
+ else {
+ result = false;
+ }
+
+ tRes.tested("resolve()", result);
+ }
+
+ private boolean runResolveTest(Parameters data) {
+ String description = data.get("description");
+ String location = data.get("location");
+ String logicalname = data.get("logicalname");
+ String expected = data.get("expected");
+ String output = "";
+
+ int storageId = getStorageId(location);
+
+ log.println(description + ": " + logicalname);
+
+ HashMap map = new HashMap();
+ map.put("SCRIPTING_DOC_STORAGE_ID", new Integer(storageId));
+ map.put("SCRIPTING_DOC_URI", util.utils.getFullTestURL(location));
+
+ Parameters params = new Parameters(map);
+ Object[] args = new Object[] {params};
+
+ try {
+ XInterface ifc = (XInterface) oObj.resolve(logicalname, args);
+
+ if (ifc == null)
+ output = "null";
+ else if (UnoRuntime.queryInterface(XScriptInfo.class, ifc) == null)
+ output = "null";
+ else
+ output = "XScriptInfo.class";
+ }
+ catch (com.sun.star.lang.IllegalArgumentException iae) {
+ log.println("caught IllegalArgumentException: " + iae);
+ output = "com.sun.star.lang.IllegalArgumentException";
+ }
+ catch (com.sun.star.script.CannotConvertException cce) {
+ log.println("caught CannotConvertException: " + cce);
+ output = "com.sun.star.script.CannotConvertException";
+ }
+ catch (com.sun.star.uno.RuntimeException re) {
+ log.println("caught RuntimeException: " + re);
+ output = "com.sun.star.uno.RuntimeException";
+ }
+
+ log.println("expected: " + expected + ", output: " + output);
+ if (output.equals(expected))
+ return true;
+ else
+ return false;
+ }
+
+ private int getStorageId(String location) {
+
+ if (location.equals("share"))
+ return 0;
+
+ if (location.equals("user"))
+ return 1;
+
+ XSimpleFileAccess access = null;
+ String uri = util.utils.getFullTestURL(location);
+
+ if (storageManager == null) {
+ try {
+ XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(
+ XPropertySet.class, tParam.getMSF());
+
+ XComponentContext xContext = (XComponentContext)
+ UnoRuntime.queryInterface(XComponentContext.class,
+ xProp.getPropertyValue("DefaultContext"));
+
+ XInterface ifc = (XInterface)
+ xContext.getValueByName("/singletons/drafts.com.sun.star." +
+ "script.framework.storage.theScriptStorageManager");
+
+ storageManager = (XScriptStorageManager)
+ UnoRuntime.queryInterface(XScriptStorageManager.class, ifc);
+ }
+ catch( Exception e ) {
+ return -1;
+ }
+ }
+
+ access = getXSimpleFileAccess();
+ if (access == null)
+ return -1;
+
+ int id = storageManager.createScriptStorageWithURI(access, uri);
+
+ return id;
+ }
+
+ private XSimpleFileAccess getXSimpleFileAccess() {
+ XSimpleFileAccess access = null;
+
+ try {
+ Object fa = tParam.getMSF().createInstance(
+ "com.sun.star.ucb.SimpleFileAccess");
+
+ access = (XSimpleFileAccess)
+ UnoRuntime.queryInterface(XSimpleFileAccess.class, fa);
+ }
+ catch (com.sun.star.uno.Exception e) {
+ return null;
+ }
+ return access;
+ }
+}
diff --git a/scripting/workben/ifc/scripting/_XScriptSecurity.java b/scripting/workben/ifc/scripting/_XScriptSecurity.java
new file mode 100644
index 000000000000..ab608c8df2d4
--- /dev/null
+++ b/scripting/workben/ifc/scripting/_XScriptSecurity.java
@@ -0,0 +1,412 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: _XScriptSecurity.java,v $
+ * $Revision: 1.8 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package ifc.script.framework.security;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Collection;
+
+import drafts.com.sun.star.script.framework.security.XScriptSecurity;
+import drafts.com.sun.star.script.framework.storage.XScriptStorageManager;
+
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.beans.PropertyValue;
+import com.sun.star.uno.XComponentContext;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XInterface;
+import com.sun.star.frame.XModel;
+import com.sun.star.container.XNameReplace;
+import com.sun.star.util.XChangesBatch;
+import com.sun.star.reflection.InvocationTargetException;
+
+import ifc.script.framework.SecurityDialogUtil;
+
+import lib.MultiMethodTest;
+import lib.StatusException;
+import lib.Parameters;
+import util.SOfficeFactory;
+
+public class _XScriptSecurity extends MultiMethodTest {
+
+ public XScriptSecurity oObj = null;
+ private XScriptStorageManager storageManager = null;
+
+ /**
+ * Retrieves object relation.
+ */
+ public void before() throws StatusException {
+ }
+
+ public void after() throws StatusException {
+ }
+
+ public void _checkPermission() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_checkPermission");
+
+ Iterator tests;
+
+ if (c != null) {
+ tests = c.iterator();
+
+ while (tests.hasNext()) {
+ result &= runCheckPermissionTest((Parameters)tests.next());
+ }
+ }
+ else {
+ result = false;
+ }
+
+ // set security to always without confirmation dialog and empty path
+ // list so other tests can run without dialog popping up
+ setSecurity(2, "false", "false", null);
+
+ tRes.tested("checkPermission()", result);
+ }
+
+ private boolean runCheckPermissionTest(Parameters testdata) {
+ // description of test
+ String description = testdata.get("description");
+
+ // document location
+ String location = testdata.get("location");
+
+ //security settings
+ String runmacro = testdata.get("runmacro");
+ String confirm = testdata.get("confirm");
+ String warning = testdata.get("warning");
+ String pathlist = testdata.get("pathlist");
+
+ //do this test produce a dialog?
+ String dialog = testdata.get("dialog");
+ //is checkbox to be ticked?
+ String checkBoxStr = testdata.get("checkbox");
+ //name of button in dialog to press
+ String buttonName = testdata.get("buttonName");
+
+ //expected result
+ String expected = testdata.get("expected");
+ //do we need to check the pathlist?
+ String checkpath = testdata.get("checkpath");
+
+ String output = null;
+
+ log.println(description);
+
+ // get the officeBasic setting
+ int officeBasic = 0;
+ if( runmacro.equals("never") )
+ {
+ officeBasic = 0;
+ }
+ else if ( runmacro.equals("pathlist") )
+ {
+ officeBasic = 1;
+ }
+ else if ( runmacro.equals("always") )
+ {
+ officeBasic = 2;
+ }
+
+ // should pathlist include doc?
+ String secureURLs = null;
+ if( pathlist.equals("true") )
+ {
+ String uri = util.utils.getFullTestURL(location);
+ secureURLs = uri.substring(0, uri.lastIndexOf('/'));
+ }
+
+ if ( !setSecurity( officeBasic, confirm, warning, secureURLs ) )
+ {
+ log.println( "failed to set security" );
+ return false;
+ }
+
+ if( dialog.equals( "true" ) )
+ {
+ // is the checkbox to be ticked?
+ boolean checkBox = false;
+ if( checkBoxStr.equals( "true" ) )
+ {
+ checkBox = true;
+ }
+ new SecurityDialogUtil( tParam.getMSF(), buttonName, checkBox ).start();
+ }
+ // need to set up dialog utils thread first
+ int storageId = getStorageId(location);
+
+ try {
+ String uri = util.utils.getFullTestURL(location);
+ oObj.checkPermission(uri, "execute" );
+ output = "true";
+ }
+ catch (com.sun.star.security.AccessControlException ace) {
+ log.println("Couldn't invoke script:" + ace);
+ output = "com.sun.star.security.AccessControlException";
+ }
+ catch (com.sun.star.lang.IllegalArgumentException iae) {
+ log.println("Couldn't invoke script:" + iae);
+ output = "com.sun.star.lang.IllegalArgumentException";
+ }
+ catch (com.sun.star.uno.RuntimeException re) {
+ log.println("Couldn't invoke script:" + re);
+ output = "com.sun.star.uno.RuntimeException";
+ }
+
+ log.println("expected: " + expected + ", output: " + output);
+ if (output.equals(expected))
+ {
+ if( checkpath.equals("true") )
+ {
+ String setPath = getPathList();
+ String expectedPath = "empty";
+ if( checkBoxStr.equals( "true" ) )
+ {
+ String uri = util.utils.getFullTestURL(location);
+ expectedPath = uri.substring(0, uri.lastIndexOf('/'));
+ }
+ log.println("pathlist: expected: " + expectedPath + ", output: " + setPath);
+ if( setPath.equals( expectedPath ) )
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+ else
+ return false;
+ }
+
+ private String getPathList()
+ {
+ String result = "";
+ try {
+ Object oProv = tParam.getMSF().createInstance(
+ "com.sun.star.configuration.ConfigurationProvider" );
+
+ XMultiServiceFactory xProv = (XMultiServiceFactory)
+ UnoRuntime.queryInterface(XMultiServiceFactory.class, oProv);
+
+ //the path to the security settings in the registry
+ PropertyValue aPathArg = new PropertyValue();
+ aPathArg.Name="nodepath";
+ aPathArg.Value="org.openoffice.Office.Common/Security/Scripting";
+ // we don't want to cache the write
+ PropertyValue aModeArg = new PropertyValue();
+ aModeArg.Name="lazywrite";
+ aModeArg.Value=new Boolean(false);
+
+ Object[] aArgs = new Object[2];
+ aArgs[0]=aPathArg;
+ aArgs[1]=aModeArg;
+ Object oConfigUpdate = xProv.createInstanceWithArguments(
+ "com.sun.star.configuration.ConfigurationAccess",
+ aArgs );
+ XPropertySet xPropertySet = (XPropertySet)UnoRuntime.queryInterface(
+ XPropertySet.class, oConfigUpdate );
+
+ String[] paths = (String[])xPropertySet.getPropertyValue("SecureURL");
+ if (paths == null || paths.length == 0)
+ result = "empty";
+ else
+ result = paths[0];
+
+ } catch (Exception e)
+ {
+ result = e.getClass().getName() + " getting list of secure URLs";
+ }
+ return result;
+ }
+
+ private boolean setSecurity( int officeBasic, String confirm,
+ String warning, String secureURLs )
+ {
+ boolean success=false;
+ try {
+ Object oProv = tParam.getMSF().createInstance(
+ "com.sun.star.configuration.ConfigurationProvider" );
+
+ XMultiServiceFactory xProv = (XMultiServiceFactory)
+ UnoRuntime.queryInterface(XMultiServiceFactory.class, oProv);
+
+ //the path to the security settings in the registry
+ PropertyValue aPathArg = new PropertyValue();
+ aPathArg.Name="nodepath";
+ aPathArg.Value="org.openoffice.Office.Common/Security/Scripting";
+ // we don't want to cache the write
+ PropertyValue aModeArg = new PropertyValue();
+ aModeArg.Name="lazywrite";
+ aModeArg.Value=new Boolean(false);
+
+ Object[] aArgs = new Object[2];
+ aArgs[0]=aPathArg;
+ aArgs[1]=aModeArg;
+ Object oConfigUpdate = xProv.createInstanceWithArguments(
+ "com.sun.star.configuration.ConfigurationUpdateAccess",
+ aArgs );
+ XNameReplace xNameReplace = (XNameReplace)UnoRuntime.queryInterface(
+ XNameReplace.class, oConfigUpdate );
+ XChangesBatch xChangesBatch = (XChangesBatch)UnoRuntime.queryInterface(
+ XChangesBatch.class, oConfigUpdate );
+
+ Object[] aSecureURLs;
+ if (secureURLs == null) {
+ aSecureURLs = new Object[0];
+ }
+ else {
+ aSecureURLs = new Object[1];
+ aSecureURLs[0] = secureURLs;
+ }
+ log.println("setting SecureURL");
+ xNameReplace.replaceByName( "SecureURL", aSecureURLs );
+
+ log.println("setting OfficeBasic");
+ xNameReplace.replaceByName( "OfficeBasic", new Integer(officeBasic) );
+
+ Boolean bConfirm = null;
+ if( ( confirm != null ) && ( confirm.equals("true") ) )
+ {
+ bConfirm = new Boolean( true );
+ }
+ else
+ {
+ bConfirm = new Boolean( false );
+ }
+ log.println("setting Confirmation");
+ xNameReplace.replaceByName( "Confirmation", bConfirm );
+
+ Boolean bWarning = null;
+ if( ( warning != null ) && ( warning.equals("true") ) )
+ {
+ bWarning = new Boolean( true );
+ }
+ else
+ {
+ bWarning = new Boolean( false );
+ }
+ log.println("setting Warning");
+ xNameReplace.replaceByName( "Warning", bWarning );
+
+ // and now commit the changes
+ xChangesBatch.commitChanges();
+ success=true;
+ } catch (Exception e) {
+ log.println("Error updating security settings: " +
+ e.getMessage() );
+ }
+ return success;
+ }
+
+ private int getStorageId(String location) {
+
+ XSimpleFileAccess access = null;
+ String uri = util.utils.getFullTestURL(location);
+
+ if (storageManager == null) {
+ try {
+ XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(
+ XPropertySet.class, tParam.getMSF());
+
+ XComponentContext xContext = (XComponentContext)
+ UnoRuntime.queryInterface(XComponentContext.class,
+ xProp.getPropertyValue("DefaultContext"));
+
+ XInterface ifc = (XInterface)
+ xContext.getValueByName("/singletons/drafts.com.sun.star." +
+ "script.framework.storage.theScriptStorageManager");
+
+ storageManager = (XScriptStorageManager)
+ UnoRuntime.queryInterface(XScriptStorageManager.class, ifc);
+ }
+ catch( Exception e ) {
+ return -1;
+ }
+ }
+
+ access = getXSimpleFileAccess();
+ if (access == null)
+ return -1;
+
+ int id = storageManager.createScriptStorageWithURI(access, uri);
+
+ return id;
+ }
+
+ private XSimpleFileAccess getXSimpleFileAccess() {
+ XSimpleFileAccess access = null;
+
+ try {
+ Object fa = tParam.getMSF().createInstance(
+ "com.sun.star.ucb.SimpleFileAccess");
+
+ access = (XSimpleFileAccess)
+ UnoRuntime.queryInterface(XSimpleFileAccess.class, fa);
+ }
+ catch (com.sun.star.uno.Exception e) {
+ return null;
+ }
+ return access;
+ }
+
+ private XModel loadDocument(String name) {
+ XModel model = null;
+ SOfficeFactory factory = SOfficeFactory.getFactory(tParam.getMSF());
+
+ String fullname = util.utils.getFullTestURL(name);
+
+ try {
+ Object obj = factory.loadDocument(fullname);
+ model = (XModel) UnoRuntime.queryInterface(XModel.class, obj);
+ }
+ catch (com.sun.star.lang.IllegalArgumentException iae) {
+ return null;
+ }
+ catch (Exception e) {
+ return null;
+ }
+
+ try {
+ Thread.sleep(5000);
+ }
+ catch (InterruptedException ie) {
+ }
+
+ return model;
+ }
+}
diff --git a/scripting/workben/ifc/scripting/_XScriptStorageManager.java b/scripting/workben/ifc/scripting/_XScriptStorageManager.java
new file mode 100644
index 000000000000..ed0aa2a4d9e9
--- /dev/null
+++ b/scripting/workben/ifc/scripting/_XScriptStorageManager.java
@@ -0,0 +1,270 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: _XScriptStorageManager.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package ifc.script.framework.storage;
+
+import drafts.com.sun.star.script.framework.storage.XScriptStorageManager;
+import drafts.com.sun.star.script.framework.storage.XScriptInfoAccess;
+
+import java.util.Iterator;
+import java.util.Collection;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.XInterface;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.uno.Exception;
+
+import java.io.PrintWriter;
+import lib.MultiMethodTest;
+import lib.StatusException;
+import lib.Parameters;
+
+public class _XScriptStorageManager extends MultiMethodTest {
+
+ public XScriptStorageManager oObj = null;
+
+ /**
+ * Retrieves object relation.
+ */
+ public void before() throws StatusException {
+ }
+
+ public void _createScriptStorage() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_createScriptStorage");
+
+ if (c == null) {
+ tRes.tested("createScriptStorage()", false);
+ return;
+ }
+
+ Iterator tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ XSimpleFileAccess access = getXSimpleFileAccess();
+
+ if (access == null) {
+ output = "Couldn't create XSimpleFileAccess";
+ }
+ else {
+ try {
+ int id = oObj.createScriptStorage(access);
+ output = "success";
+ }
+ catch (com.sun.star.uno.RuntimeException re) {
+ log.println("Exception from createScriptStorage: " + re);
+ output = "com.sun.star.uno.RuntimeException";
+ }
+ }
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+ tRes.tested("createScriptStorage()", result);
+ }
+
+ public void _createScriptStorageWithURI() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_createScriptStorageWithURI");
+
+ if (c == null) {
+ tRes.tested("createScriptStorageWithURI()", false);
+ return;
+ }
+
+ Iterator tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String location = testdata.get("location");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ String uri = util.utils.getFullTestURL(location);
+ XSimpleFileAccess access = getXSimpleFileAccess();
+
+ try {
+ int id = oObj.createScriptStorageWithURI(access, uri);
+
+ XInterface ifc = (XInterface)oObj.getScriptStorage(id);
+
+ if (ifc == null)
+ output = "null";
+ else {
+ Object info = UnoRuntime.queryInterface(
+ XScriptInfoAccess.class, ifc);
+
+ if (info == null)
+ output = "null";
+ else
+ output = "XScriptInfoAccess.class";
+ }
+ }
+ catch (com.sun.star.uno.RuntimeException re) {
+ log.println("Caught RuntimeException: " + re);
+ output = "com.sun.star.uno.RuntimeException";
+ }
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+
+ tRes.tested("createScriptStorageWithURI()", result);
+ }
+
+ public void _getScriptStorage() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_getScriptStorage");
+
+ if (c == null) {
+ tRes.tested("getScriptStorage()", false);
+ return;
+ }
+
+ Iterator tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String location = testdata.get("location");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ try {
+ int storageid = getStorageId(location);
+
+ XInterface ifc = (XInterface)oObj.getScriptStorage(storageid);
+
+ if (ifc == null)
+ output = "null";
+ else {
+ Object info = UnoRuntime.queryInterface(
+ XScriptInfoAccess.class, ifc);
+
+ if (info == null)
+ output = "null";
+ else
+ output = "XScriptInfoAccess.class";
+ }
+ }
+ catch (com.sun.star.uno.RuntimeException re) {
+ log.println("Caught RuntimeException: " + re);
+ output = "com.sun.star.uno.RuntimeException";
+ }
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+ tRes.tested("getScriptStorage()", result);
+ }
+
+ public void _refreshScriptStorage() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_refreshScriptStorage");
+
+ if (c == null) {
+ tRes.tested("refreshScriptStorage()", false);
+ return;
+ }
+
+ Iterator tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String location = testdata.get("location");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ try {
+ String uri = util.utils.getFullTestURL(location);
+ log.println("calling refreshScriptStorage with URI: " + uri);
+ oObj.refreshScriptStorage(uri);
+ output = "success";
+ }
+ catch (com.sun.star.uno.RuntimeException re) {
+ log.println("Caught RuntimeException: " + re);
+ output = "com.sun.star.uno.RuntimeException";
+ }
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+ tRes.tested("refreshScriptStorage()", result);
+ }
+
+ private int getStorageId(String location) {
+
+ if (location.equals("share"))
+ return 0;
+
+ if (location.equals("user"))
+ return 1;
+
+ String uri = util.utils.getFullTestURL(location);
+
+ XSimpleFileAccess access = getXSimpleFileAccess();
+ if (access == null)
+ return -1;
+
+ return oObj.createScriptStorageWithURI(access, uri);
+ }
+
+ private XSimpleFileAccess getXSimpleFileAccess() {
+ XSimpleFileAccess access = null;
+
+ try {
+ Object fa = tParam.getMSF().createInstance(
+ "com.sun.star.ucb.SimpleFileAccess");
+
+ access = (XSimpleFileAccess)
+ UnoRuntime.queryInterface(XSimpleFileAccess.class, fa);
+ }
+ catch (com.sun.star.uno.Exception e) {
+ return null;
+ }
+ return access;
+ }
+}
diff --git a/scripting/workben/ifc/scripting/_XScriptStorageRefresh.java b/scripting/workben/ifc/scripting/_XScriptStorageRefresh.java
new file mode 100644
index 000000000000..3b3da233c517
--- /dev/null
+++ b/scripting/workben/ifc/scripting/_XScriptStorageRefresh.java
@@ -0,0 +1,93 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: _XScriptStorageRefresh.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package ifc.script.framework.storage;
+
+import drafts.com.sun.star.script.framework.storage.XScriptStorageRefresh;
+
+import java.util.Collection;
+import java.util.Iterator;
+
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.XInterface;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.uno.Exception;
+import com.sun.star.beans.XPropertySet;
+
+import java.io.PrintWriter;
+import lib.MultiMethodTest;
+import lib.StatusException;
+import lib.Parameters;
+
+public class _XScriptStorageRefresh extends MultiMethodTest {
+
+ public XScriptStorageRefresh oObj = null;
+
+ /**
+ * Retrieves object relation.
+ */
+ public void before() throws StatusException {
+ }
+
+ public void _refresh() {
+ boolean result = true;
+
+ Collection c =
+ (Collection) tEnv.getObjRelation("_refresh");
+
+ if (c == null) {
+ tRes.tested("refresh()", false);
+ return;
+ }
+
+ Iterator tests = c.iterator();
+
+ while (tests.hasNext()) {
+ Parameters testdata = (Parameters)tests.next();
+ String expected = testdata.get("expected");
+ String output = "";
+
+ log.println(testdata.get("description"));
+
+ try {
+ oObj.refresh();
+ output = "success";
+ }
+ catch (com.sun.star.uno.RuntimeException re) {
+ log.println("Caught RuntimeException: " + re);
+ output = "com.sun.star.uno.RuntimeException";
+ }
+ log.println("expected: " + expected + ", output: " + output);
+ result &= output.equals(expected);
+ }
+ tRes.tested("refresh()", result);
+ }
+}
diff --git a/scripting/workben/ifc/scripting/makefile.mk b/scripting/workben/ifc/scripting/makefile.mk
new file mode 100644
index 000000000000..472c8d15a11b
--- /dev/null
+++ b/scripting/workben/ifc/scripting/makefile.mk
@@ -0,0 +1,44 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.5 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+PRJ = ..$/..$/..$/..
+PRJNAME = testcase
+TARGET = testcase
+
+# --- Settings -----------------------------------------------------
+.INCLUDE: settings.mk
+
+JARFILES = ridl.jar unoil.jar jurt.jar juh.jar $(CLASSPATH)$
+JAVAFILES = $(foreach,j,$(shell @ls | grep java) $j)
+
+# --- Targets ------------------------------------------------------
+
+.INCLUDE : target.mk
diff --git a/scripting/workben/installer/Banner.java b/scripting/workben/installer/Banner.java
new file mode 100644
index 000000000000..c6d0f0b0bd5e
--- /dev/null
+++ b/scripting/workben/installer/Banner.java
@@ -0,0 +1,30 @@
+package installer;
+
+import java.awt.*;
+
+public class Banner extends Canvas
+{
+ Image img;
+ Banner()
+ {
+ setBackground(Color.white);
+ img = Toolkit.getDefaultToolkit().createImage("sidebar.jpg");
+ }
+
+ public void paint(Graphics g)
+ {
+ g.drawImage(img, 0, 0, Color.white, null);
+ g.dispose();
+ }
+
+ public void update(Graphics g)
+ {
+ super.update(g);
+ }
+
+ public Dimension getPreferredSize()
+ {
+ return new Dimension(137, 358);
+ }
+
+}
diff --git a/scripting/workben/installer/ExceptionTraceHelper.java b/scripting/workben/installer/ExceptionTraceHelper.java
new file mode 100644
index 000000000000..1bc3d0ffe039
--- /dev/null
+++ b/scripting/workben/installer/ExceptionTraceHelper.java
@@ -0,0 +1,67 @@
+/*************************************************************************
+*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ExceptionTraceHelper.java,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+************************************************************************/
+package installer;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+// class for propagating the exception stack traces across the Java/UNO bridge
+public class ExceptionTraceHelper
+{
+ public static String getTrace( Exception e )
+ {
+ ByteArrayOutputStream baos = null;
+ PrintStream ps = null;
+ String result = "";
+ try
+ {
+ baos = new ByteArrayOutputStream( 128 );
+ ps = new PrintStream( baos );
+ e.printStackTrace( ps );
+ }
+ finally
+ {
+ try
+ {
+ if ( baos != null )
+ {
+ baos.close();
+ }
+ if ( ps != null )
+ {
+ ps.close();
+ }
+ }
+ catch ( Exception excp )
+ {
+ }
+ }
+ return result;
+ }
+}
diff --git a/scripting/workben/installer/ExecCmd.java b/scripting/workben/installer/ExecCmd.java
new file mode 100644
index 000000000000..fa5f9a8b2dcd
--- /dev/null
+++ b/scripting/workben/installer/ExecCmd.java
@@ -0,0 +1,100 @@
+package installer;
+import java.util.*;
+import java.io.*;
+public class ExecCmd
+{
+
+ public boolean exec( String cmd, String[] env )
+ {
+ System.out.println("About to exectute " + cmd);
+ final Process p;
+ boolean result = false;
+ try
+ {
+ Runtime rt = Runtime.getRuntime();
+ p=rt.exec( cmd, env );
+ new Thread(new Runnable() {
+ public void run()
+ {
+ BufferedReader br_in = null;
+ try
+ {
+ br_in = new BufferedReader(new InputStreamReader(p.getInputStream()));
+ String buff = null;
+ while ((buff = br_in.readLine()) != null)
+ {
+ System.out.println("Process out :" + buff);
+ /*try
+ {
+ Thread.sleep(100);
+ }
+ catch(Exception e) {}*/
+ }
+ System.out.println("finished reading out");
+ }
+ catch (IOException ioe)
+ {
+ System.out.println("Exception caught printing javac result");
+ ioe.printStackTrace();
+ }
+ finally
+ {
+ if ( br_in != null )
+ {
+ try
+ {
+ br_in.close();
+ }
+ catch( Exception e ) {} // nothing can be done
+ }
+ }
+ } } ).start();
+
+ new Thread(new Runnable() {
+ public void run() {
+ BufferedReader br_err = null;
+ try {
+ br_err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
+ String buff = null;
+ while ((buff = br_err.readLine()) != null) {
+ System.out.println("Process err :" + buff);
+ /*try {Thread.sleep(100); } catch(Exception e) {}*/
+ }
+ System.out.println("finished reading err");
+ } catch (IOException ioe) {
+ System.out.println("Exception caught printing javac result");
+ ioe.printStackTrace();
+ }
+ finally
+ {
+ if ( br_err != null )
+ {
+ try
+ {
+ br_err.close();
+ }
+ catch( Exception e ) {} // nothing can be done
+ }
+ }
+ } }).start();
+ int exitcode = p.waitFor();
+ if ( exitcode != 0 )
+ {
+ System.out.println("cmd [" + cmd + "] failed" );
+ result= false;
+ }
+ else
+ {
+ System.out.println("cmd [" + cmd + "] completed successfully");
+ result= true;
+ }
+ }
+ catch (Exception e) {
+ System.out.println("Exception");
+ e.printStackTrace();
+ }
+ System.out.println("command complete");
+ return result;
+ }
+}
+
diff --git a/scripting/workben/installer/FileUpdater.java b/scripting/workben/installer/FileUpdater.java
new file mode 100644
index 000000000000..76b5358eb6fe
--- /dev/null
+++ b/scripting/workben/installer/FileUpdater.java
@@ -0,0 +1,232 @@
+package installer;
+
+import java.io.*;
+import javax.swing.JLabel;
+
+public class FileUpdater {
+
+ public static boolean updateProtocolHandler( String installPath, JLabel statusLabel ) {
+ File in_file = null;
+ FileInputStream in = null;
+ File out_file = null;
+ FileWriter out = null;
+ int count = 0;
+
+ try {
+ in_file = new File( installPath+File.separator+"share"+File.separator+"registry"+File.separator+"data"+File.separator+"org"+File.separator+"openoffice"+File.separator+"Office"+File.separator+"ProtocolHandler.xcu" );
+
+ String[] xmlArray = new String[50];
+ try {
+ BufferedReader reader = new BufferedReader(new FileReader(in_file));
+ count = -1;
+ for (String s = reader.readLine(); s != null; s = reader.readLine()) { //</oor:node>
+ count = count + 1;
+ if(s != null) {
+ s.trim();
+ xmlArray[count] = s;
+ }
+ else
+ break;
+ }
+ }
+ catch( IOException ioe ) {
+ String message = "\nError reading ProtocolHandler.xcu, please view SFrameworkInstall.log.";
+ System.out.println(message);
+ ioe.printStackTrace();
+ statusLabel.setText(message);
+ return false;
+ }
+
+ in_file.delete();
+
+ out_file = new File( installPath+File.separator+"share"+File.separator+"registry"+File.separator+"data"+File.separator+"org"+File.separator+"openoffice"+File.separator+"Office"+File.separator+"ProtocolHandler.xcu" );
+ out_file.createNewFile();
+ out = new FileWriter( out_file );
+
+ for(int i=0; i<count + 1; i++) {
+ out.write(xmlArray[i]+"\n");
+ if( ( xmlArray[i].indexOf( "<node oor:name=\"HandlerSet\">" ) != -1 ) && ( xmlArray[i+1].indexOf( "ScriptProtocolHandler" ) == -1 ) ) {
+ out.write( " <node oor:name=\"com.sun.star.comp.ScriptProtocolHandler\" oor:op=\"replace\">\n" );
+ out.write( " <prop oor:name=\"Protocols\">\n" );
+ out.write( " <value>script:*</value>\n" );
+ out.write( " </prop>\n" );
+ out.write( " </node>\n" );
+ }
+ }
+ }
+ catch( Exception e ) {
+ String message = "\nError updating ProtocolHandler.xcu, please view SFrameworkInstall.log.";
+ System.out.println(message);
+ e.printStackTrace();
+ statusLabel.setText(message);
+ return false;
+ }
+ finally {
+ try {
+ out.close();
+ System.out.println("File closed");
+ }
+ catch(Exception e) {
+ System.out.println("Update ProtocolHandler Failed, please view SFrameworkInstall.log.");
+ System.err.println(e);
+ e.printStackTrace();
+ }
+ }
+ return true;
+
+ }// updateProtocolHandler
+
+
+ public static boolean updateScriptXLC( String installPath, JLabel statusLabel ) {
+
+ File in_file = null;
+ FileInputStream in = null;
+ File out_file = null;
+ FileWriter out = null;
+ int count = 0;
+
+ //System.out.println("updateScriptXLC");
+ try {
+ in_file = new File( installPath+File.separator+"user"+File.separator+"basic"+File.separator+"script.xlc" );
+
+ String[] xmlArray = new String[50];
+ try {
+ BufferedReader reader = new BufferedReader(new FileReader(in_file));
+ count = -1;
+ for (String s = reader.readLine(); s != null; s = reader.readLine()) { //</oor:node>
+ count = count + 1;
+ if(s != null) {
+ s.trim();
+ xmlArray[count] = s;
+ }
+ else
+ break;
+ }
+ }
+ catch( IOException ioe ) {
+ String message = "Error reading script.xlc, please view SFrameworkInstall.log.";
+ System.out.println(message);
+ ioe.printStackTrace();
+ statusLabel.setText(message);
+ return false;
+ }
+
+ in_file.delete();
+
+ out_file = new File( installPath+File.separator+"user"+File.separator+"basic"+File.separator+"script.xlc" );
+ out_file.createNewFile();
+ out = new FileWriter( out_file );
+
+ //split the string into a string array with one line of xml in each element
+ //String[] xmlArray = xmlLine.split("\n");
+ for(int i=0; i<count + 1; i++) {
+ out.write(xmlArray[i]+"\n");
+ if( ( xmlArray[i].indexOf( "<library:libraries xmlns:library" ) != -1 ) && ( xmlArray[i+1].indexOf( "ScriptBindingLibrary" ) == -1 ) ) {
+ String opSys = System.getProperty("os.name");
+ if (opSys.indexOf("Windows") != -1) {
+ out.write(" <library:library library:name=\"ScriptBindingLibrary\" library:link=\"true\"/>\n" );
+ }
+ else {
+ out.write(" <library:library library:name=\"ScriptBindingLibrary\" xlink:href=\"file://"+installPath+"/share/basic/ScriptBindingLibrary/script.xlb/\" xlink:type=\"simple\" library:link=\"true\"/>\n" );
+ }
+ }
+ }
+ }
+ catch( Exception e ) {
+ String message = "\nError updating script.xlc, please view SFrameworkInstall.log.";
+ System.out.println(message);
+ e.printStackTrace();
+ statusLabel.setText(message);
+ return false;
+ }
+ finally {
+ try {
+ out.close();
+ }
+ catch(Exception e) {
+ System.out.println("Update Script.xlc Failed, please view SFrameworkInstall.log.");
+ e.printStackTrace();
+ System.err.println(e);
+ }
+ }
+ return true;
+ }// updateScriptXLC
+
+
+ public static boolean updateDialogXLC( String installPath, JLabel statusLabel ) {
+ File in_file = null;
+ FileInputStream in = null;
+ File out_file = null;
+ FileWriter out = null;
+ int count = 0;
+
+ //System.out.println( "updateDialogXLC" );
+ try {
+ in_file = new File( installPath+File.separator+"user"+File.separator+"basic"+File.separator+"dialog.xlc" );
+ String xmlLine = "";
+
+ String[] xmlArray = new String[50];
+ try {
+ BufferedReader reader = new BufferedReader(new FileReader(in_file));
+ count = -1;
+ for (String s = reader.readLine(); s != null; s = reader.readLine()) {
+ count = count + 1;
+ if(s != null) {
+ s.trim();
+ xmlArray[count] = s;
+ }
+ else
+ break;
+ }
+ }
+ catch( IOException ioe ) {
+
+ String message = "\nError reading dialog.xlc, please view SFrameworkInstall.log.";
+ System.out.println(message);
+ statusLabel.setText(message);
+ return false;
+ }
+ in_file.delete();
+
+ out_file = new File( installPath+File.separator+"user"+File.separator+"basic"+File.separator+"dialog.xlc" );
+ out_file.createNewFile();
+
+ out = new FileWriter( out_file );
+
+ //split the string into a string array with one line of xml in each element
+ // String[] xmlArray = xmlLine.split("\n");
+ for(int i=0; i<count + 1; i++) {
+ out.write(xmlArray[i]+"\n");
+ if( ( xmlArray[i].indexOf( "<library:libraries xmlns:library" ) != -1 ) && ( xmlArray[i+1].indexOf( "ScriptBindingLibrary" ) == -1 ) ) {
+ String opSys = System.getProperty("os.name");
+ if (opSys.indexOf("Windows") != -1) {
+ out.write(" <library:library library:name=\"ScriptBindingLibrary\" library:link=\"true\"/>\n" );
+ }
+ else {
+ out.write(" <library:library library:name=\"ScriptBindingLibrary\" xlink:href=\"file://"+installPath+"/share/basic/ScriptBindingLibrary/dialog.xlb/\" xlink:type=\"simple\" library:link=\"true\"/>\n" );
+ }
+ }
+ }
+ }
+ catch( Exception e ) {
+ String message = "\nError updating dialog.xlc, please view SFrameworkInstall.log.";
+ System.out.println(message);
+ e.printStackTrace();
+ statusLabel.setText(message);
+ return false;
+ }
+ finally {
+ try {
+ out.close();
+ }
+ catch(Exception e) {
+ System.out.println("Update dialog.xlc Failed, please view SFrameworkInstall.log.");
+ e.printStackTrace();
+ System.err.println(e);
+ }
+ }
+ return true;
+ }// updateScriptXLC
+
+
+}
diff --git a/scripting/workben/installer/Final.java b/scripting/workben/installer/Final.java
new file mode 100644
index 000000000000..ea543d45ccec
--- /dev/null
+++ b/scripting/workben/installer/Final.java
@@ -0,0 +1,136 @@
+package installer;
+
+/*
+ * Welcome.java
+ *
+ * Created on 04 July 2002, 15:43
+ */
+
+/**
+ *
+ * @author mike
+ */
+
+import java.awt.event.*;
+import java.util.*;
+import java.net.*;
+import javax.swing.*;
+
+public class Final extends javax.swing.JPanel implements ActionListener, InstallListener {
+
+ /** Creates new form Welcome */
+ public Final(InstallWizard wizard) {
+ this.wizard = wizard;
+ setBackground(java.awt.Color.white);
+ xud = null;
+ initComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ private void initComponents() {//GEN-BEGIN:initComponents
+ statusPanel = new javax.swing.JPanel();
+ statusPanel.setBackground(java.awt.Color.white);
+ statusLine = new javax.swing.JLabel("Ready", javax.swing.JLabel.CENTER);
+
+ setLayout(new java.awt.BorderLayout());
+
+ statusPanel.setLayout(new java.awt.BorderLayout());
+
+ statusLine.setText("Waiting to install. \n All Office processes must be terminated.");
+ statusPanel.add(statusLine, java.awt.BorderLayout.CENTER);
+
+ add(statusPanel, java.awt.BorderLayout.CENTER);
+ nav = new NavPanel(wizard, true, true, true, InstallWizard.VERSIONS, "");
+ nav.setNextListener(this);
+ nav.removeCancelListener(nav);
+ nav.setCancelListener(this);
+ nav.navNext.setText("Install");
+ add(nav, java.awt.BorderLayout.SOUTH);
+
+
+
+ }//GEN-END:initComponents
+
+ public java.awt.Dimension getPreferredSize() {
+ return new java.awt.Dimension(InstallWizard.DEFWIDTH, InstallWizard.DEFHEIGHT);
+ }
+
+ public void actionPerformed(ActionEvent e) {
+ // navNext is "Install"
+ if (e.getSource() == nav.navNext)
+ {
+ JProgressBar progressBar=new JProgressBar();
+ progressBar.setMaximum(10);
+ progressBar.setValue(0);
+ statusPanel.add(progressBar, java.awt.BorderLayout.SOUTH);
+ nav.enableNext(false);
+ nav.enableBack(false);
+ nav.enableCancel(false);
+ ArrayList locations = wizard.getLocations();
+ //System.out.println("here "+locations.size());
+ // Returned 1
+ String progpath=null;
+ String path=null;
+ String classespath=null;
+ for (int i =0;i<locations.size();i++){
+ path= (String)locations.get(i);
+ //InstallWizard.currentPath = path;
+ xud = new XmlUpdater(path, statusLine,progressBar,InstallWizard.bNetworkInstall,InstallWizard.bBindingsInstall);
+ xud.addInstallListener(this);
+ InstallWizard.setInstallStarted(true);
+ InstallWizard.setPatchedTypes(false);
+ InstallWizard.setPatchedJava(false);
+ InstallWizard.setPatchedRDB(false);
+ xud.start();
+ }
+ }
+
+ // set to "Exit" at end of installation process
+ if (e.getSource() == nav.navCancel) {
+ int answer = JOptionPane.showConfirmDialog(wizard, "Are you sure you want to exit?");
+ if (answer == JOptionPane.YES_OPTION)
+ {
+ wizard.exitForm(null);
+ }
+ else
+ {
+ return;
+ }
+ }
+ }// actionPerformed
+
+
+ public void installationComplete(InstallationEvent ev) {
+ //System.out.println("Detected installation complete");
+ if( InstUtil.hasNetbeansInstallation() ) {
+ //System.out.println("Detected installation complete (IDE(s) detected)");
+ nav.removeCancelListener(this);
+ nav.setCancelListener(nav);
+ nav.navCancel.setText("Finish");
+ nav.enableIDE(true);
+ nav.enableCancel(true);
+ xud = null;
+ }
+ else {
+ //System.out.println("Detected installation complete (No IDE(s) detected)");
+ nav.removeCancelListener(this);
+ nav.setCancelListener(nav);
+ nav.navCancel.setText("Finish");
+ nav.enableCancel(true);
+ xud = null;
+ }
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JPanel statusPanel;
+ private javax.swing.JLabel statusLine;
+ private InstallWizard wizard;
+ private NavPanel nav;
+ private XmlUpdater xud;
+ // End of variables declaration//GEN-END:variables
+
+}
diff --git a/scripting/workben/installer/IdeFinal.java b/scripting/workben/installer/IdeFinal.java
new file mode 100644
index 000000000000..d7b622a02bef
--- /dev/null
+++ b/scripting/workben/installer/IdeFinal.java
@@ -0,0 +1,125 @@
+package installer;
+
+/*
+ * Welcome.java
+ *
+ * Created on 04 July 2002, 15:43
+ */
+
+/**
+ *
+ * @author mike
+ */
+
+import java.awt.event.*;
+import java.util.*;
+import java.net.*;
+import javax.swing.*;
+
+public class IdeFinal extends javax.swing.JPanel implements ActionListener, InstallListener {
+
+ /** Creates new form Welcome */
+ public IdeFinal(InstallWizard wizard) {
+ this.wizard = wizard;
+ setBackground(java.awt.Color.white);
+ ideupdater = null;
+ initComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ private void initComponents() {//GEN-BEGIN:initComponents
+ statusPanel = new javax.swing.JPanel();
+ statusPanel.setBackground(java.awt.Color.white);
+ statusLine = new javax.swing.JLabel("Ready", javax.swing.JLabel.CENTER);
+
+ setLayout(new java.awt.BorderLayout());
+
+ statusPanel.setLayout(new java.awt.BorderLayout());
+
+ statusLine.setText("Waiting to install IDE support.");
+ statusPanel.add(statusLine, java.awt.BorderLayout.CENTER);
+
+ add(statusPanel, java.awt.BorderLayout.CENTER);
+ nav = new NavPanel(wizard, true, true, true, InstallWizard.IDEVERSIONS, "");
+ nav.setNextListener(this);
+ nav.removeCancelListener(nav);
+ nav.setCancelListener(this);
+ nav.navNext.setText("Install");
+ add(nav, java.awt.BorderLayout.SOUTH);
+ }//GEN-END:initComponents
+
+ public java.awt.Dimension getPreferredSize() {
+ return new java.awt.Dimension(InstallWizard.DEFWIDTH, InstallWizard.DEFHEIGHT);
+ }
+
+ public void actionPerformed(ActionEvent e) {
+ // navNext is "Install"
+ if (e.getSource() == nav.navNext)
+ {
+ JProgressBar progressBar=new JProgressBar();
+ progressBar.setMaximum(10);
+ progressBar.setValue(0);
+ statusPanel.add(progressBar, java.awt.BorderLayout.SOUTH);
+ nav.enableNext(false);
+ nav.enableBack(false);
+ nav.enableCancel(false);
+ ArrayList locations = wizard.getLocations();
+ //System.out.println("here "+locations.size());
+ // Returned 1
+ String progpath=null;
+ String path=null;
+ String classespath=null;
+ for (int i =0;i<locations.size();i++){
+ path= (String)locations.get(i);
+
+ //InstallWizard.currentPath = path;
+ ideupdater = new IdeUpdater( path, statusLine, progressBar );
+ ideupdater.addInstallListener(this);
+ InstallWizard.setInstallStarted(true);
+ //InstallWizard.setPatchedTypes(false);
+ //InstallWizard.setPatchedJava(false);
+ //InstallWizard.setPatchedRDB(false);
+ ideupdater.start();
+ }
+ }
+
+ // set to "Exit" at end of installation process
+ if (e.getSource() == nav.navCancel) {
+ int answer = JOptionPane.showConfirmDialog(wizard, "Are you sure you want to exit?");
+ if (answer == JOptionPane.YES_OPTION)
+ {
+ wizard.exitForm(null);
+ }
+ else
+ {
+ return;
+ }
+ }
+ }// actionPerformed
+
+
+ public void installationComplete(InstallationEvent ev) {
+ //System.out.println("Detected installation complete");
+ //if( InstUtil.hasNetbeansInstallation() || InstUtil.hasJeditInstallation() ) {
+ //System.out.println("Detected installation complete (IDE(s) detected)");
+ nav.removeCancelListener(this);
+ nav.setCancelListener(nav);
+ nav.navCancel.setText("Finish");
+ nav.enableCancel(true);
+ ideupdater = null;
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JPanel statusPanel;
+ private javax.swing.JLabel statusLine;
+ private InstallWizard wizard;
+ private NavPanel nav;
+ //private XmlUpdater xud;
+ private IdeUpdater ideupdater;
+ // End of variables declaration//GEN-END:variables
+
+}
diff --git a/scripting/workben/installer/IdeUpdater.java b/scripting/workben/installer/IdeUpdater.java
new file mode 100644
index 000000000000..dd7dbb0991a8
--- /dev/null
+++ b/scripting/workben/installer/IdeUpdater.java
@@ -0,0 +1,172 @@
+package installer;
+
+import java.io.*;
+import java.util.*;
+import java.util.jar.*;
+//import org.xml.sax.*;
+//import org.w3c.dom.*;
+//import javax.xml.parsers.*;
+import java.net.URL;
+import java.net.JarURLConnection;
+//import javax.xml.parsers.*;
+import javax.swing.*;
+
+/**
+ * The <code>XmlUpdater</code> pulls a META-INF/converter.xml
+ * file out of a jar file and parses it, providing access to this
+ * information in a <code>Vector</code> of <code>ConverterInfo</code>
+ * objects.
+ *
+ * @author Aidan Butler
+ */
+public class IdeUpdater extends Thread {
+
+ private String classesPath = null;
+ private String jarfilename;
+ private String installPath;
+
+ private JLabel statusLabel;
+
+ private Vector listeners;
+ private Thread internalThread;
+ private boolean threadSuspended;
+ private JProgressBar progressBar;
+
+ private boolean isNetbeansPath = false;
+
+
+ public IdeUpdater(String installPath, JLabel statusLabel, JProgressBar pBar) {
+
+ if (installPath.endsWith(File.separator) == false)
+ installPath += File.separator;
+
+ //File jeditLauncher = new File( installPath + "jedit.jar" );
+ File netbeansLauncher = new File( installPath + "bin" );
+
+ if( netbeansLauncher.isDirectory() ) {
+ isNetbeansPath = true;
+ installPath = installPath +"modules" + File.separator;
+ }
+ /*
+ else if( jeditLauncher.isFile() ){
+ isNetbeansPath = false;
+ installPath = installPath + "jars" + File.separator;
+ }
+ */
+
+ System.out.println( "IdeUpdater installPath is " + installPath + " isNetbeansPath is " + isNetbeansPath );
+ this.installPath = installPath;
+ this.statusLabel = statusLabel;
+ listeners = new Vector();
+ threadSuspended = false;
+ progressBar=pBar;
+ progressBar.setStringPainted(true);
+ }// XmlUpdater
+
+
+ public boolean checkStop()
+ {
+ if (internalThread == Thread.currentThread())
+ return false;
+ return true;
+ }// checkStop
+
+
+ public void checkSuspend()
+ {
+ if (threadSuspended)
+ {
+ synchronized(this)
+ {
+ while (threadSuspended)
+ {
+ try {
+ wait();
+ } catch (InterruptedException eInt) {
+ //...
+ }
+ }
+ }
+ }
+ }// checkSuspend
+
+
+ public void setSuspend()
+ {
+ threadSuspended = true;
+ }// setSuspend
+
+
+ public void setResume()
+ {
+ threadSuspended = false;
+ notify();
+ }// setResume
+
+
+ public void setStop()
+ {
+ internalThread = null;
+ }// setStop
+
+
+ public void run() {
+
+ //InputStream istream;
+ //URL url;
+ //String fileName = null;
+
+ internalThread = Thread.currentThread();
+
+ progressBar.setString("Unzipping Required Files");
+ ZipData zd = new ZipData("SFrameworkInstall.jar");
+
+ // Adding IDE support
+ if( isNetbeansPath ) {
+ if (!zd.extractEntry("ide/office.jar",installPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ }
+ else {
+ if (!zd.extractEntry("ide/idesupport.jar",installPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("ide/OfficeScripting.jar",installPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ }
+
+ //System.out.println("About to call register");
+ //Register.register(installPath+File.separator, statusLabel, progressBar);
+
+ statusLabel.setText("Installation Complete");
+ progressBar.setString("Installation Complete");
+ progressBar.setValue(10);
+ onInstallComplete();
+
+ }// run
+
+
+ public void addInstallListener(InstallListener listener)
+ {
+ listeners.addElement(listener);
+ }// addInstallListener
+
+
+ private void onInstallComplete()
+ {
+ Enumeration e = listeners.elements();
+ while (e.hasMoreElements())
+ {
+ InstallListener listener = (InstallListener)e.nextElement();
+ listener.installationComplete(null);
+ }
+ }// onInstallComplete
+
+}// XmlUpdater class
diff --git a/scripting/workben/installer/IdeVersion.java b/scripting/workben/installer/IdeVersion.java
new file mode 100644
index 000000000000..9d35f5bd623a
--- /dev/null
+++ b/scripting/workben/installer/IdeVersion.java
@@ -0,0 +1,349 @@
+package installer;
+
+/*
+ * Welcome.java
+ *
+ * Created on 04 July 2002, 15:43
+ */
+
+/**
+ *
+ * @author mike
+ */
+
+import java.awt.*;
+import java.awt.event.*;
+import java.io.*;
+import java.util.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import javax.swing.table.*;
+import javax.swing.SwingUtilities.*;
+
+public class IdeVersion extends javax.swing.JPanel implements ActionListener, TableModelListener {
+
+ /** Creates new form Welcome */
+ public IdeVersion(InstallWizard wizard) {
+ this.wizard=wizard;
+ setBackground(Color.white);
+ initComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ private void initComponents() {
+ Properties props = null;
+ JPanel versionPanel = new JPanel();
+ setLayout(new BorderLayout());
+
+
+ try {
+ //props = InstUtil.getNetbeansLocation();
+
+ Properties netbeansProps = InstUtil.getNetbeansLocation();
+ //Properties jeditProps = InstUtil.getJeditLocation();
+ Properties ideProps = new Properties();
+ if(netbeansProps!=null )
+ {
+ System.out.println("**** Found netbeans install");
+ for( int n = 0; n < netbeansProps.size(); n++ ) {
+ for( int v = 0; v < InstUtil.versions.length; v++ ) {
+ System.out.println("n: " +n+" v: " +v);
+ String key = InstUtil.versions[v];
+ System.out.println("It got here1");
+ String path = null;
+ if ( (path = netbeansProps.getProperty(key) ) != null ) {
+ //System.out.println( "n="+n+" v="+v + " Netbeans " + " key=" + key + " path=" + path );
+ ideProps.put(key, path);
+ }
+ }
+ }
+ }
+ //System.out.println("*** About to look for jedit install");
+ /*
+ if(jeditProps!=null)
+ {
+ for( int j = 0; j < jeditProps.size(); j++ ) {
+ for( int v = 0; v < InstUtil.versions.length; v++ ) {
+ System.out.println("j: " +j+" v: " +v);
+ String key = InstUtil.versions[v];
+ String path = null;
+ if ((path = jeditProps.getProperty(key)) != null) {
+ //System.out.println( "j="+j+" v="+v + " jEdit " + " key=" + key + " path=" + path );
+ ideProps.put(key, path);
+ }
+ }
+ }
+ }
+ */
+ props = ideProps;
+ }
+ catch (IOException eIO) {
+ System.err.println("Failed to parse .netbeans/ide.log");
+ //JOptionPane.showMessageDialog(this, "There was a problem reading from the NetBeans ide.log file.", "Parse Error", JOptionPane.ERROR_MESSAGE);
+ }
+ catch (Exception e) {
+ System.err.println("Exception thrown in initComponents");
+ }
+
+ tableModel = new MyTableModelIDE (props, InstUtil.versions);
+
+ if (tableModel.getRowCount() == 0)
+ {
+ JOptionPane.showMessageDialog(this, "No compatible IDEs were found.", "Invalid versions", JOptionPane.ERROR_MESSAGE);
+ //wizard.exitForm(null);
+ }
+
+ tableModel.addTableModelListener(this);
+ JTable tableVersions = new JTable(tableModel) {
+ public String getToolTipText(MouseEvent event)
+ {
+ int col = columnAtPoint( event.getPoint() );
+ if (col != 2)
+ return null;
+
+ int row = rowAtPoint( event.getPoint() );
+ Object o = getValueAt(row, col);
+
+ if (o == null)
+ return null;
+
+ if (o.toString().equals(""))
+ return null;
+
+ return o.toString();
+ }
+
+ public Point getToolTipLocation(MouseEvent event)
+ {
+ int col = columnAtPoint( event.getPoint() );
+ if (col != 2)
+ return null;
+
+ int row = rowAtPoint( event.getPoint() );
+ Object o = getValueAt(row,col);
+
+ if (o == null)
+ return null;
+
+ if (o.toString().equals(""))
+ return null;
+
+ Point pt = getCellRect(row, col, true).getLocation();
+ pt.translate(-1,-2);
+ return pt;
+ }
+ };
+
+ JScrollPane scroll = new JScrollPane(tableVersions);
+
+ tableVersions.setPreferredSize(
+ new Dimension(InstallWizard.DEFWIDTH,InstallWizard.DEFHEIGHT));
+
+ tableVersions.setRowSelectionAllowed(false);
+ tableVersions.setColumnSelectionAllowed(false);
+ tableVersions.setCellSelectionEnabled(false);
+
+ initColumnSizes(tableVersions, tableModel);
+ versionPanel.add(scroll);
+
+ JTextArea area = new JTextArea("Please select IDEs below that you wish to add Scripting support to");
+ area.setLineWrap(true);
+ area.setEditable(false);
+ add(area, BorderLayout.NORTH);
+ add(versionPanel, BorderLayout.CENTER);
+ nav = new NavPanel(wizard, true, false, true, InstallWizard.IDEWELCOME, InstallWizard.IDEFINAL);
+ nav.setNextListener(this);
+ add(nav, BorderLayout.SOUTH);
+
+ }// initComponents
+
+
+ public java.awt.Dimension getPreferredSize() {
+ return new java.awt.Dimension(320, 280);
+ }
+
+
+ public void actionPerformed(ActionEvent ev) {
+ wizard.clearLocations();
+ int len = tableModel.data.size();
+ for (int i = 0; i < len; i++) {
+ ArrayList list = (ArrayList)tableModel.data.get(i);
+ if (((Boolean)list.get(0)).booleanValue() == true)
+ wizard.storeLocation((String)list.get(2));
+ }
+
+ //System.out.println(wizard.getLocations());
+ }
+
+
+ public void tableChanged(TableModelEvent e) {
+ if (tableModel.isAnySelected()) {
+ nav.enableNext(true);
+ }
+ else {
+ nav.enableNext(false);
+ }
+ }
+
+ private void initColumnSizes(JTable table, MyTableModelIDE model) {
+ TableColumn column = null;
+ Component comp = null;
+ int headerWidth = 0;
+ int cellWidth = 0;
+ int preferredWidth = 0;
+ int totalWidth = 0;
+ Object[] longValues = model.longValues;
+
+ for (int i = 0; i < 3; i++) {
+ column = table.getColumnModel().getColumn(i);
+
+ try {
+ comp = column.getHeaderRenderer().
+ getTableCellRendererComponent(
+ null, column.getHeaderValue(),
+ false, false, 0, 0);
+ headerWidth = comp.getPreferredSize().width;
+ } catch (NullPointerException e) {
+ // System.err.println("Null pointer exception!");
+ // System.err.println(" getHeaderRenderer returns null in 1.3.");
+ // System.err.println(" The replacement is getDefaultRenderer.");
+ }
+
+ // need to replace spaces in String before getting preferred width
+ if (longValues[i] instanceof String) {
+ longValues[i] = ((String)longValues[i]).replace(' ', '_');
+ }
+
+ System.out.println("longValues: " + longValues[i]);
+ comp = table.getDefaultRenderer(model.getColumnClass(i)).
+ getTableCellRendererComponent(
+ table, longValues[i],
+ false, false, 0, i);
+ cellWidth = comp.getPreferredSize().width;
+
+ preferredWidth = Math.max(headerWidth, cellWidth);
+
+ if (false) {
+ System.out.println("Initializing width of column "
+ + i + ". "
+ + "preferredWidth = " + preferredWidth
+ + "; totalWidth = " + totalWidth
+ + "; leftWidth = " + (InstallWizard.DEFWIDTH - totalWidth));
+ }
+
+ //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
+ if (i == 2) {
+ if (preferredWidth > InstallWizard.DEFWIDTH - totalWidth)
+ column.setPreferredWidth(InstallWizard.DEFWIDTH - totalWidth);
+ else
+ column.setPreferredWidth(preferredWidth);
+ }
+ else {
+ column.setMinWidth(preferredWidth);
+ totalWidth += preferredWidth;
+ }
+ }
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JTextField jTextField2;
+ private InstallWizard wizard;
+ private MyTableModelIDE tableModel;
+ private NavPanel nav;
+ // End of variables declaration//GEN-END:variables
+
+ }
+
+class MyTableModelIDE extends AbstractTableModel {
+ ArrayList data;
+ String colNames[] = {"", "IDE Name", "IDE Location"};
+ Object[] longValues = new Object[] {Boolean.TRUE, "Name", "Location"};
+
+ MyTableModelIDE (Properties properties, String [] validVersions) {
+ data = new ArrayList();
+ //System.out.println(properties);
+
+ int len = validVersions.length;
+ for (int i = 0; i < len; i++) {
+ String key = validVersions[i];
+ String path = null;
+
+ if ((path = properties.getProperty(key)) != null) {
+ ArrayList row = new ArrayList();
+ row.add(0, new Boolean(false));
+
+ row.add(1, key);
+ if (key.length() > ((String)longValues[1]).length()) {
+ longValues[1] = key;
+ }
+
+ row.add(2, path);
+ if (path.length() > ((String)longValues[2]).length()) {
+ longValues[2] = path;
+ }
+
+ data.add(row);
+ }
+ }
+ }// MyTableModel
+
+ public int getColumnCount() {
+ return 3;
+ }
+
+ public int getRowCount() {
+ return data.size();
+ }
+
+ public String getColumnName(int col) {
+ return colNames[col];
+ }
+
+ public Object getValueAt(int row, int col) {
+ if (row < 0 || row > getRowCount() ||
+ col < 0 || col > getColumnCount())
+ return null;
+
+ ArrayList aRow = (ArrayList)data.get(row);
+ return aRow.get(col);
+ }
+
+ public Class getColumnClass(int c) {
+ return getValueAt(0, c).getClass();
+ }
+
+ public boolean isCellEditable(int row, int col) {
+ if (col == 0) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void setValueAt(Object value, int row, int col) {
+ ArrayList aRow = (ArrayList)data.get(row);
+ aRow.set(col, value);
+ fireTableCellUpdated(row, col);
+ }
+
+ String [] getSelected() {
+ return null;
+ }
+
+ public boolean isAnySelected() {
+ Iterator iter = data.iterator();
+ while (iter.hasNext()) {
+ ArrayList row = (ArrayList)iter.next();
+ if (((Boolean)row.get(0)).booleanValue() == true) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+}
+
diff --git a/scripting/workben/installer/IdeWelcome.java b/scripting/workben/installer/IdeWelcome.java
new file mode 100644
index 000000000000..93ce8ec5e22a
--- /dev/null
+++ b/scripting/workben/installer/IdeWelcome.java
@@ -0,0 +1,79 @@
+package installer;
+
+/*
+ * Welcome.java
+ *
+ * Created on 04 July 2002, 15:43
+ */
+
+/**
+ *
+ * @author mike
+ */
+import java.awt.event.*;
+import javax.swing.*;
+import java.io.*;
+import java.net.*;
+import java.awt.*;
+
+public class IdeWelcome extends javax.swing.JPanel implements ActionListener {
+
+ /** Creates new form Welcome */
+ public IdeWelcome(InstallWizard wizard) {
+ this.wizard = wizard;
+ setBorder(new javax.swing.border.EtchedBorder(javax.swing.border.EtchedBorder.RAISED));
+ initComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ private void initComponents() {//GEN-BEGIN:initComponents
+ welcomePanel = new javax.swing.JPanel();
+ area = new javax.swing.JTextArea();
+
+ setLayout(new java.awt.BorderLayout());
+
+ welcomePanel.setLayout(new java.awt.BorderLayout());
+ //area.setHorizontalAlignment(javax.swing.JTextField.CENTER);
+ area.setEditable(false);
+ area.setLineWrap(true);
+ area.setText("\n Click Next to include Scripting Framework support for IDEs.");
+ area.append("\n Click Cancel exit the Installation process. \n");
+ if( InstUtil.hasNetbeansInstallation() ) {
+ area.append("\n \tA version of Netbeans has been detected. \n");
+ }
+ //if( InstUtil.hasJeditInstallation() ) {
+ // area.append("\n \tA version of jEdit has been detected.");
+ //}
+
+ welcomePanel.add(area, java.awt.BorderLayout.CENTER);
+ add(welcomePanel, java.awt.BorderLayout.CENTER);
+ NavPanel nav = new NavPanel(wizard, false, true, true, "", InstallWizard.IDEVERSIONS);
+ nav.setNextListener(this);
+ add(nav, java.awt.BorderLayout.SOUTH);
+
+ //Banner br = new Banner();
+ //add(br, java.awt.BorderLayout.WEST);
+
+ }//GEN-END:initComponents
+
+ public java.awt.Dimension getPreferredSize() {
+ return new java.awt.Dimension(InstallWizard.DEFWIDTH, InstallWizard.DEFHEIGHT);
+ }
+
+ public void actionPerformed(ActionEvent ev)
+ {
+ //Perform next actions here...
+ }
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JPanel welcomePanel;
+ private javax.swing.JTextArea area;
+ private InstallWizard wizard;
+
+ // End of variables declaration//GEN-END:variables
+}
diff --git a/scripting/workben/installer/InstUtil.java b/scripting/workben/installer/InstUtil.java
new file mode 100644
index 000000000000..5ca03e27a19b
--- /dev/null
+++ b/scripting/workben/installer/InstUtil.java
@@ -0,0 +1,463 @@
+package installer;
+
+import java.net.URLDecoder;
+import java.io.*;
+import java.util.*;
+import java.util.zip.*;
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+import java.net.*;
+
+public class InstUtil {
+
+ public static File buildSversionLocation() throws IOException {
+ File theFile = null;
+ StringBuffer str = new StringBuffer();
+ str.append(System.getProperty("user.home"));
+ str.append(File.separator);
+ StringBuffer thePath = new StringBuffer(str.toString());
+
+ String os = System.getProperty("os.name");
+
+ if (os.indexOf("Windows") != -1) {
+ boolean bSVersionInHomeDir = new File(thePath.toString() + "sversion.ini").exists();
+
+ if (!bSVersionInHomeDir) {
+ thePath.append("Application Data");
+ thePath.append(File.separator);
+ }
+ theFile = findVersionFile(new File(thePath.toString()));
+ } else if (os.indexOf("SunOS") != -1) {
+ thePath.append(".sversionrc");
+ theFile = new File(thePath.toString());
+ } else if (os.indexOf("Linux") != -1) {
+ thePath.append(".sversionrc");
+ theFile = new File(thePath.toString());
+ }
+
+ if (theFile == null)
+ {
+ throw new IOException("Could not locate the OpenOffice settings file.\nAre you sure StarOffice is installed on your system?");
+ }
+ if (!theFile.exists())
+ {
+ throw new IOException("Could not locate the OpenOffice settings file.\nAre you sure StarOffice is installed on your system?");
+ }
+ return theFile;
+ }
+
+
+
+ public static boolean hasNetbeansInstallation() {
+ boolean result = false;
+ try
+ {
+ result = checkForSupportedVersion( getNetbeansLocation(), versions );
+
+ if (result == false)
+ System.out.println("No supported version of NetBeans found.");
+ }
+ catch ( IOException ioe )
+ {
+ System.err.println("Exception caught trying to determine netbeans installation: " + ioe );
+ ioe.printStackTrace();
+ result = false;
+ }
+ return result;
+ }
+
+ private static boolean checkForSupportedVersion( Properties installs, String[] supportedVersions )
+ {
+ if ( installs != null )
+ {
+ for ( int index = 0; index < supportedVersions.length; index++ )
+ {
+ String key = supportedVersions[ index ];
+ String path = null;
+ if ( ( path = installs.getProperty(key) ) != null )
+ {
+ // at least one supported version for netbeans present, so return;
+ return true;
+ }
+
+ }
+ }
+ return false;
+ }
+
+
+ public static boolean hasJeditInstallation() {
+ boolean result = false;
+ try
+ {
+ result = checkForSupportedVersion( getJeditLocation(), versions );
+ if ( !result )
+ {
+ System.out.println("No supported version for JEdit found.");
+ }
+ }
+ catch ( IOException ioe )
+ {
+ System.err.println("Exception caught trying to determine jedit installation: " + ioe );
+ ioe.printStackTrace();
+ result = false;
+ }
+ return result;
+ }
+
+
+
+ public static Properties getNetbeansLocation() throws IOException {
+ File theFile = null;
+ Properties results = new Properties();
+
+ StringBuffer str = new StringBuffer();
+ str.append(System.getProperty("user.home"));
+ str.append(File.separator);
+ StringBuffer thePath = new StringBuffer(str.toString());
+
+ String os = System.getProperty("os.name");
+
+ if (os.indexOf("Windows") != -1) {
+ //theFile = findVersionFile(new File(str.toString()));
+ thePath.append(".netbeans");
+ //theFile = new File(thePath.toString());
+ } else if (os.indexOf("SunOS") != -1) {
+ thePath.append(".netbeans");
+ //theFile = new File(thePath.toString());
+ } else if (os.indexOf("Linux") != -1) {
+ thePath.append(".netbeans");
+ //theFile = new File(thePath.toString());
+ }
+
+ if ( thePath.toString().indexOf( ".netbeans" ) == -1 )
+ return null;
+ else if ( new File( thePath.append( File.separator+"3.4"+File.separator ).toString() ).isDirectory() ) {
+
+ System.out.println( "Found NetBeans 3.4 user directory: " + thePath );
+ File netbeansLogFile = new File( thePath.toString() + File.separator + "system" + File.separator + "ide.log" );
+ if( netbeansLogFile.exists() ) {
+ String installPath = getNetbeansInstallation( netbeansLogFile );
+ File f = new File(installPath);
+ results.put("NetBeans 3.4", f.getPath()+File.separator);
+ System.out.println( "NetBeans Installation directory: " + f.getPath());
+ }
+ else {
+ System.out.println( "No NetBeans log file found" );
+ return null;
+ }
+ }
+ else
+ {
+ System.out.println( "No NetBeans user directory found" );
+ return null;
+ }
+
+
+ return results;
+ }
+
+
+
+ public static Properties getJeditLocation() throws IOException {
+
+ /*if( !hasJeditInstallation() ) {
+ System.out.println( "No Jedit found (line195 InstUtil");
+ return null;
+ }*/
+
+ File theFile = null;
+ Properties results = new Properties();
+
+ StringBuffer str = new StringBuffer();
+ str.append(System.getProperty("user.home"));
+ str.append(File.separator);
+ StringBuffer thePath = new StringBuffer(str.toString());
+
+ String os = System.getProperty("os.name");
+ thePath.append(".jedit");
+ //System.out.println( ".jedit path " + thePath );
+
+ File jeditLogFile = new File( thePath.toString() + File.separator + "activity.log" );
+ if( jeditLogFile.exists() ) {
+ String[] jeditDetails = getJeditInstallation( jeditLogFile );
+ System.out.println( "getJeditLocation ) " + jeditDetails[0] );
+ File f = new File(jeditDetails[0]);
+ results.put("jEdit "+jeditDetails[1], jeditDetails[0]);
+ System.out.println( "jeditDetails[0] is " + jeditDetails[0]);
+ }
+ else {
+ System.out.println( "Prompt user for Jedit installation path" );
+ }
+
+
+ return results;
+ }
+
+
+
+
+
+ private static String getNetbeansInstallation( File logFile ) {
+ String installPath = "";
+ try {
+ BufferedReader reader = new BufferedReader(new FileReader(logFile));
+
+ for (String s = reader.readLine(); s != null; s = reader.readLine()) {
+ s.trim();
+ if( s.indexOf( "IDE Install" ) != -1 ) {
+ int pathStart = s.indexOf( "=" ) + 2;
+ //System.out.println( "pathStart " + pathStart );
+ installPath = s.substring( pathStart, s.length() );
+ //System.out.println( "installPath 1" + installPath );
+ int pathEnd = installPath.indexOf( ";");
+ //System.out.println( "pathEnd " + pathEnd );
+ installPath = installPath.substring( 0, pathEnd ) +File.separator;
+ //System.out.println( "pathStart " + pathStart );
+ //int pathEnd = s.indexOf( ";");
+ //System.out.println( "pathEnd " + pathEnd );
+ //System.out.println( "s is " + s + " and " + s.length() + " long" );
+ //installPath = s.substring( pathStart, pathEnd - 1 );
+ installPath.trim();
+ break;
+ }
+ }
+ }
+ catch( IOException ioe ) {
+ System.out.println( "Error reading Netbeans location information" );
+ }
+ //catch( FileNotFoundException fnfe ) {
+ //System.out.println( "NetBeans ide.log FileNotFoundException" );
+ //}
+
+ return installPath;
+ }
+
+
+ private static String[] getJeditInstallation( File logFile ) {
+ String[] jeditDetails = new String[2];
+ try {
+ BufferedReader reader = new BufferedReader(new FileReader(logFile));
+ String installPath = "";
+ String version = "";
+
+ for (String s = reader.readLine(); s != null; s = reader.readLine()) {
+ s.trim();
+ if( s.indexOf( "jEdit home directory is" ) != -1 ) {
+ int pathStart = new String( "[message] jEdit: jEdit home directory is " ).length();
+ //System.out.println( "pathStart " + pathStart );
+ installPath = s.substring( pathStart, s.length() ) +File.separator;
+ System.out.println( "installPath 1" + installPath );
+ //int pathEnd = installPath.indexOf( ";");
+ //System.out.println( "pathEnd " + pathEnd );
+ //installPath = installPath.substring( 0, pathEnd ) +File.separator;
+ //System.out.println( "pathStart " + pathStart );
+ //int pathEnd = s.indexOf( ";");
+ //System.out.println( "pathEnd " + pathEnd );
+ //System.out.println( "s is " + s + " and " + s.length() + " long" );
+ //installPath = s.substring( pathStart, pathEnd - 1 );
+ installPath.trim();
+ //System.out.println( "installPath 2 " + installPath );
+ //break;
+ jeditDetails[0] = installPath;
+ }
+ if( s.indexOf( "jEdit: jEdit version" ) != -1 ) {
+ int versionStart = s.indexOf( "version" ) + 8;
+ System.out.println( "versionStart is: " + versionStart );
+ version = s.substring( versionStart, s.length() );
+ version.trim();
+ System.out.println( "jEdit version is: " + version );
+ jeditDetails[1] = version;
+ }
+ }
+ }
+ catch( IOException ioe ) {
+ System.out.println( "Error reading Jedit location information" );
+ }
+ //catch( FileNotFoundException fnfe ) {
+ //System.out.println( "Jedit activity.log FileNotFoundException" );
+ //}
+
+ return jeditDetails;
+ }
+
+
+
+ public static File findVersionFile(File start)
+ {
+ File versionFile = null;
+
+ File files[] = start.listFiles(new VersionFilter());
+ if (files.length == 0)
+ {
+ File dirs[] = start.listFiles(new DirFilter());
+ for (int i=0; i< dirs.length; i++)
+ {
+ versionFile = findVersionFile(dirs[i]);
+ if (versionFile != null)
+ {
+ break;
+ }
+ }
+ }
+ else
+ {
+ versionFile = files[0];
+ }
+
+ return versionFile;
+ }
+
+ public static boolean verifySversionExists(File sversionFile) {
+ if (!sversionFile.exists())
+ return false;
+ return true;
+ }
+
+ public static Properties getOfficeVersions(File sversionFile) throws IOException {
+ BufferedReader reader = new BufferedReader(new FileReader(sversionFile));
+ Vector values;
+ String sectionName = null;
+ Properties results = new Properties();
+
+ for (String s = reader.readLine(); s != null; s = reader.readLine()) {
+ s.trim();
+ //System.out.println(s);
+ if (s.length() == 0)
+ continue;
+ if (s.charAt(0) == '[') {
+ sectionName = s.substring(1, s.length() - 1);
+ //System.out.println(sectionName);
+ continue;
+ }
+ if ((sectionName != null) && sectionName.equalsIgnoreCase("Versions")) {
+ int equals = s.indexOf( "=" );
+ String officeName = s.substring(0, equals );
+
+ String instPath = s.substring(equals + 8, s.length());
+ String [] parts = new String[2];
+ parts[0] = officeName;
+ parts[1] = instPath + File.separator;
+ //System.out.println( "InstUtil officeName " + officeName );
+ //System.out.println( "InstUtil instPath " + instPath );
+
+ //String [] parts = s.split("=");
+ if (parts.length == 2) {
+ //ver.version = parts[0].trim();
+ //File f = new File(parts[1].trim());
+ //results.put(parts[0].trim(), f.getPath());
+ try {
+ URL url = new URL("file://" + parts[1].trim());
+ String opSys =System.getProperty("os.name");
+ if (opSys.indexOf("Windows")!=-1){
+ String windowsPath = URLDecoder.decode( url.getPath() );
+ boolean firstSlash = true;
+ while( windowsPath.indexOf("/") != -1 ) {
+ int forwardSlashPos = windowsPath.indexOf("/");
+ String firstPart = windowsPath.substring( 0, forwardSlashPos );
+ String lastPart = windowsPath.substring( forwardSlashPos + 1, windowsPath.length() );
+ if( firstSlash ) {
+ windowsPath = lastPart;
+ firstSlash = false;
+ }
+ else {
+ windowsPath = firstPart + "\\" + lastPart;
+ }
+ }
+ int lastSlash = windowsPath.lastIndexOf("\\");
+ windowsPath = windowsPath.substring( 0, lastSlash );
+ results.put( parts[0].trim(), windowsPath );
+ }
+ else {
+ //System.err.println( " InstUtil URLDecoder " + URLDecoder.decode(url.getPath()) );
+ results.put(parts[0].trim(), URLDecoder.decode(url.getPath()));
+ }
+ //File f = new File(url);
+
+ //.sversion: OpenOffice.org 643=file:///scriptdev/neil/ScriptFrameOpenoffice1.0.1
+ // parts = Installation name. f.getPath = Installation path
+ //results.put(parts[0].trim(), f.getPath());
+
+ //results.put(parts[0].trim(), URLDecoder.decode(url.getPath()));
+ //results.put( parts[0].trim(), windowsPath );
+
+ }
+ catch (MalformedURLException eSyntax) {
+ //throw new IOException("Error while reading version information");
+ results.put(parts[0].trim(), parts[1].trim());
+ //System.out.println(parts[0].trim() + " : " + parts[1].trim());
+ System.err.println("GotHereException");
+ }
+ }
+ else {
+ System.out.println("not splitting on equals");
+ }
+ }
+ }
+
+ return results;
+ }
+
+ public static String getJavaVersion() {
+ return System.getProperty("java.version");
+ }
+
+ public static boolean isCorrectJavaVersion() {
+ if (System.getProperty("java.version").startsWith("1.4"))
+ return true;
+ return false;
+ }
+
+ public static void main(String args[]) {
+ InstUtil inst = new InstUtil();
+ File f = null;
+ try
+ {
+ f = inst.buildSversionLocation();
+ }
+ catch (IOException e)
+ {
+ e.printStackTrace();
+ System.out.println(e.getMessage());
+ }
+ if (!inst.verifySversionExists(f)) {
+ System.err.println("Problem with sversion.ini");
+ }
+ try {
+ Properties vers = inst.getOfficeVersions(f);
+ } catch (IOException e) {
+ e.printStackTrace();
+ System.err.println(e);
+ }
+ System.out.println(inst.getJavaVersion());
+ if (!inst.isCorrectJavaVersion()) {
+ System.err.println("Not correct Java Version");
+ }
+ }
+
+ public static final String [] versions = {"NetBeans 3.4", "jEdit 4.0.3", "jEdit 4.1pre5" };
+ private static File tmpDir = null;
+}
+
+
+
+class DirFilter implements java.io.FileFilter
+{
+ public boolean accept(File aFile)
+ {
+ return aFile.isDirectory();
+ }
+}
+class VersionFilter implements java.io.FileFilter
+{
+ public boolean accept(File aFile)
+ {
+ if (aFile.getName().compareToIgnoreCase("sversion.ini") == 0)
+ {
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/scripting/workben/installer/InstallListener.java b/scripting/workben/installer/InstallListener.java
new file mode 100644
index 000000000000..eade1ef413c8
--- /dev/null
+++ b/scripting/workben/installer/InstallListener.java
@@ -0,0 +1,6 @@
+package installer;
+
+public interface InstallListener
+{
+ public void installationComplete(InstallationEvent e);
+}
diff --git a/scripting/workben/installer/InstallWizard.java b/scripting/workben/installer/InstallWizard.java
new file mode 100644
index 000000000000..14fae1c5dfcd
--- /dev/null
+++ b/scripting/workben/installer/InstallWizard.java
@@ -0,0 +1,389 @@
+package installer;
+
+/*
+ * InstallWizard.java
+ *
+ * Created on 04 July 2002, 15:09
+ */
+
+/**
+ *
+ * @author mike
+ */
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
+import java.util.*;
+import java.net.*;
+import java.io.*;
+
+public class InstallWizard extends javax.swing.JFrame implements ActionListener {
+/*
+ private static class ShutdownHook extends Thread {
+ public void run()
+ {
+ if (InstallWizard.isInstallStarted())
+ {
+ // Check for and backup any config.xml files
+ // Check for and backup any StarBasic macro files
+ // Check for and backup ProtocolHandler
+
+ if (!InstallWizard.isPatchedTypes())
+ {
+ File backup = new File(InstUtil.getTmpDir(), "TypeDetection.xml");
+ File destination = new File(InstallWizard.getTypesPath());
+ InstUtil.copy(backup, destination); //Restore typedetection.xml
+ }
+ if (!InstallWizard.isPatchedJava())
+ {
+ File backup = new File(InstUtil.getTmpDir(), "Java.xml");
+ File destination = new File(InstallWizard.getJavaPath());
+ InstUtil.copy(backup, destination); //Restore typedetection.xml
+ }
+ if (!InstallWizard.isPatchedRDB())
+ {
+ File backup = new File(InstUtil.getTmpDir(), "applicat.rdb");
+ File destination = new File(InstallWizard.getJavaPath());
+ //InstUtil.copy(backup, destination); //Restore typedetection.xml
+ }
+
+ System.out.println( "ShutdownHook" );
+ }
+
+ InstUtil.removeTmpDir();
+ }
+ }// class ShutdownHook
+
+ static {
+ Runtime rt=Runtime.getRuntime();
+ rt.addShutdownHook(new ShutdownHook());
+ }
+*/
+ /** Creates new form InstallWizard */
+ public InstallWizard() {
+ super("Office Scripting Framework Installer - Early Developer Release");
+
+ try {
+ System.out.print("All diagnostic output is being redirected to SFrameworkInstall.log\n");
+ System.out.print("Location: "+ System.getProperty( "user.dir" ) +
+ File.separator + "SFrameworkInstall.log\n");
+
+ LogStream log = new LogStream( "SFrameworkInstall.log" );
+ System.setErr(log);
+
+ System.setOut(log);
+ }
+ catch( FileNotFoundException fnfe ) {
+ System.err.println("Office Scripting Framework Installer - Error: ");
+ System.err.println("Unable to create log file for installation.");
+ exitForm(null);
+ }
+
+ //setBackground(Color.WHITE);
+ setBackground(new Color(0,0,0));
+ locations = new ArrayList();
+ //Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
+ Point center = new Point( 400, 400 );
+ int windowWidth=200;
+ int windowHeight=300;
+ setSize(windowWidth,windowHeight);
+ setBounds((center.x-windowWidth/2)-115,(center.y-windowWidth/2)-100, windowWidth,windowHeight);
+ initComponents();
+ setResizable(false);
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ */
+ private void initComponents() {
+ navigation = new javax.swing.JPanel();
+ navBack = new javax.swing.JButton();
+ navNext = new javax.swing.JButton();
+ navCancel = new javax.swing.JButton();
+ screens = new javax.swing.JPanel();
+
+ addWindowListener(new java.awt.event.WindowAdapter() {
+ public void windowClosing(java.awt.event.WindowEvent evt) {
+ exitForm(evt);
+ }
+ });
+
+ navigation.setLayout(new java.awt.GridBagLayout());
+ java.awt.GridBagConstraints gridBagConstraints1;
+
+ navBack.setText("<< Back");
+ gridBagConstraints1 = new java.awt.GridBagConstraints();
+ gridBagConstraints1.insets = new java.awt.Insets(1, 1, 1, 1);
+
+ navNext.setText("Next >>");
+ gridBagConstraints1 = new java.awt.GridBagConstraints();
+ gridBagConstraints1.gridx = 2;
+ gridBagConstraints1.gridy = 0;
+
+ navCancel.setText("Cancel");
+ gridBagConstraints1 = new java.awt.GridBagConstraints();
+ gridBagConstraints1.gridx = 6;
+ gridBagConstraints1.gridy = 0;
+ //navigation.add(navNext, gridBagConstraints1);
+ //navigation.add(navBack, gridBagConstraints1);
+ //navigation.add(navCancel, gridBagConstraints1);
+
+ getContentPane().add(navigation, java.awt.BorderLayout.SOUTH);
+ screens.setLayout(new java.awt.CardLayout());
+ screens.add(WELCOME, new Welcome(this));
+ version = new Version(this);
+ screens.add(VERSIONS, version);
+ _final = new Final(this);
+ screens.add(FINAL, _final);
+
+ //boolean hasIDEInstallation = (InstUtil.hasNetbeansInstallation() || InstUtil.hasJeditInstallation()) ;
+ boolean hasIDEInstallation = ( InstUtil.hasNetbeansInstallation() ) ;
+
+ if( hasIDEInstallation )
+ {
+ idewelcome = new IdeWelcome(this);
+ screens.add(IDEWELCOME, idewelcome);
+ ideversion = new IdeVersion(this);
+ screens.add(IDEVERSIONS, ideversion);
+ idefinal = new IdeFinal(this);
+ screens.add(IDEFINAL, idefinal);
+ }
+ getContentPane().add(screens, java.awt.BorderLayout.CENTER);
+
+ navNext.addActionListener(this);
+ navNext.addActionListener(version);
+ navNext.addActionListener(_final);
+
+ if( hasIDEInstallation )
+ {
+ navNext.addActionListener(ideversion);
+ navNext.addActionListener(idefinal);
+ }
+
+ navCancel.addActionListener(this);
+ navBack.addActionListener(this);
+
+
+ URL url = this.getClass().getResource("sidebar.jpg");
+ JLabel sideBar = new JLabel();
+ sideBar.setIcon(new ImageIcon(url));
+ getContentPane().add (sideBar, java.awt.BorderLayout.WEST);
+ pack();
+ }// initComponents
+
+ /** Exit the Application */
+ public void exitForm(java.awt.event.WindowEvent evt) {
+ System.exit(0);
+ }
+
+
+ public void actionPerformed(ActionEvent e)
+ {
+ if (e.getSource() == navNext)
+ {
+ ((CardLayout)screens.getLayout()).next(screens);
+ }
+
+ if (e.getSource() == navCancel)
+ {
+ exitForm(null);
+ }
+
+ if (e.getSource() == navBack)
+ {
+ ((CardLayout)screens.getLayout()).previous(screens);
+ }
+ }// actionPerformed
+
+ public static void storeLocation(String path)
+ {
+ locations.add(path);
+ }
+
+ public static ArrayList getLocations()
+ {
+ return locations;
+ }
+
+ public static void clearLocations()
+ {
+ locations.clear();
+ }
+
+ public void show(String cardName)
+ {
+ ((CardLayout)screens.getLayout()).show(screens, cardName);
+ }
+
+ /**
+ * @param args the command line arguments
+ */
+ public static void main(String args[]) {
+ String officePath = null;
+ String netbeansPath = null;
+ //String jeditPath = null;
+ int i = 0;
+
+ while (i < args.length) {
+ if (args[i].equals("-help")) {
+ printUsage();
+ System.exit(0);
+ }
+ if (args[i].equals("-office"))
+ officePath = args[++i];
+ if (args[i].equals("-netbeans"))
+ netbeansPath = args[++i];
+ if (args[i].equals("-net"))
+ bNetworkInstall = true;
+ if (args[i].equals("-bindings"))
+ bBindingsInstall = true;
+ //if (args[i].equals("-jedit"))
+ // jeditPath = args[++i];
+ i++;
+ }
+
+ //if (officePath == null && netbeansPath == null && jeditPath == null)
+ if (officePath == null && netbeansPath == null)
+ new InstallWizard().show();
+
+ JLabel label = new JLabel();
+ JProgressBar progressbar = new JProgressBar();
+
+ try {
+ System.out.println("Log file is: " +
+ System.getProperty("user.dir") +
+ File.separator + "SFrameworkInstall.log");
+
+ LogStream log = new LogStream( "SFrameworkInstall.log" );
+ System.setErr(log);
+ System.setOut(log);
+ }
+ catch( FileNotFoundException fnfe ) {
+ System.err.println("Error: Unable to create log file: "
+ + fnfe.getMessage());
+ System.exit(-1);
+ }
+
+ if (officePath != null) {
+ XmlUpdater xud = new XmlUpdater(officePath, label, progressbar, bNetworkInstall, bBindingsInstall );
+ xud.run();
+ }
+
+ if (netbeansPath != null) {
+ IdeUpdater ideup = new IdeUpdater(netbeansPath, label, progressbar);
+ ideup.run();
+ }
+
+ //if (jeditPath != null) {
+ // IdeUpdater ideup = new IdeUpdater(jeditPath, label, progressbar);
+ // ideup.run();
+ //}
+ }
+
+ private static void printUsage() {
+ System.err.println("java -jar SFrameworkInstall.jar");
+ System.err.println("\t[-office <path_to_office_installation]");
+ System.err.println("\t[-netbeans <path_to_netbeans_installation]");
+ System.err.println("\t[-net]");
+ System.err.println("\t[-bindings]");
+ System.err.println("\n\n-net indicates that this is the network part of a network install.");
+ System.err.println("-bindings will only install the menu & key bindings in user/config/soffice.cfg.");
+ //System.err.println("\t[-jedit <path_to_jedit_installation]");
+ }
+
+ public static synchronized boolean isPatchedTypes()
+ {
+ return bPatchedTypes;
+ }
+
+ public static synchronized boolean isPatchedJava()
+ {
+ return bPatchedJava;
+ }
+
+ public static synchronized boolean isPatchedRDB()
+ {
+ return bPatchedRDB;
+ }
+
+ public static synchronized boolean isInstallStarted()
+ {
+ return bInstallStarted;
+ }
+
+ public static synchronized void setPatchedTypes(boolean value)
+ {
+ bPatchedTypes = value;
+ }
+
+ public static synchronized void setPatchedJava(boolean value)
+ {
+ bPatchedJava = value;
+ }
+
+ public static synchronized void setPatchedRDB(boolean value)
+ {
+ bPatchedRDB = value;
+ }
+
+ public static synchronized void setInstallStarted(boolean value)
+ {
+ bInstallStarted = value;
+ }
+
+ public static synchronized void setTypesPath(String path)
+ {
+ typesPath = path;
+ }
+
+ public static synchronized void setJavaPath(String path)
+ {
+ javaPath = path;
+ }
+
+ public static synchronized String getTypesPath()
+ {
+ return typesPath;
+ }
+
+ public static synchronized String getJavaPath()
+ {
+ return javaPath;
+ }
+
+ private javax.swing.JPanel navigation;
+ private javax.swing.JButton navBack;
+ private javax.swing.JButton navNext;
+ private javax.swing.JButton navCancel;
+ private javax.swing.JPanel screens;
+
+ private Version version = null;
+ private Final _final = null;
+ private IdeVersion ideversion = null;
+ private IdeFinal idefinal = null;
+ private IdeWelcome idewelcome = null;
+ private static ArrayList locations = null;
+
+ public static String VERSIONS = "VERSIONS";
+ public static String WELCOME = "WELCOME";
+ public static String FINAL = "FINAL";
+ public static String IDEVERSIONS = "IDEVERSIONS";
+ public static String IDEWELCOME = "IDEWELCOME";
+ public static String IDEFINAL = "IDEFINAL";
+
+ public static int DEFWIDTH = 480;
+ public static int DEFHEIGHT = 240;
+
+ private static String typesPath = null;
+ private static String javaPath = null;
+
+ public static boolean bNetworkInstall = false;
+ public static boolean bBindingsInstall = false;
+
+ private static boolean bPatchedTypes = false;
+ private static boolean bPatchedJava = false;
+ private static boolean bPatchedRDB = false;
+ private static boolean bInstallStarted = false;
+
+}// InstallWizard
diff --git a/scripting/workben/installer/InstallationEvent.java b/scripting/workben/installer/InstallationEvent.java
new file mode 100644
index 000000000000..d00dbe45a53e
--- /dev/null
+++ b/scripting/workben/installer/InstallationEvent.java
@@ -0,0 +1,22 @@
+package installer;
+
+public class InstallationEvent
+{
+ private Object source;
+ private String message;
+ InstallationEvent(Object source, String message)
+ {
+ this.source = source;
+ this.message = message;
+ }
+
+ public Object getSource()
+ {
+ return source;
+ }
+
+ public String getMessage()
+ {
+ return message;
+ }
+}
diff --git a/scripting/workben/installer/LogStream.java b/scripting/workben/installer/LogStream.java
new file mode 100644
index 000000000000..073c945579cb
--- /dev/null
+++ b/scripting/workben/installer/LogStream.java
@@ -0,0 +1,54 @@
+package installer;
+import java.io.PrintStream;
+import java.io.FileOutputStream;
+
+import java.util.Date;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+
+
+//import java.io.PrintWriter;
+public class LogStream extends PrintStream
+{
+ static final private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z: ");
+
+ private String getTimeStamp()
+ {
+ String timeStamp = formatter.format( new Date() );
+ return timeStamp;
+ }
+ public LogStream( String logFileName ) throws java.io.FileNotFoundException
+ {
+ super( new FileOutputStream( logFileName ) );
+ }
+ public void println(String x)
+ {
+ super.println( getTimeStamp() + x );
+ }
+ public static void main(String[] args)
+ {
+ if ( args.length > 0 )
+ {
+ try
+ {
+ LogStream log = new LogStream( args[0] );
+ System.setErr(log);
+ System.setOut(log);
+ System.out.println("Test from logger from out");
+ System.err.println("Test from logger from err");
+ System.out.println("finised test from out");
+ System.err.println("finised test from err");
+ }
+ catch( java.io.FileNotFoundException fe )
+ {
+ System.err.println("Error creating logStream: " + fe );
+ fe.printStackTrace();
+ }
+ }
+ else
+ {
+ System.err.println("specify log file java LogStream [logfile]");
+ System.exit(1);
+ }
+ }
+}
diff --git a/scripting/workben/installer/NavPanel.java b/scripting/workben/installer/NavPanel.java
new file mode 100644
index 000000000000..8c6cecc3042b
--- /dev/null
+++ b/scripting/workben/installer/NavPanel.java
@@ -0,0 +1,113 @@
+package installer;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
+public class NavPanel extends JPanel implements ActionListener {
+
+ NavPanel(InstallWizard wizard, boolean bBack, boolean bNext, boolean bCancel, String prev, String next) {
+ setBackground(Color.white);
+ setBorder(new javax.swing.border.EtchedBorder(javax.swing.border.EtchedBorder.LOWERED));
+ this.wizard = wizard;
+ this.next = next;
+ this.prev = prev;
+ navBack = new javax.swing.JButton("<< Back");
+ navNext = new javax.swing.JButton("Next >>");
+ navCancel = new javax.swing.JButton("Cancel");
+ setLayout(new GridBagLayout());
+
+ gridBagConstraints1 = new java.awt.GridBagConstraints();
+ gridBagConstraints1.insets = new java.awt.Insets(1, 1, 1, 1);
+ gridBagConstraints1.anchor = gridBagConstraints1.WEST;
+
+ gridBagConstraints2 = new java.awt.GridBagConstraints();
+ gridBagConstraints2.gridx = 2;
+ gridBagConstraints2.gridy = 0;
+
+ gridBagConstraints3 = new java.awt.GridBagConstraints();
+ gridBagConstraints3.gridx = 6;
+ gridBagConstraints3.gridy = 0;
+
+ navNext.setEnabled(bNext);
+ navBack.setEnabled(bBack);
+ navCancel.setEnabled(bCancel);
+ navNext.addActionListener(this);
+ navBack.addActionListener(this);
+ navCancel.addActionListener(this);
+ add(navBack, gridBagConstraints1);
+ add(navNext, gridBagConstraints2);
+ add(navCancel, gridBagConstraints3);
+ }
+
+ public void enableNext(boolean bEnable) {
+ navNext.setEnabled(bEnable);
+ }
+
+ public void enableBack(boolean bEnable) {
+ navBack.setEnabled(bEnable);
+ }
+
+ public void enableCancel(boolean bEnable) {
+ navCancel.setEnabled(bEnable);
+ }
+
+ public void enableIDE(boolean bEnable) {
+ ideDetected = bEnable;
+ }
+
+ public void actionPerformed(ActionEvent ev) {
+ if ((ev.getSource() == navNext) && (next.length() != 0)) {
+ wizard.show(next);
+ }
+ if ((ev.getSource() == navBack) && (prev.length() != 0)) {
+ wizard.show(prev);
+ }
+ if (ev.getSource() == navCancel) {
+ if( ideDetected ) {
+ wizard.show(InstallWizard.IDEWELCOME);
+ }
+ else {
+ wizard.exitForm(null);
+ }
+ enableIDE(false);
+ }
+ }
+
+ public void setNextListener(ActionListener listener) {
+ navNext.addActionListener(listener);
+ }
+
+ public void setBackListener(ActionListener listener) {
+ navBack.addActionListener(listener);
+ }
+
+ public void setCancelListener(ActionListener listener) {
+ navCancel.addActionListener(listener);
+ }
+
+ public void removeNextListener(ActionListener listener)
+ {
+ navNext.removeActionListener(listener);
+ }
+
+ public void removeBackListener(ActionListener listener)
+ {
+ navBack.removeActionListener(listener);
+ }
+
+ public void removeCancelListener(ActionListener listener)
+ {
+ navCancel.removeActionListener(listener);
+ }
+
+ public JButton navBack;
+ public JButton navNext;
+ public JButton navCancel;
+ private GridBagConstraints gridBagConstraints1;
+ private GridBagConstraints gridBagConstraints2;
+ private GridBagConstraints gridBagConstraints3;
+ private InstallWizard wizard;
+ private String next;
+ private String prev;
+ private boolean ideDetected = false;
+}
diff --git a/scripting/workben/installer/Navigation.java b/scripting/workben/installer/Navigation.java
new file mode 100644
index 000000000000..6cba1980a427
--- /dev/null
+++ b/scripting/workben/installer/Navigation.java
@@ -0,0 +1,58 @@
+package installer;
+
+/*
+ * Navigation.java
+ *
+ * Created on 04 July 2002, 15:10
+ */
+
+/**
+ *
+ * @author mike
+ */
+public class Navigation extends javax.swing.JPanel {
+
+ /** Creates new form Navigation */
+ public Navigation() {
+ initComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ private void initComponents() {//GEN-BEGIN:initComponents
+ navBack = new javax.swing.JButton();
+ navNext = new javax.swing.JButton();
+ navCancel = new javax.swing.JButton();
+
+ setLayout(new java.awt.GridBagLayout());
+ java.awt.GridBagConstraints gridBagConstraints1;
+
+ navBack.setText("<< Back");
+ gridBagConstraints1 = new java.awt.GridBagConstraints();
+ add(navBack, gridBagConstraints1);
+
+ navNext.setText("Next >>");
+ gridBagConstraints1 = new java.awt.GridBagConstraints();
+ gridBagConstraints1.gridx = 2;
+ gridBagConstraints1.gridy = 0;
+ add(navNext, gridBagConstraints1);
+
+ navCancel.setText("Cancel");
+ gridBagConstraints1 = new java.awt.GridBagConstraints();
+ gridBagConstraints1.gridx = 6;
+ gridBagConstraints1.gridy = 0;
+ add(navCancel, gridBagConstraints1);
+
+ }//GEN-END:initComponents
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton navBack;
+ private javax.swing.JButton navNext;
+ private javax.swing.JButton navCancel;
+ // End of variables declaration//GEN-END:variables
+
+}
diff --git a/scripting/workben/installer/ProtocolHandler.xcu b/scripting/workben/installer/ProtocolHandler.xcu
new file mode 100644
index 000000000000..c4dafd6e678f
--- /dev/null
+++ b/scripting/workben/installer/ProtocolHandler.xcu
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:node xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema" oor:name="ProtocolHandler" oor:package="org.openoffice.Office">
+ <node oor:name="HandlerSet">
+ <node oor:name="com.sun.star.comp.ScriptProtocolHandler" oor:op="replace">
+ <prop oor:name="Protocols" oor:type="oor:string-list">
+ <value>script:*</value>
+ </prop>
+ </node>
+ </node>
+</oor:node>
diff --git a/scripting/workben/installer/Register.java b/scripting/workben/installer/Register.java
new file mode 100644
index 000000000000..69557f59fe34
--- /dev/null
+++ b/scripting/workben/installer/Register.java
@@ -0,0 +1,144 @@
+package installer;
+
+import java.lang.String;
+import java.io.*;
+import javax.swing.*;
+public class Register{
+ private static String[] singletonDefParams = { "drafts.com.sun.star.script.framework.theScriptRuntimeForJava=drafts.com.sun.star.script.framework.ScriptRuntimeForJava",
+ "drafts.com.sun.star.script.framework.storage.theScriptStorageManager=drafts.com.sun.star.script.framework.storage.ScriptStorageManager",
+ "drafts.com.sun.star.script.framework.theScriptRuntimeManager=drafts.com.sun.star.script.framework.ScriptRuntimeManager"};
+
+
+ private static String quotedString ( String stringToQuote ) {
+ String doubleQuote = "\"";
+ String result = new String ( doubleQuote + stringToQuote + doubleQuote );
+ return result;
+ }
+ private static boolean regSingletons( String path, String progPath, String opSys, JLabel statusLabel ) {
+ try{
+ boolean goodResult = false;
+ String[] env = new String[1];
+ String regCmd = null;
+ ExecCmd command = new ExecCmd();
+ for ( int i=0; i<singletonDefParams.length; i++){
+ if ( opSys.indexOf( "Windows" ) == -1 ){
+ // Not windows
+ env[0] = "LD_LIBRARY_PATH=" + progPath;
+ command.exec( "chmod a+x " + progPath + "regsingleton", null );
+ regCmd = progPath + "regsingleton " + path + "user" + File.separator + "uno_packages" + File.separator + "cache" + File.separator + "services.rdb " + singletonDefParams[i];
+ goodResult = command.exec( regCmd, env );
+ }
+ else {
+ // Windows
+ regCmd = quotedString( progPath + "regsingleton.exe" ) + " " + quotedString( path + "user" + File.separator + "uno_packages" + File.separator + "cache" + File.separator + "services.rdb" ) + " " + quotedString( singletonDefParams[i] );
+ goodResult = command.exec( regCmd,null );
+ }
+ if ( !goodResult ){
+ System.out.println("Regsingleton cmd failed, cmd: " + regCmd );
+ statusLabel.setText("Regsingleton ScriptRuntimeForJava Failed, please view SFrameworkInstall.log");
+ return false;
+ }
+ }
+ }
+ catch ( Exception e ) {
+ String message = "\nError installing scripting package, please view SFrameworkInstall.log.";
+ System.out.println(message);
+ e.printStackTrace();
+ statusLabel.setText(message);
+ return false;
+ }
+ return true;
+
+
+ }
+ public static boolean register(String path, JLabel statusLabel) {
+ String[] packages = {"ooscriptframe.zip", "bshruntime.zip", "jsruntime.zip"};
+
+ try {
+ String s=null;
+ boolean goodResult = false;
+ String env[] = new String[1];
+ ExecCmd command = new ExecCmd();
+ boolean isWindows =
+ (System.getProperty("os.name").indexOf("Windows") != -1);
+
+ String progpath = path.concat("program" + File.separator);
+
+ statusLabel.setText("Registering Scripting Framework...");
+
+ // pkgchk Scripting Framework Components
+ statusLabel.setText("Registering Scripting Framework Components...");
+ System.out.println("Registering Scripting Framework Components...");
+
+ for (int i = 0; i < packages.length; i++) {
+ String cmd = "";
+
+ if (!isWindows) {
+ env[0]="LD_LIBRARY_PATH=" + progpath;
+
+ goodResult = command.exec("chmod a+x " + progpath + "pkgchk", null );
+
+ if ( goodResult ){
+ cmd = progpath + "pkgchk -s -f " + progpath + packages[i];
+
+ System.err.println(cmd);
+ goodResult = command.exec(cmd, env);
+ }
+ }
+ else {
+ cmd = "\"" + progpath + "pkgchk.exe\" -s -f \"" + progpath +
+ packages[i] + "\"";
+
+ System.err.println(cmd);
+ goodResult =command.exec(cmd,null);
+
+ }
+ if (!goodResult) {
+ System.err.println("\nPkgChk Failed");
+
+ if(!isWindows)
+ System.err.println("Command: " + cmd + "\n" + env[0]);
+ else
+ System.err.println("Command: \"" + cmd + "\"");
+
+ statusLabel.setText(
+ "PkgChk Failed, please view SFrameworkInstall.log");
+
+ return false;
+ }
+ }
+
+ // if ( !regSingletons( path, progpath, opSys, statusLabel ) )
+ // {
+ // return false;
+ // }
+ // updating ProtocolHandler
+ /* statusLabel.setText("Updating ProtocolHandler...");
+ if(!FileUpdater.updateProtocolHandler(path, statusLabel)) {
+ statusLabel.setText("Updating ProtocolHandler failed, please view SFrameworkInstall.log");
+ return false;
+ } */
+
+ // updating StarBasic libraries
+ statusLabel.setText("Updating StarBasic libraries...");
+ if(!FileUpdater.updateScriptXLC(path, statusLabel)) {
+ statusLabel.setText("Updating user/basic/script.xlc failed, please view SFrameworkInstall.log");
+ return false;
+ }
+ if(!FileUpdater.updateDialogXLC(path, statusLabel)) {
+ statusLabel.setText("Updating user/basic/dialog.xlc failed, please view SFrameworkInstall.log");
+ return false;
+ }
+
+ }
+ catch(Exception e){
+ String message = "\nError installing scripting package, please view SFrameworkInstall.log.";
+ System.out.println(message);
+ e.printStackTrace();
+ statusLabel.setText(message);
+ return false;
+ }
+ return true;
+ }// register
+
+}//Register
diff --git a/scripting/workben/installer/Scripting.BeanShell.xcu b/scripting/workben/installer/Scripting.BeanShell.xcu
new file mode 100644
index 000000000000..d763aa8ff7d9
--- /dev/null
+++ b/scripting/workben/installer/Scripting.BeanShell.xcu
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:node xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema" oor:name="Scripting" oor:package="org.openoffice.Office">
+ <node oor:name="ScriptRuntimes">
+ <node oor:name="BeanShell" oor:op="replace">
+ <prop oor:name="SupportedFileExtensions">
+ <value xml:lang="x-no-translate">bsh</value>
+ <value xml:lang="en-US">bsh</value>
+ </prop>
+ </node>
+ </node>
+</oor:node>
diff --git a/scripting/workben/installer/Scripting.JavaScript.xcu b/scripting/workben/installer/Scripting.JavaScript.xcu
new file mode 100755
index 000000000000..562189acc93d
--- /dev/null
+++ b/scripting/workben/installer/Scripting.JavaScript.xcu
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:node xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema" oor:name="Scripting" oor:package="org.openoffice.Office">
+ <node oor:name="ScriptRuntimes">
+ <node oor:name="JavaScript" oor:op="replace">
+ <prop oor:name="SupportedFileExtensions">
+ <value xml:lang="x-no-translate">js</value>
+ <value xml:lang="en-US">js</value>
+ </prop>
+ </node>
+ </node>
+</oor:node>
diff --git a/scripting/workben/installer/Scripting.xcs b/scripting/workben/installer/Scripting.xcs
new file mode 100644
index 000000000000..fcb6b99e7c1a
--- /dev/null
+++ b/scripting/workben/installer/Scripting.xcs
@@ -0,0 +1,60 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--***********************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: Scripting.xcs,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************ -->
+<!DOCTYPE oor:component-schema SYSTEM "../../../../component-schema.dtd">
+<oor:component-schema xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" oor:name="Scripting" oor:package="org.openoffice.Office" xml:lang="en-US">
+ <info>
+ <author>DF</author>
+ <desc xml:lang="x-no-translate"></desc>
+ <desc xml:lang="en-US">Contains the various settings needed by the Scripting Framework and its runtimes.</desc>
+ </info>
+ <templates>
+ <group oor:name="RuntimeNode">
+ <info>
+ <desc xml:lang="x-no-translate"></desc>
+ <desc xml:lang="en-US">Specifies the runtimes available to the Scriptying Framework.</desc>
+ </info>
+ <prop oor:name="SupportedFileExtensions" oor:type="oor:string-list">
+ <info>
+ <desc xml:lang="x-no-translate"></desc>
+ <desc xml:lang="en-US">Lists the file extensions that are recognized by this runtime.</desc>
+ </info>
+ </prop>
+ </group>
+ </templates>
+ <component>
+ <set oor:name="ScriptRuntimes" oor:node-type="RuntimeNode">
+ <info>
+ <desc xml:lang="x-no-translate"></desc>
+ <desc xml:lang="en-US">Lists the registered Scripting Framework runtimes.</desc>
+ </info>
+ </set>
+ </component>
+</oor:component-schema>
diff --git a/scripting/workben/installer/Version.java b/scripting/workben/installer/Version.java
new file mode 100644
index 000000000000..56e78024769e
--- /dev/null
+++ b/scripting/workben/installer/Version.java
@@ -0,0 +1,339 @@
+package installer;
+
+/*
+ * Welcome.java
+ *
+ * Created on 04 July 2002, 15:43
+ */
+
+/**
+ *
+ * @author mike
+ */
+
+import java.awt.*;
+import java.awt.event.*;
+import java.io.*;
+import java.util.*;
+import javax.swing.*;
+import javax.swing.event.*;
+import javax.swing.table.*;
+import javax.swing.SwingUtilities.*;
+
+public class Version extends javax.swing.JPanel implements ActionListener, TableModelListener {
+
+ /** Creates new form Welcome */
+ public Version(InstallWizard wizard) {
+ this.wizard=wizard;
+ setBackground(Color.white);
+ initComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ private void initComponents() {
+ Properties props = null;
+ JPanel versionPanel = new JPanel();
+ setLayout(new BorderLayout());
+
+ System.out.println("Initialising versions");
+
+ File fileVersions = null;
+ try
+ {
+ fileVersions = InstUtil.buildSversionLocation();
+ }
+ catch(IOException eFnF)
+ {
+ System.err.println("Cannot find sversion.ini/.sversionrc");
+ JOptionPane.showMessageDialog(this, eFnF.getMessage(), "File not Found", JOptionPane.ERROR_MESSAGE);
+ wizard.exitForm(null);
+ }
+
+ try {
+ props = InstUtil.getOfficeVersions(fileVersions);
+ }
+ catch (IOException eIO) {
+ //Message about no installed versions found
+ System.err.println("Failed to parse SVERSION");
+ JOptionPane.showMessageDialog(this, "There was a problem reading from the Office settings file.", "Parse Error", JOptionPane.ERROR_MESSAGE);
+ wizard.exitForm(null);
+ }
+
+ tableModel = new MyTableModel(props, versions);
+ if (tableModel.getRowCount() == 0)
+ {
+ JOptionPane.showMessageDialog(this, "No compatible versions of Office were found.", "Invalid versions", JOptionPane.ERROR_MESSAGE);
+ wizard.exitForm(null);
+ }
+
+ tableModel.addTableModelListener(this);
+ JTable tableVersions = new JTable(tableModel) {
+ public String getToolTipText(MouseEvent event)
+ {
+ int col = columnAtPoint( event.getPoint() );
+ if (col != 2)
+ return null;
+
+ int row = rowAtPoint( event.getPoint() );
+ Object o = getValueAt(row, col);
+
+ if (o == null)
+ return null;
+
+ if (o.toString().equals(""))
+ return null;
+
+ return o.toString();
+ }
+
+ public Point getToolTipLocation(MouseEvent event)
+ {
+ int col = columnAtPoint( event.getPoint() );
+ if (col != 2)
+ return null;
+
+ int row = rowAtPoint( event.getPoint() );
+ Object o = getValueAt(row,col);
+
+ if (o == null)
+ return null;
+
+ if (o.toString().equals(""))
+ return null;
+
+ Point pt = getCellRect(row, col, true).getLocation();
+ pt.translate(-1,-2);
+ return pt;
+ }
+ };
+
+ JScrollPane scroll = new JScrollPane(tableVersions);
+
+ tableVersions.setPreferredSize(
+ new Dimension(InstallWizard.DEFWIDTH,InstallWizard.DEFHEIGHT));
+
+ tableVersions.setRowSelectionAllowed(false);
+ tableVersions.setColumnSelectionAllowed(false);
+ tableVersions.setCellSelectionEnabled(false);
+
+ initColumnSizes(tableVersions, tableModel);
+ versionPanel.add(scroll);
+
+ JTextArea area = new JTextArea("Please select the Office version you wish to Update");
+ area.setLineWrap(true);
+ area.setEditable(false);
+ add(area, BorderLayout.NORTH);
+ add(versionPanel, BorderLayout.CENTER);
+ //nav = new NavPanel(wizard, true, false, true, InstallWizard.WELCOME, InstallWizard.FINAL);
+ nav = new NavPanel(wizard, true, false, true, InstallWizard.WELCOME, InstallWizard.FINAL);
+ nav.setNextListener(this);
+ add(nav, BorderLayout.SOUTH);
+
+ }// initComponents
+
+ private void initColumnSizes(JTable table, MyTableModel model) {
+ TableColumn column = null;
+ Component comp = null;
+ int headerWidth = 0;
+ int cellWidth = 0;
+ int preferredWidth = 0;
+ int totalWidth = 0;
+ Object[] longValues = model.longValues;
+
+ for (int i = 0; i < 3; i++) {
+ column = table.getColumnModel().getColumn(i);
+
+ try {
+ comp = column.getHeaderRenderer().
+ getTableCellRendererComponent(
+ null, column.getHeaderValue(),
+ false, false, 0, 0);
+ headerWidth = comp.getPreferredSize().width;
+ } catch (NullPointerException e) {
+ // System.err.println("Null pointer exception!");
+ // System.err.println(" getHeaderRenderer returns null in 1.3.");
+ // System.err.println(" The replacement is getDefaultRenderer.");
+ }
+
+ // need to replace spaces in String before getting preferred width
+ if (longValues[i] instanceof String) {
+ longValues[i] = ((String)longValues[i]).replace(' ', '_');
+ }
+
+ System.out.println("longValues: " + longValues[i]);
+ comp = table.getDefaultRenderer(model.getColumnClass(i)).
+ getTableCellRendererComponent(
+ table, longValues[i],
+ false, false, 0, i);
+ cellWidth = comp.getPreferredSize().width;
+
+ preferredWidth = Math.max(headerWidth, cellWidth);
+
+ if (false) {
+ System.out.println("Initializing width of column "
+ + i + ". "
+ + "preferredWidth = " + preferredWidth
+ + "; totalWidth = " + totalWidth
+ + "; leftWidth = " + (InstallWizard.DEFWIDTH - totalWidth));
+ }
+
+ //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
+ if (i == 2) {
+ if (preferredWidth > InstallWizard.DEFWIDTH - totalWidth)
+ column.setPreferredWidth(InstallWizard.DEFWIDTH - totalWidth);
+ else
+ column.setPreferredWidth(preferredWidth);
+ }
+ else {
+ column.setMinWidth(preferredWidth);
+ totalWidth += preferredWidth;
+ }
+ }
+ }
+
+ public java.awt.Dimension getPreferredSize() {
+ return new java.awt.Dimension(320, 280);
+ }
+
+
+ public void actionPerformed(ActionEvent ev) {
+ wizard.clearLocations();
+ int len = tableModel.data.size();
+ for (int i = 0; i < len; i++) {
+ ArrayList list = (ArrayList)tableModel.data.get(i);
+ if (((Boolean)list.get(0)).booleanValue() == true)
+ wizard.storeLocation((String)list.get(2));
+ }
+
+ //System.out.println(wizard.getLocations());
+ }
+
+
+ public void tableChanged(TableModelEvent e) {
+ if (tableModel.isAnySelected()) {
+ nav.enableNext(true);
+ }
+ else {
+ nav.enableNext(false);
+ }
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JTextField jTextField2;
+ private InstallWizard wizard;
+ private MyTableModel tableModel;
+ private NavPanel nav;
+ //private static final String [] versions = {"StarOffice 6.0", "OpenOffice.org 1.0","OpenOffice.org 1.0.1","OpenOffice.org 642","OpenOffice.org 643","StarOffice 6.1"};
+ //private static final String [] versions = {"OpenOffice.org 643"};
+ //private static final String [] versions = {"OpenOffice.org 643", "StarOffice 6.1"};
+ private static final String [] versions = {"StarOffice 6.1", "OpenOffice.org 1.1Beta", "OpenOffice.org 644", "OpenOffice.org 1.1"};
+ // End of variables declaration//GEN-END:variables
+
+}
+
+class MyTableModel extends AbstractTableModel {
+ ArrayList data;
+ String colNames[] = {"", "Name", "Location"};
+ Object[] longValues = new Object[] {Boolean.TRUE, "Name", "Location"};
+
+ MyTableModel (Properties properties, String [] validVersions) {
+ data = new ArrayList();
+ boolean isWindows =
+ (System.getProperty("os.name").indexOf("Windows") != -1);
+ int len = validVersions.length;
+ for (Enumeration e = properties.propertyNames(); e.hasMoreElements() ;) {
+ String key = (String)e.nextElement();
+ String path = null;
+
+ if ( !( key.startsWith("#") ) &&
+ ( path = properties.getProperty(key)) != null) {
+ String pkgChkPath = path + File.separator + "program" + File.separator;
+ if ( isWindows )
+ {
+ pkgChkPath += "pkgchk.exe";
+ }
+ else
+ {
+ pkgChkPath += "pkgchk";
+ }
+ File pkgChk = new File( pkgChkPath );
+ if ( pkgChk.exists() )
+ {
+ ArrayList row = new ArrayList();
+ row.add(0, new Boolean(false));
+
+ row.add(1, key);
+ if (key.length() > ((String)longValues[1]).length()) {
+ longValues[1] = key;
+ }
+
+ row.add(2, path);
+ if (path.length() > ((String)longValues[2]).length()) {
+ longValues[2] = path;
+ }
+
+ data.add(row);
+ }
+ }
+ }
+ }// MyTableModel
+
+ public int getColumnCount() {
+ return 3;
+ }
+
+ public int getRowCount() {
+ return data.size();
+ }
+
+ public String getColumnName(int col) {
+ return colNames[col];
+ }
+
+ public Object getValueAt(int row, int col) {
+ if (row < 0 || row > getRowCount() ||
+ col < 0 || col > getColumnCount())
+ return null;
+
+ ArrayList aRow = (ArrayList)data.get(row);
+ return aRow.get(col);
+ }
+
+ public Class getColumnClass(int c) {
+ return getValueAt(0, c).getClass();
+ }
+
+ public boolean isCellEditable(int row, int col) {
+ if (col == 0) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public void setValueAt(Object value, int row, int col) {
+ ArrayList aRow = (ArrayList)data.get(row);
+ aRow.set(col, value);
+ fireTableCellUpdated(row, col);
+ }
+
+ String [] getSelected() {
+ return null;
+ }
+
+ public boolean isAnySelected() {
+ Iterator iter = data.iterator();
+ while (iter.hasNext()) {
+ ArrayList row = (ArrayList)iter.next();
+ if (((Boolean)row.get(0)).booleanValue() == true) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+}
diff --git a/scripting/workben/installer/Welcome.java b/scripting/workben/installer/Welcome.java
new file mode 100644
index 000000000000..e73cdca87728
--- /dev/null
+++ b/scripting/workben/installer/Welcome.java
@@ -0,0 +1,156 @@
+package installer;
+
+/*
+ * Welcome.java
+ *
+ * Created on 04 July 2002, 15:43
+ */
+
+/**
+ *
+ * @author mike
+ */
+import java.awt.event.*;
+import javax.swing.*;
+import java.io.*;
+import java.net.*;
+import java.util.Properties;
+
+public class Welcome extends javax.swing.JPanel implements ActionListener {
+
+ /** Creates new form Welcome */
+ public Welcome(InstallWizard wizard) {
+ this.wizard = wizard;
+ setBorder(new javax.swing.border.EtchedBorder(javax.swing.border.EtchedBorder.RAISED));
+ initComponents();
+ }
+
+ /** This method is called from within the constructor to
+ * initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is
+ * always regenerated by the Form Editor.
+ */
+ private void initComponents() {//GEN-BEGIN:initComponents
+ welcomePanel = new javax.swing.JPanel();
+ area = new javax.swing.JTextArea();
+ nextButtonEnable = true;
+
+ setLayout(new java.awt.BorderLayout());
+
+ welcomePanel.setLayout(new java.awt.BorderLayout());
+ area.setEditable(false);
+ area.setLineWrap(true);
+
+ String message = "\n\tOffice Scripting Framework Version 0.3" +
+ "\n\n\n\tPlease ensure that you have exited from Office";
+
+ /* String userDir = (String) System.getProperty( "user.dir" );
+ boolean isValid = validateCurrentUserDir(userDir);
+ if( !isValid ) {
+ nextButtonEnable = false;
+ message = "Please run Installer from the program directory in a valid Office installation";
+ setUpWelcomePanel(message);
+ return;
+ }
+
+ int programPosition = userDir.lastIndexOf("program");
+ String offInstallPth = null;
+ offInstallPth = userDir.substring( 0, programPosition );
+
+ wizard.storeLocation(offInstallPth); */
+ setUpWelcomePanel(message);
+
+ }//GEN-END:initComponents
+
+ private void setUpWelcomePanel(String message){
+ area.setText( message );
+ welcomePanel.add(area, java.awt.BorderLayout.CENTER);
+ add(welcomePanel, java.awt.BorderLayout.CENTER);
+ NavPanel nav = new NavPanel(wizard, false, nextButtonEnable, true, "", InstallWizard.VERSIONS);
+ nav.setNextListener(this);
+ add(nav, java.awt.BorderLayout.SOUTH);
+
+ //Banner br = new Banner();
+ //add(br, java.awt.BorderLayout.WEST);
+ }
+
+
+ private boolean validateCurrentUserDir(String userDir){
+
+
+
+ Properties props = null;
+
+ File fileVersions = null;
+ try
+ {
+ fileVersions = InstUtil.buildSversionLocation();
+ }
+ catch(IOException eFnF)
+ {
+ System.err.println("Cannot find sversion.ini/.sversionrc");
+ JOptionPane.showMessageDialog(this, eFnF.getMessage(), "File not Found", JOptionPane.ERROR_MESSAGE);
+ wizard.exitForm(null);
+ }
+
+ try {
+ props = InstUtil.getOfficeVersions(fileVersions);
+ }
+ catch (IOException eIO) {
+ //Message about no installed versions found
+ System.err.println("Failed to parse SVERSION");
+ JOptionPane.showMessageDialog(this, "There was a problem reading from the Office settings file.", "Parse Error", JOptionPane.ERROR_MESSAGE);
+ wizard.exitForm(null);
+ }
+
+
+ boolean versionMatch = false;
+
+ for( int i = 0; i < versions.length; i++ ) {
+ String key = versions[i];
+ String progPath = ( String )props.getProperty( key );
+ if ( progPath != null ){
+ progPath = progPath + File.separator + "program";
+
+ File tmpFile = new File(progPath + File.separator + "oostubversion.txt");
+ try{
+ tmpFile.createNewFile();
+
+ if( new File(userDir + File.separator + "oostubversion.txt").exists())
+ {
+ versionMatch = true;
+ break;
+ }
+ }
+ catch( IOException e)
+ {
+ // Fail silently
+ }
+ tmpFile.delete();
+ }
+ }
+ return versionMatch;
+ }
+
+
+
+ public java.awt.Dimension getPreferredSize() {
+ return new java.awt.Dimension(InstallWizard.DEFWIDTH, InstallWizard.DEFHEIGHT);
+ }
+
+ public void actionPerformed(ActionEvent ev)
+ {
+ //Perform next actions here...
+ }
+
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JPanel welcomePanel;
+ private javax.swing.JTextArea area;
+ private InstallWizard wizard;
+ //private static final String [] versions = {"OpenOffice.org 643", "StarOffice 6.1"};
+ private static final String [] versions = { "StarOffice 6.1" };
+ private boolean nextButtonEnable = true;
+
+ // End of variables declaration//GEN-END:variables
+}
diff --git a/scripting/workben/installer/XmlUpdater.java b/scripting/workben/installer/XmlUpdater.java
new file mode 100644
index 000000000000..a0b79c2ecbb8
--- /dev/null
+++ b/scripting/workben/installer/XmlUpdater.java
@@ -0,0 +1,427 @@
+package installer;
+
+import java.io.*;
+import java.util.*;
+import java.util.jar.*;
+import java.net.URL;
+import java.net.JarURLConnection;
+import javax.swing.*;
+
+/**
+ *
+ *
+ * @author Aidan Butler
+ */
+public class XmlUpdater extends Thread {
+
+ private String classesPath = null;
+ private String jarfilename;
+ private String installPath;
+ private boolean netInstall;
+ private boolean bindingsInstall;
+
+ private JLabel statusLabel;
+
+ private Vector listeners;
+ private Thread internalThread;
+ private boolean threadSuspended;
+ private JProgressBar progressBar;
+
+ private final String[] bakFiles =
+ {
+ "writermenubar.xml",
+ "writerkeybinding.xml",
+ "calcmenubar.xml",
+ "calckeybinding.xml",
+ "impressmenubar.xml",
+ "impresskeybinding.xml",
+ "drawmenubar.xml",
+ "drawkeybinding.xml",
+ "eventbindings.xml",
+ "META-INF" + File.separator + "manifest.xml"
+ };
+
+ private final String[] dirs =
+ {
+ "java" + File.separator + "Highlight",
+ "java" + File.separator + "MemoryUsage",
+ "java" + File.separator + "ScriptFrmwrkHelper",
+ "java" + File.separator + "debugger",
+ "java" + File.separator + "debugger" + File.separator + "rhino",
+ "beanshell" + File.separator + "InteractiveBeanShell",
+ "beanshell" + File.separator + "Highlight",
+ "beanshell" + File.separator + "MemoryUsage",
+ "javascript" + File.separator + "ExportSheetsToHTML"
+ };
+
+ private final String[] names =
+ {
+ "java/Highlight/HighlightUtil.java",
+ "java/Highlight/HighlightText.java",
+ "java/Highlight/Highlight.jar",
+ "java/Highlight/parcel-descriptor.xml",
+ "java/MemoryUsage/MemoryUsage.java",
+ "java/MemoryUsage/MemoryUsage.class",
+ "java/MemoryUsage/parcel-descriptor.xml",
+ "java/MemoryUsage/ExampleSpreadSheet.sxc",
+ "java/ScriptFrmwrkHelper/parcel-descriptor.xml",
+ "java/ScriptFrmwrkHelper/ScriptFrmwrkHelper.java",
+ "java/ScriptFrmwrkHelper/ScriptFrmwrkHelper.class",
+ "java/ScriptFrmwrkHelper/ScriptFrmwrkHelper.jar",
+ "java/debugger/debugger.jar",
+ "java/debugger/OOBeanShellDebugger.java",
+ "java/debugger/OOScriptDebugger.java",
+ "java/debugger/DebugRunner.java",
+ "java/debugger/OORhinoDebugger.java",
+ "java/debugger/parcel-descriptor.xml",
+ "java/debugger/rhino/Main.java",
+ "beanshell/InteractiveBeanShell/parcel-descriptor.xml",
+ "beanshell/InteractiveBeanShell/interactive.bsh",
+ "beanshell/Highlight/parcel-descriptor.xml",
+ "beanshell/Highlight/highlighter.bsh",
+ "beanshell/MemoryUsage/parcel-descriptor.xml",
+ "beanshell/MemoryUsage/memusage.bsh",
+ "javascript/ExportSheetsToHTML/parcel-descriptor.xml",
+ "javascript/ExportSheetsToHTML/exportsheetstohtml.js"
+ };
+
+
+ public XmlUpdater(String installPath, JLabel statusLabel,JProgressBar pBar, boolean netInstall, boolean bindingsInstall) {
+ this.installPath = installPath;
+ this.statusLabel = statusLabel;
+ this.netInstall = netInstall;
+ this.bindingsInstall = bindingsInstall;
+ listeners = new Vector();
+ threadSuspended = false;
+ progressBar=pBar;
+ progressBar.setStringPainted(true);
+ }// XmlUpdater
+
+
+ public boolean checkStop()
+ {
+ if (internalThread == Thread.currentThread())
+ return false;
+ return true;
+ }// checkStop
+
+
+ public void checkSuspend()
+ {
+ if (threadSuspended) {
+ synchronized(this) {
+ while (threadSuspended) {
+ try {
+ wait();
+ } catch (InterruptedException eInt) {
+ //...
+ }
+ }
+ }
+ }
+ }// checkSuspend
+
+
+ public void setSuspend()
+ {
+ threadSuspended = true;
+ }// setSuspend
+
+
+ public void setResume()
+ {
+ threadSuspended = false;
+ notify();
+ }// setResume
+
+
+ public void setStop()
+ {
+ internalThread = null;
+ }// setStop
+
+
+ public void run() {
+
+ InputStream istream;
+ //InputSource isource;
+ //DocumentBuilderFactory builderFactory;
+ //DocumentBuilder builder = null;
+ URL url;
+ String fileName = null;
+
+ internalThread = Thread.currentThread();
+
+ //System.out.println("\n\n\n\nFileName: "+installPath);
+ classesPath= installPath.concat(File.separator+"program"+File.separator+"classes"+File.separator);
+ String opSys =System.getProperty("os.name");
+ //System.out.println("\n System "+opSys);
+
+ String progpath=installPath;
+ progpath= progpath.concat(File.separator+"program"+File.separator);
+ //System.out.println("Office progpath" + progpath );
+ //System.out.println("\nModifying Installation "+installPath);
+
+ String starBasicPath=installPath;
+ starBasicPath= starBasicPath.concat(File.separator+"share"+File.separator+"basic"+File.separator+"ScriptBindingLibrary"+File.separator);
+ //System.out.println( "Office StarBasic path: " + starBasicPath );
+
+ String regSchemaOfficePath=installPath;
+ regSchemaOfficePath= regSchemaOfficePath.concat(File.separator+"share"+File.separator+"registry"+File.separator+"schema"+File.separator+"org"+File.separator+"openoffice"+File.separator+"Office"+File.separator);
+ //System.out.println( "Office schema path: " + regSchemaOfficePath );
+
+ // Get the NetBeans installation
+ //String netbeansPath=
+
+ progressBar.setString("Unzipping Required Files");
+ ZipData zd = new ZipData("SFrameworkInstall.jar");
+
+
+ if( (!netInstall) || bindingsInstall) {
+ String configPath=installPath;
+ configPath= configPath.concat(File.separator+"user"+File.separator+"config"+File.separator+"soffice.cfg"+File.separator);
+ //System.out.println( "Office configuration path: " + configPath );
+ String manifestPath=configPath + "META-INF" + File.separator;
+
+ //Adding <Office>/user/config/soffice.cfg/
+ File configDir = new File( configPath );
+ if( !configDir.isDirectory() ) {
+ if( !configDir.mkdir() ) {
+ System.out.println( "creating " + configDir + "directory failed");
+ }
+ else {
+ System.out.println( configDir + "directory created");
+ }
+ }
+ else
+ System.out.println( "soffice.cfg exists" );
+
+ File manifestDir = new File( manifestPath );
+ if( !manifestDir.isDirectory() ) {
+ if( !manifestDir.mkdir() ) {
+ System.out.println( "creating " + manifestPath + "directory failed");
+ }
+ else {
+ System.out.println( manifestPath + " directory created");
+ }
+ }
+ else
+ System.out.println( manifestPath + " exists" );
+
+ // Backup the confguration files in
+ // <office>/user/config/soffice.cfg/
+ // If they already exist.
+
+ for( int i=0; i < bakFiles.length; i++ )
+ {
+ String pathNameBak = configPath + bakFiles[i];
+ File origFile = new File( pathNameBak );
+ if( origFile.exists() )
+ {
+ System.out.println( "Attempting to backup " + pathNameBak + " to " + pathNameBak + ".bak" );
+ if(! origFile.renameTo( new File( pathNameBak + ".bak" ) ) )
+ {
+ System.out.println( "Failed to backup " + pathNameBak + " to " + pathNameBak + ".bak" );
+ }
+ }
+ }
+
+ // Adding Office configuration files
+ if (!zd.extractEntry("bindingdialog/writermenubar.xml",configPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/writerkeybinding.xml",configPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/calcmenubar.xml",configPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/calckeybinding.xml",configPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/impressmenubar.xml",configPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/impresskeybinding.xml",configPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/drawmenubar.xml",configPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/drawkeybinding.xml",configPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/eventbindings.xml",configPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/manifest.xml",manifestPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ }
+
+ if(!bindingsInstall) {
+ // Adding new directories to Office
+ // Adding <Office>/user/basic/ScriptBindingLibrary/
+ File scriptBindingLib = new File( starBasicPath );
+ if( !scriptBindingLib.isDirectory() ) {
+ if( !scriptBindingLib.mkdir() ) {
+ System.out.println( "ScriptBindingLibrary failed");
+ }
+ else {
+ System.out.println( "ScriptBindingLibrary directory created");
+ }
+ }
+ else
+ System.out.println( "ScriptBindingLibrary exists" );
+
+ // Adding Scripting Framework and tools
+ if (!zd.extractEntry("sframework/ooscriptframe.zip",progpath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+
+ if (!zd.extractEntry("sframework/bshruntime.zip",progpath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+
+ if (!zd.extractEntry("sframework/jsruntime.zip",progpath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+
+ if (!zd.extractEntry("schema/Scripting.xcs",regSchemaOfficePath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+
+ //--------------------------------
+
+ progressBar.setString("Registering Scripting Framework");
+ progressBar.setValue(3);
+ if(!Register.register(installPath+File.separator, statusLabel) ) {
+ onInstallComplete();
+ return;
+ }
+ progressBar.setValue(5);
+
+ String path = installPath + File.separator +
+ "share" + File.separator + "Scripts" + File.separator;
+
+ for (int i = 0; i < dirs.length; i++) {
+ File dir = new File(path + dirs[i]);
+
+ if (!dir.exists()) {
+ if (!dir.mkdirs()) {
+ System.err.println("Error making dir: " +
+ dir.getAbsolutePath());
+ onInstallComplete();
+ return;
+ }
+ }
+ }
+
+ for (int i = 0; i < names.length; i++) {
+ String source = "/examples/" + names[i];
+ String dest = path + names[i].replace('/', File.separatorChar);
+
+ if (!zd.extractEntry(source, dest, statusLabel)) {
+ onInstallComplete();
+ return;
+ }
+ }
+
+
+ // Adding binding dialog
+ if (!zd.extractEntry("bindingdialog/ScriptBinding.xba",starBasicPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/MenuBinding.xdl",starBasicPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/KeyBinding.xdl",starBasicPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/EventsBinding.xdl",starBasicPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/HelpBinding.xdl",starBasicPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/EditDebug.xdl",starBasicPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/dialog.xlb",starBasicPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ if (!zd.extractEntry("bindingdialog/script.xlb",starBasicPath, statusLabel))
+ {
+ onInstallComplete();
+ return;
+ }
+ }
+
+
+ statusLabel.setText("Installation Complete");
+ progressBar.setString("Installation Complete");
+ progressBar.setValue(10);
+ onInstallComplete();
+
+ }// run
+
+
+ public void addInstallListener(InstallListener listener)
+ {
+ listeners.addElement(listener);
+ }// addInstallListener
+
+
+ private void onInstallComplete()
+ {
+ Enumeration e = listeners.elements();
+ while (e.hasMoreElements())
+ {
+ InstallListener listener = (InstallListener)e.nextElement();
+ listener.installationComplete(null);
+ }
+ }// onInstallComplete
+
+}// XmlUpdater class
diff --git a/scripting/workben/installer/ZipData.java b/scripting/workben/installer/ZipData.java
new file mode 100644
index 000000000000..301d2ef58b64
--- /dev/null
+++ b/scripting/workben/installer/ZipData.java
@@ -0,0 +1,103 @@
+package installer;
+
+import java.io.*;
+import java.util.*;
+import java.util.zip.*;
+import java.awt.*;
+import java.awt.event.*;
+import javax.swing.*;
+
+public class ZipData
+{
+ public ZipData(String file) {
+ }
+
+ public boolean extractEntry(String entry, String destination,
+ JLabel statusLabel) {
+
+ OutputStream out = null;
+ InputStream in = null;
+
+ System.out.println("Copying: " + entry);
+ System.out.println("To: " + destination);
+
+ if (statusLabel != null) {
+ statusLabel.setText("Copying " + entry);
+ }
+
+ String entryName;
+ if (entry.lastIndexOf("/") != -1) {
+ entryName = entry.substring(entry.lastIndexOf("/") + 1);
+ }
+ else {
+ entryName = entry;
+ }
+
+ String destName;
+ if (destination.lastIndexOf(File.separator) != -1) {
+ destName = destination.substring(destination.lastIndexOf(File.separator) + 1);
+ }
+ else {
+ destName = destination;
+ }
+
+ if (!destName.equals(entryName))
+ destination = destination.concat(entryName);
+
+ System.out.println("Unzipping " + entry + " to " + destination);
+
+ try {
+ out = new FileOutputStream(destination);
+ }
+ catch (IOException ioe) {
+ System.err.println("Error opening " + destination +
+ ": " + ioe.getMessage());
+
+ if (statusLabel != null)
+ statusLabel.setText("Error opening" + destination +
+ "see SFramework.log for more information");
+
+ return false;
+ }
+
+ if (entry.startsWith("/") == false)
+ entry = "/" + entry;
+
+ in = this.getClass().getResourceAsStream(entry);
+ if (in == null) {
+ System.err.println("File " + entry + " not found in jar file");
+
+ if (statusLabel != null)
+ statusLabel.setText("Failed extracting " + entry +
+ "see SFramework.log for more information");
+
+ return false;
+ }
+
+ try {
+ byte[] bytes = new byte[1024];
+ int len;
+
+ while ((len = in.read(bytes)) != -1)
+ out.write(bytes, 0, len);
+ }
+ catch (IOException ioe) {
+ System.err.println("Error writing " + destination + ": " +
+ ioe.getMessage());
+
+ if (statusLabel != null)
+ statusLabel.setText("Failed writing " + destination +
+ "see SFramework.log for more information");
+ return false;
+ }
+ finally {
+ try {
+ in.close();
+ out.close();
+ }
+ catch (IOException ioe) {
+ }
+ }
+ return true;
+ }
+}
diff --git a/scripting/workben/installer/sidebar.jpg b/scripting/workben/installer/sidebar.jpg
new file mode 100644
index 000000000000..c2b366f74e76
--- /dev/null
+++ b/scripting/workben/installer/sidebar.jpg
Binary files differ
diff --git a/scripting/workben/makefile.mk b/scripting/workben/makefile.mk
new file mode 100755
index 000000000000..9c3e1aa0e4b7
--- /dev/null
+++ b/scripting/workben/makefile.mk
@@ -0,0 +1,39 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.3 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+PRJ=..
+PRJNAME=scriptinginstaller
+TARGET=scriptinginstaller
+
+.INCLUDE : ant.mk
+
+ALLTAR : ANTBUILD
+
diff --git a/scripting/workben/mod/_scripting/Dispatch.java b/scripting/workben/mod/_scripting/Dispatch.java
new file mode 100644
index 000000000000..66bd7d34c0bf
--- /dev/null
+++ b/scripting/workben/mod/_scripting/Dispatch.java
@@ -0,0 +1,111 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: Dispatch.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package mod._scripting;
+
+import java.net.URLEncoder;
+import java.io.PrintWriter;
+
+import lib.StatusException;
+import lib.TestCase;
+import lib.TestEnvironment;
+import lib.TestParameters;
+
+import util.utils;
+import util.SOfficeFactory;
+
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.lang.XComponent;
+
+import com.sun.star.uno.XInterface;
+import com.sun.star.uno.UnoRuntime;
+
+import com.sun.star.frame.XModel;
+import com.sun.star.frame.XFrame;
+import com.sun.star.frame.XDesktop;
+
+
+import com.sun.star.util.URL;
+import com.sun.star.util.XURLTransformer;
+
+
+
+public class Dispatch extends TestCase {
+ //private String scriptURL = "script://MemoryUtils.MemUsage";
+ private String scriptURL = "script://HighlightText.showForm";
+ public void initialize( TestParameters tParam, PrintWriter log ) {
+ }
+
+ public synchronized TestEnvironment createTestEnvironment(
+ TestParameters tParam, PrintWriter log ) throws StatusException {
+ log.println("creating test environment");
+ XInterface oObj = null;
+ URL dispatchURL = null;
+ try {
+
+ XMultiServiceFactory xMSF = tParam.getMSF();
+ SOfficeFactory SOF = null;
+ SOF = SOfficeFactory.getFactory( xMSF );
+ String docPath = util.utils.getFullTestURL( "ExampleSpreadSheetLatest.sxc" );
+ XComponent doc = SOF.loadDocument( docPath );
+ XModel model = ( XModel ) UnoRuntime.queryInterface( XModel.class,
+ doc );
+ XFrame frame = model.getCurrentController().getFrame();
+ oObj = ( XInterface )xMSF.createInstanceWithArguments( "com.sun.star.comp.ScriptProtocolHandler", new Object[] { frame } );
+
+ XURLTransformer xParser=(XURLTransformer)
+ UnoRuntime.queryInterface(XURLTransformer.class,
+ tParam.getMSF().createInstance
+ ("com.sun.star.util.URLTransformer"));
+ // Because it's an in/out parameter we must use an array of
+ // URL objects.
+ URL[] aParseURL = new URL[1];
+ aParseURL[0] = new URL();
+ aParseURL[0].Complete = scriptURL;
+ xParser.parseStrict(aParseURL);
+ dispatchURL = aParseURL[0];
+
+ } catch (com.sun.star.uno.Exception e) {
+ e.printStackTrace();
+ throw new StatusException("Can't create object environment", e) ;
+ }
+
+ TestEnvironment tEnv = new TestEnvironment(oObj) ;
+ tEnv.addObjRelation( "XDispatchProvider.URL", scriptURL );
+ tEnv.addObjRelation( "XDispatch.URL", dispatchURL );
+ return tEnv ;
+ }
+
+ public synchronized void disposeTestEnvironment( TestEnvironment tEnv,
+ TestParameters tParam) {
+ }
+}
+
+
diff --git a/scripting/workben/mod/_scripting/Function.java b/scripting/workben/mod/_scripting/Function.java
new file mode 100644
index 000000000000..df8d1daae60d
--- /dev/null
+++ b/scripting/workben/mod/_scripting/Function.java
@@ -0,0 +1,98 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: Function.java,v $
+ * $Revision: 1.7 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package mod._scripting;
+
+import com.sun.star.uno.XInterface;
+import java.io.PrintWriter;
+import lib.StatusException;
+import lib.TestCase;
+import lib.TestEnvironment;
+import lib.TestParameters;
+import util.utils;
+import java.net.URLEncoder;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.UnoRuntime;
+
+import com.sun.star.frame.XModel;
+import com.sun.star.frame.XFrame;
+import com.sun.star.lang.XComponent;
+import com.sun.star.frame.XDesktop;
+
+import util.SOfficeFactory;
+
+import drafts.com.sun.star.script.framework.provider.XFunction;
+import drafts.com.sun.star.script.framework.provider.XFunctionProvider;
+
+public class Function extends TestCase {
+ private String script = "script://returns-Integer";
+ private String doc = "doc_with_beanshell_scripts.sxw";
+
+ public void initialize( TestParameters tParam, PrintWriter log ) {
+ }
+
+ public synchronized TestEnvironment createTestEnvironment(
+ TestParameters tParam, PrintWriter log ) throws StatusException {
+ XInterface oObj = null;
+ XFunctionProvider provider = null;
+
+ log.println("creating test environment");
+ try {
+
+ XMultiServiceFactory xMSF = tParam.getMSF();
+ SOfficeFactory SOF = null;
+ SOF = SOfficeFactory.getFactory( xMSF );
+ String docPath = util.utils.getFullTestURL(doc);
+ XComponent doc = SOF.loadDocument( docPath );
+ XModel model = ( XModel ) UnoRuntime.queryInterface( XModel.class,
+ doc );
+ oObj =
+ (XInterface)xMSF.createInstanceWithArguments( "drafts.com.sun.star.script.framework.provider.FunctionProvider", new Object[]{ model } );
+ provider = ( XFunctionProvider )UnoRuntime.queryInterface( XFunctionProvider.class, oObj );
+ oObj = provider.getFunction( script );
+
+ } catch (com.sun.star.uno.Exception e) {
+ e.printStackTrace();
+ throw new StatusException("Can't create object environment", e) ;
+ }
+
+ TestEnvironment tEnv = new TestEnvironment(oObj) ;
+ tEnv.addObjRelation("provider", provider);
+ TestDataLoader.setupData(tEnv, "Function");
+
+ return tEnv ;
+ }
+
+ public synchronized void disposeTestEnvironment( TestEnvironment tEnv,
+ TestParameters tParam) {
+ }
+}
+
+
diff --git a/scripting/workben/mod/_scripting/FunctionProvider.java b/scripting/workben/mod/_scripting/FunctionProvider.java
new file mode 100644
index 000000000000..86eccbc7cd01
--- /dev/null
+++ b/scripting/workben/mod/_scripting/FunctionProvider.java
@@ -0,0 +1,85 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: FunctionProvider.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package mod._scripting;
+
+import com.sun.star.uno.XInterface;
+import java.io.PrintWriter;
+import lib.StatusException;
+import lib.TestCase;
+import lib.TestEnvironment;
+import lib.TestParameters;
+import util.utils;
+import java.net.URLEncoder;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.uno.UnoRuntime;
+
+import com.sun.star.frame.XModel;
+import com.sun.star.frame.XDesktop;
+
+public class FunctionProvider extends TestCase {
+
+ String docPath = null;
+ public void initialize( TestParameters tParam, PrintWriter log ) {
+ }
+
+ public synchronized TestEnvironment createTestEnvironment(
+ TestParameters tParam, PrintWriter log ) throws StatusException {
+ XInterface oObj = null;
+ log.println("creating test environment");
+ try {
+
+ XMultiServiceFactory xMSF = tParam.getMSF();
+
+ Object xInterface = xMSF.createInstance( "com.sun.star.frame.Desktop" );
+ XDesktop dtop = ( XDesktop )UnoRuntime.queryInterface( XDesktop.class,
+ xInterface );
+
+ XModel model = dtop.getCurrentFrame().getController().getModel();
+ oObj =
+ (XInterface)xMSF.createInstanceWithArguments( "drafts.com.sun.star.script.framework.provider.FunctionProvider", new Object[]{ model } );
+
+
+ } catch (com.sun.star.uno.Exception e) {
+ throw new StatusException("Can't create object environment", e) ;
+ }
+
+ TestEnvironment tEnv = new TestEnvironment(oObj) ;
+ TestDataLoader.setupData(tEnv, "FunctionProvider");
+
+ return tEnv ;
+ }
+
+ public synchronized void disposeTestEnvironment( TestEnvironment tEnv,
+ TestParameters tParam) {
+ }
+}
+
+
diff --git a/scripting/workben/mod/_scripting/ScriptInfo.java b/scripting/workben/mod/_scripting/ScriptInfo.java
new file mode 100644
index 000000000000..d1e94b374d81
--- /dev/null
+++ b/scripting/workben/mod/_scripting/ScriptInfo.java
@@ -0,0 +1,111 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptInfo.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package mod._scripting;
+
+import com.sun.star.uno.XInterface;
+import java.io.PrintWriter;
+import lib.StatusException;
+import lib.TestCase;
+import lib.TestEnvironment;
+import lib.TestParameters;
+import util.utils;
+import java.net.URLEncoder;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.uno.UnoRuntime;
+
+import drafts.com.sun.star.script.framework.storage.XScriptInfoAccess;
+import drafts.com.sun.star.script.framework.storage.XScriptInfo;
+
+public class ScriptInfo extends TestCase {
+
+ String docPath = null;
+ public void initialize( TestParameters tParam, PrintWriter log ) {
+ // Get path to test documents
+ String rootDocPath = ( String )tParam.get( "DOCPTH" );
+ System.out.println( "DOCPTH is " + rootDocPath );
+ rootDocPath = util.utils.getFullTestURL( "ExampleSpreadSheetLatest.sxc" );
+ if ( rootDocPath != null && rootDocPath.length() > 1 ){
+ // convert all "\\" to "/", necessary for UCB
+ if ( rootDocPath.indexOf( "\\" ) > 0 ){
+ rootDocPath = rootDocPath.replace( '\\','/' );
+ }
+ System.out.println("After processing the path is " + rootDocPath);
+ // encode the ulr (for UCB)
+ String encodedPath = URLEncoder.encode( rootDocPath );
+ System.out.println("The encoded path is " + encodedPath );
+ docPath = "vnd.sun.star.pkg://" + encodedPath;
+ System.out.println( "docPath path is " + docPath );
+ }
+
+ }
+
+ public synchronized TestEnvironment createTestEnvironment(
+ TestParameters tParam, PrintWriter log ) throws StatusException {
+
+ log.println("creating test environment");
+ if ( docPath == null ){
+ log.println("Testdata not set up, docPath is null");
+ throw new StatusException(
+ "Can't create object environment, no test document available",
+ new Exception() ) ;
+ }
+
+ XInterface oObj = null;
+ XSimpleFileAccess access = null;
+ try {
+ XMultiServiceFactory xMSF = tParam.getMSF();
+ Object xInterface =
+ xMSF.createInstance( "com.sun.star.ucb.SimpleFileAccess" );
+ access = ( XSimpleFileAccess )
+ UnoRuntime.queryInterface( XSimpleFileAccess.class, xInterface );
+ Object storageObj = ( XInterface )xMSF.createInstanceWithArguments(
+ "drafts.com.sun.star.script.framework.storage.ScriptStorage",
+ new Object[]{ access, new Integer(99), docPath } );
+ XScriptInfoAccess infoAccess = ( XScriptInfoAccess )UnoRuntime.queryInterface(XScriptInfoAccess.class, storageObj);
+ XScriptInfo[] infos = infoAccess.getImplementations("script://MemoryUtils.MemUsage?location=document");
+ oObj = infos[0];
+ } catch (com.sun.star.uno.Exception e) {
+ throw new StatusException("Can't create object environment", e) ;
+ }
+
+ TestEnvironment tEnv = new TestEnvironment(oObj) ;
+ TestDataLoader.setupData(tEnv, "ScriptInfo");
+
+ return tEnv ;
+ }
+
+ public synchronized void disposeTestEnvironment( TestEnvironment tEnv,
+ TestParameters tParam) {
+ }
+}
+
+
diff --git a/scripting/workben/mod/_scripting/ScriptRuntimeManager.java b/scripting/workben/mod/_scripting/ScriptRuntimeManager.java
new file mode 100644
index 000000000000..8bd6bd275ccb
--- /dev/null
+++ b/scripting/workben/mod/_scripting/ScriptRuntimeManager.java
@@ -0,0 +1,68 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptRuntimeManager.java,v $
+ * $Revision: 1.5 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package mod._scripting;
+
+import com.sun.star.uno.XInterface;
+import java.io.PrintWriter;
+import lib.StatusException;
+import lib.TestCase;
+import lib.TestEnvironment;
+import lib.TestParameters;
+
+public class ScriptRuntimeManager extends TestCase {
+
+ public void initialize( TestParameters tParam, PrintWriter log ) {
+ }
+
+ public synchronized TestEnvironment createTestEnvironment(
+ TestParameters Param, PrintWriter log ) throws StatusException {
+
+ log.println("creating test environment");
+
+ XInterface oObj = null;
+
+ try {
+ oObj = (XInterface) Param.getMSF().createInstance
+ ("drafts.com.sun.star.script.framework.runtime.ScriptRuntimeManager");
+ } catch (com.sun.star.uno.Exception e) {
+ throw new StatusException("Can't create object environment", e) ;
+ }
+
+ TestEnvironment tEnv = new TestEnvironment(oObj) ;
+ TestDataLoader.setupData(tEnv, "ScriptRuntimeManager");
+
+ return tEnv ;
+ }
+
+ public synchronized void disposeTestEnvironment( TestEnvironment tEnv,
+ TestParameters tParam) {
+ }
+}
diff --git a/scripting/workben/mod/_scripting/ScriptStorage.java b/scripting/workben/mod/_scripting/ScriptStorage.java
new file mode 100644
index 000000000000..e4f2bbfda1d0
--- /dev/null
+++ b/scripting/workben/mod/_scripting/ScriptStorage.java
@@ -0,0 +1,106 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptStorage.java,v $
+ * $Revision: 1.6 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package mod._scripting;
+
+import com.sun.star.uno.XInterface;
+import java.io.PrintWriter;
+import lib.StatusException;
+import lib.TestCase;
+import lib.TestEnvironment;
+import lib.TestParameters;
+import util.utils;
+import java.net.URLEncoder;
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.ucb.XSimpleFileAccess;
+import com.sun.star.uno.UnoRuntime;
+
+public class ScriptStorage extends TestCase {
+
+ String docPath = null;
+ public void initialize( TestParameters tParam, PrintWriter log ) {
+ // Get path to test documents
+ String rootDocPath = ( String )tParam.get( "DOCPTH" );
+ System.out.println( "DOCPTH is " + rootDocPath );
+ rootDocPath = util.utils.getFullTestURL( "ExampleSpreadSheetLatest.sxc" );
+ if ( rootDocPath != null && rootDocPath.length() > 1 ){
+ // convert all "\\" to "/", necessary for UCB
+ if ( rootDocPath.indexOf( "\\" ) > 0 ){
+ rootDocPath = rootDocPath.replace( '\\','/' );
+ }
+ System.out.println("After processing the path is " + rootDocPath);
+ // encode the ulr (for UCB)
+ String encodedPath = URLEncoder.encode( rootDocPath );
+ System.out.println("The encoded path is " + encodedPath );
+ docPath = "vnd.sun.star.pkg://" + encodedPath;
+ System.out.println( "docPath path is " + docPath );
+ }
+
+ }
+
+ public synchronized TestEnvironment createTestEnvironment(
+ TestParameters tParam, PrintWriter log ) throws StatusException {
+
+ log.println("creating test environment");
+ if ( docPath == null ){
+ log.println("Testdata not set up, docPath is null");
+ throw new StatusException(
+ "Can't create object environment, no test document available",
+ new Exception() ) ;
+ }
+
+ XInterface oObj = null;
+ XSimpleFileAccess access = null;
+ try {
+ XMultiServiceFactory xMSF = tParam.getMSF();
+ Object xInterface =
+ xMSF.createInstance( "com.sun.star.ucb.SimpleFileAccess" );
+ access = ( XSimpleFileAccess )
+ UnoRuntime.queryInterface( XSimpleFileAccess.class, xInterface );
+ oObj = ( XInterface )xMSF.createInstanceWithArguments(
+ "drafts.com.sun.star.script.framework.storage.ScriptStorage",
+ new Object[]{ access, new Integer(99), docPath } );
+
+ } catch (com.sun.star.uno.Exception e) {
+ throw new StatusException("Can't create object environment", e) ;
+ }
+
+ TestEnvironment tEnv = new TestEnvironment(oObj) ;
+ TestDataLoader.setupData(tEnv, "ScriptStorage");
+
+ return tEnv ;
+ }
+
+ public synchronized void disposeTestEnvironment( TestEnvironment tEnv,
+ TestParameters tParam) {
+ }
+}
+
+
diff --git a/scripting/workben/mod/_scripting/ScriptStorageManager.java b/scripting/workben/mod/_scripting/ScriptStorageManager.java
new file mode 100644
index 000000000000..488cbf86d058
--- /dev/null
+++ b/scripting/workben/mod/_scripting/ScriptStorageManager.java
@@ -0,0 +1,85 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: ScriptStorageManager.java,v $
+ * $Revision: 1.4 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package mod._scripting;
+
+import com.sun.star.lang.XMultiServiceFactory;
+import com.sun.star.beans.XPropertySet;
+import com.sun.star.uno.XInterface;
+import com.sun.star.uno.UnoRuntime;
+import com.sun.star.uno.XComponentContext;
+import java.io.PrintWriter;
+import lib.StatusException;
+import lib.TestCase;
+import lib.TestEnvironment;
+import lib.TestParameters;
+import util.utils;
+
+public class ScriptStorageManager extends TestCase {
+
+ public void initialize( TestParameters tParam, PrintWriter log ) {
+ }
+
+ public synchronized TestEnvironment createTestEnvironment(
+ TestParameters Param, PrintWriter log ) throws StatusException {
+
+ XInterface oObj = null;
+ Object oInterface = null;
+
+ try {
+ XMultiServiceFactory xMSF = Param.getMSF();
+ XPropertySet xProp = (XPropertySet)UnoRuntime.queryInterface(
+ XPropertySet.class, xMSF);
+ // get context
+ XComponentContext xContext = (XComponentContext)
+ UnoRuntime.queryInterface(XComponentContext.class,
+ xProp.getPropertyValue("DefaultContext"));
+ // get the script storage manager from context
+ oInterface = xContext.getValueByName("/singletons/" +
+ "drafts.com.sun.star.script.framework.storage.theScriptStorageManager");
+ }
+ catch( Exception e ) {
+ log.println("ScriptStorageManager singleton service not available" );
+ e.printStackTrace();
+ }
+ oObj = (XInterface) oInterface;
+
+ TestEnvironment tEnv = new TestEnvironment(oObj) ;
+ TestDataLoader.setupData(tEnv, "ScriptStorageManager");
+
+ return tEnv ;
+ }
+
+ public synchronized void disposeTestEnvironment( TestEnvironment tEnv,
+ TestParameters tParam) {
+ }
+}
+
+
diff --git a/scripting/workben/mod/_scripting/TestDataLoader.java b/scripting/workben/mod/_scripting/TestDataLoader.java
new file mode 100644
index 000000000000..d82af567ad99
--- /dev/null
+++ b/scripting/workben/mod/_scripting/TestDataLoader.java
@@ -0,0 +1,126 @@
+/*************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 2008 by Sun Microsystems, Inc.
+ *
+ * OpenOffice.org - a multi-platform office productivity suite
+ *
+ * $RCSfile: TestDataLoader.java,v $
+ * $Revision: 1.3 $
+ *
+ * This file is part of OpenOffice.org.
+ *
+ * OpenOffice.org is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License version 3
+ * only, as published by the Free Software Foundation.
+ *
+ * OpenOffice.org is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Lesser General Public License version 3 for more details
+ * (a copy is included in the LICENSE file that accompanied this code).
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * version 3 along with OpenOffice.org. If not, see
+ * <http://www.openoffice.org/license.html>
+ * for a copy of the LGPLv3 License.
+ *
+ ************************************************************************/
+
+package mod._scripting;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.BufferedReader;
+import java.io.IOException;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.StringTokenizer;
+
+import lib.TestEnvironment;
+import lib.Parameters;
+
+public class TestDataLoader {
+
+ private TestDataLoader() {
+ }
+
+ public static void setupData(TestEnvironment tEnv, String name) {
+ String filename =
+ util.utils.getFullTestDocName("testdata");
+ File testdatadir = new File(filename);
+ File f = new File(testdatadir, name + ".csv");
+
+ if (!f.exists())
+ return;
+
+ BufferedReader in;
+
+ try {
+ in = new BufferedReader(new FileReader(f));
+
+ String s, previous, current;
+ ArrayList list = new ArrayList(11);
+
+ if ((s = in.readLine()) != null) {
+ StringTokenizer st = new StringTokenizer(s, ";");
+
+ current = previous = st.nextToken();
+ list.add(getParameters(st));
+ }
+ else {
+ return;
+ }
+
+ while ((s = in.readLine()) != null) {
+ StringTokenizer st = new StringTokenizer(s, ";");
+
+ current = st.nextToken();
+
+ if (!current.equals(previous)) {
+ tEnv.addObjRelation(previous, list);
+ previous = current;
+ list = new ArrayList(11);
+ }
+
+ list.add(getParameters(st));
+ }
+
+ tEnv.addObjRelation(previous, list);
+ }
+ catch (IOException ioe) {
+ }
+ }
+
+ private static Parameters getParameters(StringTokenizer st) {
+ String separator = "=";
+ HashMap map = new HashMap(5);
+
+ while (st.hasMoreTokens()) {
+ String pair = st.nextToken();
+ StringTokenizer tokens = new StringTokenizer(pair, separator);
+
+ String name;
+ String value;
+
+ if (tokens.countTokens() < 2)
+ continue;
+
+ name = tokens.nextToken();
+ if (tokens.countTokens() == 1)
+ value = tokens.nextToken();
+ else {
+ StringBuffer buf = new StringBuffer(tokens.nextToken());
+ while (tokens.hasMoreTokens())
+ buf.append(separator).append(tokens.nextToken());
+ value = buf.toString();
+ }
+
+ map.put(name, value);
+ }
+
+ return new Parameters(map);
+ }
+}
diff --git a/scripting/workben/mod/_scripting/makefile.mk b/scripting/workben/mod/_scripting/makefile.mk
new file mode 100644
index 000000000000..4abfea1ea08b
--- /dev/null
+++ b/scripting/workben/mod/_scripting/makefile.mk
@@ -0,0 +1,44 @@
+#*************************************************************************
+#
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# Copyright 2008 by Sun Microsystems, Inc.
+#
+# OpenOffice.org - a multi-platform office productivity suite
+#
+# $RCSfile: makefile.mk,v $
+#
+# $Revision: 1.5 $
+#
+# This file is part of OpenOffice.org.
+#
+# OpenOffice.org is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Lesser General Public License version 3
+# only, as published by the Free Software Foundation.
+#
+# OpenOffice.org is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU Lesser General Public License version 3 for more details
+# (a copy is included in the LICENSE file that accompanied this code).
+#
+# You should have received a copy of the GNU Lesser General Public License
+# version 3 along with OpenOffice.org. If not, see
+# <http://www.openoffice.org/license.html>
+# for a copy of the LGPLv3 License.
+#
+#*************************************************************************
+
+PRJ = ..$/..$/..$/..
+PRJNAME = testcase
+TARGET = testcase
+
+# --- Settings -----------------------------------------------------
+.INCLUDE: settings.mk
+
+JARFILES = ridl.jar unoil.jar jurt.jar juh.jar $(CLASSPATH)
+JAVAFILES = $(foreach,j,$(shell @ls | grep java) $j)
+
+# --- Targets ------------------------------------------------------
+
+.INCLUDE : target.mk