From 940b4d1848e8c70ab7642901a68594e8016caffc Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sat, 27 Apr 2024 18:51:28 +0200 Subject: Adding upstream version 1:7.0.4. Signed-off-by: Daniel Baumann --- .../CLI/CSharp/Spreadsheet/GeneralTableSample.cs | 222 ++ odk/examples/CLI/CSharp/Spreadsheet/Makefile | 110 + .../CLI/CSharp/Spreadsheet/SpreadsheetDocHelper.cs | 361 +++ .../CLI/CSharp/Spreadsheet/SpreadsheetSample.cs | 1495 ++++++++++ odk/examples/CLI/CSharp/Spreadsheet/ViewSample.cs | 182 ++ odk/examples/CLI/VB.NET/WriterDemo/Makefile | 85 + odk/examples/CLI/VB.NET/WriterDemo/WriterDemo.vb | 233 ++ .../CreatingDialogs/CreatingDialogs.odt | Bin 0 -> 8654 bytes .../BasicAndDialogs/CreatingDialogs/Makefile | 138 + .../CreatingDialogs/SampleDialog.java | 278 ++ .../BasicAndDialogs/FirstStepsBasic.odt | Bin 0 -> 18560 bytes .../BasicAndDialogs/ToolkitControls/Makefile | 125 + .../ToolkitControls/ToolkitControls.odt | Bin 0 -> 7793 bytes .../ToolkitControls/ToolkitControls/FileDialog.xba | 90 + .../ToolkitControls/FileDialogDlg.xdl | 29 + .../ToolkitControls/ToolkitControls/MultiPage.xba | 303 ++ .../ToolkitControls/MultiPageDlg.xdl | 92 + .../ToolkitControls/ProgressBar.xba | 93 + .../ToolkitControls/ProgressBarDlg.xdl | 28 + .../ToolkitControls/ToolkitControls/ScrollBar.xba | 103 + .../ToolkitControls/ScrollBarDlg.xdl | 30 + .../ToolkitControls/ToolkitControls/dialog.xlb | 8 + .../ToolkitControls/ToolkitControls/script.xlb | 8 + odk/examples/DevelopersGuide/Charts/AddInChart.ods | Bin 0 -> 18045 bytes .../DevelopersGuide/Charts/CalcHelper.java | 396 +++ .../DevelopersGuide/Charts/ChartHelper.java | 244 ++ .../DevelopersGuide/Charts/ChartInCalc.java | 417 +++ .../DevelopersGuide/Charts/ChartInDraw.java | 294 ++ .../DevelopersGuide/Charts/ChartInWriter.java | 163 ++ odk/examples/DevelopersGuide/Charts/Helper.java | 141 + .../Charts/JavaSampleChartAddIn.components | 10 + .../Charts/JavaSampleChartAddIn.java | 449 +++ .../Charts/ListenAtCalcRangeInDraw.java | 193 ++ odk/examples/DevelopersGuide/Charts/Makefile | 199 ++ .../Charts/SelectionChangeListener.java | 220 ++ odk/examples/DevelopersGuide/Charts/bullet.gif | Bin 0 -> 335 bytes .../Components/Addons/JobsAddon/Addons.xcu | 98 + .../Addons/JobsAddon/AsyncJob.components | 8 + .../Components/Addons/JobsAddon/AsyncJob.java | 425 +++ .../Components/Addons/JobsAddon/Jobs.xcu | 44 + .../Components/Addons/JobsAddon/Makefile | 136 + .../Addons/ProtocolHandlerAddon_cpp/Addons.xcu | 231 ++ .../Addons/ProtocolHandlerAddon_cpp/Makefile | 153 ++ .../ProtocolHandlerAddon_cpp/ProtocolHandler.xcu | 27 + .../Addons/ProtocolHandlerAddon_cpp/addon.cxx | 238 ++ .../Addons/ProtocolHandlerAddon_cpp/addon.hxx | 132 + .../Addons/ProtocolHandlerAddon_cpp/component.cxx | 92 + .../Addons/ProtocolHandlerAddon_java/Addons.xcu | 231 ++ .../Addons/ProtocolHandlerAddon_java/Makefile | 138 + .../ProtocolHandlerAddon_java/ProtocolHandler.xcu | 27 + .../ProtocolHandlerAddon.java | 254 ++ .../ProtocolHandlerAddon_java.components | 8 + .../Components/CppComponent/Makefile | 228 ++ .../Components/CppComponent/SimpleComponent.odt | Bin 0 -> 8841 bytes .../Components/CppComponent/TestCppComponent.cxx | 93 + .../Components/CppComponent/service1_impl.cxx | 227 ++ .../Components/CppComponent/service2_impl.cxx | 215 ++ .../Components/CppComponent/some.idl | 57 + .../JavaComponent/JavaComponent.components | 11 + .../Components/JavaComponent/Makefile | 206 ++ .../Components/JavaComponent/SomethingA.idl | 48 + .../Components/JavaComponent/SomethingB.idl | 48 + .../Components/JavaComponent/TestComponentA.java | 69 + .../Components/JavaComponent/TestComponentB.java | 92 + .../JavaComponent/TestJavaComponent.java | 144 + .../JavaComponent/TestServiceProvider.java | 61 + .../Components/JavaComponent/XSomethingA.idl | 50 + .../Components/JavaComponent/XSomethingB.idl | 50 + .../SimpleLicense/LicenseTest.components | 8 + .../Components/SimpleLicense/LicenseTest.idl | 53 + .../Components/SimpleLicense/LicenseTest.java | 129 + .../Components/SimpleLicense/Makefile | 171 ++ .../Components/SimpleLicense/description.xml | 29 + .../SimpleLicense/registration/license_de.txt | 1 + .../SimpleLicense/registration/license_en_US.txt | 1 + .../DevelopersGuide/Components/Thumbs/Makefile | 80 + .../openoffice/comp/test/ImageShrink.components | 8 + .../org/openoffice/comp/test/ImageShrink.java | 129 + .../Thumbs/org/openoffice/comp/test/Makefile | 128 + .../Thumbs/org/openoffice/comp/test/Thumbs.java | 79 + .../Thumbs/org/openoffice/test/ImageShrink.idl | 49 + .../Components/Thumbs/org/openoffice/test/Makefile | 72 + .../Thumbs/org/openoffice/test/XImageShrink.idl | 56 + .../org/openoffice/test/XImageShrinkFilter.idl | 53 + .../DevelopersGuide/Components/Thumbs/thumbs.mk | 46 + .../dialogcomponent/DialogComponent.components | 8 + .../dialogcomponent/DialogComponent.java | 294 ++ .../Components/dialogcomponent/DialogComponent.odt | Bin 0 -> 11902 bytes .../Components/dialogcomponent/Makefile | 178 ++ .../dialogcomponent/TestDialogHandler.idl | 49 + .../dialogcomponent/XTestDialogHandler.idl | 56 + .../DevelopersGuide/Config/ConfigExamples.java | 1102 ++++++++ odk/examples/DevelopersGuide/Config/Makefile | 98 + .../DevelopersGuide/Database/CodeSamples.java | 322 +++ .../DriverSkeleton/How_to_write_my_own_driver.txt | 43 + .../Database/DriverSkeleton/Makefile | 156 ++ .../Database/DriverSkeleton/OSubComponent.hxx | 242 ++ .../Database/DriverSkeleton/OTypeInfo.hxx | 100 + .../Database/DriverSkeleton/SConnection.cxx | 401 +++ .../Database/DriverSkeleton/SConnection.hxx | 158 ++ .../Database/DriverSkeleton/SDatabaseMetaData.cxx | 887 ++++++ .../Database/DriverSkeleton/SDatabaseMetaData.hxx | 218 ++ .../Database/DriverSkeleton/SDriver.cxx | 201 ++ .../Database/DriverSkeleton/SDriver.hxx | 92 + .../Database/DriverSkeleton/SPreparedStatement.cxx | 385 +++ .../Database/DriverSkeleton/SPreparedStatement.hxx | 151 + .../Database/DriverSkeleton/SResultSet.cxx | 869 ++++++ .../Database/DriverSkeleton/SResultSet.hxx | 222 ++ .../Database/DriverSkeleton/SResultSetMetaData.cxx | 170 ++ .../Database/DriverSkeleton/SResultSetMetaData.hxx | 91 + .../Database/DriverSkeleton/SServices.cxx | 153 ++ .../Database/DriverSkeleton/SStatement.cxx | 377 +++ .../Database/DriverSkeleton/SStatement.hxx | 176 ++ .../Database/DriverSkeleton/propertyids.cxx | 184 ++ .../Database/DriverSkeleton/propertyids.hxx | 145 + odk/examples/DevelopersGuide/Database/Makefile | 133 + .../DevelopersGuide/Database/OpenQuery.java | 143 + odk/examples/DevelopersGuide/Database/RowSet.java | 225 ++ .../Database/RowSetEventListener.java | 80 + odk/examples/DevelopersGuide/Database/Sales.java | 130 + .../DevelopersGuide/Database/SalesMan.java | 137 + odk/examples/DevelopersGuide/Database/sdbcx.java | 420 +++ .../DevelopersGuide/Drawing/ChangeOrderDemo.java | 113 + .../Drawing/ControlAndSelectDemo.java | 144 + .../DevelopersGuide/Drawing/CustomShowDemo.java | 169 ++ .../DevelopersGuide/Drawing/DrawViewDemo.java | 142 + .../DevelopersGuide/Drawing/DrawingDemo.java | 419 +++ .../Drawing/FillAndLineStyleDemo.java | 132 + .../DevelopersGuide/Drawing/GluePointDemo.java | 182 ++ .../DevelopersGuide/Drawing/GraphicExportDemo.java | 148 + odk/examples/DevelopersGuide/Drawing/Helper.java | 89 + .../DevelopersGuide/Drawing/LayerDemo.java | 152 ++ odk/examples/DevelopersGuide/Drawing/Makefile | 174 ++ .../Drawing/ObjectTransformationDemo.java | 131 + .../DevelopersGuide/Drawing/Organigram.java | 176 ++ .../DevelopersGuide/Drawing/PageHelper.java | 199 ++ .../DevelopersGuide/Drawing/PresentationDemo.java | 232 ++ .../DevelopersGuide/Drawing/ShapeHelper.java | 142 + .../DevelopersGuide/Drawing/SimplePresentation.odp | Bin 0 -> 74753 bytes .../DevelopersGuide/Drawing/StyleDemo.java | 164 ++ odk/examples/DevelopersGuide/Drawing/TextDemo.java | 153 ++ .../Extensions/DialogWithHelp/Addons.xcu | 68 + .../DialogWithHelp/DialogWithHelp/Dialog1.xdl | 27 + .../DialogWithHelp/DialogWithHelp/Module1.xba | 33 + .../DialogWithHelp/DialogWithHelp/dialog.xlb | 5 + .../DialogWithHelp/DialogWithHelp/script.xlb | 5 + .../DialogWithHelp/META-INF/manifest.xml | 23 + .../Extensions/DialogWithHelp/Makefile | 117 + .../Extensions/DialogWithHelp/description.xml | 25 + .../help/de/com.foocorp.foo-ext/page1.xhp | 90 + .../help/de/com.foocorp.foo-ext/page2.xhp | 44 + .../com.foocorp.foo-ext/subfolder/anotherpage.xhp | 117 + .../help/en/com.foocorp.foo-ext/page1.xhp | 90 + .../help/en/com.foocorp.foo-ext/page2.xhp | 43 + .../com.foocorp.foo-ext/subfolder/anotherpage.xhp | 117 + .../FirstSteps/FirstConnection.java | 61 + .../FirstSteps/FirstLoadComponent.java | 162 ++ .../FirstSteps/FirstUnoContact.java | 61 + .../FirstSteps/HelloTextTableShape.java | 439 +++ odk/examples/DevelopersGuide/FirstSteps/Makefile | 100 + .../FirstSteps/build_FirstUnoContact.xml | 81 + .../DevelopersGuide/Forms/BooleanValidator.java | 84 + .../DevelopersGuide/Forms/ButtonOperator.java | 219 ++ .../Forms/ComponentTreeTraversal.java | 92 + .../DevelopersGuide/Forms/ControlLock.java | 223 ++ .../DevelopersGuide/Forms/ControlValidation.java | 85 + .../DevelopersGuide/Forms/ControlValidator.java | 52 + .../DevelopersGuide/Forms/DataAwareness.java | 940 +++++++ .../DevelopersGuide/Forms/DateValidator.java | 91 + .../Forms/DocumentBasedExample.java | 219 ++ .../DevelopersGuide/Forms/DocumentHelper.java | 306 +++ .../DevelopersGuide/Forms/DocumentType.java | 40 + .../DevelopersGuide/Forms/DocumentViewHelper.java | 215 ++ odk/examples/DevelopersGuide/Forms/FLTools.java | 216 ++ odk/examples/DevelopersGuide/Forms/FormLayer.java | 272 ++ .../DevelopersGuide/Forms/GridFieldValidator.java | 174 ++ .../DevelopersGuide/Forms/HsqlDatabase.java | 184 ++ .../DevelopersGuide/Forms/InteractionRequest.java | 71 + .../DevelopersGuide/Forms/KeyGenerator.java | 434 +++ .../Forms/ListSelectionValidator.java | 59 + odk/examples/DevelopersGuide/Forms/Makefile | 196 ++ .../DevelopersGuide/Forms/NumericValidator.java | 77 + .../Forms/ProgrammaticScriptAssignment.odt | Bin 0 -> 19198 bytes odk/examples/DevelopersGuide/Forms/RowSet.java | 283 ++ .../DevelopersGuide/Forms/SalesFilter.java | 510 ++++ .../Forms/SingleControlValidation.java | 171 ++ .../DevelopersGuide/Forms/SpreadsheetDocument.java | 120 + .../Forms/SpreadsheetValueBinding.java | 125 + .../DevelopersGuide/Forms/SpreadsheetView.java | 35 + .../Forms/TableCellTextBinding.java | 199 ++ .../DevelopersGuide/Forms/TextValidator.java | 78 + .../DevelopersGuide/Forms/TimeValidator.java | 83 + odk/examples/DevelopersGuide/Forms/UNO.java | 89 + odk/examples/DevelopersGuide/Forms/URLHelper.java | 65 + .../DevelopersGuide/Forms/ValueBinding.java | 82 + .../DevelopersGuide/Forms/WaitForInput.java | 58 + .../DevelopersGuide/GUI/DialogDocument.java | 146 + .../DevelopersGuide/GUI/ImageControlSample.java | 166 ++ odk/examples/DevelopersGuide/GUI/Makefile | 141 + odk/examples/DevelopersGuide/GUI/MessageBox.java | 237 ++ .../GUI/RoadmapItemStateChangeListener.java | 69 + odk/examples/DevelopersGuide/GUI/SystemDialog.java | 188 ++ .../DevelopersGuide/GUI/UnoDialogSample.java | 1373 ++++++++++ .../DevelopersGuide/GUI/UnoDialogSample2.java | 263 ++ odk/examples/DevelopersGuide/GUI/UnoMenu.java | 186 ++ odk/examples/DevelopersGuide/GUI/UnoMenu2.java | 120 + odk/examples/DevelopersGuide/GUI/oologo.gif | Bin 0 -> 2563 bytes odk/examples/DevelopersGuide/OfficeBean/Makefile | 90 + .../DevelopersGuide/OfficeBean/OOoBeanViewer.java | 410 +++ .../OfficeBean/OfficeIconColor16.jpg | Bin 0 -> 321 bytes .../OfficeBean/OfficeIconColor32.jpg | Bin 0 -> 569 bytes .../OfficeBean/OfficeIconMono16.jpg | Bin 0 -> 321 bytes .../OfficeBean/OfficeIconMono32.jpg | Bin 0 -> 569 bytes .../OfficeDev/Clipboard/Clipboard.java | 212 ++ .../OfficeDev/Clipboard/ClipboardListener.java | 58 + .../OfficeDev/Clipboard/ClipboardOwner.java | 63 + .../DevelopersGuide/OfficeDev/Clipboard/Makefile | 98 + .../OfficeDev/Clipboard/TextTransferable.java | 88 + .../OfficeDev/ContextMenuInterceptor.java | 253 ++ .../DesktopEnvironment/CustomizeView.java | 285 ++ .../OfficeDev/DesktopEnvironment/Desk.java | 93 + .../OfficeDev/DesktopEnvironment/DocumentView.java | 428 +++ .../DesktopEnvironment/FunctionHelper.java | 939 +++++++ .../OfficeDev/DesktopEnvironment/IOnewayLink.java | 71 + .../DesktopEnvironment/IShutdownListener.java | 48 + .../OfficeDev/DesktopEnvironment/Install.txt | 10 + .../OfficeDev/DesktopEnvironment/Interceptor.java | 655 +++++ .../DesktopEnvironment/JavaWindowPeerFake.java | 109 + .../OfficeDev/DesktopEnvironment/Makefile | 131 + .../OfficeDev/DesktopEnvironment/NativeView.java | 186 ++ .../DesktopEnvironment/OfficeConnect.java | 127 + .../DesktopEnvironment/OnewayExecutor.java | 189 ++ .../DesktopEnvironment/StatusListener.java | 469 ++++ .../OfficeDev/DesktopEnvironment/StatusView.java | 264 ++ .../DesktopEnvironment/ViewContainer.java | 260 ++ .../DesktopEnvironment/nativelib/unix/Makefile | 72 + .../DesktopEnvironment/nativelib/unix/nativeview.c | 112 + .../DesktopEnvironment/nativelib/unix/nativeview.h | 66 + .../DesktopEnvironment/nativelib/windows/Makefile | 77 + .../nativelib/windows/nativeview.c | 181 ++ .../nativelib/windows/nativeview.def | 3 + .../nativelib/windows/nativeview.h | 66 + .../DisableCommands/DisableCommandsTest.java | 397 +++ .../OfficeDev/DisableCommands/Makefile | 91 + .../AsciiFilter/AsciiReplaceFilter.java | 702 +++++ .../AsciiFilter/FilterOptions.java | 225 ++ .../FilterDevelopment/AsciiFilter/Makefile | 139 + .../AsciiFilter/SampleFilter.components | 10 + .../AsciiFilter/TypeDetection.xcu | 46 + .../FlatXmlTypeDetection.xcu | 88 + .../FlatXmlFilterDetection/Makefile | 155 ++ .../FlatXmlFilterDetection/fdcomp.cxx | 84 + .../FlatXmlFilterDetection/filterdetect.cxx | 247 ++ .../FlatXmlFilterDetection/filterdetect.hxx | 122 + .../FlatXmlFilter_cpp/FlatXml.cxx | 349 +++ .../FlatXmlFilter_cpp/FlatXmlFilter_cpp.xcu | 103 + .../FilterDevelopment/FlatXmlFilter_cpp/Makefile | 153 ++ .../FlatXmlFilter_java/FlatXml.java | 267 ++ .../FlatXmlFilter_java.components | 8 + .../FlatXmlFilter_java/FlatXmlFilter_java.xcu | 103 + .../FilterDevelopment/FlatXmlFilter_java/Makefile | 142 + .../OfficeDev/Linguistic/LinguisticExamples.java | 360 +++ .../DevelopersGuide/OfficeDev/Linguistic/Makefile | 231 ++ .../OfficeDev/Linguistic/OneInstanceFactory.java | 155 ++ .../OfficeDev/Linguistic/PropChgHelper.java | 193 ++ .../OfficeDev/Linguistic/PropChgHelper_Hyph.java | 81 + .../OfficeDev/Linguistic/PropChgHelper_Spell.java | 105 + .../Linguistic/SampleHyphenator.components | 8 + .../OfficeDev/Linguistic/SampleHyphenator.java | 514 ++++ .../Linguistic/SampleSpellChecker.components | 8 + .../OfficeDev/Linguistic/SampleSpellChecker.java | 457 ++++ .../Linguistic/SampleThesaurus.components | 8 + .../OfficeDev/Linguistic/SampleThesaurus.java | 293 ++ .../OfficeDev/Linguistic/XHyphenatedWord_impl.java | 100 + .../OfficeDev/Linguistic/XMeaning_impl.java | 71 + .../Linguistic/XPossibleHyphens_impl.java | 92 + .../Linguistic/XSpellAlternatives_impl.java | 94 + odk/examples/DevelopersGuide/OfficeDev/Makefile | 105 + .../DevelopersGuide/OfficeDev/MenuElement.java | 58 + .../DevelopersGuide/OfficeDev/Number_Formats.java | 245 ++ .../DevelopersGuide/OfficeDev/OfficeConnect.java | 140 + .../OfficeDev/PathSettings/Makefile | 91 + .../OfficeDev/PathSettings/PathSettingsTest.java | 164 ++ .../OfficeDev/PathSubstitution/Makefile | 91 + .../PathSubstitution/PathSubstitutionTest.java | 116 + .../OfficeDev/TerminationTest/Makefile | 96 + .../TerminationTest/TerminateListener.java | 59 + .../OfficeDev/TerminationTest/TerminationTest.java | 100 + .../DevelopersGuide/ProfUNO/CppBinding/Makefile | 117 + .../ProfUNO/CppBinding/office_connect.cxx | 110 + .../ProfUNO/CppBinding/string_samples.cxx | 87 + .../InterprocessConn/ConnectionAwareClient.java | 255 ++ .../ProfUNO/InterprocessConn/Makefile | 85 + .../ProfUNO/InterprocessConn/UrlResolver.java | 112 + .../DevelopersGuide/ProfUNO/Lifetime/Makefile | 112 + .../ProfUNO/Lifetime/MyUnoObject.java | 63 + .../ProfUNO/Lifetime/object_lifetime.cxx | 71 + .../ProfUNO/SimpleBootstrap_cpp/Makefile | 100 + .../SimpleBootstrap_cpp/SimpleBootstrap_cpp.cxx | 104 + .../ProfUNO/SimpleBootstrap_java/Makefile | 90 + .../SimpleBootstrap_java/SimpleBootstrap_java.java | 77 + .../ProfUNO/SimpleBootstrap_java/manifest.mf | 4 + .../SayHello/META-INF/manifest.xml | 5 + .../ScriptingFramework/SayHello/Makefile | 128 + .../ScriptingFramework/SayHello/SayHello.odt | Bin 0 -> 8874 bytes .../SayHello/SayHello/SayHello.java | 65 + .../SayHello/SayHello/parcel-descriptor.xml | 33 + .../ScriptingFramework/SayHello/build.xml | 96 + .../ScriptSelector/META-INF/manifest.xml | 5 + .../ScriptingFramework/ScriptSelector/Makefile | 130 + .../ScriptSelector/ScriptSelector.odt | Bin 0 -> 8921 bytes .../ScriptSelector/ScriptSelector.java | 353 +++ .../ScriptSelector/ScriptSelector/container.gif | Bin 0 -> 164 bytes .../ScriptSelector/parcel-descriptor.xml | 33 + .../ScriptSelector/ScriptSelector/script.gif | Bin 0 -> 187 bytes .../ScriptSelector/ScriptSelector/soffice.gif | Bin 0 -> 136 bytes .../ScriptingFramework/ScriptSelector/build.xml | 96 + .../Spreadsheet/DataPilotReadme.txt | 48 + .../Spreadsheet/ExampleAddIn.components | 9 + .../DevelopersGuide/Spreadsheet/ExampleAddIn.java | 304 +++ .../DevelopersGuide/Spreadsheet/ExampleAddIn.ods | Bin 0 -> 8961 bytes .../Spreadsheet/ExampleDataPilotSource.components | 8 + .../Spreadsheet/ExampleDataPilotSource.java | 990 +++++++ .../Spreadsheet/GeneralTableSample.java | 231 ++ odk/examples/DevelopersGuide/Spreadsheet/Makefile | 309 +++ .../Spreadsheet/SpreadsheetDocHelper.java | 388 +++ .../Spreadsheet/SpreadsheetSample.java | 1347 +++++++++ .../DevelopersGuide/Spreadsheet/ViewSample.java | 164 ++ .../DevelopersGuide/Spreadsheet/XExampleAddIn.idl | 62 + odk/examples/DevelopersGuide/Text/Makefile | 95 + odk/examples/DevelopersGuide/Text/PrintDemo.odt | Bin 0 -> 6909 bytes .../DevelopersGuide/Text/TextDocuments.java | 1724 ++++++++++++ .../Text/TextTemplateWithUserFields.odt | Bin 0 -> 6641 bytes .../DevelopersGuide/UCB/ChildrenRetriever.java | 338 +++ .../DevelopersGuide/UCB/DataStreamComposer.java | 246 ++ .../DevelopersGuide/UCB/DataStreamRetriever.java | 227 ++ odk/examples/DevelopersGuide/UCB/Helper.java | 242 ++ odk/examples/DevelopersGuide/UCB/Makefile | 155 ++ .../DevelopersGuide/UCB/MyActiveDataSink.java | 74 + .../DevelopersGuide/UCB/MyInputStream.java | 180 ++ .../DevelopersGuide/UCB/PropertiesComposer.java | 289 ++ .../DevelopersGuide/UCB/PropertiesRetriever.java | 245 ++ .../DevelopersGuide/UCB/ResourceCreator.java | 304 +++ .../DevelopersGuide/UCB/ResourceManager.java | 280 ++ .../DevelopersGuide/UCB/ResourceRemover.java | 175 ++ odk/examples/DevelopersGuide/UCB/data/data.txt | 1 + odk/examples/DevelopersGuide/examples.html | 2880 ++++++++++++++++++++ odk/examples/OLE/activex/Makefile | 121 + odk/examples/OLE/activex/README.txt | 40 + odk/examples/OLE/activex/SOActiveX.cpp | 645 +++++ odk/examples/OLE/activex/SOActiveX.h | 168 ++ odk/examples/OLE/activex/SOActiveX.rgs | 33 + odk/examples/OLE/activex/SOComWindowPeer.cpp | 61 + odk/examples/OLE/activex/SOComWindowPeer.h | 156 ++ odk/examples/OLE/activex/SOComWindowPeer.rgs | 23 + odk/examples/OLE/activex/StdAfx2.cpp | 49 + odk/examples/OLE/activex/StdAfx2.h | 64 + odk/examples/OLE/activex/example.html | 44 + odk/examples/OLE/activex/resource.h | 57 + odk/examples/OLE/activex/so_activex.cpp | 110 + odk/examples/OLE/activex/so_activex.def | 5 + odk/examples/OLE/activex/so_activex.idl | 140 + odk/examples/OLE/activex/so_activex.rc | 136 + odk/examples/OLE/delphi/InsertTables/Project1.dpr | 14 + odk/examples/OLE/delphi/InsertTables/Project1.res | 0 .../OLE/delphi/InsertTables/SampleCode.pas | 393 +++ odk/examples/OLE/delphi/InsertTables/SampleUI.dfm | 4 + odk/examples/OLE/delphi/InsertTables/SampleUI.pas | 168 ++ odk/examples/OLE/delphi/StarOffice_Delphi.sxw | Bin 0 -> 34970 bytes odk/examples/OLE/delphi/StarOffice_and_Delphi.pdf | Bin 0 -> 60963 bytes odk/examples/OLE/vbscript/WriterDemo.vbs | 172 ++ odk/examples/OLE/vbscript/readme.txt | 4 + odk/examples/basic/drawing/dirtree.txt | 20 + .../basic/drawing/importexportofasciifiles.odg | Bin 0 -> 11125 bytes odk/examples/basic/forms_and_controls/beef.wmf | Bin 0 -> 9856 bytes odk/examples/basic/forms_and_controls/burger.wmf | Bin 0 -> 84308 bytes .../basic/forms_and_controls/burger_factory.odt | Bin 0 -> 18934 bytes odk/examples/basic/forms_and_controls/chicken.wmf | Bin 0 -> 14272 bytes odk/examples/basic/forms_and_controls/fish.wmf | Bin 0 -> 13716 bytes .../basic/forms_and_controls/vegetable.wmf | Bin 0 -> 17862 bytes odk/examples/basic/sheet/adapting_to_euroland.ods | Bin 0 -> 9964 bytes odk/examples/basic/stock_quotes_updater/stock.ods | Bin 0 -> 21540 bytes .../basic/text/creating_an_index/index.odt | Bin 0 -> 13160 bytes .../basic/text/creating_an_index/indexlist.txt | 9 + .../changing_appearance.odt | Bin 0 -> 9883 bytes .../inserting_bookmarks.odt | Bin 0 -> 10207 bytes .../replacing_text.odt | Bin 0 -> 10021 bytes .../using_regular_expressions.odt | Bin 0 -> 10072 bytes odk/examples/cpp/DocumentLoader/DocumentLoader.cxx | 150 + odk/examples/cpp/DocumentLoader/Makefile | 107 + odk/examples/cpp/DocumentLoader/test.odt | Bin 0 -> 11176 bytes odk/examples/cpp/complextoolbarcontrols/Addons.xcu | 187 ++ .../cpp/complextoolbarcontrols/CalcListener.cxx | 32 + .../cpp/complextoolbarcontrols/CalcWindowState.xcu | 38 + odk/examples/cpp/complextoolbarcontrols/Jobs.xcu | 39 + .../cpp/complextoolbarcontrols/ListenerHelper.cxx | 138 + .../cpp/complextoolbarcontrols/ListenerHelper.h | 85 + odk/examples/cpp/complextoolbarcontrols/Makefile | 182 ++ odk/examples/cpp/complextoolbarcontrols/MyJob.cxx | 97 + odk/examples/cpp/complextoolbarcontrols/MyJob.h | 91 + .../cpp/complextoolbarcontrols/MyListener.cxx | 134 + .../cpp/complextoolbarcontrols/MyListener.h | 116 + .../complextoolbarcontrols/MyProtocolHandler.cxx | 501 ++++ .../cpp/complextoolbarcontrols/MyProtocolHandler.h | 161 ++ .../cpp/complextoolbarcontrols/ProtocolHandler.xcu | 27 + .../cpp/complextoolbarcontrols/WriterListener.cxx | 40 + .../complextoolbarcontrols/WriterWindowState.xcu | 38 + .../cpp/complextoolbarcontrols/description.xml | 26 + .../cpp/complextoolbarcontrols/exports.cxx | 68 + .../cpp/complextoolbarcontrols/logo_big.png | Bin 0 -> 616 bytes .../cpp/complextoolbarcontrols/logo_small.png | Bin 0 -> 585 bytes odk/examples/cpp/counter/Makefile | 174 ++ odk/examples/cpp/counter/XCountable.idl | 58 + odk/examples/cpp/counter/counter.cxx | 183 ++ odk/examples/cpp/counter/countermain.cxx | 98 + odk/examples/cpp/custompanel/CalcWindowState.xcu | 39 + odk/examples/cpp/custompanel/DrawWindowState.xcu | 39 + odk/examples/cpp/custompanel/Factories.xcu | 39 + .../cpp/custompanel/ImpressWindowState.xcu | 39 + odk/examples/cpp/custompanel/Makefile | 171 ++ odk/examples/cpp/custompanel/WriterWindowState.xcu | 53 + odk/examples/cpp/custompanel/ctp_factory.cxx | 126 + odk/examples/cpp/custompanel/ctp_factory.hxx | 70 + odk/examples/cpp/custompanel/ctp_panel.cxx | 243 ++ odk/examples/cpp/custompanel/ctp_panel.hxx | 108 + odk/examples/cpp/custompanel/ctp_services.cxx | 63 + odk/examples/cpp/custompanel/description.xml | 33 + odk/examples/cpp/custompanel/manifest.xml | 35 + odk/examples/cpp/custompanel/panel.png | Bin 0 -> 202 bytes odk/examples/cpp/remoteclient/Makefile | 154 ++ odk/examples/cpp/remoteclient/remoteclient.cxx | 260 ++ odk/examples/examples.html | 834 ++++++ .../java/ConverterServlet/ConverterServlet.html | 64 + .../java/ConverterServlet/ConverterServlet.java | 325 +++ odk/examples/java/ConverterServlet/Makefile | 93 + odk/examples/java/ConverterServlet/README | 38 + odk/examples/java/ConverterServlet/web.xml | 76 + .../java/DocumentHandling/DocumentConverter.java | 226 ++ .../java/DocumentHandling/DocumentLoader.java | 94 + .../java/DocumentHandling/DocumentPrinter.java | 111 + .../java/DocumentHandling/DocumentSaver.java | 131 + odk/examples/java/DocumentHandling/Makefile | 144 + odk/examples/java/DocumentHandling/test/test1.odt | Bin 0 -> 397817 bytes odk/examples/java/Drawing/Makefile | 91 + odk/examples/java/Drawing/SDraw.java | 266 ++ .../EmbedDocument/Container1/EmbedContApp.java | 1044 +++++++ .../EmbedDocument/Container1/EmbedContFrame.java | 128 + .../java/EmbedDocument/Container1/Makefile | 65 + .../EmbedDocument/EmbeddedObject/EditorFrame.java | 134 + .../EmbeddedObject/EmbeddedObject.odt | Bin 0 -> 9975 bytes .../EmbeddedObject/EmbeddedObject.xcu | 45 + .../java/EmbedDocument/EmbeddedObject/Makefile | 148 + .../EmbeddedObject/OwnEmbeddedObject.components | 8 + .../EmbeddedObject/OwnEmbeddedObject.java | 1123 ++++++++ .../EmbeddedObject/OwnEmbeddedObjectFactory.java | 106 + odk/examples/java/Inspector/Addons.xcu | 40 + .../java/Inspector/HideableMutableTreeNode.java | 106 + odk/examples/java/Inspector/HideableTreeModel.java | 258 ++ odk/examples/java/Inspector/Inspector.java | 459 ++++ odk/examples/java/Inspector/InspectorAddon.java | 224 ++ odk/examples/java/Inspector/InspectorPane.java | 577 ++++ odk/examples/java/Inspector/InstanceInspector.idl | 55 + .../java/Inspector/InstanceInspectorTest.odt | Bin 0 -> 12272 bytes odk/examples/java/Inspector/Introspector.java | 643 +++++ odk/examples/java/Inspector/Makefile | 194 ++ .../java/Inspector/MethodParametersDialog.java | 351 +++ odk/examples/java/Inspector/ObjectInspector.xcs | 34 + odk/examples/java/Inspector/ObjectInspector.xcu | 35 + odk/examples/java/Inspector/ProtocolHandler.xcu | 28 + .../java/Inspector/ProtocolHandlerAddon.java | 273 ++ .../java/Inspector/SourceCodeGenerator.java | 1635 +++++++++++ .../java/Inspector/SwingDialogProvider.java | 444 +++ .../java/Inspector/SwingTreeControlProvider.java | 423 +++ .../java/Inspector/SwingTreePathProvider.java | 60 + .../java/Inspector/SwingUnoFacetteNode.java | 84 + .../java/Inspector/SwingUnoMethodNode.java | 144 + odk/examples/java/Inspector/SwingUnoNode.java | 160 ++ .../java/Inspector/SwingUnoPropertyNode.java | 102 + odk/examples/java/Inspector/TDocSupplier.java | 166 ++ odk/examples/java/Inspector/TestInspector.java | 88 + odk/examples/java/Inspector/UnoMethodNode.java | 228 ++ odk/examples/java/Inspector/UnoNode.java | 351 +++ odk/examples/java/Inspector/UnoPropertyNode.java | 218 ++ odk/examples/java/Inspector/UnoTreeRenderer.java | 122 + odk/examples/java/Inspector/XDialogProvider.java | 68 + odk/examples/java/Inspector/XInstanceInspector.idl | 59 + .../Inspector/XLanguageSourceCodeGenerator.java | 108 + .../java/Inspector/XTreeControlProvider.java | 96 + odk/examples/java/Inspector/XTreePathProvider.java | 33 + odk/examples/java/Inspector/XUnoFacetteNode.java | 66 + odk/examples/java/Inspector/XUnoMethodNode.java | 70 + odk/examples/java/Inspector/XUnoNode.java | 87 + odk/examples/java/Inspector/XUnoPropertyNode.java | 54 + .../java/Inspector/images/containers_16.png | Bin 0 -> 233 bytes odk/examples/java/Inspector/images/content_16.png | Bin 0 -> 370 bytes .../java/Inspector/images/interfaces_16.png | Bin 0 -> 433 bytes odk/examples/java/Inspector/images/methods_16.png | Bin 0 -> 380 bytes .../java/Inspector/images/properties_16.png | Bin 0 -> 242 bytes odk/examples/java/Inspector/images/services_16.png | Bin 0 -> 258 bytes odk/examples/java/Inspector/manifest.mf | 3 + .../MinimalComponent/BuildMinimalComponent.xml | 76 + odk/examples/java/MinimalComponent/Makefile | 204 ++ .../MinimalComponent/MinimalComponent.components | 8 + .../java/MinimalComponent/MinimalComponent.idl | 55 + .../java/MinimalComponent/MinimalComponent.java | 156 ++ .../MinimalComponent/TestMinimalComponent.java | 67 + odk/examples/java/NotesAccess/Makefile | 112 + odk/examples/java/NotesAccess/NotesAccess.java | 282 ++ odk/examples/java/NotesAccess/Stocks.nsf | Bin 0 -> 262144 bytes odk/examples/java/PropertySet/Makefile | 135 + odk/examples/java/PropertySet/PropTest.components | 8 + odk/examples/java/PropertySet/PropTest.java | 262 ++ odk/examples/java/PropertySet/PropertySet.odt | Bin 0 -> 8391 bytes .../java/Spreadsheet/CalcAddins.components | 9 + odk/examples/java/Spreadsheet/CalcAddins.java | 283 ++ odk/examples/java/Spreadsheet/CalcAddins.ods | Bin 0 -> 8653 bytes odk/examples/java/Spreadsheet/ChartTypeChange.java | 347 +++ odk/examples/java/Spreadsheet/EuroAdaption.java | 383 +++ odk/examples/java/Spreadsheet/Makefile | 214 ++ odk/examples/java/Spreadsheet/SCalc.java | 408 +++ odk/examples/java/Spreadsheet/XCalcAddins.idl | 103 + odk/examples/java/Storage/Makefile | 75 + .../java/Storage/StorageFunctionality.java | 156 ++ odk/examples/java/Storage/StorageTest.java | 25 + odk/examples/java/Storage/Test01.java | 169 ++ odk/examples/java/Storage/Test02.java | 165 ++ odk/examples/java/Storage/Test03.java | 220 ++ odk/examples/java/Storage/Test04.java | 282 ++ odk/examples/java/Storage/Test05.java | 278 ++ odk/examples/java/Storage/Test06.java | 285 ++ odk/examples/java/Storage/Test07.java | 148 + odk/examples/java/Storage/Test08.java | 224 ++ odk/examples/java/Storage/Test09.java | 134 + odk/examples/java/Storage/TestHelper.java | 881 ++++++ odk/examples/java/Text/BookmarkInsertion.java | 275 ++ odk/examples/java/Text/GraphicsInserter.java | 195 ++ odk/examples/java/Text/HardFormatting.java | 279 ++ odk/examples/java/Text/Makefile | 135 + odk/examples/java/Text/SWriter.java | 390 +++ odk/examples/java/Text/StyleCreation.java | 224 ++ odk/examples/java/Text/StyleInitialization.java | 311 +++ odk/examples/java/Text/TextDocumentStructure.java | 201 ++ odk/examples/java/Text/TextReplace.java | 224 ++ odk/examples/java/Text/WriterSelector.java | 161 ++ odk/examples/java/Text/oo_smiley.gif | Bin 0 -> 46109 bytes odk/examples/java/ToDo/Makefile | 167 ++ odk/examples/java/ToDo/ToDo.components | 8 + odk/examples/java/ToDo/ToDo.idl | 53 + odk/examples/java/ToDo/ToDo.java | 932 +++++++ odk/examples/java/ToDo/ToDo.ods | Bin 0 -> 13276 bytes odk/examples/java/ToDo/XToDo.idl | 53 + odk/examples/python/toolpanel/CalcWindowState.xcu | 29 + odk/examples/python/toolpanel/Factory.xcu | 34 + .../python/toolpanel/META-INF/manifest.xml | 23 + odk/examples/python/toolpanel/Makefile | 29 + odk/examples/python/toolpanel/description.xml | 13 + odk/examples/python/toolpanel/readme | 13 + .../python/toolpanel/toolPanelPocBasic/Module1.xba | 29 + .../python/toolpanel/toolPanelPocBasic/dialog.xlb | 3 + .../python/toolpanel/toolPanelPocBasic/script.xlb | 5 + odk/examples/python/toolpanel/toolpanel.component | 16 + odk/examples/python/toolpanel/toolpanel.py | 139 + odk/examples/python/toolpanel/toolpanels/poc.xdl | 11 + 563 files changed, 91922 insertions(+) create mode 100644 odk/examples/CLI/CSharp/Spreadsheet/GeneralTableSample.cs create mode 100644 odk/examples/CLI/CSharp/Spreadsheet/Makefile create mode 100644 odk/examples/CLI/CSharp/Spreadsheet/SpreadsheetDocHelper.cs create mode 100644 odk/examples/CLI/CSharp/Spreadsheet/SpreadsheetSample.cs create mode 100644 odk/examples/CLI/CSharp/Spreadsheet/ViewSample.cs create mode 100644 odk/examples/CLI/VB.NET/WriterDemo/Makefile create mode 100644 odk/examples/CLI/VB.NET/WriterDemo/WriterDemo.vb create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/CreatingDialogs.odt create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/Makefile create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/SampleDialog.java create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/FirstStepsBasic.odt create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/Makefile create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls.odt create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/FileDialog.xba create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/FileDialogDlg.xdl create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/MultiPage.xba create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/MultiPageDlg.xdl create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ProgressBar.xba create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ProgressBarDlg.xdl create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ScrollBar.xba create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ScrollBarDlg.xdl create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/dialog.xlb create mode 100644 odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/script.xlb create mode 100644 odk/examples/DevelopersGuide/Charts/AddInChart.ods create mode 100644 odk/examples/DevelopersGuide/Charts/CalcHelper.java create mode 100644 odk/examples/DevelopersGuide/Charts/ChartHelper.java create mode 100644 odk/examples/DevelopersGuide/Charts/ChartInCalc.java create mode 100644 odk/examples/DevelopersGuide/Charts/ChartInDraw.java create mode 100644 odk/examples/DevelopersGuide/Charts/ChartInWriter.java create mode 100644 odk/examples/DevelopersGuide/Charts/Helper.java create mode 100644 odk/examples/DevelopersGuide/Charts/JavaSampleChartAddIn.components create mode 100644 odk/examples/DevelopersGuide/Charts/JavaSampleChartAddIn.java create mode 100644 odk/examples/DevelopersGuide/Charts/ListenAtCalcRangeInDraw.java create mode 100644 odk/examples/DevelopersGuide/Charts/Makefile create mode 100644 odk/examples/DevelopersGuide/Charts/SelectionChangeListener.java create mode 100644 odk/examples/DevelopersGuide/Charts/bullet.gif create mode 100644 odk/examples/DevelopersGuide/Components/Addons/JobsAddon/Addons.xcu create mode 100644 odk/examples/DevelopersGuide/Components/Addons/JobsAddon/AsyncJob.components create mode 100644 odk/examples/DevelopersGuide/Components/Addons/JobsAddon/AsyncJob.java create mode 100644 odk/examples/DevelopersGuide/Components/Addons/JobsAddon/Jobs.xcu create mode 100644 odk/examples/DevelopersGuide/Components/Addons/JobsAddon/Makefile create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/Addons.xcu create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/Makefile create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/ProtocolHandler.xcu create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/addon.cxx create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/addon.hxx create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/component.cxx create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/Addons.xcu create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/Makefile create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandler.xcu create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandlerAddon.java create mode 100644 odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandlerAddon_java.components create mode 100644 odk/examples/DevelopersGuide/Components/CppComponent/Makefile create mode 100644 odk/examples/DevelopersGuide/Components/CppComponent/SimpleComponent.odt create mode 100644 odk/examples/DevelopersGuide/Components/CppComponent/TestCppComponent.cxx create mode 100644 odk/examples/DevelopersGuide/Components/CppComponent/service1_impl.cxx create mode 100644 odk/examples/DevelopersGuide/Components/CppComponent/service2_impl.cxx create mode 100644 odk/examples/DevelopersGuide/Components/CppComponent/some.idl create mode 100644 odk/examples/DevelopersGuide/Components/JavaComponent/JavaComponent.components create mode 100644 odk/examples/DevelopersGuide/Components/JavaComponent/Makefile create mode 100644 odk/examples/DevelopersGuide/Components/JavaComponent/SomethingA.idl create mode 100644 odk/examples/DevelopersGuide/Components/JavaComponent/SomethingB.idl create mode 100644 odk/examples/DevelopersGuide/Components/JavaComponent/TestComponentA.java create mode 100644 odk/examples/DevelopersGuide/Components/JavaComponent/TestComponentB.java create mode 100644 odk/examples/DevelopersGuide/Components/JavaComponent/TestJavaComponent.java create mode 100644 odk/examples/DevelopersGuide/Components/JavaComponent/TestServiceProvider.java create mode 100644 odk/examples/DevelopersGuide/Components/JavaComponent/XSomethingA.idl create mode 100644 odk/examples/DevelopersGuide/Components/JavaComponent/XSomethingB.idl create mode 100644 odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.components create mode 100644 odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.idl create mode 100644 odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.java create mode 100644 odk/examples/DevelopersGuide/Components/SimpleLicense/Makefile create mode 100644 odk/examples/DevelopersGuide/Components/SimpleLicense/description.xml create mode 100644 odk/examples/DevelopersGuide/Components/SimpleLicense/registration/license_de.txt create mode 100644 odk/examples/DevelopersGuide/Components/SimpleLicense/registration/license_en_US.txt create mode 100644 odk/examples/DevelopersGuide/Components/Thumbs/Makefile create mode 100644 odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/ImageShrink.components create mode 100644 odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/ImageShrink.java create mode 100644 odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/Makefile create mode 100644 odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/Thumbs.java create mode 100644 odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/ImageShrink.idl create mode 100644 odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/Makefile create mode 100644 odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/XImageShrink.idl create mode 100644 odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/XImageShrinkFilter.idl create mode 100644 odk/examples/DevelopersGuide/Components/Thumbs/thumbs.mk create mode 100644 odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.components create mode 100644 odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.java create mode 100644 odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.odt create mode 100644 odk/examples/DevelopersGuide/Components/dialogcomponent/Makefile create mode 100644 odk/examples/DevelopersGuide/Components/dialogcomponent/TestDialogHandler.idl create mode 100644 odk/examples/DevelopersGuide/Components/dialogcomponent/XTestDialogHandler.idl create mode 100644 odk/examples/DevelopersGuide/Config/ConfigExamples.java create mode 100644 odk/examples/DevelopersGuide/Config/Makefile create mode 100644 odk/examples/DevelopersGuide/Database/CodeSamples.java create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/How_to_write_my_own_driver.txt create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/Makefile create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/OSubComponent.hxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/OTypeInfo.hxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SConnection.cxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SConnection.hxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SDatabaseMetaData.cxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SDatabaseMetaData.hxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SDriver.cxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SDriver.hxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SPreparedStatement.cxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SPreparedStatement.hxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSet.cxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSet.hxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSetMetaData.cxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSetMetaData.hxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SServices.cxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SStatement.cxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/SStatement.hxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/propertyids.cxx create mode 100644 odk/examples/DevelopersGuide/Database/DriverSkeleton/propertyids.hxx create mode 100644 odk/examples/DevelopersGuide/Database/Makefile create mode 100644 odk/examples/DevelopersGuide/Database/OpenQuery.java create mode 100644 odk/examples/DevelopersGuide/Database/RowSet.java create mode 100644 odk/examples/DevelopersGuide/Database/RowSetEventListener.java create mode 100644 odk/examples/DevelopersGuide/Database/Sales.java create mode 100644 odk/examples/DevelopersGuide/Database/SalesMan.java create mode 100644 odk/examples/DevelopersGuide/Database/sdbcx.java create mode 100644 odk/examples/DevelopersGuide/Drawing/ChangeOrderDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/ControlAndSelectDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/CustomShowDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/DrawViewDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/DrawingDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/FillAndLineStyleDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/GluePointDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/GraphicExportDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/Helper.java create mode 100644 odk/examples/DevelopersGuide/Drawing/LayerDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/Makefile create mode 100644 odk/examples/DevelopersGuide/Drawing/ObjectTransformationDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/Organigram.java create mode 100644 odk/examples/DevelopersGuide/Drawing/PageHelper.java create mode 100644 odk/examples/DevelopersGuide/Drawing/PresentationDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/ShapeHelper.java create mode 100644 odk/examples/DevelopersGuide/Drawing/SimplePresentation.odp create mode 100644 odk/examples/DevelopersGuide/Drawing/StyleDemo.java create mode 100644 odk/examples/DevelopersGuide/Drawing/TextDemo.java create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/Addons.xcu create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/Dialog1.xdl create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/Module1.xba create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/dialog.xlb create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/script.xlb create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/META-INF/manifest.xml create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/Makefile create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/description.xml create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/page1.xhp create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/page2.xhp create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/subfolder/anotherpage.xhp create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/page1.xhp create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/page2.xhp create mode 100644 odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/subfolder/anotherpage.xhp create mode 100644 odk/examples/DevelopersGuide/FirstSteps/FirstConnection.java create mode 100644 odk/examples/DevelopersGuide/FirstSteps/FirstLoadComponent.java create mode 100644 odk/examples/DevelopersGuide/FirstSteps/FirstUnoContact.java create mode 100644 odk/examples/DevelopersGuide/FirstSteps/HelloTextTableShape.java create mode 100644 odk/examples/DevelopersGuide/FirstSteps/Makefile create mode 100644 odk/examples/DevelopersGuide/FirstSteps/build_FirstUnoContact.xml create mode 100644 odk/examples/DevelopersGuide/Forms/BooleanValidator.java create mode 100644 odk/examples/DevelopersGuide/Forms/ButtonOperator.java create mode 100644 odk/examples/DevelopersGuide/Forms/ComponentTreeTraversal.java create mode 100644 odk/examples/DevelopersGuide/Forms/ControlLock.java create mode 100644 odk/examples/DevelopersGuide/Forms/ControlValidation.java create mode 100644 odk/examples/DevelopersGuide/Forms/ControlValidator.java create mode 100644 odk/examples/DevelopersGuide/Forms/DataAwareness.java create mode 100644 odk/examples/DevelopersGuide/Forms/DateValidator.java create mode 100644 odk/examples/DevelopersGuide/Forms/DocumentBasedExample.java create mode 100644 odk/examples/DevelopersGuide/Forms/DocumentHelper.java create mode 100644 odk/examples/DevelopersGuide/Forms/DocumentType.java create mode 100644 odk/examples/DevelopersGuide/Forms/DocumentViewHelper.java create mode 100644 odk/examples/DevelopersGuide/Forms/FLTools.java create mode 100644 odk/examples/DevelopersGuide/Forms/FormLayer.java create mode 100644 odk/examples/DevelopersGuide/Forms/GridFieldValidator.java create mode 100644 odk/examples/DevelopersGuide/Forms/HsqlDatabase.java create mode 100644 odk/examples/DevelopersGuide/Forms/InteractionRequest.java create mode 100644 odk/examples/DevelopersGuide/Forms/KeyGenerator.java create mode 100644 odk/examples/DevelopersGuide/Forms/ListSelectionValidator.java create mode 100644 odk/examples/DevelopersGuide/Forms/Makefile create mode 100644 odk/examples/DevelopersGuide/Forms/NumericValidator.java create mode 100644 odk/examples/DevelopersGuide/Forms/ProgrammaticScriptAssignment.odt create mode 100644 odk/examples/DevelopersGuide/Forms/RowSet.java create mode 100644 odk/examples/DevelopersGuide/Forms/SalesFilter.java create mode 100644 odk/examples/DevelopersGuide/Forms/SingleControlValidation.java create mode 100644 odk/examples/DevelopersGuide/Forms/SpreadsheetDocument.java create mode 100644 odk/examples/DevelopersGuide/Forms/SpreadsheetValueBinding.java create mode 100644 odk/examples/DevelopersGuide/Forms/SpreadsheetView.java create mode 100644 odk/examples/DevelopersGuide/Forms/TableCellTextBinding.java create mode 100644 odk/examples/DevelopersGuide/Forms/TextValidator.java create mode 100644 odk/examples/DevelopersGuide/Forms/TimeValidator.java create mode 100644 odk/examples/DevelopersGuide/Forms/UNO.java create mode 100644 odk/examples/DevelopersGuide/Forms/URLHelper.java create mode 100644 odk/examples/DevelopersGuide/Forms/ValueBinding.java create mode 100644 odk/examples/DevelopersGuide/Forms/WaitForInput.java create mode 100644 odk/examples/DevelopersGuide/GUI/DialogDocument.java create mode 100644 odk/examples/DevelopersGuide/GUI/ImageControlSample.java create mode 100644 odk/examples/DevelopersGuide/GUI/Makefile create mode 100644 odk/examples/DevelopersGuide/GUI/MessageBox.java create mode 100644 odk/examples/DevelopersGuide/GUI/RoadmapItemStateChangeListener.java create mode 100644 odk/examples/DevelopersGuide/GUI/SystemDialog.java create mode 100644 odk/examples/DevelopersGuide/GUI/UnoDialogSample.java create mode 100644 odk/examples/DevelopersGuide/GUI/UnoDialogSample2.java create mode 100644 odk/examples/DevelopersGuide/GUI/UnoMenu.java create mode 100644 odk/examples/DevelopersGuide/GUI/UnoMenu2.java create mode 100644 odk/examples/DevelopersGuide/GUI/oologo.gif create mode 100644 odk/examples/DevelopersGuide/OfficeBean/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeBean/OOoBeanViewer.java create mode 100644 odk/examples/DevelopersGuide/OfficeBean/OfficeIconColor16.jpg create mode 100644 odk/examples/DevelopersGuide/OfficeBean/OfficeIconColor32.jpg create mode 100644 odk/examples/DevelopersGuide/OfficeBean/OfficeIconMono16.jpg create mode 100644 odk/examples/DevelopersGuide/OfficeBean/OfficeIconMono32.jpg create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Clipboard/Clipboard.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Clipboard/ClipboardListener.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Clipboard/ClipboardOwner.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Clipboard/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Clipboard/TextTransferable.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/ContextMenuInterceptor.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/CustomizeView.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Desk.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/DocumentView.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/FunctionHelper.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/IOnewayLink.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/IShutdownListener.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Install.txt create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Interceptor.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/JavaWindowPeerFake.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/NativeView.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/OfficeConnect.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/OnewayExecutor.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/StatusListener.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/StatusView.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/ViewContainer.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/nativeview.c create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/nativeview.h create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.c create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.def create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.h create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DisableCommands/DisableCommandsTest.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/DisableCommands/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/AsciiReplaceFilter.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/FilterOptions.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/SampleFilter.components create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/TypeDetection.xcu create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/FlatXmlTypeDetection.xcu create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/fdcomp.cxx create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/filterdetect.cxx create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/filterdetect.hxx create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/FlatXml.cxx create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/FlatXmlFilter_cpp.xcu create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXml.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXmlFilter_java.components create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXmlFilter_java.xcu create mode 100644 odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/LinguisticExamples.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/OneInstanceFactory.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper_Hyph.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper_Spell.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleHyphenator.components create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleHyphenator.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleSpellChecker.components create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleSpellChecker.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleThesaurus.components create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleThesaurus.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/XHyphenatedWord_impl.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/XMeaning_impl.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/XPossibleHyphens_impl.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Linguistic/XSpellAlternatives_impl.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/MenuElement.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/Number_Formats.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/OfficeConnect.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/PathSettings/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/PathSettings/PathSettingsTest.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/PathSubstitution/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/PathSubstitution/PathSubstitutionTest.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/TerminationTest/Makefile create mode 100644 odk/examples/DevelopersGuide/OfficeDev/TerminationTest/TerminateListener.java create mode 100644 odk/examples/DevelopersGuide/OfficeDev/TerminationTest/TerminationTest.java create mode 100644 odk/examples/DevelopersGuide/ProfUNO/CppBinding/Makefile create mode 100644 odk/examples/DevelopersGuide/ProfUNO/CppBinding/office_connect.cxx create mode 100644 odk/examples/DevelopersGuide/ProfUNO/CppBinding/string_samples.cxx create mode 100644 odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/ConnectionAwareClient.java create mode 100644 odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/Makefile create mode 100644 odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/UrlResolver.java create mode 100644 odk/examples/DevelopersGuide/ProfUNO/Lifetime/Makefile create mode 100644 odk/examples/DevelopersGuide/ProfUNO/Lifetime/MyUnoObject.java create mode 100644 odk/examples/DevelopersGuide/ProfUNO/Lifetime/object_lifetime.cxx create mode 100644 odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_cpp/Makefile create mode 100644 odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_cpp/SimpleBootstrap_cpp.cxx create mode 100644 odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/Makefile create mode 100644 odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/SimpleBootstrap_java.java create mode 100644 odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/manifest.mf create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/SayHello/META-INF/manifest.xml create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/SayHello/Makefile create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello.odt create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello/SayHello.java create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello/parcel-descriptor.xml create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/SayHello/build.xml create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/META-INF/manifest.xml create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/Makefile create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector.odt create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/ScriptSelector.java create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/container.gif create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/parcel-descriptor.xml create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/script.gif create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/soffice.gif create mode 100644 odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/build.xml create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/DataPilotReadme.txt create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.components create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.java create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.ods create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/ExampleDataPilotSource.components create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/ExampleDataPilotSource.java create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/GeneralTableSample.java create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/Makefile create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/SpreadsheetDocHelper.java create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/SpreadsheetSample.java create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/ViewSample.java create mode 100644 odk/examples/DevelopersGuide/Spreadsheet/XExampleAddIn.idl create mode 100644 odk/examples/DevelopersGuide/Text/Makefile create mode 100644 odk/examples/DevelopersGuide/Text/PrintDemo.odt create mode 100644 odk/examples/DevelopersGuide/Text/TextDocuments.java create mode 100644 odk/examples/DevelopersGuide/Text/TextTemplateWithUserFields.odt create mode 100644 odk/examples/DevelopersGuide/UCB/ChildrenRetriever.java create mode 100644 odk/examples/DevelopersGuide/UCB/DataStreamComposer.java create mode 100644 odk/examples/DevelopersGuide/UCB/DataStreamRetriever.java create mode 100644 odk/examples/DevelopersGuide/UCB/Helper.java create mode 100644 odk/examples/DevelopersGuide/UCB/Makefile create mode 100644 odk/examples/DevelopersGuide/UCB/MyActiveDataSink.java create mode 100644 odk/examples/DevelopersGuide/UCB/MyInputStream.java create mode 100644 odk/examples/DevelopersGuide/UCB/PropertiesComposer.java create mode 100644 odk/examples/DevelopersGuide/UCB/PropertiesRetriever.java create mode 100644 odk/examples/DevelopersGuide/UCB/ResourceCreator.java create mode 100644 odk/examples/DevelopersGuide/UCB/ResourceManager.java create mode 100644 odk/examples/DevelopersGuide/UCB/ResourceRemover.java create mode 100644 odk/examples/DevelopersGuide/UCB/data/data.txt create mode 100644 odk/examples/DevelopersGuide/examples.html create mode 100644 odk/examples/OLE/activex/Makefile create mode 100644 odk/examples/OLE/activex/README.txt create mode 100644 odk/examples/OLE/activex/SOActiveX.cpp create mode 100644 odk/examples/OLE/activex/SOActiveX.h create mode 100644 odk/examples/OLE/activex/SOActiveX.rgs create mode 100644 odk/examples/OLE/activex/SOComWindowPeer.cpp create mode 100644 odk/examples/OLE/activex/SOComWindowPeer.h create mode 100644 odk/examples/OLE/activex/SOComWindowPeer.rgs create mode 100644 odk/examples/OLE/activex/StdAfx2.cpp create mode 100644 odk/examples/OLE/activex/StdAfx2.h create mode 100644 odk/examples/OLE/activex/example.html create mode 100644 odk/examples/OLE/activex/resource.h create mode 100644 odk/examples/OLE/activex/so_activex.cpp create mode 100644 odk/examples/OLE/activex/so_activex.def create mode 100644 odk/examples/OLE/activex/so_activex.idl create mode 100644 odk/examples/OLE/activex/so_activex.rc create mode 100644 odk/examples/OLE/delphi/InsertTables/Project1.dpr create mode 100644 odk/examples/OLE/delphi/InsertTables/Project1.res create mode 100644 odk/examples/OLE/delphi/InsertTables/SampleCode.pas create mode 100644 odk/examples/OLE/delphi/InsertTables/SampleUI.dfm create mode 100644 odk/examples/OLE/delphi/InsertTables/SampleUI.pas create mode 100644 odk/examples/OLE/delphi/StarOffice_Delphi.sxw create mode 100644 odk/examples/OLE/delphi/StarOffice_and_Delphi.pdf create mode 100644 odk/examples/OLE/vbscript/WriterDemo.vbs create mode 100644 odk/examples/OLE/vbscript/readme.txt create mode 100644 odk/examples/basic/drawing/dirtree.txt create mode 100644 odk/examples/basic/drawing/importexportofasciifiles.odg create mode 100644 odk/examples/basic/forms_and_controls/beef.wmf create mode 100644 odk/examples/basic/forms_and_controls/burger.wmf create mode 100644 odk/examples/basic/forms_and_controls/burger_factory.odt create mode 100644 odk/examples/basic/forms_and_controls/chicken.wmf create mode 100644 odk/examples/basic/forms_and_controls/fish.wmf create mode 100644 odk/examples/basic/forms_and_controls/vegetable.wmf create mode 100644 odk/examples/basic/sheet/adapting_to_euroland.ods create mode 100644 odk/examples/basic/stock_quotes_updater/stock.ods create mode 100644 odk/examples/basic/text/creating_an_index/index.odt create mode 100644 odk/examples/basic/text/creating_an_index/indexlist.txt create mode 100644 odk/examples/basic/text/modifying_text_automatically/changing_appearance.odt create mode 100644 odk/examples/basic/text/modifying_text_automatically/inserting_bookmarks.odt create mode 100644 odk/examples/basic/text/modifying_text_automatically/replacing_text.odt create mode 100644 odk/examples/basic/text/modifying_text_automatically/using_regular_expressions.odt create mode 100644 odk/examples/cpp/DocumentLoader/DocumentLoader.cxx create mode 100644 odk/examples/cpp/DocumentLoader/Makefile create mode 100644 odk/examples/cpp/DocumentLoader/test.odt create mode 100644 odk/examples/cpp/complextoolbarcontrols/Addons.xcu create mode 100644 odk/examples/cpp/complextoolbarcontrols/CalcListener.cxx create mode 100644 odk/examples/cpp/complextoolbarcontrols/CalcWindowState.xcu create mode 100644 odk/examples/cpp/complextoolbarcontrols/Jobs.xcu create mode 100644 odk/examples/cpp/complextoolbarcontrols/ListenerHelper.cxx create mode 100644 odk/examples/cpp/complextoolbarcontrols/ListenerHelper.h create mode 100644 odk/examples/cpp/complextoolbarcontrols/Makefile create mode 100644 odk/examples/cpp/complextoolbarcontrols/MyJob.cxx create mode 100644 odk/examples/cpp/complextoolbarcontrols/MyJob.h create mode 100644 odk/examples/cpp/complextoolbarcontrols/MyListener.cxx create mode 100644 odk/examples/cpp/complextoolbarcontrols/MyListener.h create mode 100644 odk/examples/cpp/complextoolbarcontrols/MyProtocolHandler.cxx create mode 100644 odk/examples/cpp/complextoolbarcontrols/MyProtocolHandler.h create mode 100644 odk/examples/cpp/complextoolbarcontrols/ProtocolHandler.xcu create mode 100644 odk/examples/cpp/complextoolbarcontrols/WriterListener.cxx create mode 100644 odk/examples/cpp/complextoolbarcontrols/WriterWindowState.xcu create mode 100644 odk/examples/cpp/complextoolbarcontrols/description.xml create mode 100644 odk/examples/cpp/complextoolbarcontrols/exports.cxx create mode 100644 odk/examples/cpp/complextoolbarcontrols/logo_big.png create mode 100644 odk/examples/cpp/complextoolbarcontrols/logo_small.png create mode 100644 odk/examples/cpp/counter/Makefile create mode 100644 odk/examples/cpp/counter/XCountable.idl create mode 100644 odk/examples/cpp/counter/counter.cxx create mode 100644 odk/examples/cpp/counter/countermain.cxx create mode 100644 odk/examples/cpp/custompanel/CalcWindowState.xcu create mode 100644 odk/examples/cpp/custompanel/DrawWindowState.xcu create mode 100644 odk/examples/cpp/custompanel/Factories.xcu create mode 100644 odk/examples/cpp/custompanel/ImpressWindowState.xcu create mode 100644 odk/examples/cpp/custompanel/Makefile create mode 100644 odk/examples/cpp/custompanel/WriterWindowState.xcu create mode 100644 odk/examples/cpp/custompanel/ctp_factory.cxx create mode 100644 odk/examples/cpp/custompanel/ctp_factory.hxx create mode 100644 odk/examples/cpp/custompanel/ctp_panel.cxx create mode 100644 odk/examples/cpp/custompanel/ctp_panel.hxx create mode 100644 odk/examples/cpp/custompanel/ctp_services.cxx create mode 100644 odk/examples/cpp/custompanel/description.xml create mode 100644 odk/examples/cpp/custompanel/manifest.xml create mode 100644 odk/examples/cpp/custompanel/panel.png create mode 100644 odk/examples/cpp/remoteclient/Makefile create mode 100644 odk/examples/cpp/remoteclient/remoteclient.cxx create mode 100644 odk/examples/examples.html create mode 100644 odk/examples/java/ConverterServlet/ConverterServlet.html create mode 100644 odk/examples/java/ConverterServlet/ConverterServlet.java create mode 100644 odk/examples/java/ConverterServlet/Makefile create mode 100644 odk/examples/java/ConverterServlet/README create mode 100644 odk/examples/java/ConverterServlet/web.xml create mode 100644 odk/examples/java/DocumentHandling/DocumentConverter.java create mode 100644 odk/examples/java/DocumentHandling/DocumentLoader.java create mode 100644 odk/examples/java/DocumentHandling/DocumentPrinter.java create mode 100644 odk/examples/java/DocumentHandling/DocumentSaver.java create mode 100644 odk/examples/java/DocumentHandling/Makefile create mode 100644 odk/examples/java/DocumentHandling/test/test1.odt create mode 100644 odk/examples/java/Drawing/Makefile create mode 100644 odk/examples/java/Drawing/SDraw.java create mode 100644 odk/examples/java/EmbedDocument/Container1/EmbedContApp.java create mode 100644 odk/examples/java/EmbedDocument/Container1/EmbedContFrame.java create mode 100644 odk/examples/java/EmbedDocument/Container1/Makefile create mode 100644 odk/examples/java/EmbedDocument/EmbeddedObject/EditorFrame.java create mode 100644 odk/examples/java/EmbedDocument/EmbeddedObject/EmbeddedObject.odt create mode 100644 odk/examples/java/EmbedDocument/EmbeddedObject/EmbeddedObject.xcu create mode 100644 odk/examples/java/EmbedDocument/EmbeddedObject/Makefile create mode 100644 odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObject.components create mode 100644 odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObject.java create mode 100644 odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObjectFactory.java create mode 100644 odk/examples/java/Inspector/Addons.xcu create mode 100644 odk/examples/java/Inspector/HideableMutableTreeNode.java create mode 100644 odk/examples/java/Inspector/HideableTreeModel.java create mode 100644 odk/examples/java/Inspector/Inspector.java create mode 100644 odk/examples/java/Inspector/InspectorAddon.java create mode 100644 odk/examples/java/Inspector/InspectorPane.java create mode 100644 odk/examples/java/Inspector/InstanceInspector.idl create mode 100644 odk/examples/java/Inspector/InstanceInspectorTest.odt create mode 100644 odk/examples/java/Inspector/Introspector.java create mode 100644 odk/examples/java/Inspector/Makefile create mode 100644 odk/examples/java/Inspector/MethodParametersDialog.java create mode 100644 odk/examples/java/Inspector/ObjectInspector.xcs create mode 100644 odk/examples/java/Inspector/ObjectInspector.xcu create mode 100644 odk/examples/java/Inspector/ProtocolHandler.xcu create mode 100644 odk/examples/java/Inspector/ProtocolHandlerAddon.java create mode 100644 odk/examples/java/Inspector/SourceCodeGenerator.java create mode 100644 odk/examples/java/Inspector/SwingDialogProvider.java create mode 100644 odk/examples/java/Inspector/SwingTreeControlProvider.java create mode 100644 odk/examples/java/Inspector/SwingTreePathProvider.java create mode 100644 odk/examples/java/Inspector/SwingUnoFacetteNode.java create mode 100644 odk/examples/java/Inspector/SwingUnoMethodNode.java create mode 100644 odk/examples/java/Inspector/SwingUnoNode.java create mode 100644 odk/examples/java/Inspector/SwingUnoPropertyNode.java create mode 100644 odk/examples/java/Inspector/TDocSupplier.java create mode 100644 odk/examples/java/Inspector/TestInspector.java create mode 100644 odk/examples/java/Inspector/UnoMethodNode.java create mode 100644 odk/examples/java/Inspector/UnoNode.java create mode 100644 odk/examples/java/Inspector/UnoPropertyNode.java create mode 100644 odk/examples/java/Inspector/UnoTreeRenderer.java create mode 100644 odk/examples/java/Inspector/XDialogProvider.java create mode 100644 odk/examples/java/Inspector/XInstanceInspector.idl create mode 100644 odk/examples/java/Inspector/XLanguageSourceCodeGenerator.java create mode 100644 odk/examples/java/Inspector/XTreeControlProvider.java create mode 100644 odk/examples/java/Inspector/XTreePathProvider.java create mode 100644 odk/examples/java/Inspector/XUnoFacetteNode.java create mode 100644 odk/examples/java/Inspector/XUnoMethodNode.java create mode 100644 odk/examples/java/Inspector/XUnoNode.java create mode 100644 odk/examples/java/Inspector/XUnoPropertyNode.java create mode 100644 odk/examples/java/Inspector/images/containers_16.png create mode 100644 odk/examples/java/Inspector/images/content_16.png create mode 100644 odk/examples/java/Inspector/images/interfaces_16.png create mode 100644 odk/examples/java/Inspector/images/methods_16.png create mode 100644 odk/examples/java/Inspector/images/properties_16.png create mode 100644 odk/examples/java/Inspector/images/services_16.png create mode 100644 odk/examples/java/Inspector/manifest.mf create mode 100644 odk/examples/java/MinimalComponent/BuildMinimalComponent.xml create mode 100644 odk/examples/java/MinimalComponent/Makefile create mode 100644 odk/examples/java/MinimalComponent/MinimalComponent.components create mode 100644 odk/examples/java/MinimalComponent/MinimalComponent.idl create mode 100644 odk/examples/java/MinimalComponent/MinimalComponent.java create mode 100644 odk/examples/java/MinimalComponent/TestMinimalComponent.java create mode 100644 odk/examples/java/NotesAccess/Makefile create mode 100644 odk/examples/java/NotesAccess/NotesAccess.java create mode 100644 odk/examples/java/NotesAccess/Stocks.nsf create mode 100644 odk/examples/java/PropertySet/Makefile create mode 100644 odk/examples/java/PropertySet/PropTest.components create mode 100644 odk/examples/java/PropertySet/PropTest.java create mode 100644 odk/examples/java/PropertySet/PropertySet.odt create mode 100644 odk/examples/java/Spreadsheet/CalcAddins.components create mode 100644 odk/examples/java/Spreadsheet/CalcAddins.java create mode 100644 odk/examples/java/Spreadsheet/CalcAddins.ods create mode 100644 odk/examples/java/Spreadsheet/ChartTypeChange.java create mode 100644 odk/examples/java/Spreadsheet/EuroAdaption.java create mode 100644 odk/examples/java/Spreadsheet/Makefile create mode 100644 odk/examples/java/Spreadsheet/SCalc.java create mode 100644 odk/examples/java/Spreadsheet/XCalcAddins.idl create mode 100644 odk/examples/java/Storage/Makefile create mode 100644 odk/examples/java/Storage/StorageFunctionality.java create mode 100644 odk/examples/java/Storage/StorageTest.java create mode 100644 odk/examples/java/Storage/Test01.java create mode 100644 odk/examples/java/Storage/Test02.java create mode 100644 odk/examples/java/Storage/Test03.java create mode 100644 odk/examples/java/Storage/Test04.java create mode 100644 odk/examples/java/Storage/Test05.java create mode 100644 odk/examples/java/Storage/Test06.java create mode 100644 odk/examples/java/Storage/Test07.java create mode 100644 odk/examples/java/Storage/Test08.java create mode 100644 odk/examples/java/Storage/Test09.java create mode 100644 odk/examples/java/Storage/TestHelper.java create mode 100644 odk/examples/java/Text/BookmarkInsertion.java create mode 100644 odk/examples/java/Text/GraphicsInserter.java create mode 100644 odk/examples/java/Text/HardFormatting.java create mode 100644 odk/examples/java/Text/Makefile create mode 100644 odk/examples/java/Text/SWriter.java create mode 100644 odk/examples/java/Text/StyleCreation.java create mode 100644 odk/examples/java/Text/StyleInitialization.java create mode 100644 odk/examples/java/Text/TextDocumentStructure.java create mode 100644 odk/examples/java/Text/TextReplace.java create mode 100644 odk/examples/java/Text/WriterSelector.java create mode 100644 odk/examples/java/Text/oo_smiley.gif create mode 100644 odk/examples/java/ToDo/Makefile create mode 100644 odk/examples/java/ToDo/ToDo.components create mode 100644 odk/examples/java/ToDo/ToDo.idl create mode 100644 odk/examples/java/ToDo/ToDo.java create mode 100644 odk/examples/java/ToDo/ToDo.ods create mode 100644 odk/examples/java/ToDo/XToDo.idl create mode 100644 odk/examples/python/toolpanel/CalcWindowState.xcu create mode 100644 odk/examples/python/toolpanel/Factory.xcu create mode 100644 odk/examples/python/toolpanel/META-INF/manifest.xml create mode 100644 odk/examples/python/toolpanel/Makefile create mode 100644 odk/examples/python/toolpanel/description.xml create mode 100644 odk/examples/python/toolpanel/readme create mode 100644 odk/examples/python/toolpanel/toolPanelPocBasic/Module1.xba create mode 100644 odk/examples/python/toolpanel/toolPanelPocBasic/dialog.xlb create mode 100644 odk/examples/python/toolpanel/toolPanelPocBasic/script.xlb create mode 100644 odk/examples/python/toolpanel/toolpanel.component create mode 100644 odk/examples/python/toolpanel/toolpanel.py create mode 100644 odk/examples/python/toolpanel/toolpanels/poc.xdl (limited to 'odk/examples') diff --git a/odk/examples/CLI/CSharp/Spreadsheet/GeneralTableSample.cs b/odk/examples/CLI/CSharp/Spreadsheet/GeneralTableSample.cs new file mode 100644 index 000000000..70942f737 --- /dev/null +++ b/odk/examples/CLI/CSharp/Spreadsheet/GeneralTableSample.cs @@ -0,0 +1,222 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +using System; + +// __________ implementation ____________________________________ + +/** Create a spreadsheet document and provide access to table contents. + */ +public class GeneralTableSample : SpreadsheetDocHelper +{ + + public static void Main( String [] args ) + { + try + { + using ( GeneralTableSample aSample = + new GeneralTableSample( args ) ) + { + aSample.doSampleFunction(); + } + Console.WriteLine( "Sample done." ); + } + catch (Exception ex) + { + Console.WriteLine( "Sample caught exception! " + ex ); + } + } + + + + public GeneralTableSample( String[] args ) : base( args ) + { + } + + + + /// This sample function modifies cells and cell ranges. + public void doSampleFunction() + { + // for common usage + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 0 ); + unoidl.com.sun.star.beans.XPropertySet xPropSet = null; + unoidl.com.sun.star.table.XCell xCell = null; + unoidl.com.sun.star.table.XCellRange xCellRange = null; + + // *** Access and modify a VALUE CELL *** + Console.WriteLine( "*** Sample for service table.Cell ***" ); + + xCell = xSheet.getCellByPosition( 0, 0 ); + // Set cell value. + xCell.setValue( 1234 ); + + // Get cell value. + double nDblValue = xCell.getValue() * 2; + xSheet.getCellByPosition( 0, 1 ).setValue( nDblValue ); + + // *** Create a FORMULA CELL and query error type *** + xCell = xSheet.getCellByPosition( 0, 2 ); + // Set formula string. + xCell.setFormula( "=1/0" ); + + // Get error type. + bool bValid = (xCell.getError() == 0); + // Get formula string. + String aText = "The formula " + xCell.getFormula() + " is "; + aText += bValid ? "valid." : "erroneous."; + + // *** Insert a TEXT CELL using the XText interface *** + xCell = xSheet.getCellByPosition( 0, 3 ); + unoidl.com.sun.star.text.XText xCellText = + (unoidl.com.sun.star.text.XText) xCell; + unoidl.com.sun.star.text.XTextCursor xTextCursor = + xCellText.createTextCursor(); + xCellText.insertString( xTextCursor, aText, false ); + + // *** Change cell properties *** + int nValue = bValid ? 0x00FF00 : 0xFF4040; + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCell; + xPropSet.setPropertyValue( + "CellBackColor", new uno.Any( (Int32) nValue ) ); + + + // *** Accessing a CELL RANGE *** + Console.WriteLine( "*** Sample for service table.CellRange ***" ); + + // Accessing a cell range over its position. + xCellRange = xSheet.getCellRangeByPosition( 2, 0, 3, 1 ); + + // Change properties of the range. + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCellRange; + xPropSet.setPropertyValue( + "CellBackColor", new uno.Any( (Int32) 0x8080FF ) ); + + // Accessing a cell range over its name. + xCellRange = xSheet.getCellRangeByName( "C4:D5" ); + + // Change properties of the range. + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCellRange; + xPropSet.setPropertyValue( + "CellBackColor", new uno.Any( (Int32) 0xFFFF80 ) ); + + + // *** Using the CELL CURSOR to add some data below of + // the filled area *** + Console.WriteLine( "*** Sample for service table.CellCursor ***" ); + + // Create a cursor using the XSpreadsheet method createCursorByRange() + xCellRange = xSheet.getCellRangeByName( "A1" ); + unoidl.com.sun.star.sheet.XSheetCellRange xSheetCellRange = + (unoidl.com.sun.star.sheet.XSheetCellRange) xCellRange; + + unoidl.com.sun.star.sheet.XSheetCellCursor xSheetCellCursor = + xSheet.createCursorByRange( xSheetCellRange ); + unoidl.com.sun.star.table.XCellCursor xCursor = + (unoidl.com.sun.star.table.XCellCursor) xSheetCellCursor; + + // Move to the last filled cell. + xCursor.gotoEnd(); + // Move one row down. + xCursor.gotoOffset( 0, 1 ); + xCursor.getCellByPosition( 0, 0 ).setFormula( + "Beyond of the last filled cell." ); + + + // *** Modifying COLUMNS and ROWS *** + Console.WriteLine( "*** Sample for services table.TableRows and " + + "table.TableColumns ***" ); + + unoidl.com.sun.star.table.XColumnRowRange xCRRange = + (unoidl.com.sun.star.table.XColumnRowRange) xSheet; + unoidl.com.sun.star.table.XTableColumns xColumns = + xCRRange.getColumns(); + unoidl.com.sun.star.table.XTableRows xRows = xCRRange.getRows(); + + // Get column C by index (interface XIndexAccess). + uno.Any aColumnObj = xColumns.getByIndex( 2 ); + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) aColumnObj.Value; + xPropSet.setPropertyValue( "Width", new uno.Any( (Int32) 5000 ) ); + + // Get the name of the column. + unoidl.com.sun.star.container.XNamed xNamed = + (unoidl.com.sun.star.container.XNamed) aColumnObj.Value; + aText = "The name of this column is " + xNamed.getName() + "."; + xSheet.getCellByPosition( 2, 2 ).setFormula( aText ); + + // Get column D by name (interface XNameAccess). + unoidl.com.sun.star.container.XNameAccess xColumnsName = + (unoidl.com.sun.star.container.XNameAccess) xColumns; + + aColumnObj = xColumnsName.getByName( "D" ); + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) aColumnObj.Value; + xPropSet.setPropertyValue( + "IsVisible", new uno.Any( (Boolean) false ) ); + + // Get row 7 by index (interface XIndexAccess) + uno.Any aRowObj = xRows.getByIndex( 6 ); + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) aRowObj.Value; + xPropSet.setPropertyValue( "Height", new uno.Any( (Int32) 5000 ) ); + + xSheet.getCellByPosition( 2, 6 ).setFormula( "What a big cell." ); + + // Create a cell series with the values 1 ... 7. + for (int nRow = 8; nRow < 15; ++nRow) + xSheet.getCellByPosition( 0, nRow ).setValue( nRow - 7 ); + // Insert a row between 1 and 2 + xRows.insertByIndex( 9, 1 ); + // Delete the rows with the values 3 and 4. + xRows.removeByIndex( 11, 2 ); + + // *** Inserting CHARTS *** + Console.WriteLine( "*** Sample for service table.TableCharts ***" ); + + unoidl.com.sun.star.table.XTableChartsSupplier xChartsSupp = + (unoidl.com.sun.star.table.XTableChartsSupplier) xSheet; + unoidl.com.sun.star.table.XTableCharts xCharts = + xChartsSupp.getCharts(); + + // The chart will base on the last cell series, initializing all values. + String aName = "newChart"; + unoidl.com.sun.star.awt.Rectangle aRect = + new unoidl.com.sun.star.awt.Rectangle(); + aRect.X = 10000; + aRect.Y = 3000; + aRect.Width = aRect.Height = 5000; + unoidl.com.sun.star.table.CellRangeAddress[] aRanges = + new unoidl.com.sun.star.table.CellRangeAddress[1]; + aRanges[0] = createCellRangeAddress( xSheet, "A9:A14" ); + + // Create the chart. + xCharts.addNewByName( aName, aRect, aRanges, false, false ); + + // Get the chart by name. + uno.Any aChartObj = xCharts.getByName( aName ); + unoidl.com.sun.star.table.XTableChart xChart = + (unoidl.com.sun.star.table.XTableChart) aChartObj.Value; + + // Query the state of row and column headers. + aText = "Chart has column headers: "; + aText += xChart.getHasColumnHeaders() ? "yes" : "no"; + xSheet.getCellByPosition( 2, 8 ).setFormula( aText ); + aText = "Chart has row headers: "; + aText += xChart.getHasRowHeaders() ? "yes" : "no"; + xSheet.getCellByPosition( 2, 9 ).setFormula( aText ); + } + +} diff --git a/odk/examples/CLI/CSharp/Spreadsheet/Makefile b/odk/examples/CLI/CSharp/Spreadsheet/Makefile new file mode 100644 index 000000000..6d03200e4 --- /dev/null +++ b/odk/examples/CLI/CSharp/Spreadsheet/Makefile @@ -0,0 +1,110 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# +# Builds the SpreadSheet examples of the Developers Guide. + +# This Makefile is supposed to be run by a GNU Make built for native +# Windows Not the Cygwin GNU Make, not dmake, not Microsoft's NMAKE. +# But yeah, that is what the setsdkenv_windows.bat file in +# ../../../.. presumably tries to set up. + +PRJ = ../../../.. +SETTINGS = $(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +CSC_FLAGS = -warnaserror+ -noconfig -platform:x86 +VBC_FLAGS = -warnaserror+ +ifeq "$(DEBUG)" "yes" +CC_FLAGS+=-Zi -MT +CSC_FLAGS += -debug+ -checked+ -define:DEBUG -define:TRACE +VBC_FLAGS += -debug+ -define:DEBUG=1 -define:TRACE=1 +else +CSC_FLAGS += -o +VBC_FLAGS += -o +endif + +THIS_OUT_MISC = $(OUT_MISC)/csharp_SpreadsheetExamples + +SPREADSHEET_OUT:= $(OUT_BIN)/CSharp_SpreadsheetExamples + +ifneq "$(OUTDIR)" "" +# We are running in a LO build environment, good +CLI_LIB_LOCATION = $(OUTDIR)\bin +else +# Bad guess, but hey, this is how it was +CLI_LIB_LOCATION = $(PRJ)\cli +endif + +# Targets +.PHONY : ALL +ALL : Info + +include $(SETTINGS)/stdtarget.mk + + +# build executables +#csc -lib:"d:\StarOffice 8" does not work. csc does not understand the quotes. +#but they are needed if the path contains a space. Therefore we use full path +#with the -reference switch +$(SPREADSHEET_OUT)/%.exe : %.cs SpreadsheetDocHelper.cs + -$(MKDIR) $(subst /,$(PS),$(@D)) + csc $(CSC_FLAGS) \ + -target:exe \ + -out:$@ \ + -reference:"$(CLI_LIB_LOCATION)"\cli_basetypes.dll \ + -reference:"$(CLI_LIB_LOCATION)"\cli_uretypes.dll \ + -reference:"$(CLI_LIB_LOCATION)"\cli_oootypes.dll \ + -reference:"$(CLI_LIB_LOCATION)"\cli_ure.dll \ + -reference:"$(CLI_LIB_LOCATION)"\cli_cppuhelper.dll \ + $^ + +SpreadsheetSample : $(SPREADSHEET_OUT)/SpreadsheetSample.exe + +GeneralTableSample : $(SPREADSHEET_OUT)/GeneralTableSample.exe + +ViewSample : $(SPREADSHEET_OUT)/ViewSample.exe + +.PHONY : Info +ifeq "$(OS)" "WIN" +Info : SpreadsheetSample GeneralTableSample ViewSample + @echo ------------------------------------------------------------------------------- + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) GeneralTableSample.run + @echo $(MAKE) SpreadsheetSample.run + @echo $(MAKE) ViewSample.run + @echo ------------------------------------------------------------------------------- +else +Info : + @echo -------------------------------------------------------------------------------- + @echo This example works only under Windows! + @echo -------------------------------------------------------------------------------- +endif + +%.run : $(SPREADSHEET_OUT)/%.exe + @echo ------------------------------------------------------------------------------- + @echo Executing sample $@ $(UNORC) $(CONNECT_STRING)... + @echo ------------------------------------------------------------------------------- + cd $(subst /,\\,$(SPREADSHEET_OUT)) && $(basename $@).exe + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_BIN)/CSharp_SpreadsheetExamples) + + diff --git a/odk/examples/CLI/CSharp/Spreadsheet/SpreadsheetDocHelper.cs b/odk/examples/CLI/CSharp/Spreadsheet/SpreadsheetDocHelper.cs new file mode 100644 index 000000000..d8ddd6beb --- /dev/null +++ b/odk/examples/CLI/CSharp/Spreadsheet/SpreadsheetDocHelper.cs @@ -0,0 +1,361 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +using System; +using unoidl.com.sun.star.lang; +using unoidl.com.sun.star.uno; +using unoidl.com.sun.star.bridge; +using unoidl.com.sun.star.frame; + +// __________ implementation ____________________________________ + +/** This is a helper class for the spreadsheet and table samples. + It connects to a running office and creates a spreadsheet document. + Additionally it contains various helper functions. + */ +public class SpreadsheetDocHelper : System.IDisposable +{ + +// __ private members ___________________________________________ + + private const String msDataSheetName = "Data"; + + private unoidl.com.sun.star.uno.XComponentContext m_xContext; + private unoidl.com.sun.star.lang.XMultiServiceFactory mxMSFactory; + private unoidl.com.sun.star.sheet.XSpreadsheetDocument mxDocument; + + + + public SpreadsheetDocHelper( String[] args ) + { + // Connect to a running office and get the service manager + mxMSFactory = connect( args ); + // Create a new spreadsheet document + mxDocument = initDocument(); + } + +// __ helper methods ____________________________________________ + + /** Returns the service manager. + @return XMultiServiceFactory interface of the service manager. */ + public unoidl.com.sun.star.lang.XMultiServiceFactory getServiceManager() + { + return mxMSFactory; + } + + /** Returns the whole spreadsheet document. + @return XSpreadsheetDocument interface of the document. */ + public unoidl.com.sun.star.sheet.XSpreadsheetDocument getDocument() + { + return mxDocument; + } + + /** Returns the spreadsheet with the specified index (0-based). + @param nIndex The index of the sheet. + @return XSpreadsheet interface of the sheet. */ + public unoidl.com.sun.star.sheet.XSpreadsheet getSpreadsheet( int nIndex ) + { + // Collection of sheets + unoidl.com.sun.star.sheet.XSpreadsheets xSheets = + mxDocument.getSheets(); + + unoidl.com.sun.star.container.XIndexAccess xSheetsIA = + (unoidl.com.sun.star.container.XIndexAccess) xSheets; + + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = + (unoidl.com.sun.star.sheet.XSpreadsheet) + xSheetsIA.getByIndex( nIndex ).Value; + + return xSheet; + } + + /** Inserts a new empty spreadsheet with the specified name. + @param aName The name of the new sheet. + @param nIndex The insertion index. + @return The XSpreadsheet interface of the new sheet. */ + public unoidl.com.sun.star.sheet.XSpreadsheet insertSpreadsheet( + String aName, short nIndex ) + { + // Collection of sheets + unoidl.com.sun.star.sheet.XSpreadsheets xSheets = + mxDocument.getSheets(); + + xSheets.insertNewByName( aName, nIndex ); + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = + (unoidl.com.sun.star.sheet.XSpreadsheet) + xSheets.getByName( aName ).Value; + + return xSheet; + } + + +// Methods to fill values into cells. + + /** Writes a double value into a spreadsheet. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aCellName The address of the cell (or a named range). + @param fValue The value to write into the cell. */ + public void setValue( + unoidl.com.sun.star.sheet.XSpreadsheet xSheet, + String aCellName, + double fValue ) + { + xSheet.getCellRangeByName( aCellName ).getCellByPosition( + 0, 0 ).setValue( fValue ); + } + + /** Writes a formula into a spreadsheet. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aCellName The address of the cell (or a named range). + @param aFormula The formula to write into the cell. */ + public void setFormula( + unoidl.com.sun.star.sheet.XSpreadsheet xSheet, + String aCellName, + String aFormula ) + { + xSheet.getCellRangeByName( aCellName ).getCellByPosition( + 0, 0 ).setFormula( aFormula ); + } + + /** Writes a date with standard date format into a spreadsheet. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aCellName The address of the cell (or a named range). + @param nDay The day of the date. + @param nMonth The month of the date. + @param nYear The year of the date. */ + public void setDate( + unoidl.com.sun.star.sheet.XSpreadsheet xSheet, + String aCellName, + int nDay, int nMonth, int nYear ) + { + // Set the date value. + unoidl.com.sun.star.table.XCell xCell = + xSheet.getCellRangeByName( aCellName ).getCellByPosition( 0, 0 ); + String aDateStr = nMonth + "/" + nDay + "/" + nYear; + xCell.setFormula( aDateStr ); + + // Set standard date format. + unoidl.com.sun.star.util.XNumberFormatsSupplier xFormatsSupplier = + (unoidl.com.sun.star.util.XNumberFormatsSupplier) getDocument(); + unoidl.com.sun.star.util.XNumberFormatTypes xFormatTypes = + (unoidl.com.sun.star.util.XNumberFormatTypes) + xFormatsSupplier.getNumberFormats(); + int nFormat = xFormatTypes.getStandardFormat( + unoidl.com.sun.star.util.NumberFormat.DATE, + new unoidl.com.sun.star.lang.Locale() ); + + unoidl.com.sun.star.beans.XPropertySet xPropSet = + (unoidl.com.sun.star.beans.XPropertySet) xCell; + xPropSet.setPropertyValue( + "NumberFormat", + new uno.Any( (Int32) nFormat ) ); + } + + /** Draws a colored border around the range and writes the headline + in the first cell. + + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aRange The address of the cell range (or a named range). + @param aHeadline The headline text. */ + public void prepareRange( + unoidl.com.sun.star.sheet.XSpreadsheet xSheet, + String aRange, String aHeadline ) + { + unoidl.com.sun.star.beans.XPropertySet xPropSet = null; + unoidl.com.sun.star.table.XCellRange xCellRange = null; + + // draw border + xCellRange = xSheet.getCellRangeByName( aRange ); + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCellRange; + unoidl.com.sun.star.table.BorderLine aLine = + new unoidl.com.sun.star.table.BorderLine(); + aLine.Color = 0x99CCFF; + aLine.InnerLineWidth = aLine.LineDistance = 0; + aLine.OuterLineWidth = 100; + unoidl.com.sun.star.table.TableBorder aBorder = + new unoidl.com.sun.star.table.TableBorder(); + aBorder.TopLine = aBorder.BottomLine = aBorder.LeftLine = + aBorder.RightLine = aLine; + aBorder.IsTopLineValid = aBorder.IsBottomLineValid = true; + aBorder.IsLeftLineValid = aBorder.IsRightLineValid = true; + xPropSet.setPropertyValue( + "TableBorder", + new uno.Any( + typeof (unoidl.com.sun.star.table.TableBorder), aBorder ) ); + + // draw headline + unoidl.com.sun.star.sheet.XCellRangeAddressable xAddr = + (unoidl.com.sun.star.sheet.XCellRangeAddressable) xCellRange; + unoidl.com.sun.star.table.CellRangeAddress aAddr = + xAddr.getRangeAddress(); + + xCellRange = xSheet.getCellRangeByPosition( + aAddr.StartColumn, + aAddr.StartRow, aAddr.EndColumn, aAddr.StartRow ); + + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCellRange; + xPropSet.setPropertyValue( + "CellBackColor", new uno.Any( (Int32) 0x99CCFF ) ); + // write headline + unoidl.com.sun.star.table.XCell xCell = + xCellRange.getCellByPosition( 0, 0 ); + xCell.setFormula( aHeadline ); + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCell; + xPropSet.setPropertyValue( + "CharColor", new uno.Any( (Int32) 0x003399 ) ); + xPropSet.setPropertyValue( + "CharWeight", + new uno.Any( (Single) unoidl.com.sun.star.awt.FontWeight.BOLD ) ); + } + + +// Methods to create cell addresses and range addresses. + + /** Creates a unoidl.com.sun.star.table.CellAddress and initializes it + with the given range. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aCell The address of the cell (or a named cell). */ + public unoidl.com.sun.star.table.CellAddress createCellAddress( + unoidl.com.sun.star.sheet.XSpreadsheet xSheet, + String aCell ) + { + unoidl.com.sun.star.sheet.XCellAddressable xAddr = + (unoidl.com.sun.star.sheet.XCellAddressable) + xSheet.getCellRangeByName( aCell ).getCellByPosition( 0, 0 ); + return xAddr.getCellAddress(); + } + + /** Creates a unoidl.com.sun.star.table.CellRangeAddress and initializes + it with the given range. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aRange The address of the cell range (or a named range). */ + public unoidl.com.sun.star.table.CellRangeAddress createCellRangeAddress( + unoidl.com.sun.star.sheet.XSpreadsheet xSheet, String aRange ) + { + unoidl.com.sun.star.sheet.XCellRangeAddressable xAddr = + (unoidl.com.sun.star.sheet.XCellRangeAddressable) + xSheet.getCellRangeByName( aRange ); + return xAddr.getRangeAddress(); + } + + +// Methods to convert cell addresses and range addresses to strings. + + /** Returns the text address of the cell. + @param nColumn The column index. + @param nRow The row index. + @return A string containing the cell address. */ + public String getCellAddressString( int nColumn, int nRow ) + { + String aStr = ""; + if (nColumn > 25) + aStr += (char) ('A' + nColumn / 26 - 1); + aStr += (char) ('A' + nColumn % 26); + aStr += (nRow + 1); + return aStr; + } + + /** Returns the text address of the cell range. + @param aCellRange The cell range address. + @return A string containing the cell range address. */ + public String getCellRangeAddressString( + unoidl.com.sun.star.table.CellRangeAddress aCellRange ) + { + return + getCellAddressString( aCellRange.StartColumn, aCellRange.StartRow ) + + ":" + + getCellAddressString( aCellRange.EndColumn, aCellRange.EndRow ); + } + + /** Returns the text address of the cell range. + @param xCellRange The XSheetCellRange interface of the cell range. + @param bWithSheet true = Include sheet name. + @return A string containing the cell range address. */ + public String getCellRangeAddressString( + unoidl.com.sun.star.sheet.XSheetCellRange xCellRange, bool bWithSheet ) + { + String aStr = ""; + if (bWithSheet) + { + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = + xCellRange.getSpreadsheet(); + unoidl.com.sun.star.container.XNamed xNamed = + (unoidl.com.sun.star.container.XNamed) xSheet; + aStr += xNamed.getName() + "."; + } + unoidl.com.sun.star.sheet.XCellRangeAddressable xAddr = + (unoidl.com.sun.star.sheet.XCellRangeAddressable) xCellRange; + aStr += getCellRangeAddressString( xAddr.getRangeAddress() ); + return aStr; + } + + /** Returns a list of addresses of all cell ranges contained in the + collection. + + @param xRangesIA The XIndexAccess interface of the collection. + @return A string containing the cell range address list. */ + public String getCellRangeListString( + unoidl.com.sun.star.container.XIndexAccess xRangesIA ) + { + String aStr = ""; + int nCount = xRangesIA.getCount(); + for (int nIndex = 0; nIndex < nCount; ++nIndex) + { + if (nIndex > 0) + aStr += " "; + uno.Any aRangeObj = xRangesIA.getByIndex( nIndex ); + unoidl.com.sun.star.sheet.XSheetCellRange xCellRange = + (unoidl.com.sun.star.sheet.XSheetCellRange) aRangeObj.Value; + aStr += getCellRangeAddressString( xCellRange, false ); + } + return aStr; + } + + + + /** Connect to a running office that is accepting connections. + @return The ServiceManager to instantiate office components. */ + private XMultiServiceFactory connect( String [] args ) + { + + m_xContext = uno.util.Bootstrap.bootstrap(); + + return (XMultiServiceFactory) m_xContext.getServiceManager(); + } + + public void Dispose() + { + + } + + /** Creates an empty spreadsheet document. + @return The XSpreadsheetDocument interface of the document. */ + private unoidl.com.sun.star.sheet.XSpreadsheetDocument initDocument() + { + XComponentLoader aLoader = (XComponentLoader) + mxMSFactory.createInstance( "com.sun.star.frame.Desktop" ); + + XComponent xComponent = aLoader.loadComponentFromURL( + "private:factory/scalc", "_blank", 0, + new unoidl.com.sun.star.beans.PropertyValue[0] ); + + return (unoidl.com.sun.star.sheet.XSpreadsheetDocument) xComponent; + } + + +} diff --git a/odk/examples/CLI/CSharp/Spreadsheet/SpreadsheetSample.cs b/odk/examples/CLI/CSharp/Spreadsheet/SpreadsheetSample.cs new file mode 100644 index 000000000..1dd2f8a03 --- /dev/null +++ b/odk/examples/CLI/CSharp/Spreadsheet/SpreadsheetSample.cs @@ -0,0 +1,1495 @@ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +using System; + +// __________ implementation ____________________________________ + +/** Create and modify a spreadsheet document. + */ +public class SpreadsheetSample : SpreadsheetDocHelper +{ + + public static void Main( String [] args ) + { + try + { + using ( SpreadsheetSample aSample = new SpreadsheetSample( args ) ) + { + aSample.doSampleFunctions(); + } + Console.WriteLine( "\nSamples done." ); + } + catch (Exception ex) + { + Console.WriteLine( "Sample caught exception! " + ex ); + } + } + + public SpreadsheetSample( String[] args ) + : base( args ) + { + } + + /** This sample function performs all changes on the document. */ + public void doSampleFunctions() + { + doCellSamples(); + doCellRangeSamples(); + doCellRangesSamples(); + doCellCursorSamples(); + doFormattingSamples(); + doDocumentSamples(); + doDatabaseSamples(); + doDataPilotSamples(); + doNamedRangesSamples(); + doFunctionAccessSamples(); + doApplicationSettingsSamples(); + } + + + + /** All samples regarding the service com.sun.star.sheet.SheetCell. */ + private void doCellSamples() + { + Console.WriteLine( "\n*** Samples for service sheet.SheetCell ***\n" ); + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 0 ); + unoidl.com.sun.star.table.XCell xCell = null; + unoidl.com.sun.star.beans.XPropertySet xPropSet = null; + String aText; + prepareRange( xSheet, "A1:C7", "Cells and Cell Ranges" ); + + // --- Get cell B3 by position - (column, row) --- + xCell = xSheet.getCellByPosition( 1, 2 ); + + // --- Insert two text paragraphs into the cell. --- + unoidl.com.sun.star.text.XText xText = + (unoidl.com.sun.star.text.XText) xCell; + unoidl.com.sun.star.text.XTextCursor xTextCursor = + xText.createTextCursor(); + + xText.insertString( xTextCursor, "Text in first line.", false ); + xText.insertControlCharacter( xTextCursor, + unoidl.com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false ); + xText.insertString( xTextCursor, "And a ", false ); + + // create a hyperlink + unoidl.com.sun.star.lang.XMultiServiceFactory xServiceMan = + (unoidl.com.sun.star.lang.XMultiServiceFactory) getDocument(); + Object aHyperlinkObj = + xServiceMan.createInstance( "com.sun.star.text.TextField.URL" ); + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) aHyperlinkObj; + xPropSet.setPropertyValue( + "URL", new uno.Any( "http://www.example.org" ) ); + xPropSet.setPropertyValue( + "Representation", new uno.Any( "hyperlink" ) ); + // ... and insert + unoidl.com.sun.star.text.XTextContent xContent = + (unoidl.com.sun.star.text.XTextContent) aHyperlinkObj; + xText.insertTextContent( xTextCursor, xContent, false ); + + // --- Query the separate paragraphs. --- + unoidl.com.sun.star.container.XEnumerationAccess xParaEA = + (unoidl.com.sun.star.container.XEnumerationAccess) xCell; + unoidl.com.sun.star.container.XEnumeration xParaEnum = + xParaEA.createEnumeration(); + // Go through the paragraphs + while( xParaEnum.hasMoreElements() ) + { + uno.Any aPortionObj = xParaEnum.nextElement(); + unoidl.com.sun.star.container.XEnumerationAccess xPortionEA = + (unoidl.com.sun.star.container.XEnumerationAccess) + aPortionObj.Value; + unoidl.com.sun.star.container.XEnumeration xPortionEnum = + xPortionEA.createEnumeration(); + aText = ""; + // Go through all text portions of a paragraph and construct string. + while( xPortionEnum.hasMoreElements() ) + { + unoidl.com.sun.star.text.XTextRange xRange = + (unoidl.com.sun.star.text.XTextRange) + xPortionEnum.nextElement().Value; + aText += xRange.getString(); + } + Console.WriteLine( "Paragraph text: " + aText ); + } + + + // --- Change cell properties. --- + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCell; + // from styles.CharacterProperties + xPropSet.setPropertyValue( + "CharColor", new uno.Any( (Int32) 0x003399 ) ); + xPropSet.setPropertyValue( + "CharHeight", new uno.Any( (Single) 20.0 ) ); + // from styles.ParagraphProperties + xPropSet.setPropertyValue( + "ParaLeftMargin", new uno.Any( (Int32) 500 ) ); + // from table.CellProperties + xPropSet.setPropertyValue( + "IsCellBackgroundTransparent", new uno.Any( false ) ); + xPropSet.setPropertyValue( + "CellBackColor", new uno.Any( (Int32) 0x99CCFF ) ); + + + // --- Get cell address. --- + unoidl.com.sun.star.sheet.XCellAddressable xCellAddr = + (unoidl.com.sun.star.sheet.XCellAddressable) xCell; + unoidl.com.sun.star.table.CellAddress aAddress = + xCellAddr.getCellAddress(); + aText = "Address of this cell: Column=" + aAddress.Column; + aText += "; Row=" + aAddress.Row; + aText += "; Sheet=" + aAddress.Sheet; + Console.WriteLine( aText ); + + + // --- Insert an annotation --- + unoidl.com.sun.star.sheet.XSheetAnnotationsSupplier xAnnotationsSupp = + (unoidl.com.sun.star.sheet.XSheetAnnotationsSupplier) xSheet; + unoidl.com.sun.star.sheet.XSheetAnnotations xAnnotations = + xAnnotationsSupp.getAnnotations(); + xAnnotations.insertNew( aAddress, "This is an annotation" ); + + unoidl.com.sun.star.sheet.XSheetAnnotationAnchor xAnnotAnchor = + (unoidl.com.sun.star.sheet.XSheetAnnotationAnchor) xCell; + unoidl.com.sun.star.sheet.XSheetAnnotation xAnnotation = + xAnnotAnchor.getAnnotation(); + xAnnotation.setIsVisible( true ); + } + + + + /** All samples regarding the service com.sun.star.sheet.SheetCellRange. */ + private void doCellRangeSamples() + { + Console.WriteLine( + "\n*** Samples for service sheet.SheetCellRange ***\n" ); + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 0 ); + unoidl.com.sun.star.table.XCellRange xCellRange = null; + unoidl.com.sun.star.beans.XPropertySet xPropSet = null; + unoidl.com.sun.star.table.CellRangeAddress aRangeAddress = null; + + // Preparation + setFormula( xSheet, "B5", "First cell" ); + setFormula( xSheet, "B6", "Second cell" ); + // Get cell range B5:B6 by position - (column, row, column, row) + xCellRange = xSheet.getCellRangeByPosition( 1, 4, 1, 5 ); + + + // --- Change cell range properties. --- + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCellRange; + // from com.sun.star.styles.CharacterProperties + xPropSet.setPropertyValue( + "CharColor", new uno.Any( (Int32) 0x003399 ) ); + xPropSet.setPropertyValue( + "CharHeight", new uno.Any( (Single) 20.0 ) ); + // from com.sun.star.styles.ParagraphProperties + xPropSet.setPropertyValue( + "ParaLeftMargin", new uno.Any( (Int32) 500 ) ); + // from com.sun.star.table.CellProperties + xPropSet.setPropertyValue( + "IsCellBackgroundTransparent", new uno.Any( false ) ); + xPropSet.setPropertyValue( + "CellBackColor", new uno.Any( (Int32) 0x99CCFF ) ); + + + // --- Replace text in all cells. --- + unoidl.com.sun.star.util.XReplaceable xReplace = + (unoidl.com.sun.star.util.XReplaceable) xCellRange; + unoidl.com.sun.star.util.XReplaceDescriptor xReplaceDesc = + xReplace.createReplaceDescriptor(); + xReplaceDesc.setSearchString( "cell" ); + xReplaceDesc.setReplaceString( "text" ); + // property SearchWords searches for whole cells! + xReplaceDesc.setPropertyValue( "SearchWords", new uno.Any( false ) ); + int nCount = xReplace.replaceAll( xReplaceDesc ); + Console.WriteLine( "Search text replaced " + nCount + " times." ); + + + // --- Merge cells. --- + xCellRange = xSheet.getCellRangeByName( "F3:G6" ); + prepareRange( xSheet, "E1:H7", "XMergeable" ); + unoidl.com.sun.star.util.XMergeable xMerge = + (unoidl.com.sun.star.util.XMergeable) xCellRange; + xMerge.merge( true ); + + + // --- Change indentation. --- +/* does not work (bug in XIndent implementation) + prepareRange( xSheet, "I20:I23", "XIndent" ); + setValue( xSheet, "I21", 1 ); + setValue( xSheet, "I22", 1 ); + setValue( xSheet, "I23", 1 ); + + xCellRange = xSheet.getCellRangeByName( "I21:I22" ); + unoidl.com.sun.star.util.XIndent xIndent = + (unoidl.com.sun.star.util.XIndent) xCellRange; + xIndent.incrementIndent(); + + xCellRange = xSheet.getCellRangeByName( "I22:I23" ); + xIndent = (unoidl.com.sun.star.util.XIndent) xCellRange; + xIndent.incrementIndent(); +*/ + + + // --- Column properties. --- + xCellRange = xSheet.getCellRangeByName( "B1" ); + unoidl.com.sun.star.table.XColumnRowRange xColRowRange = + (unoidl.com.sun.star.table.XColumnRowRange) xCellRange; + unoidl.com.sun.star.table.XTableColumns xColumns = + xColRowRange.getColumns(); + + uno.Any aColumnObj = xColumns.getByIndex( 0 ); + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) aColumnObj.Value; + xPropSet.setPropertyValue( "Width", new uno.Any( (Int32) 6000 ) ); + + unoidl.com.sun.star.container.XNamed xNamed = + (unoidl.com.sun.star.container.XNamed) aColumnObj.Value; + Console.WriteLine( + "The name of the wide column is " + xNamed.getName() + "." ); + + + // --- Cell range data --- + prepareRange( xSheet, "A9:C30", "XCellRangeData" ); + + xCellRange = xSheet.getCellRangeByName( "A10:C30" ); + unoidl.com.sun.star.sheet.XCellRangeData xData = + (unoidl.com.sun.star.sheet.XCellRangeData) xCellRange; + uno.Any [][] aValues = + { + new uno.Any [] { new uno.Any( "Name" ), + new uno.Any( "Fruit" ), + new uno.Any( "Quantity" ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Apples" ), + new uno.Any( (Double) 3.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Oranges" ), + new uno.Any( (Double) 7.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( "Apples" ), + new uno.Any( (Double) 3.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Apples" ), + new uno.Any( (Double) 9.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( "Apples" ), + new uno.Any( (Double) 5.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( "Oranges" ), + new uno.Any( (Double) 6.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Oranges" ), + new uno.Any( (Double) 3.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Apples" ), + new uno.Any( (Double) 8.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Oranges" ), + new uno.Any( (Double) 1.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( "Oranges" ), + new uno.Any( (Double) 2.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( "Oranges" ), + new uno.Any( (Double) 7.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( "Apples" ), + new uno.Any( (Double) 1.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Apples" ), + new uno.Any( (Double) 8.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Oranges" ), + new uno.Any( (Double) 8.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Apples" ), + new uno.Any( (Double) 7.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( "Apples" ), + new uno.Any( (Double) 1.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( "Oranges" ), + new uno.Any( (Double) 9.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( "Oranges" ), + new uno.Any( (Double) 3.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Oranges" ), + new uno.Any( (Double) 4.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( "Apples" ), + new uno.Any( (Double) 9.0 ) } + }; + xData.setDataArray( aValues ); + + + // --- Get cell range address. --- + unoidl.com.sun.star.sheet.XCellRangeAddressable xRangeAddr = + (unoidl.com.sun.star.sheet.XCellRangeAddressable) xCellRange; + aRangeAddress = xRangeAddr.getRangeAddress(); + Console.WriteLine( + "Address of this range: Sheet=" + aRangeAddress.Sheet ); + Console.WriteLine( + "Start column=" + aRangeAddress.StartColumn + "; Start row=" + + aRangeAddress.StartRow ); + Console.WriteLine( + "End column =" + aRangeAddress.EndColumn + "; End row =" + + aRangeAddress.EndRow ); + + + // --- Sheet operation. --- + // uses the range filled with XCellRangeData + unoidl.com.sun.star.sheet.XSheetOperation xSheetOp = + (unoidl.com.sun.star.sheet.XSheetOperation) xData; + double fResult = xSheetOp.computeFunction( + unoidl.com.sun.star.sheet.GeneralFunction.AVERAGE ); + Console.WriteLine( + "Average value of the data table A10:C30: " + fResult ); + + + // --- Fill series --- + // Prepare the example + setValue( xSheet, "E10", 1 ); + setValue( xSheet, "E11", 4 ); + setDate( xSheet, "E12", 30, 1, 2002 ); + setFormula( xSheet, "I13", "Text 10" ); + setFormula( xSheet, "E14", "Jan" ); + setValue( xSheet, "K14", 10 ); + setValue( xSheet, "E16", 1 ); + setValue( xSheet, "F16", 2 ); + setDate( xSheet, "E17", 28, 2, 2002 ); + setDate( xSheet, "F17", 28, 1, 2002 ); + setValue( xSheet, "E18", 6 ); + setValue( xSheet, "F18", 4 ); + + unoidl.com.sun.star.sheet.XCellSeries xSeries = null; + // Fill 2 rows linear with end value + // -> 2nd series is not filled completely + xSeries = getCellSeries( xSheet, "E10:I11" ); + xSeries.fillSeries( + unoidl.com.sun.star.sheet.FillDirection.TO_RIGHT, + unoidl.com.sun.star.sheet.FillMode.LINEAR, + unoidl.com.sun.star.sheet.FillDateMode.FILL_DATE_DAY, 2, 9 ); + // Add months to a date + xSeries = getCellSeries( xSheet, "E12:I12" ); + xSeries.fillSeries( + unoidl.com.sun.star.sheet.FillDirection.TO_RIGHT, + unoidl.com.sun.star.sheet.FillMode.DATE, + unoidl.com.sun.star.sheet.FillDateMode.FILL_DATE_MONTH, + 1, 0x7FFFFFFF ); + // Fill right to left with a text containing a value + xSeries = getCellSeries( xSheet, "E13:I13" ); + xSeries.fillSeries( + unoidl.com.sun.star.sheet.FillDirection.TO_LEFT, + unoidl.com.sun.star.sheet.FillMode.LINEAR, + unoidl.com.sun.star.sheet.FillDateMode.FILL_DATE_DAY, + 10, 0x7FFFFFFF ); + // Fill with an user defined list + xSeries = getCellSeries( xSheet, "E14:I14" ); + xSeries.fillSeries( + unoidl.com.sun.star.sheet.FillDirection.TO_RIGHT, + unoidl.com.sun.star.sheet.FillMode.AUTO, + unoidl.com.sun.star.sheet.FillDateMode.FILL_DATE_DAY, + 1, 0x7FFFFFFF ); + // Fill bottom to top with a geometric series + xSeries = getCellSeries( xSheet, "K10:K14" ); + xSeries.fillSeries( + unoidl.com.sun.star.sheet.FillDirection.TO_TOP, + unoidl.com.sun.star.sheet.FillMode.GROWTH, + unoidl.com.sun.star.sheet.FillDateMode.FILL_DATE_DAY, + 2, 0x7FFFFFFF ); + // Auto fill + xSeries = getCellSeries( xSheet, "E16:K18" ); + xSeries.fillAuto( + unoidl.com.sun.star.sheet.FillDirection.TO_RIGHT, 2 ); + // Fill series copies cell formats -> draw border here + prepareRange( xSheet, "E9:K18", "XCellSeries" ); + + + // --- Array formulas --- + xCellRange = xSheet.getCellRangeByName( "E21:G23" ); + prepareRange( xSheet, "E20:G23", "XArrayFormulaRange" ); + unoidl.com.sun.star.sheet.XArrayFormulaRange xArrayFormula = + (unoidl.com.sun.star.sheet.XArrayFormulaRange) xCellRange; + // Insert a 3x3 unit matrix. + xArrayFormula.setArrayFormula( "=A10:C12" ); + Console.WriteLine( + "Array formula is: " + xArrayFormula.getArrayFormula() ); + + + // --- Multiple operations --- + setFormula( xSheet, "E26", "=E27^F26" ); + setValue( xSheet, "E27", 1 ); + setValue( xSheet, "F26", 1 ); + getCellSeries( xSheet, "E27:E31" ).fillAuto( + unoidl.com.sun.star.sheet.FillDirection.TO_BOTTOM, 1 ); + getCellSeries( xSheet, "F26:J26" ).fillAuto( + unoidl.com.sun.star.sheet.FillDirection.TO_RIGHT, 1 ); + setFormula( xSheet, "F33", "=SIN(E33)" ); + setFormula( xSheet, "G33", "=COS(E33)" ); + setFormula( xSheet, "H33", "=TAN(E33)" ); + setValue( xSheet, "E34", 0 ); + setValue( xSheet, "E35", 0.2 ); + getCellSeries( xSheet, "E34:E38" ).fillAuto( + unoidl.com.sun.star.sheet.FillDirection.TO_BOTTOM, 2 ); + prepareRange( xSheet, "E25:J38", "XMultipleOperation" ); + + unoidl.com.sun.star.table.CellRangeAddress aFormulaRange = + createCellRangeAddress( xSheet, "E26" ); + unoidl.com.sun.star.table.CellAddress aColCell = + createCellAddress( xSheet, "E27" ); + unoidl.com.sun.star.table.CellAddress aRowCell = + createCellAddress( xSheet, "F26" ); + + xCellRange = xSheet.getCellRangeByName( "E26:J31" ); + unoidl.com.sun.star.sheet.XMultipleOperation xMultOp = + (unoidl.com.sun.star.sheet.XMultipleOperation) xCellRange; + xMultOp.setTableOperation( + aFormulaRange, unoidl.com.sun.star.sheet.TableOperationMode.BOTH, + aColCell, aRowCell ); + + aFormulaRange = createCellRangeAddress( xSheet, "F33:H33" ); + aColCell = createCellAddress( xSheet, "E33" ); + // Row cell not needed + + xCellRange = xSheet.getCellRangeByName( "E34:H38" ); + xMultOp = (unoidl.com.sun.star.sheet.XMultipleOperation) xCellRange; + xMultOp.setTableOperation( + aFormulaRange, unoidl.com.sun.star.sheet.TableOperationMode.COLUMN, + aColCell, aRowCell ); + + + // --- Cell Ranges Query --- + xCellRange = xSheet.getCellRangeByName( "A10:C30" ); + unoidl.com.sun.star.sheet.XCellRangesQuery xRangesQuery = + (unoidl.com.sun.star.sheet.XCellRangesQuery) xCellRange; + unoidl.com.sun.star.sheet.XSheetCellRanges xCellRanges = + xRangesQuery.queryContentCells( + (short) unoidl.com.sun.star.sheet.CellFlags.STRING ); + Console.WriteLine( + "Cells in A10:C30 containing text: " + + xCellRanges.getRangeAddressesAsString() ); + } + + /** Returns the XCellSeries interface of a cell range. + @param xSheet The spreadsheet containing the cell range. + @param aRange The address of the cell range. + @return The XCellSeries interface. */ + private unoidl.com.sun.star.sheet.XCellSeries getCellSeries( + unoidl.com.sun.star.sheet.XSpreadsheet xSheet, String aRange ) + { + return (unoidl.com.sun.star.sheet.XCellSeries) + xSheet.getCellRangeByName( aRange ); + } + + + + /** All samples regarding cell range collections. */ + private void doCellRangesSamples() + { + Console.WriteLine( "\n*** Samples for cell range collections ***\n" ); + + // Create a new cell range container + unoidl.com.sun.star.lang.XMultiServiceFactory xDocFactory = + (unoidl.com.sun.star.lang.XMultiServiceFactory) getDocument(); + unoidl.com.sun.star.sheet.XSheetCellRangeContainer xRangeCont = + (unoidl.com.sun.star.sheet.XSheetCellRangeContainer) + xDocFactory.createInstance( + "com.sun.star.sheet.SheetCellRanges" ); + + + // --- Insert ranges --- + insertRange( xRangeCont, 0, 0, 0, 0, 0, false ); // A1:A1 + insertRange( xRangeCont, 0, 0, 1, 0, 2, true ); // A2:A3 + insertRange( xRangeCont, 0, 1, 0, 1, 2, false ); // B1:B3 + + + // --- Query the list of filled cells --- + Console.WriteLine( "All filled cells: " ); + unoidl.com.sun.star.container.XEnumerationAccess xCellsEA = + xRangeCont.getCells(); + unoidl.com.sun.star.container.XEnumeration xEnum = + xCellsEA.createEnumeration(); + while( xEnum.hasMoreElements() ) + { + uno.Any aCellObj = xEnum.nextElement(); + unoidl.com.sun.star.sheet.XCellAddressable xAddr = + (unoidl.com.sun.star.sheet.XCellAddressable) aCellObj.Value; + unoidl.com.sun.star.table.CellAddress aAddr = + xAddr.getCellAddress(); + Console.WriteLine( + getCellAddressString( aAddr.Column, aAddr.Row ) + " " ); + } + Console.WriteLine(); + } + + /** Inserts a cell range address into a cell range container and prints + a message. + @param xContainer unoidl.com.sun.star.sheet.XSheetCellRangeContainer + interface of the container. + @param nSheet Index of sheet of the range. + @param nStartCol Index of first column of the range. + @param nStartRow Index of first row of the range. + @param nEndCol Index of last column of the range. + @param nEndRow Index of last row of the range. + @param bMerge Determines whether the new range should be merged + with the existing ranges. + */ + private void insertRange( + unoidl.com.sun.star.sheet.XSheetCellRangeContainer xContainer, + int nSheet, int nStartCol, int nStartRow, int nEndCol, int nEndRow, + bool bMerge ) + { + unoidl.com.sun.star.table.CellRangeAddress aAddress = + new unoidl.com.sun.star.table.CellRangeAddress(); + aAddress.Sheet = (short)nSheet; + aAddress.StartColumn = nStartCol; + aAddress.StartRow = nStartRow; + aAddress.EndColumn = nEndCol; + aAddress.EndRow = nEndRow; + xContainer.addRangeAddress( aAddress, bMerge ); + Console.WriteLine( + "Inserting " + getCellRangeAddressString( aAddress ) + + " " + (bMerge ? " with" : "without") + " merge," + + " resulting list: " + xContainer.getRangeAddressesAsString() ); + } + + + + /** All samples regarding cell cursors. */ + private void doCellCursorSamples() + { + Console.WriteLine( "\n*** Samples for cell cursor ***\n" ); + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 0 ); + + + // --- Find the array formula using a cell cursor --- + unoidl.com.sun.star.table.XCellRange xRange = + xSheet.getCellRangeByName( "F22" ); + unoidl.com.sun.star.sheet.XSheetCellRange xCellRange = + (unoidl.com.sun.star.sheet.XSheetCellRange) xRange; + unoidl.com.sun.star.sheet.XSheetCellCursor xCursor = + xSheet.createCursorByRange( xCellRange ); + + xCursor.collapseToCurrentArray(); + unoidl.com.sun.star.sheet.XArrayFormulaRange xArray = + (unoidl.com.sun.star.sheet.XArrayFormulaRange) xCursor; + Console.WriteLine( + "Array formula in " + getCellRangeAddressString( xCursor, false ) + + " contains formula " + xArray.getArrayFormula() ); + + + // --- Find the used area --- + unoidl.com.sun.star.sheet.XUsedAreaCursor xUsedCursor = + (unoidl.com.sun.star.sheet.XUsedAreaCursor) xCursor; + xUsedCursor.gotoStartOfUsedArea( false ); + xUsedCursor.gotoEndOfUsedArea( true ); + // xUsedCursor and xCursor are interfaces of the same object - + // so modifying xUsedCursor takes effect on xCursor: + Console.WriteLine( + "The used area is: " + getCellRangeAddressString( xCursor, true ) ); + } + + + + /** All samples regarding the formatting of cells and ranges. */ + private void doFormattingSamples() + { + Console.WriteLine( "\n*** Formatting samples ***\n" ); + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 1 ); + unoidl.com.sun.star.table.XCellRange xCellRange; + unoidl.com.sun.star.beans.XPropertySet xPropSet = null; + unoidl.com.sun.star.container.XIndexAccess xRangeIA = null; + unoidl.com.sun.star.lang.XMultiServiceFactory xServiceManager; + + + // --- Cell styles --- + // get the cell style container + unoidl.com.sun.star.style.XStyleFamiliesSupplier xFamiliesSupplier = + (unoidl.com.sun.star.style.XStyleFamiliesSupplier) getDocument(); + unoidl.com.sun.star.container.XNameAccess xFamiliesNA = + xFamiliesSupplier.getStyleFamilies(); + uno.Any aCellStylesObj = xFamiliesNA.getByName( "CellStyles" ); + unoidl.com.sun.star.container.XNameContainer xCellStylesNA = + (unoidl.com.sun.star.container.XNameContainer) aCellStylesObj.Value; + + // create a new cell style + xServiceManager = + (unoidl.com.sun.star.lang.XMultiServiceFactory) getDocument(); + Object aCellStyle = xServiceManager.createInstance( + "com.sun.star.style.CellStyle" ); + String aStyleName = "MyNewCellStyle"; + xCellStylesNA.insertByName( + aStyleName, new uno.Any( typeof (Object), aCellStyle ) ); + + // modify properties of the new style + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) aCellStyle; + xPropSet.setPropertyValue( + "CellBackColor", new uno.Any( (Int32) 0x888888 ) ); + xPropSet.setPropertyValue( + "IsCellBackgroundTransparent", new uno.Any( false ) ); + + + + // --- Query equal-formatted cell ranges --- + // prepare example, use the new cell style + xCellRange = xSheet.getCellRangeByName( "D2:F2" ); + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCellRange; + xPropSet.setPropertyValue( "CellStyle", new uno.Any( aStyleName ) ); + + xCellRange = xSheet.getCellRangeByName( "A3:G3" ); + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCellRange; + xPropSet.setPropertyValue( "CellStyle", new uno.Any( aStyleName ) ); + + // All ranges in one container + xCellRange = xSheet.getCellRangeByName( "A1:G3" ); + Console.WriteLine( "Service CellFormatRanges:" ); + unoidl.com.sun.star.sheet.XCellFormatRangesSupplier xFormatSupp = + (unoidl.com.sun.star.sheet.XCellFormatRangesSupplier) xCellRange; + xRangeIA = xFormatSupp.getCellFormatRanges(); + Console.WriteLine( getCellRangeListString( xRangeIA ) ); + + // Ranges sorted in SheetCellRanges containers + Console.WriteLine( "\nService UniqueCellFormatRanges:" ); + unoidl.com.sun.star.sheet.XUniqueCellFormatRangesSupplier + xUniqueFormatSupp = + (unoidl.com.sun.star.sheet.XUniqueCellFormatRangesSupplier) + xCellRange; + unoidl.com.sun.star.container.XIndexAccess xRangesIA = + xUniqueFormatSupp.getUniqueCellFormatRanges(); + int nCount = xRangesIA.getCount(); + for (int nIndex = 0; nIndex < nCount; ++nIndex) + { + uno.Any aRangesObj = xRangesIA.getByIndex( nIndex ); + xRangeIA = + (unoidl.com.sun.star.container.XIndexAccess) aRangesObj.Value; + Console.WriteLine( + "Container " + (nIndex + 1) + ": " + + getCellRangeListString( xRangeIA ) ); + } + + + // --- Table auto formats --- + // get the global collection of table auto formats, + // use global service manager + xServiceManager = getServiceManager(); + Object aAutoFormatsObj = xServiceManager.createInstance( + "com.sun.star.sheet.TableAutoFormats" ); + unoidl.com.sun.star.container.XNameContainer xAutoFormatsNA = + (unoidl.com.sun.star.container.XNameContainer) aAutoFormatsObj; + + // create a new table auto format and insert into the container + String aAutoFormatName = "Temp_Example"; + bool bExistsAlready = xAutoFormatsNA.hasByName( aAutoFormatName ); + uno.Any aAutoFormatObj; + if (bExistsAlready) + // auto format already exists -> use it + aAutoFormatObj = xAutoFormatsNA.getByName( aAutoFormatName ); + else + { + // create a new auto format (with document service manager!) + xServiceManager = + (unoidl.com.sun.star.lang.XMultiServiceFactory) getDocument(); + aAutoFormatObj = new uno.Any( + typeof (Object), + xServiceManager.createInstance( + "com.sun.star.sheet.TableAutoFormat" ) ); + xAutoFormatsNA.insertByName( aAutoFormatName, aAutoFormatObj ); + } + // index access to the auto format fields + unoidl.com.sun.star.container.XIndexAccess xAutoFormatIA = + (unoidl.com.sun.star.container.XIndexAccess) aAutoFormatObj.Value; + + // set properties of all auto format fields + for (int nRow = 0; nRow < 4; ++nRow) + { + int nRowColor = 0; + switch (nRow) + { + case 0: nRowColor = 0x999999; break; + case 1: nRowColor = 0xFFFFCC; break; + case 2: nRowColor = 0xEEEEEE; break; + case 3: nRowColor = 0x999999; break; + } + + for (int nColumn = 0; nColumn < 4; ++nColumn) + { + int nColor = nRowColor; + if ((nColumn == 0) || (nColumn == 3)) + nColor -= 0x333300; + + // get the auto format field and apply properties + uno.Any aFieldObj = xAutoFormatIA.getByIndex( + 4 * nRow + nColumn ); + xPropSet = + (unoidl.com.sun.star.beans.XPropertySet) aFieldObj.Value; + xPropSet.setPropertyValue( + "CellBackColor", new uno.Any( (Int32) nColor ) ); + } + } + + // set the auto format to the spreadsheet + xCellRange = xSheet.getCellRangeByName( "A5:H25" ); + unoidl.com.sun.star.table.XAutoFormattable xAutoForm = + (unoidl.com.sun.star.table.XAutoFormattable) xCellRange; + xAutoForm.autoFormat( aAutoFormatName ); + + // remove the auto format + if (!bExistsAlready) + xAutoFormatsNA.removeByName( aAutoFormatName ); + + + // --- Conditional formats --- + xSheet = getSpreadsheet( 0 ); + prepareRange( xSheet, "K20:K23", "Cond. Format" ); + setValue( xSheet, "K21", 1 ); + setValue( xSheet, "K22", 2 ); + setValue( xSheet, "K23", 3 ); + + // get the conditional format object of the cell range + xCellRange = xSheet.getCellRangeByName( "K21:K23" ); + xPropSet = (unoidl.com.sun.star.beans.XPropertySet) xCellRange; + unoidl.com.sun.star.sheet.XSheetConditionalEntries xEntries = + (unoidl.com.sun.star.sheet.XSheetConditionalEntries) + xPropSet.getPropertyValue( "ConditionalFormat" ).Value; + + // create a condition and apply it to the range + unoidl.com.sun.star.beans.PropertyValue[] aCondition = + new unoidl.com.sun.star.beans.PropertyValue[3]; + aCondition[0] = new unoidl.com.sun.star.beans.PropertyValue(); + aCondition[0].Name = "Operator"; + aCondition[0].Value = + new uno.Any( + typeof (unoidl.com.sun.star.sheet.ConditionOperator), + unoidl.com.sun.star.sheet.ConditionOperator.GREATER ); + aCondition[1] = new unoidl.com.sun.star.beans.PropertyValue(); + aCondition[1].Name = "Formula1"; + aCondition[1].Value = new uno.Any( "1" ); + aCondition[2] = new unoidl.com.sun.star.beans.PropertyValue(); + aCondition[2].Name = "StyleName"; + aCondition[2].Value = new uno.Any( aStyleName ); + xEntries.addNew( aCondition ); + xPropSet.setPropertyValue( + "ConditionalFormat", + new uno.Any( + typeof (unoidl.com.sun.star.sheet.XSheetConditionalEntries), + xEntries ) ); + } + + + + /** All samples regarding the spreadsheet document. */ + private void doDocumentSamples() + { + Console.WriteLine( "\n*** Samples for spreadsheet document ***\n" ); + + + // --- Insert a new spreadsheet --- + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = + insertSpreadsheet( "A new sheet", (short) 0x7FFF ); + + + // --- Copy a cell range --- + prepareRange( xSheet, "A1:B3", "Copy from" ); + prepareRange( xSheet, "D1:E3", "To" ); + setValue( xSheet, "A2", 123 ); + setValue( xSheet, "B2", 345 ); + setFormula( xSheet, "A3", "=SUM(A2:B2)" ); + setFormula( xSheet, "B3", "=FORMULA(A3)" ); + + unoidl.com.sun.star.sheet.XCellRangeMovement xMovement = + (unoidl.com.sun.star.sheet.XCellRangeMovement) xSheet; + unoidl.com.sun.star.table.CellRangeAddress aSourceRange = + createCellRangeAddress( xSheet, "A2:B3" ); + unoidl.com.sun.star.table.CellAddress aDestCell = + createCellAddress( xSheet, "D2" ); + xMovement.copyRange( aDestCell, aSourceRange ); + + + // --- Print automatic column page breaks --- + unoidl.com.sun.star.sheet.XSheetPageBreak xPageBreak = + (unoidl.com.sun.star.sheet.XSheetPageBreak) xSheet; + unoidl.com.sun.star.sheet.TablePageBreakData[] aPageBreakArray = + xPageBreak.getColumnPageBreaks(); + + Console.Write( "Automatic column page breaks:" ); + for (int nIndex = 0; nIndex < aPageBreakArray.Length; ++nIndex) + if (!aPageBreakArray[nIndex].ManualBreak) + Console.Write( " " + aPageBreakArray[nIndex].Position ); + Console.WriteLine(); + + + // --- Document properties --- + unoidl.com.sun.star.beans.XPropertySet xPropSet = + (unoidl.com.sun.star.beans.XPropertySet) getDocument(); + + String aText = "Value of property IsIterationEnabled: "; + aText += + (Boolean) xPropSet.getPropertyValue( "IsIterationEnabled" ).Value; + Console.WriteLine( aText ); + aText = "Value of property IterationCount: "; + aText += (Int32) xPropSet.getPropertyValue( "IterationCount" ).Value; + Console.WriteLine( aText ); + aText = "Value of property NullDate: "; + unoidl.com.sun.star.util.Date aDate = (unoidl.com.sun.star.util.Date) + xPropSet.getPropertyValue( "NullDate" ).Value; + aText += aDate.Year + "-" + aDate.Month + "-" + aDate.Day; + Console.WriteLine( aText ); + + + // --- Data validation --- + prepareRange( xSheet, "A5:C7", "Validation" ); + setFormula( xSheet, "A6", "Insert values between 0.0 and 5.0 below:" ); + + unoidl.com.sun.star.table.XCellRange xCellRange = + xSheet.getCellRangeByName( "A7:C7" ); + unoidl.com.sun.star.beans.XPropertySet xCellPropSet = + (unoidl.com.sun.star.beans.XPropertySet) xCellRange; + // validation properties + unoidl.com.sun.star.beans.XPropertySet xValidPropSet = + (unoidl.com.sun.star.beans.XPropertySet) + xCellPropSet.getPropertyValue( "Validation" ).Value; + xValidPropSet.setPropertyValue( + "Type", + new uno.Any( + typeof (unoidl.com.sun.star.sheet.ValidationType), + unoidl.com.sun.star.sheet.ValidationType.DECIMAL ) ); + xValidPropSet.setPropertyValue( + "ShowErrorMessage", new uno.Any( true ) ); + xValidPropSet.setPropertyValue( + "ErrorMessage", new uno.Any( "This is an invalid value!" ) ); + xValidPropSet.setPropertyValue( + "ErrorAlertStyle", + new uno.Any( + typeof (unoidl.com.sun.star.sheet.ValidationAlertStyle), + unoidl.com.sun.star.sheet.ValidationAlertStyle.STOP ) ); + // condition + unoidl.com.sun.star.sheet.XSheetCondition xCondition = + (unoidl.com.sun.star.sheet.XSheetCondition) xValidPropSet; + xCondition.setOperator( + unoidl.com.sun.star.sheet.ConditionOperator.BETWEEN ); + xCondition.setFormula1( "0.0" ); + xCondition.setFormula2( "5.0" ); + // apply on cell range + xCellPropSet.setPropertyValue( + "Validation", + new uno.Any( + typeof (unoidl.com.sun.star.beans.XPropertySet), + xValidPropSet ) ); + + + // --- Scenarios --- + uno.Any [][] aValues = { + new uno.Any [] { uno.Any.VOID, uno.Any.VOID }, + new uno.Any [] { uno.Any.VOID, uno.Any.VOID } + }; + + aValues[ 0 ][ 0 ] = new uno.Any( (Double) 11 ); + aValues[ 0 ][ 1 ] = new uno.Any( (Double) 12 ); + aValues[ 1 ][ 0 ] = new uno.Any( "Test13" ); + aValues[ 1 ][ 1 ] = new uno.Any( "Test14" ); + insertScenario( + xSheet, "B10:C11", aValues, + "First Scenario", "The first scenario." ); + + aValues[ 0 ][ 0 ] = new uno.Any( "Test21" ); + aValues[ 0 ][ 1 ] = new uno.Any( "Test22" ); + aValues[ 1 ][ 0 ] = new uno.Any( (Double) 23 ); + aValues[ 1 ][ 1 ] = new uno.Any( (Double) 24 ); + insertScenario( + xSheet, "B10:C11", aValues, + "Second Scenario", "The visible scenario." ); + + aValues[ 0 ][ 0 ] = new uno.Any( (Double) 31 ); + aValues[ 0 ][ 1 ] = new uno.Any( (Double) 32 ); + aValues[ 1 ][ 0 ] = new uno.Any( "Test33" ); + aValues[ 1 ][ 1 ] = new uno.Any( "Test34" ); + insertScenario( + xSheet, "B10:C11", aValues, + "Third Scenario", "The last scenario." ); + + // show second scenario + showScenario( xSheet, "Second Scenario" ); + } + + /** Inserts a scenario containing one cell range into a sheet and + applies the value array. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aRange The range address for the scenario. + @param aValueArray The array of cell contents. + @param aScenarioName The name of the new scenario. + @param aScenarioComment The user comment for the scenario. */ + private void insertScenario( + unoidl.com.sun.star.sheet.XSpreadsheet xSheet, + String aRange, + uno.Any [][] aValueArray, + String aScenarioName, + String aScenarioComment ) + { + // get the cell range with the given address + unoidl.com.sun.star.table.XCellRange xCellRange = + xSheet.getCellRangeByName( aRange ); + + // create the range address sequence + unoidl.com.sun.star.sheet.XCellRangeAddressable xAddr = + (unoidl.com.sun.star.sheet.XCellRangeAddressable) xCellRange; + unoidl.com.sun.star.table.CellRangeAddress[] aRangesSeq = + new unoidl.com.sun.star.table.CellRangeAddress[1]; + aRangesSeq[0] = xAddr.getRangeAddress(); + + // create the scenario + unoidl.com.sun.star.sheet.XScenariosSupplier xScenSupp = + (unoidl.com.sun.star.sheet.XScenariosSupplier) xSheet; + unoidl.com.sun.star.sheet.XScenarios xScenarios = + xScenSupp.getScenarios(); + xScenarios.addNewByName( aScenarioName, aRangesSeq, aScenarioComment ); + + // insert the values into the range + unoidl.com.sun.star.sheet.XCellRangeData xData = + (unoidl.com.sun.star.sheet.XCellRangeData) xCellRange; + xData.setDataArray( aValueArray ); + } + + /** Activates a scenario. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aScenarioName The name of the scenario. */ + private void showScenario( + unoidl.com.sun.star.sheet.XSpreadsheet xSheet, + String aScenarioName ) + { + // get the scenario set + unoidl.com.sun.star.sheet.XScenariosSupplier xScenSupp = + (unoidl.com.sun.star.sheet.XScenariosSupplier) xSheet; + unoidl.com.sun.star.sheet.XScenarios xScenarios = + xScenSupp.getScenarios(); + + // get the scenario and activate it + uno.Any aScenarioObj = xScenarios.getByName( aScenarioName ); + unoidl.com.sun.star.sheet.XScenario xScenario = + (unoidl.com.sun.star.sheet.XScenario) aScenarioObj.Value; + xScenario.apply(); + } + + + + private void doNamedRangesSamples() + { + Console.WriteLine( "\n*** Samples for named ranges ***\n" ); + unoidl.com.sun.star.sheet.XSpreadsheetDocument xDocument = + getDocument(); + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = + getSpreadsheet( 0 ); + + + // --- Named ranges --- + prepareRange( xSheet, "G42:H45", "Named ranges" ); + xSheet.getCellByPosition( 6, 42 ).setValue( 1 ); + xSheet.getCellByPosition( 6, 43 ).setValue( 2 ); + xSheet.getCellByPosition( 7, 42 ).setValue( 3 ); + xSheet.getCellByPosition( 7, 43 ).setValue( 4 ); + + // insert a named range + unoidl.com.sun.star.beans.XPropertySet xDocProp = + (unoidl.com.sun.star.beans.XPropertySet) xDocument; + uno.Any aRangesObj = xDocProp.getPropertyValue( "NamedRanges" ); + unoidl.com.sun.star.sheet.XNamedRanges xNamedRanges = + (unoidl.com.sun.star.sheet.XNamedRanges) aRangesObj.Value; + unoidl.com.sun.star.table.CellAddress aRefPos = + new unoidl.com.sun.star.table.CellAddress(); + aRefPos.Sheet = 0; + aRefPos.Column = 6; + aRefPos.Row = 44; + xNamedRanges.addNewByName( "ExampleName", "SUM(G43:G44)", aRefPos, 0 ); + + // use the named range in formulas + xSheet.getCellByPosition( 6, 44 ).setFormula( "=ExampleName" ); + xSheet.getCellByPosition( 7, 44 ).setFormula( "=ExampleName" ); + + + // --- Label ranges --- + prepareRange( xSheet, "G47:I50", "Label ranges" ); + unoidl.com.sun.star.table.XCellRange xRange = + xSheet.getCellRangeByPosition( 6, 47, 7, 49 ); + unoidl.com.sun.star.sheet.XCellRangeData xData = + ( unoidl.com.sun.star.sheet.XCellRangeData ) xRange; + uno.Any [][] aValues = + { + new uno.Any [] { new uno.Any( "Apples" ), + new uno.Any( "Oranges" ) }, + new uno.Any [] { new uno.Any( (Double) 5 ), + new uno.Any( (Double) 7 ) }, + new uno.Any [] { new uno.Any( (Double) 6 ), + new uno.Any( (Double) 8 ) } + }; + xData.setDataArray( aValues ); + + // insert a column label range + uno.Any aLabelsObj = xDocProp.getPropertyValue( "ColumnLabelRanges" ); + unoidl.com.sun.star.sheet.XLabelRanges xLabelRanges = + (unoidl.com.sun.star.sheet.XLabelRanges) aLabelsObj.Value; + unoidl.com.sun.star.table.CellRangeAddress aLabelArea = + new unoidl.com.sun.star.table.CellRangeAddress(); + aLabelArea.Sheet = 0; + aLabelArea.StartColumn = 6; + aLabelArea.StartRow = 47; + aLabelArea.EndColumn = 7; + aLabelArea.EndRow = 47; + unoidl.com.sun.star.table.CellRangeAddress aDataArea = + new unoidl.com.sun.star.table.CellRangeAddress(); + aDataArea.Sheet = 0; + aDataArea.StartColumn = 6; + aDataArea.StartRow = 48; + aDataArea.EndColumn = 7; + aDataArea.EndRow = 49; + xLabelRanges.addNew( aLabelArea, aDataArea ); + + // use the label range in formulas + xSheet.getCellByPosition( 8, 48 ).setFormula( "=Apples+Oranges" ); + xSheet.getCellByPosition( 8, 49 ).setFormula( "=Apples+Oranges" ); + } + + + + /** Helper for doDatabaseSamples: get name of first database. */ + private String getFirstDatabaseName() + { + String aDatabase = null; + unoidl.com.sun.star.lang.XMultiServiceFactory xServiceManager = + getServiceManager(); + unoidl.com.sun.star.container.XNameAccess xContext = + (unoidl.com.sun.star.container.XNameAccess) + xServiceManager.createInstance( + "com.sun.star.sdb.DatabaseContext" ); + String[] aNames = xContext.getElementNames(); + if ( aNames.Length > 0 ) + aDatabase = aNames[0]; + return aDatabase; + } + + /** Helper for doDatabaseSamples: get name of first table in a database. */ + private String getFirstTableName( String aDatabase ) + { + if ( aDatabase == null ) + return null; + + String aTable = null; + unoidl.com.sun.star.lang.XMultiServiceFactory xServiceManager = + getServiceManager(); + unoidl.com.sun.star.container.XNameAccess xContext = + (unoidl.com.sun.star.container.XNameAccess) + xServiceManager.createInstance( + "com.sun.star.sdb.DatabaseContext" ); + unoidl.com.sun.star.sdb.XCompletedConnection xSource = + (unoidl.com.sun.star.sdb.XCompletedConnection) + xContext.getByName( aDatabase ).Value; + unoidl.com.sun.star.task.XInteractionHandler xHandler = + (unoidl.com.sun.star.task.XInteractionHandler) + xServiceManager.createInstance( + "com.sun.star.task.InteractionHandler" ); + unoidl.com.sun.star.sdbcx.XTablesSupplier xSupplier = + (unoidl.com.sun.star.sdbcx.XTablesSupplier) + xSource.connectWithCompletion( xHandler ); + unoidl.com.sun.star.container.XNameAccess xTables = + xSupplier.getTables(); + String[] aNames = xTables.getElementNames(); + if ( aNames.Length > 0 ) + aTable = aNames[0]; + return aTable; + } + + private void doDatabaseSamples() + { + Console.WriteLine( "\n*** Samples for database operations ***\n" ); + unoidl.com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 2 ); + + + // --- put some example data into the sheet --- + unoidl.com.sun.star.table.XCellRange xRange = + xSheet.getCellRangeByName( "B3:D24" ); + unoidl.com.sun.star.sheet.XCellRangeData xData = + (unoidl.com.sun.star.sheet.XCellRangeData) xRange; + uno.Any [][] aValues = + { + new uno.Any [] { new uno.Any( "Name" ), + new uno.Any( "Year" ), + new uno.Any( "Sales" ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( (Double) 2001 ), + new uno.Any( (Double) 4.0 ) }, + new uno.Any [] { new uno.Any( "Carol" ), + new uno.Any( (Double) 1997 ), + new uno.Any( (Double) 3.0 ) }, + new uno.Any [] { new uno.Any( "Carol" ), + new uno.Any( (Double) 1998 ), + new uno.Any( (Double) 8.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( (Double) 1997 ), + new uno.Any( (Double) 8.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( (Double) 2002 ), + new uno.Any( (Double) 9.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( (Double) 1999 ), + new uno.Any( (Double) 7.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( (Double) 1996 ), + new uno.Any( (Double) 3.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( (Double) 2000 ), + new uno.Any( (Double) 1.0 ) }, + new uno.Any [] { new uno.Any( "Carol" ), + new uno.Any( (Double) 1999 ), + new uno.Any( (Double) 5.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( (Double) 2002 ), + new uno.Any( (Double) 1.0 ) }, + new uno.Any [] { new uno.Any( "Carol" ), + new uno.Any( (Double) 2001 ), + new uno.Any( (Double) 5.0 ) }, + new uno.Any [] { new uno.Any( "Carol" ), + new uno.Any( (Double) 2000 ), + new uno.Any( (Double) 1.0 ) }, + new uno.Any [] { new uno.Any( "Carol" ), + new uno.Any( (Double) 1996 ), + new uno.Any( (Double) 8.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( (Double) 1996 ), + new uno.Any( (Double) 7.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( (Double) 1997 ), + new uno.Any( (Double) 3.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( (Double) 2000 ), + new uno.Any( (Double) 9.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( (Double) 1998 ), + new uno.Any( (Double) 1.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( (Double) 1999 ), + new uno.Any( (Double) 6.0 ) }, + new uno.Any [] { new uno.Any( "Carol" ), + new uno.Any( (Double) 2002 ), + new uno.Any( (Double) 8.0 ) }, + new uno.Any [] { new uno.Any( "Alice" ), + new uno.Any( (Double) 1998 ), + new uno.Any( (Double) 5.0 ) }, + new uno.Any [] { new uno.Any( "Bob" ), + new uno.Any( (Double) 2001 ), + new uno.Any( (Double) 6.0 ) } + }; + xData.setDataArray( aValues ); + + + // --- filter for second column >= 1998 --- + unoidl.com.sun.star.sheet.XSheetFilterable xFilter = + (unoidl.com.sun.star.sheet.XSheetFilterable) xRange; + unoidl.com.sun.star.sheet.XSheetFilterDescriptor xFilterDesc = + xFilter.createFilterDescriptor( true ); + unoidl.com.sun.star.sheet.TableFilterField[] aFilterFields = + new unoidl.com.sun.star.sheet.TableFilterField[1]; + aFilterFields[0] = new unoidl.com.sun.star.sheet.TableFilterField(); + aFilterFields[0].Field = 1; + aFilterFields[0].IsNumeric = true; + aFilterFields[0].Operator = + unoidl.com.sun.star.sheet.FilterOperator.GREATER_EQUAL; + aFilterFields[0].NumericValue = 1998; + xFilterDesc.setFilterFields( aFilterFields ); + unoidl.com.sun.star.beans.XPropertySet xFilterProp = + (unoidl.com.sun.star.beans.XPropertySet) xFilterDesc; + xFilterProp.setPropertyValue( + "ContainsHeader", new uno.Any( true ) ); + xFilter.filter( xFilterDesc ); + + + // --- do the same filter as above, using criteria from a cell range --- + unoidl.com.sun.star.table.XCellRange xCritRange = + xSheet.getCellRangeByName( "B27:B28" ); + unoidl.com.sun.star.sheet.XCellRangeData xCritData = + (unoidl.com.sun.star.sheet.XCellRangeData) xCritRange; + uno.Any [][] aCritValues = + { + new uno.Any [] { new uno.Any( "Year" ) }, + new uno.Any [] { new uno.Any( ">= 1998" ) } + }; + xCritData.setDataArray( aCritValues ); + unoidl.com.sun.star.sheet.XSheetFilterableEx xCriteria = + (unoidl.com.sun.star.sheet.XSheetFilterableEx) xCritRange; + xFilterDesc = xCriteria.createFilterDescriptorByObject( xFilter ); + if ( xFilterDesc != null ) + xFilter.filter( xFilterDesc ); + + + // --- sort by second column, ascending --- + unoidl.com.sun.star.util.SortField[] aSortFields = + new unoidl.com.sun.star.util.SortField[1]; + aSortFields[0] = new unoidl.com.sun.star.util.SortField(); + aSortFields[0].Field = 1; + aSortFields[0].SortAscending = true; + + unoidl.com.sun.star.beans.PropertyValue[] aSortDesc = + new unoidl.com.sun.star.beans.PropertyValue[2]; + aSortDesc[0] = new unoidl.com.sun.star.beans.PropertyValue(); + aSortDesc[0].Name = "SortFields"; + aSortDesc[0].Value = + new uno.Any( + typeof (unoidl.com.sun.star.util.SortField []), + aSortFields ); + aSortDesc[1] = new unoidl.com.sun.star.beans.PropertyValue(); + aSortDesc[1].Name = "ContainsHeader"; + aSortDesc[1].Value = new uno.Any( true ); + + unoidl.com.sun.star.util.XSortable xSort = + (unoidl.com.sun.star.util.XSortable) xRange; + xSort.sort( aSortDesc ); + + + // --- insert subtotals --- + unoidl.com.sun.star.sheet.XSubTotalCalculatable xSub = + (unoidl.com.sun.star.sheet.XSubTotalCalculatable) xRange; + unoidl.com.sun.star.sheet.XSubTotalDescriptor xSubDesc = + xSub.createSubTotalDescriptor( true ); + unoidl.com.sun.star.sheet.SubTotalColumn[] aColumns = + new unoidl.com.sun.star.sheet.SubTotalColumn[1]; + // calculate sum of third column + aColumns[0] = new unoidl.com.sun.star.sheet.SubTotalColumn(); + aColumns[0].Column = 2; + aColumns[0].Function = unoidl.com.sun.star.sheet.GeneralFunction.SUM; + // group by first column + xSubDesc.addNew( aColumns, 0 ); + xSub.applySubTotals( xSubDesc, true ); + + String aDatabase = getFirstDatabaseName(); + String aTableName = getFirstTableName( aDatabase ); + if ( aDatabase != null && aTableName != null ) + { + // --- import from database --- + unoidl.com.sun.star.beans.PropertyValue[] aImportDesc = + new unoidl.com.sun.star.beans.PropertyValue[3]; + aImportDesc[0] = new unoidl.com.sun.star.beans.PropertyValue(); + aImportDesc[0].Name = "DatabaseName"; + aImportDesc[0].Value = new uno.Any( aDatabase ); + aImportDesc[1] = new unoidl.com.sun.star.beans.PropertyValue(); + aImportDesc[1].Name = "SourceType"; + aImportDesc[1].Value = + new uno.Any( + typeof (unoidl.com.sun.star.sheet.DataImportMode), + unoidl.com.sun.star.sheet.DataImportMode.TABLE ); + aImportDesc[2] = new unoidl.com.sun.star.beans.PropertyValue(); + aImportDesc[2].Name = "SourceObject"; + aImportDesc[2].Value = new uno.Any( aTableName ); + + unoidl.com.sun.star.table.XCellRange xImportRange = + xSheet.getCellRangeByName( "B35:B35" ); + unoidl.com.sun.star.util.XImportable xImport = + (unoidl.com.sun.star.util.XImportable) xImportRange; + xImport.doImport( aImportDesc ); + + + // --- use the temporary database range to find the + // imported data's size --- + unoidl.com.sun.star.beans.XPropertySet xDocProp = + (unoidl.com.sun.star.beans.XPropertySet) getDocument(); + uno.Any aRangesObj = xDocProp.getPropertyValue( "DatabaseRanges" ); + unoidl.com.sun.star.container.XNameAccess xRanges = + (unoidl.com.sun.star.container.XNameAccess) aRangesObj.Value; + String[] aNames = xRanges.getElementNames(); + for ( int i=0; i 2 Then +' Console.WriteLine("WriterDemo takes two arguments. A file url to the office" & _ +' "program directory and a connection string.") +' End If +'Connect to a running office +'-------------------------------------------------- + +'Create a service manager of the remote office +'Dim ht As Hashtable = New Hashtable() +'ht.Add("SYSBINDIR", args(0)) +Dim xContext As XComponentContext +'xLocalContext = Bootstrap.defaultBootstrap_InitialComponentContext( _ +' args(0) & "/uno.ini", ht.GetEnumerator()) + +xContext = Bootstrap.bootstrap() + +'Dim xURLResolver As XUnoUrlResolver +'xURLResolver = DirectCast(xLocalContext.getServiceManager(). _ +' createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", _ +' xLocalContext), XUnoUrlResolver) + +'Dim xRemoteContext As XComponentContext +'xRemoteContext = DirectCast(xURLResolver.resolve( _ +' "uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext"), _ +' XComponentContext) + +Dim xFactory As XMultiServiceFactory +xFactory = DirectCast(xContext.getServiceManager(), _ + XMultiServiceFactory) + +'Create the Desktop +Dim xDesktop As unoidl.com.sun.star.frame.XDesktop +xDesktop = DirectCast(xFactory.createInstance("com.sun.star.frame.Desktop"), _ + unoidl.com.sun.star.frame.XDesktop) + +'Open a new empty writer document +Dim xComponentLoader As unoidl.com.sun.star.frame.XComponentLoader +xComponentLoader = DirectCast(xDesktop, unoidl.com.sun.star.frame.XComponentLoader) +Dim arProps() As unoidl.com.sun.star.beans.PropertyValue = _ + New unoidl.com.sun.star.beans.PropertyValue(){} +Dim xComponent As unoidl.com.sun.star.lang.XComponent + xComponent = xComponentLoader.loadComponentFromURL( _ + "private:factory/swriter", "_blank", 0, arProps) +Dim xTextDocument As unoidl.com.sun.star.text.XTextDocument +xTextDocument = DirectCast(xComponent, unoidl.com.sun.star.text.XTextDocument) + +'Create a text object +Dim xText As unoidl.com.sun.star.text.XText +xText = xTextDocument.getText() + +Dim xSimpleText As unoidl.com.sun.star.text.XSimpleText +xSimpleText = DirectCast(xText, unoidl.com.sun.star.text.XSimpleText) + +'Create a cursor object +Dim xCursor As unoidl.com.sun.star.text.XTextCursor +xCursor = xSimpleText.createTextCursor() + +'Inserting some Text +xText.insertString(xCursor, "The first line in the newly created text document." _ + & vbLf, false) + +'Create instance of a text table with 4 columns and 4 rows +Dim objTextTable As Object +objTextTable= DirectCast(xTextDocument, unoidl.com.sun.star.lang.XMultiServiceFactory). _ + createInstance("com.sun.star.text.TextTable") +Dim xTextTable As unoidl.com.sun.star.text.XTextTable +xTextTable = DirectCast(objTextTable, unoidl.com.sun.star.text.XTextTable) +xTextTable.initialize(4, 4) +xText.insertTextContent(xCursor, xTextTable, false) + +'Set the table background color +Dim xPropertySetTable As unoidl.com.sun.star.beans.XPropertySet +xPropertySetTable = DirectCast(objTextTable, unoidl.com.sun.star.beans.XPropertySet) +xPropertySetTable.setPropertyValue("BackTransparent", New uno.Any(False)) +xPropertySetTable.setPropertyValue("BackColor", New uno.Any(&Hccccff)) + +'Get first row +Dim xTableRows As unoidl.com.sun.star.table.XTableRows +xTableRows = xTextTable.getRows() +Dim anyRow As uno.Any +anyRow = DirectCast(xTableRows, unoidl.com.sun.star.container.XIndexAccess).getByIndex( 0) + +'Set a different background color for the first row +Dim xPropertySetFirstRow As unoidl.com.sun.star.beans.XPropertySet +xPropertySetFirstRow = DirectCast(anyRow.Value, unoidl.com.sun.star.beans.XPropertySet) +xPropertySetFirstRow.setPropertyValue("BackTransparent", New uno.Any(False)) +xPropertySetFirstRow.setPropertyValue("BackColor", New uno.Any(&H6666AA)) + +'Fill the first table row +insertIntoCell("A1","FirstColumn", xTextTable) +insertIntoCell("B1","SecondColumn", xTextTable) +insertIntoCell("C1","ThirdColumn", xTextTable) +insertIntoCell("D1","SUM", xTextTable) + +'Fill the remaining rows +xTextTable.getCellByName("A2").setValue(22.5) +xTextTable.getCellByName("B2").setValue(5615.3) +xTextTable.getCellByName("C2").setValue(-2315.7) +xTextTable.getCellByName("D2").setFormula("sum ") + +xTextTable.getCellByName("A3").setValue(21.5) +xTextTable.getCellByName("B3").setValue (615.3) +xTextTable.getCellByName("C3").setValue( -315.7) +xTextTable.getCellByName("D3").setFormula( "sum ") + +xTextTable.getCellByName("A4").setValue( 121.5) +xTextTable.getCellByName("B4").setValue( -615.3) +xTextTable.getCellByName("C4").setValue( 415.7) +xTextTable.getCellByName("D4").setFormula( "sum ") + +'Change the CharColor and add a Shadow +Dim xPropertySetCursor As unoidl.com.sun.star.beans.XPropertySet +xPropertySetCursor = DirectCast(xCursor, unoidl.com.sun.star.beans.XPropertySet) +xPropertySetCursor.setPropertyValue("CharColor", New uno.Any(255)) +xPropertySetCursor.setPropertyValue("CharShadowed", New uno.Any(true)) + +'Create a paragraph break +xSimpleText.insertControlCharacter(xCursor, _ + unoidl.com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False) + +'Inserting colored Text. +xSimpleText.insertString(xCursor," This is a colored Text - blue with shadow" & vbLf, _ + False) + +'Create a paragraph break +xSimpleText.insertControlCharacter(xCursor, _ + unoidl.com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False) + +'Create a TextFrame. +Dim objTextFrame As Object +objTextFrame = DirectCast(xTextDocument, unoidl.com.sun.star.lang.XMultiServiceFactory). _ + createInstance("com.sun.star.text.TextFrame") + +Dim xTextFrame As unoidl.com.sun.star.text.XTextFrame = _ + DirectCast(objTextFrame, unoidl.com.sun.star.text.XTextFrame) + +'Set the size of the frame +Dim aSize As unoidl.com.sun.star.awt.Size = _ + New unoidl.com.sun.star.awt.Size(15000, 400) +DirectCast(xTextFrame, unoidl.com.sun.star.drawing.XShape).setSize(aSize) + +'Set anchortype +Dim xPropertySetFrame As unoidl.com.sun.star.beans.XPropertySet +xPropertySetFrame = DirectCast(xTextFrame, unoidl.com.sun.star.beans.XPropertySet) +xPropertySetFrame.setPropertyValue("AnchorType", New uno.Any( _ + GetType(unoidl.com.sun.star.text.TextContentAnchorType), _ + unoidl.com.sun.star.text.TextContentAnchorType.AS_CHARACTER)) + +'insert the frame +xText.insertTextContent(xCursor, xTextFrame, False) + +'Get the text object of the frame + +Dim xFrameText As unoidl.com.sun.star.text.XText +xFrameText = xTextFrame.getText() + +Dim xFrameSimpleText As unoidl.com.sun.star.text.XSimpleText +xFrameSimpleText = DirectCast(xFrameText, unoidl.com.sun.star.text.XSimpleText) + +'Create a cursor object +Dim xFrameCursor As unoidl.com.sun.star.text.XTextCursor +xFrameCursor = xFrameSimpleText.createTextCursor() + +'Inserting some Text +xFrameSimpleText.insertString(xFrameCursor, _ + "The first line in the newly created text frame.", False) +xFrameSimpleText.insertString(xFrameCursor, _ + vbLf & "With this second line the height of the frame raises.", False) + +'Create a paragraph break +xSimpleText.insertControlCharacter(xFrameCursor, _ + unoidl.com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, False) + +'Change the CharColor and add a Shadow +xPropertySetCursor.setPropertyValue("CharColor", New uno.Any(65536)) +xPropertySetCursor.setPropertyValue("CharShadowed", New uno.Any(False)) + +'Insert another string +xText.insertString(xCursor, vbLf + " That's all for now !!", False) + +End Sub + +Sub insertIntoCell(sCellName As String,sText As String, _ + xTable As unoidl.com.sun.star.text.XTextTable) + Dim xCell As unoidl.com.sun.star.table.XCell + xCell = xTable.getCellByName(sCellName) + + Dim xSimpleTextCell As unoidl.com.sun.star.text.XSimpleText + xSimpleTextCell = DirectCast(xCell, unoidl.com.sun.star.text.XSimpleText) + + Dim xCursor As unoidl.com.sun.star.text.XTextCursor + xCursor = xSimpleTextCell.createTextCursor() + + Dim xPropertySetCursor As unoidl.com.sun.star.beans.XPropertySet + xPropertySetCursor = DirectCast(xCursor, unoidl.com.sun.star.beans.XPropertySet) + + xPropertySetCursor.setPropertyValue("CharColor", New uno.Any(&Hffffff)) + xSimpleTextCell.insertString(xCursor, sText, False) +End Sub + +End Module diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/CreatingDialogs.odt b/odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/CreatingDialogs.odt new file mode 100644 index 000000000..dd55f9076 Binary files /dev/null and b/odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/CreatingDialogs.odt differ diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/Makefile b/odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/Makefile new file mode 100644 index 000000000..3af249f9d --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/Makefile @@ -0,0 +1,138 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the CreatingDialogs example of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=BaDCreatingDialogsExample +OUT_COMP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +COMPONENT_NAME=SampleDialog +COMPONENT_PACKAGE = $(OUT_BIN)/$(COMPONENT_NAME).$(UNOOXT_EXT) +COMPONENT_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMPONENT_NAME).$(UNOOXT_EXT)") +COMPONENT_JAR_NAME = $(COMPONENT_NAME).uno.jar +COMPONENT_JAR = $(OUT_CLASS)/$(COMPONENT_JAR_NAME) +COMPONENT_MANIFESTFILE = $(OUT_COMP_CLASS)/$(COMPONENT_NAME).uno.Manifest +COMPONENT_UNOPKG_MANIFEST = $(OUT_COMP_CLASS)/$(COMPONENT_NAME)/META-INF/manifest.xml +REGISTERFLAG = $(OUT_MISC)/devguide_basicanddialogs_creatingdialogs_register_component.flag + +# often the java files are structured in a hierarchy similar to the package, +# for the example we know the package +PACKAGE = com.sun.star.comp.sdk.examples + +JAVAFILES = \ + SampleDialog.java + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(JAVAFILES)) + +$(COMPONENT_NAME)_CLASSFILES = SampleDialog.class \ + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + + +# Targets +.PHONY: ALL +ALL: $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_CLASS)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo RegistrationClassName: $(PACKAGE).$(basename $(basename $(@F)))> $@ + +$(OUT_COMP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $< + +# rule for component jar file +$(COMPONENT_JAR) : $(COMPONENT_MANIFESTFILE) $(CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(OUT_COMP_CLASS) . + +# rule for component package manifest +$(OUT_COMP_CLASS)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-component;type=Java$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(OUT_COMP_CLASS)/,,$(@D))).uno.jar$(QM)"/$(CSEP) >> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMPONENT_PACKAGE) : $(COMPONENT_JAR) $(COMPONENT_UNOPKG_MANIFEST) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + cd $(subst /,$(PS),$(OUT_CLASS)) && $(SDK_ZIP) ../bin/$(@F) $( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(EXAMPLE_NAME) : $(REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The SampleDialog Java component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo Please load the "$(QM)CreatingDialogs.odt$(QM)" document to use the component or use it + @echo by yourself in your office installation, see the example description. + @echo - + @echo $(MAKE) CreatingDialogs.odt.load + @echo -------------------------------------------------------------------------------- + +CreatingDialogs.odt.load : $(REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMPONENT_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(REGISTERFLAG))) diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/SampleDialog.java b/odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/SampleDialog.java new file mode 100644 index 000000000..d5a976c59 --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/CreatingDialogs/SampleDialog.java @@ -0,0 +1,278 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +package com.sun.star.comp.sdk.examples; + +import com.sun.star.awt.ActionEvent; +import com.sun.star.awt.XActionListener; +import com.sun.star.awt.XButton; +import com.sun.star.lang.XComponent; +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.XFixedText; +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.EventObject; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; +import com.sun.star.lang.XTypeProvider; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.registry.XRegistryKey; +import com.sun.star.task.XJobExecutor; +import com.sun.star.uno.Type; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + + +/** example of a Java component which creates a dialog at runtime + + This component can be tested by the following StarOffice Basic code: + Sub Main + Dim oJobExecutor + oJobExecutor = CreateUnoService( "com.sun.star.examples.SampleDialog" ) + oJobExecutor.trigger( "execute" ) + End Sub +*/ + +public class SampleDialog extends WeakBase implements XServiceInfo, XJobExecutor { + + static final String __serviceName = "com.sun.star.examples.SampleDialog"; + + private static final String _buttonName = "Button1"; + private static final String _cancelButtonName = "CancelButton"; + private static final String _labelName = "Label1"; + private static final String _labelPrefix = "Number of button clicks: "; + + private XComponentContext _xComponentContext; + + public SampleDialog( XComponentContext xComponentContext ) { + _xComponentContext = xComponentContext; + } + + // static component operations + public static XSingleServiceFactory __getServiceFactory( String implName, + XMultiServiceFactory multiFactory, + XRegistryKey regKey ) { + XSingleServiceFactory xSingleServiceFactory = null; + if ( implName.equals( SampleDialog.class.getName() ) ) { + xSingleServiceFactory = FactoryHelper.getServiceFactory( + SampleDialog.class, SampleDialog.__serviceName, multiFactory, regKey ); + } + return xSingleServiceFactory; + } + + public static boolean __writeRegistryServiceInfo( XRegistryKey regKey ) { + return FactoryHelper.writeRegistryServiceInfo( + SampleDialog.class.getName(), SampleDialog.__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; + } + + // XJobExecutor + public void trigger(String sEvent) { + if ( sEvent.equals( "execute" ) ) { + try { + createDialog(); + } + catch ( Exception e ) { + throw new com.sun.star.lang.WrappedTargetRuntimeException( e, e.getMessage(), this, e ); + } + } + } + + /** method for creating a dialog at runtime + */ + private void 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", Integer.valueOf( 100 ) ); + xPSetDialog.setPropertyValue( "PositionY", Integer.valueOf( 100 ) ); + xPSetDialog.setPropertyValue( "Width", Integer.valueOf( 150 ) ); + xPSetDialog.setPropertyValue( "Height", Integer.valueOf( 100 ) ); + xPSetDialog.setPropertyValue( "Title", "Runtime Dialog Demo" ); + + // get the service manager from the dialog model + XMultiServiceFactory xMultiServiceFactory = ( XMultiServiceFactory )UnoRuntime.queryInterface( + XMultiServiceFactory.class, dialogModel ); + + // create the button model and set the properties + Object buttonModel = xMultiServiceFactory.createInstance( + "com.sun.star.awt.UnoControlButtonModel" ); + XPropertySet xPSetButton = ( XPropertySet )UnoRuntime.queryInterface( + XPropertySet.class, buttonModel ); + xPSetButton.setPropertyValue( "PositionX", Integer.valueOf( 20 ) ); + xPSetButton.setPropertyValue( "PositionY", Integer.valueOf( 70 ) ); + xPSetButton.setPropertyValue( "Width", Integer.valueOf( 50 ) ); + xPSetButton.setPropertyValue( "Height", Integer.valueOf( 14 ) ); + xPSetButton.setPropertyValue( "Name", _buttonName ); + xPSetButton.setPropertyValue( "TabIndex", Short.valueOf( (short)0 ) ); + xPSetButton.setPropertyValue( "Label", "Click Me" ); + + // 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", Integer.valueOf( 40 ) ); + xPSetLabel.setPropertyValue( "PositionY", Integer.valueOf( 30 ) ); + xPSetLabel.setPropertyValue( "Width", Integer.valueOf( 100 ) ); + xPSetLabel.setPropertyValue( "Height", Integer.valueOf( 14 ) ); + xPSetLabel.setPropertyValue( "Name", _labelName ); + xPSetLabel.setPropertyValue( "TabIndex", Short.valueOf( (short)1 ) ); + xPSetLabel.setPropertyValue( "Label", _labelPrefix ); + + // create a Cancel button model and set the properties + Object cancelButtonModel = xMultiServiceFactory.createInstance( + "com.sun.star.awt.UnoControlButtonModel" ); + XPropertySet xPSetCancelButton = ( XPropertySet )UnoRuntime.queryInterface( + XPropertySet.class, cancelButtonModel ); + xPSetCancelButton.setPropertyValue( "PositionX", Integer.valueOf( 80 ) ); + xPSetCancelButton.setPropertyValue( "PositionY", Integer.valueOf( 70 ) ); + xPSetCancelButton.setPropertyValue( "Width", Integer.valueOf( 50 ) ); + xPSetCancelButton.setPropertyValue( "Height", Integer.valueOf( 14 ) ); + xPSetCancelButton.setPropertyValue( "Name", _cancelButtonName ); + xPSetCancelButton.setPropertyValue( "TabIndex", Short.valueOf( (short)2 ) ); + xPSetCancelButton.setPropertyValue( "PushButtonType", Short.valueOf( (short)2 ) ); + xPSetCancelButton.setPropertyValue( "Label", "Cancel" ); + + // insert the control models into the dialog model + XNameContainer xNameCont = ( XNameContainer )UnoRuntime.queryInterface( + XNameContainer.class, dialogModel ); + xNameCont.insertByName( _buttonName, buttonModel ); + xNameCont.insertByName( _labelName, labelModel ); + xNameCont.insertByName( _cancelButtonName, 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 ); + + // add an action listener to the button control + XControlContainer xControlCont = ( XControlContainer )UnoRuntime.queryInterface( + XControlContainer.class, dialog ); + Object objectButton = xControlCont.getControl( "Button1" ); + XButton xButton = ( XButton )UnoRuntime.queryInterface( + XButton.class, objectButton ); + xButton.addActionListener( new ActionListenerImpl( 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 ); + + // execute the dialog + XDialog xDialog = ( XDialog )UnoRuntime.queryInterface( + XDialog.class, dialog ); + xDialog.execute(); + + // dispose the dialog + XComponent xComponent = ( XComponent )UnoRuntime.queryInterface( + XComponent.class, dialog ); + xComponent.dispose(); + } + + /** action listener + */ + public class ActionListenerImpl implements com.sun.star.awt.XActionListener { + + private int _nCounts = 0; + + private XControlContainer _xControlCont; + + public ActionListenerImpl( XControlContainer xControlCont ) { + _xControlCont = xControlCont; + } + + // XEventListener + public void disposing( EventObject eventObject ) { + _xControlCont = null; + } + + // XActionListener + public void actionPerformed( ActionEvent actionEvent ) { + + // increase click counter + _nCounts++; + + // set label text + Object label = _xControlCont.getControl( "Label1" ); + XFixedText xLabel = ( XFixedText )UnoRuntime.queryInterface( + XFixedText.class, label ); + xLabel.setText( _labelPrefix + _nCounts ); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/FirstStepsBasic.odt b/odk/examples/DevelopersGuide/BasicAndDialogs/FirstStepsBasic.odt new file mode 100644 index 000000000..4024740f1 Binary files /dev/null and b/odk/examples/DevelopersGuide/BasicAndDialogs/FirstStepsBasic.odt differ diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/Makefile b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/Makefile new file mode 100644 index 000000000..bd3a43444 --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/Makefile @@ -0,0 +1,125 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the CreatingDialogs example of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=BaDToolkitControls +SAMPLE_GEN_OUT=$(OUT_MISC)/$(SAMPLE_NAME) + +COMP_NAME=ToolkitControls +COMP_GEN_OUT=$(SAMPLE_GEN_OUT)/$(COMP_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_UNOPKG_MANIFEST = $(COMP_GEN_OUT)/META-INF/manifest.xml +COMP_REGISTERFLAG=$(COMP_GEN_OUT)$(PS)devguide_basic_$(COMP_NAME)_register_component.flag + +COMP_LIBRARY_FILES=\ + ToolkitControls/dialog.xlb\ + ToolkitControls/FileDialog.xba\ + ToolkitControls/FileDialogDlg.xdl\ + ToolkitControls/MultiPage.xba\ + ToolkitControls/MultiPageDlg.xdl\ + ToolkitControls/ProgressBar.xba\ + ToolkitControls/ProgressBarDlg.xdl\ + ToolkitControls/script.xlb\ + ToolkitControls/ScrollBar.xba\ + ToolkitControls/ScrollBarDlg.xdl + +# Targets +.PHONY: ALL +ALL : $(SAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +# rule for component package manifest +$(COMP_GEN_OUT)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.basic-library$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME)$(QM)"/$(CSEP) >> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_UNOPKG_MANIFEST) $(COMP_LIBRARY_FILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ ToolkitControls/dialog.xlb \ + ToolkitControls/FileDialog.xba ToolkitControls/FileDialogDlg.xdl \ + ToolkitControls/MultiPage.xba ToolkitControls/MultiPageDlg.xdl \ + ToolkitControls/ProgressBar.xba ToolkitControls/ProgressBarDlg.xdl \ + ToolkitControls/script.xlb ToolkitControls/ScrollBar.xba \ + ToolkitControls/ScrollBarDlg.xdl + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u ../../../bin/$(@F) META-INF/manifest.xml + +$(COMP_REGISTERFLAG) : $(COMP_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(COMP_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(SAMPLE_NAME) : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The "$(QM)ToolkitControls$(QM)" library was installed in your office installation + @echo if SDK_AUTO_DEPLOYMENT = YES. You can use it in the BASIC IDE as a normal + @echo Basic library. + @echo You can also load the document "$(QM)$(COMP_NAME).odt$(QM)" and press a button + @echo to run one of the example macros. + @echo - + @echo $(MAKE) $(COMP_NAME).odt.load + @echo -------------------------------------------------------------------------------- + +$(COMP_NAME).odt.load : $(COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(COMP_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls.odt b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls.odt new file mode 100644 index 000000000..ffedaa756 Binary files /dev/null and b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls.odt differ diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/FileDialog.xba b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/FileDialog.xba new file mode 100644 index 000000000..60f6a491f --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/FileDialog.xba @@ -0,0 +1,90 @@ + + + +REM ***** BASIC ***** + +Dim oDialog As Object + +Sub Main() + + Dim oLibContainer As Object, oLib As Object + Dim oInputStreamProvider As Object + + Const sLibName = "ToolkitControls" + Const sDialogName = "FileDialogDlg" + + REM load/get library and input stream provider + oLibContainer = DialogLibraries + oLibContainer.loadLibrary( sLibName ) + oLib = oLibContainer.getByName( sLibName ) + oInputStreamProvider = oLib.getByName( sDialogName ) + + REM create dialog control + oDialog = CreateUnoDialog( oInputStreamProvider ) + + REM show the dialog + oDialog.execute() + +End Sub + +Sub OpenFileDialog() + + Dim oFilePicker As Object, oSimpleFileAccess As Object + Dim oPathSettings As Object + Dim oTextField As Object, oTextFieldModel As Object + Dim sFileURL As String + Dim sFiles As Variant + + REM file dialog + oFilePicker = CreateUnoService( "com.sun.star.ui.dialogs.FilePicker" ) + + REM set filter + oFilePicker.AppendFilter( "All files", "*.*" ) + oFilePicker.AppendFilter( "StarOffice 6.0 Text Text Document", "*.sxw" ) + oFilePicker.AppendFilter( "StarOffice 6.0 Spreadsheet", "*.sxc" ) + oFilePicker.SetCurrentFilter( "All files" ) + + REM if no file URL is set, get path settings from configuration + oTextFieldModel = oDialog.Model.TextField1 + sFileURL = ConvertToURL( oTextFieldModel.Text ) + If sFileURL = "" Then + oSettings = CreateUnoService( "com.sun.star.frame.Settings" ) + oPathSettings = CreateUnoService( "com.sun.star.util.PathSettings" ) + sFileURL = oPathSettings.getPropertyValue( "Work" ) + End If + + REM set display directory + oSimpleFileAccess = CreateUnoService( "com.sun.star.ucb.SimpleFileAccess" ) + If oSimpleFileAccess.exists( sFileURL ) And oSimpleFileAccess.isFolder( sFileURL ) Then + oFilePicker.setDisplayDirectory( sFileURL ) + End If + + REM execute file dialog + If oFilePicker.execute() Then + sFiles = oFilePicker.getFiles() + sFileURL = sFiles(0) + If oSimpleFileAccess.exists( sFileURL ) Then + REM set file path in text field + oTextField = oDialog.GetControl("TextField1") + oTextField.SetText( ConvertFromURL( sFileURL ) ) + End If + End If + +End Sub + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/FileDialogDlg.xdl b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/FileDialogDlg.xdl new file mode 100644 index 000000000..ec99f7b48 --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/FileDialogDlg.xdl @@ -0,0 +1,29 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/MultiPage.xba b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/MultiPage.xba new file mode 100644 index 000000000..65f160614 --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/MultiPage.xba @@ -0,0 +1,303 @@ + + + +REM ***** BASIC ***** + +Dim oDialog As Object + +Sub Main() + + Dim oLibContainer As Object, oLib As Object + Dim oInputStreamProvider As Object + Dim oDialogModel As Object + + Const sLibName = "ToolkitControls" + Const sDialogName = "MultiPageDlg" + + REM load/get library and input stream provider + oLibContainer = DialogLibraries + oLibContainer.loadLibrary( sLibName ) + oLib = oLibContainer.getByName( sLibName ) + oInputStreamProvider = oLib.getByName( sDialogName ) + + REM create dialog control + oDialog = CreateUnoDialog( oInputStreamProvider ) + + REM initialize dialog and controls + Initialize() + + REM show the dialog + oDialog.execute() + +End Sub + + +Sub Initialize() + + Dim oDialogModel As Object + Dim oNextButton As Object, oNextButtonModel As Object + Dim oListBox As Object + Dim oCheckBoxModel As Object + Dim oOptionButtonModel As Object + Dim oCurrencyFieldModel As Object + Dim oNumericFieldModel As Object + Dim oComboBox As Object, oComboBoxModel As Object + Dim i As Integer + Dim sName As String + Dim sPizzas As Variant, sToppings As Variant + Dim sCreditCards As Variant + Dim sMonths As Variant + Dim iCount As Integer + + REM dialog properties + oDialogModel = oDialog.Model + oDialogModel.Step = 1 + + REM next button properties + oNextButtonModel = oDialogModel.NextButton + oNextButtonModel.DefaultButton = True + oNextButton = oDialog.getControl("NextButton") + oNextButton.setFocus() + + REM enable/disable back button, set label of next button + PageChanged() + + REM set control properties on dialog page 1 + + REM pizzas in list box + oListBox = oDialog.getControl("ListBox1") + sPizzas = Array("Margarita","Vegetarian","Ham & Pineapple","Mexican","Seafood") + oListBox.addItems( sPizzas, 0 ) + oListBox.selectItem( sPizzas(0), True ) + + REM extra toppings + sToppings = Array("Extra Cheese","Corn","Onions","Olives") + For i = 0 To 3 + sName = "CheckBox" + i + oCheckBoxModel = oDialogModel.getByName( sName ) + oCheckBoxModel.Label = sToppings( i ) + Next i + + REM default pizza size + oOptionButtonModel = oDialogModel.OptionButton2 + oOptionButtonModel.State = True + + REM currency field properties + oCurrencyFieldModel = oDialogModel.CurrencyField1 + oCurrencyFieldModel.ReadOnly = True + oCurrencyFieldModel.DecimalAccuracy = 2 + oCurrencyFieldModel.CurrencySymbol = "€" + oCurrencyFieldModel.PrependCurrencySymbol = True + + REM calculate prize for default settings + CalculatePrize() + + REM set control properties on dialog page 2 + + REM numeric field properties + oNumericFieldModel = oDialogModel.NumericField1 + oNumericFieldModel.DecimalAccuracy = 0 + + REM set control properties on dialog page 3 + + REM default payment method + oOptionButtonModel = oDialogModel.OptionButton4 + oOptionButtonModel.State = True + + REM credit cards in combo box + oComboBox = oDialog.getControl("ComboBox1") + sCreditCards = Array("Visa","Master/EuroCard","American Express") + oComboBox.addItems( sCreditCards, 0 ) + oComboBoxModel = oDialogModel.ComboBox1 + oComboBoxModel.Text = sCreditCards(0) + + REM expiration month + oListBox = oDialog.getControl("ListBox2") + sMonths = Array("01","02","03","04","05","06","07","08","09","10","11","12") + oListBox.addItems( sMonths, 0 ) + oListBox.selectItemPos( Month(Date())-1, True ) + + REM expiration year + oListBox = oDialog.getControl("ListBox3") + For i = Year(Date()) To Year(Date()) + 4 + iCount = oListBox.getItemCount() + oListBox.addItem( Str( i ), iCount ) + Next i + oListBox.selectItemPos( 0, True ) + +End Sub + + +Sub CalculatePrize() + + Dim oDialogModel As Object + Dim oListBox As Object + Dim oCheckBoxModel As Object + Dim oCurrencyFieldModel As Object + Dim Position As Integer + Dim sName As String + Dim i As Integer, nChecked As Integer + Dim Prizes As Variant + Dim Prize As Double + + REM prizes for medium size pizzas + Prizes = Array( 4, 5, 6, 6, 7 ) + + REM get the position of the currently selected pizza + oListBox = oDialog.getControl("ListBox1") + Position = oListBox.getSelectedItemPos() + Prize = Prizes( Position ) + + REM small pizzas are 1€ cheaper, large pizzas are 1€ more expensive + oDialogModel = oDialog.Model + If oDialogModel.OptionButton1.State = 1 Then + Prize = Prize - 1 + ElseIf oDialogModel.OptionButton3.State = 1 Then + Prize = Prize + 1 + End If + + REM get the number of extra toppings (0.5€ per extra topping) + For i = 0 To 3 + sName = "CheckBox" + i + oCheckBoxModel = oDialogModel.getByName( sName ) + If oCheckBoxModel.State = 1 Then + nChecked = nChecked + 1 + End If + Next i + Prize = Prize + nChecked * 0.5 + + REM set the value of the currency field + oCurrencyFieldModel = oDialogModel.CurrencyField1 + oCurrencyFieldModel.Value = Prize + +End Sub + + +Sub PaymentMethodChanged() + + Dim oDialogModel As Object + Dim bEnabled As Boolean + + REM get dialog model + oDialogModel = oDialog.getModel() + + If oDialogModel.OptionButton4.State = 1 Then + REM enable controls for payment by credit card + bEnabled = True + ElseIf oDialogModel.OptionButton5.State = 1 Then + REM disable controls for payment by check + bEnabled = False + End If + + REM enable/disable controls + With oDialogModel + .Label11.Enabled = bEnabled + .Label12.Enabled = bEnabled + .Label13.Enabled = bEnabled + .ComboBox1.Enabled = bEnabled + .TextField6.Enabled = bEnabled + .ListBox2.Enabled = bEnabled + .ListBox3.Enabled = bEnabled + .TextField7.Enabled = bEnabled + End With + +End Sub + + +Sub NextPage() + + Dim oDialogModel As Object + + REM get dialog model + oDialogModel = oDialog.getModel() + + If oDialogModel.Step < 3 Then + REM next page + oDialogModel.Step = oDialogModel.Step + 1 + REM enable/disable back button, set label of next button + PageChanged() + ElseIf oDialogModel.Step = 3 Then + REM submit order + SubmitOrder() + REM hide dialog + oDialog.endExecute() + End If + +End Sub + + +Sub PreviousPage() + + Dim oDialogModel As Object + + REM get dialog model + oDialogModel = oDialog.getModel() + + If oDialogModel.Step > 1 Then + REM previous page + oDialogModel.Step = oDialogModel.Step - 1 + REM enable/disable back button, set label of next button + PageChanged() + End If + +End Sub + + +Sub PageChanged() + + Dim oDialogModel As Object + Dim oBackButtonModel As Object + Dim oNextButtonModel As Object + + Const sLabelNext = "Next >>" + Const sLabelSubmit = "Submit" + + REM get dialog model + oDialogModel = oDialog.getModel() + + REM get back button model + oBackButtonModel = oDialogModel.getByName("BackButton") + + REM enable/disable back button + If oDialogModel.Step = 1 Then + oBackButtonModel.Enabled = False + Else + oBackButtonModel.Enabled = True + End If + + REM get next button model + oNextButtonModel = oDialogModel.getByName("NextButton") + + REM set label of next button + If oDialogModel.Step = 3 Then + oNextButtonModel.Label = sLabelSubmit + Else + oNextButtonModel.Label = sLabelNext + End If + +End Sub + + +Sub SubmitOrder() + + MsgBox "Your pizza will be delivered in 45 minutes." + +End Sub + + diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/MultiPageDlg.xdl b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/MultiPageDlg.xdl new file mode 100644 index 000000000..f7b28aa33 --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/MultiPageDlg.xdl @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ProgressBar.xba b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ProgressBar.xba new file mode 100644 index 000000000..8b34f0cc3 --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ProgressBar.xba @@ -0,0 +1,93 @@ + + + +REM ***** BASIC ***** + +Dim oDialog As Object + +Sub Main() + + Dim oLibContainer As Object, oLib As Object + Dim oInputStreamProvider As Object + Dim oProgressBar As Object + + Const sLibName = "ToolkitControls" + Const sDialogName = "ProgressBarDlg" + + REM load/get library and input stream provider + oLibContainer = DialogLibraries + oLibContainer.loadLibrary( sLibName ) + oLib = oLibContainer.getByName( sLibName ) + oInputStreamProvider = oLib.getByName( sDialogName ) + + REM create dialog control + oDialog = CreateUnoDialog( oInputStreamProvider ) + + REM hide progress bar + oProgressBar = oDialog.getControl("ProgressBar1") + oProgressBar.setVisible( False ) + + REM show the dialog + oDialog.execute() + +End Sub + +Sub ProgressBarDemo() + + Dim oProgressBar As Object, oProgressBarModel As Object + Dim oCancelButtonModel As Object + Dim oStartButtonModel As Object + Dim ProgressValue As Long + + REM progress bar settings + Const ProgressValueMin = 0 + Const ProgressValueMax = 50 + Const ProgressStep = 1 + + REM set minimum and maximum progress value + oProgressBarModel = oDialog.Model.ProgressBar1 + oProgressBarModel.ProgressValueMin = ProgressValueMin + oProgressBarModel.ProgressValueMax = ProgressValueMax + + REM disable cancel and start button + oCancelButtonModel = oDialog.Model.CommandButton1 + oCancelButtonModel.Enabled = False + oStartButtonModel = oDialog.Model.CommandButton2 + oStartButtonModel.Enabled = False + + REM show progress bar + oProgressBar = oDialog.getControl("ProgressBar1") + oProgressBar.setVisible( True ) + + REM increase progress value every second + For ProgressValue = ProgressValueMin To ProgressValueMax Step ProgressStep + oProgressBarModel.ProgressValue = ProgressValue + Wait 40 + Next ProgressValue + + REM hide progress bar + oProgressBar.setVisible( False ) + + REM enable cancel and start button + oCancelButtonModel.Enabled = True + oStartButtonModel.Enabled = True + +End Sub + + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ProgressBarDlg.xdl b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ProgressBarDlg.xdl new file mode 100644 index 000000000..4a5803273 --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ProgressBarDlg.xdl @@ -0,0 +1,28 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ScrollBar.xba b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ScrollBar.xba new file mode 100644 index 000000000..db2dd7cdd --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ScrollBar.xba @@ -0,0 +1,103 @@ + + + +REM ***** BASIC ***** + +Dim oDialog As Object +Const Border = 5 + +Sub Main() + + Dim oLibContainer As Object, oLib As Object + Dim oInputStreamProvider As Object + Dim oDialogModel As Object + Dim oScrollBarModel As Object + Dim oLabelModel As Object + Dim sLabel As String + Dim VisibleSize As Double + + Const sLibName = "ToolkitControls" + Const sDialogName = "ScrollBarDlg" + + REM load/get library and input stream provider + oLibContainer = DialogLibraries + oLibContainer.loadLibrary( sLibName ) + oLib = oLibContainer.getByName( sLibName ) + oInputStreamProvider = oLib.getByName( sDialogName ) + + REM create dialog control + oDialog = CreateUnoDialog( oInputStreamProvider ) + + REM set the label + sLabel = "This Text exceeds the visible area of the dialog and can be" + sLabel = sLabel + " scrolled horizontally by clicking on the scroll bar." + oDialogModel = oDialog.Model + oLabelModel = oDialogModel.Label1 + oLabelModel.Label = sLabel + + REM scroll bar settings + oScrollBarModel = oDialog.Model.ScrollBar1 + oScrollBarModel.ScrollValueMax = 100 + VisibleSize = (oDialogModel.Width - Border - oLabelModel.PositionX) / oLabelModel.Width + VisibleSize = VisibleSize * oScrollBarModel.ScrollValueMax + oScrollBarModel.VisibleSize = VisibleSize + oScrollBarModel.BlockIncrement = oScrollBarModel.VisibleSize + oScrollBarModel.LineIncrement = oScrollBarModel.BlockIncrement / 20 + + REM show the dialog + oDialog.execute() + +End Sub + +Sub AdjustmentHandler() + + Dim oLabelModel As Object + Dim oScrollBarModel As Object + Dim ScrollValue As Long, ScrollValueMax As Long + Dim VisibleSize As Long + Dim Factor As Double + + Static bInit As Boolean + Static PositionX0 As Long + Static Offset As Long + + REM get the model of the label control + oLabelModel = oDialog.Model.Label1 + + REM on initialization remember the position of the label control and calculate offset + If bInit = False Then + bInit = True + PositionX0 = oLabelModel.PositionX + OffSet = PositionX0 + oLabelModel.Width - (oDialog.Model.Width - Border) + End If + + REM get the model of the scroll bar control + oScrollBarModel = oDialog.Model.ScrollBar1 + + REM get the actual scroll value + ScrollValue = oScrollBarModel.ScrollValue + + REM calculate and set new position of the label control + ScrollValueMax = oScrollBarModel.ScrollValueMax + VisibleSize = oScrollBarModel.VisibleSize + Factor = Offset / (ScrollValueMax - VisibleSize) + oLabelModel.PositionX = PositionX0 - Factor * ScrollValue + +End Sub + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ScrollBarDlg.xdl b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ScrollBarDlg.xdl new file mode 100644 index 000000000..ae36d0000 --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/ScrollBarDlg.xdl @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/dialog.xlb b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/dialog.xlb new file mode 100644 index 000000000..a74e020a1 --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/dialog.xlb @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/script.xlb b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/script.xlb new file mode 100644 index 000000000..03741ae35 --- /dev/null +++ b/odk/examples/DevelopersGuide/BasicAndDialogs/ToolkitControls/ToolkitControls/script.xlb @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/Charts/AddInChart.ods b/odk/examples/DevelopersGuide/Charts/AddInChart.ods new file mode 100644 index 000000000..01708ed7b Binary files /dev/null and b/odk/examples/DevelopersGuide/Charts/AddInChart.ods differ diff --git a/odk/examples/DevelopersGuide/Charts/CalcHelper.java b/odk/examples/DevelopersGuide/Charts/CalcHelper.java new file mode 100644 index 000000000..d7d932282 --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/CalcHelper.java @@ -0,0 +1,396 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import java.util.Random; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XMultiServiceFactory; +// container access +import com.sun.star.container.*; + +// application specific classes +import com.sun.star.sheet.*; +import com.sun.star.table.*; +import com.sun.star.chart.*; +import com.sun.star.text.XText; + +import com.sun.star.document.XEmbeddedObjectSupplier; +import com.sun.star.frame.XModel; +// base graphics things +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; +import com.sun.star.awt.Rectangle; + +// Exceptions +import com.sun.star.uno.RuntimeException; +import com.sun.star.container.NoSuchElementException; + +// __________ Implementation __________ + +// Helper for accessing a calc document + +public class CalcHelper +{ + public CalcHelper( XSpreadsheetDocument aDoc ) + { + maSpreadSheetDoc = aDoc; + initSpreadSheet(); + } + + + + public XSpreadsheet getChartSheet() throws RuntimeException + { + XNameAccess aSheetsNA = UnoRuntime.queryInterface( + XNameAccess.class, maSpreadSheetDoc.getSheets() ); + + XSpreadsheet aSheet = null; + try + { + aSheet = UnoRuntime.queryInterface( + XSpreadsheet.class, aSheetsNA.getByName( msChartSheetName ) ); + } + catch( NoSuchElementException ex ) + { + System.out.println( "Couldn't find sheet with name " + msChartSheetName + ": " + ex ); + } + catch( Exception ex ) + {} + + return aSheet; + } + + + + public XSpreadsheet getDataSheet() throws RuntimeException + { + XNameAccess aSheetsNA = UnoRuntime.queryInterface( + XNameAccess.class, maSpreadSheetDoc.getSheets() ); + + XSpreadsheet aSheet = null; + if( aSheetsNA != null ) + { + try + { + aSheet = UnoRuntime.queryInterface( + XSpreadsheet.class, aSheetsNA.getByName( msDataSheetName ) ); + } + catch( NoSuchElementException ex ) + { + System.out.println( "Couldn't find sheet with name " + msDataSheetName + ": " + ex ); + } + catch( Exception ex ) + {} + } + + return aSheet; + } + + + + /** Insert a chart using the given name as name of the OLE object and the range as corresponding + range of data to be used for rendering. The chart is placed in the sheet for charts at + position aUpperLeft extending as large as given in aExtent. + + The service name must be the name of a diagram service that can be instantiated via the + factory of the chart document + */ + public XChartDocument insertChart( + String sChartName, + CellRangeAddress aRange, + Point aUpperLeft, + Size aExtent, + String sChartServiceName ) + { + XChartDocument aResult = null; + XTableChartsSupplier aSheet; + + // get the sheet to insert the chart + try + { + aSheet = UnoRuntime.queryInterface( + XTableChartsSupplier.class, getChartSheet() ); + } + catch( Exception ex ) + { + System.out.println( "Sheet not found" + ex ); + return aResult; + } + + XTableCharts aChartCollection = aSheet.getCharts(); + XNameAccess aChartCollectionNA = UnoRuntime.queryInterface( + XNameAccess.class, aChartCollection ); + + if( aChartCollectionNA != null && + ! aChartCollectionNA.hasByName( sChartName ) ) + { + Rectangle aRect = new Rectangle( aUpperLeft.X, aUpperLeft.Y, aExtent.Width, aExtent.Height ); + + CellRangeAddress[] aAddresses = new CellRangeAddress[ 1 ]; + aAddresses[ 0 ] = aRange; + + // first bool: ColumnHeaders + // second bool: RowHeaders + aChartCollection.addNewByName( sChartName, aRect, aAddresses, true, false ); + + try + { + XTableChart aTableChart = UnoRuntime.queryInterface( + XTableChart.class, aChartCollectionNA.getByName( sChartName )); + + // the table chart is an embedded object which contains the chart document + aResult = UnoRuntime.queryInterface( + XChartDocument.class, + UnoRuntime.queryInterface( + XEmbeddedObjectSupplier.class, + aTableChart ).getEmbeddedObject()); + + // create a diagram via the factory and set this as new diagram + aResult.setDiagram( + UnoRuntime.queryInterface( + XDiagram.class, + UnoRuntime.queryInterface( + XMultiServiceFactory.class, + aResult ).createInstance( sChartServiceName ))); + } + catch( NoSuchElementException ex ) + { + System.out.println( "Couldn't find chart with name " + sChartName + ": " + ex ); + } + catch( Exception ex ) + {} + } + + return aResult; + } + + + + /** Fill a rectangular range with random numbers. + The first column has increasing values + */ + public XCellRange insertRandomRange( int nColumnCount, int nRowCount ) + { + XCellRange aRange = null; + + // get the sheet to insert the chart + try + { + XSpreadsheet aSheet = getDataSheet(); + XCellRange aSheetRange = UnoRuntime.queryInterface( XCellRange.class, aSheet ); + + aRange = aSheetRange.getCellRangeByPosition( + 0, 0, + nColumnCount - 1, nRowCount - 1 ); + + int nCol, nRow; + double fBase = 0.0; + double fRange = 10.0; + double fValue; + Random aGenerator = new Random(); + + + for( nCol = 0; nCol < nColumnCount; nCol++ ) + { + if( 0 == nCol ) + { + (aSheet.getCellByPosition( nCol, 0 )).setFormula( "X" ); + } + else + { + (aSheet.getCellByPosition( nCol, 0 )).setFormula( "Random " + nCol ); + } + + for( nRow = 1; nRow < nRowCount; nRow++ ) + { + if( 0 == nCol ) + { + // x values: ascending numbers + fValue = nRow + aGenerator.nextDouble(); + } + else + { + fValue = fBase + ( aGenerator.nextGaussian() * fRange ); + } + + // put value into cell + + // note: getCellByPosition is a method at ...table.XCellRange which + // the XSpreadsheet inherits via ...sheet.XSheetCellRange + (aSheet.getCellByPosition( nCol, nRow )).setValue( fValue ); + } + } + + } + catch( Exception ex ) + { + System.out.println( "Sheet not found" + ex ); + } + + return aRange; + } + + + + public XCellRange insertFormulaRange( int nColumnCount, int nRowCount ) + { + XCellRange aRange = null; + + // get the sheet to insert the chart + try + { + XSpreadsheet aSheet = getDataSheet(); + XCellRange aSheetRange = UnoRuntime.queryInterface( XCellRange.class, aSheet ); + + aRange = aSheetRange.getCellRangeByPosition( + 0, 0, + nColumnCount - 1, nRowCount - 1 ); + + int nCol, nRow; + double fValue; + double fFactor = 2.0 * Math.PI / (nRowCount - 1); + String aFormula; + + // set variable factor for cos formula + int nFactorCol = nColumnCount + 2; + (aSheet.getCellByPosition( nFactorCol - 1, 0 )).setValue( 0.2 ); + + XText xCellText = UnoRuntime.queryInterface( XText.class, aSheet.getCellByPosition( nFactorCol - 1, 1 ) ); + xCellText.setString( "Change the factor above and\nwatch the changes in the chart" ); + + for( nCol = 0; nCol < nColumnCount; nCol++ ) + { + for( nRow = 0; nRow < nRowCount; nRow++ ) + { + if( 0 == nCol ) + { + // x values: ascending numbers + fValue = nRow * fFactor; + (aSheet.getCellByPosition( nCol, nRow )).setValue( fValue ); + } + else + { + aFormula = "="; + if( nCol % 2 == 0 ) + aFormula += "SIN"; + else + aFormula += "COS"; + aFormula += "(INDIRECT(ADDRESS(" + (nRow + 1) + ";1)))+RAND()*INDIRECT(ADDRESS(1;" + nFactorCol + "))"; + (aSheet.getCellByPosition( nCol, nRow )).setFormula( aFormula ); + } + } + } + + } + catch( Exception ex ) + { + System.out.println( "Sheet not found" + ex ); + } + + return aRange; + } + + + + /** Bring the sheet containing charts visually to the foreground + */ + public void raiseChartSheet() + { + UnoRuntime.queryInterface( + XSpreadsheetView.class, + UnoRuntime.queryInterface( + XModel.class, + maSpreadSheetDoc ).getCurrentController()).setActiveSheet( getChartSheet() ); + } + + + // __________ private members and methods __________ + + private static final String msDataSheetName = "Data"; + private static final String msChartSheetName = "Chart"; + + private final XSpreadsheetDocument maSpreadSheetDoc; + + + + + /** create two sheets, one for data and one for charts in the document + */ + private void initSpreadSheet() + { + if( maSpreadSheetDoc != null ) + { + XSpreadsheets aSheets = maSpreadSheetDoc.getSheets(); + XNameContainer aSheetsNC = UnoRuntime.queryInterface( + XNameContainer.class, aSheets ); + XIndexAccess aSheetsIA = UnoRuntime.queryInterface( + XIndexAccess.class, aSheets ); + + if( aSheets != null && + aSheetsNC != null && + aSheetsIA != null ) + { + try + { + // remove all sheets except one + for( int i = aSheetsIA.getCount() - 1; i > 0; i-- ) + { + aSheetsNC.removeByName( + UnoRuntime.queryInterface( + XNamed.class, aSheetsIA.getByIndex( i ) ).getName() ); + } + + XNamed aFirstSheet = UnoRuntime.queryInterface( + XNamed.class, + aSheetsIA.getByIndex( 0 )); + + // first sheet becomes data sheet + aFirstSheet.setName( msDataSheetName ); + + // second sheet becomes chart sheet + aSheets.insertNewByName( msChartSheetName, (short)1 ); + } + catch( Exception ex ) + { + System.out.println( "Couldn't initialize Spreadsheet Document: " + ex ); + } + } + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Charts/ChartHelper.java b/odk/examples/DevelopersGuide/Charts/ChartHelper.java new file mode 100644 index 000000000..7263ea7ad --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/ChartHelper.java @@ -0,0 +1,244 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + + +// base graphics things +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; +import com.sun.star.beans.XPropertySet; +// application specific classes +import com.sun.star.chart.XChartDocument; +import com.sun.star.chart.XDiagram; +import com.sun.star.drawing.XDrawPageSupplier; +import com.sun.star.drawing.XDrawPagesSupplier; +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.frame.XModel; +// factory for creating components +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.text.XText; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; +import com.sun.star.uno.Any; +import com.sun.star.uno.Type; +import com.sun.star.uno.UnoRuntime; + +// __________ Implementation __________ + +// Helper for creating an OLE chart + +public class ChartHelper +{ + public ChartHelper( XModel aContainerDoc ) + { + maContainerDocument = aContainerDoc; + } + + public XChartDocument insertOLEChartInWriter( + Point aUpperLeft, + Size aExtent, + String sChartServiceName ) + { + XChartDocument aResult = null; + + XMultiServiceFactory aFact = UnoRuntime.queryInterface(XMultiServiceFactory.class, + maContainerDocument ); + + if( aFact != null ) + { + try + { + XTextContent xTextContent = UnoRuntime.queryInterface( + XTextContent.class, + aFact.createInstance("com.sun.star.text.TextEmbeddedObject")); + + if ( xTextContent != null ) + { + XPropertySet xPropSet = UnoRuntime.queryInterface( + XPropertySet.class, xTextContent); + + Any aAny = new Any(new Type(String.class), msChartClassID); + xPropSet.setPropertyValue("CLSID", aAny ); + + XTextDocument xTextDoc = UnoRuntime.queryInterface(XTextDocument.class, + maContainerDocument); + XText xText = xTextDoc.getText(); + XTextCursor xCursor = xText.createTextCursor(); + + //insert embedded object in text -> object will be created + xText.insertTextContent( xCursor, xTextContent, true ); + + // set size and position + XShape xShape = UnoRuntime.queryInterface( + XShape.class, xTextContent); + xShape.setSize( aExtent ); + + aAny = new Any(new Type(Short.class), + Short.valueOf(com.sun.star.text.VertOrientation.NONE)); + xPropSet.setPropertyValue("VertOrient", aAny ); + aAny = new Any(new Type(Short.class), + Short.valueOf(com.sun.star.text.HoriOrientation.NONE)); + xPropSet.setPropertyValue("HoriOrient", aAny ); + aAny = new Any(new Type(Integer.class), Integer.valueOf(aUpperLeft.Y)); + xPropSet.setPropertyValue("VertOrientPosition", aAny ); + aAny = new Any(new Type(Integer.class), Integer.valueOf(aUpperLeft.X)); + xPropSet.setPropertyValue("HoriOrientPosition", aAny ); + + // retrieve the chart document as model of the OLE shape + aResult = UnoRuntime.queryInterface( + XChartDocument.class, + xPropSet.getPropertyValue( "Model" )); + + // create a diagram via the factory and set this as + // new diagram + aResult.setDiagram( + UnoRuntime.queryInterface( + XDiagram.class, + UnoRuntime.queryInterface( + XMultiServiceFactory.class, + aResult ).createInstance(sChartServiceName ))); + } + } catch( Exception ex) + { + System.out.println( "caught exception: " + ex ); + } + } + + return aResult; + } + + public XChartDocument insertOLEChartInDraw( + Point aUpperLeft, + Size aExtent, + String sChartServiceName ) + { + XChartDocument aResult = null; + + XShapes aPage = null; + + // try interface for multiple pages in a document + XDrawPagesSupplier aSupplier = UnoRuntime.queryInterface(XDrawPagesSupplier.class, + maContainerDocument ); + + if( aSupplier != null ) + { + try + { + // get first page + aPage = UnoRuntime.queryInterface( + XShapes.class, aSupplier.getDrawPages().getByIndex( 0 ) ); + } + catch( Exception ex ) + { + System.out.println( "First page not found in shape collection: " + + ex ); + } + } + else + { + // try interface for single draw page (e.g. spreadsheet) + XDrawPageSupplier aOnePageSupplier = UnoRuntime.queryInterface(XDrawPageSupplier.class, + maContainerDocument ); + + if( aOnePageSupplier != null ) + { + aPage = UnoRuntime.queryInterface( + XShapes.class, aOnePageSupplier.getDrawPage()); + } + } + + if( aPage != null ) + { + XMultiServiceFactory aFact = UnoRuntime.queryInterface(XMultiServiceFactory.class, + maContainerDocument ); + + if( aFact != null ) + { + try + { + // create an OLE shape + XShape aShape = UnoRuntime.queryInterface( + XShape.class, + aFact.createInstance( "com.sun.star.drawing.OLE2Shape" )); + + // insert the shape into the page + aPage.add( aShape ); + aShape.setPosition( aUpperLeft ); + aShape.setSize( aExtent ); + + // make the OLE shape a chart + XPropertySet aShapeProp = UnoRuntime.queryInterface(XPropertySet.class, aShape ); + if( aShapeProp != null ) + { + // set the class id for charts + aShapeProp.setPropertyValue( "CLSID", msChartClassID ); + + // retrieve the chart document as model of the OLE shape + aResult = UnoRuntime.queryInterface( + XChartDocument.class, + aShapeProp.getPropertyValue( "Model" )); + + // create a diagram via the factory and set this as + // new diagram + aResult.setDiagram( + UnoRuntime.queryInterface( + XDiagram.class, + UnoRuntime.queryInterface( + XMultiServiceFactory.class, + aResult ).createInstance(sChartServiceName ))); + } + } + catch( Exception ex ) + { + System.out.println( "Couldn't change the OLE shape into a chart: " + ex ); + } + } + } + + return aResult; + } + + + // __________ private members and methods __________ + + private static final String msChartClassID = "12dcae26-281f-416f-a234-c3086127382e"; + + private final XModel maContainerDocument; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Charts/ChartInCalc.java b/odk/examples/DevelopersGuide/Charts/ChartInCalc.java new file mode 100644 index 000000000..d974d6e45 --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/ChartInCalc.java @@ -0,0 +1,417 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.*; + +// property access +import com.sun.star.beans.*; + +// application specific classes +import com.sun.star.chart.*; +import com.sun.star.drawing.*; + +import com.sun.star.table.CellRangeAddress; +import com.sun.star.table.XCellRange; +import com.sun.star.sheet.XCellRangeAddressable; + +import com.sun.star.frame.XModel; +import com.sun.star.util.XNumberFormatsSupplier; +import com.sun.star.util.XNumberFormats; + +// base graphics things +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; +import com.sun.star.awt.FontWeight; +// Exceptions +import com.sun.star.uno.Exception; +import com.sun.star.uno.RuntimeException; +import com.sun.star.beans.UnknownPropertyException; +import com.sun.star.lang.IndexOutOfBoundsException; +import com.sun.star.util.MalformedNumberFormatException; + + +// __________ Implementation __________ + +// Create a spreadsheet add some data and add a chart + +public class ChartInCalc +{ + + + public static void main( String args[] ) + { + Helper aHelper = new Helper( args ); + + CalcHelper aCalcHelper = new CalcHelper( aHelper.createSpreadsheetDocument() ); + + // insert a cell range with 4 columns and 24 rows filled with random numbers + XCellRange aRange = aCalcHelper.insertRandomRange( 4, 24 ); + CellRangeAddress aRangeAddress = UnoRuntime.queryInterface( + XCellRangeAddressable.class, aRange).getRangeAddress(); + + // change view to sheet containing the chart + aCalcHelper.raiseChartSheet(); + + // the unit for measures is 1/100th of a millimeter + // position at (1cm, 1cm) + Point aPos = new Point( 1000, 1000 ); + + // size of the chart is 15cm x 9.271cm + Size aExtent = new Size( 15000, 9271 ); + + // insert a new chart into the "Chart" sheet of the + // spreadsheet document + XChartDocument aChartDoc = aCalcHelper.insertChart( + "ScatterChart", + aRangeAddress, + aPos, + aExtent, + "com.sun.star.chart.XYDiagram" ); + + // instantiate test class with newly created chart + ChartInCalc aTest = new ChartInCalc( aChartDoc ); + + try + { + aTest.lockControllers(); + + aTest.testDiagram(); + aTest.testArea(); + aTest.testWall(); + aTest.testTitle(); + aTest.testAxis(); + aTest.testGrid(); + + // show an intermediate state, ... + aTest.unlockControllers(); + aTest.lockControllers(); + + // ..., because the following takes a while: + // an internet URL has to be resolved + aTest.testDataRowProperties(); + aTest.testDataPointProperties(); + + aTest.unlockControllers(); + } + catch( Exception ex ) + { + System.out.println( "UNO Exception caught: " + ex ); + System.out.println( "Message: " + ex.getMessage() ); + } + + System.exit( 0 ); + } + + + + + public ChartInCalc( XChartDocument aChartDoc ) + { + maChartDocument = aChartDoc; + maDiagram = maChartDocument.getDiagram(); + } + + + + public void lockControllers() + throws RuntimeException + { + UnoRuntime.queryInterface( XModel.class, maChartDocument ).lockControllers(); + } + + + + public void unlockControllers() + throws RuntimeException + { + UnoRuntime.queryInterface( XModel.class, maChartDocument ).unlockControllers(); + } + + + + public void testDiagram() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + XPropertySet aDiaProp = UnoRuntime.queryInterface( XPropertySet.class, maDiagram ); + + if( aDiaProp != null ) + { + // change chart type + aDiaProp.setPropertyValue( "Lines", Boolean.TRUE); + + // change attributes for all series + // set line width to 0.5mm + aDiaProp.setPropertyValue( "LineWidth", Integer.valueOf( 50 )); + } + } + + + + public void testDataRowProperties() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + // change properties of the data series + try + { + XPropertySet aSeriesProp; + for( int i = 1; i <= 3; i++ ) + { + aSeriesProp = maDiagram.getDataRowProperties( i ); + aSeriesProp.setPropertyValue( "LineColor", Integer.valueOf( + 0x400000 * i + + 0x005000 * i + + 0x0000ff - 0x40 * i )); + if( 1 == i ) + { + StringBuffer sUrl = new StringBuffer("file:///"); + try { + /* for use without net it's easier to load a local graphic */ + java.io.File sourceFile = new java.io.File("bullet.gif"); + sUrl.append(sourceFile.getCanonicalPath().replace('\\', '/')); + } catch (java.io.IOException e) { + sUrl = new StringBuffer("http://graphics.openoffice.org/chart/bullet1.gif"); + } + + // set a bitmap via URL as symbol for the first series + aSeriesProp.setPropertyValue( "SymbolType", Integer.valueOf( ChartSymbolType.BITMAPURL )); + aSeriesProp.setPropertyValue( "SymbolBitmapURL", sUrl.toString() ); + } + else + { + aSeriesProp.setPropertyValue( "SymbolType", Integer.valueOf( ChartSymbolType.SYMBOL1 )); + aSeriesProp.setPropertyValue( "SymbolSize", new Size( 250, 250 )); + } + } + } + catch( IndexOutOfBoundsException ex ) + { + System.out.println( "Oops, there not enough series for setting properties: " + ex ); + } + } + + + + public void testDataPointProperties() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + // set properties for a single data point + try + { + // determine the maximum value of the first series + + XChartDataArray aDataArray = UnoRuntime.queryInterface( + XChartDataArray.class, maChartDocument.getData()); + double aData[][] = aDataArray.getData(); + + int i; + double fMax = aData[ 0 ][ 1 ]; + for( i = 1; i < aData.length; i++ ) + { + if( aData[ i ][ 1 ] > fMax ) + { + fMax = aData[ i ][ 1 ]; + } + } + + // first parameter is the index of the point, the second one is the series + XPropertySet aPointProp = maDiagram.getDataPointProperties( 0, 1 ); + + // set a different, larger symbol + aPointProp.setPropertyValue( "SymbolType", Integer.valueOf( ChartSymbolType.SYMBOL6 )); + aPointProp.setPropertyValue( "SymbolSize", new Size( 600, 600 )); + + // add a label text with bold font, bordeaux red 14pt + aPointProp.setPropertyValue( "DataCaption", Integer.valueOf( ChartDataCaption.VALUE )); + aPointProp.setPropertyValue( "CharHeight", new Float( 14.0 )); + aPointProp.setPropertyValue( "CharColor", Integer.valueOf( 0x993366 )); + aPointProp.setPropertyValue( "CharWeight", new Float( FontWeight.BOLD )); + } + catch( IndexOutOfBoundsException ex ) + { + System.out.println( "Oops, there not enough data points or series for setting properties: " + ex ); + } + } + + + + public void testArea() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + XPropertySet aArea = maChartDocument.getArea(); + + if( aArea != null ) + { + // change background color of entire chart + aArea.setPropertyValue( "FillStyle", FillStyle.SOLID ); + aArea.setPropertyValue( "FillColor", Integer.valueOf( 0xeeeeee )); + } + } + + + + public void testWall() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + XPropertySet aWall = UnoRuntime.queryInterface( + X3DDisplay.class, maDiagram ).getWall(); + + // change background color of area + aWall.setPropertyValue( "FillStyle", FillStyle.SOLID ); + aWall.setPropertyValue( "FillColor", Integer.valueOf( 0xcccccc )); + } + + + + public void testTitle() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + // change main title + XPropertySet aDocProp = UnoRuntime.queryInterface( + XPropertySet.class, maChartDocument ); + aDocProp.setPropertyValue( "HasMainTitle", Boolean.TRUE); + + XShape aTitle = maChartDocument.getTitle(); + XPropertySet aTitleProp = UnoRuntime.queryInterface( XPropertySet.class, aTitle ); + + // set new text + if( aTitleProp != null ) + { + aTitleProp.setPropertyValue( "String", "Random Scatter Chart" ); + aTitleProp.setPropertyValue( "CharHeight", new Float(14.0) ); + } + + // align title with y axis + XShape aAxis = UnoRuntime.queryInterface( + XShape.class, UnoRuntime.queryInterface( + XAxisYSupplier.class, maDiagram ).getYAxis() ); + + if( aAxis != null && + aTitle != null ) + { + Point aPos = aTitle.getPosition(); + aPos.X = ( aAxis.getPosition() ).X; + aTitle.setPosition( aPos ); + } + } + + + + public void testAxis() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException, + MalformedNumberFormatException + { + // x axis + XPropertySet aAxisProp = UnoRuntime.queryInterface( + XAxisXSupplier.class, maDiagram ).getXAxis(); + if( aAxisProp != null ) + { + aAxisProp.setPropertyValue( "Max", Integer.valueOf( 24 )); + aAxisProp.setPropertyValue( "StepMain", Integer.valueOf( 3 )); + } + + // change number format for y axis + aAxisProp = UnoRuntime.queryInterface( + XAxisYSupplier.class, maDiagram ).getYAxis(); + + // add a new custom number format and get the new key + int nNewNumberFormat = 0; + XNumberFormatsSupplier aNumFmtSupp = UnoRuntime.queryInterface( + XNumberFormatsSupplier.class, maChartDocument ); + + if( aNumFmtSupp != null ) + { + XNumberFormats aFormats = aNumFmtSupp.getNumberFormats(); + Locale aLocale = new Locale( "de", "DE", "de" ); + + String aFormatStr = aFormats.generateFormat( nNewNumberFormat, aLocale, true, true, (short)3, (short)1 ); + nNewNumberFormat = aFormats.addNew( aFormatStr, aLocale ); + } + + if( aAxisProp != null ) + { + aAxisProp.setPropertyValue( "NumberFormat", Integer.valueOf( nNewNumberFormat )); + } + } + + + + public void testGrid() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + // y major grid + XPropertySet aGridProp = UnoRuntime.queryInterface( + XPropertySet.class, + UnoRuntime.queryInterface( + XAxisYSupplier.class, maDiagram ).getYMainGrid()); + + if( aGridProp != null ) + { + LineDash aDash = new LineDash(); + aDash.Style = DashStyle.ROUND; + aDash.Dots = 2; + aDash.DotLen = 10; + aDash.Dashes = 1; + aDash.DashLen = 200; + aDash.Distance = 100; + + aGridProp.setPropertyValue( "LineColor", Integer.valueOf( 0x999999 )); + aGridProp.setPropertyValue( "LineStyle", LineStyle.DASH ); + aGridProp.setPropertyValue( "LineDash", aDash ); + aGridProp.setPropertyValue( "LineWidth", Integer.valueOf( 30 )); + } + } + + + + + // private members + + + private final XChartDocument maChartDocument; + private final XDiagram maDiagram; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Charts/ChartInDraw.java b/odk/examples/DevelopersGuide/Charts/ChartInDraw.java new file mode 100644 index 000000000..d13b6d07f --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/ChartInDraw.java @@ -0,0 +1,294 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.*; + +// property access +import com.sun.star.beans.*; + +// application specific classes +import com.sun.star.chart.*; +import com.sun.star.drawing.*; + +import com.sun.star.frame.XModel; +// base graphics things +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; +// Exceptions +import com.sun.star.uno.Exception; +import com.sun.star.uno.RuntimeException; +import com.sun.star.beans.UnknownPropertyException; + + +// __________ Implementation __________ + +// Create a spreadsheet add some data and add a chart + +public class ChartInDraw +{ + + + public static void main( String args[] ) + { + Helper aHelper = new Helper( args ); + + ChartHelper aChartHelper = new ChartHelper( aHelper.createDrawingDocument()); + + // the unit for measures is 1/100th of a millimeter + // position at (1cm, 1cm) + Point aPos = new Point( 1000, 1000 ); + + // size of the chart is 15cm x 12cm + Size aExtent = new Size( 15000, 13000 ); + + // insert a new chart into the "Chart" sheet of the + // spreadsheet document + XChartDocument aChartDoc = aChartHelper.insertOLEChartInDraw( + aPos, + aExtent, + "com.sun.star.chart.BarDiagram" ); + + // instantiate test class with newly created chart + ChartInDraw aTest = new ChartInDraw( aChartDoc ); + + try + { + aTest.lockControllers(); + + aTest.testArea(); + aTest.testWall(); + aTest.testTitle(); + aTest.testLegend(); + aTest.testThreeD(); + + aTest.unlockControllers(); + } + catch( Exception ex ) + { + System.out.println( "UNO Exception caught: " + ex ); + System.out.println( "Message: " + ex.getMessage() ); + } + + System.exit( 0 ); + } + + + + + public ChartInDraw( XChartDocument aChartDoc ) + { + maChartDocument = aChartDoc; + maDiagram = maChartDocument.getDiagram(); + } + + + + public void lockControllers() + throws RuntimeException + { + UnoRuntime.queryInterface( XModel.class, maChartDocument ).lockControllers(); + } + + + + public void unlockControllers() + throws RuntimeException + { + UnoRuntime.queryInterface( XModel.class, maChartDocument ).unlockControllers(); + } + + + + public void testArea() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + XPropertySet aArea = maChartDocument.getArea(); + + if( aArea != null ) + { + // change background color of entire chart + aArea.setPropertyValue( "FillStyle", FillStyle.SOLID ); + aArea.setPropertyValue( "FillColor", Integer.valueOf( 0xeeeeee )); + } + } + + + + public void testWall() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + XPropertySet aWall = UnoRuntime.queryInterface( + X3DDisplay.class, maDiagram ).getWall(); + + // change background color of area + aWall.setPropertyValue( "FillColor", Integer.valueOf( 0xcccccc )); + aWall.setPropertyValue( "FillStyle", FillStyle.SOLID ); + } + + + + public void testTitle() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + // change main title + XPropertySet aDocProp = UnoRuntime.queryInterface( + XPropertySet.class, maChartDocument ); + aDocProp.setPropertyValue( "HasMainTitle", Boolean.TRUE); + + XShape aTitle = maChartDocument.getTitle(); + XPropertySet aTitleProp = UnoRuntime.queryInterface( XPropertySet.class, aTitle ); + + // set new text + if( aTitleProp != null ) + { + aTitleProp.setPropertyValue( "String", "Bar Chart in a Draw Document" ); + } + } + + + + public void testLegend() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + XShape aLegend = maChartDocument.getLegend(); + XPropertySet aLegendProp = UnoRuntime.queryInterface( XPropertySet.class, aLegend ); + + aLegendProp.setPropertyValue( "Alignment", ChartLegendPosition.LEFT ); + aLegendProp.setPropertyValue( "FillStyle", FillStyle.SOLID ); + aLegendProp.setPropertyValue( "FillColor", Integer.valueOf( 0xeeddee )); + } + + + + public void testThreeD() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + XPropertySet aDiaProp = UnoRuntime.queryInterface( XPropertySet.class, maDiagram ); + Boolean aTrue = Boolean.TRUE; + + aDiaProp.setPropertyValue( "Dim3D", aTrue ); + aDiaProp.setPropertyValue( "Deep", aTrue ); + // from Chart3DBarProperties: + aDiaProp.setPropertyValue( "SolidType", Integer.valueOf( ChartSolidType.CYLINDER )); + + // change floor color to Magenta6 + XPropertySet aFloor = UnoRuntime.queryInterface( + X3DDisplay.class, maDiagram ).getFloor(); + aFloor.setPropertyValue( "FillColor", Integer.valueOf( 0x6b2394 )); + + // apply changes to get a 3d scene + unlockControllers(); + lockControllers(); + + + // rotate scene to a different angle + HomogenMatrix aMatrix = new HomogenMatrix(); + HomogenMatrixLine aLines[] = new HomogenMatrixLine[] + { + new HomogenMatrixLine( 1.0, 0.0, 0.0, 0.0 ), + new HomogenMatrixLine( 0.0, 1.0, 0.0, 0.0 ), + new HomogenMatrixLine( 0.0, 0.0, 1.0, 0.0 ), + new HomogenMatrixLine( 0.0, 0.0, 0.0, 1.0 ) + }; + + aMatrix.Line1 = aLines[ 0 ]; + aMatrix.Line2 = aLines[ 1 ]; + aMatrix.Line3 = aLines[ 2 ]; + aMatrix.Line4 = aLines[ 3 ]; + + // rotate 10 degrees along the x axis + double fAngle = 10.0; + double fCosX = Math.cos( Math.PI / 180.0 * fAngle ); + double fSinX = Math.sin( Math.PI / 180.0 * fAngle ); + + // rotate -20 degrees along the y axis + fAngle = -20.0; + double fCosY = Math.cos( Math.PI / 180.0 * fAngle ); + double fSinY = Math.sin( Math.PI / 180.0 * fAngle ); + + // rotate -5 degrees along the z axis + fAngle = -5.0; + double fCosZ = Math.cos( Math.PI / 180.0 * fAngle ); + double fSinZ = Math.sin( Math.PI / 180.0 * fAngle ); + + aMatrix.Line1.Column1 = fCosY * fCosZ; + aMatrix.Line1.Column2 = fCosY * -fSinZ; + aMatrix.Line1.Column3 = fSinY; + + aMatrix.Line2.Column1 = fSinX * fSinY * fCosZ + fCosX * fSinZ; + aMatrix.Line2.Column2 = -fSinX * fSinY * fSinZ + fCosX * fCosZ; + aMatrix.Line2.Column3 = -fSinX * fCosY; + + aMatrix.Line3.Column1 = -fCosX * fSinY * fCosZ + fSinX * fSinZ; + aMatrix.Line3.Column2 = fCosX * fSinY * fSinZ + fSinX * fCosZ; + aMatrix.Line3.Column3 = fCosX * fCosY; + + aDiaProp.setPropertyValue( "D3DTransformMatrix", aMatrix ); + + // add a red light source + + // in a chart by default only the second (non-specular) light source is switched on + // light source 1 is a specular light source + aDiaProp.setPropertyValue( "D3DSceneLightColor1", Integer.valueOf( 0xff3333 )); + + // set direction + com.sun.star.drawing.Direction3D aDirection = new com.sun.star.drawing.Direction3D(); + + aDirection.DirectionX = -0.75; + aDirection.DirectionY = 0.5; + aDirection.DirectionZ = 0.5; + + aDiaProp.setPropertyValue( "D3DSceneLightDirection1", aDirection ); + aDiaProp.setPropertyValue( "D3DSceneLightOn1", Boolean.TRUE); + } + + + + // private members + + + private final XChartDocument maChartDocument; + private final XDiagram maDiagram; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Charts/ChartInWriter.java b/odk/examples/DevelopersGuide/Charts/ChartInWriter.java new file mode 100644 index 000000000..b84404d8b --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/ChartInWriter.java @@ -0,0 +1,163 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.*; + +// property access +import com.sun.star.beans.*; + +// application specific classes +import com.sun.star.chart.*; +import com.sun.star.drawing.*; +import com.sun.star.frame.XModel; +// base graphics things +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; +// Exceptions +import com.sun.star.uno.Exception; +import com.sun.star.uno.RuntimeException; +import com.sun.star.beans.UnknownPropertyException; + + +// __________ Implementation __________ + +/** Test to create a writer document and insert an OLE Chart. + + Be careful! This does not really work. The Writer currently has no + interface for dealing with OLE objects. You can add an OLE shape to the + Writer's drawing layer, but it is not treated correctly as OLE object. + Thus, you can not activate the chart by double-clicking. The office may + also crash when the document is closed! + + */ +public class ChartInWriter +{ + + + public static void main( String args[] ) + { + Helper aHelper = new Helper( args ); + + ChartHelper aChartHelper = new ChartHelper( + UnoRuntime.queryInterface( XModel.class, + aHelper.createTextDocument())); + + // the unit for measures is 1/100th of a millimeter + // position at (1cm, 1cm) + Point aPos = new Point( 1000, 1000 ); + + // size of the chart is 15cm x 12cm + Size aExtent = new Size( 15000, 13000 ); + + // insert a new chart into the "Chart" sheet of the + // spreadsheet document + XChartDocument aChartDoc = aChartHelper.insertOLEChartInWriter( + aPos, + aExtent, + "com.sun.star.chart.AreaDiagram" ); + + // instantiate test class with newly created chart + ChartInWriter aTest = new ChartInWriter( aChartDoc ); + + try + { + aTest.lockControllers(); + + // do tests here + aTest.testWall(); + + aTest.unlockControllers(); + } + catch( Exception ex ) + { + System.out.println( "UNO Exception caught: " + ex ); + System.out.println( "Message: " + ex.getMessage() ); + } + + System.exit( 0 ); + } + + + + + public ChartInWriter( XChartDocument aChartDoc ) + { + maChartDocument = aChartDoc; + maDiagram = maChartDocument.getDiagram(); + } + + + + public void lockControllers() + throws RuntimeException + { + UnoRuntime.queryInterface( XModel.class, maChartDocument ).lockControllers(); + } + + + + public void unlockControllers() + throws RuntimeException + { + UnoRuntime.queryInterface( XModel.class, maChartDocument ).unlockControllers(); + } + + + + public void testWall() + throws RuntimeException, UnknownPropertyException, PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, WrappedTargetException + { + XPropertySet aWall = UnoRuntime.queryInterface( + X3DDisplay.class, maDiagram ).getWall(); + + // change background color of area + aWall.setPropertyValue( "FillColor", Integer.valueOf( 0xeecc99 )); + aWall.setPropertyValue( "FillStyle", FillStyle.SOLID ); + } + + + + // private members + + + private final XChartDocument maChartDocument; + private final XDiagram maDiagram; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Charts/Helper.java b/odk/examples/DevelopersGuide/Charts/Helper.java new file mode 100644 index 000000000..ef1faccbc --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/Helper.java @@ -0,0 +1,141 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.*; + +import com.sun.star.frame.XComponentLoader; + +// property access +import com.sun.star.beans.*; + +// application specific classes +import com.sun.star.sheet.XSpreadsheetDocument; +import com.sun.star.frame.XModel; + +// __________ Implementation __________ + +// Helper for creating a calc document adding cell values and charts + +public class Helper +{ + public Helper( String[] args ) + { + // connect to a running office and get the ServiceManager + try { + // get the remote office component context + maContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + // get the remote office service manager + maMCFactory = maContext.getServiceManager(); + } + catch( Exception e) { + System.out.println( "Couldn't get ServiceManager: " + e ); + e.printStackTrace(); + System.exit(1); + } + } + + + + public XSpreadsheetDocument createSpreadsheetDocument() + { + return UnoRuntime.queryInterface( + XSpreadsheetDocument.class, createDocument( "scalc" )); + } + + + + + + + + public XModel createDrawingDocument() + { + return createDocument( "sdraw" ); + } + + + + public XModel createTextDocument() + { + return createDocument( "swriter" ); + } + + + + private XModel createDocument( String sDocType ) + { + XModel aResult = null; + try + { + XComponentLoader aLoader = UnoRuntime.queryInterface(XComponentLoader.class, + maMCFactory.createInstanceWithContext("com.sun.star.frame.Desktop", + maContext) ); + + aResult = UnoRuntime.queryInterface( + XModel.class, + aLoader.loadComponentFromURL( "private:factory/" + sDocType, + "_blank", + 0, + new PropertyValue[ 0 ] ) ); + } + catch( Exception e ) + { + System.err.println("Couldn't create Document of type "+ sDocType +": "+e); + e.printStackTrace(); + System.exit( 0 ); + } + + return aResult; + } + + public XComponentContext getComponentContext(){ + return maContext; + + } + + // __________ private members and methods __________ + + + private XComponentContext maContext; + private XMultiComponentFactory maMCFactory; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Charts/JavaSampleChartAddIn.components b/odk/examples/DevelopersGuide/Charts/JavaSampleChartAddIn.components new file mode 100644 index 000000000..e9a7baa48 --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/JavaSampleChartAddIn.components @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Charts/JavaSampleChartAddIn.java b/odk/examples/DevelopersGuide/Charts/JavaSampleChartAddIn.java new file mode 100644 index 000000000..54a39d172 --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/JavaSampleChartAddIn.java @@ -0,0 +1,449 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.container.XIndexAccess; +import com.sun.star.lib.uno.helper.WeakBase; + +// factories +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; + +// graphics stuff +import com.sun.star.drawing.*; +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +// chart stuff +import com.sun.star.chart.*; + +// property access +import com.sun.star.beans.*; + +// Add-In stuff +import com.sun.star.lang.XInitialization; +import com.sun.star.util.XRefreshable; +import com.sun.star.lang.XServiceName; +import com.sun.star.lang.XServiceInfo; +// Exceptions +import com.sun.star.uno.Exception; +import com.sun.star.uno.RuntimeException; + +import javax.swing.JOptionPane; + +public class JavaSampleChartAddIn extends WeakBase implements + XInitialization, + XRefreshable, + XDiagram, + XServiceName, + XServiceInfo +{ + + // __________ interface methods __________ + + // XInitialization + public void initialize( Object[] aArguments ) + throws Exception, RuntimeException + { + if( aArguments.length > 0 ) + { + maChartDocument = UnoRuntime.queryInterface( + XChartDocument.class, aArguments[ 0 ]); + + XPropertySet aDocProp = UnoRuntime.queryInterface( + XPropertySet.class, maChartDocument ); + if( aDocProp != null ) + { + // set base diagram which will be extended in refresh() + aDocProp.setPropertyValue( "BaseDiagram", "com.sun.star.chart.XYDiagram" ); + } + + // get the draw page + XDrawPageSupplier aPageSupp = UnoRuntime.queryInterface( + XDrawPageSupplier.class, maChartDocument ); + if( aPageSupp != null ) + maDrawPage = UnoRuntime.queryInterface( + XDrawPage.class, aPageSupp.getDrawPage() ); + + // get a factory for creating shapes + maShapeFactory = UnoRuntime.queryInterface( + XMultiServiceFactory.class, maChartDocument ); + } + } + + // XRefreshable + public void refresh() throws RuntimeException + { + // recycle shapes in first call, if document was loaded + if( maBottomLine == null || + maTopLine == null ) + { + // try to recycle loaded shapes + XPropertySet aDocProp = UnoRuntime.queryInterface( + XPropertySet.class, maChartDocument ); + if( aDocProp != null ) + { + try + { + XIndexAccess aShapesIA = UnoRuntime.queryInterface( + XIndexAccess.class, aDocProp.getPropertyValue( "AdditionalShapes" )); + if( aShapesIA != null && + aShapesIA.getCount() > 0 ) + { + XShape aShape; + String aName; + for( int i = aShapesIA.getCount() - 1; i >= 0; --i ) + { + aShape = UnoRuntime.queryInterface( + XShape.class, aShapesIA.getByIndex( i )); + if( aShape != null ) + { + XPropertySet aProp = UnoRuntime.queryInterface( + XPropertySet.class, aShape ); + aName = (String) aProp.getPropertyValue( "Name" ); + + if( aName.equals( "top" )) + { + maTopLine = aShape; + } + else if( aName.equals( "bottom" )) + { + maBottomLine = aShape; + } + } + } + } + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( null, ex, "Exception caught", JOptionPane.WARNING_MESSAGE ); + } + } + } + + // create top line if it does not yet exist + try + { + if( maTopLine == null ) + { + maTopLine = UnoRuntime.queryInterface( + XShape.class, maShapeFactory.createInstance( "com.sun.star.drawing.LineShape" )); + maDrawPage.add( maTopLine ); + + // make line red and thicker + XPropertySet aShapeProp = UnoRuntime.queryInterface( + XPropertySet.class, maTopLine ); + + aShapeProp.setPropertyValue( "LineColor", Integer.valueOf( 0xe01010 )); + aShapeProp.setPropertyValue( "LineWidth", Integer.valueOf( 50 )); + aShapeProp.setPropertyValue( "Name", "top" ); + } + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( null, ex, "Exception caught", JOptionPane.WARNING_MESSAGE ); + } + + // create bottom line if it does not yet exist + try + { + if( maBottomLine == null ) + { + maBottomLine = UnoRuntime.queryInterface( + XShape.class, maShapeFactory.createInstance( "com.sun.star.drawing.LineShape" )); + maDrawPage.add( maBottomLine ); + + // make line green and thicker + XPropertySet aShapeProp = UnoRuntime.queryInterface( + XPropertySet.class, maBottomLine ); + + aShapeProp.setPropertyValue( "LineColor", Integer.valueOf( 0x10e010 )); + aShapeProp.setPropertyValue( "LineWidth", Integer.valueOf( 50 )); + aShapeProp.setPropertyValue( "Name", "bottom" ); + } + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( null, ex, "Exception caught", JOptionPane.WARNING_MESSAGE ); + } + + if( maTopLine == null || + maBottomLine == null ) + { + JOptionPane.showMessageDialog( null, "One of the lines is still null", "Assertion", JOptionPane.WARNING_MESSAGE ); + return; + } + + // position lines + + + // get data + XChartDataArray aDataArray = UnoRuntime.queryInterface( + XChartDataArray.class, maChartDocument.getData()); + double aData[][] = aDataArray.getData(); + + // get axes + XDiagram aDiagram = maChartDocument.getDiagram(); + XShape aXAxis = UnoRuntime.queryInterface( + XShape.class, UnoRuntime.queryInterface( + XAxisXSupplier.class, aDiagram ).getXAxis() ); + XShape aYAxis = UnoRuntime.queryInterface( + XShape.class, UnoRuntime.queryInterface( + XAxisYSupplier.class, aDiagram ).getYAxis() ); + + // calculate points for hull + final int nLength = aData.length; + int i, j; + double fMax, fMin; + + Point aMaxPtSeq[][] = new Point[ 1 ][]; + aMaxPtSeq[ 0 ] = new Point[ nLength ]; + Point aMinPtSeq[][] = new Point[ 1 ][]; + aMinPtSeq[ 0 ] = new Point[ nLength ]; + + for( i = 0; i < nLength; i++ ) + { + fMin = fMax = aData[ i ][ 1 ]; + for( j = 1; j < aData[ i ].length; j++ ) + { + if( aData[ i ][ j ] > fMax ) + fMax = aData[ i ][ j ]; + else if( aData[ i ][ j ] < fMin ) + fMin = aData[ i ][ j ]; + } + aMaxPtSeq[ 0 ][ i ] = new Point( getAxisPosition( aXAxis, aData[ i ][ 0 ], false ), + getAxisPosition( aYAxis, fMax, true )); + aMinPtSeq[ 0 ][ i ] = new Point( getAxisPosition( aXAxis, aData[ i ][ 0 ], false ), + getAxisPosition( aYAxis, fMin, true )); + } + + // apply point sequences to lines + try + { + XPropertySet aShapeProp = UnoRuntime.queryInterface( + XPropertySet.class, maTopLine ); + aShapeProp.setPropertyValue( "PolyPolygon", aMaxPtSeq ); + + aShapeProp = UnoRuntime.queryInterface( + XPropertySet.class, maBottomLine ); + aShapeProp.setPropertyValue( "PolyPolygon", aMinPtSeq ); + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( null, ex, "Exception caught", JOptionPane.WARNING_MESSAGE ); + } + } + + public void addRefreshListener( com.sun.star.util.XRefreshListener aListener ) + throws RuntimeException + { + // we don't want this but we have to implement the interface + } + + public void removeRefreshListener( com.sun.star.util.XRefreshListener aListener ) + throws RuntimeException + { + // we don't want this but we have to implement the interface + } + + + // XServiceName + public String getServiceName() throws RuntimeException + { + return smServiceName; + } + + // XServiceInfo + public boolean supportsService( String aServiceName ) + { + String[] aServices = getSupportedServiceNames_Static(); + int i, nLength = aServices.length; + boolean bResult = false; + + for( i = 0; !bResult && i < nLength; ++i ) + bResult = aServiceName.equals( aServices[ i ] ); + + return bResult; + } + + public String getImplementationName() + { + return( JavaSampleChartAddIn.class.getName() ); + } + + public String[] getSupportedServiceNames() + { + return getSupportedServiceNames_Static(); + } + + // XDiagram + public String getDiagramType() throws RuntimeException + { + return smServiceName; + } + + public XPropertySet getDataRowProperties( int nRow ) + throws com.sun.star.lang.IndexOutOfBoundsException, RuntimeException + { + return maChartDocument.getDiagram().getDataRowProperties( nRow ); + } + + public XPropertySet getDataPointProperties( int nCol, int nRow ) + throws com.sun.star.lang.IndexOutOfBoundsException, RuntimeException + { + return maChartDocument.getDiagram().getDataPointProperties( nCol, nRow ); + } + + // XShape : XDiagram + public Size getSize() throws RuntimeException + { + return UnoRuntime.queryInterface( XShape.class, maChartDocument.getDiagram()).getSize(); + } + public void setSize( Size aSize ) throws RuntimeException, PropertyVetoException + { + UnoRuntime.queryInterface( XShape.class, maChartDocument.getDiagram()).setSize( aSize ); + } + + public Point getPosition() throws RuntimeException + { + return UnoRuntime.queryInterface( XShape.class, maChartDocument.getDiagram()).getPosition(); + } + public void setPosition( Point aPos ) throws RuntimeException + { + UnoRuntime.queryInterface( XShape.class, maChartDocument.getDiagram()).setPosition( aPos ); + } + + // XShapeDescriptor : XShape : XDiagram + public String getShapeType() throws RuntimeException + { + return "com.sun.star.comp.Chart.JavaSampleDiagramShape"; + } + + + // __________ private members __________ + private com.sun.star.chart.XChartDocument maChartDocument; + private com.sun.star.drawing.XDrawPage maDrawPage; + private com.sun.star.lang.XMultiServiceFactory maShapeFactory; + + // shapes added by add-in + private com.sun.star.drawing.XShape maTopLine; + private com.sun.star.drawing.XShape maBottomLine; + + // __________ private methods __________ + + private int getAxisPosition( XShape aAxis, double fValue, boolean bVertical ) + { + int nResult = 0; + + if( aAxis != null ) + { + XPropertySet aAxisProp = UnoRuntime.queryInterface( + XPropertySet.class, aAxis ); + + try + { + double fMin, fMax; + fMin = ((Double) aAxisProp.getPropertyValue( "Min" )).doubleValue(); + fMax = ((Double) aAxisProp.getPropertyValue( "Max" )).doubleValue(); + double fRange = fMax - fMin; + + if( fMin <= fValue && fValue <= fMax && + fRange != 0 ) + { + if( bVertical ) + { + nResult = aAxis.getPosition().Y + + (int)((aAxis.getSize().Height) * + (1.0 - (( fValue - fMin ) / fRange ))); + } + else + { + nResult = aAxis.getPosition().X + + (int)((aAxis.getSize().Width) * + (( fValue - fMin ) / fRange )); + } + } + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( null, ex, "Exception caught", JOptionPane.WARNING_MESSAGE ); + } + } + return nResult; + } + + // __________ static things __________ + + private static final String smServiceName = "com.sun.star.comp.Chart.JavaSampleChartAddIn"; + + public static String[] getSupportedServiceNames_Static() + { + String[] aResult = { smServiceName, + "com.sun.star.chart.Diagram", + "com.sun.star.chart.ChartAxisYSupplier" }; + return aResult; + } + + + /** + * Returns a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XSingleServiceFactory for creating the component + * @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 + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleServiceFactory __getServiceFactory( + String implName, + XMultiServiceFactory multiFactory, + com.sun.star.registry.XRegistryKey regKey ) + { + XSingleServiceFactory xSingleServiceFactory = null; + + if( implName.equals( JavaSampleChartAddIn.class.getName()) ) + { + xSingleServiceFactory = com.sun.star.comp.loader.FactoryHelper.getServiceFactory( + JavaSampleChartAddIn.class, smServiceName, + multiFactory, regKey ); + } + + return xSingleServiceFactory; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Charts/ListenAtCalcRangeInDraw.java b/odk/examples/DevelopersGuide/Charts/ListenAtCalcRangeInDraw.java new file mode 100644 index 000000000..76808b4ae --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/ListenAtCalcRangeInDraw.java @@ -0,0 +1,193 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.*; + +// property access +import com.sun.star.beans.*; + +// application specific classes +import com.sun.star.chart.*; +import com.sun.star.table.XCellRange; +import com.sun.star.sheet.XSpreadsheetDocument; + +import com.sun.star.frame.XModel; +// base graphics things +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; +// Exceptions +import com.sun.star.uno.Exception; + + +// __________ Implementation __________ + +/** Create a spreadsheet add some data. + Create a presentation and add a chart. + Connect the chart to a calc range via a listener + */ +public class ListenAtCalcRangeInDraw implements XChartDataChangeEventListener +{ + public static void main( String args[] ) + { + ListenAtCalcRangeInDraw aMySelf = new ListenAtCalcRangeInDraw( args ); + + aMySelf.run(); + } + + public ListenAtCalcRangeInDraw( String args[] ) + { + Helper aHelper = new Helper( args ); + + maSheetDoc = aHelper.createSpreadsheetDocument(); + XModel aDrawDoc = aHelper.createDrawingDocument(); + CalcHelper aCalcHelper = new CalcHelper( maSheetDoc ); + ChartHelper aChartHelper = new ChartHelper( aDrawDoc ); + + XCellRange aRange = aCalcHelper.insertFormulaRange( 3, 30 ); + + // the unit for measures is 1/100th of a millimeter + // position at (1cm, 1cm) + Point aPos = new Point( 1000, 1000 ); + + // size of the chart is 15cm x 9.271cm + Size aExtent = new Size( 15000, 9271 ); + + // insert a new chart into the "Chart" sheet of the + // spreadsheet document + maChartDocument = aChartHelper.insertOLEChartInDraw( + aPos, + aExtent, + "com.sun.star.chart.XYDiagram" ); + + // attach the data coming from the cell range to the chart + maChartData = UnoRuntime.queryInterface( XChartData.class, aRange ); + maChartDocument.attachData( maChartData ); + } + + + + public void run() + { + try + { + UnoRuntime.queryInterface( + XPropertySet.class, maChartDocument ).setPropertyValue( + "HasSubTitle", Boolean.TRUE); + + // start listening for death of spreadsheet + UnoRuntime.queryInterface( + XComponent.class, maSheetDoc ).addEventListener( this ); + + // start listening for death of chart + UnoRuntime.queryInterface( + XComponent.class, maChartDocument ).addEventListener( this ); + + //start listening for change of data + maChartData.addChartDataChangeEventListener( this ); + } + catch( Exception ex ) + { + System.out.println( "Oops: " + ex ); + } + + // call listener + ChartDataChangeEvent aEvent = new ChartDataChangeEvent(); + aEvent.Type = ChartDataChangeType.ALL; + chartDataChanged( aEvent ); + } + + + + // XEventListener (base of XChartDataChangeEventListener) + public void disposing( EventObject aSourceObj ) + { + if( UnoRuntime.queryInterface( XChartDocument.class, aSourceObj.Source ) != null ) + System.out.println( "Disconnecting Listener because Chart was shut down" ); + + if( UnoRuntime.queryInterface( XSpreadsheetDocument.class, aSourceObj.Source ) != null ) + System.out.println( "Disconnecting Listener because Spreadsheet was shut down" ); + + // remove data change listener + maChartData.removeChartDataChangeEventListener( this ); + + // remove dispose listeners + UnoRuntime.queryInterface( + XComponent.class, maSheetDoc ).removeEventListener( this ); + UnoRuntime.queryInterface( + XComponent.class, maChartDocument ).removeEventListener( this ); + + System.exit( 0 ); + } + + + + // XChartDataChangeEventListener + public void chartDataChanged( ChartDataChangeEvent aEvent ) + { + // update subtitle + String aTitle = "Last Update: " + new java.util.Date(); + + try + { + XPropertySet aDocProp = UnoRuntime.queryInterface( + XPropertySet.class, maChartDocument ); + aDocProp.setPropertyValue( "HasMainTitle", Boolean.TRUE); + + UnoRuntime.queryInterface( + XPropertySet.class, maChartDocument.getSubTitle()).setPropertyValue( + "String", aTitle ); + + maChartDocument.attachData( maChartData ); + } + catch( Exception ex ) + { + System.out.println( "Oops: " + ex ); + } + + System.out.println( "Data has changed" ); + } + + + // __________ private __________ + + private final XSpreadsheetDocument maSheetDoc; + private final XChartDocument maChartDocument; + private final XChartData maChartData; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Charts/Makefile b/odk/examples/DevelopersGuide/Charts/Makefile new file mode 100644 index 000000000..dbb55d51c --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/Makefile @@ -0,0 +1,199 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Charts examples of the Developers Guide. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=DevGuideChartExample +SAMPLE_CLASS_OUT = $(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT = $(OUT_MISC)/$(SAMPLE_NAME) + +APP1_NAME=ChartInCalc +APP1_JAR=$(SAMPLE_CLASS_OUT)/$(APP1_NAME).jar +APP2_NAME=ChartInDraw +APP2_JAR=$(SAMPLE_CLASS_OUT)/$(APP2_NAME).jar +APP3_NAME=ChartInWriter +APP3_JAR=$(SAMPLE_CLASS_OUT)/$(APP3_NAME).jar +APP4_NAME=ListenAtCalcRangeInDraw +APP4_JAR=$(SAMPLE_CLASS_OUT)/$(APP4_NAME).jar +APP5_NAME=SelectionChangeListener +APP5_JAR=$(SAMPLE_CLASS_OUT)/$(APP5_NAME).jar + +COMP_NAME=JavaSampleChartAddIn +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME = $(COMP_NAME).uno.jar +COMP_JAR = $(SAMPLE_CLASS_OUT)/$(COMP_JAR_NAME) +COMP_MANIFESTFILE = $(SAMPLE_CLASS_OUT)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(SAMPLE_CLASS_OUT)/$(COMP_NAME)/META-INF/manifest.xml +COMP_REGISTERFLAG = $(SAMPLE_GEN_OUT)/devguide_$(COMP_NAME)_register_component.flag +COMP_COMPONENTS=$(COMP_NAME).components + +COMPJAVAFILES = \ + JavaSampleChartAddIn.java + +APP_JAVAFILES = \ + Helper.java \ + CalcHelper.java \ + ChartHelper.java + +COMPCLASSFILES= $(patsubst %.java,$(SAMPLE_CLASS_OUT)/%.class,$(COMPJAVAFILES)) + +APP_CLASSFILES= $(patsubst %.java,$(SAMPLE_CLASS_OUT)/%.class,$(APP_JAVAFILES)) +APP_CLASSNAMES= $(patsubst %.java,%.class,$(APP_JAVAFILES)) + +$(COMP_NAME)_CLASSFILES = $(COMP_NAME).class + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : $(SAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(SAMPLE_CLASS_OUT)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo RegistrationClassName: $(basename $(basename $(@F)))> $@ + +# rule for client/example application class files, explicit dependencies to common +# java files which are used in all examples. +$(SAMPLE_CLASS_OUT)/%.class : %.java $(APP_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SAMPLE_CLASS_OUT) $< $(APP_JAVAFILES) + +$(COMPCLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SAMPLE_CLASS_OUT) $(COMPJAVAFILES) + +# rule for client/example application manifest file +$(SAMPLE_CLASS_OUT)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +# rule for client/example application jar file +$(SAMPLE_CLASS_OUT)/%.jar : $(SAMPLE_CLASS_OUT)/%.mf $(SAMPLE_CLASS_OUT)/%.class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) cvfm $(@F) $*.mf $**.class $(APP_CLASSNAMES) + + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_MANIFESTFILE) $(COMPCLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) cvfm $(@F) $( $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_JAR) $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ $(COMP_COMPONENTS) + cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_ZIP) ../../bin/$(@F) -u $( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(APP1_JAR) : $(SAMPLE_CLASS_OUT)/$(APP1_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP1_NAME).class +$(APP2_JAR) : $(SAMPLE_CLASS_OUT)/$(APP2_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP2_NAME).class +$(APP3_JAR) : $(SAMPLE_CLASS_OUT)/$(APP3_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP3_NAME).class +$(APP4_JAR) : $(SAMPLE_CLASS_OUT)/$(APP4_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP4_NAME).class +$(APP5_JAR) : $(SAMPLE_CLASS_OUT)/$(APP5_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP5_NAME).class + +$(SAMPLE_NAME) : $(COMP_REGISTERFLAG) $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) $(APP4_JAR) $(APP5_JAR) + @echo -------------------------------------------------------------------------------- + @echo When you run the "$(QM)$(APP5_NAME)$(QM)" example please select the + @echo legend or the title to add a $(APP5_NAME). The example terminates + @echo when the document is closed. + @echo - + @echo Please use the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP2_NAME).run + @echo $(MAKE) $(APP3_NAME).run + @echo $(MAKE) $(APP4_NAME).run + @echo $(MAKE) $(APP5_NAME).run + @echo -------- + @echo The Chart add-in component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo Load the "$(QM)AddInChart.ods$(QM)" document in your office to see the new chart type, + @echo and see the example description. + @echo - + @echo $(MAKE) AddInChart.ods.load + @echo -------------------------------------------------------------------------------- + +%.run: $(SAMPLE_CLASS_OUT)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +AddInChart.ods.load : $(REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/DevelopersGuide/Charts/SelectionChangeListener.java b/odk/examples/DevelopersGuide/Charts/SelectionChangeListener.java new file mode 100644 index 000000000..e9ba0581c --- /dev/null +++ b/odk/examples/DevelopersGuide/Charts/SelectionChangeListener.java @@ -0,0 +1,220 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.awt.XMessageBox; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.frame.XDesktop; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.*; +import com.sun.star.frame.XModel; +import com.sun.star.frame.XController; + +// application specific classes +import com.sun.star.chart.*; +import com.sun.star.uno.XComponentContext; +import com.sun.star.uno.XInterface; + +import com.sun.star.view.XSelectionChangeListener; +import com.sun.star.view.XSelectionSupplier; + +import com.sun.star.table.CellRangeAddress; +import com.sun.star.table.XCellRange; +import com.sun.star.sheet.XCellRangeAddressable; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; +import com.sun.star.awt.XMessageBoxFactory; +import com.sun.star.awt.MessageBoxType; +import com.sun.star.awt.XWindow; + +// __________ Implementation __________ + +/** Create a spreadsheet add some data. + * Create a presentation and add a chart. + * Connect the chart to a calc range via a listener + * + * Note: This example does not work in StarOffice 6.0. It will be available + * in the StarOffice Accessibility release. + */ +public class SelectionChangeListener implements XSelectionChangeListener { + public static void main( String args[] ) { + SelectionChangeListener aMySelf = new SelectionChangeListener( args ); + + aMySelf.run(); + } + + public SelectionChangeListener( String args[] ) { + Helper aHelper = new Helper( args ); + + maContext = aHelper.getComponentContext(); + + CalcHelper aCalcHelper = new CalcHelper( aHelper.createSpreadsheetDocument() ); + + // insert a cell range with 4 columns and 12 rows filled with random numbers + XCellRange aRange = aCalcHelper.insertRandomRange( 4, 12 ); + CellRangeAddress aRangeAddress = UnoRuntime.queryInterface( + XCellRangeAddressable.class, aRange).getRangeAddress(); + + // change view to sheet containing the chart + aCalcHelper.raiseChartSheet(); + + // the unit for measures is 1/100th of a millimeter + // position at (1cm, 1cm) + Point aPos = new Point( 1000, 1000 ); + + // size of the chart is 15cm x 9.271cm + Size aExtent = new Size( 15000, 9271 ); + + // insert a new chart into the "Chart" sheet of the + // spreadsheet document + maChartDocument = aCalcHelper.insertChart( + "SampleChart", + aRangeAddress, + aPos, + aExtent, + "com.sun.star.chart.XYDiagram" ); + } + + + + public void run() { + boolean bTrying = true; + + while( bTrying ) { + // start listening for selection changes + XSelectionSupplier aSelSupp = UnoRuntime.queryInterface( + XSelectionSupplier.class, + (UnoRuntime.queryInterface( + XModel.class, maChartDocument ).getCurrentController()) ); + if( aSelSupp != null ) { + aSelSupp.addSelectionChangeListener( this ); + System.out.println( "Successfully attached as selection change listener" ); + bTrying = false; + } + + // start listening for death of Controller + XComponent aComp = UnoRuntime.queryInterface( XComponent.class, aSelSupp ); + if( aComp != null ) { + aComp.addEventListener( this ); + System.out.println( "Successfully attached as dispose listener" ); + } + + try { + Thread.sleep( 500 ); + } catch( InterruptedException ex ) { + } + } + } + + + + // XEventListener (base of XSelectionChangeListener) + public void disposing( EventObject aSourceObj ) { + System.out.println( "disposing called. detaching as listener" ); + + // stop listening for selection changes + XSelectionSupplier aCtrl = UnoRuntime.queryInterface( + XSelectionSupplier.class, aSourceObj ); + if( aCtrl != null ) + aCtrl.removeSelectionChangeListener( this ); + + // remove as dispose listener + XComponent aComp = UnoRuntime.queryInterface( XComponent.class, aSourceObj ); + if( aComp != null ) + aComp.removeEventListener( this ); + + // bail out + System.exit( 0 ); + } + + + + // XSelectionChangeListener + public void selectionChanged( EventObject aEvent ) { + XController aCtrl = UnoRuntime.queryInterface( XController.class, aEvent.Source ); + if( aCtrl != null ) { + XMultiComponentFactory mMCF = maContext.getServiceManager(); + + MyMessageBox aMsgBox = new MyMessageBox(mMCF); + + aMsgBox.start(); + + System.out.println("Listener finished"); + } + } + + // __________ private __________ + + private class MyMessageBox extends Thread{ + private final XMultiComponentFactory mMCF; + + public MyMessageBox(XMultiComponentFactory xMCF){ + mMCF = xMCF; + } + + @Override + public void run() { + XDesktop aDesktop = null; + XInterface aToolKit = null; + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + ex.printStackTrace(); + } + try { + Object oDesktop = mMCF.createInstanceWithContext("com.sun.star.frame.Desktop", maContext); + Object oToolKit = mMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", maContext); + + aDesktop = UnoRuntime.queryInterface(XDesktop.class, oDesktop); + aToolKit = UnoRuntime.queryInterface(XInterface.class, oToolKit); + } catch (Exception ex) { + ex.printStackTrace(); + } + + XWindow xWin = aDesktop.getCurrentFrame().getContainerWindow(); + XWindowPeer aWinPeer = UnoRuntime.queryInterface(XWindowPeer.class, xWin); + + int button = com.sun.star.awt.MessageBoxButtons.BUTTONS_OK; + XMessageBoxFactory aMBF = UnoRuntime.queryInterface(XMessageBoxFactory.class, aToolKit); + XMessageBox xMB = aMBF.createMessageBox(aWinPeer, MessageBoxType.INFOBOX, button, "Event-Notify", "Listener was called, selection has changed"); + xMB.execute(); + } + } + + private final XChartDocument maChartDocument; + private final XComponentContext maContext; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Charts/bullet.gif b/odk/examples/DevelopersGuide/Charts/bullet.gif new file mode 100644 index 000000000..0f8efd140 Binary files /dev/null and b/odk/examples/DevelopersGuide/Charts/bullet.gif differ diff --git a/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/Addons.xcu b/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/Addons.xcu new file mode 100644 index 000000000..e9b9976d3 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/Addons.xcu @@ -0,0 +1,98 @@ + + + + + + + + + + + + vnd.sun.star.job:alias=AsyncJob + + + + + private:image/3216 + + + + + + + AsyncJob (ALIAS)... + AsyncJob (ALIAS) ... + + + _self + + + + + + + + vnd.sun.star.job:event=onMyOwnJobEvent + + + + + private:image/3216 + + + + + + + AsyncJob (EVENT)... + AsyncJob (EVENT) ... + + + _self + + + + + + + + vnd.sun.star.job:service=com.sun.star.comp.framework.java.services.AsyncJob + + + + + private:image/3216 + + + + + + + AsyncJob (SERVICE)... + AsyncJob (SERVICE) ... + + + _self + + + + + + diff --git a/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/AsyncJob.components b/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/AsyncJob.components new file mode 100644 index 000000000..c47f26b01 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/AsyncJob.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/AsyncJob.java b/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/AsyncJob.java new file mode 100644 index 000000000..9b55929d8 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/AsyncJob.java @@ -0,0 +1,425 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.XComponentContext; +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.task.*; +import com.sun.star.uno.*; + +/** it implements a simple job component. + * + * Such jobs are executable in different ways: + *

    + *
  • registered for a special URL schema "vnd.sun.star.jobs:*" and used from the generic dispatch framework
  • + *
  • the global com.sun.star.task.JobExecutor service and registered for special events.
  • + *
+ */ +public class AsyncJob extends WeakBase implements XServiceInfo, XAsyncJob +{ + public final XComponentContext m_xCmpCtx; + + /** the const list of supported uno service names. */ + public static final String[] SERVICENAMES = {"com.sun.star.task.AsyncJob"}; + + /** the const uno implementation name. + * It must be a unique value! The best naming schema seems to use + * a registered domain in reverse order ... + */ + public static final String IMPLEMENTATIONNAME = "com.sun.star.comp.framework.java.services.AsyncJob"; + + + // interface + + /** initialize a new instance of this class with default values. */ + public AsyncJob( XComponentContext xCompContext ) + { + m_xCmpCtx = xCompContext; + } + + + + /** starts execution of this job. + * + * @param lArgs + * list which contains: + *
    + *
  • generic job configuration data
  • + *
  • job specific configuration data
  • + *
  • some environment information
  • + *
  • may optional arguments of a corresponding dispatch request
  • + *
+ * + * @params xListener + * callback to the executor of this job, which control our life time + * + * @throws com.sun.star.lang.IllegalArgumentException + * if given argument list seems to be wrong + */ + public synchronized void executeAsync(com.sun.star.beans.NamedValue[] lArgs , + com.sun.star.task.XJobListener xListener) + throws com.sun.star.lang.IllegalArgumentException + { + // For asynchronous jobs a valid listener reference is guaranteed normally ... + if (xListener == null) + throw new com.sun.star.lang.IllegalArgumentException("invalid listener"); + + // extract all possible sub list of given argument list + com.sun.star.beans.NamedValue[] lGenericConfig = null; + com.sun.star.beans.NamedValue[] lJobConfig = null; + com.sun.star.beans.NamedValue[] lEnvironment = null; + com.sun.star.beans.NamedValue[] lDynamicData = null; + + int c = lArgs.length; + for (int i=0; i + + + + + + com.sun.star.comp.framework.java.services.AsyncJob + + + + val_1 + + + + + + + + + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/Makefile b/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/Makefile new file mode 100644 index 000000000..6ee3481fc --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/JobsAddon/Makefile @@ -0,0 +1,136 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the DevGuide Jobs Addon component example of the SDK. + +PRJ=../../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=AsyncJob +OUT_COMP_CLASS=$(OUT_CLASS)/$(COMP_NAME) +OUT_COMP_MISC=$(OUT_MISC)/$(COMP_NAME) +COMP_PACKAGE=$(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL=$(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME=$(COMP_NAME).uno.jar +COMP_JAR=$(OUT_CLASS)/$(COMP_JAR_NAME) +COMP_MANIFESTFILE=$(OUT_COMP_CLASS)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(OUT_COMP_CLASS)/$(COMP_NAME)/META-INF/manifest.xml +REGISTERFLAG=$(OUT_COMP_MISC)$(PS)java_$(COMP_NAME)_register_component.flag +COMP_COMPONENTS=$(COMP_NAME).components + +JAVAFILES = AsyncJob.java + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : DevGuideJobsAddon + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_CLASS)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo RegistrationClassName: $(basename $(basename $(@F)))> $@ + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(JAVAFILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_MANIFESTFILE) $(CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(OUT_COMP_CLASS) . + +# rule for component package manifest +$(OUT_COMP_CLASS)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)Addons.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)Jobs.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_JAR) Addons.xcu Jobs.xcu $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + cd $(subst /,$(PS),$(OUT_CLASS)) && $(SDK_ZIP) ../bin/$(@F) $( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +DevGuideJobsAddon : $(REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The "$(QM)AsyncJob$(QM)" addon component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the example + @echo description. + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.class + $(SDK_JAVA) -classpath "$(SDK_CLASSPATH)" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_MISC)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_JAR))) diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/Addons.xcu b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/Addons.xcu new file mode 100644 index 000000000..e891edaae --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/Addons.xcu @@ -0,0 +1,231 @@ + + + + + + + + Add-On example + + + com.sun.star.text.TextDocument + + + + + org.openoffice.Office.addon.example:Function1 + + + + + + + Add-On Function 1 + + + _self + + + + + org.openoffice.Office.addon.example:Function2 + + + + + + + Add-On Function 2 + + + _self + + + + + + + + + + Add-On example + + + + + org.openoffice.Office.addon.example:Function1 + + + + + + + Add-On Function 1 + + + _self + + + com.sun.star.text.TextDocument + + + + + private:separator + + + + + + + + + + + + Add-On sub menu + + + _self + + + + + org.openoffice.Office.addon.example:Function2 + + + + + + + Add-On Function 2 + + + _self + + + com.sun.star.sheet.SpreadsheetDocument + + + + + + + + + + + + org.openoffice.Office.addon.example:Function1 + + + + + + + Function 1 + + + _self + + + com.sun.star.text.TextDocument + + + + + org.openoffice.Office.addon.example:Function2 + + + + + + + Function 2 + + + _self + + + com.sun.star.text.TextDocument + + + + + + + + org.openoffice.Office.addon.example:Function1 + + + + 424df80000000000000076000000280000001000000010000000010004000000000000000000120b0000120b000000000000000000000000ff0000ffff0000ff0000ffff0000ff000000ff00ff00ffffff00c0c0c0008080800000000000000080000080800000800000808000008000000080008000cccccccccccccccc2c266b181b666c2c5cc66b818b6665c555566b181b66655555566b818b66655555566b181b6665555a8666bbb6668a55a0a866666668a0a5000a8666668a000a6000a86668a000a556000a868a000a55556000a8a000a5555556000a000a55555555600000a55555555556000a55555555555560a55555550000 + + + 424d180200000000000076000000280000001a0000001a000000010004000000000000000000120b0000120b000000000000000000000000ff0000ffff0000ff0000ffff0000ff000000ff00ff00ffffff00c0c0c000808080000000000000008000008080000080000080800000800000008000800055555555555555555555555555999990cccccccccccccccccccccccccc9055552cc2c6666b18181b6666c2cc2c99ccccc2ccc6666b81818b66668c2cc5902cc25c2586666b18181b66668ccc5590c2cc555586666b81818b6666855555995c25555586666b18181b6666855555995555555586666b81818b6666855555005555555586666b18181b666685555590555555a5866666b181b6666685a5550955555a0a8666666bbb6666668a0a559955a5a000a866666666666668a000a5995a0a00000a8666666666668a00000a90a000600000a86666666668a00000a50900005600000a866666668a00000a5599600055600000a8666668a00000a555095600555600000a86668a00000a55559955605555600000a868a00000a5555599555655555600000a8a00000a555555005555555555600000a00000a555555590555555555556000000000a555555550955555555555560000000a555555555995555555555555600000a555555555590555555555555556000a555555555550055555555555555560a555555555555905555555555555555555555555555559055550000 + + + 424df60000000000000076000000280000001000000010000000010004000000000080000000120b0000120b000000000000000000000000ff0000ffff0000ff0000ffff0000ff000000ff00ff00ffffff00c0c0c00080808000000000000000800000808000008000008080000080000000800080002222222222222222222996969699922252299669669995255559969696999555555996696699955555599696969995555969996669996955969699999996969566696999996966699666969996966695596669696966695555966696966695555559666966695555555596666695555555555966695555555555559695555555 + + + + + + + + + org.openoffice.Office.addon.example:Help + + + + 424d36030000000000003600000028000000100000001000000001001800000000000003000000000000000000000000000000000000ff00ffff00ffff00ffff00fff0eeee6c5f602512133c2b2c2b1719594a4bdcd8d8ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff5443453a2525d0c5bdffffffffffffffffffe6e7e8493c3c5e514eb7b1b0ff00ffff00ffff00ffff00ffff00ff5c4a4dc0bbbcfffffffbeadee7bca8e7bcabdfb4a2f1c4b0fffffad0d0cd584a4dc5bbb8ff00ffff00ffff00ffddd9d9514449ffffffd49578b7511eb5582ed29d85ce8b6db54513ba5f32eeccb8fffffffffffbd3cfcfff00ffff00ffd9cdc5e0d9dadc9270ba4613bf511dc99076edeae7f2dcced27b54bc4811ba5724d3ad96ffffff402d30ff00ffefeae6e9e0daeabba4ba4308cb5b28cb5f2ecc7046d99979db8f66ce6635cc5d2dbf4e1ab85225ffeee5726361b1aaaad8cbc2ffffffbf4911c65b21cf6532cc5d2bcc764edbae97dfa284ce6a3bcc5b2bcc602ebb4310d28259ffffff332124d7cbc2fffffebb2600d0703bcc612ecb5b2bca7a56dfd3cdf5f4f1e1a686cd6333ce622dc95e2abe3901ffffff2b1a1dd8cdc4ffffffbe2f00d36f40cb602dcb5928c95a29ce8666e9ded7f1dcd2d77e56cd612acc6530c43a00ffffff312125d5c8beffffffcf3f00d66e3dcc632fc95d2ccb5522c44f19cf8c6becd4ccde9b81d06435d05b26c65619ffffff251317d9cdc5fefffff09361e87437da794ad29a7edfa68ad56f3bd5835bedd5cbe3b399d36939db6126e9b395ffffff3f3033f5f2f0ded6d1fff1e4f9a36ff28b52e3b39beeefedf3e5d9f2e7def4f0eaeba87ee66d2fee9e72fffffcb28d89c7c6c6ff00ffcbb6aaffffffffebdcfec08ff6b584edcebbeddaddf3dfdff5cab3f79c66fbaa7dfce8dcffffffb99e9bff00ffff00ffdccbc3e0d6cef2f2f2fffffcfff2d1fadca3f6cf91fac588fdc68bffe4c5fffefaffffffe2d4c8f2efeeff00ffff00ffff00fff0ebe6dfd0c9dbcac2f8f7f4fffffffffffffffffffdf8f2e3d9d1cfbfb4ebe3ddff00ffff00ffff00ffff00ffff00ffff00ffff00fffafaf9e1d6ced5c2b9d9c9c2d5c6beddcfc8f4f0efff00ffff00ffff00ffff00ffff00ff + + + 424d560800000000000036000000280000001a0000001a00000001001800000000002008000000000000000000000000000000000000ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff524142524142524142524142524142524142524142524142ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffff00ff524142524142bda69cd6c7bddecfc6ded7d6e7dfd6e7d7cebdbebdb59694524142524142ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ff524142fffffffffffffffffffffffffffffffffffffffffff7f7f7ffffffffffffffefefbdb6ad524142524142ff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ff524142ffffffffffffffffffefefefdedfdebdb6adc6a694d6a68cdebeade7d7ceefefeff7f7f7ffffffefe7deefe7de524142ff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffbda69cffffffffffffffffffefe7ded6a68cbd6139bd5929ce6942c6795abd5929bd5931ce8663debeadefefeffffffffff7f7efe7de524142ff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffbda69cffffffffffffe7cfc6ce7142bd5929bd5929bd6139d6c7bdffffffd69e84bd5929bd5929bd5929d69e7befefefffffffffefef524142ff00ffff00ffff00ffff00ff0000ff00ffff00ffdecfc6ffffffffffffe7cfc6c66139bd5929c66131ce6131bd7152dedfdeffffffe7c7bdce6131ce6131bd5929bd5929ce8e6befefefffffffdecfc6524142ff00ffff00ffff00ff0000ff00ffff00ffdecfc6ffffffefe7e7ce7142c66131ce6131ce6131ce6131c66131d6a68cefcfbdd68652ce6131ce6131ce6131c66131bd5929d6a68cffffffffffff524142ff00ffff00ffff00ff0000ff00ffdecfc6fff7f7ffffffdeae94bd5929ce6131ce6931ce6131ce6131ce6131ce6939d67142ce6131ce6131ce6131ce6131ce6131bd5929c66139f7dfd6ffffffdecfc6524142ff00ffff00ff0000ff00ffdecfc6fffffff7efefd6714ac66131ce6931ce6931ce6131ce6131c66939debeadffefe7de966bc66131ce6131ce6131ce6131ce6131bd5929deae94ffffffffefe7524142ff00ffff00ff0000ff00ffdecfc6ffffffefd7cece6131ce6931ce6931ce6131ce6131ce6131c66939d6d7d6ffffffdeb69cce6131ce6131ce6131ce6131ce6131bd5929ce8e63f7f7f7ffffff524142ff00ffff00ff0000ff00ffdecfc6ffffffefc7adce6131ce6939ce6931ce6131ce6131ce6131ce6131c6a694f7f7f7fff7efd68e63ce6131ce6131ce6131ce6931ce6131d6714af7efefffffff524142ff00ffff00ff0000ff00ffdecfc6ffffffefc7adce6131d66939ce6931ce6131ce6131ce6131ce6131c66139debeadfffffffff7efd68e63ce6131ce6931ce6931ce6131d6714af7efefffffff524142ff00ffff00ff0000ff00ffdecfc6ffffffffcfb5d67139d67142d66939ce6131ce6131ce6131ce6131ce6131c66939d6c7bdffffffffefefd6714ace6131d66939ce6931d68652fff7f7ffffff524142ff00ffff00ff0000ff00ffdecfc6ffffffffe7dee7794ade7142d67139ce6931ce6131ce6131ce6131ce6131ce6131ce7142f7efefffffffe7ae94ce6131d66939d66939d69673ffffffffffff524142ff00ffff00ff0000ff00ffdecfc6ffffffffffffefa67bef8652de7142d6714adebeadefdfcede9e7bce6131ce6131ce6131f7dfd6ffffffefc7add66939de7142d66939efc7b5ffffffffefef524142ff00ffff00ff0000ff00ffdecfc6f7f7f7ffffffffdfc6f7965af78e5ade794acecfceffffffffefe7d68652ce6131d69e84ffffffffffffdeae94d67139de7142ef9663fff7f7ffffffd6c7bd524142ff00ffff00ff0000ff00ffff00ffdecfc6fffffffffffff7c7adff9e6bf7965ad69e84efefeffffffffffff7ffefdeffffffffffffefe7e7ef9663e7864aef8652f7dfceffffffffffffb59694ff00ffff00ffff00ff0000ff00ffff00ffdecfc6f7f7efffffffffffffffd7adffb684ffa673efb69cdedfdeefefefefefefefefefefe7deefae8cf7965aff9663ffcfb5ffffffffffffdecfc6b59694ff00ffff00ffff00ff0000ff00ffff00ffff00ffdecfc6ffffffffffffffffffffefd6ffdfadffc794ffc794efb69cefb69cffbe9cffb684ffae7bffb68cffe7d6fffffffffffff7efe7bdb6adff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffdecfc6fffffffffffffffffffffff7ffffe7ffffd6ffefb5ffefb5ffdfadffdfadffefd6fffff7fffffffffffffff7efdecfc6ff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffdecfc6fff7efffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdecfc6decfc6ff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffff00ffdecfc6decfc6fff7effffffffffffffffffffffffffffffffffffffffff7decfc6decfc6ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffdecfc6decfc6decfc6decfc6decfc6decfc6decfc6decfc6ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000 + + + 424d36030000000000003600000028000000100000001000000001001800000000000003000000000000000000000000000000000000ff00ffff00ffff00ffff00fff0eeee6c5f602512133c2b2c2b1719594a4bdcd8d8ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff5443453a2525d0c5bdffffffffffffffffffe6e7e8493c3c5e514eb7b1b0ff00ffff00ffff00ffff00ffff00ff5c4a4dc0bbbcffffffffffffffffffffffffffffffffffffffffffd0d0cd584a4dc5bbb8ff00ffff00ffff00ffddd9d9514449ffffffffffffffffffffffff251317251317fffffffffffffffffffffffffffffbd3cfcfff00ffff00ffd9cdc5e0d9daffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff402d30ff00ffefeae6e9e0daffffffffffffffffffffffffffffff251317251317ffffffffffffffffffffffffffffff726361b1aaaad8cbc2ffffffffffffffffffffffffffffffffffff251317251317ffffffffffffffffffffffffffffffffffff332124d7cbc2fffffeffffffffffffffffffffffffffffff251317251317000000ffffffffffffffffffffffffffffff2b1a1dd8cdc4ffffffffffffffffffffffffffffffffffffffffff251317251317ffffffffffffffffffffffffffffff312125d5c8beffffffffffffffffffffffffffffffffffffffffffffffff251317251317ffffffffffffffffffffffff251317d9cdc5feffffffffffffffffffffff000000000000ffffffffffff251317251317ffffffffffffffffffffffff3f3033f5f2f0ded6d1ffffffffffffffffff000000251317251317251317251317000000ffffffffffffffffffb28d89c7c6c6ff00ffcbb6aaffffffffffffffffffffffff000000251317251317000000ffffffffffffffffffffffffb99e9bff00ffff00ffdccbc3e0d6cef2f2f2fffffffffffffffffffffffffffffffffffffffffffffefaffffffe2d4c8f2efeeff00ffff00ffff00fff0ebe6dfd0c9dbcac2f8f7f4fffffffffffffffffffdf8f2e3d9d1cfbfb4ebe3ddff00ffff00ffff00ffff00ffff00ffff00ffff00fffafaf9e1d6ced5c2b9d9c9c2d5c6beddcfc8f4f0efff00ffff00ffff00ffff00ffff00ff + + + + + + + + + + + org.openoffice.Office.addon.example:Help + + + + + + + + Ãœber Add-On Beispiel + About Add-On Example + + + _self + + + + + diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/Makefile b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/Makefile new file mode 100644 index 000000000..239b7e283 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/Makefile @@ -0,0 +1,153 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the ProtocolHandlerAddon C++ component example of the SDK. + +PRJ=../../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=ProtocolHandlerAddon_cpp +COMP_IMPL_NAME=$(COMP_NAME).uno.$(SHAREDLIB_EXT) +OUT_COMP_INC=$(OUT_INC)/$(COMP_NAME) +OUT_COMP_GEN=$(OUT_MISC)/$(COMP_NAME) +OUT_COMP_SLO=$(OUT_SLO)/$(COMP_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_UNOPKG_MANIFEST = $(OUT_COMP_GEN)/$(COMP_NAME)/META-INF/manifest.xml +COMP_COMPONENTS = $(OUT_COMP_GEN)/$(COMP_NAME).components + +REGISTERFLAG = $(OUT_MISC)/cpp_$(COMP_NAME)_register_component.flag + +CXXFILES = component.cxx \ + addon.cxx + +SLOFILES = $(patsubst %.cxx,$(OUT_COMP_SLO)/%.$(OBJ_EXT),$(CXXFILES)) + +# Targets +.PHONY: ALL +ALL : \ + Example + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_SLO)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +ifeq "$(OS)" "WIN" +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)) + $(LINK) $(COMP_LINK_FLAGS) /OUT:$@ \ + /MAP:$(OUT_COMP_GEN)/$(subst $(SHAREDLIB_EXT),map,$(@F)) $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) msvcprt.lib $(LIBO_SDK_LDFLAGS_STDLIBS) + $(LINK_MANIFEST) +else +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(COMP_LINK_FLAGS) $(LINK_LIBS) -o $@ $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS) $@ +endif +endif + +# rule for component package manifest +$(OUT_COMP_GEN)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)Addons.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)ProtocolHandler.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components;platform=$(UNOPKG_PLATFORM)$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +$(COMP_COMPONENTS) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)components xmlns="$(QM)http://openoffice.org/2010/uno-components$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)component loader="$(QM)com.sun.star.loader.SharedLibrary$(QM)" uri="$(QM)$(UNOPKG_PLATFORM)/$(COMP_IMPL_NAME)$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)org.openoffice.Office.addon.example$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)com.sun.star.frame.ProtocolHandler$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/component$(CSEP) >> $@ + @echo $(OSEP)/components$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(SHAREDLIB_OUT)/$(COMP_IMPL_NAME) Addons.xcu ProtocolHandler.xcu $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(MKDIR) $(subst /,$(PS),$(@D)) && $(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)/$(UNOPKG_PLATFORM)) + $(COPY) $(subst /,$(PS),$<) $(subst /,$(PS),$(OUT_COMP_GEN)/$(UNOPKG_PLATFORM)) + cd $(subst /,$(PS),$(OUT_COMP_GEN)) && $(SDK_ZIP) ../../bin/$(@F) $(COMP_NAME).components + cd $(subst /,$(PS),$(OUT_COMP_GEN)) && $(SDK_ZIP) -u ../../bin/$(@F) $(UNOPKG_PLATFORM)/$( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +Example : $(REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The "$(QM)ProtocolHandler$(QM)" addon component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the example + @echo description. + @echo -------------------------------------------------------------------------------- + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_SLO)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_COMPONENTS))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(REGISTERFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SHAREDLIB_OUT)/$(COMP_NAME).*)) diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/ProtocolHandler.xcu b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/ProtocolHandler.xcu new file mode 100644 index 000000000..eecd51fcf --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/ProtocolHandler.xcu @@ -0,0 +1,27 @@ + + + + + + + org.openoffice.Office.addon.example:* + + + + diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/addon.cxx b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/addon.cxx new file mode 100644 index 000000000..a11286e55 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/addon.cxx @@ -0,0 +1,238 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using rtl::OUString; +using namespace com::sun::star::uno; +using namespace com::sun::star::frame; +using namespace com::sun::star::awt; +using com::sun::star::beans::PropertyValue; +using com::sun::star::util::URL; + +// This is the service name an Add-On has to implement +#define SERVICE_NAME "com.sun.star.frame.ProtocolHandler" + + +/** + * Show a message box with the UNO based toolkit + */ +static void ShowMessageBox( const Reference< XToolkit >& rToolkit, const Reference< XFrame >& rFrame, const OUString& aTitle, const OUString& aMsgText ) +{ + if ( rFrame.is() && rToolkit.is() ) + { + // describe window properties. + WindowDescriptor aDescriptor; + aDescriptor.Type = WindowClass_MODALTOP; + aDescriptor.WindowServiceName = "infobox"; + aDescriptor.ParentIndex = -1; + aDescriptor.Parent = Reference< XWindowPeer >( rFrame->getContainerWindow(), UNO_QUERY ); + aDescriptor.Bounds = Rectangle(0,0,300,200); + aDescriptor.WindowAttributes = WindowAttribute::BORDER | +WindowAttribute::MOVEABLE | +WindowAttribute::CLOSEABLE; + + Reference< XWindowPeer > xPeer = rToolkit->createWindow( aDescriptor ); + if ( xPeer.is() ) + { + Reference< XMessageBox > xMsgBox( xPeer, UNO_QUERY ); + if ( xMsgBox.is() ) + { + xMsgBox->setCaptionText( aTitle ); + xMsgBox->setMessageText( aMsgText ); + xMsgBox->execute(); + } + } + } +} + +/** + * Called by the Office framework. + * One-time initialization. We have to store the context information + * given, like the frame we are bound to, into our members. + */ +void SAL_CALL Addon::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException) +{ + Reference < XFrame > xFrame; + if ( aArguments.getLength() ) + { + aArguments[0] >>= xFrame; + mxFrame = xFrame; + } + + // Create the toolkit to have access to it later + mxToolkit = Reference< XToolkit >( Toolkit::create(mxContext), UNO_QUERY_THROW ); +} + +/** + * Called by the Office framework. + * We are ask to query the given URL and return a dispatch object if the URL + * contains an Add-On command. + */ +Reference< XDispatch > SAL_CALL Addon::queryDispatch( const URL& aURL, const ::rtl::OUString& sTargetFrameName, sal_Int32 nSearchFlags ) + throw( RuntimeException ) +{ + Reference < XDispatch > xRet; + if ( aURL.Protocol.equalsAscii("org.openoffice.Office.addon.example:") ) + { + if ( aURL.Path.equalsAscii( "Function1" ) ) + xRet = this; + else if ( aURL.Path.equalsAscii( "Function2" ) ) + xRet = this; + else if ( aURL.Path.equalsAscii( "Help" ) ) + xRet = this; + } + + return xRet; +} + +/** + * Called by the Office framework. + * We are ask to execute the given Add-On command URL. + */ +void SAL_CALL Addon::dispatch( const URL& aURL, const Sequence < PropertyValue >& lArgs ) throw (RuntimeException) +{ + if ( aURL.Protocol.equalsAscii("org.openoffice.Office.addon.example:") ) + { + if ( aURL.Path.equalsAscii( "Function1" ) ) + { + ShowMessageBox( mxToolkit, mxFrame, + OUString( "SDK Add-On example" ), + OUString( "Function 1 activated" ) ); + } + else if ( aURL.Path.equalsAscii( "Function2" ) ) + { + ShowMessageBox( mxToolkit, mxFrame, + OUString( "SDK Add-On example" ), + OUString( "Function 2 activated" ) ); + } + else if ( aURL.Path.equalsAscii( "Help" ) ) + { + // Show info box + ShowMessageBox( mxToolkit, mxFrame, + OUString( "About SDK Add-On example" ), + OUString( "This is the SDK Add-On example" ) ); + } + } +} + +/** + * Called by the Office framework. + * We are ask to query the given sequence of URLs and return dispatch objects if the URLs + * contain Add-On commands. + */ +Sequence < Reference< XDispatch > > SAL_CALL Addon::queryDispatches( const Sequence < DispatchDescriptor >& seqDescripts ) + throw( RuntimeException ) +{ + sal_Int32 nCount = seqDescripts.getLength(); + Sequence < Reference < XDispatch > > lDispatcher( nCount ); + + for( sal_Int32 i=0; i& xControl, const URL& aURL ) throw (RuntimeException) +{ +} + +/** + * Called by the Office framework. + * We are ask to query the given sequence of URLs and return dispatch objects if the URLs + * contain Add-On commands. + */ +void SAL_CALL Addon::removeStatusListener( const Reference< XStatusListener >& xControl, const URL& aURL ) throw (RuntimeException) +{ +} + +// Helper functions for the implementation of UNO component interfaces. +OUString Addon_getImplementationName() +throw (RuntimeException) +{ + return OUString ( IMPLEMENTATION_NAME ); +} + +Sequence< ::rtl::OUString > SAL_CALL Addon_getSupportedServiceNames() +throw (RuntimeException) +{ + Sequence < ::rtl::OUString > aRet(1); + ::rtl::OUString* pArray = aRet.getArray(); + pArray[0] = OUString ( SERVICE_NAME ); + return aRet; +} + +Reference< XInterface > SAL_CALL Addon_createInstance( const Reference< XComponentContext > & rContext) + throw( Exception ) +{ + return (cppu::OWeakObject*) new Addon( rContext ); +} + +// Implementation of the recommended/mandatory interfaces of a UNO component. +// XServiceInfo +::rtl::OUString SAL_CALL Addon::getImplementationName( ) + throw (RuntimeException) +{ + return Addon_getImplementationName(); +} + +sal_Bool SAL_CALL Addon::supportsService( const ::rtl::OUString& rServiceName ) + throw (RuntimeException) +{ + return cppu::supportsService(this, rServiceName); +} + +Sequence< ::rtl::OUString > SAL_CALL Addon::getSupportedServiceNames( ) + throw (RuntimeException) +{ + return Addon_getSupportedServiceNames(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/addon.hxx b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/addon.hxx new file mode 100644 index 000000000..65641fb33 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/addon.hxx @@ -0,0 +1,132 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_COMPONENTS_ADDONS_PROTOCOLHANDLERADDON_CPP_ADDON_HXX +#define INCLUDED_EXAMPLES_COMPONENTS_ADDONS_PROTOCOLHANDLERADDON_CPP_ADDON_HXX + +#include +#include +#include +#include + +#define IMPLEMENTATION_NAME "org.openoffice.Office.addon.example" + +namespace com +{ + namespace sun + { + namespace star + { + namespace frame + { + class XFrame; + } + namespace awt + { + class XToolkit; + } + namespace uno + { + class XComponentContext; + } + } + } +} + +class Addon : public cppu::WeakImplHelper4 +< + com::sun::star::frame::XDispatchProvider, + com::sun::star::frame::XDispatch, + com::sun::star::lang::XInitialization, + com::sun::star::lang::XServiceInfo +> +{ +private: + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mxContext; + ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; + ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit > mxToolkit; + +public: + Addon( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > &rxContext) + : mxContext( rxContext ) {} + + // XDispatchProvider + virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > + SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, + const ::rtl::OUString& sTargetFrameName, sal_Int32 nSearchFlags ) + throw( ::com::sun::star::uno::RuntimeException ); + virtual ::com::sun::star::uno::Sequence < ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > + SAL_CALL queryDispatches( + const ::com::sun::star::uno::Sequence < ::com::sun::star::frame::DispatchDescriptor >& seqDescriptor ) + throw( ::com::sun::star::uno::RuntimeException ); + + // XDispatch + virtual void SAL_CALL dispatch( const ::com::sun::star::util::URL& aURL, + const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lArgs ) + throw (::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL addStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, + const ::com::sun::star::util::URL& aURL ) throw (::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL removeStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, + const ::com::sun::star::util::URL& aURL ) 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); + + // 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); +}; + +::rtl::OUString Addon_getImplementationName() + throw ( ::com::sun::star::uno::RuntimeException ); + +sal_Bool SAL_CALL Addon_supportsService( const ::rtl::OUString& ServiceName ) + throw ( ::com::sun::star::uno::RuntimeException ); + +::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL Addon_getSupportedServiceNames( ) + throw ( ::com::sun::star::uno::RuntimeException ); + +::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > +SAL_CALL Addon_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > & rContext) + throw ( ::com::sun::star::uno::Exception ); + +#endif // INCLUDED_EXAMPLES_COMPONENTS_ADDONS_PROTOCOLHANDLERADDON_CPP_ADDON_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/component.cxx b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/component.cxx new file mode 100644 index 000000000..4d34b5521 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_cpp/component.cxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include +#include +#include +#include +// generated c++ interfaces +#include +#include +#include + +// include our specific addon header to get access to functions and definitions +#include + +using namespace ::rtl; +using namespace ::osl; +using namespace ::cppu; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::registry; + +/** + * 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 + */ +extern "C" SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory(const char * pImplName, void * /*pServiceManager*/, void * pRegistryKey) +{ + void * pRet = 0; + + if (rtl_str_compare( pImplName, IMPLEMENTATION_NAME ) == 0) + { + Reference< XSingleComponentFactory > xFactory( createSingleComponentFactory( + Addon_createInstance, + OUString( IMPLEMENTATION_NAME ), + Addon_getSupportedServiceNames() ) ); + + if (xFactory.is()) + { + xFactory->acquire(); + pRet = xFactory.get(); + } + } + + return pRet; +} + +extern "C" SAL_DLLPUBLIC_EXPORT void SAL_CALL +component_getImplementationEnvironment( + char const ** ppEnvTypeName, uno_Environment **) +{ + *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/Addons.xcu b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/Addons.xcu new file mode 100644 index 000000000..4e23a827e --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/Addons.xcu @@ -0,0 +1,231 @@ + + + + + + + + Add-On example + + + com.sun.star.text.TextDocument + + + + + org.openoffice.Office.addon.example:Function1 + + + + + + + Add-On Function 1 + + + _self + + + + + org.openoffice.Office.addon.example:Function2 + + + + + + + Add-On Function 2 + + + _self + + + + + + + + + + Add-On example + + + + + org.openoffice.Office.addon.example:Function1 + + + + + + + Add-On Function 1 + + + _self + + + com.sun.star.text.TextDocument + + + + + private:separator + + + + + + + + + + + + Add-On sub menu + + + _self + + + + + org.openoffice.Office.addon.example:Function2 + + + + + + + Add-On Function 2 + + + _self + + + com.sun.star.sheet.SpreadsheetDocument + + + + + + + + + + + + org.openoffice.Office.addon.example:Function1 + + + + + + + Function 1 + + + _self + + + com.sun.star.text.TextDocument + + + + + org.openoffice.Office.addon.example:Function2 + + + + + + + Function 2 + + + _self + + + com.sun.star.text.TextDocument + + + + + + + + org.openoffice.Office.addon.example:Function1 + + + + 424df80000000000000076000000280000001000000010000000010004000000000000000000120b0000120b000000000000000000000000ff0000ffff0000ff0000ffff0000ff000000ff00ff00ffffff00c0c0c0008080800000000000000080000080800000800000808000008000000080008000cccccccccccccccc2c266b181b666c2c5cc66b818b6665c555566b181b66655555566b818b66655555566b181b6665555a8666bbb6668a55a0a866666668a0a5000a8666668a000a6000a86668a000a556000a868a000a55556000a8a000a5555556000a000a55555555600000a55555555556000a55555555555560a55555550000 + + + 424d180200000000000076000000280000001a0000001a000000010004000000000000000000120b0000120b000000000000000000000000ff0000ffff0000ff0000ffff0000ff000000ff00ff00ffffff00c0c0c000808080000000000000008000008080000080000080800000800000008000800055555555555555555555555555999990cccccccccccccccccccccccccc9055552cc2c6666b18181b6666c2cc2c99ccccc2ccc6666b81818b66668c2cc5902cc25c2586666b18181b66668ccc5590c2cc555586666b81818b6666855555995c25555586666b18181b6666855555995555555586666b81818b6666855555005555555586666b18181b666685555590555555a5866666b181b6666685a5550955555a0a8666666bbb6666668a0a559955a5a000a866666666666668a000a5995a0a00000a8666666666668a00000a90a000600000a86666666668a00000a50900005600000a866666668a00000a5599600055600000a8666668a00000a555095600555600000a86668a00000a55559955605555600000a868a00000a5555599555655555600000a8a00000a555555005555555555600000a00000a555555590555555555556000000000a555555550955555555555560000000a555555555995555555555555600000a555555555590555555555555556000a555555555550055555555555555560a555555555555905555555555555555555555555555559055550000 + + + 424df60000000000000076000000280000001000000010000000010004000000000080000000120b0000120b000000000000000000000000ff0000ffff0000ff0000ffff0000ff000000ff00ff00ffffff00c0c0c00080808000000000000000800000808000008000008080000080000000800080002222222222222222222996969699922252299669669995255559969696999555555996696699955555599696969995555969996669996955969699999996969566696999996966699666969996966695596669696966695555966696966695555559666966695555555596666695555555555966695555555555559695555555 + + + + + + + + + org.openoffice.Office.addon.example:Help + + + + 424d36030000000000003600000028000000100000001000000001001800000000000003000000000000000000000000000000000000ff00ffff00ffff00ffff00fff0eeee6c5f602512133c2b2c2b1719594a4bdcd8d8ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff5443453a2525d0c5bdffffffffffffffffffe6e7e8493c3c5e514eb7b1b0ff00ffff00ffff00ffff00ffff00ff5c4a4dc0bbbcfffffffbeadee7bca8e7bcabdfb4a2f1c4b0fffffad0d0cd584a4dc5bbb8ff00ffff00ffff00ffddd9d9514449ffffffd49578b7511eb5582ed29d85ce8b6db54513ba5f32eeccb8fffffffffffbd3cfcfff00ffff00ffd9cdc5e0d9dadc9270ba4613bf511dc99076edeae7f2dcced27b54bc4811ba5724d3ad96ffffff402d30ff00ffefeae6e9e0daeabba4ba4308cb5b28cb5f2ecc7046d99979db8f66ce6635cc5d2dbf4e1ab85225ffeee5726361b1aaaad8cbc2ffffffbf4911c65b21cf6532cc5d2bcc764edbae97dfa284ce6a3bcc5b2bcc602ebb4310d28259ffffff332124d7cbc2fffffebb2600d0703bcc612ecb5b2bca7a56dfd3cdf5f4f1e1a686cd6333ce622dc95e2abe3901ffffff2b1a1dd8cdc4ffffffbe2f00d36f40cb602dcb5928c95a29ce8666e9ded7f1dcd2d77e56cd612acc6530c43a00ffffff312125d5c8beffffffcf3f00d66e3dcc632fc95d2ccb5522c44f19cf8c6becd4ccde9b81d06435d05b26c65619ffffff251317d9cdc5fefffff09361e87437da794ad29a7edfa68ad56f3bd5835bedd5cbe3b399d36939db6126e9b395ffffff3f3033f5f2f0ded6d1fff1e4f9a36ff28b52e3b39beeefedf3e5d9f2e7def4f0eaeba87ee66d2fee9e72fffffcb28d89c7c6c6ff00ffcbb6aaffffffffebdcfec08ff6b584edcebbeddaddf3dfdff5cab3f79c66fbaa7dfce8dcffffffb99e9bff00ffff00ffdccbc3e0d6cef2f2f2fffffcfff2d1fadca3f6cf91fac588fdc68bffe4c5fffefaffffffe2d4c8f2efeeff00ffff00ffff00fff0ebe6dfd0c9dbcac2f8f7f4fffffffffffffffffffdf8f2e3d9d1cfbfb4ebe3ddff00ffff00ffff00ffff00ffff00ffff00ffff00fffafaf9e1d6ced5c2b9d9c9c2d5c6beddcfc8f4f0efff00ffff00ffff00ffff00ffff00ff + + + 424d560800000000000036000000280000001a0000001a00000001001800000000002008000000000000000000000000000000000000ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff524142524142524142524142524142524142524142524142ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffff00ff524142524142bda69cd6c7bddecfc6ded7d6e7dfd6e7d7cebdbebdb59694524142524142ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ff524142fffffffffffffffffffffffffffffffffffffffffff7f7f7ffffffffffffffefefbdb6ad524142524142ff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ff524142ffffffffffffffffffefefefdedfdebdb6adc6a694d6a68cdebeade7d7ceefefeff7f7f7ffffffefe7deefe7de524142ff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffbda69cffffffffffffffffffefe7ded6a68cbd6139bd5929ce6942c6795abd5929bd5931ce8663debeadefefeffffffffff7f7efe7de524142ff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffbda69cffffffffffffe7cfc6ce7142bd5929bd5929bd6139d6c7bdffffffd69e84bd5929bd5929bd5929d69e7befefefffffffffefef524142ff00ffff00ffff00ffff00ff0000ff00ffff00ffdecfc6ffffffffffffe7cfc6c66139bd5929c66131ce6131bd7152dedfdeffffffe7c7bdce6131ce6131bd5929bd5929ce8e6befefefffffffdecfc6524142ff00ffff00ffff00ff0000ff00ffff00ffdecfc6ffffffefe7e7ce7142c66131ce6131ce6131ce6131c66131d6a68cefcfbdd68652ce6131ce6131ce6131c66131bd5929d6a68cffffffffffff524142ff00ffff00ffff00ff0000ff00ffdecfc6fff7f7ffffffdeae94bd5929ce6131ce6931ce6131ce6131ce6131ce6939d67142ce6131ce6131ce6131ce6131ce6131bd5929c66139f7dfd6ffffffdecfc6524142ff00ffff00ff0000ff00ffdecfc6fffffff7efefd6714ac66131ce6931ce6931ce6131ce6131c66939debeadffefe7de966bc66131ce6131ce6131ce6131ce6131bd5929deae94ffffffffefe7524142ff00ffff00ff0000ff00ffdecfc6ffffffefd7cece6131ce6931ce6931ce6131ce6131ce6131c66939d6d7d6ffffffdeb69cce6131ce6131ce6131ce6131ce6131bd5929ce8e63f7f7f7ffffff524142ff00ffff00ff0000ff00ffdecfc6ffffffefc7adce6131ce6939ce6931ce6131ce6131ce6131ce6131c6a694f7f7f7fff7efd68e63ce6131ce6131ce6131ce6931ce6131d6714af7efefffffff524142ff00ffff00ff0000ff00ffdecfc6ffffffefc7adce6131d66939ce6931ce6131ce6131ce6131ce6131c66139debeadfffffffff7efd68e63ce6131ce6931ce6931ce6131d6714af7efefffffff524142ff00ffff00ff0000ff00ffdecfc6ffffffffcfb5d67139d67142d66939ce6131ce6131ce6131ce6131ce6131c66939d6c7bdffffffffefefd6714ace6131d66939ce6931d68652fff7f7ffffff524142ff00ffff00ff0000ff00ffdecfc6ffffffffe7dee7794ade7142d67139ce6931ce6131ce6131ce6131ce6131ce6131ce7142f7efefffffffe7ae94ce6131d66939d66939d69673ffffffffffff524142ff00ffff00ff0000ff00ffdecfc6ffffffffffffefa67bef8652de7142d6714adebeadefdfcede9e7bce6131ce6131ce6131f7dfd6ffffffefc7add66939de7142d66939efc7b5ffffffffefef524142ff00ffff00ff0000ff00ffdecfc6f7f7f7ffffffffdfc6f7965af78e5ade794acecfceffffffffefe7d68652ce6131d69e84ffffffffffffdeae94d67139de7142ef9663fff7f7ffffffd6c7bd524142ff00ffff00ff0000ff00ffff00ffdecfc6fffffffffffff7c7adff9e6bf7965ad69e84efefeffffffffffff7ffefdeffffffffffffefe7e7ef9663e7864aef8652f7dfceffffffffffffb59694ff00ffff00ffff00ff0000ff00ffff00ffdecfc6f7f7efffffffffffffffd7adffb684ffa673efb69cdedfdeefefefefefefefefefefe7deefae8cf7965aff9663ffcfb5ffffffffffffdecfc6b59694ff00ffff00ffff00ff0000ff00ffff00ffff00ffdecfc6ffffffffffffffffffffefd6ffdfadffc794ffc794efb69cefb69cffbe9cffb684ffae7bffb68cffe7d6fffffffffffff7efe7bdb6adff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffdecfc6fffffffffffffffffffffff7ffffe7ffffd6ffefb5ffefb5ffdfadffdfadffefd6fffff7fffffffffffffff7efdecfc6ff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffdecfc6fff7efffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdecfc6decfc6ff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffff00ffdecfc6decfc6fff7effffffffffffffffffffffffffffffffffffffffff7decfc6decfc6ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffdecfc6decfc6decfc6decfc6decfc6decfc6decfc6decfc6ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff0000 + + + 424d36030000000000003600000028000000100000001000000001001800000000000003000000000000000000000000000000000000ff00ffff00ffff00ffff00fff0eeee6c5f602512133c2b2c2b1719594a4bdcd8d8ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff5443453a2525d0c5bdffffffffffffffffffe6e7e8493c3c5e514eb7b1b0ff00ffff00ffff00ffff00ffff00ff5c4a4dc0bbbcffffffffffffffffffffffffffffffffffffffffffd0d0cd584a4dc5bbb8ff00ffff00ffff00ffddd9d9514449ffffffffffffffffffffffff251317251317fffffffffffffffffffffffffffffbd3cfcfff00ffff00ffd9cdc5e0d9daffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff402d30ff00ffefeae6e9e0daffffffffffffffffffffffffffffff251317251317ffffffffffffffffffffffffffffff726361b1aaaad8cbc2ffffffffffffffffffffffffffffffffffff251317251317ffffffffffffffffffffffffffffffffffff332124d7cbc2fffffeffffffffffffffffffffffffffffff251317251317000000ffffffffffffffffffffffffffffff2b1a1dd8cdc4ffffffffffffffffffffffffffffffffffffffffff251317251317ffffffffffffffffffffffffffffff312125d5c8beffffffffffffffffffffffffffffffffffffffffffffffff251317251317ffffffffffffffffffffffff251317d9cdc5feffffffffffffffffffffff000000000000ffffffffffff251317251317ffffffffffffffffffffffff3f3033f5f2f0ded6d1ffffffffffffffffff000000251317251317251317251317000000ffffffffffffffffffb28d89c7c6c6ff00ffcbb6aaffffffffffffffffffffffff000000251317251317000000ffffffffffffffffffffffffb99e9bff00ffff00ffdccbc3e0d6cef2f2f2fffffffffffffffffffffffffffffffffffffffffffffefaffffffe2d4c8f2efeeff00ffff00ffff00fff0ebe6dfd0c9dbcac2f8f7f4fffffffffffffffffffdf8f2e3d9d1cfbfb4ebe3ddff00ffff00ffff00ffff00ffff00ffff00ffff00fffafaf9e1d6ced5c2b9d9c9c2d5c6beddcfc8f4f0efff00ffff00ffff00ffff00ffff00ff + + + + + + + + + + + org.openoffice.Office.addon.example:Help + + + + + + + + Ãœber Add-On Beispiel + About Add-On Example + + + _self + + + + + diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/Makefile b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/Makefile new file mode 100644 index 000000000..e85570b49 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/Makefile @@ -0,0 +1,138 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the ProtoclHandlerAddon Java component example of the SDK. + +PRJ=../../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=ProtocolHandlerAddon_java +OUT_COMP_CLASS=$(OUT_CLASS)/$(COMP_NAME) +OUT_COMP_MISC=$(OUT_MISC)/$(COMP_NAME) +COMP_PACKAGE=$(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL=$(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME=$(COMP_NAME).uno.jar +COMP_JAR=$(OUT_CLASS)/$(COMP_JAR_NAME) +COMP_MANIFESTFILE=$(OUT_COMP_CLASS)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(OUT_COMP_CLASS)/$(COMP_NAME)/META-INF/manifest.xml +COMP_COMPONENTS=$(COMP_NAME).components + +REGISTERFLAG=$(OUT_COMP_MISC)$(PS)java_$(COMP_NAME)_register_component.flag + +JAVAFILES = ProtocolHandlerAddon.java + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : DevGuideProtocolHandlerAddon + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_CLASS)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo RegistrationClassName: ProtocolHandlerAddon> $@ + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(JAVAFILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_MANIFESTFILE) $(CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(OUT_COMP_CLASS) . + +# rule for component package manifest +$(OUT_COMP_CLASS)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)Addons.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)ProtocolHandler.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_JAR) Addons.xcu ProtocolHandler.xcu $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_MISC)) + $(COPY) $(subst /,$(PS),$<) $(subst /,$(PS),$(OUT_COMP_MISC)) + cd $(subst /,$(PS),$(OUT_COMP_MISC)) && $(SDK_ZIP) ../../bin/$(@F) $( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +DevGuideProtocolHandlerAddon : $(REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The "$(QM)ProtocolHandler$(QM)" addon component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the example + @echo description. + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.class + $SDJ_JAVA) -classpath "$(SDK_CLASSPATH)" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_MISC)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_JAR))) diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandler.xcu b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandler.xcu new file mode 100644 index 000000000..7974c3e95 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandler.xcu @@ -0,0 +1,27 @@ + + + + + + + org.openoffice.Office.addon.example:* + + + + diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandlerAddon.java b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandlerAddon.java new file mode 100644 index 000000000..c12c69288 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandlerAddon.java @@ -0,0 +1,254 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.XComponentContext; +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XInitialization; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.frame.XStatusListener; +import com.sun.star.frame.XDispatchProvider; +import com.sun.star.frame.XDispatch; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.DispatchDescriptor; +import com.sun.star.awt.XToolkit; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.awt.XMessageBox; +import com.sun.star.awt.WindowAttribute; +import com.sun.star.awt.WindowClass; +import com.sun.star.awt.WindowDescriptor; +import com.sun.star.awt.Rectangle; + +public class ProtocolHandlerAddon { + /** This class implements the component. At least the interfaces XServiceInfo, + * XTypeProvider, and XInitialization should be provided by the service. + */ + public static class ProtocolHandlerAddonImpl extends WeakBase implements + XDispatchProvider, + XDispatch, + XInitialization, + XServiceInfo { + + /** The service name, that must be used to get an instance of this service. + */ + private static final String[] m_serviceNames = { "com.sun.star.frame.ProtocolHandler" }; + + /** The component context, that gives access to the service manager and all registered services. + */ + private final XComponentContext m_xCmpCtx; + + /** The toolkit, that we can create UNO dialogs. + */ + private XToolkit m_xToolkit; + + /** The frame where the addon depends on. + */ + private XFrame m_xFrame; + + + /** The constructor of the inner class has a XMultiServiceFactory parameter. + * @param xComponentContext A special service factory + * could be introduced while initializing. + */ + public ProtocolHandlerAddonImpl( XComponentContext xComponentContext ) { + m_xCmpCtx = xComponentContext; + } + + /** This method is a member of the interface for initializing an object + * directly after its creation. + * @param object This array of arbitrary objects will be passed to the + * component after its creation. + * @throws com.sun.star.uno.Exception Every exception will not be handled, but will be + * passed to the caller. + */ + public void initialize( Object[] object ) + throws com.sun.star.uno.Exception { + + if ( object.length > 0 ) + { + m_xFrame = UnoRuntime.queryInterface( + XFrame.class, object[ 0 ] ); + } + + // Create the toolkit to have access to it later + m_xToolkit = UnoRuntime.queryInterface( + XToolkit.class, + m_xCmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.awt.Toolkit", + m_xCmpCtx)); + } + + /** This method returns an array of all supported service names. + * @return Array of supported service names. + */ + public String[] getSupportedServiceNames() { + return getServiceNames(); + } + + public static String[] getServiceNames() { + return m_serviceNames; + } + + /** This method returns true, if the given service will be + * supported by the component. + * @return True, if the given service name will be supported. + */ + public boolean supportsService( String sService ) { + int len = m_serviceNames.length; + + for( int i=0; i < len; i++) { + if ( sService.equals( m_serviceNames[i] ) ) + return true; + } + + return false; + } + + /** Return the class name of the component. + * @return Class name of the component. + */ + public String getImplementationName() { + return ProtocolHandlerAddonImpl.class.getName(); + } + + // XDispatchProvider + public XDispatch queryDispatch( /*IN*/com.sun.star.util.URL aURL, + /*IN*/String sTargetFrameName, + /*IN*/int iSearchFlags ) { + XDispatch xRet = null; + if ( aURL.Protocol.equals("org.openoffice.Office.addon.example:") ) { + if ( aURL.Path.equals( "Function1" ) ) + xRet = this; + if ( aURL.Path.equals( "Function2" ) ) + xRet = this; + if ( aURL.Path.equals( "Help" ) ) + xRet = this; + } + return xRet; + } + + public XDispatch[] queryDispatches( /*IN*/DispatchDescriptor[] seqDescripts ) { + int nCount = seqDescripts.length; + XDispatch[] lDispatcher = new XDispatch[nCount]; + + for( int i=0; iJavaLoader + *

+ * @return Returns a XSingleServiceFactory for creating the + * component. + * @see com.sun.star.comp.loader.JavaLoader + * @param sImplementationName The implementation name of the component. + */ + public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) { + XSingleComponentFactory xFactory = null; + + if ( sImplementationName.equals( ProtocolHandlerAddonImpl.class.getName() ) ) + xFactory = Factory.createComponentFactory(ProtocolHandlerAddonImpl.class, + ProtocolHandlerAddonImpl.getServiceNames()); + + return xFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandlerAddon_java.components b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandlerAddon_java.components new file mode 100644 index 000000000..13665ebbc --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Addons/ProtocolHandlerAddon_java/ProtocolHandlerAddon_java.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Components/CppComponent/Makefile b/odk/examples/DevelopersGuide/Components/CppComponent/Makefile new file mode 100644 index 000000000..5a63f4687 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/CppComponent/Makefile @@ -0,0 +1,228 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the C++ component example of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=CppComponentSample +SAMPLE_INC_OUT=$(OUT_INC)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT=$(OUT_MISC)/$(SAMPLE_NAME) +SAMPLE_SLO_OUT=$(OUT_SLO)/$(SAMPLE_NAME) +SAMPLE_OBJ_OUT=$(OUT_OBJ)/$(SAMPLE_NAME) + +COMP_NAME=CppComponent +COMP_IMPL_NAME=$(COMP_NAME).uno.$(SHAREDLIB_EXT) + +APP1_NAME= TestCppComponent +APP1_BINARY= $(OUT_BIN)/$(APP1_NAME)$(EXE_EXT) + +COMP_RDB_NAME = $(COMP_NAME).uno.rdb +COMP_RDB = $(SAMPLE_GEN_OUT)/$(COMP_RDB_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_UNOPKG_MANIFEST = $(SAMPLE_GEN_OUT)/$(COMP_NAME)/META-INF/manifest.xml +COMP_COMPONENTS = $(SAMPLE_GEN_OUT)/$(COMP_NAME).components + +COMP_REGISTERFLAG = $(SAMPLE_GEN_OUT)/devguide_$(COMP_NAME)_register_component.flag +COMP_TYPEFLAG = $(SAMPLE_GEN_OUT)/devguide_$(COMP_NAME)_types.flag + +IDLFILES = some.idl + +CXXFILES = service1_impl.cxx \ + service2_impl.cxx + +SLOFILES = $(patsubst %.cxx,$(SAMPLE_SLO_OUT)/%.$(OBJ_EXT),$(CXXFILES)) + +GENURDFILES = $(patsubst %.idl,$(SAMPLE_GEN_OUT)/%.urd,$(IDLFILES)) + +TYPELIST=-Tmy_module.XSomething \ + -Tmy_modules.MyService1 \ + -Tmy_module.MyService2 + +# Targets +.PHONY: ALL +ALL : \ + $(SAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(SAMPLE_GEN_OUT)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -I. -I$(IDL_DIR) -O$(SAMPLE_GEN_OUT) $< + +$(SAMPLE_GEN_OUT)/%.rdb : $(GENURDFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(REGMERGE) $@ /UCR $(GENURDFILES) + +$(COMP_TYPEFLAG) : $(COMP_RDB) $(SDKTYPEFLAG) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CPPUMAKER) -Gc -O$(SAMPLE_INC_OUT) $(TYPESLIST) $(COMP_RDB) -X$(URE_TYPES) -X$(OFFICE_TYPES) + echo flagged > $@ + +$(SAMPLE_SLO_OUT)/%.$(OBJ_EXT) : %.cxx $(COMP_TYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(SAMPLE_INC_OUT) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +ifeq "$(OS)" "WIN" +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + $(LINK) $(COMP_LINK_FLAGS) /OUT:$@ \ + /MAP:$(SAMPLE_GEN_OUT)/$(subst $(SHAREDLIB_EXT),map,$(@F)) $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) msvcprt.lib $(LIBO_SDK_LDFLAGS_STDLIBS) + $(LINK_MANIFEST) +else +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) && $(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + $(LINK) $(COMP_LINK_FLAGS) $(LINK_LIBS) -o $@ $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS) $@ +endif +endif + +# rule for component package manifest +$(SAMPLE_GEN_OUT)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-typelibrary;type=RDB$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(SAMPLE_GEN_OUT)/,,$(@D))).uno.rdb$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components;platform=$(UNOPKG_PLATFORM)$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +$(COMP_COMPONENTS) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)components xmlns="$(QM)http://openoffice.org/2010/uno-components$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)component loader="$(QM)com.sun.star.loader.SharedLibrary$(QM)" uri="$(QM)$(UNOPKG_PLATFORM)/$(COMP_IMPL_NAME)$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)my_module.my_sc_implementation.MyService1$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)my_module.MyService1$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)my_module.my_sc_implementation.MyService2$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)my_module.MyService2$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/component$(CSEP) >> $@ + @echo $(OSEP)/components$(CSEP) >> $@ + +$(COMP_PACKAGE) : $(SHAREDLIB_OUT)/$(COMP_IMPL_NAME) $(COMP_RDB) $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(SAMPLE_GEN_OUT)/$(UNOPKG_PLATFORM)) + $(COPY) $(subst /,$(PS),$<) $(subst /,$(PS),$(SAMPLE_GEN_OUT)/$(UNOPKG_PLATFORM)) + cd $(subst /,$(PS),$(SAMPLE_GEN_OUT)) && $(SDK_ZIP) ../../bin/$(@F) $(COMP_NAME).components + cd $(subst /,$(PS),$(SAMPLE_GEN_OUT)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_RDB_NAME) $(UNOPKG_PLATFORM)/$( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(SAMPLE_OBJ_OUT)/$(APP1_NAME).$(OBJ_EXT) : $(APP1_NAME).cxx $(COMP_TYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(SAMPLE_INC_OUT) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +$(OUT_BIN)/_$(APP1_NAME)$(EXE_EXT) : $(SAMPLE_OBJ_OUT)/$(APP1_NAME).$(OBJ_EXT) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) +ifeq "$(OS)" "WIN" + $(LINK) $(EXE_LINK_FLAGS) /OUT:$@ /MAP:$(SAMPLE_GEN_OUT)/$(basename $(@F)).map \ + $< $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) +else + $(LINK) $(EXE_LINK_FLAGS) $(LINK_LIBS) -o $@ $< \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) $(STDC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS_BIN) $@ +endif +endif + +$(OUT_BIN)/$(APP1_NAME)$(EXE_EXT) : $(OUT_BIN)/_$(APP1_NAME)$(EXE_EXT) + $(COPY) $(subst /,$(PS),$(BIN_DIR)/unoapploader$(EXE_EXT)) $(subst /,$(PS),$@) +# touch the target to renew the date for correct dependencies. +# Note: no touch under windows! The unoapploader.exe is copied always. +ifneq "$(OS)" "WIN" + touch $@ +endif + +$(SAMPLE_NAME) : $(COMP_REGISTERFLAG) $(APP1_BINARY) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo -------- + @echo The simple C++ component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the example + @echo description. You can also load the "$(QM)SimpleComponent.odt$(QM)" document containing + @echo a StarBasic macro which uses this component. + @echo - + @echo $(MAKE) SimpleComponent.odt.load + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_BIN)/%$(EXE_EXT) + $(subst /,$(PS),$(OUT_BIN))$(PS)$(basename $@) +# cd $(subst /,$(PS),$(OUT_BIN)) && $(basename $@) + +SimpleComponent.odt.load : $(COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_INC_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_SLO_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_OBJ_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_COMPONENTS))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_BIN)/$(COMP_NAME)*)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_BIN)/*$(APP1_NAME)*)) diff --git a/odk/examples/DevelopersGuide/Components/CppComponent/SimpleComponent.odt b/odk/examples/DevelopersGuide/Components/CppComponent/SimpleComponent.odt new file mode 100644 index 000000000..e8d7e9133 Binary files /dev/null and b/odk/examples/DevelopersGuide/Components/CppComponent/SimpleComponent.odt differ diff --git a/odk/examples/DevelopersGuide/Components/CppComponent/TestCppComponent.cxx b/odk/examples/DevelopersGuide/Components/CppComponent/TestCppComponent.cxx new file mode 100644 index 000000000..0dd690995 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/CppComponent/TestCppComponent.cxx @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::frame; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; + +SAL_IMPLEMENT_MAIN() +{ + try + { + // get the remote office component context + Reference< XComponentContext > xContext( ::cppu::bootstrap() ); + fprintf(stdout, "\nconnected to a running office...\n"); + + // create a new instance of MyService1 + Reference xSomething = + my_module::MyService1::create(xContext); + + // call methodOne and print the return value on stdout + OUString s = xSomething->methodOne(OUString("Hello World!")); + fprintf(stdout,"\nCreate new instance of MyService1\nCall of XSomething.methOne at MyService1 = %s", OUStringToOString( s, RTL_TEXTENCODING_ASCII_US ).getStr()); + + // create a new instance of MyService2 with the specified string argument + xSomething = my_module::MyService2::create(xContext, OUString("Hello My World!")); + + // call methodTwo and print the return value of methodTwo + s = xSomething->methodTwo(); + fprintf(stdout, "\n\nCreate new instance of MyService2 with argument\nCall of XSomething.methTwo at MyService2 = %s", OUStringToOString( s, RTL_TEXTENCODING_ASCII_US ).getStr()); + + fprintf(stdout, "\n\nPlease press 'return' to finish the example!\n"); + getchar(); + } + catch ( ::cppu::BootstrapException & e ) + { + fprintf(stderr, "\ncaught BootstrapException: %s\n", + OUStringToOString( e.getMessage(), RTL_TEXTENCODING_ASCII_US ).getStr()); + return 1; + } + catch ( Exception & e ) + { + fprintf(stderr, "\ncaught UNO exception: %s\n", + OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ).getStr()); + return 1; + } + + return 0; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/CppComponent/service1_impl.cxx b/odk/examples/DevelopersGuide/Components/CppComponent/service1_impl.cxx new file mode 100644 index 000000000..b9cf6f17b --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/CppComponent/service1_impl.cxx @@ -0,0 +1,227 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include +#include +#include + +#include +#include +#include + + +using namespace ::rtl; // for OUString +using namespace ::com::sun::star; // for odk interfaces +using namespace ::com::sun::star::uno; // for basic types + +namespace my_sc_impl +{ + +Sequence< OUString > SAL_CALL getSupportedServiceNames_MyService1Impl() +{ + Sequence< OUString > names(1); + names[0] = "my_module.MyService1"; + return names; +} + +OUString SAL_CALL getImplementationName_MyService1Impl() +{ + return OUString("my_module.my_sc_implementation.MyService1"); +} + + +class MyService1Impl + : public ::my_module::XSomething + , public lang::XServiceInfo + , public lang::XTypeProvider +{ + oslInterlockedCount m_refcount; + OUString m_sData; + // it's good practise to store the context for further use when you use + // other UNO API's in your implementation + Reference< XComponentContext > m_xContext; +public: + inline MyService1Impl(Reference< XComponentContext > const & xContext) throw () + : m_refcount( 0 ), + m_xContext(xContext) + {} + + virtual ~MyService1Impl() {} + + // XInterface + virtual Any SAL_CALL queryInterface( Type const & type ) + throw (RuntimeException); + virtual void SAL_CALL acquire() + throw (); + virtual void SAL_CALL release() + throw (); + // XTypeProvider + virtual Sequence< Type > SAL_CALL getTypes() + throw (RuntimeException); + virtual Sequence< sal_Int8 > SAL_CALL getImplementationId() + throw (RuntimeException); + // XSomething + virtual OUString SAL_CALL methodOne( OUString const & str ) + throw (RuntimeException); + virtual OUString SAL_CALL methodTwo( ) + throw (RuntimeException); + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() + throw (RuntimeException); + virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName ) + throw (RuntimeException); + virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() + throw (RuntimeException); +}; + +// XInterface implementation +Any MyService1Impl::queryInterface( Type const & type ) + throw (RuntimeException) +{ + if (type.equals(::cppu::UnoType::get())) + { + // return XInterface interface + // (resolve ambiguity by casting to lang::XTypeProvider) + Reference< XInterface > x( + static_cast< lang::XTypeProvider * >( this ) ); + return makeAny( x ); + } + if (type.equals(::cppu::UnoType::get())) + { + // return XInterface interface + Reference< XInterface > x( + static_cast< lang::XTypeProvider * >( this ) ); + return makeAny( x ); + } + if (type.equals(::cppu::UnoType::get())) + { + // return XServiceInfo interface + Reference< lang::XServiceInfo > x( + static_cast< lang::XServiceInfo * >( this ) ); + return makeAny( x ); + } + if (type.equals(::cppu::UnoType::get())) + { + // return sample interface + Reference< ::my_module::XSomething > x( + static_cast< ::my_module::XSomething * >( this ) ); + return makeAny( x ); + } + // querying for unsupported type + return Any(); +} + +void MyService1Impl::acquire() + throw () +{ + // thread-safe incrementation of reference count + ::osl_atomic_increment( &m_refcount ); +} + +void MyService1Impl::release() + throw () +{ + // thread-safe decrementation of reference count + if (0 == ::osl_atomic_decrement( &m_refcount )) + { + delete this; // shutdown this object + } +} + +// XTypeProvider implementation +Sequence< Type > MyService1Impl::getTypes() + throw (RuntimeException) +{ + Sequence< Type > seq( 3 ); + seq[ 0 ] = ::cppu::UnoType::get(); + seq[ 1 ] = ::cppu::UnoType::get(); + seq[ 2 ] = ::cppu::UnoType::get(); + return seq; +} + +Sequence< sal_Int8 > MyService1Impl::getImplementationId() + throw (RuntimeException) +{ + return css::uno::Sequence(); +} + +// XSomething implementation +OUString MyService1Impl::methodOne( OUString const & str ) + throw (RuntimeException) +{ + m_sData = str; + return OUString( "called methodOne() of MyService1 implementation: " ) + m_sData; +} + +OUString MyService1Impl::methodTwo( ) + throw (RuntimeException) +{ + return OUString( "called methodTwo() of MyService1 implementation: " ) + m_sData; +} + +// XServiceInfo implementation +OUString MyService1Impl::getImplementationName() + throw (RuntimeException) +{ + // unique implementation name + return OUString("my_module.my_sc_implementation.MyService1"); +} +sal_Bool MyService1Impl::supportsService( OUString const & serviceName ) + throw (RuntimeException) +{ + return cppu::supportsService(this, serviceName); +} +Sequence< OUString > MyService1Impl::getSupportedServiceNames() + throw (RuntimeException) +{ + // this object only supports one service + OUString serviceName("my_module.MyService1"); + return Sequence< OUString >( &serviceName, 1 ); +} + +Reference< XInterface > SAL_CALL create_MyService1Impl( + Reference< XComponentContext > const & xContext ) +{ + return static_cast< lang::XTypeProvider * >( new MyService1Impl( xContext) ); +} + +// forward decl: implemented in service2_impl.cxx +Reference< XInterface > SAL_CALL create_MyService2Impl( + Reference< XComponentContext > const & ); + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/CppComponent/service2_impl.cxx b/odk/examples/DevelopersGuide/Components/CppComponent/service2_impl.cxx new file mode 100644 index 000000000..b032b670e --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/CppComponent/service2_impl.cxx @@ -0,0 +1,215 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + + +using namespace ::rtl; // for OUString +using namespace ::com::sun::star; // for odk interfaces +using namespace ::com::sun::star::uno; // for basic types + + +namespace my_sc_impl +{ + +extern Sequence< OUString > SAL_CALL getSupportedServiceNames_MyService1Impl(); +extern OUString SAL_CALL getImplementationName_MyService1Impl(); +extern Reference< XInterface > SAL_CALL create_MyService1Impl( + Reference< XComponentContext > const & xContext ); + +static Sequence< OUString > getSupportedServiceNames_MyService2Impl() +{ + Sequence names(1); + names[0] = "my_module.MyService2"; + return names; +} + +static OUString getImplementationName_MyService2Impl() +{ + return OUString("my_module.my_sc_implementation.MyService2"); +} + +class MyService2Impl : public ::cppu::WeakImplHelper3< + ::my_module::XSomething, lang::XServiceInfo, lang::XInitialization > +{ + OUString m_sData; + // it's good practise to store the context for further use when you use + // other UNO API's in your implementation + Reference< XComponentContext > m_xContext; +public: + inline MyService2Impl(Reference< XComponentContext > const & xContext) throw () + : m_xContext(xContext) + {} + + virtual ~MyService2Impl() {} + + // focus on three given interfaces, + // no need to implement XInterface, XTypeProvider, XWeak + + // XInitialization will be called upon + // createInstanceWithArguments[AndContext]() + virtual void SAL_CALL initialize( Sequence< Any > const & args ) + throw (Exception); + // XSomething + virtual OUString SAL_CALL methodOne( OUString const & str ) + throw (RuntimeException); + virtual OUString SAL_CALL methodTwo( ) + throw (RuntimeException); + // XServiceInfo + virtual OUString SAL_CALL getImplementationName() + throw (RuntimeException); + virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName ) + throw (RuntimeException); + virtual Sequence< OUString > SAL_CALL getSupportedServiceNames() + throw (RuntimeException); +}; + +// XInitialization implementation +void MyService2Impl::initialize( Sequence< Any > const & args ) + throw (Exception) +{ + if (args.getLength() != 1) + { + throw lang::IllegalArgumentException( + OUString( + "give a string instantiating this component!"), + // resolve to XInterface reference: + static_cast< ::cppu::OWeakObject * >(this), + 0 ); // argument pos + } + if (! (args[ 0 ] >>= m_sData)) + { + throw lang::IllegalArgumentException( + OUString( + "no string given as argument!"), + // resolve to XInterface reference: + static_cast< ::cppu::OWeakObject * >(this), + 0 ); // argument pos + } +} + +// XSomething implementation +OUString MyService2Impl::methodOne( OUString const & str ) + throw (RuntimeException) +{ + m_sData = str; + return OUString( "called methodOne() of MyService2 implementation: " ) + m_sData; +} + +OUString MyService2Impl::methodTwo( ) + throw (RuntimeException) +{ + return OUString( "called methodTwo() of MyService2 implementation: " ) + m_sData; +} + +// XServiceInfo implementation +OUString MyService2Impl::getImplementationName() + throw (RuntimeException) +{ + // unique implementation name + return OUString("my_module.my_sc_implementation.MyService2"); +} + +sal_Bool MyService2Impl::supportsService( OUString const & serviceName ) + throw (RuntimeException) +{ + return cppu::supportsService(this, serviceName); +} + +Sequence< OUString > MyService2Impl::getSupportedServiceNames() + throw (RuntimeException) +{ + return getSupportedServiceNames_MyService2Impl(); +} + +Reference< XInterface > SAL_CALL create_MyService2Impl( + Reference< XComponentContext > const & xContext ) +{ + return static_cast< ::cppu::OWeakObject * >( new MyService2Impl( xContext ) ); +} + +} + +/* shared lib exports implemented without helpers in service_impl1.cxx */ +namespace my_sc_impl +{ +static const struct ::cppu::ImplementationEntry s_component_entries [] = +{ + { + create_MyService1Impl, getImplementationName_MyService1Impl, + getSupportedServiceNames_MyService1Impl, + ::cppu::createSingleComponentFactory, + 0, 0 + }, + { + create_MyService2Impl, getImplementationName_MyService2Impl, + getSupportedServiceNames_MyService2Impl, + ::cppu::createSingleComponentFactory, + 0, 0 + }, + { 0, 0, 0, 0, 0, 0 } +}; +} + +extern "C" +{ + +SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory( + char const * implName, lang::XMultiServiceFactory * xMgr, + registry::XRegistryKey * xRegistry ) +{ + return ::cppu::component_getFactoryHelper( + implName, xMgr, xRegistry, ::my_sc_impl::s_component_entries ); +} + +SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( + char const ** ppEnvTypeName, uno_Environment **) +{ + *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; +} + +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/CppComponent/some.idl b/odk/examples/DevelopersGuide/Components/CppComponent/some.idl new file mode 100644 index 000000000..22f6f74d1 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/CppComponent/some.idl @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include + +module my_module +{ + + interface XSomething + { + string methodOne( [in] string val ); + string methodTwo(); + }; + + service MyService1 : XSomething; + + service MyService2 : XSomething + { + create([in]string sArgument) + raises (::com::sun::star::lang::IllegalArgumentException); + }; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/JavaComponent/JavaComponent.components b/odk/examples/DevelopersGuide/Components/JavaComponent/JavaComponent.components new file mode 100644 index 000000000..67ac8696d --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/JavaComponent/JavaComponent.components @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Components/JavaComponent/Makefile b/odk/examples/DevelopersGuide/Components/JavaComponent/Makefile new file mode 100644 index 000000000..d78259e36 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/JavaComponent/Makefile @@ -0,0 +1,206 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the SpreadSheet examples of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings + +COMP_NAME=JavaComponent +OUT_COMP_CLASS = $(OUT_CLASS)/$(COMP_NAME) +OUT_COMP_GEN = $(OUT_MISC)/$(COMP_NAME) +COMP_RDB_NAME = $(COMP_NAME).uno.rdb +COMP_RDB = $(OUT_COMP_GEN)/$(COMP_RDB_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME = $(COMP_NAME).uno.jar +COMP_JAR = $(OUT_COMP_CLASS)/$(COMP_JAR_NAME) +COMP_MANIFESTFILE = $(OUT_COMP_CLASS)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(OUT_COMP_CLASS)/$(COMP_NAME)/META-INF/manifest.xml +COMP_COMPONENTS=$(COMP_NAME).components + +APP1_NAME=TestJavaComponent +APP1_JAR=$(OUT_COMP_CLASS)/$(APP1_NAME).jar + +REGISTERFLAG = $(OUT_MISC)$(PS)devguide_$(COMP_NAME)_register_component.flag + +IDLFILES = XSomethingA.idl \ + XSomethingB.idl \ + SomethingA.idl \ + SomethingB.idl + +# normally the idl file should be stored in a directory tree fitting the module +# structure, for the example we know the module structure +PACKAGE = com/sun/star/test + +COMPJAVAFILES = \ + TestComponentA.java \ + TestComponentB.java \ + TestServiceProvider.java + +GENCLASSFILES = $(patsubst %.idl,$(OUT_COMP_CLASS)/$(PACKAGE)/%.class,$(IDLFILES)) +GENCLASSNAMES = $(patsubst %.idl,$(PACKAGE)/%.class,$(IDLFILES)) +GENTYPELIST = $(subst /,.,$(patsubst %.idl,-T$(PACKAGE)/% ,$(IDLFILES))) +GENURDFILES = $(patsubst %.idl,$(OUT_COMP_GEN)/%.urd,$(IDLFILES)) + +COMPCLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(COMPJAVAFILES)) + +$(COMP_NAME)_CLASSFILES = $(patsubst %.java,%.class,$(COMPJAVAFILES)) + +$(COMP_NAME)_CLASSFILES += $(subst $(OUT_COMP_CLASS)/,,$(GENCLASSFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : \ + JavaComponentExample + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_CLASS)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo UNO-Type-Path: $(basename $(notdir $*)).uno.jar> $@ + @echo RegistrationClassName: TestServiceProvider>> $@ + +$(OUT_COMP_GEN)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -I. -I$(IDL_DIR) -O$(OUT_COMP_GEN) $^ + +$(OUT_COMP_GEN)/%.rdb : $(GENURDFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(REGMERGE) $@ /UCR $(GENURDFILES) + +$(OUT_COMP_CLASS)/$(PACKAGE)/%.class : $(COMP_RDB) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(JAVAMAKER) -nD $(GENTYPELIST) -O$(OUT_COMP_CLASS) $(COMP_RDB) -X$(URE_TYPES) -X$(OFFICE_TYPES) + +$(OUT_COMP_CLASS)/%.class : %.java $(GENCLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $< + +$(COMPCLASSFILES) : $(COMPJAVAFILES) $(GENCLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(COMPJAVAFILES) + +# rule for client/example application manifest file +$(OUT_COMP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +# rule for client/example application jar file +# Note that the example needs the component files as well for local usage +$(APP1_JAR) : $(OUT_COMP_CLASS)/$(APP1_NAME).mf $(OUT_COMP_CLASS)/$(APP1_NAME).class $(COMPCLASSFILES) $(GENCLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(basename $(@F)).class $($(COMP_NAME)_CLASSFILES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_MANIFESTFILE) $(COMPCLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_JAR) cvfm $(@F) $( $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-typelibrary;type=RDB$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(OUT_COMP_CLASS)/,,$(@D))).uno.rdb$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_RDB) $(COMP_JAR) $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(COPY) $(subst /,$(PS),$(COMP_RDB)) $(subst /,$(PS),$(OUT_COMP_CLASS)) + $(SDK_ZIP) $@ $(COMP_COMPONENTS) + cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_RDB_NAME) $(COMP_JAR_NAME) + cd $(subst /,$(PS),$(OUT_COMP_CLASS)/$(subst .$(UNOOXT_EXT),,$(@F))) && $(SDK_ZIP) -u ../../../bin/$(@F) META-INF/manifest.xml + $(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_COMP_CLASS)/$(COMP_RDB_NAME))) + +$(REGISTERFLAG) : $(COMP_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(COMP_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +JavaComponentExample : $(REGISTERFLAG) $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP1_NAME).local + @echo -------- + @echo The Java components were installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the + @echo example description. + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +%.local: $(OUT_COMP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< local + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(REGISTERFLAG))) diff --git a/odk/examples/DevelopersGuide/Components/JavaComponent/SomethingA.idl b/odk/examples/DevelopersGuide/Components/JavaComponent/SomethingA.idl new file mode 100644 index 000000000..e609ad461 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/JavaComponent/SomethingA.idl @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_COM_SUN_STAR_TEST_SOMETHINGA_IDL +#define INCLUDED_COM_SUN_STAR_TEST_SOMETHINGA_IDL + +#include + +module com { module sun { module star { module test { + service SomethingA: XSomethingA; +}; }; }; }; + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/JavaComponent/SomethingB.idl b/odk/examples/DevelopersGuide/Components/JavaComponent/SomethingB.idl new file mode 100644 index 000000000..5f458aa88 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/JavaComponent/SomethingB.idl @@ -0,0 +1,48 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_COM_SUN_STAR_TEST_SOMETHINGB_IDL +#define INCLUDED_COM_SUN_STAR_TEST_SOMETHINGB_IDL + +#include + +module com { module sun { module star { module test { + service SomethingB : XSomethingB; +}; }; }; }; + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/JavaComponent/TestComponentA.java b/odk/examples/DevelopersGuide/Components/JavaComponent/TestComponentA.java new file mode 100644 index 000000000..5427a3081 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/JavaComponent/TestComponentA.java @@ -0,0 +1,69 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.test.XSomethingA; + +// TestComponentA use the implementation helper WeakBase +public class TestComponentA extends WeakBase implements XServiceInfo, XSomethingA { + static final String __serviceName= "com.sun.star.test.SomethingA"; + + static byte[] _implementationId; + + // XSomethingA + public String methodOne(String val) { + return val; + } + + //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; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/JavaComponent/TestComponentB.java b/odk/examples/DevelopersGuide/Components/JavaComponent/TestComponentB.java new file mode 100644 index 000000000..c8f6def18 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/JavaComponent/TestComponentB.java @@ -0,0 +1,92 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XTypeProvider; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.test.XSomethingB; +import com.sun.star.uno.Type; + +// TestComponentB implements all necessary interfaces self, this is only +// for demonstration. More convenient is to use the implementation WeakBase or +// ComponentBase, see implementation of TestComponentA. +public class TestComponentB implements XTypeProvider, XServiceInfo, XSomethingB { + static final String __serviceName= "com.sun.star.test.SomethingB"; + + private final Object[] args; + + public TestComponentB(XComponentContext context, Object[] args) { + this.args= args; + } + + // XSomethingB + public String methodTwo(String val) { + if (args.length > 0 && args[0] instanceof String ) + return (String) args[0]; + return val; + } + + //XTypeProvider + public com.sun.star.uno.Type[] getTypes( ) { + Type[] retValue= new Type[3]; + retValue[0]= new Type( XServiceInfo.class); + retValue[1]= new Type( XTypeProvider.class); + retValue[2]= new Type( XSomethingB.class); + return retValue; + } + //XTypeProvider + public byte[] getImplementationId( ) { + return new byte[0]; + } + + //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; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/JavaComponent/TestJavaComponent.java b/odk/examples/DevelopersGuide/Components/JavaComponent/TestJavaComponent.java new file mode 100644 index 000000000..cea18aebc --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/JavaComponent/TestJavaComponent.java @@ -0,0 +1,144 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.uno.XComponentContext; +import com.sun.star.comp.helper.Bootstrap; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.test.XSomethingB; +import com.sun.star.test.SomethingB; +import com.sun.star.container.XSet; + +// sample starbasic code, you can execute it after you have connected to the office. +// Sub Main +// o = createUnoService( "com.sun.star.test.SomethingB" ) +// msgbox o.methodOne( "from the office !" ) +// End Sub + +public class TestJavaComponent +{ + + public static void insertIntoServiceManager( + XMultiComponentFactory serviceManager, Object singleFactory ) + throws com.sun.star.uno.Exception + { + XSet set = UnoRuntime.queryInterface( XSet.class, serviceManager ); + set.insert( singleFactory ); + } + + public static void removeFromServiceManager( + XMultiComponentFactory serviceManager, Object singleFactory ) + throws com.sun.star.uno.Exception + { + XSet set = UnoRuntime.queryInterface( XSet.class, serviceManager ); + set.remove( singleFactory ); + + } + + public static void main(String[] args) throws java.lang.Exception + { + try { + boolean bLocal = false; + + XMultiComponentFactory xUsedServiceManager = null; + XComponentContext xUsedComponentContext = null; + + if( args.length == 1 && args[0].equals( "local" )) + { + XComponentContext xLocalComponentContext = + Bootstrap.createInitialComponentContext( null ); + + // initial serviceManager + XMultiComponentFactory xLocalServiceManager = + xLocalComponentContext.getServiceManager(); + + bLocal = true; + xUsedServiceManager = xLocalServiceManager; + xUsedComponentContext = xLocalComponentContext; + + System.out.println( "Using local servicemanager" ); + } else { + // get the remote office component context + xUsedComponentContext = + com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + xUsedServiceManager = xUsedComponentContext.getServiceManager(); + System.out.println( "Using remote servicemanager" ); + } + + if ( xUsedServiceManager == null ) + { + System.out.println( "ERROR: no service manager" ); + System.exit(0); + } + + Object factory = new Object(); + if ( bLocal ) + { + // retrieve the factory for the component implementation + factory = TestServiceProvider.__getServiceFactory( + "TestComponentB", null, null); + + // insert the factory into the local servicemanager + // From now on, the service can be instantiated ! + insertIntoServiceManager( xUsedServiceManager, factory ); + } + + XSomethingB xSomethingB = SomethingB.create(xUsedComponentContext); + + // and call the test method. + String s= xSomethingB.methodTwo("Hello World!"); + System.out.println(s); + + if ( bLocal ) + { + // remove it again from the servicemanager, + removeFromServiceManager( xUsedServiceManager, factory ); + } + + } + catch ( Exception e ) + { + System.out.println( "UNO Exception caught: " + e ); + System.out.println( "Message: " + e.getMessage() ); + e.printStackTrace(System.err); + } + + // quit, even when a remote bridge is running + System.exit(0); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/JavaComponent/TestServiceProvider.java b/odk/examples/DevelopersGuide/Components/JavaComponent/TestServiceProvider.java new file mode 100644 index 000000000..fde48e894 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/JavaComponent/TestServiceProvider.java @@ -0,0 +1,61 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +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; + +public class TestServiceProvider +{ + public static XSingleServiceFactory __getServiceFactory( + String implName, + XMultiServiceFactory multiFactory, + XRegistryKey regKey) { + XSingleServiceFactory xSingleServiceFactory = null; + + if (implName.equals( TestComponentA.class.getName()) ) + xSingleServiceFactory = FactoryHelper.getServiceFactory( + TestComponentA.class, TestComponentA.__serviceName, + multiFactory, regKey); + else if (implName.equals(TestComponentB.class.getName())) + xSingleServiceFactory= FactoryHelper.getServiceFactory( + TestComponentB.class, TestComponentB.__serviceName, + multiFactory, regKey); + return xSingleServiceFactory; + } +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/JavaComponent/XSomethingA.idl b/odk/examples/DevelopersGuide/Components/JavaComponent/XSomethingA.idl new file mode 100644 index 000000000..61b501229 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/JavaComponent/XSomethingA.idl @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_COM_SUN_STAR_TEST_XSOMETHINGA_IDL +#define INCLUDED_COM_SUN_STAR_TEST_XSOMETHINGA_IDL + +#include + +module com { module sun { module star { module test { + interface XSomethingA { + string methodOne([in]string value); + }; +}; }; }; }; + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/JavaComponent/XSomethingB.idl b/odk/examples/DevelopersGuide/Components/JavaComponent/XSomethingB.idl new file mode 100644 index 000000000..92d0bd19e --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/JavaComponent/XSomethingB.idl @@ -0,0 +1,50 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_COM_SUN_STAR_TEST_XSOMETHINGB_IDL +#define INCLUDED_COM_SUN_STAR_TEST_XSOMETHINGB_IDL + +#include + +module com { module sun { module star { module test { + interface XSomethingB { + string methodTwo([in]string value); + }; +}; }; }; }; + +#endif + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.components b/odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.components new file mode 100644 index 000000000..94a4848c0 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.idl b/odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.idl new file mode 100644 index 000000000..68eab80ee --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.idl @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef _org_openoffice_LicenseTest_idl_ +#define _org_openoffice_LicenseTest_idl_ + +#include + +// org +module org { + // openoffice + module openoffice { + // example service, XServiceInfo is implemented here for demonstration + // issues. XServiceInfo must be implemented by all components. + service LicenseTest: ::com::sun::star::lang::XServiceInfo; + }; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.java b/odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.java new file mode 100644 index 000000000..b47aa7008 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/SimpleLicense/LicenseTest.java @@ -0,0 +1,129 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.lang.XServiceInfo; + +/** This class capsulates the class, that implements the minimal component, a + * factory for creating the service (__getComponentFactory) and a + * method, that writes the information into the given registry key + * (__writeRegistryServiceInfo). + */ +public class LicenseTest { + /** This class implements the component. At least the interfaces XServiceInfo, + * XTypeProvider, and XInitialization should be provided by the service. + */ + public static class _LicenseTest extends WeakBase + implements XServiceInfo { + /** The service name, that must be used to get an instance of this service. + */ + private static final String __serviceName = + "org.openoffice.LicenseTest"; + + /** This method returns an array of all supported service names. + * @return Array of supported service names. + */ + public String[] getSupportedServiceNames() { + return getServiceNames(); + } + + /** This method is a simple helper function to used in the + * static component initialisation functions as well as in + * getSupportedServiceNames. + */ + public static String[] getServiceNames() { + String[] sSupportedServiceNames = { __serviceName }; + return sSupportedServiceNames; + } + + /** This method returns true, if the given service will be + * supported by the component. + * @param sServiceName Service name. + * @return True, if the given service name will be supported. + */ + public boolean supportsService( String sServiceName ) { + return sServiceName.equals( __serviceName ); + } + + /** Return the class name of the component. + * @return Class name of the component. + */ + public String getImplementationName() { + return _LicenseTest.class.getName(); + } + } + + + /** + * Gives a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XSingleComponentFactory for creating + * the component + * @param sImplName the name of the implementation for which a + * service is desired + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleComponentFactory __getComponentFactory(String sImplName) + { + XSingleComponentFactory xFactory = null; + + if ( sImplName.equals( _LicenseTest.class.getName() ) ) + xFactory = Factory.createComponentFactory(_LicenseTest.class, + _LicenseTest.getServiceNames()); + + return xFactory; + } + + /** This method is a member of the interface for initializing an object + * directly after its creation. + * @param object This array of arbitrary objects will be passed to the + * component after its creation. + * @throws com.sun.star.uno.Exception Every exception will not be handled, but will be + * passed to the caller. + */ + public void initialize( Object[] object ) + throws com.sun.star.uno.Exception { + /* The component describes what arguments are expected and in which + * order! At this point you can read the objects and initialize + * your component using these objects. + */ + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/SimpleLicense/Makefile b/odk/examples/DevelopersGuide/Components/SimpleLicense/Makefile new file mode 100644 index 000000000..efcac2aac --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/SimpleLicense/Makefile @@ -0,0 +1,171 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the License Test component example of the SDK. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings + +# we use the sample directory name for separating this example +# from others in the output directory +SAMPLE_NAME=LicenseTest +SAMPLE_CLASS_OUT=$(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT=$(OUT_MISC)/$(SAMPLE_NAME) + +COMP_NAME=LicenseTest +COMP_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(COMP_NAME) +COMP_GEN_OUT=$(SAMPLE_GEN_OUT)/$(COMP_NAME) +COMP_RDB_NAME=$(COMP_NAME).uno.rdb +COMP_RDB=$(COMP_GEN_OUT)/$(COMP_RDB_NAME) +COMP_PACKAGE=$(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL=$(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME=$(COMP_NAME).uno.jar +COMP_JAR=$(SAMPLE_CLASS_OUT)/$(COMP_JAR_NAME) +COMP_JAR_MANIFEST=$(COMP_GEN_OUT)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(COMP_GEN_OUT)/META-INF/manifest.xml +COMP_REGISTERFLAG=$(COMP_GEN_OUT)$(PS)java_$(COMP_NAME)_register_component.flag +COMP_LOCAL_FILES = description.xml registration/license_de.txt registration/license_en_US.txt +COMP_COMPONENTS=$(COMP_NAME).components + +IDLFILES = LicenseTest.idl + +# normally the idl file should be stored in a directory tree fitting the module structure, +# for the example we know the module structure +PACKAGE = org/openoffice + +COMP_JAVAFILES = LicenseTest.java +COMP_CLASSFILES = $(patsubst %.java,$(COMP_CLASS_OUT)/%.class,$(COMP_JAVAFILES)) + +GEN_CLASSFILES = $(patsubst %.idl,$(SAMPLE_CLASS_OUT)/$(PACKAGE)/%.class,$(IDLFILES)) +GEN_TYPELIST = $(subst /,.,$(patsubst %.idl,-T$(PACKAGE)/% ,$(IDLFILES))) +GEN_URDFILES = $(patsubst %.idl,$(SAMPLE_GEN_OUT)/%.urd,$(IDLFILES)) + +# the generated types are necessary for the component and the application jar +GEN_CLASSFILENAMES = $(subst $(SAMPLE_CLASS_OUT)/,,$(GEN_CLASSFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)\ + $(PATH_SEPARATOR)$(COMP_CLASS_OUT)\ + $(PATH_SEPARATOR)$(APP1_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : JavaLicenseTestExample + +include $(SETTINGS)/stdtarget.mk + +$(COMP_GEN_OUT)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo UNO-Type-Path: $(basename $(notdir $*)).uno.jar> $@ + @echo RegistrationClassName: $(basename $*)>> $@ + +$(SAMPLE_GEN_OUT)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -C -I. -I$(IDL_DIR) -O$(SAMPLE_GEN_OUT) $< + +$(COMP_GEN_OUT)/%.rdb : $(GEN_URDFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(REGMERGE) $@ /UCR $(GEN_URDFILES) + +$(GEN_CLASSFILES) : $(COMP_RDB) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(JAVAMAKER) -nD $(GEN_TYPELIST) -O$(SAMPLE_CLASS_OUT) $(COMP_RDB) -X$(URE_TYPES) -X$(OFFICE_TYPES) + +# component as well as application are dependent from the generated types +# rule for component class files +$(COMP_CLASS_OUT)/%.class : %.java $(GEN_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(COMP_CLASS_OUT) $< + +# rule for component jar file +$(COMP_JAR) : $(COMP_JAR_MANIFEST) $(COMP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(COMP_CLASS_OUT) . + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) uvf $(@F) $(GEN_CLASSFILENAMES) + +# rule for component package manifest +$(COMP_GEN_OUT)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-typelibrary;type=RDB$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(SAMPLE_GEN_OUT)/,,$(@D))).uno.rdb$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_RDB) $(COMP_JAR) $(COMP_UNOPKG_MANIFEST) $(COMP_LOCAL_FILES) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ $(COMP_COMPONENTS) + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u ../../../bin/$(@F) $(COMP_RDB_NAME) + cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_JAR_NAME) + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u ../../../bin/$(@F) META-INF/manifest.xml + $(SDK_ZIP) -u $@ $(COMP_LOCAL_FILES) + +$(COMP_REGISTERFLAG) : $(COMP_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(COMP_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +JavaLicenseTestExample : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The $(COMP_NAME) component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo This extension demonstrates the $(QM)Simple License$(QM) feature. + @echo -------------------------------------------------------------------------------- + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/DevelopersGuide/Components/SimpleLicense/description.xml b/odk/examples/DevelopersGuide/Components/SimpleLicense/description.xml new file mode 100644 index 000000000..efc2dcb17 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/SimpleLicense/description.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Components/SimpleLicense/registration/license_de.txt b/odk/examples/DevelopersGuide/Components/SimpleLicense/registration/license_de.txt new file mode 100644 index 000000000..6deedf8b4 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/SimpleLicense/registration/license_de.txt @@ -0,0 +1 @@ +Eine ganz kurze Lizenz. \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/Components/SimpleLicense/registration/license_en_US.txt b/odk/examples/DevelopersGuide/Components/SimpleLicense/registration/license_en_US.txt new file mode 100644 index 000000000..127a4569b --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/SimpleLicense/registration/license_en_US.txt @@ -0,0 +1 @@ +A very short license. \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/Components/Thumbs/Makefile b/odk/examples/DevelopersGuide/Components/Thumbs/Makefile new file mode 100644 index 000000000..95adaef3d --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Thumbs/Makefile @@ -0,0 +1,80 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Component Thumbs of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +include thumbs.mk + +SUBDIRS= org/openoffice/test org/openoffice/comp/test + +# Targets +.PHONY: ALL +ALL : \ + $(SUBDIRS) \ + ComponentsThumbsExample + +include $(SETTINGS)/stdtarget.mk + +.PHONY : $(SUBDIRS) +$(SUBDIRS) : + $(MAKE) -C $@ + +org/openoffice/comp/test : org/openoffice/test + +ComponentsThumbsExample : $(COMP_PACKAGE) + @echo -------------------------------------------------------------------------------- + @echo Please use one of the following command to execute the example! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo -------- + @echo The ImageShrink Java component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the example + @echo description. + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + $(MAKE) -C org/openoffice/test clean + $(MAKE) -C org/openoffice/comp/test clean + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) diff --git a/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/ImageShrink.components b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/ImageShrink.components new file mode 100644 index 000000000..11d958fe8 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/ImageShrink.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/ImageShrink.java b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/ImageShrink.java new file mode 100644 index 000000000..7022f5c32 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/ImageShrink.java @@ -0,0 +1,129 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +package org.openoffice.comp.test; + +import com.sun.star.lang.XSingleServiceFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.comp.loader.FactoryHelper; +import com.sun.star.lib.uno.helper.WeakBase; + +public class ImageShrink extends WeakBase + implements com.sun.star.lang.XServiceInfo, + org.openoffice.test.XImageShrinkFilter { + + com.sun.star.uno.XComponentContext xComponentContext = null; + + // hold the service name in a private static member variable of the class + protected static final String __serviceName = "org.openoffice.test.ImageShrink"; + + + String destDir = ""; + String sourceDir = ""; + boolean cancel = false; + com.sun.star.awt.Size dimension = new com.sun.star.awt.Size(); + + // static __getServiceFactory() Implementation + public static XSingleServiceFactory __getServiceFactory(String implName, + XMultiServiceFactory multiFactory, + com.sun.star.registry.XRegistryKey regKey) { + + com.sun.star.lang.XSingleServiceFactory xSingleServiceFactory = null; + if (implName.equals( ImageShrink.class.getName()) ) + xSingleServiceFactory = FactoryHelper.getServiceFactory( ImageShrink.class, + ImageShrink.__serviceName, + multiFactory, + regKey); + + return xSingleServiceFactory; + } + + // XFilter implementation (a sub-interface of XImageShrinkFilter) + public void cancel() { + cancel = true; + } + + public boolean filter(com.sun.star.beans.PropertyValue[] propertyValue) { + // while cancel = false, + // scale images found in sourceDir according to dimension and + // write them to destDir, using the image file format given in + + + // []propertyValue + return true; + } + + // XImageShrink implementation (a sub-interface of XImageShrinkFilter) + public String getDestinationDirectory() { + return destDir; + } + + public com.sun.star.awt.Size getDimension() { + return dimension; + } + + public String getSourceDirectory() { + return sourceDir; + } + + public void setDestinationDirectory(String str) { + destDir = str; + } + + public void setDimension(com.sun.star.awt.Size size) { + dimension = size; + } + + public void setSourceDirectory(String str) { + sourceDir = str; + } + + //XServiceInfo implementation + public String getImplementationName( ) { + return getClass().getName(); + } + + public boolean supportsService(String serviceName) { + if ( serviceName.equals( __serviceName)) + return true; + return false; + } + + public String[] getSupportedServiceNames( ) { + return new String[] { __serviceName }; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/Makefile b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/Makefile new file mode 100644 index 000000000..c89cbb62f --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/Makefile @@ -0,0 +1,128 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the SpreadSheet examples of the Developers Guide. + +PRJ=../../../../../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +include ../../../../thumbs.mk + +# Define non-platform/compiler specific settings +PACKAGE = org/openoffice/comp/test + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : $(REGISTERFLAG) \ + $(APP1_JAR) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_CLASS)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo UNO-Type-Path: $(basename $(notdir $*)).uno.jar> $@ + @echo RegistrationClassName: $(subst /,.,$(PACKAGE)).$(basename $(basename $(@F)))>> $@ + +$(OUT_COMP_CLASS)/$(PACKAGE)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $< + +$(OUT_COMP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $(subst /,.,$(PACKAGE)).$*>> $@ + +# rule for component jar file +$(COMP_JAR) : $(COMP_MANIFESTFILE) $(OUT_COMP_CLASS)/$(PACKAGE)/$(COMP_NAME).class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(OUT_COMP_CLASS) $(PACKAGE)/$(basename $(basename $(@F))).class $(patsubst %.class,-C $(OUT_COMP_CLASS) %.class,$(GENCLASSNAMES)) + +# rule for component package manifest +$(OUT_COMP_CLASS)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-typelibrary;type=RDB$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(OUT_COMP_CLASS)/,,$(@D))).uno.rdb$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_RDB) $(COMP_JAR) $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(COPY) $(subst /,$(PS),$(COMP_RDB)) $(subst /,$(PS),$(OUT_COMP_CLASS)) + $(SDK_ZIP) $@ $(COMP_COMPONENTS) + cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_RDB_NAME) $(COMP_JAR_NAME) + cd $(subst /,$(PS),$(OUT_COMP_CLASS)/$(subst .$(UNOOXT_EXT),,$(@F))) && $(SDK_ZIP) -u ../../../bin/$(@F) META-INF/manifest.xml + $(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_CLASS)/$(COMP_RDB_NAME))) + +$(APP1_JAR) : $(OUT_COMP_CLASS)/$(APP1_NAME).mf $(OUT_COMP_CLASS)/$(PACKAGE)/$(APP1_NAME).class + -$(MKDIR) $(subst /,$(PS),$(@D)) && $(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + $(SDK_JAR) cvfm $@ $< -C $(OUT_COMP_CLASS) $(PACKAGE)/$(basename $(@F)).class $(patsubst %.class,-C $(OUT_COMP_CLASS) %.class,$(GENCLASSNAMES)) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + + +$(REGISTERFLAG) : $(COMP_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(COMP_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +.PHONY: clean +clean : + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_JAR))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(REGISTERFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(APP1_JAR))) diff --git a/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/Thumbs.java b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/Thumbs.java new file mode 100644 index 000000000..a43c4da87 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/comp/test/Thumbs.java @@ -0,0 +1,79 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +package org.openoffice.comp.test; + + +/** + * Test class for testing the ImageShrink service skeleton. + * Note: the image shrink functionality is not implemented + */ +public class Thumbs { + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + try { + // get the remote office component context + com.sun.star.uno.XComponentContext xRemoteContext = + com.sun.star.comp.helper.Bootstrap.bootstrap(); + + System.out.println("Connected to a running office ..."); + + // use the generated default create method to instantiate a + // new ImageShrink object + org.openoffice.test.XImageShrinkFilter xImageShrinkFilter = + org.openoffice.test.ImageShrink.create(xRemoteContext); + + System.out.println("ImageShrink component successfully instantiated"); + + java.io.File f = new java.io.File("."); + System.out.println("set SourceDirectory..."); + xImageShrinkFilter.setSourceDirectory(f.getCanonicalPath()); + + System.out.println("source Directory = " + + xImageShrinkFilter.getSourceDirectory()); + } + catch (java.lang.Exception e){ + System.err.println("Error: " + e); + e.printStackTrace(); + } + finally { + System.exit(0); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/ImageShrink.idl b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/ImageShrink.idl new file mode 100644 index 000000000..29741ffeb --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/ImageShrink.idl @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef _org_openoffice_test_ImageShrink_idl_ +#define _org_openoffice_test_ImageShrink_idl_ + +#include + +module org { module openoffice { module test { + + service ImageShrink : XImageShrinkFilter; + +}; }; }; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/Makefile b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/Makefile new file mode 100644 index 000000000..a9f13dbf5 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/Makefile @@ -0,0 +1,72 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the SpreadSheet examples of the Developers Guide. + +PRJ=../../../../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +include ../../../thumbs.mk + +PACKAGE = org/openoffice/test + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + +# Targets +.PHONY: ALL +ALL : \ + $(GENCLASSFILES) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_GEN)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -I. -I../../.. -I$(IDL_DIR) -O$(OUT_COMP_GEN) $^ + +$(OUT_COMP_GEN)/%.rdb : $(GENURDFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(REGMERGE) $@ /UCR $(GENURDFILES) + +$(OUT_COMP_CLASS)/%.class : $(COMP_RDB) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(JAVAMAKER) -nD $(GENTYPELIST) -O$(OUT_COMP_CLASS) $(COMP_RDB) -X$(URE_TYPES) -X$(OFFICE_TYPES) + +.PHONY: clean +clean : + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(GENCLASSFILES))) diff --git a/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/XImageShrink.idl b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/XImageShrink.idl new file mode 100644 index 000000000..c6097925f --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/XImageShrink.idl @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef _org_openoffice_test_XImageShrink_idl_ +#define _org_openoffice_test_XImageShrink_idl_ + +#include +#include + +module org { module openoffice { module test { + +interface XImageShrink { + + [attribute] string SourceDirectory; + [attribute] string DestinationDirectory; + [attribute] com::sun::star::awt::Size Dimension; + +}; + +}; }; }; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/XImageShrinkFilter.idl b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/XImageShrinkFilter.idl new file mode 100644 index 000000000..6388e0aa3 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Thumbs/org/openoffice/test/XImageShrinkFilter.idl @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef _org_openoffice_test_XImageShrinkFilter_idl_ +#define _org_openoffice_test_XImageShrinkFilter_idl_ + +#include +#include + +module org { module openoffice { module test { + +interface XImageShrinkFilter { + interface XImageShrink; + interface com::sun::star::document::XFilter; +}; + +}; }; }; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/Thumbs/thumbs.mk b/odk/examples/DevelopersGuide/Components/Thumbs/thumbs.mk new file mode 100644 index 000000000..d5dbc181e --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/Thumbs/thumbs.mk @@ -0,0 +1,46 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +OUT_COMP_CLASS = $(OUT_CLASS)/ComponentThumbsExample +OUT_COMP_GEN = $(OUT_MISC)/ComponentThumbsExample + +COMP_NAME=ImageShrink +COMP_RDB_NAME = $(COMP_NAME).uno.rdb +COMP_RDB = $(OUT_COMP_GEN)/$(COMP_RDB_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME = $(COMP_NAME).uno.jar +COMP_JAR = $(OUT_COMP_CLASS)/$(COMP_JAR_NAME) +COMP_MANIFESTFILE = $(OUT_COMP_CLASS)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(OUT_COMP_CLASS)/$(COMP_NAME)/META-INF/manifest.xml +REGISTERFLAG = $(OUT_MISC)$(PS)devguide_$(COMP_NAME)_register_component.flag +COMP_COMPONENTS=$(COMP_NAME).components + +IDL_PACKAGE=org/openoffice/test + +IDLFILES = XImageShrink.idl \ + XImageShrinkFilter.idl \ + ImageShrink.idl + +GENCLASSFILES = $(patsubst %.idl,$(OUT_COMP_CLASS)/$(IDL_PACKAGE)/%.class,$(IDLFILES)) +GENCLASSNAMES = $(patsubst %.idl,$(IDL_PACKAGE)/%.class,$(IDLFILES)) +GENTYPELIST = $(subst /,.,$(patsubst %.idl,-T$(IDL_PACKAGE)/% ,$(IDLFILES))) +GENURDFILES = $(patsubst %.idl,$(OUT_COMP_GEN)/%.urd,$(IDLFILES)) + +APP1_NAME=Thumbs +APP1_JAR=$(OUT_COMP_CLASS)/$(APP1_NAME).jar diff --git a/odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.components b/odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.components new file mode 100644 index 000000000..56d7c8eb8 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.java b/odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.java new file mode 100644 index 000000000..643dcda64 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.java @@ -0,0 +1,294 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.beans.XPropertySet; +import com.sun.star.uno.Type; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XTypeProvider; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.awt.XControl; +import com.sun.star.awt.XControlContainer; +import com.sun.star.awt.XControlModel; +import com.sun.star.awt.XDialog; +import com.sun.star.awt.XDialogEventHandler; +import com.sun.star.awt.XDialogProvider2; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.XModel; + +import com.sun.star.awt.XToolkit; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.awt.XMessageBox; +import com.sun.star.awt.WindowAttribute; +import com.sun.star.awt.WindowClass; +import com.sun.star.awt.WindowDescriptor; +import com.sun.star.awt.Rectangle; + +import com.sun.star.test.XTestDialogHandler; + +// DialogComponent implements all necessary interfaces self, this is only +// for demonstration. More convenient is to use the implementation WeakBase or +// ComponentBase, see implementation of TestComponentA. +public class DialogComponent { + + public static class _DialogComponent + implements XTypeProvider, XServiceInfo, XTestDialogHandler, XDialogEventHandler { + + private static final String __serviceName= "com.sun.star.test.TestDialogHandler"; + + + private final XComponentContext m_xCmpCtx; + + private XFrame m_xFrame; + private XToolkit m_xToolkit; + + public _DialogComponent(XComponentContext context) { + m_xCmpCtx= context; + + try { + // Create the toolkit to have access to it later + m_xToolkit = UnoRuntime.queryInterface( + XToolkit.class, + m_xCmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.awt.Toolkit", + m_xCmpCtx)); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + // XTestDialogHandler + public String createDialog( String DialogURL, XModel xModel, XFrame xFrame ) { + m_xFrame = xFrame; + + try { + XMultiComponentFactory xMCF = m_xCmpCtx.getServiceManager(); + Object obj; + + // If valid we must pass the XModel when creating a DialogProvider object + if( xModel != null ) { + Object[] args = new Object[1]; + args[0] = xModel; + + obj = xMCF.createInstanceWithArgumentsAndContext( + "com.sun.star.awt.DialogProvider2", args, m_xCmpCtx ); + } + else { + obj = xMCF.createInstanceWithContext( + "com.sun.star.awt.DialogProvider2", m_xCmpCtx ); + } + + XDialogProvider2 xDialogProvider = UnoRuntime.queryInterface( XDialogProvider2.class, obj ); + + XDialog xDialog = xDialogProvider.createDialogWithHandler( DialogURL, this ); + if( xDialog != null ) + xDialog.execute(); + } + catch (Exception e) { + e.printStackTrace(); + } + return "Created dialog \"" + DialogURL + "\""; + } + + public void copyText( XDialog xDialog, Object aEventObject ) { + XControlContainer xControlContainer = UnoRuntime.queryInterface( + XControlContainer.class, xDialog ); + String aTextPropertyStr = "Text"; + String aText = ""; + XControl xTextField1Control = xControlContainer.getControl( "TextField1" ); + XControlModel xControlModel1 = xTextField1Control.getModel(); + XPropertySet xPropertySet1 = UnoRuntime.queryInterface( + XPropertySet.class, xControlModel1 ); + try + { + aText = (String)xPropertySet1.getPropertyValue( aTextPropertyStr ); + } + catch (Exception e) { + e.printStackTrace(); + } + + XControl xTextField2Control = xControlContainer.getControl( "TextField2" ); + XControlModel xControlModel2 = xTextField2Control.getModel(); + XPropertySet xPropertySet2 = UnoRuntime.queryInterface( + XPropertySet.class, xControlModel2 ); + try + { + xPropertySet2.setPropertyValue( aTextPropertyStr, aText ); + } + catch (Exception e) { + e.printStackTrace(); + } + + showMessageBox( "DialogComponent", "copyText() called" ); + } + + public void handleEvent() { + showMessageBox( "DialogComponent", "handleEvent() called" ); + } + + public void handleEventWithArguments( XDialog xDialog, Object aEventObject ) { + showMessageBox( "DialogComponent", "handleEventWithArguments() called\n\n" + + "Event Object = " + aEventObject ); + } + + private static final String aHandlerMethod1 = "doit1"; + private static final String aHandlerMethod2 = "doit2"; + private static final String aHandlerMethod3 = "doit3"; + + //XDialogEventHandler + public boolean callHandlerMethod( /*IN*/XDialog xDialog, /*IN*/Object EventObject, /*IN*/String MethodName ) { + if ( MethodName.equals( aHandlerMethod1 ) ) + { + showMessageBox( "DialogComponent", "callHandlerMethod() handled \"" + aHandlerMethod1 + "\"" ); + return true; + } + else if ( MethodName.equals( aHandlerMethod2 ) ) + { + showMessageBox( "DialogComponent", "callHandlerMethod() handled \"" + aHandlerMethod2 + "\"" ); + return true; + } + else if ( MethodName.equals( aHandlerMethod3 ) ) + { + showMessageBox( "DialogComponent", "callHandlerMethod() handled \"" + aHandlerMethod3 + "\"" ); + return true; + } + return false; + } + + public String[] getSupportedMethodNames() { + String[] retValue= new String[] { + aHandlerMethod1, + aHandlerMethod2, + aHandlerMethod3 }; + return retValue; + } + + + //XTypeProvider + public com.sun.star.uno.Type[] getTypes( ) { + Type[] retValue= new Type[4]; + retValue[0]= new Type( XServiceInfo.class); + retValue[1]= new Type( XTypeProvider.class); + retValue[2]= new Type( XTestDialogHandler.class); + retValue[3]= new Type( XDialogEventHandler.class); + return retValue; + } + //XTypeProvider + public byte[] getImplementationId( ) { + return new byte[0]; + } + + + + /** This method is a simple helper function to used in the + * static component initialisation functions as well as in + * getSupportedServiceNames. + */ + private static String[] getServiceNames() { + String[] sSupportedServiceNames = { __serviceName }; + return sSupportedServiceNames; + } + + //XServiceInfo + public String[] getSupportedServiceNames() { + return getServiceNames(); + } + + //XServiceInfo + public boolean supportsService( String sServiceName ) { + return sServiceName.equals( __serviceName ); + } + + //XServiceInfo + public String getImplementationName() { + return _DialogComponent.class.getName(); + } + + private void showMessageBox(String sTitle, String sMessage) { + if ( null != m_xFrame && null != m_xToolkit ) { + + // describe window properties. + WindowDescriptor aDescriptor = new WindowDescriptor(); + aDescriptor.Type = WindowClass.MODALTOP; + aDescriptor.WindowServiceName = "infobox"; + aDescriptor.ParentIndex = -1; + aDescriptor.Parent = UnoRuntime.queryInterface( + XWindowPeer.class, m_xFrame.getContainerWindow()); + aDescriptor.Bounds = new Rectangle(0,0,300,200); + aDescriptor.WindowAttributes = WindowAttribute.BORDER | + WindowAttribute.MOVEABLE | + WindowAttribute.CLOSEABLE; + + XWindowPeer xPeer = m_xToolkit.createWindow( aDescriptor ); + if ( null != xPeer ) { + XMessageBox xMsgBox = UnoRuntime.queryInterface( + XMessageBox.class, xPeer); + if ( null != xMsgBox ) + { + xMsgBox.setCaptionText( sTitle ); + xMsgBox.setMessageText( sMessage ); + xMsgBox.execute(); + } + } + } + } + } + + /** + * Gives a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XSingleComponentFactory for creating + * the component + * @param sImplName the name of the implementation for which a + * service is desired + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleComponentFactory __getComponentFactory(String sImplName) + { + XSingleComponentFactory xFactory = null; + + if ( sImplName.equals( _DialogComponent.class.getName() ) ) + xFactory = Factory.createComponentFactory(_DialogComponent.class, + _DialogComponent.getServiceNames()); + + return xFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.odt b/odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.odt new file mode 100644 index 000000000..bd6a9b40f Binary files /dev/null and b/odk/examples/DevelopersGuide/Components/dialogcomponent/DialogComponent.odt differ diff --git a/odk/examples/DevelopersGuide/Components/dialogcomponent/Makefile b/odk/examples/DevelopersGuide/Components/dialogcomponent/Makefile new file mode 100644 index 000000000..23d766868 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/dialogcomponent/Makefile @@ -0,0 +1,178 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java dialog component example of the SDK. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings + +# we use the sample directory name for separating this example +# from others in the output directory +SAMPLE_NAME=DialogComponentSample +SAMPLE_CLASS_OUT=$(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT=$(OUT_MISC)/$(SAMPLE_NAME) + +COMP_NAME=DialogComponent +COMP_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(COMP_NAME) +COMP_GEN_OUT=$(SAMPLE_GEN_OUT)/$(COMP_NAME) +COMP_RDB_NAME=$(COMP_NAME).uno.rdb +COMP_RDB=$(COMP_GEN_OUT)/$(COMP_RDB_NAME) +COMP_PACKAGE=$(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL=$(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME=$(COMP_NAME).uno.jar +COMP_JAR=$(SAMPLE_CLASS_OUT)/$(COMP_JAR_NAME) +COMP_JAR_MANIFEST=$(COMP_GEN_OUT)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(COMP_GEN_OUT)/META-INF/manifest.xml +COMP_REGISTERFLAG=$(COMP_GEN_OUT)$(PS)java_$(COMP_NAME)_register_component.flag +COMP_COMPONENTS=$(COMP_NAME).components + +IDLFILES = XTestDialogHandler.idl \ + TestDialogHandler.idl + +# normally the idl file should be stored in a directory tree fitting the module structure, +# for the example we know the module structure +PACKAGE = com/sun/star/test +#PACKAGE = org/openoffice + +COMP_JAVAFILES = DialogComponent.java +COMP_CLASSFILES = $(patsubst %.java,$(COMP_CLASS_OUT)/%.class,$(COMP_JAVAFILES)) + +GEN_CLASSFILES = $(patsubst %.idl,$(SAMPLE_CLASS_OUT)/$(PACKAGE)/%.class,$(IDLFILES)) +GEN_TYPELIST = $(subst /,.,$(patsubst %.idl,-T$(PACKAGE)/% ,$(IDLFILES))) +GEN_URDFILES = $(patsubst %.idl,$(SAMPLE_GEN_OUT)/%.urd,$(IDLFILES)) + +# the generated types are necessary for the component and the application jar +GEN_CLASSFILENAMES = $(subst $(SAMPLE_CLASS_OUT)/,,$(GEN_CLASSFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)\ + $(PATH_SEPARATOR)$(COMP_CLASS_OUT)\ + $(PATH_SEPARATOR)$(APP1_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : DialogComponentExample + +include $(SETTINGS)/stdtarget.mk + +$(COMP_GEN_OUT)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo UNO-Type-Path: $(basename $(notdir $*)).uno.jar> $@ + @echo RegistrationClassName: $(basename $*)>> $@ + +$(SAMPLE_GEN_OUT)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -C -I. -I$(IDL_DIR) -O$(SAMPLE_GEN_OUT) $< + +$(COMP_GEN_OUT)/%.rdb : $(GEN_URDFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(REGMERGE) $@ /UCR $(GEN_URDFILES) + +$(GEN_CLASSFILES) : $(COMP_RDB) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(JAVAMAKER) -nD $(GEN_TYPELIST) -O$(SAMPLE_CLASS_OUT) $(COMP_RDB) -X$(URE_TYPES) -X$(OFFICE_TYPES) + +# component as well as application are dependent from the generated types +# rule for component class files +$(COMP_CLASS_OUT)/%.class : %.java $(GEN_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(COMP_CLASS_OUT) $< + +# rule for component jar file +$(COMP_JAR) : $(COMP_JAR_MANIFEST) $(COMP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(COMP_CLASS_OUT) . + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) uvf $(@F) $(GEN_CLASSFILENAMES) + +# rule for component package manifest +$(COMP_GEN_OUT)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-typelibrary;type=RDB$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(SAMPLE_GEN_OUT)/,,$(@D))).uno.rdb$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_RDB) $(COMP_JAR) $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ $(COMP_COMPONENTS) + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u ../../../bin/$(@F) $(COMP_RDB_NAME) + cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_JAR_NAME) + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u ../../../bin/$(@F) META-INF/manifest.xml + +$(COMP_REGISTERFLAG) : $(COMP_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(COMP_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +DialogComponentExample : $(COMP_REGISTERFLAG) +# TODO: adapt + @echo -------------------------------------------------------------------------------- + @echo The PropTest was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo Load the "$(QM)PropertySet.odt$(QM)" document to see how this component works. You can + @echo use this component inside your office installation, see the example description. + @echo - + @echo $(MAKE) DialogComponent.odt.load + @echo -------------------------------------------------------------------------------- + +DialogComponent.odt.load : $(COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/DevelopersGuide/Components/dialogcomponent/TestDialogHandler.idl b/odk/examples/DevelopersGuide/Components/dialogcomponent/TestDialogHandler.idl new file mode 100644 index 000000000..1c5e8ad4c --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/dialogcomponent/TestDialogHandler.idl @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +#ifndef INCLUDED_COM_SUN_STAR_TEST_TESTDIALOGHANDLER_IDL +#define INCLUDED_COM_SUN_STAR_TEST_TESTDIALOGHANDLER_IDL + +#include + +module com { module sun { module star { module test { + service TestDialogHandler : XTestDialogHandler; +}; }; }; }; + +#endif + + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Components/dialogcomponent/XTestDialogHandler.idl b/odk/examples/DevelopersGuide/Components/dialogcomponent/XTestDialogHandler.idl new file mode 100644 index 000000000..b7c680f36 --- /dev/null +++ b/odk/examples/DevelopersGuide/Components/dialogcomponent/XTestDialogHandler.idl @@ -0,0 +1,56 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_COM_SUN_STAR_TEST_XTESTDIALOGHANDLER_IDL +#define INCLUDED_COM_SUN_STAR_TEST_XTESTDIALOGHANDLER_IDL + +#include +#include +#include +#include + +module com { module sun { module star { module test { + interface XTestDialogHandler { + string createDialog( [in] string DialogURL, [in] ::com::sun::star::frame::XModel xModel, + [in] ::com::sun::star::frame::XFrame xFrame ); + void copyText( [in] ::com::sun::star::awt::XDialog xDialog, [in] any aEventObject ); + void handleEvent(); + void handleEventWithArguments( [in] ::com::sun::star::awt::XDialog xDialog, [in] any aEventObject ); + }; +}; }; }; }; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Config/ConfigExamples.java b/odk/examples/DevelopersGuide/Config/ConfigExamples.java new file mode 100644 index 000000000..b74d24f7d --- /dev/null +++ b/odk/examples/DevelopersGuide/Config/ConfigExamples.java @@ -0,0 +1,1102 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// Import everything we use + +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.XMultiPropertySet; +import com.sun.star.beans.XHierarchicalPropertySet; +import com.sun.star.beans.XMultiHierarchicalPropertySet; +import com.sun.star.beans.XPropertyState; +import com.sun.star.beans.XMultiPropertyStates; + +import com.sun.star.configuration.XTemplateInstance; + +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNameReplace; +import com.sun.star.container.XNameContainer; +import com.sun.star.container.XNamed; +import com.sun.star.container.XChild; +import com.sun.star.container.XHierarchicalNameAccess; +import com.sun.star.container.XHierarchicalName; + +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XSingleServiceFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.EventObject; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.AnyConverter; + +import com.sun.star.util.XChangesBatch; +import com.sun.star.util.XChangesNotifier; +import com.sun.star.util.XChangesListener; +import com.sun.star.util.ChangesEvent; +// Config examples + +/* These examples show how to use the following features of the Config API: + + o Accessing data + o Updating data + o Updating properties in groups + o Adding and removing items in sets + o Resetting data to their defaults + + Each example is in a separate method call. +*/ +public class ConfigExamples +{ + // The ComponentContext interface of the remote component context + private final XComponentContext mxContext; + + // The MultiComponentFactory interface of the ServiceManager + private final XMultiComponentFactory mxServiceManager; + + // The MultiServiceFactory interface of the ConfigurationProvider + private XMultiServiceFactory mxProvider = null; + + public static void main( String args[] ) + { + try { + // get the remote office component context + com.sun.star.uno.XComponentContext xContext = + com.sun.star.comp.helper.Bootstrap.bootstrap(); + + if( xContext != null ) + System.out.println("Connected to a running office ..."); + else + System.out.println( "ERROR: Cannot connect - no remote component context available." ); + + // Create an instance of the class and call its run method + ConfigExamples aExample = new ConfigExamples(xContext); + aExample.run( ); + + // if you own the service manager dispose it here + // to ensure that the default provider is properly disposed and flushed + System.exit(0); + } + catch( Exception e ) + { + e.printStackTrace(); + System.exit(-1); + } + } + + /** Create a ConfigExamples instance supplying a service factory + */ + public ConfigExamples(XComponentContext xContext) + { + mxContext = xContext; + mxServiceManager = xContext.getServiceManager(); + } + + /** Run the examples with a default ConfigurationProvider + */ + public void run() + throws com.sun.star.uno.Exception + { + mxProvider = createProvider(); + + runExamples( ); + + // we are using the default ConfigurationProvider, so we must not dispose it + mxProvider = null; + } + + /** Run the examples with a given ConfigurationProvider + */ + public void runExamples( ) + { + if (checkProvider(mxProvider)) + { + System.out.println("\nStarting examples."); + + readDataExample(); + + browseDataExample(); + + updateGroupExample(); + + resetGroupExample(); + + updateSetExample(); + + System.out.println("\nAll Examples completed."); + } + else + System.out.println("ERROR: Cannot run examples without ConfigurationProvider."); + + } + + /** Do some simple checks, if there is a valid ConfigurationProvider + */ + public static boolean checkProvider(XMultiServiceFactory xProvider) + { + // check the provider we have + if (xProvider == null) + { + System.out.println("No provider available. Cannot access configuration data."); + return false; + + } + + try + { + // check the provider implementation + XServiceInfo xProviderServices = + UnoRuntime.queryInterface( XServiceInfo.class, xProvider ); + + if (xProviderServices == null || + !xProviderServices.supportsService("com.sun.star.configuration.ConfigurationProvider")) + { + System.out.println("WARNING: The provider is not a com.sun.star.configuration.ConfigurationProvider"); + } + + if (xProviderServices != null) + { + System.out.println("Using provider implementation: " + xProviderServices.getImplementationName()); + } + + return true; + } + catch (com.sun.star.uno.RuntimeException e) + { + System.err.println("ERROR: Failure while checking the provider services."); + e.printStackTrace(); + return false; + } + } + + /** Get the provider we have + */ + public XMultiServiceFactory getProvider( ) + { + return mxProvider; + } + + /** Create a default configuration provider + */ + public XMultiServiceFactory createProvider( ) + throws com.sun.star.uno.Exception + { + final String sProviderService = "com.sun.star.configuration.ConfigurationProvider"; + + // create the provider and return it as a XMultiServiceFactory + XMultiServiceFactory xProvider = UnoRuntime.queryInterface(XMultiServiceFactory.class, + mxServiceManager.createInstanceWithContext(sProviderService, + mxContext)); + + return xProvider; + } + + /** Create a specified read-only configuration view + */ + public Object createConfigurationView( String sPath ) + throws com.sun.star.uno.Exception + { + XMultiServiceFactory xProvider = getProvider(); + + // The service name: Need only read access: + final String sReadOnlyView = "com.sun.star.configuration.ConfigurationAccess"; + + // creation arguments: nodepath + com.sun.star.beans.PropertyValue aPathArgument = new com.sun.star.beans.PropertyValue(); + aPathArgument.Name = "nodepath"; + aPathArgument.Value = sPath; + + Object[] aArguments = new Object[1]; + aArguments[0] = aPathArgument; + + // create the view + Object xViewRoot = xProvider.createInstanceWithArguments(sReadOnlyView, aArguments); + + return xViewRoot; + } + + /** Create a specified updatable configuration view + */ + Object createUpdatableView( String sPath ) + throws com.sun.star.uno.Exception + { + XMultiServiceFactory xProvider = getProvider(); + + // The service name: Need update access: + final String cUpdatableView = "com.sun.star.configuration.ConfigurationUpdateAccess"; + + // creation arguments: nodepath + com.sun.star.beans.PropertyValue aPathArgument = new com.sun.star.beans.PropertyValue(); + aPathArgument.Name = "nodepath"; + aPathArgument.Value = sPath; + + Object[] aArguments = new Object[1]; + aArguments[0] = aPathArgument; + + // create the view + Object xViewRoot = xProvider.createInstanceWithArguments(cUpdatableView, aArguments); + + return xViewRoot; + } + + /** This method demonstrates read access to data + */ + protected void readDataExample () + { + try + { + System.out.println("\n--- starting example: read grid option settings --------------------"); + Object aData = readGridConfiguration( ); + System.out.println("Read grid options: " + aData); + + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + + /** This method demonstrates browsing access to data + */ + protected void browseDataExample () + { + try + { + System.out.println("\n--- starting example: browse filter configuration ------------------"); + printRegisteredFilters( ); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + + /** This method demonstrates update access to group data + */ + protected void updateGroupExample () + { + try + { + System.out.println("\n--- starting example: update group data --------------"); + editGridOptions( ); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + + /** This method demonstrates resetting data to its default state + */ + protected void resetGroupExample () + { + try + { + System.out.println("\n--- starting example: reset group data -----------------------------"); + Object aOldData = readGridConfiguration( ); + resetGridConfiguration( ); + Object aNewData = readGridConfiguration( ); + System.out.println("Before reset: user grid options: " + aOldData); + System.out.println("After reset: default grid options: " + aNewData); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + + /** This method demonstrates update access to set data + */ + protected void updateSetExample () + { + try + { + System.out.println("\n--- starting example: update set data ---------------"); + storeSampleDataSource( ); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + +// READ example + /// class to hold information about grid settings + private static class GridOptions + { + private boolean visible; + private int resolution_x; + private int resolution_y; + private int subdivision_x; + private int subdivision_y; + + @Override + public String toString() { + StringBuffer aBuffer = new StringBuffer(); + aBuffer.append("[ Grid is "); aBuffer.append(visible ? "VISIBLE" : "HIDDEN"); + aBuffer.append("; resolution = (" + resolution_x + "," + resolution_y + ")"); + aBuffer.append("; subdivision = (" + subdivision_x + "," + subdivision_y + ")"); + aBuffer.append(" ]"); + return aBuffer.toString(); + } + } + + /// This method reads information about grid settings + protected GridOptions readGridConfiguration() + throws com.sun.star.uno.Exception + { + // The path to the root element + final String cGridOptionsPath = "/org.openoffice.Office.Calc/Grid"; + + // create the view + Object xViewRoot = createConfigurationView(cGridOptionsPath); + + // the result structure + GridOptions options = new GridOptions(); + + // accessing a single nested value + XHierarchicalPropertySet xProperties = + UnoRuntime.queryInterface(XHierarchicalPropertySet.class, xViewRoot); + + Object aVisible = xProperties.getHierarchicalPropertyValue("Option/VisibleGrid"); + options.visible = ((Boolean) aVisible).booleanValue(); + + // accessing a nested object and its subproperties + Object xSubdivision = xProperties.getHierarchicalPropertyValue("Subdivision"); + + XMultiPropertySet xSubdivProperties = + UnoRuntime.queryInterface(XMultiPropertySet.class, xSubdivision); + + // variables for multi-element access + String[] aElementNames = new String[] { "XAxis", "YAxis" }; + + Object[] aElementValues = xSubdivProperties.getPropertyValues(aElementNames); + + options.subdivision_x = ((Integer) aElementValues[0]).intValue(); + options.subdivision_y = ((Integer) aElementValues[1]).intValue(); + + // accessing deeply nested subproperties + Object xResolution = xProperties.getHierarchicalPropertyValue("Resolution"); + + XMultiHierarchicalPropertySet xResolutionProperties = + UnoRuntime.queryInterface(XMultiHierarchicalPropertySet.class, xResolution); + + aElementNames[0] = "XAxis/Metric"; + aElementNames[1] = "YAxis/Metric"; + + aElementValues = xResolutionProperties.getHierarchicalPropertyValues(aElementNames); + + options.resolution_x = ((Integer) aElementValues[0]).intValue(); + options.resolution_y = ((Integer) aElementValues[1]).intValue(); + + // all options have been retrieved - clean up and return + // we are done with the view - dispose it + + UnoRuntime.queryInterface(XComponent.class, xViewRoot).dispose(); + + return options; + } + +// BROWSE example + /// Interface to process information when browsing the configuration tree + public interface IConfigurationProcessor + { + /// process a value item + void processValueElement( String sPath_, Object aValue_ ); + /// process a structural item + void processStructuralElement( String sPath_, XInterface xElement_); + } + + /// Internal method to recursively browse a structural element in preorder + public void browseElementRecursively( XInterface xElement, IConfigurationProcessor aProcessor ) + throws com.sun.star.uno.Exception + { + // First process this as an element (preorder traversal) + XHierarchicalName xElementPath = + UnoRuntime.queryInterface(XHierarchicalName.class, xElement); + + String sPath = xElementPath.getHierarchicalName(); + + aProcessor.processStructuralElement( sPath, xElement); + + // now process this as a container + XNameAccess xChildAccess = + UnoRuntime.queryInterface(XNameAccess.class, xElement); + + // get a list of child elements + String[] aElementNames = xChildAccess.getElementNames(); + + // and process them one by one + for(int i=0; i< aElementNames.length; ++i) + { + Object aChild = xChildAccess.getByName( aElementNames[i] ); + // is it a structural element (object) ... + if ( AnyConverter.isObject(aChild) && !AnyConverter.isArray(aChild) ) + { + // then get an interface + XInterface xChildElement = UnoRuntime.queryInterface(XInterface.class, aChild); + + // and continue processing child elements recursively + browseElementRecursively( xChildElement, aProcessor ); + } + // ... or is it a simple value + else + { + // Build the path to it from the path of + // the element and the name of the child + String sChildPath; + sChildPath = + xElementPath.composeHierarchicalName(aElementNames[i]); + + // and process the value + aProcessor.processValueElement( sChildPath, aChild ); + } + } + } + + /** Method to browse the part rooted at sRootPath + of the configuration that the Provider provides. + + All nodes will be processed by the IConfigurationProcessor passed. + */ + public void browseConfiguration( String sRootPath, IConfigurationProcessor aProcessor ) + throws com.sun.star.uno.Exception + { + // create the root element + XInterface xViewRoot = (XInterface)createConfigurationView( sRootPath ); + + // now do the processing + browseElementRecursively( xViewRoot, aProcessor ); + + // we are done with the view - dispose it + // This assumes that the processor + // does not keep a reference to the elements in processStructuralElement + + UnoRuntime.queryInterface(XComponent.class,xViewRoot).dispose(); + xViewRoot = null; + } + + /** Method to browse the filter configuration. + + Information about installed filters will be printed. + */ + public void printRegisteredFilters() + throws com.sun.star.uno.Exception + { + final String sFilterKey = "/org.openoffice.TypeDetection.Filter/Filters"; + + // browse the configuration, dumping filter information + browseConfiguration( sFilterKey, + new IConfigurationProcessor () { + /// prints Path and Value of properties + public void processValueElement( String sPath_, Object aValue_ ) { + if (AnyConverter.isArray(aValue_)) + { + final Object [] aArray = (Object [])aValue_; + + System.out.print("\tValue: " + sPath_ + " = { "); + for (int i=0; i $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +# rule for client/example application jar file +$(APP1_JAR) : $(APP1_JAR_MANIFEST) $(APP1_CLASS_OUT)/$(APP1_NAME).class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(APP1_CLASS_OUT) . + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(SAMPLE_NAME) : $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(SAMPLE_CLASS_OUT)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) diff --git a/odk/examples/DevelopersGuide/Database/CodeSamples.java b/odk/examples/DevelopersGuide/Database/CodeSamples.java new file mode 100644 index 000000000..094901feb --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/CodeSamples.java @@ -0,0 +1,322 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XSingleServiceFactory; +import com.sun.star.lang.XComponent; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNameContainer; +import com.sun.star.sdbc.*; +import com.sun.star.sdb.*; +import com.sun.star.sdbcx.*; +import com.sun.star.frame.*; + +public class CodeSamples +{ + public static XComponentContext xContext; + public static XMultiComponentFactory xMCF; + + public static void main(String argv[]) throws java.lang.Exception + { + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + xMCF = xContext.getServiceManager(); + } + catch(Exception e) { + System.err.println("ERROR: can't get a component context from a running office ..."); + e.printStackTrace(); + System.exit(1); + } + + try{ + createQuerydefinition( ); + printQueryColumnNames( ); + + XConnection con = openConnectionWithDriverManager(); + if ( con != null ) { + { + SalesMan sm = new SalesMan( con ); + + try { + sm.dropSalesManTable( ); // doesn't matter here + } + catch(com.sun.star.uno.Exception e) + { + } + sm.createSalesManTable( ); + sm.insertDataIntoSalesMan( ); + sm.updateSalesMan( ); + sm.retrieveSalesManData( ); + } + + { + Sales sm = new Sales( con ); + + try { + sm.dropSalesTable( ); // doesn't matter here + } + catch(com.sun.star.uno.Exception e) + { + } + sm.createSalesTable( ); + sm.insertDataIntoSales( ); + sm.updateSales( ); + sm.retrieveSalesData( ); + sm.displayColumnNames( ); + } + displayTableStructure( con ); + } + } + catch(Exception e) + { + System.err.println(e); + e.printStackTrace(); + } + System.exit(0); + } + + // check if the connection is not null and dispose it later on. + public static void checkConnection(XConnection con) + { + if(con != null) + { + System.out.println("Connection was created!"); + // now we dispose the connection to close it + XComponent xComponent = UnoRuntime.queryInterface(XComponent.class,con); + if(xComponent != null) + { + // connections must be disposed + xComponent.dispose(); + System.out.println("Connection disposed!"); + } + } + else + System.out.println("Connection could not be created!"); + } + + // uses the driver manager to create a new connection and dispose it. + public static XConnection openConnectionWithDriverManager() throws com.sun.star.uno.Exception + { + XConnection con = null; + // create the DriverManager + Object driverManager = + xMCF.createInstanceWithContext("com.sun.star.sdbc.DriverManager", + xContext); + // query for the interface + com.sun.star.sdbc.XDriverManager xDriverManager; + xDriverManager = UnoRuntime.queryInterface(XDriverManager.class,driverManager); + if(xDriverManager != null) + { + // first create the needed url + String url = "jdbc:mysql://localhost:3306/TestTables"; + // second create the necessary properties + com.sun.star.beans.PropertyValue [] props = new com.sun.star.beans.PropertyValue[] + { + new com.sun.star.beans.PropertyValue("user",0,"test1",com.sun.star.beans.PropertyState.DIRECT_VALUE), + new com.sun.star.beans.PropertyValue("password",0,"test1",com.sun.star.beans.PropertyState.DIRECT_VALUE), + new com.sun.star.beans.PropertyValue("JavaDriverClass",0,"org.gjt.mm.mysql.Driver",com.sun.star.beans.PropertyState.DIRECT_VALUE) + }; + // now create a connection to mysql + con = xDriverManager.getConnectionWithInfo(url,props); + } + return con; + } + + // uses the driver directly to create a new connection and dispose it. + public static XConnection openConnectionWithDriver() throws com.sun.star.uno.Exception + { + XConnection con = null; + // create the Driver with the implementation name + Object aDriver = + xMCF.createInstanceWithContext("org.openoffice.comp.drivers.MySQL.Driver", + xContext); + // query for the interface + com.sun.star.sdbc.XDriver xDriver; + xDriver = UnoRuntime.queryInterface(XDriver.class,aDriver); + if(xDriver != null) + { + // first create the needed url + String url = "jdbc:mysql://localhost:3306/TestTables"; + // second create the necessary properties + com.sun.star.beans.PropertyValue [] props = new com.sun.star.beans.PropertyValue[] + { + new com.sun.star.beans.PropertyValue("user",0,"test1",com.sun.star.beans.PropertyState.DIRECT_VALUE), + new com.sun.star.beans.PropertyValue("password",0,"test1",com.sun.star.beans.PropertyState.DIRECT_VALUE), + new com.sun.star.beans.PropertyValue("JavaDriverClass",0,"org.gjt.mm.mysql.Driver",com.sun.star.beans.PropertyState.DIRECT_VALUE) + }; + // now create a connection to mysql + con = xDriver.connect(url,props); + } + return con; + } + + // print all available datasources + public static void printDataSources() throws com.sun.star.uno.Exception + { + // create a DatabaseContext and print all DataSource names + XNameAccess xNameAccess = UnoRuntime.queryInterface( + XNameAccess.class, + xMCF.createInstanceWithContext("com.sun.star.sdb.DatabaseContext", + xContext)); + String aNames [] = xNameAccess.getElementNames(); + for(int i=0;i have a look at SDriver.?xx +2. Implement a class called connection -> have a look at SConnection.?xx +3. Have a look at the DatabaseMetaData -> see SDatabaseMetaData.cxx + The methods which should be implemented at least are + - getTableTypes + - getTables + - getTypeInfo + - getColumns + +4. You need a statement to show/access some data -> have a look at SStatement.cxx + -> especially executeQuery() + +5. The ResultSet: without you see nothing -> look at SResultSet.cxx +6. The ResultSetMetaData needed to get some information about what are waiting for us + -> look at SResultSetMetaData.cxx + +7. The prepared statement is the last class we have to implement now + -> you have to allow statements like "SELECT * FROM table WHERE id = ?" + +8. congratulations you have now implement your own driver :-) diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/Makefile b/odk/examples/DevelopersGuide/Database/DriverSkeleton/Makefile new file mode 100644 index 000000000..567ba1149 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/Makefile @@ -0,0 +1,156 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Database SDBC driver skeleton example of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=DatabaseSDBCDriverSkeleton +COMP_IMPL_NAME=$(COMP_NAME).uno.$(SHAREDLIB_EXT) +COMP_LIBRARY=$(SHAREDLIB_OUT)/$(COMP_IMPL_NAME) +OUT_COMP_INC=$(OUT_INC)/$(COMP_NAME) +OUT_COMP_MISC=$(OUT_MISC)/$(COMP_NAME) +OUT_COMP_SLO=$(OUT_SLO)/$(COMP_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_UNOPKG_MANIFEST = $(OUT_COMP_MISC)/$(COMP_NAME)/META-INF/manifest.xml +COMP_COMPONENTS = $(OUT_COMP_MISC)/$(COMP_NAME).components + +COMP_REGISTERFLAG = $(OUT_COMP_MISC)/devguide_$(COMP_NAME)_register_component.flag + +CXXFILES = SConnection.cxx \ + SDatabaseMetaData.cxx \ + propertyids.cxx \ + SDriver.cxx \ + SPreparedStatement.cxx \ + SResultSet.cxx \ + SResultSetMetaData.cxx \ + SServices.cxx \ + SStatement.cxx + +SLOFILES = $(patsubst %.cxx,$(OUT_COMP_SLO)/%.$(OBJ_EXT),$(CXXFILES)) + +# Targets +.PHONY: ALL +ALL : \ + DatabaseSDBCDriverSkeletonExample + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_SLO)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) $(STL_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +ifeq "$(OS)" "WIN" +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_MISC)) + $(LINK) $(COMP_LINK_FLAGS) /OUT:$@ \ + /MAP:$(OUT_COMP_MISC)/$(COMP_NAME).map $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) msvcprt.lib $(LIBO_SDK_LDFLAGS_STDLIBS) + $(LINK_MANIFEST) +else +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(COMP_LINK_FLAGS) $(LINK_LIBS) -o $@ $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS) $@ +endif +endif + +# rule for component package manifest +$(OUT_COMP_MISC)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components;platform=$(UNOPKG_PLATFORM)$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +$(COMP_COMPONENTS) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)components xmlns="$(QM)http://openoffice.org/2010/uno-components$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)component loader="$(QM)com.sun.star.loader.SharedLibrary$(QM)" uri="$(QM)$(UNOPKG_PLATFORM)/$(COMP_IMPL_NAME)$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)com.sun.star.comp.sdbc.SkeletonDriver$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)com.sun.star.sdbc.Driver$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/component$(CSEP) >> $@ + @echo $(OSEP)/components$(CSEP) >> $@ + +$(COMP_PACKAGE) : $(COMP_LIBRARY) $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(MKDIR) $(subst /,$(PS),$(@D)) && $(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_MISC)/$(UNOPKG_PLATFORM)) + $(COPY) $(subst /,$(PS),$<) $(subst /,$(PS),$(OUT_COMP_MISC)/$(UNOPKG_PLATFORM)) + cd $(subst /,$(PS),$(OUT_COMP_MISC)) && $(SDK_ZIP) ../../bin/$(@F) $(COMP_NAME).components + cd $(subst /,$(PS),$(OUT_COMP_MISC)) && $(SDK_ZIP) -u ../../bin/$(@F) $(UNOPKG_PLATFORM)/$( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +DatabaseSDBCDriverSkeletonExample : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The Database SDBC skeleton driver component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the example + @echo description and the howto of implementing a sdbc driver. + @echo -------------------------------------------------------------------------------- + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_MISC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_SLO)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_LIBRARY))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_COMPONENTS))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_REGISTERFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/OSubComponent.hxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/OSubComponent.hxx new file mode 100644 index 000000000..c915cdac0 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/OSubComponent.hxx @@ -0,0 +1,242 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_OSUBCOMPONENT_HXX +#define INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_OSUBCOMPONENT_HXX + +#include +#include +#include +#include +#include +#include +#include + +namespace cppu { + class IPropertyArrayHelper; +} + +namespace com +{ + namespace sun + { + namespace star + { + namespace lang + { + class XComponent; + } + } + } +} + +namespace connectivity +{ + + namespace skeleton + { + void release(oslInterlockedCount& _refCount, + ::cppu::OBroadcastHelper& rBHelper, + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xInterface, + ::com::sun::star::lang::XComponent* _pObject); + + void checkDisposed(sal_Bool _bThrow) throw ( ::com::sun::star::lang::DisposedException ); + + template class OSubComponent + { + protected: + // the parent must support the tunnel implementation + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > m_xParent; + SELF* m_pDerivedImplementation; + + public: + OSubComponent( + const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xParent, + SELF* _pDerivedImplementation) + :m_xParent(_xParent) + ,m_pDerivedImplementation(_pDerivedImplementation) + { + } + + protected: + void dispose_ChildImpl() + { + ::osl::MutexGuard aGuard( m_pDerivedImplementation->rBHelper.rMutex ); + m_xParent = NULL; + } + void release_ChildImpl() + { + release(m_pDerivedImplementation->m_refCount, + m_pDerivedImplementation->rBHelper, + m_xParent, + m_pDerivedImplementation); + + m_pDerivedImplementation->WEAK::release(); + } + }; + + template + class OPropertyArrayUsageHelper + { + protected: + static sal_Int32 s_nRefCount; + static ::cppu::IPropertyArrayHelper* s_pProps; + static ::osl::Mutex s_aMutex; + + public: + OPropertyArrayUsageHelper(); + virtual ~OPropertyArrayUsageHelper(); + + /** call this in the getInfoHelper method of your derived class. The method returns the array helper of the + class, which is created if necessary. + */ + ::cppu::IPropertyArrayHelper* getArrayHelper(); + + protected: + /** used to implement the creation of the array helper which is shared amongst all instances of the class. + This method needs to be implemented in derived classes. +
+ The method gets called with s_aMutex acquired. + @return a pointer to the newly created array helper. Must not be NULL. + */ + virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const = 0; + }; + + template + sal_Int32 OPropertyArrayUsageHelper< TYPE >::s_nRefCount = 0; + + template + ::cppu::IPropertyArrayHelper* OPropertyArrayUsageHelper< TYPE >::s_pProps = NULL; + + template + ::osl::Mutex OPropertyArrayUsageHelper< TYPE >::s_aMutex; + + template + OPropertyArrayUsageHelper::OPropertyArrayUsageHelper() + { + ::osl::MutexGuard aGuard(s_aMutex); + ++s_nRefCount; + } + + template + OPropertyArrayUsageHelper::~OPropertyArrayUsageHelper() + { + ::osl::MutexGuard aGuard(s_aMutex); + OSL_ENSURE(s_nRefCount > 0, "OPropertyArrayUsageHelper::~OPropertyArrayUsageHelper : suspicious call : have a refcount of 0 !"); + if (!--s_nRefCount) + { + delete s_pProps; + s_pProps = NULL; + } + } + + template + ::cppu::IPropertyArrayHelper* OPropertyArrayUsageHelper::getArrayHelper() + { + OSL_ENSURE(s_nRefCount, "OPropertyArrayUsageHelper::getArrayHelper : suspicious call : have a refcount of 0 !"); + if (!s_pProps) + { + ::osl::MutexGuard aGuard(s_aMutex); + if (!s_pProps) + { + s_pProps = createArrayHelper(); + OSL_ENSURE(s_pProps, "OPropertyArrayUsageHelper::getArrayHelper : createArrayHelper returned nonsense !"); + } + } + return s_pProps; + } + + class OBase_Mutex + { + public: + ::osl::Mutex m_aMutex; + }; + + namespace internal + { + template + void implCopySequence(const T* _pSource, T*& _pDest, sal_Int32 _nSourceLen) + { + for (sal_Int32 i=0; i<_nSourceLen; ++i, ++_pSource, ++_pDest) + *_pDest = *_pSource; + } + } + + /// concat two sequences + template + ::com::sun::star::uno::Sequence concatSequences(const ::com::sun::star::uno::Sequence& _rLeft, const ::com::sun::star::uno::Sequence& _rRight) + { + sal_Int32 nLeft(_rLeft.getLength()), nRight(_rRight.getLength()); + const T* pLeft = _rLeft.getConstArray(); + const T* pRight = _rRight.getConstArray(); + + sal_Int32 nReturnLen(nLeft + nRight); + ::com::sun::star::uno::Sequence aReturn(nReturnLen); + T* pReturn = aReturn.getArray(); + + internal::implCopySequence(pLeft, pReturn, nLeft); + internal::implCopySequence(pRight, pReturn, nRight); + + return aReturn; + } + + +#define DECLARE_SERVICE_INFO() \ + 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) \ + +#define IMPLEMENT_SERVICE_INFO(classname, implasciiname, serviceasciiname) \ + ::rtl::OUString SAL_CALL classname::getImplementationName( ) throw (::com::sun::star::uno::RuntimeException) \ + { \ + return ::rtl::OUString::createFromAscii(implasciiname); \ + } \ + ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL classname::getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException) \ + { \ + ::com::sun::star::uno::Sequence< ::rtl::OUString > aSupported(1); \ + aSupported[0] = ::rtl::OUString::createFromAscii(serviceasciiname); \ + return aSupported; \ + } \ + sal_Bool SAL_CALL classname::supportsService( const ::rtl::OUString& _rServiceName ) throw(::com::sun::star::uno::RuntimeException) \ + { \ + return cppu::supportsService(this, _rServiceName); \ + } + + } +} + +#endif // INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_OSUBCOMPONENT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/OTypeInfo.hxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/OTypeInfo.hxx new file mode 100644 index 000000000..610bb4062 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/OTypeInfo.hxx @@ -0,0 +1,100 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_OTYPEINFO_HXX +#define INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_OTYPEINFO_HXX + +#include +#include + +namespace connectivity +{ + struct OTypeInfo + { + ::rtl::OUString aTypeName; // Name of the type in the database + ::rtl::OUString aLiteralPrefix; // Prefix for literals + ::rtl::OUString aLiteralSuffix; // Suffix for literals + ::rtl::OUString aCreateParams; // Parameters to create + ::rtl::OUString aLocalTypeName; + + sal_Int32 nPrecision; // Length of the types + + sal_Int16 nMaximumScale; // Decimal places (precision) + sal_Int16 nMinimumScale; // Min decimal places (precision) + + sal_Int16 nType; // Database type + sal_Int16 nSearchType; // Can search for the type + sal_Int16 nNumPrecRadix; // indicating the radix, which is usually 2 or 10 + + sal_Bool bCurrency : 1, // Currency + bAutoIncrement : 1, // Is this field auto incrementing? + bNullable : 1, // Can this field assume a NULL value? + bCaseSensitive : 1, // Is this type case-sensitive? + bUnsigned : 1, // Is this type unsigned? + bEmpty_1 : 1, // for later use + bEmpty_2 : 1; + + OTypeInfo() + :bCurrency(sal_False) + ,bAutoIncrement(sal_False) + ,bNullable(sal_True) + ,bCaseSensitive(sal_False) + ,bUnsigned(sal_False) + ,nMaximumScale(0) + ,nMinimumScale(0) + ,nType( ::com::sun::star::sdbc::DataType::OTHER) + ,nPrecision(0) + ,nSearchType( ::com::sun::star::sdbc::ColumnSearch::FULL) + {} + + inline static void * SAL_CALL operator new( size_t nSize ) + { return ::rtl_allocateMemory( nSize ); } + inline static void * SAL_CALL operator new( size_t nSize,void* _pHint ) + { return _pHint; } + inline static void SAL_CALL operator delete( void * pMem ) + { ::rtl_freeMemory( pMem ); } + inline static void SAL_CALL operator delete( void * pMem,void* _pHint ) + { } + + sal_Bool operator == (const OTypeInfo& lh) const { return lh.nType == nType; } + sal_Bool operator != (const OTypeInfo& lh) const { return lh.nType != nType; } + + inline ::rtl::OUString getDBName() const { return aTypeName; } + }; +} + +#endif // INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_OTYPEINFO_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SConnection.cxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SConnection.cxx new file mode 100644 index 000000000..775fe6cef --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SConnection.cxx @@ -0,0 +1,401 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include "SConnection.hxx" + +#include "SDatabaseMetaData.hxx" +#include "SDriver.hxx" +#include "SStatement.hxx" +#include "SPreparedStatement.hxx" +#include +#include +#include +#include + +using namespace connectivity::skeleton; + + +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; + +OConnection::OConnection(SkeletonDriver* _pDriver) + : OSubComponent((::cppu::OWeakObject*)_pDriver, this), + OMetaConnection_BASE(m_aMutex), + m_pDriver(_pDriver), + m_bClosed(sal_False), + m_xMetaData(NULL), + m_bUseCatalog(sal_False), + m_bUseOldDateFormat(sal_False) +{ + m_pDriver->acquire(); +} + +OConnection::~OConnection() +{ + if(!isClosed()) + close(); + m_pDriver->release(); + m_pDriver = NULL; +} + +void SAL_CALL OConnection::release() throw() +{ + release_ChildImpl(); +} + + +void OConnection::construct(const ::rtl::OUString& url,const Sequence< PropertyValue >& info) throw(SQLException) +{ + osl_atomic_increment( &m_refCount ); + + // some example code how to get the information out of the sequence + + sal_Int32 nLen = url.indexOf(':'); + nLen = url.indexOf(':',nLen+1); + ::rtl::OUString aDSN("DSN="), aUID, aPWD, aSysDrvSettings; + aDSN += url.copy(nLen+1); + + const char* pUser = "user"; + const char* pTimeout = "Timeout"; + const char* pSilent = "Silent"; + const char* pPwd = "password"; + const char* pUseCatalog = "UseCatalog"; + const char* pSysDrv = "SystemDriverSettings"; + + sal_Int32 nTimeout = 20; + sal_Bool bSilent = sal_True; + const PropertyValue *pBegin = info.getConstArray(); + const PropertyValue *pEnd = pBegin + info.getLength(); + for(;pBegin != pEnd;++pBegin) + { + if(pBegin->Name.equalsAscii(pTimeout)) + pBegin->Value >>= nTimeout; + else if(pBegin->Name.equalsAscii(pSilent)) + pBegin->Value >>= bSilent; + else if(pBegin->Name.equalsAscii(pUser)) + { + pBegin->Value >>= aUID; + aDSN += ";UID=" + aUID; + } + else if(pBegin->Name.equalsAscii(pPwd)) + { + pBegin->Value >>= aPWD; + aDSN += ";PWD=" + aPWD; + } + else if(pBegin->Name.equalsAscii(pUseCatalog)) + { + pBegin->Value >>= m_bUseCatalog; + } + else if(pBegin->Name.equalsAscii(pSysDrv)) + { + pBegin->Value >>= aSysDrvSettings; + aDSN += ";"; + aDSN += aSysDrvSettings; + } + } + m_sUser = aUID; + + osl_atomic_decrement( &m_refCount ); +} +// XServiceInfo + +IMPLEMENT_SERVICE_INFO(OConnection, "com.sun.star.sdbc.drivers.skeleton.OConnection", "com.sun.star.sdbc.Connection") + + +Reference< XStatement > SAL_CALL OConnection::createStatement( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + // create a statement + // the statement can only be executed once + Reference< XStatement > xReturn = new OStatement(this); + m_aStatements.push_back(WeakReferenceHelper(xReturn)); + return xReturn; +} + +Reference< XPreparedStatement > SAL_CALL OConnection::prepareStatement( const ::rtl::OUString& _sSql ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + // the pre + if(m_aTypeInfo.empty()) + buildTypeInfo(); + + // create a statement + // the statement can only be executed more than once + Reference< XPreparedStatement > xReturn = new OPreparedStatement(this,m_aTypeInfo,_sSql); + m_aStatements.push_back(WeakReferenceHelper(xReturn)); + return xReturn; +} + +Reference< XPreparedStatement > SAL_CALL OConnection::prepareCall( const ::rtl::OUString& _sSql ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + // not implemented yet :-) a task to do + return NULL; +} + +::rtl::OUString SAL_CALL OConnection::nativeSQL( const ::rtl::OUString& _sSql ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + // when you need to transform SQL92 to you driver specific you can do it here + + return _sSql; +} + +void SAL_CALL OConnection::setAutoCommit( sal_Bool autoCommit ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + // here you have to set your commit mode please have a look at the jdbc documentation to get a clear explanation +} + +sal_Bool SAL_CALL OConnection::getAutoCommit( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + // you have to distinguish which if you are in autocommit mode or not + // at normal case true should be fine here + + return sal_True; +} + +void SAL_CALL OConnection::commit( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + // when your database does support transactions you should commit here +} + +void SAL_CALL OConnection::rollback( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + // same as commit but for the other case +} + +sal_Bool SAL_CALL OConnection::isClosed( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + + // just simple -> we are close when we are disposed that means someone called dispose(); (XComponent) + return OConnection_BASE::rBHelper.bDisposed; +} + +Reference< XDatabaseMetaData > SAL_CALL OConnection::getMetaData( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + // here we have to create the class with biggest interface + // The answer is 42 :-) + Reference< XDatabaseMetaData > xMetaData = m_xMetaData; + if(!xMetaData.is()) + { + xMetaData = new ODatabaseMetaData(this); // need the connection because it can return it + m_xMetaData = xMetaData; + } + + return xMetaData; +} + +void SAL_CALL OConnection::setReadOnly( sal_Bool readOnly ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + // set you connection to readonly +} + +sal_Bool SAL_CALL OConnection::isReadOnly( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + // return if your connection to readonly + return sal_False; +} + +void SAL_CALL OConnection::setCatalog( const ::rtl::OUString& catalog ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + // if your database doesn't work with catalogs you go to next method otherwise you know what to do +} + +::rtl::OUString SAL_CALL OConnection::getCatalog( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + // return your current catalog + return ::rtl::OUString(); +} + +void SAL_CALL OConnection::setTransactionIsolation( sal_Int32 level ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + /// set your isolation level + /// please have a look at @see com.sun.star.sdbc.TransactionIsolation +} + +sal_Int32 SAL_CALL OConnection::getTransactionIsolation( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + + // please have a look at @see com.sun.star.sdbc.TransactionIsolation + return TransactionIsolation::NONE; +} + +Reference< ::com::sun::star::container::XNameAccess > SAL_CALL OConnection::getTypeMap( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + // if your driver has special database types you can return it here + + return NULL; +} + +void SAL_CALL OConnection::setTypeMap( const Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(SQLException, RuntimeException) +{ + // the other way around +} + +// XCloseable +void SAL_CALL OConnection::close( ) throw(SQLException, RuntimeException) +{ + // we just dispose us + { + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OConnection_BASE::rBHelper.bDisposed); + + } + dispose(); +} + +// XWarningsSupplier +Any SAL_CALL OConnection::getWarnings( ) throw(SQLException, RuntimeException) +{ + // when you collected some warnings -> return it + return Any(); +} + +void SAL_CALL OConnection::clearWarnings( ) throw(SQLException, RuntimeException) +{ + // you should clear your collected warnings here +} + +void OConnection::buildTypeInfo() throw( SQLException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + + Reference< XResultSet> xRs = getMetaData ()->getTypeInfo (); + Reference< XRow> xRow(xRs,UNO_QUERY); + // Information for a single SQL type + + // Loop on the result set until we reach end of file + + while (xRs->next ()) + { + OTypeInfo aInfo; + aInfo.aTypeName = xRow->getString (1); + aInfo.nType = xRow->getShort (2); + aInfo.nPrecision = xRow->getInt (3); + aInfo.aLiteralPrefix = xRow->getString (4); + aInfo.aLiteralSuffix = xRow->getString (5); + aInfo.aCreateParams = xRow->getString (6); + aInfo.bNullable = xRow->getBoolean (7); + aInfo.bCaseSensitive = xRow->getBoolean (8); + aInfo.nSearchType = xRow->getShort (9); + aInfo.bUnsigned = xRow->getBoolean (10); + aInfo.bCurrency = xRow->getBoolean (11); + aInfo.bAutoIncrement = xRow->getBoolean (12); + aInfo.aLocalTypeName = xRow->getString (13); + aInfo.nMinimumScale = xRow->getShort (14); + aInfo.nMaximumScale = xRow->getShort (15); + aInfo.nNumPrecRadix = (sal_Int16)xRow->getInt(18); + + + // Now that we have the type info, save it + // in the Hashtable if we don't already have an + // entry for this SQL type. + + m_aTypeInfo.push_back(aInfo); + } + + // Close the result set/statement. + + Reference< XCloseable> xClose(xRs,UNO_QUERY); + xClose->close(); +} + +void OConnection::disposing() +{ + // we noticed that we should be destroyed in near future so we have to dispose our statements + ::osl::MutexGuard aGuard(m_aMutex); + + for (OWeakRefArray::iterator i = m_aStatements.begin(); m_aStatements.end() != i; ++i) + { + Reference< XComponent > xComp(i->get(), UNO_QUERY); + if (xComp.is()) + xComp->dispose(); + } + m_aStatements.clear(); + + m_bClosed = sal_True; + m_xMetaData = ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData>(); + + dispose_ChildImpl(); + OConnection_BASE::disposing(); +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SConnection.hxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SConnection.hxx new file mode 100644 index 000000000..dee2dc390 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SConnection.hxx @@ -0,0 +1,158 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SCONNECTION_HXX +#define INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SCONNECTION_HXX + +#include +#include +#include "OSubComponent.hxx" +#include "OTypeInfo.hxx" +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace connectivity +{ + namespace skeleton + { + + typedef ::cppu::WeakComponentImplHelper3< ::com::sun::star::sdbc::XConnection, + ::com::sun::star::sdbc::XWarningsSupplier, + ::com::sun::star::lang::XServiceInfo + > OMetaConnection_BASE; + + class OStatement_Base; + class SkeletonDriver; + class ODatabaseMetaData; + + typedef OMetaConnection_BASE OConnection_BASE; // implements basics and text encoding + typedef ::std::vector< ::connectivity::OTypeInfo> TTypeInfoVector; + typedef std::vector< ::com::sun::star::uno::WeakReferenceHelper > OWeakRefArray; + + class OConnection : public OBase_Mutex, + public OConnection_BASE, + public connectivity::skeleton::OSubComponent + { + friend class connectivity::skeleton::OSubComponent; + + protected: + + rtl_TextEncoding m_nTextEncoding; // the encoding which is used for all text conversions + + // Data attributes + + TTypeInfoVector m_aTypeInfo; // vector containing an entry + // for each row returned by + // DatabaseMetaData.getTypeInfo. + ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData > m_xMetaData; + + OWeakRefArray m_aStatements; // vector containing a list + // of all the Statement objects + // for this Connection + + ::com::sun::star::sdbc::SQLWarning m_aLastWarning; // Last SQLWarning generated by + // an operation + ::rtl::OUString m_aURL; // URL of connection + ::rtl::OUString m_sUser; // the user name + SkeletonDriver* m_pDriver; // Pointer to the owning + // driver object + + sal_Bool m_bClosed; + sal_Bool m_bUseCatalog; // should we use the catalog on filebased databases + sal_Bool m_bUseOldDateFormat; + + + void buildTypeInfo() throw( ::com::sun::star::sdbc::SQLException); + + public: + virtual void construct( const ::rtl::OUString& url,const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info) throw(::com::sun::star::sdbc::SQLException); + + OConnection(SkeletonDriver* _pDriver); + virtual ~OConnection(); + + void closeAllStatements () throw( ::com::sun::star::sdbc::SQLException); + + // OComponentHelper + virtual void SAL_CALL disposing(); + // XInterface + virtual void SAL_CALL release() throw(); + + // XServiceInfo + DECLARE_SERVICE_INFO(); + // XConnection + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL getAutoCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL commit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL rollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isClosed( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getCatalog( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XCloseable + virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XWarningsSupplier + virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + + + // should we use the catalog on filebased databases + inline sal_Bool isCatalogUsed() const { return m_bUseCatalog; } + inline ::rtl::OUString getUserName() const { return m_sUser; } + inline SkeletonDriver* getDriver() const { return m_pDriver;} + inline rtl_TextEncoding getTextEncoding() const { return m_nTextEncoding; } + }; + } +} + +#endif // INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SCONNECTION_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDatabaseMetaData.cxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDatabaseMetaData.cxx new file mode 100644 index 000000000..e51e3a05b --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDatabaseMetaData.cxx @@ -0,0 +1,887 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include "SDatabaseMetaData.hxx" +#include +#include +#include +#include + +using namespace connectivity::skeleton; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; + +ODatabaseMetaData::ODatabaseMetaData(OConnection* _pCon) +: m_pConnection(_pCon) +, m_bUseCatalog(sal_True) +{ + OSL_ENSURE(m_pConnection,"ODatabaseMetaData::ODatabaseMetaData: No connection set!"); + if(!m_pConnection->isCatalogUsed()) + { + osl_atomic_increment( &m_refCount ); + m_bUseCatalog = !(usesLocalFiles() || usesLocalFilePerTable()); + osl_atomic_decrement( &m_refCount ); + } +} + +ODatabaseMetaData::~ODatabaseMetaData() +{ +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getCatalogSeparator( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aVal; + if(m_bUseCatalog) + { // do some special here for you database + } + + return aVal; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxBinaryLiteralLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxRowSize( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxCatalogNameLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxCharLiteralLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnNameLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnsInIndex( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxCursorNameLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxConnections( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnsInTable( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxStatementLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxTableNameLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxTablesInSelect( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + + +sal_Bool SAL_CALL ODatabaseMetaData::doesMaxRowSizeIncludeBlobs( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesLowerCaseQuotedIdentifiers( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesLowerCaseIdentifiers( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesMixedCaseQuotedIdentifiers( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesMixedCaseIdentifiers( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesUpperCaseQuotedIdentifiers( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::storesUpperCaseIdentifiers( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsAlterTableWithAddColumn( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsAlterTableWithDropColumn( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxIndexLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsNonNullableColumns( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getCatalogTerm( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aVal; + if(m_bUseCatalog) + { + } + return aVal; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getIdentifierQuoteString( ) throw(SQLException, RuntimeException) +{ + // normally this is " + ::rtl::OUString aVal("\""); + return aVal; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getExtraNameCharacters( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aVal; + return aVal; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsDifferentTableCorrelationNames( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::isCatalogAtStart( ) throw(SQLException, RuntimeException) +{ + sal_Bool bValue = sal_False; + if(m_bUseCatalog) + { + } + return bValue; +} + +sal_Bool SAL_CALL ODatabaseMetaData::dataDefinitionIgnoredInTransactions( ) throw(SQLException, RuntimeException) +{ + return sal_True; +} + +sal_Bool SAL_CALL ODatabaseMetaData::dataDefinitionCausesTransactionCommit( ) throw(SQLException, RuntimeException) +{ + return sal_True; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsDataManipulationTransactionsOnly( ) throw(SQLException, RuntimeException) +{ + return sal_True; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsDataDefinitionAndDataManipulationTransactions( ) throw(SQLException, RuntimeException) +{ + return sal_True; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsPositionedDelete( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsPositionedUpdate( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOpenStatementsAcrossRollback( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOpenStatementsAcrossCommit( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOpenCursorsAcrossCommit( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOpenCursorsAcrossRollback( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsTransactionIsolationLevel( sal_Int32 level ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSchemasInDataManipulation( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsANSI92FullSQL( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsANSI92EntryLevelSQL( ) throw(SQLException, RuntimeException) +{ + return sal_True; // should be supported at least +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsIntegrityEnhancementFacility( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSchemasInIndexDefinitions( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSchemasInTableDefinitions( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCatalogsInTableDefinitions( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCatalogsInIndexDefinitions( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCatalogsInDataManipulation( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOuterJoins( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxStatements( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxProcedureNameLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxSchemaNameLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsTransactions( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::allProceduresAreCallable( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsStoredProcedures( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSelectForUpdate( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::allTablesAreSelectable( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::isReadOnly( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::usesLocalFiles( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::usesLocalFilePerTable( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsTypeConversion( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::nullPlusNonNullIsNull( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsColumnAliasing( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsTableCorrelationNames( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsConvert( sal_Int32 fromType, sal_Int32 toType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsExpressionsInOrderBy( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsGroupBy( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsGroupByBeyondSelect( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsGroupByUnrelated( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsMultipleTransactions( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsMultipleResultSets( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsLikeEscapeClause( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsOrderByUnrelated( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsUnion( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsUnionAll( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsMixedCaseIdentifiers( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsMixedCaseQuotedIdentifiers( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::nullsAreSortedAtEnd( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::nullsAreSortedAtStart( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::nullsAreSortedHigh( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::nullsAreSortedLow( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSchemasInProcedureCalls( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSchemasInPrivilegeDefinitions( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCatalogsInProcedureCalls( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCatalogsInPrivilegeDefinitions( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCorrelatedSubqueries( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSubqueriesInComparisons( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSubqueriesInExists( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSubqueriesInIns( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsSubqueriesInQuantifieds( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsANSI92IntermediateSQL( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getURL( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aValue("sdbc:skeleton:"); + return aValue; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getUserName( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aValue; + return aValue; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getDriverName( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aValue; + return aValue; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getDriverVersion() throw(SQLException, RuntimeException) +{ + ::rtl::OUString aValue; + return aValue; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getDatabaseProductVersion( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aValue; + return aValue; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getDatabaseProductName( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aValue; + return aValue; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getProcedureTerm( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aValue; + return aValue; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getSchemaTerm( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aValue; + return aValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getDriverMajorVersion( ) throw(RuntimeException) +{ + return 1; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getDefaultTransactionIsolation( ) throw(SQLException, RuntimeException) +{ + return TransactionIsolation::NONE; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getDriverMinorVersion( ) throw(RuntimeException) +{ + return 0; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getSQLKeywords( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aValue; + return aValue; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getSearchStringEscape( ) throw(SQLException, RuntimeException) +{ + ::rtl::OUString aValue; + return aValue; +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getStringFunctions( ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString(); +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getTimeDateFunctions( ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString(); +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getSystemFunctions( ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString(); +} + +::rtl::OUString SAL_CALL ODatabaseMetaData::getNumericFunctions( ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString(); +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsExtendedSQLGrammar( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsCoreSQLGrammar( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsMinimumSQLGrammar( ) throw(SQLException, RuntimeException) +{ + return sal_True; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsFullOuterJoins( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsLimitedOuterJoins( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnsInGroupBy( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnsInOrderBy( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxColumnsInSelect( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Int32 SAL_CALL ODatabaseMetaData::getMaxUserNameLength( ) throw(SQLException, RuntimeException) +{ + sal_Int32 nValue = 0; // 0 means no limit + return nValue; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsResultSetType( sal_Int32 setType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsResultSetConcurrency( sal_Int32 setType, sal_Int32 concurrency ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::ownUpdatesAreVisible( sal_Int32 setType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::ownDeletesAreVisible( sal_Int32 setType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::ownInsertsAreVisible( sal_Int32 setType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::othersUpdatesAreVisible( sal_Int32 setType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::othersDeletesAreVisible( sal_Int32 setType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::othersInsertsAreVisible( sal_Int32 setType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::updatesAreDetected( sal_Int32 setType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::deletesAreDetected( sal_Int32 setType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::insertsAreDetected( sal_Int32 setType ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Bool SAL_CALL ODatabaseMetaData::supportsBatchUpdates( ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +Reference< XConnection > SAL_CALL ODatabaseMetaData::getConnection( ) throw(SQLException, RuntimeException) +{ + return (Reference< XConnection >)m_pConnection;//new OConnection(m_aConnectionHandle); +} + +// here follow all methods which return a resultset +// the first methods is an example implementation how to use this resultset +// of course you could implement it on your and you should do this because +// the general way is more memory expensive + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getTableTypes( ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getTypeInfo( ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getCatalogs( ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getSchemas( ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getColumnPrivileges( + const Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table, + const ::rtl::OUString& columnNamePattern ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getColumns( + const Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern, + const ::rtl::OUString& columnNamePattern ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getTables( + const Any& catalog, const ::rtl::OUString& schemaPattern, + const ::rtl::OUString& tableNamePattern, const Sequence< ::rtl::OUString >& types ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getProcedureColumns( + const Any& catalog, const ::rtl::OUString& schemaPattern, + const ::rtl::OUString& procedureNamePattern, const ::rtl::OUString& columnNamePattern ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getProcedures( + const Any& catalog, const ::rtl::OUString& schemaPattern, + const ::rtl::OUString& procedureNamePattern ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getVersionColumns( + const Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getExportedKeys( + const Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getImportedKeys( + const Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getPrimaryKeys( + const Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getIndexInfo( + const Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table, + sal_Bool unique, sal_Bool approximate ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getBestRowIdentifier( + const Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table, sal_Int32 scope, + sal_Bool nullable ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getTablePrivileges( + const Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getCrossReference( + const Any& primaryCatalog, const ::rtl::OUString& primarySchema, + const ::rtl::OUString& primaryTable, const Any& foreignCatalog, + const ::rtl::OUString& foreignSchema, const ::rtl::OUString& foreignTable ) throw(SQLException, RuntimeException) +{ + return NULL; +} + +Reference< XResultSet > SAL_CALL ODatabaseMetaData::getUDTs( const Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& typeNamePattern, const Sequence< sal_Int32 >& types ) throw(SQLException, RuntimeException) +{ + OSL_FAIL("Not implemented yet!"); + throw SQLException(); + return NULL; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDatabaseMetaData.hxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDatabaseMetaData.hxx new file mode 100644 index 000000000..66e6d4bc7 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDatabaseMetaData.hxx @@ -0,0 +1,218 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SDATABASEMETADATA_HXX +#define INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SDATABASEMETADATA_HXX + +#include "SConnection.hxx" +#include +#include + +namespace connectivity +{ + namespace skeleton + { + + typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XDatabaseMetaData> ODatabaseMetaData_BASE; + + class ODatabaseMetaData : public ODatabaseMetaData_BASE + { + OConnection* m_pConnection; + sal_Bool m_bUseCatalog; + public: + + inline OConnection* getOwnConnection() const { return m_pConnection; } + + ODatabaseMetaData(OConnection* _pCon); + virtual ~ODatabaseMetaData(); + + // as I mentioned before this interface is really BIG + // XDatabaseMetaData + virtual sal_Bool SAL_CALL allProceduresAreCallable( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL allTablesAreSelectable( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getURL( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getUserName( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isReadOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL nullsAreSortedHigh( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL nullsAreSortedLow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL nullsAreSortedAtStart( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL nullsAreSortedAtEnd( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getDatabaseProductName( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getDatabaseProductVersion( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getDriverName( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getDriverVersion( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getDriverMajorVersion( ) throw(::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getDriverMinorVersion( ) throw(::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL usesLocalFiles( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL usesLocalFilePerTable( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsMixedCaseIdentifiers( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL storesUpperCaseIdentifiers( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL storesLowerCaseIdentifiers( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL storesMixedCaseIdentifiers( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsMixedCaseQuotedIdentifiers( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL storesUpperCaseQuotedIdentifiers( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL storesLowerCaseQuotedIdentifiers( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL storesMixedCaseQuotedIdentifiers( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getIdentifierQuoteString( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getSQLKeywords( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getNumericFunctions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getStringFunctions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getSystemFunctions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getTimeDateFunctions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getSearchStringEscape( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getExtraNameCharacters( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsAlterTableWithAddColumn( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsAlterTableWithDropColumn( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsColumnAliasing( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL nullPlusNonNullIsNull( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsTypeConversion( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsConvert( sal_Int32 fromType, sal_Int32 toType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsTableCorrelationNames( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsDifferentTableCorrelationNames( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsExpressionsInOrderBy( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsOrderByUnrelated( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsGroupBy( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsGroupByUnrelated( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsGroupByBeyondSelect( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsLikeEscapeClause( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsMultipleResultSets( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsMultipleTransactions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsNonNullableColumns( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsMinimumSQLGrammar( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsCoreSQLGrammar( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsExtendedSQLGrammar( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsANSI92EntryLevelSQL( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsANSI92IntermediateSQL( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsANSI92FullSQL( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsIntegrityEnhancementFacility( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsOuterJoins( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsFullOuterJoins( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsLimitedOuterJoins( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getSchemaTerm( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getProcedureTerm( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getCatalogTerm( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isCatalogAtStart( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getCatalogSeparator( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsSchemasInDataManipulation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsSchemasInProcedureCalls( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsSchemasInTableDefinitions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsSchemasInIndexDefinitions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsSchemasInPrivilegeDefinitions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsCatalogsInDataManipulation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsCatalogsInProcedureCalls( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsCatalogsInTableDefinitions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsCatalogsInIndexDefinitions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsCatalogsInPrivilegeDefinitions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsPositionedDelete( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsPositionedUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsSelectForUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsStoredProcedures( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsSubqueriesInComparisons( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsSubqueriesInExists( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsSubqueriesInIns( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsSubqueriesInQuantifieds( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsCorrelatedSubqueries( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsUnion( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsUnionAll( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsOpenCursorsAcrossCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsOpenCursorsAcrossRollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsOpenStatementsAcrossCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsOpenStatementsAcrossRollback( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxBinaryLiteralLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxCharLiteralLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxColumnNameLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxColumnsInGroupBy( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxColumnsInIndex( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxColumnsInOrderBy( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxColumnsInSelect( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxColumnsInTable( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxConnections( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxCursorNameLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxIndexLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxSchemaNameLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxProcedureNameLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxCatalogNameLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxRowSize( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL doesMaxRowSizeIncludeBlobs( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxStatementLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxStatements( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxTableNameLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxTablesInSelect( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMaxUserNameLength( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getDefaultTransactionIsolation( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsTransactions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsTransactionIsolationLevel( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsDataDefinitionAndDataManipulationTransactions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsDataManipulationTransactionsOnly( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL dataDefinitionCausesTransactionCommit( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL dataDefinitionIgnoredInTransactions( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getProcedures( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& procedureNamePattern ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getProcedureColumns( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& procedureNamePattern, const ::rtl::OUString& columnNamePattern ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getTables( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& types ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getSchemas( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getCatalogs( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getTableTypes( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getColumns( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern, const ::rtl::OUString& columnNamePattern ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getColumnPrivileges( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table, const ::rtl::OUString& columnNamePattern ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getTablePrivileges( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& tableNamePattern ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getBestRowIdentifier( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table, sal_Int32 scope, sal_Bool nullable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getVersionColumns( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getPrimaryKeys( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getImportedKeys( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getExportedKeys( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getCrossReference( const ::com::sun::star::uno::Any& primaryCatalog, const ::rtl::OUString& primarySchema, const ::rtl::OUString& primaryTable, const ::com::sun::star::uno::Any& foreignCatalog, const ::rtl::OUString& foreignSchema, const ::rtl::OUString& foreignTable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getTypeInfo( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getIndexInfo( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schema, const ::rtl::OUString& table, sal_Bool unique, sal_Bool approximate ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsResultSetType( sal_Int32 setType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsResultSetConcurrency( sal_Int32 setType, sal_Int32 concurrency ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL ownUpdatesAreVisible( sal_Int32 setType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL ownDeletesAreVisible( sal_Int32 setType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL ownInsertsAreVisible( sal_Int32 setType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL othersUpdatesAreVisible( sal_Int32 setType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL othersDeletesAreVisible( sal_Int32 setType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL othersInsertsAreVisible( sal_Int32 setType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL updatesAreDetected( sal_Int32 setType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL deletesAreDetected( sal_Int32 setType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL insertsAreDetected( sal_Int32 setType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsBatchUpdates( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getUDTs( const ::com::sun::star::uno::Any& catalog, const ::rtl::OUString& schemaPattern, const ::rtl::OUString& typeNamePattern, const ::com::sun::star::uno::Sequence< sal_Int32 >& types ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + }; + } +} + +#endif // INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SDATABASEMETADATA_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDriver.cxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDriver.cxx new file mode 100644 index 000000000..1c3abbadf --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDriver.cxx @@ -0,0 +1,201 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include "SDriver.hxx" +#include "SConnection.hxx" + +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; +using namespace connectivity::skeleton; + +namespace connectivity +{ + namespace skeleton + { + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL SkeletonDriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception ) + { + return *(new SkeletonDriver()); + } + } +} + +SkeletonDriver::SkeletonDriver() + : ODriver_BASE(m_aMutex) +{ +} + +void SkeletonDriver::disposing() +{ + ::osl::MutexGuard aGuard(m_aMutex); + + // when driver will be destroyed so all our connections have to be destroyed as well + for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i) + { + Reference< XComponent > xComp(i->get(), UNO_QUERY); + if (xComp.is()) + xComp->dispose(); + } + m_xConnections.clear(); + + ODriver_BASE::disposing(); +} + +// static ServiceInfo + +rtl::OUString SkeletonDriver::getImplementationName_Static( ) throw(RuntimeException) +{ + return rtl::OUString("com.sun.star.comp.sdbc.SkeletonDriver"); + // this name is referenced in the configuration and in the skeleton.xml + // Please take care when changing it. +} + +Sequence< ::rtl::OUString > SkeletonDriver::getSupportedServiceNames_Static( ) throw (RuntimeException) +{ + /// which service is supported + /// for more information @see com.sun.star.sdbc.Driver + Sequence< ::rtl::OUString > aSNS( 1 ); + aSNS[0] = ::rtl::OUString("com.sun.star.sdbc.Driver"); + return aSNS; +} + +::rtl::OUString SAL_CALL SkeletonDriver::getImplementationName( ) throw(RuntimeException) +{ + return getImplementationName_Static(); +} + +sal_Bool SAL_CALL SkeletonDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException) +{ + return cppu::supportsService(this, _rServiceName); +} + +Sequence< ::rtl::OUString > SAL_CALL SkeletonDriver::getSupportedServiceNames( ) throw(RuntimeException) +{ + return getSupportedServiceNames_Static(); +} + +Reference< XConnection > SAL_CALL SkeletonDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) +{ + // create a new connection with the given properties and append it to our vector + OConnection* pCon = new OConnection(this); + Reference< XConnection > xCon = pCon; // important here because otherwise the connection could be deleted inside (refcount goes -> 0) + pCon->construct(url,info); // late constructor call which can throw exception and allows a correct dtor call when so + m_xConnections.push_back(WeakReferenceHelper(*pCon)); + + return xCon; +} + +sal_Bool SAL_CALL SkeletonDriver::acceptsURL( const ::rtl::OUString& url ) + throw(SQLException, RuntimeException) +{ + // here we have to look if we support this url format + // change the URL format to your needs, but please aware that the first on who accepts the URl wins. + return url.startsWith("sdbc:skeleton:"); +} + +Sequence< DriverPropertyInfo > SAL_CALL SkeletonDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException) +{ + // if you have something special to say, return it here :-) + return Sequence< DriverPropertyInfo >(); +} + +sal_Int32 SAL_CALL SkeletonDriver::getMajorVersion( ) throw(RuntimeException) +{ + return 0; // depends on you +} + +sal_Int32 SAL_CALL SkeletonDriver::getMinorVersion( ) throw(RuntimeException) +{ + return 1; // depends on you +} + + +namespace connectivity +{ + namespace skeleton + { + + +void release(oslInterlockedCount& _refCount, + ::cppu::OBroadcastHelper& rBHelper, + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _xInterface, + ::com::sun::star::lang::XComponent* _pObject) +{ + if (osl_atomic_decrement( &_refCount ) == 0) + { + osl_atomic_increment( &_refCount ); + + if (!rBHelper.bDisposed && !rBHelper.bInDispose) + { + // remember the parent + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xParent; + { + ::osl::MutexGuard aGuard( rBHelper.rMutex ); + xParent = _xInterface; + _xInterface = NULL; + } + + // First dispose + _pObject->dispose(); + + // only the alive ref holds the object + OSL_ASSERT( _refCount == 1 ); + + // release the parent in the ~ + if (xParent.is()) + { + ::osl::MutexGuard aGuard( rBHelper.rMutex ); + _xInterface = xParent; + } + } + } + else + osl_atomic_increment( &_refCount ); +} + +void checkDisposed(sal_Bool _bThrow) throw ( DisposedException ) +{ + if (_bThrow) + throw DisposedException(); + +} + + } +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDriver.hxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDriver.hxx new file mode 100644 index 000000000..59abf9dd5 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SDriver.hxx @@ -0,0 +1,92 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SDRIVER_HXX +#define INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SDRIVER_HXX + +#include +#include +#include +#include "SConnection.hxx" + +namespace com { namespace sun { namespace star { namespace lang { + class XMultiServiceFactory; +} } } } + +namespace connectivity +{ + namespace skeleton + { + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL SkeletonDriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception ); + + typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::sdbc::XDriver, + ::com::sun::star::lang::XServiceInfo > ODriver_BASE; + + class SkeletonDriver : public ODriver_BASE + { + protected: + ::osl::Mutex m_aMutex; // mutex is need to control member access + OWeakRefArray m_xConnections; // vector containing a list + // of all the Connection objects + // for this Driver + public: + + SkeletonDriver(); + + // OComponentHelper + virtual void SAL_CALL disposing(); + // XInterface + static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException); + static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static( ) throw (::com::sun::star::uno::RuntimeException); + + // 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); + + // XDriver + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMajorVersion( ) throw(::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getMinorVersion( ) throw(::com::sun::star::uno::RuntimeException); + }; + } + +} + +#endif // INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SDRIVER_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SPreparedStatement.cxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SPreparedStatement.cxx new file mode 100644 index 000000000..3034c95ba --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SPreparedStatement.cxx @@ -0,0 +1,385 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include "SPreparedStatement.hxx" +#include +#include "SResultSetMetaData.hxx" +#include +#include +#include "propertyids.hxx" + +using namespace connectivity::skeleton; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; +using namespace com::sun::star::container; +using namespace com::sun::star::io; +using namespace com::sun::star::util; + +IMPLEMENT_SERVICE_INFO(OPreparedStatement,"com.sun.star.sdbcx.skeleton.PreparedStatement","com.sun.star.sdbc.PreparedStatement"); + + +OPreparedStatement::OPreparedStatement( OConnection* _pConnection,const TTypeInfoVector& _TypeInfo,const ::rtl::OUString& sql) + :OStatement_BASE2(_pConnection) + ,m_aTypeInfo(_TypeInfo) + ,m_bPrepared(sal_False) + ,m_sSqlStatement(sql) + ,m_nNumParams(0) +{ +} + +OPreparedStatement::~OPreparedStatement() +{ +} + +void SAL_CALL OPreparedStatement::acquire() throw() +{ + OStatement_BASE2::acquire(); +} + +void SAL_CALL OPreparedStatement::release() throw() +{ + OStatement_BASE2::release(); +} + +Any SAL_CALL OPreparedStatement::queryInterface( const Type & rType ) throw(RuntimeException) +{ + Any aRet = OStatement_BASE2::queryInterface(rType); + if(!aRet.hasValue()) + aRet = OPreparedStatement_BASE::queryInterface(rType); + return aRet; +} + +::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL OPreparedStatement::getTypes( ) throw(::com::sun::star::uno::RuntimeException) +{ + return concatSequences(OPreparedStatement_BASE::getTypes(),OStatement_BASE2::getTypes()); +} + + +Reference< XResultSetMetaData > SAL_CALL OPreparedStatement::getMetaData( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + if(!m_xMetaData.is()) + m_xMetaData = new OResultSetMetaData(getOwnConnection()); + return m_xMetaData; +} + + +void SAL_CALL OPreparedStatement::close( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + // Reset last warning message + + try { + clearWarnings (); + OStatement_BASE2::close(); + } + catch (SQLException &) { + // If we get an error, ignore + } + + // Remove this Statement object from the Connection object's + // list +} + + +sal_Bool SAL_CALL OPreparedStatement::execute( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + // same as in statement with the difference that this statement also can contain parameter + return sal_False; +} + + +sal_Int32 SAL_CALL OPreparedStatement::executeUpdate( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + // same as in statement with the difference that this statement also can contain parameter + return 0; +} + + +void SAL_CALL OPreparedStatement::setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); +} + + +Reference< XConnection > SAL_CALL OPreparedStatement::getConnection( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + return (Reference< XConnection >)m_pConnection; +} + + +Reference< XResultSet > SAL_CALL OPreparedStatement::executeQuery( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + Reference< XResultSet > rs = NULL; + + + return rs; +} + + +void SAL_CALL OPreparedStatement::setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OPreparedStatement::setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + +} + + +void SAL_CALL OPreparedStatement::setDate( sal_Int32 parameterIndex, const Date& aData ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setTime( sal_Int32 parameterIndex, const css::util::Time& aVal ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setTimestamp( sal_Int32 parameterIndex, const DateTime& aVal ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setDouble( sal_Int32 parameterIndex, double x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setFloat( sal_Int32 parameterIndex, float x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setLong( sal_Int32 parameterIndex, sal_Int64 aVal ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setClob( sal_Int32 parameterIndex, const Reference< XClob >& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setBlob( sal_Int32 parameterIndex, const Reference< XBlob >& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setArray( sal_Int32 parameterIndex, const Reference< XArray >& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setRef( sal_Int32 parameterIndex, const Reference< XRef >& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setObjectWithInfo( sal_Int32 parameterIndex, const Any& x, sal_Int32 sqlType, sal_Int32 scale ) throw(SQLException, RuntimeException) +{ + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + +} + + +void SAL_CALL OPreparedStatement::setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setObject( sal_Int32 parameterIndex, const Any& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setBytes( sal_Int32 parameterIndex, const Sequence< sal_Int8 >& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setCharacterStream( sal_Int32 parameterIndex, const Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::setBinaryStream( sal_Int32 parameterIndex, const Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OPreparedStatement::clearParameters( ) throw(SQLException, RuntimeException) +{ +} + +void SAL_CALL OPreparedStatement::clearBatch( ) throw(SQLException, RuntimeException) +{ +} + + +void SAL_CALL OPreparedStatement::addBatch( ) throw(SQLException, RuntimeException) +{ +} + + +Sequence< sal_Int32 > SAL_CALL OPreparedStatement::executeBatch( ) throw(SQLException, RuntimeException) +{ + return Sequence< sal_Int32 > (); +} + +void OPreparedStatement::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception) +{ + switch(nHandle) + { + case PROPERTY_ID_RESULTSETCONCURRENCY: + break; + case PROPERTY_ID_RESULTSETTYPE: + break; + case PROPERTY_ID_FETCHDIRECTION: + break; + case PROPERTY_ID_USEBOOKMARKS: + break; + default: + OStatement_Base::setFastPropertyValue_NoBroadcast(nHandle,rValue); + } +} + +void OPreparedStatement::checkParameterIndex(sal_Int32 _parameterIndex) +{ + if( !_parameterIndex || _parameterIndex > m_nNumParams) + throw SQLException(); +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SPreparedStatement.hxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SPreparedStatement.hxx new file mode 100644 index 000000000..ca4df6e35 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SPreparedStatement.hxx @@ -0,0 +1,151 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SPREPAREDSTATEMENT_HXX +#define INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SPREPAREDSTATEMENT_HXX + +#include "SStatement.hxx" +#include +#include +#include +#include +#include + +namespace connectivity +{ + namespace skeleton + { + + class OBoundParam; + typedef ::cppu::ImplHelper5< ::com::sun::star::sdbc::XPreparedStatement, + ::com::sun::star::sdbc::XParameters, + ::com::sun::star::sdbc::XPreparedBatchExecution, + ::com::sun::star::sdbc::XResultSetMetaDataSupplier, + ::com::sun::star::lang::XServiceInfo> OPreparedStatement_BASE; + + class OPreparedStatement : public OStatement_BASE2, + public OPreparedStatement_BASE + { + protected: + struct Parameter + { + ::com::sun::star::uno::Any aValue; + sal_Int32 nDataType; + + Parameter(const ::com::sun::star::uno::Any& rValue, + sal_Int32 rDataType) : aValue(rValue),nDataType(rDataType) + { + } + + }; + + ::std::vector< Parameter> m_aParameters; + + // Data attributes + + TTypeInfoVector m_aTypeInfo; // Hashtable containing an entry + // for each row returned by + // DatabaseMetaData.getTypeInfo. + + sal_Int32 m_nNumParams; // Number of parameter markers + // for the prepared statement + + ::rtl::OUString m_sSqlStatement; + ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > m_xMetaData; + sal_Bool m_bPrepared; + + void checkParameterIndex(sal_Int32 _parameterIndex); + + protected: + virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, + const ::com::sun::star::uno::Any& rValue) + throw (::com::sun::star::uno::Exception); + virtual ~OPreparedStatement(); + public: + DECLARE_SERVICE_INFO(); + // a constructor, which is required for returning objects: + OPreparedStatement( OConnection* _pConnection,const TTypeInfoVector& _TypeInfo,const ::rtl::OUString& sql); + + //XInterface + virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL acquire() throw(); + virtual void SAL_CALL release() throw(); + //XTypeProvider + virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); + + // XPreparedStatement + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL executeUpdate( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL execute( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XParameters + virtual void SAL_CALL setNull( sal_Int32 parameterIndex, sal_Int32 sqlType ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setObjectNull( sal_Int32 parameterIndex, sal_Int32 sqlType, const ::rtl::OUString& typeName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setBoolean( sal_Int32 parameterIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setByte( sal_Int32 parameterIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setShort( sal_Int32 parameterIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setInt( sal_Int32 parameterIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setLong( sal_Int32 parameterIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setFloat( sal_Int32 parameterIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setDouble( sal_Int32 parameterIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setString( sal_Int32 parameterIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setBytes( sal_Int32 parameterIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setDate( sal_Int32 parameterIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setTime( sal_Int32 parameterIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setTimestamp( sal_Int32 parameterIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setBinaryStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setCharacterStream( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setObject( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setObjectWithInfo( sal_Int32 parameterIndex, const ::com::sun::star::uno::Any& x, sal_Int32 targetSqlType, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setRef( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setBlob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setClob( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL setArray( sal_Int32 parameterIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL clearParameters( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XPreparedBatchExecution + virtual void SAL_CALL addBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL clearBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL executeBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XCloseable + virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XResultSetMetaDataSupplier + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + }; + } +} + +#endif // INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SPREPAREDSTATEMENT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSet.cxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSet.cxx new file mode 100644 index 000000000..9cb6a9252 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSet.cxx @@ -0,0 +1,869 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include "SResultSet.hxx" +#include "SResultSetMetaData.hxx" +#include +#include +#include +#include +#include +#include +#include "propertyids.hxx" + +using namespace connectivity::skeleton; +using namespace cppu; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; +using namespace com::sun::star::sdbcx; +using namespace com::sun::star::container; +using namespace com::sun::star::io; +using namespace com::sun::star::util; + +// IMPLEMENT_SERVICE_INFO(OResultSet,"com.sun.star.sdbcx.OResultSet","com.sun.star.sdbc.ResultSet"); +::rtl::OUString SAL_CALL OResultSet::getImplementationName( ) throw ( RuntimeException) +{ + return ::rtl::OUString("com.sun.star.sdbcx.skeleton.ResultSet"); +} + + Sequence< ::rtl::OUString > SAL_CALL OResultSet::getSupportedServiceNames( ) throw( RuntimeException) +{ + Sequence< ::rtl::OUString > aSupported(2); + aSupported[0] = ::rtl::OUString("com.sun.star.sdbc.ResultSet"); + aSupported[1] = ::rtl::OUString("com.sun.star.sdbcx.ResultSet"); + return aSupported; +} + +sal_Bool SAL_CALL OResultSet::supportsService( const ::rtl::OUString& _rServiceName ) throw( RuntimeException) +{ + return cppu::supportsService(this, _rServiceName); +} + +OResultSet::OResultSet(OStatement_Base* pStmt) + : OResultSet_BASE(m_aMutex) + ,OPropertySetHelper(OResultSet_BASE::rBHelper) + ,m_aStatement((OWeakObject*)pStmt) + ,m_xMetaData(NULL) + ,m_nTextEncoding(pStmt->getOwnConnection()->getTextEncoding()) + ,m_pStatement(pStmt) + ,m_bWasNull(sal_True) +{ +} + +OResultSet::~OResultSet() +{ +} + +void OResultSet::disposing() +{ + OPropertySetHelper::disposing(); + + ::osl::MutexGuard aGuard(m_aMutex); + + m_aStatement = NULL; + m_xMetaData = NULL; +} + +Any SAL_CALL OResultSet::queryInterface( const Type & rType ) throw(RuntimeException) +{ + Any aRet = OPropertySetHelper::queryInterface(rType); + if(!aRet.hasValue()) + aRet = OResultSet_BASE::queryInterface(rType); + return aRet; +} + + Sequence< Type > SAL_CALL OResultSet::getTypes( ) throw( RuntimeException) +{ + OTypeCollection aTypes( + ::cppu::UnoType::get(), + ::cppu::UnoType::get(), + ::cppu::UnoType::get()); + + return concatSequences(aTypes.getTypes(),OResultSet_BASE::getTypes()); +} + + +sal_Int32 SAL_CALL OResultSet::findColumn( const ::rtl::OUString& columnName ) throw(SQLException, RuntimeException) +{ + + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + // find the first column with the name columnName + + ::osl::MutexGuard aGuard( m_aMutex ); + + Reference< XResultSetMetaData > xMeta = getMetaData(); + sal_Int32 nLen = xMeta->getColumnCount(); + sal_Int32 i = 1; + for(;i<=nLen;++i) + if(xMeta->isCaseSensitive(i) ? columnName == xMeta->getColumnName(i) : + columnName.equalsIgnoreAsciiCase(xMeta->getColumnName(i))) + break; + return i; +} + +Reference< XInputStream > SAL_CALL OResultSet::getBinaryStream( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return NULL; +} + +Reference< XInputStream > SAL_CALL OResultSet::getCharacterStream( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return NULL; +} + + +sal_Bool SAL_CALL OResultSet::getBoolean( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return sal_False; +} + + +sal_Int8 SAL_CALL OResultSet::getByte( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + sal_Int8 nRet = 0; + return nRet; +} + + +Sequence< sal_Int8 > SAL_CALL OResultSet::getBytes( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + + return Sequence< sal_Int8 >(); +} + + +Date SAL_CALL OResultSet::getDate( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + Date nRet; + return nRet; +} + + +double SAL_CALL OResultSet::getDouble( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + double nRet = 0; + return nRet; +} + + +float SAL_CALL OResultSet::getFloat( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + float nVal(0); + return nVal; +} + + +sal_Int32 SAL_CALL OResultSet::getInt( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + sal_Int32 nRet=0; + return nRet; +} + + +sal_Int32 SAL_CALL OResultSet::getRow( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + sal_Int32 nValue = 0; + return nValue; +} + + +sal_Int64 SAL_CALL OResultSet::getLong( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return sal_Int64(); +} + + +Reference< XResultSetMetaData > SAL_CALL OResultSet::getMetaData( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + if(!m_xMetaData.is()) + m_xMetaData = new OResultSetMetaData(m_pStatement->getOwnConnection()); + return m_xMetaData; +} + +Reference< XArray > SAL_CALL OResultSet::getArray( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return NULL; +} + + +Reference< XClob > SAL_CALL OResultSet::getClob( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return NULL; +} + +Reference< XBlob > SAL_CALL OResultSet::getBlob( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return NULL; +} + + +Reference< XRef > SAL_CALL OResultSet::getRef( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return NULL; +} + + +Any SAL_CALL OResultSet::getObject( sal_Int32 columnIndex, const Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return Any(); +} + + +sal_Int16 SAL_CALL OResultSet::getShort( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + sal_Int16 nRet=0; + return nRet; +} + + +::rtl::OUString SAL_CALL OResultSet::getString( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + ::rtl::OUString nRet; + return nRet; +} + + +css::util::Time SAL_CALL OResultSet::getTime( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + ::osl::MutexGuard aGuard( m_aMutex ); + + css::util::Time nRet; + return nRet; +} + + +DateTime SAL_CALL OResultSet::getTimestamp( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + ::osl::MutexGuard aGuard( m_aMutex ); + + DateTime nRet; + return nRet; +} + + +sal_Bool SAL_CALL OResultSet::isBeforeFirst( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + // here you have to implement your movements + // return true means there is no data + return sal_True; +} + +sal_Bool SAL_CALL OResultSet::isAfterLast( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return sal_True; +} + +sal_Bool SAL_CALL OResultSet::isFirst( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return sal_False; +} + +sal_Bool SAL_CALL OResultSet::isLast( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return sal_False; +} + +void SAL_CALL OResultSet::beforeFirst( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + // move before the first row so that isBeforeFirst returns false + // the same for other movement methods +} + +void SAL_CALL OResultSet::afterLast( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); +} + + +void SAL_CALL OResultSet::close( ) throw(SQLException, RuntimeException) +{ + { + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + } + dispose(); +} + + +sal_Bool SAL_CALL OResultSet::first( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return sal_False; +} + + +sal_Bool SAL_CALL OResultSet::last( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return sal_False; +} + +sal_Bool SAL_CALL OResultSet::absolute( sal_Int32 row ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return sal_False; +} + +sal_Bool SAL_CALL OResultSet::relative( sal_Int32 row ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return sal_False; +} + +sal_Bool SAL_CALL OResultSet::previous( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return sal_False; +} + +Reference< XInterface > SAL_CALL OResultSet::getStatement( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return m_aStatement.get(); +} + + +sal_Bool SAL_CALL OResultSet::rowDeleted( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return sal_False; +} + +sal_Bool SAL_CALL OResultSet::rowInserted( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return sal_False; +} + +sal_Bool SAL_CALL OResultSet::rowUpdated( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return sal_False; +} + + +sal_Bool SAL_CALL OResultSet::next( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return sal_False; +} + + +sal_Bool SAL_CALL OResultSet::wasNull( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return m_bWasNull; +} + + +void SAL_CALL OResultSet::cancel( ) throw(RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OResultSet::clearWarnings( ) throw(SQLException, RuntimeException) +{ +} + +Any SAL_CALL OResultSet::getWarnings( ) throw(SQLException, RuntimeException) +{ + return Any(); +} + +void SAL_CALL OResultSet::insertRow( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + // you only have to implement this if you want to insert new rows +} + +void SAL_CALL OResultSet::updateRow( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + // only when you allow updates +} + +void SAL_CALL OResultSet::deleteRow( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); +} + + +void SAL_CALL OResultSet::cancelRowUpdates( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); +} + + +void SAL_CALL OResultSet::moveToInsertRow( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + // only when you allow insert's +} + + +void SAL_CALL OResultSet::moveToCurrentRow( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); +} + + +void SAL_CALL OResultSet::updateNull( sal_Int32 columnIndex ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); +} + + +void SAL_CALL OResultSet::updateBoolean( sal_Int32 columnIndex, sal_Bool x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OResultSet::updateByte( sal_Int32 columnIndex, sal_Int8 x ) throw(SQLException, RuntimeException) +{ + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + +} + + +void SAL_CALL OResultSet::updateShort( sal_Int32 columnIndex, sal_Int16 x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OResultSet::updateInt( sal_Int32 columnIndex, sal_Int32 x ) throw(SQLException, RuntimeException) +{ + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + ::osl::MutexGuard aGuard( m_aMutex ); + +} + +void SAL_CALL OResultSet::updateLong( sal_Int32 columnIndex, sal_Int64 x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OResultSet::updateFloat( sal_Int32 columnIndex, float x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OResultSet::updateDouble( sal_Int32 columnIndex, double x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OResultSet::updateString( sal_Int32 columnIndex, const ::rtl::OUString& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OResultSet::updateBytes( sal_Int32 columnIndex, const Sequence< sal_Int8 >& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OResultSet::updateDate( sal_Int32 columnIndex, const Date& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OResultSet::updateTime( sal_Int32 columnIndex, const css::util::Time& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OResultSet::updateTimestamp( sal_Int32 columnIndex, const DateTime& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OResultSet::updateBinaryStream( sal_Int32 columnIndex, const Reference< XInputStream >& x, sal_Int32 length ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OResultSet::updateCharacterStream( sal_Int32 columnIndex, const Reference< XInputStream >& x, sal_Int32 length ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OResultSet::refreshRow( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +void SAL_CALL OResultSet::updateObject( sal_Int32 columnIndex, const Any& x ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + + +void SAL_CALL OResultSet::updateNumericObject( sal_Int32 columnIndex, const Any& x, sal_Int32 scale ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + +} + +// XRowLocate +Any SAL_CALL OResultSet::getBookmark( ) throw( SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + // if you don't want to support bookmark you must remove the XRowLocate interface + + return Any(); +} + +sal_Bool SAL_CALL OResultSet::moveToBookmark( const Any& bookmark ) throw( SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return sal_False; +} + +sal_Bool SAL_CALL OResultSet::moveRelativeToBookmark( const Any& bookmark, sal_Int32 rows ) throw( SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return sal_False; +} + +sal_Int32 SAL_CALL OResultSet::compareBookmarks( const Any& first, const Any& second ) throw( SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + + return CompareBookmark::NOT_EQUAL; +} + +sal_Bool SAL_CALL OResultSet::hasOrderedBookmarks( ) throw( SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Int32 SAL_CALL OResultSet::hashBookmark( const Any& bookmark ) throw( SQLException, RuntimeException) +{ + throw SQLException(); +} + +// XDeleteRows +Sequence< sal_Int32 > SAL_CALL OResultSet::deleteRows( const Sequence< Any >& rows ) throw( SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OResultSet_BASE::rBHelper.bDisposed); + + return Sequence< sal_Int32 >(); +} + +IPropertyArrayHelper* OResultSet::createArrayHelper( ) const +{ + Sequence< Property > aProps(6); + Property* pProperties = aProps.getArray(); + sal_Int32 nPos = 0; + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_CURSORNAME), + PROPERTY_ID_CURSORNAME, ::cppu::UnoType::get(), PropertyAttribute::READONLY); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_FETCHDIRECTION), + PROPERTY_ID_FETCHDIRECTION, ::cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_FETCHSIZE), + PROPERTY_ID_FETCHSIZE, ::cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_ISBOOKMARKABLE), + PROPERTY_ID_ISBOOKMARKABLE, cppu::UnoType::get(), PropertyAttribute::READONLY); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETCONCURRENCY), + PROPERTY_ID_RESULTSETCONCURRENCY, ::cppu::UnoType::get(), PropertyAttribute::READONLY); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETTYPE), + PROPERTY_ID_RESULTSETTYPE, ::cppu::UnoType::get(), PropertyAttribute::READONLY); + + return new OPropertyArrayHelper(aProps); +} + +IPropertyArrayHelper & OResultSet::getInfoHelper() +{ + return *const_cast(this)->getArrayHelper(); +} + +sal_Bool OResultSet::convertFastPropertyValue( + Any & rConvertedValue, + Any & rOldValue, + sal_Int32 nHandle, + const Any& rValue ) + throw (::com::sun::star::lang::IllegalArgumentException) +{ + switch(nHandle) + { + case PROPERTY_ID_ISBOOKMARKABLE: + case PROPERTY_ID_CURSORNAME: + case PROPERTY_ID_RESULTSETCONCURRENCY: + case PROPERTY_ID_RESULTSETTYPE: + throw ::com::sun::star::lang::IllegalArgumentException(); + break; + case PROPERTY_ID_FETCHDIRECTION: + case PROPERTY_ID_FETCHSIZE: + default: + ; + } + return sal_False; +} + +void OResultSet::setFastPropertyValue_NoBroadcast( + sal_Int32 nHandle, + const Any& rValue + ) + throw (Exception) +{ + switch(nHandle) + { + case PROPERTY_ID_ISBOOKMARKABLE: + case PROPERTY_ID_CURSORNAME: + case PROPERTY_ID_RESULTSETCONCURRENCY: + case PROPERTY_ID_RESULTSETTYPE: + throw Exception(); + break; + case PROPERTY_ID_FETCHDIRECTION: + break; + case PROPERTY_ID_FETCHSIZE: + break; + default: + ; + } +} + +void OResultSet::getFastPropertyValue( + Any& rValue, + sal_Int32 nHandle + ) const +{ + switch(nHandle) + { + case PROPERTY_ID_ISBOOKMARKABLE: + case PROPERTY_ID_CURSORNAME: + case PROPERTY_ID_RESULTSETCONCURRENCY: + case PROPERTY_ID_RESULTSETTYPE: + case PROPERTY_ID_FETCHDIRECTION: + case PROPERTY_ID_FETCHSIZE: + ; + } +} + +void SAL_CALL OResultSet::acquire() throw() +{ + OResultSet_BASE::acquire(); +} + +void SAL_CALL OResultSet::release() throw() +{ + OResultSet_BASE::release(); +} + +::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OResultSet::getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException) +{ + return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper()); +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSet.hxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSet.hxx new file mode 100644 index 000000000..4f887ebe7 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSet.hxx @@ -0,0 +1,222 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SRESULTSET_HXX +#define INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SRESULTSET_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "SStatement.hxx" +#include "OSubComponent.hxx" + +namespace connectivity +{ + namespace skeleton + { + + /* + ** OResultSet + */ + typedef ::cppu::WeakComponentImplHelper12< ::com::sun::star::sdbc::XResultSet, + ::com::sun::star::sdbc::XRow, + ::com::sun::star::sdbc::XResultSetMetaDataSupplier, + ::com::sun::star::util::XCancellable, + ::com::sun::star::sdbc::XWarningsSupplier, + ::com::sun::star::sdbc::XResultSetUpdate, + ::com::sun::star::sdbc::XRowUpdate, + ::com::sun::star::sdbcx::XRowLocate, + ::com::sun::star::sdbcx::XDeleteRows, + ::com::sun::star::sdbc::XCloseable, + ::com::sun::star::sdbc::XColumnLocate, + ::com::sun::star::lang::XServiceInfo> OResultSet_BASE; + + class OResultSet : public OBase_Mutex, + public OResultSet_BASE, + public ::cppu::OPropertySetHelper, + public OPropertyArrayUsageHelper + { + protected: + OStatement_Base* m_pStatement; + ::com::sun::star::uno::WeakReferenceHelper m_aStatement; + ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData> m_xMetaData; + rtl_TextEncoding m_nTextEncoding; + sal_Bool m_bWasNull; + + // OPropertyArrayUsageHelper + virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; + // OPropertySetHelper + virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); + + virtual sal_Bool SAL_CALL convertFastPropertyValue( + ::com::sun::star::uno::Any & rConvertedValue, + ::com::sun::star::uno::Any & rOldValue, + sal_Int32 nHandle, + const ::com::sun::star::uno::Any& rValue ) + throw (::com::sun::star::lang::IllegalArgumentException); + virtual void SAL_CALL setFastPropertyValue_NoBroadcast( + sal_Int32 nHandle, + const ::com::sun::star::uno::Any& rValue + ) + throw (::com::sun::star::uno::Exception); + virtual void SAL_CALL getFastPropertyValue( + ::com::sun::star::uno::Any& rValue, + sal_Int32 nHandle + ) const; + + // you can't delete objects of this type + virtual ~OResultSet(); + public: + DECLARE_SERVICE_INFO(); + + OResultSet( OStatement_Base* pStmt); + + + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > operator *() + { + return ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(*(OResultSet_BASE*)this); + } + + // ::cppu::OComponentHelper + virtual void SAL_CALL disposing(); + // XInterface + virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL acquire() throw(); + virtual void SAL_CALL release() throw(); + //XTypeProvider + virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) 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); + // XResultSet + virtual sal_Bool SAL_CALL next( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isBeforeFirst( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isAfterLast( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isFirst( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isLast( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL beforeFirst( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL afterLast( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL first( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL last( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL absolute( sal_Int32 row ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL relative( sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL previous( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL refreshRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL rowUpdated( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL rowInserted( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL rowDeleted( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getStatement( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XRow + virtual sal_Bool SAL_CALL wasNull( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getString( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL getBoolean( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int8 SAL_CALL getByte( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int16 SAL_CALL getShort( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getInt( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int64 SAL_CALL getLong( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual float SAL_CALL getFloat( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual double SAL_CALL getDouble( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getBytes( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::util::Date SAL_CALL getDate( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::util::Time SAL_CALL getTime( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::util::DateTime SAL_CALL getTimestamp( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getBinaryStream( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getCharacterStream( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Any SAL_CALL getObject( sal_Int32 columnIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRef > SAL_CALL getRef( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XBlob > SAL_CALL getBlob( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XClob > SAL_CALL getClob( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XArray > SAL_CALL getArray( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XResultSetMetaDataSupplier + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > SAL_CALL getMetaData( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XCancellable + virtual void SAL_CALL cancel( ) throw(::com::sun::star::uno::RuntimeException); + // XCloseable + virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XWarningsSupplier + virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XResultSetUpdate + virtual void SAL_CALL insertRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL deleteRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL cancelRowUpdates( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL moveToInsertRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL moveToCurrentRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XRowUpdate + virtual void SAL_CALL updateNull( sal_Int32 columnIndex ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateBoolean( sal_Int32 columnIndex, sal_Bool x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateByte( sal_Int32 columnIndex, sal_Int8 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateShort( sal_Int32 columnIndex, sal_Int16 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateInt( sal_Int32 columnIndex, sal_Int32 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateLong( sal_Int32 columnIndex, sal_Int64 x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateFloat( sal_Int32 columnIndex, float x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateDouble( sal_Int32 columnIndex, double x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateString( sal_Int32 columnIndex, const ::rtl::OUString& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateBytes( sal_Int32 columnIndex, const ::com::sun::star::uno::Sequence< sal_Int8 >& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateDate( sal_Int32 columnIndex, const ::com::sun::star::util::Date& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateTime( sal_Int32 columnIndex, const ::com::sun::star::util::Time& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateTimestamp( sal_Int32 columnIndex, const ::com::sun::star::util::DateTime& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateBinaryStream( sal_Int32 columnIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateCharacterStream( sal_Int32 columnIndex, const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& x, sal_Int32 length ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateObject( sal_Int32 columnIndex, const ::com::sun::star::uno::Any& x ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL updateNumericObject( sal_Int32 columnIndex, const ::com::sun::star::uno::Any& x, sal_Int32 scale ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XColumnLocate + virtual sal_Int32 SAL_CALL findColumn( const ::rtl::OUString& columnName ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XRowLocate + virtual ::com::sun::star::uno::Any SAL_CALL getBookmark( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL moveToBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL moveRelativeToBookmark( const ::com::sun::star::uno::Any& bookmark, sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL compareBookmarks( const ::com::sun::star::uno::Any& first, const ::com::sun::star::uno::Any& second ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL hasOrderedBookmarks( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL hashBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XDeleteRows + virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL deleteRows( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + }; + } +} + +#endif // INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SRESULTSET_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSetMetaData.cxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSetMetaData.cxx new file mode 100644 index 000000000..348af271d --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSetMetaData.cxx @@ -0,0 +1,170 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include "SResultSetMetaData.hxx" + +using namespace connectivity::skeleton; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::sdbc; + + +OResultSetMetaData::~OResultSetMetaData() +{ +} + + +sal_Int32 SAL_CALL OResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return 50; +} + + +sal_Int32 SAL_CALL OResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + sal_Int32 nType = 0; + return nType; +} + + +sal_Int32 SAL_CALL OResultSetMetaData::getColumnCount( ) throw(SQLException, RuntimeException) +{ + // this makes no sense here so you have to change this + return 0; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isCaseSensitive( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return sal_True; +} + + +::rtl::OUString SAL_CALL OResultSetMetaData::getSchemaName( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString(); +} + + +::rtl::OUString SAL_CALL OResultSetMetaData::getColumnName( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString("Column") + ::rtl::OUString::number(column); +} + +::rtl::OUString SAL_CALL OResultSetMetaData::getTableName( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString(); +} + +::rtl::OUString SAL_CALL OResultSetMetaData::getCatalogName( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString(); +} + +::rtl::OUString SAL_CALL OResultSetMetaData::getColumnTypeName( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString(); +} + +::rtl::OUString SAL_CALL OResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString(); +} + +::rtl::OUString SAL_CALL OResultSetMetaData::getColumnServiceName( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return ::rtl::OUString(); +} + + +sal_Bool SAL_CALL OResultSetMetaData::isCurrency( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isAutoIncrement( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isSigned( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + +sal_Int32 SAL_CALL OResultSetMetaData::getPrecision( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return 0; +} + +sal_Int32 SAL_CALL OResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) +{ + return 0; +} + + +sal_Int32 SAL_CALL OResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return 0; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isSearchable( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return sal_True; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isReadOnly( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return sal_True; +} + + +sal_Bool SAL_CALL OResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return sal_False; +; +} + +sal_Bool SAL_CALL OResultSetMetaData::isWritable( sal_Int32 column ) throw(SQLException, RuntimeException) +{ + return sal_False; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSetMetaData.hxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSetMetaData.hxx new file mode 100644 index 000000000..846295b90 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SResultSetMetaData.hxx @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SRESULTSETMETADATA_HXX +#define INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SRESULTSETMETADATA_HXX + +#include +#include +#include "SConnection.hxx" + +namespace connectivity +{ + namespace skeleton + { + + typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData> OResultSetMetaData_BASE; + + class OResultSetMetaData : public OResultSetMetaData_BASE + { + OConnection* m_pConnection; + + protected: + virtual ~OResultSetMetaData(); + public: + // a constructor, which is required for returning objects: + OResultSetMetaData(OConnection* _pConnection) : m_pConnection(_pConnection){} + + /// Avoid ambiguous cast error from the compiler. + inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw() + { return this; } + + virtual sal_Int32 SAL_CALL getColumnCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + }; + } +} + +#endif // INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SRESULTSETMETADATA_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SServices.cxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SServices.cxx new file mode 100644 index 000000000..b04963d05 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SServices.cxx @@ -0,0 +1,153 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include "SDriver.hxx" +#include +#include +#include +#include +#include + +using namespace connectivity::skeleton; +using ::rtl::OUString; +using ::com::sun::star::uno::Reference; +using ::com::sun::star::uno::Sequence; +using ::com::sun::star::registry::XRegistryKey; +using ::com::sun::star::lang::XSingleServiceFactory; +using ::com::sun::star::lang::XMultiServiceFactory; + +typedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc) + ( + const Reference< XMultiServiceFactory > & rServiceManager, + const OUString & rComponentName, + ::cppu::ComponentInstantiation pCreateFunction, + const Sequence< OUString > & rServiceNames, + rtl_ModuleCount* + ); + + +// The required C-Api must be provided! +// It contains of 3 special functions that have to be exported. + + +void REGISTER_PROVIDER( + const OUString& aServiceImplName, + const Sequence< OUString>& Services, + const Reference< ::com::sun::star::registry::XRegistryKey > & xKey) +{ + OUString aMainKeyName("/"); + aMainKeyName += aServiceImplName; + aMainKeyName += "/UNO/SERVICES"; + + Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) ); + OSL_ENSURE(xNewKey.is(), "SKELETON::component_writeInfo : could not create a registry key !"); + + for (sal_uInt32 i=0; icreateKey(Services[i]); +} + + +struct ProviderRequest +{ + Reference< XSingleServiceFactory > xRet; + Reference< XMultiServiceFactory > const xServiceManager; + OUString const sImplementationName; + + ProviderRequest( + void* pServiceManager, + char const* pImplementationName + ) + : xServiceManager(reinterpret_cast(pServiceManager)) + , sImplementationName(OUString::createFromAscii(pImplementationName)) + { + } + + inline + sal_Bool CREATE_PROVIDER( + const OUString& Implname, + const Sequence< OUString > & Services, + ::cppu::ComponentInstantiation Factory, + createFactoryFunc creator + ) + { + if (!xRet.is() && (Implname == sImplementationName)) + try + { + xRet = creator( xServiceManager, sImplementationName,Factory, Services,0); + } + catch(...) + { + } + return xRet.is(); + } + + void* getProvider() const { return xRet.get(); } +}; + + +extern "C" SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory( + const char* pImplementationName, + void* pServiceManager, + void* pRegistryKey) +{ + void* pRet = 0; + if (pServiceManager) + { + ProviderRequest aReq(pServiceManager,pImplementationName); + + aReq.CREATE_PROVIDER( + SkeletonDriver::getImplementationName_Static(), + SkeletonDriver::getSupportedServiceNames_Static(), + SkeletonDriver_CreateInstance, ::cppu::createSingleFactory) + ; + + if(aReq.xRet.is()) + aReq.xRet->acquire(); + + pRet = aReq.getProvider(); + } + + return pRet; +}; + +extern "C" SAL_DLLPUBLIC_EXPORT void SAL_CALL +component_getImplementationEnvironment( + char const ** ppEnvTypeName, uno_Environment **) +{ + *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SStatement.cxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SStatement.cxx new file mode 100644 index 000000000..aaec8cdd3 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SStatement.cxx @@ -0,0 +1,377 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include "SStatement.hxx" +#include "SConnection.hxx" +#include "SResultSet.hxx" +#include +#include +#include +#include +#include +#include +#include +#include "propertyids.hxx" + +using namespace connectivity::skeleton; + +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::sdbc; +using namespace com::sun::star::sdbcx; +using namespace com::sun::star::container; +using namespace com::sun::star::io; +using namespace com::sun::star::util; + +OStatement_Base::OStatement_Base(OConnection* _pConnection ) + : OStatement_BASE(m_aMutex), + OPropertySetHelper(OStatement_BASE::rBHelper), + rBHelper(OStatement_BASE::rBHelper), + m_pConnection(_pConnection) +{ + m_pConnection->acquire(); +} + +OStatement_Base::~OStatement_Base() +{ +} + +void OStatement_Base::disposeResultSet() +{ + // free the cursor if alive + Reference< XComponent > xComp(m_xResultSet.get(), UNO_QUERY); + if (xComp.is()) + xComp->dispose(); + m_xResultSet.clear(); +} + +void OStatement_BASE2::disposing() +{ + ::osl::MutexGuard aGuard(m_aMutex); + + disposeResultSet(); + + if (m_pConnection) + m_pConnection->release(); + m_pConnection = NULL; + + dispose_ChildImpl(); + OStatement_Base::disposing(); +} + +void SAL_CALL OStatement_BASE2::release() throw() +{ + release_ChildImpl(); +} + +Any SAL_CALL OStatement_Base::queryInterface( const Type & rType ) throw(RuntimeException) +{ + Any aRet = OStatement_BASE::queryInterface(rType); + if(!aRet.hasValue()) + aRet = OPropertySetHelper::queryInterface(rType); + return aRet; +} + +Sequence< Type > SAL_CALL OStatement_Base::getTypes( ) throw(RuntimeException) +{ + ::cppu::OTypeCollection aTypes( + ::cppu::UnoType::get(), + ::cppu::UnoType::get(), + ::cppu::UnoType::get()); + + return concatSequences(aTypes.getTypes(),OStatement_BASE::getTypes()); +} + + +void SAL_CALL OStatement_Base::cancel( ) throw(RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + // cancel the current sql statement +} + + +void SAL_CALL OStatement_Base::close( ) throw(SQLException, RuntimeException) +{ + { + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + } + dispose(); +} + + +void SAL_CALL OStatement::clearBatch( ) throw(SQLException, RuntimeException) +{ + // if you support batches clear it here +} + +sal_Bool SAL_CALL OStatement_Base::execute( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + // returns true when a resultset is available + return sal_False; +} + + +Reference< XResultSet > SAL_CALL OStatement_Base::executeQuery( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + Reference< XResultSet > xRS = NULL; + // create a resultset as result of executing the sql statement + // you have to here something :-) + m_xResultSet = xRS; // we need a reference to it for later use + return xRS; +} + + +Reference< XConnection > SAL_CALL OStatement_Base::getConnection( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + // just return our connection here + return (Reference< XConnection >)m_pConnection; +} + +sal_Int32 SAL_CALL OStatement_Base::getUpdateCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) +{ + return 0; +} + + +Any SAL_CALL OStatement::queryInterface( const Type & rType ) throw(RuntimeException) +{ + Any aRet = ::cppu::queryInterface(rType,static_cast< XBatchExecution*> (this)); + if(!aRet.hasValue()) + aRet = OStatement_Base::queryInterface(rType); + return aRet; +} + + +void SAL_CALL OStatement::addBatch( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + m_aBatchVector.push_back(sql); +} + +Sequence< sal_Int32 > SAL_CALL OStatement::executeBatch( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + return Sequence< sal_Int32 >(); +} + + +sal_Int32 SAL_CALL OStatement_Base::executeUpdate( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + // the return values gives information about how many rows are affected by executing the sql statement + return 0; + +} + + +Reference< XResultSet > SAL_CALL OStatement_Base::getResultSet( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + +// return our save resultset here + return m_xResultSet; +} + + +sal_Bool SAL_CALL OStatement_Base::getMoreResults( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + // if your driver supports more than only one resultset + // and has one more at this moment return true + return sal_False; +} + + +Any SAL_CALL OStatement_Base::getWarnings( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + return makeAny(m_aLastWarning); +} + + +void SAL_CALL OStatement_Base::clearWarnings( ) throw(SQLException, RuntimeException) +{ + ::osl::MutexGuard aGuard( m_aMutex ); + checkDisposed(OStatement_BASE::rBHelper.bDisposed); + + + m_aLastWarning = SQLWarning(); +} + +::cppu::IPropertyArrayHelper* OStatement_Base::createArrayHelper( ) const +{ + // this properties are define by the service statement + // they must in alphabetic order + Sequence< Property > aProps(10); + Property* pProperties = aProps.getArray(); + sal_Int32 nPos = 0; + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_CURSORNAME), + PROPERTY_ID_CURSORNAME, ::cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_ESCAPEPROCESSING), + PROPERTY_ID_ESCAPEPROCESSING, cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_FETCHDIRECTION), + PROPERTY_ID_FETCHDIRECTION, ::cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_FETCHSIZE), + PROPERTY_ID_FETCHSIZE, ::cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_MAXFIELDSIZE), + PROPERTY_ID_MAXFIELDSIZE, ::cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_MAXROWS), + PROPERTY_ID_MAXROWS, ::cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_QUERYTIMEOUT), + PROPERTY_ID_QUERYTIMEOUT, ::cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETCONCURRENCY), + PROPERTY_ID_RESULTSETCONCURRENCY, ::cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_RESULTSETTYPE), + PROPERTY_ID_RESULTSETTYPE, ::cppu::UnoType::get(), 0); + pProperties[nPos++] = ::com::sun::star::beans::Property(OPropertyMap::getPropMap().getNameByIndex(PROPERTY_ID_USEBOOKMARKS), + PROPERTY_ID_USEBOOKMARKS, cppu::UnoType::get(), 0); + + return new ::cppu::OPropertyArrayHelper(aProps); +} + + +::cppu::IPropertyArrayHelper & OStatement_Base::getInfoHelper() +{ + return *const_cast(this)->getArrayHelper(); +} + +sal_Bool OStatement_Base::convertFastPropertyValue( + Any & rConvertedValue, + Any & rOldValue, + sal_Int32 nHandle, + const Any& rValue ) + throw (::com::sun::star::lang::IllegalArgumentException) +{ + sal_Bool bConverted = sal_False; + // here we have to try to convert + return bConverted; +} + +void OStatement_Base::setFastPropertyValue_NoBroadcast(sal_Int32 nHandle,const Any& rValue) throw (Exception) +{ + // set the value to whatever is necessary + switch(nHandle) + { + case PROPERTY_ID_QUERYTIMEOUT: + case PROPERTY_ID_MAXFIELDSIZE: + case PROPERTY_ID_MAXROWS: + case PROPERTY_ID_CURSORNAME: + case PROPERTY_ID_RESULTSETCONCURRENCY: + case PROPERTY_ID_RESULTSETTYPE: + case PROPERTY_ID_FETCHDIRECTION: + case PROPERTY_ID_FETCHSIZE: + case PROPERTY_ID_ESCAPEPROCESSING: + case PROPERTY_ID_USEBOOKMARKS: + default: + ; + } +} + +void OStatement_Base::getFastPropertyValue(Any& rValue,sal_Int32 nHandle) const +{ + switch(nHandle) + { + case PROPERTY_ID_QUERYTIMEOUT: + case PROPERTY_ID_MAXFIELDSIZE: + case PROPERTY_ID_MAXROWS: + case PROPERTY_ID_CURSORNAME: + case PROPERTY_ID_RESULTSETCONCURRENCY: + case PROPERTY_ID_RESULTSETTYPE: + case PROPERTY_ID_FETCHDIRECTION: + case PROPERTY_ID_FETCHSIZE: + case PROPERTY_ID_ESCAPEPROCESSING: + case PROPERTY_ID_USEBOOKMARKS: + default: + ; + } +} + +IMPLEMENT_SERVICE_INFO(OStatement,"com.sun.star.sdbcx.OStatement","com.sun.star.sdbc.Statement"); + +void SAL_CALL OStatement_Base::acquire() throw() +{ + OStatement_BASE::acquire(); +} + +void SAL_CALL OStatement_Base::release() throw() +{ + OStatement_BASE::release(); +} + +void SAL_CALL OStatement::acquire() throw() +{ + OStatement_BASE2::acquire(); +} + +void SAL_CALL OStatement::release() throw() +{ + OStatement_BASE2::release(); +} + +Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL OStatement_Base::getPropertySetInfo( ) throw(RuntimeException) +{ + return ::cppu::OPropertySetHelper::createPropertySetInfo(getInfoHelper()); +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/SStatement.hxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SStatement.hxx new file mode 100644 index 000000000..c870048d8 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/SStatement.hxx @@ -0,0 +1,176 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SSTATEMENT_HXX +#define INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SSTATEMENT_HXX + +#include +#include +#include +#include +#include +#include +#include +#include +#include "SConnection.hxx" +#include +#include "OSubComponent.hxx" +#include + +namespace connectivity +{ + namespace skeleton + { + + typedef ::cppu::WeakComponentImplHelper5< ::com::sun::star::sdbc::XStatement, + ::com::sun::star::sdbc::XWarningsSupplier, + ::com::sun::star::util::XCancellable, + ::com::sun::star::sdbc::XCloseable, + ::com::sun::star::sdbc::XMultipleResults> OStatement_BASE; + + // A base class for the normal statement and for the prepared statement + class OStatement_Base : public OBase_Mutex, + public OStatement_BASE, + public ::cppu::OPropertySetHelper, + public OPropertyArrayUsageHelper + + { + ::com::sun::star::sdbc::SQLWarning m_aLastWarning; + protected: + ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XResultSet> m_xResultSet; // The last ResultSet created + // for this Statement + + ::std::vector< ::rtl::OUString> m_aBatchVector; + + OConnection* m_pConnection; // The owning Connection object + protected: + + void disposeResultSet(); + + // OPropertyArrayUsageHelper + virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; + // OPropertySetHelper + virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper(); + virtual sal_Bool SAL_CALL convertFastPropertyValue( + ::com::sun::star::uno::Any & rConvertedValue, + ::com::sun::star::uno::Any & rOldValue, + sal_Int32 nHandle, + const ::com::sun::star::uno::Any& rValue ) + throw (::com::sun::star::lang::IllegalArgumentException); + virtual void SAL_CALL setFastPropertyValue_NoBroadcast( + sal_Int32 nHandle, + const ::com::sun::star::uno::Any& rValue) throw (::com::sun::star::uno::Exception); + virtual void SAL_CALL getFastPropertyValue( + ::com::sun::star::uno::Any& rValue, + sal_Int32 nHandle) const; + virtual ~OStatement_Base(); + + public: + ::cppu::OBroadcastHelper& rBHelper; + OStatement_Base(OConnection* _pConnection ); + using OStatement_BASE::operator ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >; + + // OComponentHelper + virtual void SAL_CALL disposing(){OStatement_BASE::disposing();} + // XInterface + virtual void SAL_CALL release() throw(); + virtual void SAL_CALL acquire() throw(); + // XInterface + virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); + //XTypeProvider + virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) 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); + // XStatement + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ; + virtual sal_Int32 SAL_CALL executeUpdate( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ; + virtual sal_Bool SAL_CALL execute( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ; + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ; + // XWarningsSupplier + virtual ::com::sun::star::uno::Any SAL_CALL getWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL clearWarnings( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XCancellable + virtual void SAL_CALL cancel( ) throw(::com::sun::star::uno::RuntimeException); + // XCloseable + virtual void SAL_CALL close( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + // XMultipleResults + virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getResultSet( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Int32 SAL_CALL getUpdateCount( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL getMoreResults( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + + // other methods + OConnection* getOwnConnection() const { return m_pConnection;} + }; + + class OStatement_BASE2 :public OStatement_Base + ,public OSubComponent + + { + friend class OSubComponent; + public: + OStatement_BASE2(OConnection* _pConnection ) : OStatement_Base(_pConnection ), + OSubComponent((::cppu::OWeakObject*)_pConnection, this){} + // OComponentHelper + virtual void SAL_CALL disposing(); + // XInterface + virtual void SAL_CALL release() throw(); + }; + + class OStatement : public OStatement_BASE2, + public ::com::sun::star::sdbc::XBatchExecution, + public ::com::sun::star::lang::XServiceInfo + { + protected: + virtual ~OStatement(){} + public: + // a constructor, which is required for returning objects: + OStatement( OConnection* _pConnection) : OStatement_BASE2( _pConnection){} + DECLARE_SERVICE_INFO(); + + virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL acquire() throw(); + virtual void SAL_CALL release() throw(); + // XBatchExecution + virtual void SAL_CALL addBatch( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL clearBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL executeBatch( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); + }; + } +} + +#endif // INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_SSTATEMENT_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/propertyids.cxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/propertyids.cxx new file mode 100644 index 000000000..cbbe29bd1 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/propertyids.cxx @@ -0,0 +1,184 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include "propertyids.hxx" +namespace connectivity +{ +namespace skeleton +{ + const char* getPROPERTY_QUERYTIMEOUT() { return "QueryTimeOut"; } + const char* getPROPERTY_MAXFIELDSIZE() { return "MaxFieldSize"; } + const char* getPROPERTY_MAXROWS() { return "MaxRows"; } + const char* getPROPERTY_CURSORNAME() { return "CursorName"; } + const char* getPROPERTY_RESULTSETCONCURRENCY() { return "ResultSetConcurrency"; } + const char* getPROPERTY_RESULTSETTYPE() { return "ResultSetType"; } + const char* getPROPERTY_FETCHDIRECTION() { return "FetchDirection"; } + const char* getPROPERTY_FETCHSIZE() { return "FetchSize"; } + const char* getPROPERTY_ESCAPEPROCESSING() { return "EscapeProcessing"; } + const char* getPROPERTY_USEBOOKMARKS() { return "UseBookmarks"; } + + const char* getPROPERTY_NAME() { return "Name"; } + const char* getPROPERTY_TYPE() { return "Type"; } + const char* getPROPERTY_TYPENAME() { return "TypeName"; } + const char* getPROPERTY_PRECISION() { return "Precision"; } + const char* getPROPERTY_SCALE() { return "Scale"; } + const char* getPROPERTY_ISNULLABLE() { return "IsNullable"; } + const char* getPROPERTY_ISAUTOINCREMENT() { return "IsAutoIncrement"; } + const char* getPROPERTY_ISROWVERSION() { return "IsRowVersion"; } + const char* getPROPERTY_DESCRIPTION() { return "Description"; } + const char* getPROPERTY_DEFAULTVALUE() { return "DefaultValue"; } + + const char* getPROPERTY_REFERENCEDTABLE() { return "ReferencedTable"; } + const char* getPROPERTY_UPDATERULE() { return "UpdateRule"; } + const char* getPROPERTY_DELETERULE() { return "DeleteRule"; } + const char* getPROPERTY_CATALOG() { return "Catalog"; } + const char* getPROPERTY_ISUNIQUE() { return "IsUnique"; } + const char* getPROPERTY_ISPRIMARYKEYINDEX() { return "IsPrimaryKeyIndex"; } + const char* getPROPERTY_ISCLUSTERED() { return "IsClustered"; } + const char* getPROPERTY_ISASCENDING() { return "IsAscending"; } + const char* getPROPERTY_SCHEMANAME() { return "SchemaName"; } + const char* getPROPERTY_CATALOGNAME() { return "CatalogName"; } + const char* getPROPERTY_COMMAND() { return "Command"; } + const char* getPROPERTY_CHECKOPTION() { return "CheckOption"; } + const char* getPROPERTY_PASSWORD() { return "Password"; } + const char* getPROPERTY_RELATEDCOLUMN() { return "RelatedColumn"; } + + const char* getSTAT_INVALID_INDEX() { return "Invalid descriptor index"; } + + const char* getPROPERTY_FUNCTION() { return "Function"; } + const char* getPROPERTY_TABLENAME() { return "TableName"; } + const char* getPROPERTY_REALNAME() { return "RealName"; } + const char* getPROPERTY_DBASEPRECISIONCHANGED() { return "DbasePrecisionChanged"; } + const char* getPROPERTY_ISCURRENCY() { return "IsCurrency"; } + const char* getPROPERTY_ISBOOKMARKABLE() { return "IsBookmarkable"; } + + const char* getPROPERTY_FORMATKEY() { return "FormatKey"; } + const char* getPROPERTY_LOCALE() { return "Locale"; } + + const char* getPROPERTY_AUTOINCREMENTCREATION() { return "AutoIncrementCreation"; } + const char* getPROPERTY_PRIVILEGES() { return "Privileges"; } + + //= error messages + + const char* getERRORMSG_SEQUENCE() { return "Function sequence error"; } + const char* getSQLSTATE_SEQUENCE() { return "HY010"; } + const char* getSQLSTATE_GENERAL() { return "HY0000"; } + const char* getSTR_DELIMITER() { return "/"; } + + OPropertyMap::~OPropertyMap() + { + ::std::map::iterator aIter = m_aPropertyMap.begin(); + for(;aIter != m_aPropertyMap.end();++aIter) + if(aIter->second) + rtl_uString_release(aIter->second); + } + + ::rtl::OUString OPropertyMap::getNameByIndex(sal_Int32 _nIndex) const + { + ::rtl::OUString sRet; + ::std::map::const_iterator aIter = m_aPropertyMap.find(_nIndex); + if(aIter == m_aPropertyMap.end()) + sRet = const_cast(this)->fillValue(_nIndex); + else + sRet = aIter->second; + return sRet; + } + + ::rtl::OUString OPropertyMap::fillValue(sal_Int32 _nIndex) + { + rtl_uString* pStr = NULL; + switch(_nIndex) + { + case PROPERTY_ID_QUERYTIMEOUT: { rtl_uString_newFromAscii(&pStr,getPROPERTY_QUERYTIMEOUT() ); break; } + case PROPERTY_ID_MAXFIELDSIZE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_MAXFIELDSIZE() ); break; } + case PROPERTY_ID_MAXROWS: { rtl_uString_newFromAscii(&pStr,getPROPERTY_MAXROWS() ); break; } + case PROPERTY_ID_CURSORNAME: { rtl_uString_newFromAscii(&pStr,getPROPERTY_CURSORNAME() ); break; } + case PROPERTY_ID_RESULTSETCONCURRENCY: { rtl_uString_newFromAscii(&pStr,getPROPERTY_RESULTSETCONCURRENCY() ); break; } + case PROPERTY_ID_RESULTSETTYPE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_RESULTSETTYPE() ); break; } + case PROPERTY_ID_FETCHDIRECTION: { rtl_uString_newFromAscii(&pStr,getPROPERTY_FETCHDIRECTION() ); break; } + case PROPERTY_ID_FETCHSIZE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_FETCHSIZE() ); break; } + case PROPERTY_ID_ESCAPEPROCESSING: { rtl_uString_newFromAscii(&pStr,getPROPERTY_ESCAPEPROCESSING() ); break; } + case PROPERTY_ID_USEBOOKMARKS: { rtl_uString_newFromAscii(&pStr,getPROPERTY_USEBOOKMARKS() ); break; } + // Column + case PROPERTY_ID_NAME: { rtl_uString_newFromAscii(&pStr,getPROPERTY_NAME() ); break; } + case PROPERTY_ID_TYPE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_TYPE() ); break; } + case PROPERTY_ID_TYPENAME: { rtl_uString_newFromAscii(&pStr,getPROPERTY_TYPENAME() ); break; } + case PROPERTY_ID_PRECISION: { rtl_uString_newFromAscii(&pStr,getPROPERTY_PRECISION() ); break; } + case PROPERTY_ID_SCALE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_SCALE() ); break; } + case PROPERTY_ID_ISNULLABLE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_ISNULLABLE() ); break; } + case PROPERTY_ID_ISAUTOINCREMENT: { rtl_uString_newFromAscii(&pStr,getPROPERTY_ISAUTOINCREMENT() ); break; } + case PROPERTY_ID_ISROWVERSION: { rtl_uString_newFromAscii(&pStr,getPROPERTY_ISROWVERSION() ); break; } + case PROPERTY_ID_DESCRIPTION: { rtl_uString_newFromAscii(&pStr,getPROPERTY_DESCRIPTION() ); break; } + case PROPERTY_ID_DEFAULTVALUE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_DEFAULTVALUE() ); break; } + + case PROPERTY_ID_REFERENCEDTABLE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_REFERENCEDTABLE() ); break; } + case PROPERTY_ID_UPDATERULE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_UPDATERULE() ); break; } + case PROPERTY_ID_DELETERULE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_DELETERULE() ); break; } + case PROPERTY_ID_CATALOG: { rtl_uString_newFromAscii(&pStr,getPROPERTY_CATALOG() ); break; } + case PROPERTY_ID_ISUNIQUE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_ISUNIQUE() ); break; } + case PROPERTY_ID_ISPRIMARYKEYINDEX: { rtl_uString_newFromAscii(&pStr,getPROPERTY_ISPRIMARYKEYINDEX() ); break; } + case PROPERTY_ID_ISCLUSTERED: { rtl_uString_newFromAscii(&pStr,getPROPERTY_ISCLUSTERED() ); break; } + case PROPERTY_ID_ISASCENDING: { rtl_uString_newFromAscii(&pStr,getPROPERTY_ISASCENDING() ); break; } + case PROPERTY_ID_SCHEMANAME: { rtl_uString_newFromAscii(&pStr,getPROPERTY_SCHEMANAME() ); break; } + case PROPERTY_ID_CATALOGNAME: { rtl_uString_newFromAscii(&pStr,getPROPERTY_CATALOGNAME() ); break; } + + case PROPERTY_ID_COMMAND: { rtl_uString_newFromAscii(&pStr,getPROPERTY_COMMAND() ); break; } + case PROPERTY_ID_CHECKOPTION: { rtl_uString_newFromAscii(&pStr,getPROPERTY_CHECKOPTION() ); break; } + case PROPERTY_ID_PASSWORD: { rtl_uString_newFromAscii(&pStr,getPROPERTY_PASSWORD() ); break; } + case PROPERTY_ID_RELATEDCOLUMN: { rtl_uString_newFromAscii(&pStr,getPROPERTY_RELATEDCOLUMN() ); break; } + + case PROPERTY_ID_FUNCTION: { rtl_uString_newFromAscii(&pStr,getPROPERTY_FUNCTION() ); break; } + case PROPERTY_ID_TABLENAME: { rtl_uString_newFromAscii(&pStr,getPROPERTY_TABLENAME() ); break; } + case PROPERTY_ID_REALNAME: { rtl_uString_newFromAscii(&pStr,getPROPERTY_REALNAME() ); break; } + case PROPERTY_ID_DBASEPRECISIONCHANGED: { rtl_uString_newFromAscii(&pStr,getPROPERTY_DBASEPRECISIONCHANGED() ); break; } + case PROPERTY_ID_ISCURRENCY: { rtl_uString_newFromAscii(&pStr,getPROPERTY_ISCURRENCY() ); break; } + case PROPERTY_ID_ISBOOKMARKABLE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_ISBOOKMARKABLE() ); break; } + case PROPERTY_ID_INVALID_INDEX: { rtl_uString_newFromAscii(&pStr,getSTAT_INVALID_INDEX() ); break; } + case PROPERTY_ID_ERRORMSG_SEQUENCE: { rtl_uString_newFromAscii(&pStr,getERRORMSG_SEQUENCE() ); break; } + case PROPERTY_ID_HY010: { rtl_uString_newFromAscii(&pStr,getSQLSTATE_SEQUENCE() ); break; } + case PROPERTY_ID_HY0000: { rtl_uString_newFromAscii(&pStr,getSQLSTATE_GENERAL() ); break; } + case PROPERTY_ID_DELIMITER: { rtl_uString_newFromAscii(&pStr,getSTR_DELIMITER() ); break; } + case PROPERTY_ID_FORMATKEY: { rtl_uString_newFromAscii(&pStr,getPROPERTY_FORMATKEY() ); break; } + case PROPERTY_ID_LOCALE: { rtl_uString_newFromAscii(&pStr,getPROPERTY_LOCALE() ); break; } + case PROPERTY_ID_AUTOINCREMENTCREATION: { rtl_uString_newFromAscii(&pStr,getPROPERTY_AUTOINCREMENTCREATION() ); break; } + case PROPERTY_ID_PRIVILEGES: { rtl_uString_newFromAscii(&pStr,getPROPERTY_PRIVILEGES() ); break; } + } + m_aPropertyMap[_nIndex] = pStr; + return pStr; + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/DriverSkeleton/propertyids.hxx b/odk/examples/DevelopersGuide/Database/DriverSkeleton/propertyids.hxx new file mode 100644 index 000000000..bc8e20d7a --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/DriverSkeleton/propertyids.hxx @@ -0,0 +1,145 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_PROPERTYIDS_HXX +#define INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_PROPERTYIDS_HXX + +// this define has to be set to split the names into different dll's or so's +// every dll has his own set of property names +#include +#include + +namespace connectivity +{ +namespace skeleton +{ + class OPropertyMap + { + ::std::map m_aPropertyMap; + + ::rtl::OUString fillValue(sal_Int32 _nIndex); + public: + OPropertyMap() + { + } + ~OPropertyMap(); + ::rtl::OUString getNameByIndex(sal_Int32 _nIndex) const; + + static OPropertyMap& getPropMap() + { + static OPropertyMap s_aPropMap; + return s_aPropMap; + } + }; + + + typedef const char* (*PVFN)(); + + struct UStringDescription + { + const char* pZeroTerminatedName; + sal_Int32 nLength; + + UStringDescription(PVFN _fCharFkt); + operator ::rtl::OUString() const { return ::rtl::OUString(pZeroTerminatedName,nLength,RTL_TEXTENCODING_ASCII_US); } + ~UStringDescription(); + private: + UStringDescription(); + }; + } +} + + +#define PROPERTY_ID_QUERYTIMEOUT 1 +#define PROPERTY_ID_MAXFIELDSIZE 2 +#define PROPERTY_ID_MAXROWS 3 +#define PROPERTY_ID_CURSORNAME 4 +#define PROPERTY_ID_RESULTSETCONCURRENCY 5 +#define PROPERTY_ID_RESULTSETTYPE 6 +#define PROPERTY_ID_FETCHDIRECTION 7 +#define PROPERTY_ID_FETCHSIZE 8 +#define PROPERTY_ID_ESCAPEPROCESSING 9 +#define PROPERTY_ID_USEBOOKMARKS 10 +// Column +#define PROPERTY_ID_NAME 11 +#define PROPERTY_ID_TYPE 12 +#define PROPERTY_ID_TYPENAME 13 +#define PROPERTY_ID_PRECISION 14 +#define PROPERTY_ID_SCALE 15 +#define PROPERTY_ID_ISNULLABLE 16 +#define PROPERTY_ID_ISAUTOINCREMENT 17 +#define PROPERTY_ID_ISROWVERSION 18 +#define PROPERTY_ID_DESCRIPTION 19 +#define PROPERTY_ID_DEFAULTVALUE 20 + +#define PROPERTY_ID_REFERENCEDTABLE 21 +#define PROPERTY_ID_UPDATERULE 22 +#define PROPERTY_ID_DELETERULE 23 +#define PROPERTY_ID_CATALOG 24 +#define PROPERTY_ID_ISUNIQUE 25 +#define PROPERTY_ID_ISPRIMARYKEYINDEX 26 +#define PROPERTY_ID_ISCLUSTERED 27 +#define PROPERTY_ID_ISASCENDING 28 +#define PROPERTY_ID_SCHEMANAME 29 +#define PROPERTY_ID_CATALOGNAME 30 + +#define PROPERTY_ID_COMMAND 31 +#define PROPERTY_ID_CHECKOPTION 32 +#define PROPERTY_ID_PASSWORD 33 +#define PROPERTY_ID_RELATEDCOLUMN 34 + +#define PROPERTY_ID_FUNCTION 35 +#define PROPERTY_ID_TABLENAME 36 +#define PROPERTY_ID_REALNAME 37 +#define PROPERTY_ID_DBASEPRECISIONCHANGED 38 +#define PROPERTY_ID_ISCURRENCY 39 +#define PROPERTY_ID_ISBOOKMARKABLE 40 + +#define PROPERTY_ID_INVALID_INDEX 41 +#define PROPERTY_ID_ERRORMSG_SEQUENCE 42 +#define PROPERTY_ID_HY010 43 +#define PROPERTY_ID_HY0000 44 +#define PROPERTY_ID_DELIMITER 45 +#define PROPERTY_ID_FORMATKEY 46 +#define PROPERTY_ID_LOCALE 47 +#define PROPERTY_ID_IM001 48 + +#define PROPERTY_ID_AUTOINCREMENTCREATION 49 + +#define PROPERTY_ID_PRIVILEGES 50 + +#endif // INCLUDED_EXAMPLES_DATABASE_DRIVERSKELETON_PROPERTYIDS_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/Makefile b/odk/examples/DevelopersGuide/Database/Makefile new file mode 100644 index 000000000..a155fcaf5 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/Makefile @@ -0,0 +1,133 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Database examples of the Developers Guide. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=DataBaseExamples +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +APP1_NAME=CodeSamples +APP1_JAR=$(OUT_APP_CLASS)/$(APP1_NAME).jar +APP2_NAME=OpenQuery +APP2_JAR=$(OUT_APP_CLASS)/$(APP2_NAME).jar +APP3_NAME=RowSet +APP3_JAR=$(OUT_APP_CLASS)/$(APP3_NAME).jar + +APP1_JAVAFILES = \ + Sales.java \ + SalesMan.java \ + CodeSamples.java \ + sdbcx.java + +APP3_JAVAFILES = \ + RowSetEventListener.java \ + RowSet.java + +APP1_CLASSFILES = $(patsubst %.java,$(OUT_APP_CLASS)/%.class,$(APP1_JAVAFILES)) +APP1_CLASSNAMES = $(patsubst %.java,%.class,$(APP1_JAVAFILES)) + +APP3_CLASSFILES = $(patsubst %.java,$(OUT_APP_CLASS)/%.class,$(APP3_JAVAFILES)) +APP3_CLASSNAMES = $(patsubst %.java,%.class,$(APP3_JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + +# Targets +.PHONY: ALL +ALL : \ + $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(APP1_CLASSFILES) : $(APP1_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $(APP1_JAVAFILES) + +$(APP3_CLASSFILES) : $(APP3_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $(APP3_JAVAFILES) + +$(OUT_APP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(OUT_APP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(APP1_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(APP1_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP2_JAR) : $(OUT_APP_CLASS)/$(APP2_NAME).mf $(OUT_APP_CLASS)/$(APP2_NAME).class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(basename $(@F)).class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP3_JAR) : $(OUT_APP_CLASS)/$(APP3_NAME).mf $(APP3_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(APP3_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(EXAMPLE_NAME) : $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) + @echo -------------------------------------------------------------------------------- + @echo This examples needs a running database with name "$(QM)MYDB0$(QM)". Make sure that you + @echo have created such a database and have established a connection to it. + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) CodeSamples.run + @echo $(MAKE) OpenQuery.run + @echo $(MAKE) RowSet.run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/Database/OpenQuery.java b/odk/examples/DevelopersGuide/Database/OpenQuery.java new file mode 100644 index 000000000..fffae8a2f --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/OpenQuery.java @@ -0,0 +1,143 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.beans.XPropertySet; + +public class OpenQuery { + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + OpenQuery openQuery1 = new OpenQuery(); + try { + openQuery1.openQuery(); + } + catch (java.lang.Exception e){ + e.printStackTrace(); + } + finally { + System.exit(0); + } + } + + protected void openQuery() throws com.sun.star.uno.Exception, java.lang.Exception { + XComponentContext xContext = null; + XMultiComponentFactory xMCF = null; + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + xMCF = xContext.getServiceManager(); + } + catch( Exception e) { + System.err.println("ERROR: can't get a component context from a running office ..."); + e.printStackTrace(); + System.exit(1); + } + + // first we create our RowSet object and get its XRowSet interface + Object rowSet = xMCF.createInstanceWithContext( + "com.sun.star.sdb.RowSet", xContext); + + com.sun.star.sdbc.XRowSet xRowSet = UnoRuntime.queryInterface(com.sun.star.sdbc.XRowSet.class, rowSet); + + // set the properties needed to connect to a database + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class, xRowSet); + + // the DataSourceName can be a data source registered with [PRODUCTNAME], among other possibilities + xProp.setPropertyValue("DataSourceName","Bibliography"); + + // the CommandType must be TABLE, QUERY or COMMAND, here we use COMMAND + xProp.setPropertyValue("CommandType",Integer.valueOf(com.sun.star.sdb.CommandType.COMMAND)); + + // the Command could be a table or query name or a SQL command, depending on the CommandType + xProp.setPropertyValue("Command","SELECT IDENTIFIER, AUTHOR FROM biblio ORDER BY IDENTIFIER"); + + // if your database requires logon, you can use the properties User and Password + // xProp.setPropertyValue("User", "JohnDoe"); + // xProp.setPropertyValue("Password", "mysecret"); + + xRowSet.execute(); + + // prepare the XRow and XColumnLocate interface for column access + // XRow gets column values + com.sun.star.sdbc.XRow xRow = UnoRuntime.queryInterface( + com.sun.star.sdbc.XRow.class, xRowSet); + // XColumnLocate finds columns by name + com.sun.star.sdbc.XColumnLocate xLoc = UnoRuntime.queryInterface( + com.sun.star.sdbc.XColumnLocate.class, xRowSet); + + // print output header + System.out.println("Identifier\tAuthor"); + System.out.println("----------\t------"); + + // output result rows + while ( xRowSet.next() ) { + String ident = xRow.getString(xLoc.findColumn("IDENTIFIER")); + String author = xRow.getString(xLoc.findColumn("AUTHOR")); + System.out.println(ident + "\t\t" + author); + } + + // XResultSetUpdate for insertRow handling + com.sun.star.sdbc.XResultSetUpdate xResultSetUpdate = UnoRuntime.queryInterface( + com.sun.star.sdbc.XResultSetUpdate.class, xRowSet); + + // XRowUpdate for row updates + com.sun.star.sdbc.XRowUpdate xRowUpdate = UnoRuntime.queryInterface( + com.sun.star.sdbc.XRowUpdate.class, xRowSet); + + // move to insertRow buffer + xResultSetUpdate.moveToInsertRow(); + + // edit insertRow buffer + xRowUpdate.updateString(xLoc.findColumn("IDENTIFIER"), "GOF95"); + xRowUpdate.updateString(xLoc.findColumn("AUTHOR"), "Gamma, Helm, Johnson, Vlissides"); + + // write buffer to database + xResultSetUpdate.insertRow(); + + // throw away the row set + com.sun.star.lang.XComponent xComp = UnoRuntime.queryInterface( + com.sun.star.lang.XComponent.class, xRowSet); + xComp.dispose(); + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/RowSet.java b/odk/examples/DevelopersGuide/Database/RowSet.java new file mode 100644 index 000000000..e053dabb9 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/RowSet.java @@ -0,0 +1,225 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XComponent; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.beans.XPropertySet; +import com.sun.star.sdbc.*; +import com.sun.star.sdbcx.Privilege; +import com.sun.star.sdb.XRowSetApproveBroadcaster; + +public class RowSet +{ + private static XComponentContext xContext = null; + private static XMultiComponentFactory xMCF = null; + public static void main(String argv[]) throws java.lang.Exception + { + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + xMCF = xContext.getServiceManager(); + } + catch( Exception e) { + System.err.println("ERROR: can't get a component context from a running office ..."); + e.printStackTrace(System.err); + System.exit(1); + } + + try{ + showRowSetEvents(); + showRowSetRowCount(); + showRowSetPrivileges(); + useRowSet(); + } + catch(com.sun.star.uno.Exception e) + { + System.err.println(e); + e.printStackTrace(); + } + System.exit(0); + } + + + + private static void useRowSet() throws com.sun.star.uno.Exception + { + // first we create our RowSet object + XRowSet xRowRes = UnoRuntime.queryInterface( + XRowSet.class, + xMCF.createInstanceWithContext("com.sun.star.sdb.RowSet", xContext)); + + System.out.println("RowSet created!"); + // set the properties needed to connect to a database + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class,xRowRes); + xProp.setPropertyValue("DataSourceName","Bibliography"); + xProp.setPropertyValue("Command","biblio"); + xProp.setPropertyValue("CommandType",Integer.valueOf(com.sun.star.sdb.CommandType.TABLE)); + + xRowRes.execute(); + System.out.println("RowSet executed!"); + + + XComponent xComp = UnoRuntime.queryInterface(XComponent.class,xRowRes); + xComp.dispose(); + System.out.println("RowSet destroyed!"); + } + + private static void showRowSetPrivileges() throws com.sun.star.uno.Exception + { + // first we create our RowSet object + XRowSet xRowRes = UnoRuntime.queryInterface( + XRowSet.class, + xMCF.createInstanceWithContext("com.sun.star.sdb.RowSet", xContext)); + + System.out.println("RowSet created!"); + // set the properties needed to connect to a database + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class,xRowRes); + xProp.setPropertyValue("DataSourceName","Bibliography"); + xProp.setPropertyValue("Command","biblio"); + xProp.setPropertyValue("CommandType",Integer.valueOf(com.sun.star.sdb.CommandType.TABLE)); + + xRowRes.execute(); + System.out.println("RowSet executed!"); + + Integer aPriv = (Integer)xProp.getPropertyValue("Privileges"); + int nPriv = aPriv.intValue(); + if( (nPriv & Privilege.SELECT) == Privilege.SELECT) + System.out.println("SELECT"); + if( (nPriv & Privilege.INSERT) == Privilege.INSERT) + System.out.println("INSERT"); + if( (nPriv & Privilege.UPDATE) == Privilege.UPDATE) + System.out.println("UPDATE"); + if( (nPriv & Privilege.DELETE) == Privilege.DELETE) + System.out.println("DELETE"); + + // now destroy the RowSet + XComponent xComp = UnoRuntime.queryInterface(XComponent.class,xRowRes); + xComp.dispose(); + System.out.println("RowSet destroyed!"); + } + + private static void showRowSetRowCount() throws com.sun.star.uno.Exception + { + // first we create our RowSet object + XRowSet xRowRes = UnoRuntime.queryInterface( + XRowSet.class, + xMCF.createInstanceWithContext("com.sun.star.sdb.RowSet", xContext)); + + System.out.println("RowSet created!"); + // set the properties needed to connect to a database + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class,xRowRes); + xProp.setPropertyValue("DataSourceName","Bibliography"); + xProp.setPropertyValue("Command","biblio"); + xProp.setPropertyValue("CommandType",Integer.valueOf(com.sun.star.sdb.CommandType.TABLE)); + + xRowRes.execute(); + System.out.println("RowSet executed!"); + + // now look if the RowCount is already final + System.out.println("The RowCount is final: " + xProp.getPropertyValue("IsRowCountFinal")); + + XResultSet xRes = UnoRuntime.queryInterface(XResultSet.class,xRowRes); + xRes.last(); + + System.out.println("The RowCount is final: " + xProp.getPropertyValue("IsRowCountFinal")); + System.out.println("There are " + xProp.getPropertyValue("RowCount") + " rows!"); + + // now destroy the RowSet + XComponent xComp = UnoRuntime.queryInterface(XComponent.class,xRowRes); + xComp.dispose(); + System.out.println("RowSet destroyed!"); + } + + private static void showRowSetEvents() throws com.sun.star.uno.Exception + { + // first we create our RowSet object + XRowSet xRowRes = UnoRuntime.queryInterface( + XRowSet.class, + xMCF.createInstanceWithContext("com.sun.star.sdb.RowSet", xContext)); + + System.out.println("RowSet created!"); + // add our Listener + System.out.println("Append our Listener!"); + RowSetEventListener pRow = new RowSetEventListener(); + XRowSetApproveBroadcaster xApBroad = UnoRuntime.queryInterface(XRowSetApproveBroadcaster.class,xRowRes); + xApBroad.addRowSetApproveListener(pRow); + xRowRes.addRowSetListener(pRow); + + // set the properties needed to connect to a database + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class,xRowRes); + xProp.setPropertyValue("DataSourceName","Bibliography"); + xProp.setPropertyValue("Command","biblio"); + xProp.setPropertyValue("CommandType",Integer.valueOf(com.sun.star.sdb.CommandType.TABLE)); + + xRowRes.execute(); + System.out.println("RowSet executed!"); + + // do some movements to check if we got all notifications + XResultSet xRes = UnoRuntime.queryInterface(XResultSet.class,xRowRes); + System.out.println("beforeFirst"); + xRes.beforeFirst(); + // this should lead to no notifications because + // we should stand before the first row at the beginning + System.out.println("We stand before the first row: " + xRes.isBeforeFirst()); + + System.out.println("next"); + xRes.next(); + System.out.println("next"); + xRes.next(); + System.out.println("last"); + xRes.last(); + System.out.println("next"); + xRes.next(); + System.out.println("We stand after the last row: " + xRes.isAfterLast()); + System.out.println("first"); + xRes.first(); + System.out.println("previous"); + xRes.previous(); + System.out.println("We stand before the first row: " + xRes.isBeforeFirst()); + System.out.println("afterLast"); + xRes.afterLast(); + System.out.println("We stand after the last row: " + xRes.isAfterLast()); + + // now destroy the RowSet + XComponent xComp = UnoRuntime.queryInterface(XComponent.class,xRowRes); + xComp.dispose(); + System.out.println("RowSet destroyed!"); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/RowSetEventListener.java b/odk/examples/DevelopersGuide/Database/RowSetEventListener.java new file mode 100644 index 000000000..785164d25 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/RowSetEventListener.java @@ -0,0 +1,80 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.sdb.XRowSetApproveListener; +import com.sun.star.sdbc.XRowSetListener; +import com.sun.star.sdb.RowChangeEvent; +import com.sun.star.lang.EventObject; + +public class RowSetEventListener implements XRowSetApproveListener,XRowSetListener +{ + // XEventListener + public void disposing(com.sun.star.lang.EventObject event) + { + System.out.println("RowSet will be destroyed!"); + } + // XRowSetApproveBroadcaster + public boolean approveCursorMove(EventObject event) + { + System.out.println("Before CursorMove!"); + return true; + } + public boolean approveRowChange(RowChangeEvent event) + { + System.out.println("Before row change!"); + return true; + } + public boolean approveRowSetChange(EventObject event) + { + System.out.println("Before RowSet change!"); + return true; + } + + // XRowSetListener + public void cursorMoved(com.sun.star.lang.EventObject event) + { + System.out.println("Cursor moved!"); + } + public void rowChanged(com.sun.star.lang.EventObject event) + { + System.out.println("Row changed!"); + } + public void rowSetChanged(com.sun.star.lang.EventObject event) + { + System.out.println("RowSet changed!"); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/Sales.java b/odk/examples/DevelopersGuide/Database/Sales.java new file mode 100644 index 000000000..f50e21595 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/Sales.java @@ -0,0 +1,130 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.*; +import com.sun.star.beans.XPropertySet; +import com.sun.star.sdbc.*; + +public class Sales +{ + private final XConnection con; + + public Sales(XConnection connection ) + { + con = connection; + } + // create the table sales. + public void createSalesTable() throws com.sun.star.uno.Exception + { + String createTableSales = "CREATE TABLE SALES " + + "(SALENR INTEGER NOT NULL, " + + " COS_NR INTEGER, " + + " SNR INTEGER, " + + " NAME VARCHAR(50)," + + " SALEDATE DATE," + + " PRICE FLOAT(10), " + + " PRIMARY KEY(SALENR)" + + " )"; + XStatement stmt = con.createStatement(); + stmt.executeUpdate( createTableSales ); + } + + // drop the table sales. + public void dropSalesTable() throws com.sun.star.uno.Exception + { + String createTableSalesman = "DROP TABLE SALES "; + XStatement stmt = con.createStatement(); + stmt.executeUpdate( createTableSalesman ); + } + + // insert data into the table sales. + public void insertDataIntoSales() throws com.sun.star.uno.Exception + { + XStatement stmt = con.createStatement(); + stmt.executeUpdate("INSERT INTO SALES " + + "VALUES (1, '100', '1','Linux','2001-02-12',15)"); + stmt.executeUpdate("INSERT INTO SALES " + + "VALUES (2, '101', '2','Beef','2001-10-18',15.78)"); + stmt.executeUpdate("INSERT INTO SALES " + + "VALUES (3, '104', '4','orange juice','2001-08-09',1.5)"); + } + + // update the table sales with a prepared statement. + public void updateSales() throws com.sun.star.uno.Exception + { + XStatement stmt = con.createStatement(); + String updateString = "UPDATE SALES " + + "SET PRICE = 30 " + + "WHERE SALENR = 1"; + stmt.executeUpdate(updateString); + } + + // retrieve the data of the table sales. + public void retrieveSalesData() throws com.sun.star.uno.Exception + { + XStatement stmt = con.createStatement(); + String query = "SELECT NAME, PRICE FROM SALES " + + "WHERE SALENR = 1"; + XResultSet rs = stmt.executeQuery(query); + XRow row = UnoRuntime.queryInterface(XRow.class, rs); + while (rs.next()) { + String s = row.getString(1); + float n = row.getFloat(2); + System.out.println("The current price for " + s + " is: $" + n + "."); + } + } + + + + // displays the column names + public void displayColumnNames() throws com.sun.star.uno.Exception + { + XStatement stmt = con.createStatement(); + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class,stmt); + xProp.setPropertyValue("ResultSetType", Integer.valueOf(ResultSetType.SCROLL_INSENSITIVE)); + xProp.setPropertyValue("ResultSetConcurrency", Integer.valueOf(ResultSetConcurrency.READ_ONLY)); + XResultSet rs = stmt.executeQuery("SELECT NAME, PRICE FROM SALES"); + XResultSetMetaDataSupplier xRsMetaSup = UnoRuntime.queryInterface(XResultSetMetaDataSupplier.class,rs); + XResultSetMetaData xRsMetaData = xRsMetaSup.getMetaData(); + int nColumnCount = xRsMetaData.getColumnCount(); + for(int i=1 ; i <= nColumnCount ; ++i) + { + System.out.println("Name: " + xRsMetaData.getColumnName(i) + " Type: " + + xRsMetaData.getColumnType(i)); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/SalesMan.java b/odk/examples/DevelopersGuide/Database/SalesMan.java new file mode 100644 index 000000000..db00ef75a --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/SalesMan.java @@ -0,0 +1,137 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.*; +import com.sun.star.util.Date; +import com.sun.star.sdbc.*; + +public class SalesMan +{ + private final XConnection con; + + public SalesMan(XConnection connection ) + { + con = connection; + } + // create the table salesman. + public void createSalesManTable() throws com.sun.star.uno.Exception + { + String createTableSalesman = "CREATE TABLE SALESMAN " + + "(SNR INTEGER NOT NULL, "+ + " FIRSTNAME VARCHAR(50)," + + " LASTNAME VARCHAR(100)," + + " STREET VARCHAR(50)," + + " STATE VARCHAR(50)," + + " ZIP INTEGER," + + " BIRTHDATE DATE," + + " PRIMARY KEY(SNR)" + + " )"; + XStatement stmt = con.createStatement(); + stmt.executeUpdate( createTableSalesman ); + } + + // drop the table salesman + public void dropSalesManTable() throws com.sun.star.uno.Exception + { + String createTableSalesman = "DROP TABLE SALESMAN "; + XStatement stmt = con.createStatement(); + stmt.executeUpdate( createTableSalesman ); + } + + // insert data into the table salesman + public void insertDataIntoSalesMan() throws com.sun.star.uno.Exception + { + XStatement stmt = con.createStatement(); + stmt.executeUpdate("INSERT INTO SALESMAN " + + "VALUES (1, 'Joseph', 'Smith','Bond Street','CA',95460," + + "'1946-07-02')"); + stmt.executeUpdate("INSERT INTO SALESMAN " + + "VALUES (2, 'Frank', 'Jones','Lake Silver','CA',95460," + + "'1963-12-24')"); + stmt.executeUpdate("INSERT INTO SALESMAN " + + "VALUES (3, 'Jane', 'Esperansa','23 Hollywood drive','CA',95460," + + "'1972-04-01')"); + stmt.executeUpdate("INSERT INTO SALESMAN " + + "VALUES (4, 'George', 'Flint','12 Washington street','CA',95460," + + "'1953-02-13')"); + stmt.executeUpdate("INSERT INTO SALESMAN " + + "VALUES (5, 'Bob', 'Meyers','2 Moon way','CA',95460," + + "'1949-09-07')"); + } + + // update the table sales man with a prepared statement. + public void updateSalesMan() throws com.sun.star.uno.Exception + { + XPreparedStatement updateStreet = con.prepareStatement( + "UPDATE SALESMAN SET STREET = ? WHERE SNR = ?"); + XParameters setPara = UnoRuntime.queryInterface(XParameters.class,updateStreet); + setPara.setString(1, "34 Main Road"); + setPara.setInt(2, 1); + updateStreet.executeUpdate(); + + setPara.setString(1, "Marryland"); + setPara.setInt(2, 4); + updateStreet.executeUpdate(); + // changes STREET column of salesman George to Marryland + setPara.setString(1, "Michigan road"); + updateStreet.executeUpdate(); + // changes again STREET column of salesman George to + // Michigan road + // parameter 2 stayed 4, and the first parameter was reset + // to "Michigan road") + + setPara.setString(1, "Bond Street"); + setPara.setInt(2, 3); + int n = updateStreet.executeUpdate(); + System.out.println("executeUpdate returns: " + n); + // n = 1 because one row had a change in it + } + + // retrieve the data of the table salesman + public void retrieveSalesManData() throws com.sun.star.uno.Exception + { + XStatement stmt = con.createStatement(); + XResultSet rs = stmt.executeQuery("SELECT FIRSTNAME, LASTNAME, BIRTHDATE FROM SALESMAN"); + XRow row = UnoRuntime.queryInterface(XRow.class,rs); + while ( rs != null && rs.next() ) { + String fn = row.getString( 1 ); + String ln = row.getString( 2 ); + Date dt = row.getDate( 3 ); + System.out.println(fn + " " + ln + " " + dt.Month + "/" + dt.Day + "/" + dt.Year); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Database/sdbcx.java b/odk/examples/DevelopersGuide/Database/sdbcx.java new file mode 100644 index 000000000..8d7bcab93 --- /dev/null +++ b/odk/examples/DevelopersGuide/Database/sdbcx.java @@ -0,0 +1,420 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lang.XComponent; +import com.sun.star.uno.*; +import com.sun.star.bridge.XUnoUrlResolver; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XIndexAccess; +import com.sun.star.sdbc.*; +import com.sun.star.sdbcx.*; +import com.sun.star.lang.XMultiServiceFactory; + +public class sdbcx +{ + private final XMultiServiceFactory xORB; + private static XConnection con; + private XTablesSupplier xTabSup; + + public static XMultiServiceFactory rSmgr; + + public static void main(String argv[]) throws java.lang.Exception + { + try{ + rSmgr = connect("socket,host=localhost,port=8100"); + sdbcx test = new sdbcx(rSmgr); + test.createConnection(); + test.displayTableProperties(); + // now we dispose the connection to close it + XComponent xComponent = UnoRuntime.queryInterface(XComponent.class,con); + if(xComponent != null) + { + xComponent.dispose(); + System.out.println("Connection disposed!"); + } + } + catch(com.sun.star.uno.Exception e) + { + System.out.println(e); + e.printStackTrace(); + } + System.exit(0); + } + public static XMultiServiceFactory connect( String connectStr ) + throws com.sun.star.uno.Exception, + com.sun.star.uno.RuntimeException, java.lang.Exception + { + // initial serviceManager + XMultiServiceFactory xLocalServiceManager = + com.sun.star.comp.helper.Bootstrap.createSimpleServiceManager(); + + // create a connector, so that it can contact the office + Object xUrlResolver = xLocalServiceManager.createInstance( "com.sun.star.bridge.UnoUrlResolver" ); + XUnoUrlResolver urlResolver = UnoRuntime.queryInterface( + XUnoUrlResolver.class, xUrlResolver ); + + Object rInitialObject = urlResolver.resolve( "uno:" + connectStr + ";urp;StarOffice.NamingService" ); + + XNamingService rName = UnoRuntime.queryInterface( + XNamingService.class, rInitialObject ); + + XMultiServiceFactory xMSF = null; + if( rName != null ) { + System.err.println( "got the remote naming service !" ); + Object rXsmgr = rName.getRegisteredObject("StarOffice.ServiceManager" ); + + xMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, rXsmgr ); + } + + return xMSF; + } + + + public sdbcx(XMultiServiceFactory rSmgr ) + { + xORB = rSmgr; + } + + public void createConnection() throws com.sun.star.uno.Exception + { + // create the Driver with the implementation name + Object aDriver = xORB.createInstance("org.openoffice.comp.connectivity.pq.Driver.noext"); + // query for the interface + com.sun.star.sdbc.XDriver xDriver; + xDriver = UnoRuntime.queryInterface(XDriver.class,aDriver); + if(xDriver != null) + { + // first create the needed url + String URL = "sdbc:postgresql:dbname=MYDB0"; + // second create the necessary properties + com.sun.star.beans.PropertyValue [] Props = new com.sun.star.beans.PropertyValue[] + { + new com.sun.star.beans.PropertyValue("user",0,"test1",com.sun.star.beans.PropertyState.DIRECT_VALUE), + new com.sun.star.beans.PropertyValue("password",0,"test1",com.sun.star.beans.PropertyState.DIRECT_VALUE) + }; + + // now create a connection to the database + con = xDriver.connect(URL, Props); + if(con != null) + { + System.out.println("Connection could be created!"); + // with the XDatabaseDefinitionSupplier interface from the driver to get the XTablesSupplier + XDataDefinitionSupplier xDDSup = UnoRuntime.queryInterface( + XDataDefinitionSupplier.class,xDriver); + if(xDDSup != null) + { + xTabSup = xDDSup.getDataDefinitionByConnection(con); + if(xTabSup != null) + { + XNameAccess xTables = xTabSup.getTables(); + // now print all table names + System.out.println("Tables available:"); + String [] aTableNames = xTables.getElementNames(); + for ( int i =0; i<= aTableNames.length-1; i++) + System.out.println(aTableNames[i]); + } + } + else + System.out.println("The driver is not a SDBCX capable!"); + } + else + System.out.println("Connection could not be created!"); + } + } + + public void displayTableProperties() throws com.sun.star.uno.Exception + { + XNameAccess xTables = xTabSup.getTables(); + String [] aTableNames = xTables.getElementNames(); + if(0 != aTableNames.length) + { + Object table = xTables.getByName(aTableNames[0]); + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class,table); + System.out.println("Name: " + xProp.getPropertyValue("Name")); + System.out.println("CatalogName: " + xProp.getPropertyValue("CatalogName")); + System.out.println("SchemaName: " + xProp.getPropertyValue("SchemaName")); + System.out.println("Description: " + xProp.getPropertyValue("Description")); + // the following property is optional so we first must check if it exists + if(xProp.getPropertySetInfo().hasPropertyByName("Type")) + System.out.println("Type: " + xProp.getPropertyValue("Type")); + } + } + + + // 15. example + // print all columns of a XColumnsSupplier + + public static void printColumns(XColumnsSupplier xColumnsSup) + { + System.out.println("Example printColumns"); + // the table must be at least support a XColumnsSupplier interface + System.out.println("--- Columns ---"); + XNameAccess xColumns = xColumnsSup.getColumns(); + String [] aColumnNames = xColumns.getElementNames(); + for ( int i =0; i<= aColumnNames.length-1; i++) + System.out.println(" " + aColumnNames[i]); + } + + // 16. example + // print all keys inclusive the columns of a key + + public static void printKeys(XColumnsSupplier xColumnsSup) throws com.sun.star.uno.Exception + { + System.out.println("Example printKeys"); + XKeysSupplier xKeysSup = UnoRuntime.queryInterface(XKeysSupplier.class,xColumnsSup); + if(xKeysSup != null) + { + System.out.println("--- Keys ---"); + XIndexAccess xKeys = xKeysSup.getKeys(); + for ( int i =0; i < xKeys.getCount(); i++) + { + Object key = xKeys.getByIndex(i); + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class,key); + System.out.println(" " + xProp.getPropertyValue("Name")); + XColumnsSupplier xKeyColumnsSup = UnoRuntime.queryInterface(XColumnsSupplier.class,xProp); + printColumns(xKeyColumnsSup); + } + } + } + + // 17. example + // print all keys inclusive the columns of a key + + public static void printIndexes(XColumnsSupplier xColumnsSup) throws com.sun.star.uno.Exception + { + System.out.println("Example printIndexes"); + XIndexesSupplier xIndexesSup = UnoRuntime.queryInterface(XIndexesSupplier.class,xColumnsSup); + if(xIndexesSup != null) + { + System.out.println("--- Indexes ---"); + XNameAccess xIndexs = xIndexesSup.getIndexes(); + String [] aIndexNames = xIndexs.getElementNames(); + for ( int i =0; i<= aIndexNames.length-1; i++) + { + System.out.println(" " + aIndexNames[i]); + Object index = xIndexs.getByName(aIndexNames[i]); + XColumnsSupplier xIndexColumnsSup = UnoRuntime.queryInterface(XColumnsSupplier.class,index); + printColumns(xIndexColumnsSup); + } + } + } + + + // 18. example + // column properties + + public static void printColumnProperties(Object column) throws com.sun.star.uno.Exception + { + System.out.println("Example printColumnProperties"); + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class,column); + System.out.println("Name: " + xProp.getPropertyValue("Name")); + System.out.println("Type: " + xProp.getPropertyValue("Type")); + System.out.println("TypeName: " + xProp.getPropertyValue("TypeName")); + System.out.println("Precision: " + xProp.getPropertyValue("Precision")); + System.out.println("Scale: " + xProp.getPropertyValue("Scale")); + System.out.println("IsNullable: " + xProp.getPropertyValue("IsNullable")); + System.out.println("IsAutoIncrement: " + xProp.getPropertyValue("IsAutoIncrement")); + System.out.println("IsCurrency: " + xProp.getPropertyValue("IsCurrency")); + // the following property is optional so we first must check if it exists + if(xProp.getPropertySetInfo().hasPropertyByName("IsRowVersion")) + System.out.println("IsRowVersion: " + xProp.getPropertyValue("IsRowVersion")); + if(xProp.getPropertySetInfo().hasPropertyByName("Description")) + System.out.println("Description: " + xProp.getPropertyValue("Description")); + if(xProp.getPropertySetInfo().hasPropertyByName("DefaultValue")) + System.out.println("DefaultValue: " + xProp.getPropertyValue("DefaultValue")); + } + + + // 19. example + // index properties + + public static void printIndexProperties(Object index) throws com.sun.star.uno.Exception + { + System.out.println("Example printIndexProperties"); + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class,index); + System.out.println("Name: " + xProp.getPropertyValue("Name")); + System.out.println("Catalog: " + xProp.getPropertyValue("Catalog")); + System.out.println("IsUnique: " + xProp.getPropertyValue("IsUnique")); + System.out.println("IsPrimaryKeyIndex: " + xProp.getPropertyValue("IsPrimaryKeyIndex")); + System.out.println("IsClustered: " + xProp.getPropertyValue("IsClustered")); + } + + + // 20. example + // key properties + + public static void printKeyProperties(Object key) throws com.sun.star.uno.Exception + { + System.out.println("Example printKeyProperties"); + XPropertySet xProp = UnoRuntime.queryInterface(XPropertySet.class,key); + System.out.println("Name: " + xProp.getPropertyValue("Name")); + System.out.println("Type: " + xProp.getPropertyValue("Type")); + System.out.println("ReferencedTable: " + xProp.getPropertyValue("ReferencedTable")); + System.out.println("UpdateRule: " + xProp.getPropertyValue("UpdateRule")); + System.out.println("DeleteRule: " + xProp.getPropertyValue("DeleteRule")); + } + + + // 21. example + // print all groups and the users with their privileges who belong to this group + + public static void printGroups(XTablesSupplier xTabSup) throws com.sun.star.uno.Exception,SQLException + { + System.out.println("Example printGroups"); + XGroupsSupplier xGroupsSup = UnoRuntime.queryInterface(XGroupsSupplier.class,xTabSup); + if(xGroupsSup != null) + { + // the table must be at least support a XColumnsSupplier interface + System.out.println("--- Groups ---"); + XNameAccess xGroups = xGroupsSup.getGroups(); + String [] aGroupNames = xGroups.getElementNames(); + for ( int i =0; i < aGroupNames.length; i++) + { + System.out.println(" " + aGroupNames[i]); + XUsersSupplier xUsersSup = UnoRuntime.queryInterface(XUsersSupplier.class,xGroups.getByName(aGroupNames[i])); + if(xUsersSup != null) + { + XAuthorizable xAuth = UnoRuntime.queryInterface(XAuthorizable.class,xUsersSup); + // the table must be at least support a XColumnsSupplier interface + System.out.println("\t--- Users ---"); + XNameAccess xUsers = xUsersSup.getUsers(); + String [] aUserNames = xUsers.getElementNames(); + for ( int j =0; j < aUserNames.length; j++) + { + System.out.println("\t " + aUserNames[j] + " Privileges: " + xAuth.getPrivileges(aUserNames[j],PrivilegeObject.TABLE)); + } + } + } + } + } + + + // 22. example + // create the table salesmen + + public static void createTableSalesMen(XNameAccess xTables) throws com.sun.star.uno.Exception,SQLException + { + System.out.println("Example createTableSalesMen"); + XDataDescriptorFactory xTabFac = UnoRuntime.queryInterface(XDataDescriptorFactory.class,xTables); + if(xTabFac != null) + { + // create the new table + XPropertySet xTable = xTabFac.createDataDescriptor(); + // set the name of the new table + xTable.setPropertyValue("Name","SALESMAN"); + // append the columns + XColumnsSupplier xColumSup = UnoRuntime.queryInterface(XColumnsSupplier.class,xTable); + XDataDescriptorFactory xColFac = UnoRuntime.queryInterface(XDataDescriptorFactory.class,xColumSup.getColumns()); + XAppend xAppend = UnoRuntime.queryInterface(XAppend.class,xColFac); + // we only need one descriptor + XPropertySet xCol = xColFac.createDataDescriptor(); + // create first column and append + xCol.setPropertyValue("Name","SNR"); + xCol.setPropertyValue("Type",Integer.valueOf(DataType.INTEGER)); + xCol.setPropertyValue("IsNullable",Integer.valueOf(ColumnValue.NO_NULLS)); + xAppend.appendByDescriptor(xCol); + // 2nd only set the properties which differs + xCol.setPropertyValue("Name","FIRSTNAME"); + xCol.setPropertyValue("Type",Integer.valueOf(DataType.VARCHAR)); + xCol.setPropertyValue("IsNullable",Integer.valueOf(ColumnValue.NULLABLE)); + xCol.setPropertyValue("Precision",Integer.valueOf(50)); + xAppend.appendByDescriptor(xCol); + // 3nd only set the properties which differs + xCol.setPropertyValue("Name","LASTNAME"); + xCol.setPropertyValue("Precision",Integer.valueOf(100)); + xAppend.appendByDescriptor(xCol); + // 4nd only set the properties which differs + xCol.setPropertyValue("Name","STREET"); + xCol.setPropertyValue("Precision",Integer.valueOf(50)); + xAppend.appendByDescriptor(xCol); + // 5nd only set the properties which differs + xCol.setPropertyValue("Name","STATE"); + xAppend.appendByDescriptor(xCol); + // 6nd only set the properties which differs + xCol.setPropertyValue("Name","ZIP"); + xCol.setPropertyValue("Type",Integer.valueOf(DataType.INTEGER)); + xCol.setPropertyValue("Precision",Integer.valueOf(10)); // default value integer + xAppend.appendByDescriptor(xCol); + // 7nd only set the properties which differs + xCol.setPropertyValue("Name","BIRTHDATE"); + xCol.setPropertyValue("Type",Integer.valueOf(DataType.DATE)); + xCol.setPropertyValue("Precision",Integer.valueOf(10)); // default value integer + xAppend.appendByDescriptor(xCol); + // now we create the primary key + XKeysSupplier xKeySup = UnoRuntime.queryInterface(XKeysSupplier.class,xTable); + XDataDescriptorFactory xKeyFac = UnoRuntime.queryInterface(XDataDescriptorFactory.class,xKeySup.getKeys()); + XAppend xKeyAppend = UnoRuntime.queryInterface(XAppend.class,xKeyFac); + XPropertySet xKey = xKeyFac.createDataDescriptor(); + xKey.setPropertyValue("Type",Integer.valueOf(KeyType.PRIMARY)); + // now append the columns to key + XColumnsSupplier xKeyColumSup = UnoRuntime.queryInterface(XColumnsSupplier.class,xKey); + XDataDescriptorFactory xKeyColFac = UnoRuntime.queryInterface(XDataDescriptorFactory.class,xKeyColumSup.getColumns()); + XAppend xKeyColAppend = UnoRuntime.queryInterface(XAppend.class,xKeyColFac); + // we only need one descriptor + XPropertySet xKeyCol = xKeyColFac.createDataDescriptor(); + xKeyCol.setPropertyValue("Name","SNR"); + // append the key column + xKeyColAppend.appendByDescriptor(xKeyCol); + // append the key + xKeyAppend.appendByDescriptor(xKey); + // the last step is to append the new table to the tables collection + XAppend xTableAppend = UnoRuntime.queryInterface(XAppend.class,xTabFac); + xTableAppend.appendByDescriptor(xTable); + } + } + + + // 23. example + // create a user + + public static void createUser(XNameAccess xUsers) throws com.sun.star.uno.Exception,SQLException + { + System.out.println("Example createUser"); + XDataDescriptorFactory xUserFac = UnoRuntime.queryInterface(XDataDescriptorFactory.class,xUsers); + if(xUserFac != null) + { + // create the new table + XPropertySet xUser = xUserFac.createDataDescriptor(); + // set the name of the new table + xUser.setPropertyValue("Name","BOSS"); + xUser.setPropertyValue("Password","BOSSWIFENAME"); + XAppend xAppend = UnoRuntime.queryInterface(XAppend.class,xUserFac); + xAppend.appendByDescriptor(xUser); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/ChangeOrderDemo.java b/odk/examples/DevelopersGuide/Drawing/ChangeOrderDemo.java new file mode 100644 index 000000000..6a5de2c7d --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/ChangeOrderDemo.java @@ -0,0 +1,113 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XDrawPage; + + + +// __________ Implementation __________ + +// ChangeOrderDemo + +public class ChangeOrderDemo +{ + public static void main( String args[] ) + { + XComponent xDrawDoc = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xDrawDoc = Helper.createDocument( xOfficeContext, + "private:factory/sdraw", "_blank", 0, pPropValues ); + + // create two rectangles + XDrawPage xPage = PageHelper.getDrawPageByIndex( xDrawDoc, 0 ); + XShapes xShapes = UnoRuntime.queryInterface( XShapes.class, xPage ); + + XShape xShape1 = ShapeHelper.createShape( xDrawDoc, + new Point( 1000, 1000 ), new Size( 5000, 5000 ), + "com.sun.star.drawing.RectangleShape" ); + + XShape xShape2 = ShapeHelper.createShape( xDrawDoc, + new Point( 2000, 2000 ), new Size( 5000, 5000 ), + "com.sun.star.drawing.EllipseShape" ); + + xShapes.add( xShape1 ); + ShapeHelper.addPortion( xShape1, " this shape was inserted first", false ); + ShapeHelper.addPortion( xShape1, "by changing the ZOrder it lie now on top", true ); + xShapes.add( xShape2 ); + + XPropertySet xPropSet1 = UnoRuntime.queryInterface( XPropertySet.class, xShape1 ); + XPropertySet xPropSet2 = UnoRuntime.queryInterface( XPropertySet.class, xShape2 ); + + int nOrderOfShape1 = ((Integer)xPropSet1.getPropertyValue( "ZOrder" )).intValue(); + int nOrderOfShape2 = ((Integer)xPropSet2.getPropertyValue( "ZOrder" )).intValue(); + + xPropSet1.setPropertyValue( "ZOrder", Integer.valueOf( nOrderOfShape2 ) ); + xPropSet2.setPropertyValue( "ZOrder", Integer.valueOf( nOrderOfShape1 ) ); + } + catch( Exception ex ) + { + System.out.println( ex ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/ControlAndSelectDemo.java b/odk/examples/DevelopersGuide/Drawing/ControlAndSelectDemo.java new file mode 100644 index 000000000..b2108db18 --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/ControlAndSelectDemo.java @@ -0,0 +1,144 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiServiceFactory; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; +import com.sun.star.awt.XControlModel; + +import com.sun.star.beans.PropertyValue; + +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XControlShape; +import com.sun.star.drawing.XDrawPage; +import com.sun.star.drawing.XDrawPages; +import com.sun.star.drawing.XDrawPagesSupplier; + +import com.sun.star.frame.XModel; +import com.sun.star.frame.XController; + +import com.sun.star.view.XSelectionSupplier; + + +// __________ Implementation __________ + +/** ControlAndSelectDemo + + A (GroupBox) ControlShape will be created. + Finally the ControlShape will be inserted into a selection. +*/ + +public class ControlAndSelectDemo +{ + public static void main( String args[] ) + { + XComponent xComponent = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xComponent = Helper.createDocument( xOfficeContext, + "private:factory/sdraw", "_blank", 0, pPropValues ); + + XMultiServiceFactory xFactory = + UnoRuntime.queryInterface( + XMultiServiceFactory.class, xComponent ); + + XDrawPagesSupplier xDrawPagesSupplier = + UnoRuntime.queryInterface( + XDrawPagesSupplier.class, xComponent ); + XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages(); + XDrawPage xDrawPage = UnoRuntime.queryInterface( + XDrawPage.class, xDrawPages.getByIndex( 0 )); + XShapes xShapes = UnoRuntime.queryInterface(XShapes.class, + xDrawPage ); + + + // create and insert the ControlShape + Object xObj = xFactory.createInstance( + "com.sun.star.drawing.ControlShape" ); + XShape xShape = UnoRuntime.queryInterface( XShape.class, xObj ); + xShape.setPosition( new Point( 1000, 1000 ) ); + xShape.setSize( new Size( 2000, 2000 ) ); + xShapes.add( xShape ); + + // create and set the control + XControlModel xControlModel = UnoRuntime.queryInterface( + XControlModel.class, + xFactory.createInstance( "com.sun.star.form.component.GroupBox" ) ); + XControlShape xControlShape = UnoRuntime.queryInterface( + XControlShape.class, xShape ); + xControlShape.setControl( xControlModel ); + + + // the following code will demonstrate how to + // make a selection that contains our new created ControlShape + XModel xModel = UnoRuntime.queryInterface( XModel.class, + xComponent ); + XController xController = xModel.getCurrentController(); + XSelectionSupplier xSelectionSupplier =UnoRuntime.queryInterface( XSelectionSupplier.class, xController ); + // take care to use the global service factory only and not the one + // that is provided by the component if you create the ShapeColletion + XShapes xSelection = UnoRuntime.queryInterface( XShapes.class, + xOfficeContext.getServiceManager().createInstanceWithContext( + "com.sun.star.drawing.ShapeCollection", xOfficeContext ) ); + xSelection.add( xShape ); + xSelectionSupplier.select( xSelection ); + } + catch( java.lang.Exception ex ) + { + System.out.println( ex ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/CustomShowDemo.java b/odk/examples/DevelopersGuide/Drawing/CustomShowDemo.java new file mode 100644 index 000000000..7dcf1d71d --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/CustomShowDemo.java @@ -0,0 +1,169 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XSingleServiceFactory; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.container.XNamed; +import com.sun.star.container.XNameContainer; +import com.sun.star.container.XIndexContainer; + +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XDrawPage; +import com.sun.star.drawing.XDrawPages; +import com.sun.star.drawing.XDrawPagesSupplier; + +import com.sun.star.presentation.XPresentation; +import com.sun.star.presentation.XPresentationSupplier; +import com.sun.star.presentation.XCustomPresentationSupplier; + + +// __________ Implementation __________ + +// presentation demo + +// This demo will demonstrate how to create a CustomShow + +// The first parameter describes the connection that is to use. If there is no parameter +// "uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" is used. + + +public class CustomShowDemo +{ + public static void main( String args[] ) + { + XComponent xDrawDoc = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xDrawDoc = Helper.createDocument( xOfficeContext, + "private:factory/simpress", "_blank", 0, pPropValues ); + + XDrawPagesSupplier xDrawPagesSupplier = + UnoRuntime.queryInterface( + XDrawPagesSupplier.class, xDrawDoc ); + XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages(); + + // take care that this document has ten pages + while ( xDrawPages.getCount() < 10 ) + xDrawPages.insertNewByIndex( 0 ); + + // assign a name to each page and also insert a text object including the name of the page + String aNameArray[] = { "Introduction", "page one", "page two", "page three", "page four", + "page five", "page six", "page seven", "page eight", "page nine" }; + int i; + for ( i = 0; i < 10; i++ ) + { + XDrawPage xDrawPage = UnoRuntime.queryInterface( + XDrawPage.class, xDrawPages.getByIndex( i )); + XNamed xPageName = UnoRuntime.queryInterface( + XNamed.class, xDrawPage ); + xPageName.setName( aNameArray[ i ] ); + + // now we will create and insert the text object + XShape xTextObj = ShapeHelper.createShape( xDrawDoc, new Point( 10000, 9000 ), + new Size( 10000, 5000 ), + "com.sun.star.drawing.TextShape" ); + XShapes xShapes = UnoRuntime.queryInterface( XShapes.class, xDrawPage ); + xShapes.add( xTextObj ); + ShapeHelper.addPortion( xTextObj, aNameArray[ i ], true ); + } + + /* create two custom shows, one will play slide 6 to 10 and is named "ShortVersion" + the other one will play slide 2 til 10 and is named "LongVersion" */ + XCustomPresentationSupplier xCustPresSupplier = UnoRuntime.queryInterface( XCustomPresentationSupplier.class, xDrawDoc ); + + /* the following container is a container for further container + which concludes the list of pages that are to play within a custom show */ + XNameContainer xNameContainer = xCustPresSupplier.getCustomPresentations(); + XSingleServiceFactory xFactory = UnoRuntime.queryInterface( XSingleServiceFactory.class, xNameContainer ); + + Object xObj; + XIndexContainer xContainer; + + /* instantiate an IndexContainer that will take + a list of draw pages for the first custom show */ + xObj = xFactory.createInstance(); + xContainer = UnoRuntime.queryInterface( XIndexContainer.class, xObj ); + for ( i = 5; i < 10; i++ ) + xContainer.insertByIndex( xContainer.getCount(), xDrawPages.getByIndex( i ) ); + xNameContainer.insertByName( "ShortVersion", xContainer ); + + /* instantiate an IndexContainer that will take + a list of draw page for the second custom show */ + xObj = xFactory.createInstance(); + xContainer = UnoRuntime.queryInterface( XIndexContainer.class, xObj ); + for ( i = 1; i < 10; i++ ) + xContainer.insertByIndex( xContainer.getCount(), xDrawPages.getByIndex( i ) ); + xNameContainer.insertByName( "LongVersion", xContainer ); + + /* which custom show is to use + can been set in the presentation settings */ + + XPresentationSupplier xPresSupplier = UnoRuntime.queryInterface( XPresentationSupplier.class, xDrawDoc ); + XPresentation xPresentation = xPresSupplier.getPresentation(); + XPropertySet xPresPropSet = UnoRuntime.queryInterface( XPropertySet.class, xPresentation ); + xPresPropSet.setPropertyValue( "CustomShow", "ShortVersion" ); + } + catch( Exception ex ) + { + System.out.println( ex ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/DrawViewDemo.java b/odk/examples/DevelopersGuide/Drawing/DrawViewDemo.java new file mode 100644 index 000000000..111915366 --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/DrawViewDemo.java @@ -0,0 +1,142 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; + +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.XPropertySetInfo; + +import com.sun.star.container.XIndexAccess; + +import com.sun.star.document.XViewDataSupplier; + +import com.sun.star.frame.XModel; +import com.sun.star.frame.XController; + + + +// __________ Implementation __________ + +// text demo + +public class DrawViewDemo +{ + public static void main( String args[] ) + { + if ( args.length < 1 ) + { + System.out.println( "usage: DrawViewDemo SourceURL" ); + System.exit(1); + } + + XComponent xComponent = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + java.io.File sourceFile = new java.io.File(args[0]); + StringBuffer sUrl = new StringBuffer("file:///"); + sUrl.append(sourceFile.getCanonicalPath().replace('\\', '/')); + + xComponent = Helper.createDocument( xOfficeContext, + sUrl.toString(), "_blank", 0, + pPropValues ); + XModel xModel = + UnoRuntime.queryInterface( + XModel.class, xComponent ); + + + // print all available properties of first view + System.out.println("*** print all available properties of first view"); + XViewDataSupplier xViewDataSupplier = + UnoRuntime.queryInterface( + XViewDataSupplier.class, xModel ); + XIndexAccess xIndexAccess = xViewDataSupplier.getViewData(); + if ( xIndexAccess.getCount() != 0 ) + { + PropertyValue[] aPropSeq = (PropertyValue[]) + xIndexAccess.getByIndex( 0 ); + + for( int i = 0; i < aPropSeq.length; i++ ) + { + System.out.println( aPropSeq[ i ].Name + " = " + + aPropSeq[ i ].Value ); + } + } + + + // print all properties that are supported by the controller + // and change into masterpage mode + System.out.println("*** print all properties that are supported by the controller"); + XController xController = xModel.getCurrentController(); + XPropertySet xPropSet = + UnoRuntime.queryInterface( + XPropertySet.class, xController ); + XPropertySetInfo xPropSetInfo = xPropSet.getPropertySetInfo(); + Property[] aPropSeq = xPropSetInfo.getProperties(); + for( int i = 0; i < aPropSeq.length; i++ ) + { + System.out.println( aPropSeq[ i ].Name ); + } + System.out.println("*** change into masterpage mode"); + xPropSet.setPropertyValue( "IsMasterPageMode", Boolean.TRUE ); + + } + catch( Exception ex ) + { + System.out.println( ex.getMessage() ); + ex.printStackTrace(System.err); + } + + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/DrawingDemo.java b/odk/examples/DevelopersGuide/Drawing/DrawingDemo.java new file mode 100644 index 000000000..f71197cf6 --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/DrawingDemo.java @@ -0,0 +1,419 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.container.XNamed; + +import com.sun.star.drawing.PolygonFlags; +import com.sun.star.drawing.PolyPolygonBezierCoords; +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XShapeGrouper; +import com.sun.star.drawing.XDrawPage; + +import java.util.Random; + + +// __________ Implementation __________ + +// drawing demo + +// This drawing demo will create/load a document, and show how to +// handle pages and shapes using the Office API, + +// Calling this demo two parameter can be used. The first parameter +// describes if a document is to create or load: "draw" creates a +// draw document, "impress" creates an impress document, any other +// parameter is interpreted as URL and loads the corresponding +// document. ( example for a URL is: "file:///c:/test.odp" ) +// The second parameter is the connection that is to use. If no parameter +// is given a standard impress document is created by using following +// connection: "uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager"; + +public class DrawingDemo +{ + public static void main( String args[] ) + { + XComponent xDrawDoc = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + String sURL; + if ( args.length == 0 ) + sURL = "impress"; + else + sURL = args[ 0 ]; + + if ( sURL.equals( "draw" ) ) + sURL = "private:factory/sdraw"; + else if ( sURL.equals( "impress" ) ) + sURL = "private:factory/simpress"; + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xDrawDoc = Helper.createDocument( xOfficeContext, + sURL, "_blank", 0, pPropValues ); + } + catch( Exception ex ) + { + System.out.println( ex ); + System.exit( 0 ); + } + + + Demo_PageCreation( xDrawDoc, 10 ); + Demo_PageNaming( xDrawDoc, "this page is called: LastPage" ); + Demo_ShapeCreation( xDrawDoc ); + Demo_PolyPolygonBezier( xDrawDoc ); + Demo_Group1( xDrawDoc ); + Demo_Group2( xDrawDoc ); + System.exit( 0 ); + } + + // This method appends draw pages to the document, so that a + // minimum of n draw pages will be available. + // For each second draw page also a new master page is created. + public static void Demo_PageCreation( XComponent xDrawDoc, int n ) + { + try + { + // If the document has less than n draw pages, append them, + // a minimum of n draw pages will be available + int i, nDrawPages; + for ( nDrawPages = PageHelper.getDrawPageCount( xDrawDoc ); + nDrawPages < n; nDrawPages++ ) + PageHelper.insertNewDrawPageByIndex( xDrawDoc, nDrawPages ); + // Create a master page for each second drawpage + int nMasterPages; + for ( nMasterPages = PageHelper.getMasterPageCount( xDrawDoc ); + nMasterPages < ( ( nDrawPages + 1 ) / 2 ); nMasterPages++ ) + PageHelper.insertNewMasterPageByIndex( xDrawDoc, nMasterPages ); + + // Now connect master page 1 to draw page 1 and 2, + // master page 2 to draw page 3 and 4 and so on. + for ( i = 0; i < nDrawPages; i++ ) + { + XDrawPage xDrawPage = PageHelper.getDrawPageByIndex( xDrawDoc, i ); + XDrawPage xMasterPage = PageHelper.getMasterPageByIndex( + xDrawDoc, i / 2 ); + PageHelper.setMasterPage( xDrawPage, xMasterPage ); + } + } + catch( Exception ex ) + { + System.out.println("Demo_PageCreation: I have a page creation problem"); + } + } + + // this method shows how to name a page, this is exemplary + // be done for the last draw page + public static void Demo_PageNaming( + XComponent xDrawDoc, String sLastPageName ) + { + try + { + XDrawPage xLastPage = PageHelper.getDrawPageByIndex( xDrawDoc, + PageHelper.getDrawPageCount( xDrawDoc ) - 1 ); + + // each drawpage is supporting an XNamed interface + XNamed xNamed = UnoRuntime.queryInterface( + XNamed.class, xLastPage ); + + // beware, the page must have a unique name + xNamed.setName( sLastPageName ); + } + catch( Exception ex ) + { + System.out.println( "Demo_PageNaming: can't set page name" ); + } + } + + // This method will add one rectangle shape into the lower left quarter of + // every page that is available, + public static void Demo_ShapeCreation( XComponent xDrawDoc ) + { + try + { + boolean bIsImpressDocument = PageHelper.isImpressDocument( xDrawDoc ); + + int nDrawingPages = PageHelper.getDrawPageCount( xDrawDoc ); + int nMasterPages = PageHelper.getMasterPageCount( xDrawDoc ); + int nGlobalPageCount = nDrawingPages + nMasterPages; + + if ( bIsImpressDocument ) + { + // in impress each draw page also has a notes page + nGlobalPageCount += nDrawingPages; + // for each drawing master is also a notes master available + nGlobalPageCount += nMasterPages; + // one handout is existing + nGlobalPageCount += 1; + } + + // create and fill a container with all draw pages + XDrawPage[] pPages = new XDrawPage[ nGlobalPageCount ]; + int i, nCurrentPageIndex = 0; + + // insert handout page + if ( bIsImpressDocument ) + pPages[ nCurrentPageIndex++ ] = PageHelper.getHandoutMasterPage( + xDrawDoc ); + + // inserting all master pages + for( i = 0; i < nMasterPages; i++ ) + { + XDrawPage xMasterPage = PageHelper.getMasterPageByIndex( + xDrawDoc, i ); + pPages[ nCurrentPageIndex++ ] = xMasterPage; + + // if the document is an impress, get the corresponding notes + // master page + if ( bIsImpressDocument ) + pPages[ nCurrentPageIndex++ ] = PageHelper.getNotesPage( + xMasterPage ); + } + for ( i = 0; i < nDrawingPages; i++ ) + { + XDrawPage xDrawPage = PageHelper.getDrawPageByIndex( xDrawDoc, i ); + pPages[ nCurrentPageIndex++ ] = xDrawPage; + + // if the document is an impress, get the corresponding notes page + if ( bIsImpressDocument ) + pPages[ nCurrentPageIndex++ ] = PageHelper.getNotesPage( + xDrawPage ); + } + + // Now a complete list of pages is available in pPages. + // The following code will insert a rectangle into each page. + for ( i = 0; i < nGlobalPageCount; i++ ) + { + Size aPageSize = PageHelper.getPageSize( pPages[ i ] ); + int nHalfWidth = aPageSize.Width / 2; + int nHalfHeight = aPageSize.Height / 2; + + Random aRndGen = new Random(); + int nRndObjWidth = aRndGen.nextInt( nHalfWidth ); + int nRndObjHeight = aRndGen.nextInt( nHalfHeight ); + + int nRndObjPosX = aRndGen.nextInt( nHalfWidth - nRndObjWidth ); + int nRndObjPosY = aRndGen.nextInt( nHalfHeight - nRndObjHeight ) + + nHalfHeight; + + XShapes xShapes = UnoRuntime.queryInterface( XShapes.class, pPages[ i ] ); + ShapeHelper.createAndInsertShape( xDrawDoc, xShapes, + new Point( nRndObjPosX, nRndObjPosY ), + new Size( nRndObjWidth, nRndObjHeight ), + "com.sun.star.drawing.RectangleShape" ); + } + } + catch( Exception ex ) + { + System.out.println( "Demo_ShapeCreation:" + ex ); + } + } + + // This method will show how to create a PolyPolygonBezier that lies is in the + // topleft quarter of the page and positioned at the back + public static void Demo_PolyPolygonBezier( XComponent xDrawDoc ) + { + try + { + XShape xPolyPolygonBezier = ShapeHelper.createShape( xDrawDoc, + new Point( 0, 0 ), + new Size( 0, 0 ), + "com.sun.star.drawing.ClosedBezierShape" ); + + // the fact that the shape must have been added to the page before + // it is possible to apply changes to the PropertySet, it is a good + // proceeding to add the shape as soon as possible + XDrawPage xDrawPage; + // if possible insert our new shape in the master page + if ( PageHelper.isImpressDocument( xDrawDoc ) ) + xDrawPage = PageHelper.getMasterPageByIndex( xDrawDoc, 0 ); + else + xDrawPage = PageHelper.getDrawPageByIndex( xDrawDoc, 0 ); + XShapes xShapes = UnoRuntime.queryInterface( XShapes.class, xDrawPage ); + xShapes.add( xPolyPolygonBezier ); + + XPropertySet xShapeProperties = UnoRuntime.queryInterface( XPropertySet.class, xPolyPolygonBezier ); + + // get pagesize + XPropertySet xPageProperties = UnoRuntime.queryInterface( XPropertySet.class, xDrawPage ); + int nPageWidth = ((Integer)xPageProperties.getPropertyValue( "Width" )).intValue() / 2; + int nPageHeight = ((Integer)xPageProperties.getPropertyValue( "Height" )).intValue() / 2; + + PolyPolygonBezierCoords aCoords = new PolyPolygonBezierCoords(); + // allocating the outer sequence + int nPolygonCount = 50; + aCoords.Coordinates = new Point[ nPolygonCount ][ ]; + aCoords.Flags = new PolygonFlags[ nPolygonCount ][ ]; + int i, n, nY; + // fill the inner point sequence now + for ( nY = 0, i = 0; i < nPolygonCount; i++, nY += nPageHeight / nPolygonCount ) + { + // create a polygon using two normal and two control points + // allocating the inner sequence + int nPointCount = 8; + Point[] pPolyPoints = new Point[ nPointCount ]; + PolygonFlags[] pPolyFlags = new PolygonFlags[ nPointCount ]; + + for ( n = 0; n < nPointCount; n++ ) + pPolyPoints[ n ] = new Point(); + + pPolyPoints[ 0 ].X = 0; + pPolyPoints[ 0 ].Y = nY; + pPolyFlags[ 0 ] = PolygonFlags.NORMAL; + pPolyPoints[ 1 ].X = nPageWidth / 2; + pPolyPoints[ 1 ].Y = nPageHeight; + pPolyFlags[ 1 ] = PolygonFlags.CONTROL; + pPolyPoints[ 2 ].X = nPageWidth / 2; + pPolyPoints[ 2 ].Y = nPageHeight; + pPolyFlags[ 2 ] = PolygonFlags.CONTROL; + pPolyPoints[ 3 ].X = nPageWidth; + pPolyPoints[ 3 ].Y = nY; + pPolyFlags[ 3 ] = PolygonFlags.NORMAL; + + pPolyPoints[ 4 ].X = nPageWidth - 1000; + pPolyPoints[ 4 ].Y = nY; + pPolyFlags[ 4 ] = PolygonFlags.NORMAL; + pPolyPoints[ 5 ].X = nPageWidth / 2; + pPolyPoints[ 5 ].Y = nPageHeight / 2; + pPolyFlags[ 5 ] = PolygonFlags.CONTROL; + pPolyPoints[ 6 ].X = nPageWidth / 2; + pPolyPoints[ 6 ].Y = nPageHeight / 2; + pPolyFlags[ 6 ] = PolygonFlags.CONTROL; + pPolyPoints[ 7 ].X = 1000; + pPolyPoints[ 7 ].Y = nY; + pPolyFlags[ 7 ] = PolygonFlags.NORMAL; + + aCoords.Coordinates[ i ]= pPolyPoints; + aCoords.Flags[ i ] = pPolyFlags; + } + xShapeProperties.setPropertyValue( "PolyPolygonBezier", aCoords ); + + // move the shape to the back by changing the ZOrder + xShapeProperties.setPropertyValue( "ZOrder", Integer.valueOf( 1 ) ); + } + catch ( Exception ex ) + { + System.out.println( "Demo_PolyPolygonBezier:" + ex ); + } + } + + // This method will create a group containing two ellipses + // the shapes will be added into the top right corner of the first + // draw page + public static void Demo_Group1( XComponent xDrawDoc ) + { + try + { + XShape xGroup = ShapeHelper.createShape( xDrawDoc, + new Point( 0, 0 ), + new Size( 0, 0 ), + "com.sun.star.drawing.GroupShape" ); + + // before it is possible to insert shapes, + // the group must have been added to the page + XDrawPage xDrawPage = PageHelper.getDrawPageByIndex( xDrawDoc, 0 ); + XShapes xShapes = UnoRuntime.queryInterface( XShapes.class, xDrawPage ); + xShapes.add( xGroup ); + + XShapes xShapesGroup = UnoRuntime.queryInterface( XShapes.class, xGroup ); + + Size aPageSize = PageHelper.getPageSize( xDrawPage ); + + int nWidth = 4000; + int nHeight = 2000; + int nPosX = ( aPageSize.Width * 3 ) / 4 - nWidth / 2; + int nPosY1 = 2000; + int nPosY2 = aPageSize.Height / 2 - ( nPosY1 + nHeight ); + XShape xRect1 = ShapeHelper.createShape( xDrawDoc, + new Point( nPosX, nPosY1 ), + new Size( nWidth, nHeight ), + "com.sun.star.drawing.EllipseShape" ); + XShape xRect2 = ShapeHelper.createShape( xDrawDoc, + new Point( nPosX, nPosY2 ), + new Size( nWidth, nHeight ), + "com.sun.star.drawing.EllipseShape" ); + + xShapesGroup.add( xRect1 ); + xShapesGroup.add( xRect2 ); + } + catch ( Exception ex ) + { + System.out.println( "Demo_Group1:" + ex ); + } + } + + // This method will group all available objects on the + // first page. + public static void Demo_Group2( XComponent xDrawDoc ) + { + try + { + XDrawPage xDrawPage = PageHelper.getDrawPageByIndex( xDrawDoc, 0 ); + XShapeGrouper xShapeGrouper = UnoRuntime.queryInterface( XShapeGrouper.class, xDrawPage ); + + XShapes xShapesPage = UnoRuntime.queryInterface( XShapes.class, xDrawPage ); + + xShapeGrouper.group( xShapesPage ); + } + catch ( Exception ex ) + { + System.out.println( "Demo_Group2:" + ex ); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/FillAndLineStyleDemo.java b/odk/examples/DevelopersGuide/Drawing/FillAndLineStyleDemo.java new file mode 100644 index 000000000..1f678b307 --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/FillAndLineStyleDemo.java @@ -0,0 +1,132 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.drawing.LineDash; +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XDrawPage; + +import com.sun.star.awt.Gradient; +import com.sun.star.awt.GradientStyle; +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + + +// __________ Implementation __________ + +// FillStyle and LineStyle demo + +public class FillAndLineStyleDemo +{ + public static void main( String args[] ) + { + XComponent xDrawDoc = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xDrawDoc = Helper.createDocument( xOfficeContext, + "private:factory/sdraw", "_blank", 0, pPropValues ); + + XDrawPage xPage = PageHelper.getDrawPageByIndex( xDrawDoc, 0 ); + + XShape xRectangle = ShapeHelper.createShape( xDrawDoc, + new Point( 0, 0 ), + new Size( 15000, 12000 ), + "com.sun.star.drawing.RectangleShape" ); + + XShapes xShapes = UnoRuntime.queryInterface( XShapes.class, xPage ); + xShapes.add( xRectangle ); + + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xRectangle ); + + /* apply a gradient fill style that goes from top left to bottom + right and is changing its color from green to yellow */ + xPropSet.setPropertyValue( "FillStyle", + com.sun.star.drawing.FillStyle.GRADIENT ); + Gradient aGradient = new Gradient(); + aGradient.Style = GradientStyle.LINEAR; + aGradient.StartColor = 0x00ff00; + aGradient.EndColor = 0xffff00; + aGradient.Angle = 450; + aGradient.Border = 0; + aGradient.XOffset = 0; + aGradient.YOffset = 0; + aGradient.StartIntensity = 100; + aGradient.EndIntensity = 100; + aGradient.StepCount = 10; + xPropSet.setPropertyValue( "FillGradient", aGradient ); + + /* create a blue line with dashes and dots */ + xPropSet.setPropertyValue( "LineStyle", + com.sun.star.drawing.LineStyle.DASH ); + LineDash aLineDash = new LineDash(); + aLineDash.Dots = 3; + aLineDash.DotLen = 150; + aLineDash.Dashes = 3; + aLineDash.DashLen = 300; + aLineDash.Distance = 150; + xPropSet.setPropertyValue( "LineDash", aLineDash ); + xPropSet.setPropertyValue( "LineColor", Integer.valueOf( 0x0000ff ) ); + xPropSet.setPropertyValue( "LineWidth", Integer.valueOf( 200 ) ); + + } + catch( Exception ex ) + { + System.out.println( ex ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/GluePointDemo.java b/odk/examples/DevelopersGuide/Drawing/GluePointDemo.java new file mode 100644 index 000000000..f45ea385a --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/GluePointDemo.java @@ -0,0 +1,182 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.container.XIndexContainer; +import com.sun.star.container.XIdentifierContainer; + +import com.sun.star.drawing.Alignment; +import com.sun.star.drawing.EscapeDirection; +import com.sun.star.drawing.GluePoint2; +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XDrawPage; +import com.sun.star.drawing.XGluePointsSupplier; + + + +// __________ Implementation __________ + +// GluePointDemo + +public class GluePointDemo +{ + public static void main( String args[] ) + { + XComponent xDrawDoc = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xDrawDoc = Helper.createDocument( xOfficeContext, + "private:factory/sdraw", "_blank", 0, pPropValues ); + + + XDrawPage xPage = PageHelper.getDrawPageByIndex( xDrawDoc, 0 ); + XShapes xShapes = UnoRuntime.queryInterface( XShapes.class, xPage ); + + // create two rectangles + XShape xShape1 = ShapeHelper.createShape( xDrawDoc, + new Point( 15000, 1000 ), new Size( 5000, 5000 ), + "com.sun.star.drawing.RectangleShape" ); + + XShape xShape2 = ShapeHelper.createShape( xDrawDoc, + new Point( 2000, 15000 ), new Size( 5000, 5000 ), + "com.sun.star.drawing.EllipseShape" ); + + // and a connector + XShape xConnector = ShapeHelper.createShape( xDrawDoc, + new Point( 0, 0 ), + new Size( 0, 0 ), + "com.sun.star.drawing.ConnectorShape" ); + + xShapes.add( xShape1 ); + xShapes.add( xShape2 ); + xShapes.add( xConnector ); + + XPropertySet xConnectorPropSet = UnoRuntime.queryInterface( XPropertySet.class, xConnector ); + +// Index value of 0 : the shape is connected at the top +// Index value of 1 : the shape is connected at the left +// Index value of 2 : the shape is connected at the bottom +// Index value of 3 : the shape is connected at the right + + int nStartIndex = 3; + int nEndIndex = 1; + + // the "StartPosition" or "EndPosition" property needs not to be set + // if there is a shape to connect + xConnectorPropSet.setPropertyValue( "StartShape", xShape1 ); + xConnectorPropSet.setPropertyValue( "StartGluePointIndex", + Integer.valueOf( nStartIndex ) ); + + xConnectorPropSet.setPropertyValue( "EndShape", xShape2 ); + xConnectorPropSet.setPropertyValue( "EndGluePointIndex", + Integer.valueOf( nEndIndex ) ); + + XGluePointsSupplier xGluePointsSupplier; + XIndexContainer xIndexContainer; + XIdentifierContainer xIdentifierContainer; + + GluePoint2 aGluePoint = new GluePoint2(); + aGluePoint.IsRelative = false; + aGluePoint.PositionAlignment = Alignment.CENTER; + aGluePoint.Escape = EscapeDirection.SMART; + aGluePoint.IsUserDefined = true; + aGluePoint.Position.X = 0; + aGluePoint.Position.Y = 0; + + // create and insert a glue point at shape1 + xGluePointsSupplier = UnoRuntime.queryInterface( XGluePointsSupplier.class, xShape1 ); + xIndexContainer = xGluePointsSupplier.getGluePoints(); + xIdentifierContainer = UnoRuntime.queryInterface( XIdentifierContainer.class, + xIndexContainer ); + int nIndexOfGluePoint1 = xIdentifierContainer.insert( aGluePoint ); + + // create and insert a glue point at shape2 + xGluePointsSupplier = UnoRuntime.queryInterface( XGluePointsSupplier.class, xShape2 ); + xIndexContainer = xGluePointsSupplier.getGluePoints(); + xIdentifierContainer = UnoRuntime.queryInterface( XIdentifierContainer.class, + xIndexContainer ); + int nIndexOfGluePoint2 = xIdentifierContainer.insert( aGluePoint ); + + // create and add a connector + XShape xConnector2 = ShapeHelper.createShape( xDrawDoc, + new Point( 0, 0 ), + new Size( 0, 0 ), + "com.sun.star.drawing.ConnectorShape" ); + xShapes.add( xConnector2 ); + + XPropertySet xConnector2PropSet = UnoRuntime.queryInterface( XPropertySet.class, xConnector2 ); + + xConnector2PropSet.setPropertyValue( "StartShape", xShape1 ); + xConnector2PropSet.setPropertyValue( "StartGluePointIndex", + Integer.valueOf( nIndexOfGluePoint1 ) ); + + xConnector2PropSet.setPropertyValue( "EndShape", xShape2 ); + xConnector2PropSet.setPropertyValue( "EndGluePointIndex", + Integer.valueOf( nIndexOfGluePoint2 ) ); + + + } + catch( Exception ex ) + { + System.out.println( ex ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/GraphicExportDemo.java b/odk/examples/DevelopersGuide/Drawing/GraphicExportDemo.java new file mode 100644 index 000000000..2b8ad77de --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/GraphicExportDemo.java @@ -0,0 +1,148 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; + +import com.sun.star.beans.PropertyValue; + +import com.sun.star.document.XExporter; +import com.sun.star.document.XFilter; + +import com.sun.star.drawing.XDrawPage; + +// __________ Implementation __________ + +// text demo + +public class GraphicExportDemo +{ + public static void main( String args[] ) + { + if ( args.length < 3 ) + { + System.out.println( "usage: GraphicExportDemo SourceURL DestinationURL PageIndexToExport" ); + System.exit(1); + } + + XComponent xComponent = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + java.io.File sourceFile = new java.io.File(args[0]); + StringBuffer sUrl = new StringBuffer("file:///"); + sUrl.append(sourceFile.getCanonicalPath().replace('\\', '/')); + + xComponent = Helper.createDocument( xOfficeContext, + sUrl.toString(), "_blank", 0, + pPropValues ); + + Object GraphicExportFilter = + xOfficeContext.getServiceManager().createInstanceWithContext( + "com.sun.star.drawing.GraphicExportFilter", xOfficeContext); + XExporter xExporter = UnoRuntime.queryInterface( XExporter.class, GraphicExportFilter ); + + PropertyValue aProps[] = new PropertyValue[2]; + aProps[0] = new PropertyValue(); + aProps[0].Name = "MediaType"; + aProps[0].Value = "image/gif"; + + /* some graphics e.g. the Windows Metafile does not have a Media Type, + for this case + aProps[0].Name = "FilterName"; // it is possible to set a FilterName + aProps[0].Value = "WMF"; + */ + java.io.File destFile = new java.io.File(args[1]); + java.net.URL destUrl = destFile.toURI().toURL(); + + aProps[1] = new PropertyValue(); + aProps[1].Name = "URL"; + aProps[1].Value = destUrl.toString();//args[ 1 ]; + + int nPageIndex = Integer.parseInt( args[ 2 ] ); + if ( nPageIndex < PageHelper.getDrawPageCount( xComponent ) && + nPageIndex > 1 ) + { + XDrawPage xPage = PageHelper.getDrawPageByIndex( xComponent, + nPageIndex ); + XComponent xComp = UnoRuntime.queryInterface( XComponent.class, xPage ); + xExporter.setSourceDocument( xComp ); + XFilter xFilter = UnoRuntime.queryInterface( XFilter.class, xExporter ); + xFilter.filter( aProps ); + System.out.println( "*** graphics on page \"" + nPageIndex + + "\" from file \"" + args[0] + + "\" exported under the name \"" + + args[1] + "\" in the local directory" ); + } else + { + System.out.println( "page index not in range" ); + } + + + // close the document + com.sun.star.util.XCloseable xCloseable = UnoRuntime.queryInterface(com.sun.star.util.XCloseable.class, + xComponent); + + if (xCloseable != null ) + xCloseable.close(false); + else + xComponent.dispose(); + + System.out.println("*** document closed!"); + + } + catch( Exception ex ) + { + System.out.println( ex ); + } + + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/Helper.java b/odk/examples/DevelopersGuide/Drawing/Helper.java new file mode 100644 index 000000000..5e5c52d1f --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/Helper.java @@ -0,0 +1,89 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XComponent; +import com.sun.star.frame.XComponentLoader; + +public class Helper +{ + // __________ static helper methods __________ + + /** Connect to an office, if no office is running a new instance is started. + * A new connection is established and the service manager from the running + * office is returned. + */ + public static XComponentContext connect() + throws Exception + { + // get the remote office component context + XComponentContext xOfficeContext = + com.sun.star.comp.helper.Bootstrap.bootstrap(); + + // if connection fails an exception is thrown + System.out.println("Connected to a running office ..."); + + return xOfficeContext; + } + + /** creates and instantiates new document + */ + public static com.sun.star.lang.XComponent createDocument( + com.sun.star.uno.XComponentContext xOfficeContext, + String sURL, String sTargetFrame, int nSearchFlags, + com.sun.star.beans.PropertyValue[] aArgs ) + throws Exception + { + XComponentLoader aLoader = + UnoRuntime.queryInterface( + XComponentLoader.class, + xOfficeContext.getServiceManager().createInstanceWithContext( + "com.sun.star.frame.Desktop", xOfficeContext)); + + XComponent xComponent = + UnoRuntime.queryInterface( + XComponent.class, aLoader.loadComponentFromURL( + sURL, sTargetFrame, nSearchFlags, aArgs ) ); + + if ( xComponent == null ) + throw new Exception( "could not create document: " + sURL ); + return xComponent; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/LayerDemo.java b/odk/examples/DevelopersGuide/Drawing/LayerDemo.java new file mode 100644 index 000000000..4687cdc54 --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/LayerDemo.java @@ -0,0 +1,152 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.container.XNameAccess; + +import com.sun.star.style.ParagraphAdjust; + +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XDrawPage; +import com.sun.star.drawing.XLayer; +import com.sun.star.drawing.XLayerManager; +import com.sun.star.drawing.XLayerSupplier; + + +// __________ Implementation __________ + +// LayerDemo + +public class LayerDemo +{ + public static void main( String args[] ) + { + XComponent xDrawDoc = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xDrawDoc = Helper.createDocument( xOfficeContext, + "private:factory/sdraw", "_blank", 0, pPropValues ); + + + // create two rectangles + XDrawPage xPage = PageHelper.getDrawPageByIndex( xDrawDoc, 0 ); + XShapes xShapes = UnoRuntime.queryInterface( XShapes.class, xPage ); + + XShape xRect1 = ShapeHelper.createShape( xDrawDoc, + new Point( 1000, 1000 ), new Size( 5000, 5000 ), + "com.sun.star.drawing.RectangleShape" ); + + XShape xRect2 = ShapeHelper.createShape( xDrawDoc, + new Point( 1000, 7000 ), new Size( 5000, 5000 ), + "com.sun.star.drawing.RectangleShape" ); + + xShapes.add( xRect1 ); + xShapes.add( xRect2 ); + XPropertySet xTextProp = ShapeHelper.addPortion( xRect2, + "this shape is locked", + false ); + xTextProp.setPropertyValue( "ParaAdjust", ParagraphAdjust.CENTER ); + ShapeHelper.addPortion( xRect2, "and the shape above is not visible", + true ); + ShapeHelper.addPortion( xRect2, + "(switch to the layer view to gain access)", + true ); + + + // query for the XLayerManager + XLayerSupplier xLayerSupplier = UnoRuntime.queryInterface( + XLayerSupplier.class, xDrawDoc ); + XNameAccess xNameAccess = xLayerSupplier.getLayerManager(); + XLayerManager xLayerManager = UnoRuntime.queryInterface( + XLayerManager.class, xNameAccess ); + + // create a layer and set its properties + XPropertySet xLayerPropSet; + XLayer xNotVisibleAndEditable = xLayerManager.insertNewByIndex( + xLayerManager.getCount() ); + + xLayerPropSet = UnoRuntime.queryInterface( + XPropertySet.class, xNotVisibleAndEditable ); + xLayerPropSet.setPropertyValue( "Name", "NotVisibleAndEditable" ); + xLayerPropSet.setPropertyValue( "IsVisible", Boolean.FALSE ); + xLayerPropSet.setPropertyValue( "IsLocked", Boolean.TRUE ); + + // create a second layer + XLayer xNotEditable = xLayerManager.insertNewByIndex( + xLayerManager.getCount() ); + + xLayerPropSet = UnoRuntime.queryInterface( + XPropertySet.class, xNotEditable ); + xLayerPropSet.setPropertyValue( "Name", "NotEditable" ); + xLayerPropSet.setPropertyValue( "IsVisible", Boolean.TRUE ); + xLayerPropSet.setPropertyValue( "IsLocked", Boolean.TRUE ); + + // attach the layer to the rectangles + xLayerManager.attachShapeToLayer( xRect1, xNotVisibleAndEditable ); + xLayerManager.attachShapeToLayer( xRect2, xNotEditable ); + + } + catch( Exception ex ) + { + System.out.println( ex ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/Makefile b/odk/examples/DevelopersGuide/Drawing/Makefile new file mode 100644 index 000000000..e5bbf1bf1 --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/Makefile @@ -0,0 +1,174 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Drawing examples of the Developers Guide. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=DrawingExamples +SAMPLE_CLASS_OUT = $(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT = $(OUT_MISC)/$(SAMPLE_NAME) + +APP1_NAME=ChangeOrderDemo +APP1_JAR=$(SAMPLE_CLASS_OUT)/$(APP1_NAME).jar +APP2_NAME=ControlAndSelectDemo +APP2_JAR=$(SAMPLE_CLASS_OUT)/$(APP2_NAME).jar +APP3_NAME=CustomShowDemo +APP3_JAR=$(SAMPLE_CLASS_OUT)/$(APP3_NAME).jar +APP4_NAME=DrawingDemo +APP4_JAR=$(SAMPLE_CLASS_OUT)/$(APP4_NAME).jar +APP5_NAME=DrawViewDemo +APP5_JAR=$(SAMPLE_CLASS_OUT)/$(APP5_NAME).jar +APP6_NAME=FillAndLineStyleDemo +APP6_JAR=$(SAMPLE_CLASS_OUT)/$(APP6_NAME).jar +APP7_NAME=GluePointDemo +APP7_JAR=$(SAMPLE_CLASS_OUT)/$(APP7_NAME).jar +APP8_NAME=GraphicExportDemo +APP8_JAR=$(SAMPLE_CLASS_OUT)/$(APP8_NAME).jar +APP9_NAME=LayerDemo +APP9_JAR=$(SAMPLE_CLASS_OUT)/$(APP9_NAME).jar +APP10_NAME=ObjectTransformationDemo +APP10_JAR=$(SAMPLE_CLASS_OUT)/$(APP10_NAME).jar +APP11_NAME=Organigram +APP11_JAR=$(SAMPLE_CLASS_OUT)/$(APP11_NAME).jar +APP12_NAME=PresentationDemo +APP12_JAR=$(SAMPLE_CLASS_OUT)/$(APP12_NAME).jar +APP13_NAME=StyleDemo +APP13_JAR=$(SAMPLE_CLASS_OUT)/$(APP13_NAME).jar +APP14_NAME=TextDemo +APP14_JAR=$(SAMPLE_CLASS_OUT)/$(APP14_NAME).jar + +APP_JAVAFILES = \ + Helper.java \ + PageHelper.java \ + ShapeHelper.java + +APP_CLASSFILES = $(patsubst %.java,$(SAMPLE_CLASS_OUT)/%.class,$(APP_JAVAFILES)) +APP_CLASSNAMES = $(patsubst %.java,%.class,$(APP_JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : \ + DrawingExamples + +include $(SETTINGS)/stdtarget.mk + +$(APP_CLASSFILES) : $(APP_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SAMPLE_CLASS_OUT) $(APP_JAVAFILES) + +$(SAMPLE_CLASS_OUT)/%.class : %.java $(APP_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SAMPLE_CLASS_OUT) $< + +$(SAMPLE_CLASS_OUT)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(SAMPLE_CLASS_OUT)/%.jar : $(SAMPLE_CLASS_OUT)/%.mf $(SAMPLE_CLASS_OUT)/%.class $(APP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class $(APP_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP1_JAR) : $(SAMPLE_CLASS_OUT)/$(APP1_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP1_NAME).class +$(APP2_JAR) : $(SAMPLE_CLASS_OUT)/$(APP2_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP2_NAME).class +$(APP3_JAR) : $(SAMPLE_CLASS_OUT)/$(APP3_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP3_NAME).class +$(APP4_JAR) : $(SAMPLE_CLASS_OUT)/$(APP4_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP4_NAME).class +$(APP5_JAR) : $(SAMPLE_CLASS_OUT)/$(APP5_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP5_NAME).class +$(APP6_JAR) : $(SAMPLE_CLASS_OUT)/$(APP6_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP6_NAME).class +$(APP7_JAR) : $(SAMPLE_CLASS_OUT)/$(APP7_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP7_NAME).class +$(APP8_JAR) : $(SAMPLE_CLASS_OUT)/$(APP8_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP8_NAME).class +$(APP9_JAR) : $(SAMPLE_CLASS_OUT)/$(APP9_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP9_NAME).class +$(APP10_JAR) : $(SAMPLE_CLASS_OUT)/$(APP10_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP10_NAME).class +$(APP11_JAR) : $(SAMPLE_CLASS_OUT)/$(APP11_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP11_NAME).class +$(APP12_JAR) : $(SAMPLE_CLASS_OUT)/$(APP12_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP12_NAME).class +$(APP13_JAR) : $(SAMPLE_CLASS_OUT)/$(APP13_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP13_NAME).class +$(APP14_JAR) : $(SAMPLE_CLASS_OUT)/$(APP14_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP14_NAME).class + +DrawingExamples : $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) $(APP4_JAR) $(APP5_JAR) $(APP6_JAR) $(APP7_JAR) $(APP8_JAR) $(APP9_JAR) $(APP10_JAR) $(APP11_JAR) $(APP12_JAR) $(APP13_JAR) $(APP14_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP2_NAME).run + @echo $(MAKE) $(APP3_NAME).run + @echo $(MAKE) $(APP4_NAME).run + @echo $(MAKE) $(APP5_NAME).run + @echo $(MAKE) $(APP6_NAME).run + @echo $(MAKE) $(APP7_NAME).run + @echo $(MAKE) $(APP8_NAME).run + @echo $(MAKE) $(APP9_NAME).run + @echo $(MAKE) $(APP10_NAME).run + @echo $(MAKE) $(APP11_NAME).run + @echo $(MAKE) $(APP12_NAME).run + @echo $(MAKE) $(APP13_NAME).run + @echo $(MAKE) $(APP14_NAME).run + @echo -------- + @echo The $(APP5_NAME) and the $(APP8_NAME) needs parameters. Please use the + @echo following command to start the demo if you do not want the default parameters + @echo specified in the this makefile: + @echo --- $(APP5_NAME) --- + @echo java -Dcom.sun.star.lib.loader.unopath="$(QM)$(OFFICE_PROGRAM_PATH)$(QM)" -jar $(APP5_NAME).jar "$(QM)SourceUrl$(QM)" + @echo --- $(APP8_NAME) --- + @echo java -Dcom.sun.star.lib.loader.unopath="$(QM)$(OFFICE_PROGRAM_PATH)$(QM)" -jar $(APP8_NAME).jar "$(QM)SourceUrl$(QM)" "$(QM)DestinationUrl$(QM)" "$(QM)index$(QM)" + @echo -------------------------------------------------------------------------------- + +%.run: $(SAMPLE_CLASS_OUT)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +$(APP5_NAME).run: $(APP5_JAR) + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< SimplePresentation.odp + +$(APP8_NAME).run: $(APP8_JAR) + -$(MKDIR) $(subst /,$(PS),$(SAMPLE_GEN_OUT)/export) + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< SimplePresentation.odp "$(SAMPLE_GEN_OUT)/export/MyTestExport.gif" 2 + + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) diff --git a/odk/examples/DevelopersGuide/Drawing/ObjectTransformationDemo.java b/odk/examples/DevelopersGuide/Drawing/ObjectTransformationDemo.java new file mode 100644 index 000000000..5bf81e577 --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/ObjectTransformationDemo.java @@ -0,0 +1,131 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XDrawPage; +import com.sun.star.drawing.HomogenMatrix3; + +import java.awt.geom.AffineTransform; + +// __________ Implementation __________ + +// ObjectTransformationDemo + +public class ObjectTransformationDemo +{ + public static void main( String args[] ) + { + XComponent xDrawDoc = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xDrawDoc = Helper.createDocument( xOfficeContext, + "private:factory/simpress", "_blank", 0, pPropValues ); + + XDrawPage xPage = PageHelper.getDrawPageByIndex( xDrawDoc, 0 ); + XPropertySet xPagePropSet= UnoRuntime.queryInterface( XPropertySet.class, xPage ); + + XShapes xShapes = UnoRuntime.queryInterface( XShapes.class, xPage ); + + + XShape xShape = ShapeHelper.createShape( xDrawDoc, + new Point( 0, 0 ), new Size( 10000, 2500 ), + "com.sun.star.drawing.RectangleShape" ); + xShapes.add( xShape ); + + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xShape ); + + HomogenMatrix3 aHomogenMatrix3 = (HomogenMatrix3) + xPropSet.getPropertyValue( "Transformation" ); + + java.awt.geom.AffineTransform aOriginalMatrix = + new java.awt.geom.AffineTransform( + aHomogenMatrix3.Line1.Column1, aHomogenMatrix3.Line2.Column1, + aHomogenMatrix3.Line1.Column2, aHomogenMatrix3.Line2.Column2, + aHomogenMatrix3.Line1.Column3, aHomogenMatrix3.Line2.Column3 ); + + + AffineTransform aNewMatrix1 = new AffineTransform(); + aNewMatrix1.setToRotation( Math.PI /180 * 15 ); + aNewMatrix1.concatenate( aOriginalMatrix ); + + AffineTransform aNewMatrix2 = new AffineTransform(); + aNewMatrix2.setToTranslation( 2000, 2000 ); + aNewMatrix2.concatenate( aNewMatrix1 ); + + double aFlatMatrix[] = new double[ 6 ]; + aNewMatrix2.getMatrix( aFlatMatrix ); + aHomogenMatrix3.Line1.Column1 = aFlatMatrix[ 0 ]; + aHomogenMatrix3.Line2.Column1 = aFlatMatrix[ 1 ]; + aHomogenMatrix3.Line1.Column2 = aFlatMatrix[ 2 ]; + aHomogenMatrix3.Line2.Column2 = aFlatMatrix[ 3 ]; + aHomogenMatrix3.Line1.Column3 = aFlatMatrix[ 4 ]; + aHomogenMatrix3.Line2.Column3 = aFlatMatrix[ 5 ]; + xPropSet.setPropertyValue( "Transformation", aHomogenMatrix3 ); + + + } + catch( Exception ex ) + { + System.out.println( ex ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/Organigram.java b/odk/examples/DevelopersGuide/Drawing/Organigram.java new file mode 100644 index 000000000..5a496086e --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/Organigram.java @@ -0,0 +1,176 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.beans.PropertyValue; +import com.sun.star.frame.XComponentLoader; + +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.XComponentContext; + + +public class Organigram { + + private XComponentContext xRemoteContext = null; + private XMultiComponentFactory xRemoteServiceManager = null; + + /** Creates a new instance of OpenQuery */ + public Organigram() { + } + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + Organigram organigram1 = new Organigram(); + try { + organigram1.drawOrganigram(); + } + catch (java.lang.Exception e){ + e.printStackTrace(); + } + finally { + System.exit(0); + } + } + public void drawOrganigram() throws java.lang.Exception { + // get the remote office component context + xRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + // get the remote service manager + xRemoteServiceManager = xRemoteContext.getServiceManager(); + + Object desktop = xRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", xRemoteContext); + XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, desktop); + + PropertyValue[] loadProps = new PropertyValue[0]; + XComponent xDrawComponent = xComponentLoader.loadComponentFromURL( + "private:factory/sdraw", "_blank", 0, loadProps); + + // get draw page by index + com.sun.star.drawing.XDrawPagesSupplier xDrawPagesSupplier = + UnoRuntime.queryInterface( + com.sun.star.drawing.XDrawPagesSupplier.class, xDrawComponent ); + com.sun.star.drawing.XDrawPages xDrawPages = + xDrawPagesSupplier.getDrawPages(); + Object drawPage = xDrawPages.getByIndex(0); + com.sun.star.drawing.XDrawPage xDrawPage = UnoRuntime.queryInterface(com.sun.star.drawing.XDrawPage.class, + drawPage); + + com.sun.star.lang.XMultiServiceFactory xDocumentFactory = + UnoRuntime.queryInterface( + com.sun.star.lang.XMultiServiceFactory.class, xDrawComponent); + + com.sun.star.beans.XPropertySet xPageProps = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xDrawPage); + + int pageWidth = AnyConverter.toInt(xPageProps.getPropertyValue("Width")); + int pageHeight = AnyConverter.toInt(xPageProps.getPropertyValue("Height")); + int pageBorderTop = AnyConverter.toInt(xPageProps.getPropertyValue("BorderTop")); + int pageBorderLeft = AnyConverter.toInt(xPageProps.getPropertyValue("BorderLeft")); + int pageBorderRight = AnyConverter.toInt(xPageProps.getPropertyValue("BorderRight")); + int drawWidth = pageWidth - pageBorderLeft - pageBorderRight; + int horCenter = pageBorderLeft + drawWidth / 2; + + String[][] orgUnits = new String[2][4]; + orgUnits[0][0] = "Management"; + orgUnits[1][0] = "Production"; + orgUnits[1][1] = "Purchasing"; + orgUnits[1][2] = "IT Services"; + orgUnits[1][3] = "Sales"; + int[] levelCount = {1, 4}; + + int horSpace = 300; + int verSpace = 3000; + + int shapeWidth = (drawWidth - (levelCount[1] - 1) * horSpace) / levelCount[1]; + int shapeHeight = pageHeight / 20; + int shapeX = pageWidth / 2 - shapeWidth / 2; + int shapeY = pageBorderTop; + + int levelY; + int levelX; + + com.sun.star.drawing.XShape xStartShape = null; + + for (int level = 0; level <= 1; level++) { + levelY = pageBorderTop + 2000 + level * (shapeHeight + verSpace); + for (int i = levelCount[level] - 1; i > -1; i--) { + shapeX = horCenter - (levelCount[level] * shapeWidth + + (levelCount[level] - 1) * horSpace) / 2 + + i * shapeWidth + i * horSpace; + Object shape = xDocumentFactory.createInstance("com.sun.star.drawing.RectangleShape"); + com.sun.star.drawing.XShape xShape = UnoRuntime.queryInterface( + com.sun.star.drawing.XShape.class, shape); + xShape.setPosition(new com.sun.star.awt.Point(shapeX, levelY)); + xShape.setSize(new com.sun.star.awt.Size(shapeWidth, shapeHeight)); + xDrawPage.add(xShape); + + com.sun.star.text.XText xText = UnoRuntime.queryInterface( + com.sun.star.text.XText.class, xShape); + + xText.setString(orgUnits[level][i]); + + // memorize the root shape + if (level == 0 && i == 0) + xStartShape = xShape; + + if (level == 1) { + Object connector = xDocumentFactory.createInstance("com.sun.star.drawing.ConnectorShape"); + com.sun.star.beans.XPropertySet xConnectorProps = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, connector); + com.sun.star.drawing.XShape xConnector = + UnoRuntime.queryInterface( + com.sun.star.drawing.XShape.class, connector); + xDrawPage.add(xConnector); + xConnectorProps.setPropertyValue("StartShape", xStartShape); + xConnectorProps.setPropertyValue("EndShape", xShape); + xConnectorProps.setPropertyValue("StartGluePointIndex", + Integer.valueOf(2)); // 2 = bottom glue point + xConnectorProps.setPropertyValue("EndGluePointIndex", + Integer.valueOf(0)); // 0 = top glue point + } + } + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/PageHelper.java b/odk/examples/DevelopersGuide/Drawing/PageHelper.java new file mode 100644 index 000000000..9e8cfa295 --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/PageHelper.java @@ -0,0 +1,199 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XServiceInfo; + +import com.sun.star.awt.Size; + +import com.sun.star.beans.XPropertySet; + +import com.sun.star.drawing.XDrawPage; +import com.sun.star.drawing.XDrawPages; +import com.sun.star.drawing.XDrawPagesSupplier; +import com.sun.star.drawing.XMasterPageTarget; +import com.sun.star.drawing.XMasterPagesSupplier; + +import com.sun.star.presentation.XPresentationPage; +import com.sun.star.presentation.XHandoutMasterSupplier; + + +public class PageHelper +{ + // __________ static helper methods __________ + + // __________ draw pages __________ + + /** get the page count for standard pages + */ + public static int getDrawPageCount( XComponent xComponent ) + { + XDrawPagesSupplier xDrawPagesSupplier = + UnoRuntime.queryInterface( + XDrawPagesSupplier.class, xComponent ); + XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages(); + return xDrawPages.getCount(); + } + + /** get draw page by index + */ + public static XDrawPage getDrawPageByIndex( XComponent xComponent, int nIndex ) + throws com.sun.star.lang.IndexOutOfBoundsException, + com.sun.star.lang.WrappedTargetException + { + XDrawPagesSupplier xDrawPagesSupplier = + UnoRuntime.queryInterface( + XDrawPagesSupplier.class, xComponent ); + XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages(); + return UnoRuntime.queryInterface(XDrawPage.class, xDrawPages.getByIndex( nIndex )); + } + + /** creates and inserts a draw page into the giving position, + the method returns the new created page + */ + public static XDrawPage insertNewDrawPageByIndex( XComponent xComponent, int nIndex ) + throws Exception + { + XDrawPagesSupplier xDrawPagesSupplier = + UnoRuntime.queryInterface( + XDrawPagesSupplier.class, xComponent ); + XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages(); + return xDrawPages.insertNewByIndex( nIndex ); + } + + + + /** get size of the given page + */ + public static Size getPageSize( XDrawPage xDrawPage ) + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.lang.WrappedTargetException + { + XPropertySet xPageProperties = UnoRuntime.queryInterface( XPropertySet.class, xDrawPage ); + return new Size( + ((Integer)xPageProperties.getPropertyValue( "Width" )).intValue(), + ((Integer)xPageProperties.getPropertyValue( "Height" )).intValue() ); + } + + // __________ master pages __________ + + /** get the page count for master pages + */ + public static int getMasterPageCount( XComponent xComponent ) + { + XMasterPagesSupplier xMasterPagesSupplier = + UnoRuntime.queryInterface( + XMasterPagesSupplier.class, xComponent ); + XDrawPages xDrawPages = xMasterPagesSupplier.getMasterPages(); + return xDrawPages.getCount(); + } + + /** get master page by index + */ + public static XDrawPage getMasterPageByIndex( XComponent xComponent, int nIndex ) + throws com.sun.star.lang.IndexOutOfBoundsException, + com.sun.star.lang.WrappedTargetException + { + XMasterPagesSupplier xMasterPagesSupplier = + UnoRuntime.queryInterface( + XMasterPagesSupplier.class, xComponent ); + XDrawPages xDrawPages = xMasterPagesSupplier.getMasterPages(); + return UnoRuntime.queryInterface(XDrawPage.class, xDrawPages.getByIndex( nIndex )); + } + + /** creates and inserts a new master page into the giving position, + the method returns the new created page + */ + public static XDrawPage insertNewMasterPageByIndex( XComponent xComponent, int nIndex ) + { + XMasterPagesSupplier xMasterPagesSupplier = + UnoRuntime.queryInterface( + XMasterPagesSupplier.class, xComponent ); + XDrawPages xDrawPages = xMasterPagesSupplier.getMasterPages(); + return xDrawPages.insertNewByIndex( nIndex ); + } + + + + + + /** sets given masterpage at the drawpage + */ + public static void setMasterPage( XDrawPage xDrawPage, XDrawPage xMasterPage ) + { + XMasterPageTarget xMasterPageTarget = + UnoRuntime.queryInterface( + XMasterPageTarget.class, xDrawPage ); + xMasterPageTarget.setMasterPage( xMasterPage ); + } + + // __________ presentation pages __________ + + /** test if a Presentation Document is supported. + This is important, because only presentation documents + have notes and handout pages + */ + public static boolean isImpressDocument( XComponent xComponent ) + { + XServiceInfo xInfo = UnoRuntime.queryInterface( + XServiceInfo.class, xComponent ); + return xInfo.supportsService( "com.sun.star.presentation.PresentationDocument" ); + } + + /** in impress documents each normal draw page has a corresponding notes page + */ + public static XDrawPage getNotesPage( XDrawPage xDrawPage ) + { + XPresentationPage aPresentationPage = + UnoRuntime.queryInterface( + XPresentationPage.class, xDrawPage ); + return aPresentationPage.getNotesPage(); + } + + /** in impress each documents has one handout page + */ + public static XDrawPage getHandoutMasterPage( XComponent xComponent ) + { + XHandoutMasterSupplier aHandoutMasterSupplier = + UnoRuntime.queryInterface( + XHandoutMasterSupplier.class, xComponent ); + return aHandoutMasterSupplier.getHandoutMasterPage(); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/PresentationDemo.java b/odk/examples/DevelopersGuide/Drawing/PresentationDemo.java new file mode 100644 index 000000000..06b5bc4b1 --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/PresentationDemo.java @@ -0,0 +1,232 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XServiceInfo; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.container.XNamed; + +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XDrawPage; + +import com.sun.star.presentation.XPresentation; +import com.sun.star.presentation.XPresentationSupplier; + + + +// __________ Implementation __________ + +// presentation demo + +// This demo will demonstrate how to create a presentation using the Office API + +// The first parameter describes the connection that is to use. If there is no parameter +// "uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" is used. + + +public class PresentationDemo +{ + public static void main( String args[] ) + { + XComponent xDrawDoc = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xDrawDoc = Helper.createDocument( xOfficeContext, + "private:factory/simpress", "_blank", 0, pPropValues ); + + + XDrawPage xPage; + XShapes xShapes; + XPropertySet xShapePropSet; + + // create pages, so that three are available + while ( PageHelper.getDrawPageCount( xDrawDoc ) < 3 ) + PageHelper.insertNewDrawPageByIndex( xDrawDoc, 0 ); + + + // set the slide transition for the first page + xPage = PageHelper.getDrawPageByIndex( xDrawDoc, 0 ); + xShapes = UnoRuntime.queryInterface( XShapes.class, xPage ); + // set slide transition effect + setSlideTransition( xPage, + com.sun.star.presentation.FadeEffect.FADE_FROM_RIGHT, + com.sun.star.presentation.AnimationSpeed.FAST, + 1, 0 ); // automatic object and slide transition + + // create a rectangle that is placed on the top left of the page + xShapePropSet = ShapeHelper.createAndInsertShape( xDrawDoc, + xShapes,new Point( 1000, 1000 ), new Size( 5000, 5000 ), + "com.sun.star.drawing.RectangleShape" ); + xShapePropSet.setPropertyValue("Effect", + com.sun.star.presentation.AnimationEffect.WAVYLINE_FROM_BOTTOM ); + + /* the following three properties provokes that the shape is dimmed + to red + after the animation has been finished */ + xShapePropSet.setPropertyValue( "DimHide", Boolean.FALSE ); + xShapePropSet.setPropertyValue( "DimPrevious", Boolean.TRUE ); + xShapePropSet.setPropertyValue( "DimColor", Integer.valueOf( 0xff0000 ) ); + + + // set the slide transition for the second page + xPage = PageHelper.getDrawPageByIndex( xDrawDoc, 1 ); + xShapes = UnoRuntime.queryInterface( XShapes.class, xPage ); + setSlideTransition( xPage, + com.sun.star.presentation.FadeEffect.FADE_FROM_RIGHT, + com.sun.star.presentation.AnimationSpeed.SLOW, + 1, 0 ); // automatic object and slide transition + + // create an ellipse that is placed on the bottom right of second page + xShapePropSet = ShapeHelper.createAndInsertShape( xDrawDoc, + xShapes, new Point( 21000, 15000 ), new Size( 5000, 5000 ), + "com.sun.star.drawing.EllipseShape" ); + xShapePropSet.setPropertyValue( + "Effect", com.sun.star.presentation.AnimationEffect.HIDE ); + + + // create two objects for the third page + // clicking the first object lets the presentation jump + // to page one by using ClickAction.FIRSTPAGE, + // the second object lets the presentation jump to page two + // by using a ClickAction.BOOKMARK; + xPage = PageHelper.getDrawPageByIndex( xDrawDoc, 2 ); + xShapes = UnoRuntime.queryInterface( XShapes.class, xPage ); + setSlideTransition( xPage, + com.sun.star.presentation.FadeEffect.ROLL_FROM_LEFT, + com.sun.star.presentation.AnimationSpeed.MEDIUM, + 2, 0 ); + XShape xShape = ShapeHelper.createShape( xDrawDoc, + new Point( 1000, 8000 ), new Size( 5000, 5000 ), + "com.sun.star.drawing.EllipseShape" ); + xShapes.add( xShape ); + ShapeHelper.addPortion( xShape, "click to go", false ); + ShapeHelper.addPortion( xShape, "to first page", true ); + xShapePropSet = UnoRuntime.queryInterface( XPropertySet.class, xShape ); + xShapePropSet.setPropertyValue("Effect", + com.sun.star.presentation.AnimationEffect.FADE_FROM_BOTTOM ); + xShapePropSet.setPropertyValue( + "OnClick", com.sun.star.presentation.ClickAction.FIRSTPAGE ); + + + xShape = ShapeHelper.createShape( xDrawDoc, + new Point( 22000, 8000 ), new Size( 5000, 5000 ), + "com.sun.star.drawing.RectangleShape" ); + xShapes.add( xShape ); + ShapeHelper.addPortion( xShape, "click to go", false ); + ShapeHelper.addPortion( xShape, "to the second page", true ); + xShapePropSet = UnoRuntime.queryInterface( XPropertySet.class, xShape ); + xShapePropSet.setPropertyValue("Effect", + com.sun.star.presentation.AnimationEffect.FADE_FROM_BOTTOM ); + + xShapePropSet.setPropertyValue( + "OnClick", com.sun.star.presentation.ClickAction.BOOKMARK ); + // set the name of page two, and use it with the bookmark action + XNamed xPageName = UnoRuntime.queryInterface( + XNamed.class, PageHelper.getDrawPageByIndex( xDrawDoc, 1 ) ); + xPageName.setName( "page two" ); + xShapePropSet.setPropertyValue( + "Bookmark", xPageName.getName() ); + + + /* start an endless presentation which is displayed in + full-screen mode and placed on top */ + + XPresentationSupplier xPresSupplier = UnoRuntime.queryInterface( XPresentationSupplier.class, xDrawDoc ); + XPresentation xPresentation = xPresSupplier.getPresentation(); + XPropertySet xPresPropSet = UnoRuntime.queryInterface( XPropertySet.class, xPresentation ); + xPresPropSet.setPropertyValue( "IsEndless", Boolean.TRUE ); + xPresPropSet.setPropertyValue( "IsAlwaysOnTop", Boolean.TRUE ); + xPresPropSet.setPropertyValue( "Pause", Integer.valueOf( 0 ) ); + xPresentation.start(); + } + catch( Exception ex ) + { + System.out.println( ex ); + } + System.exit( 0 ); + } + + // this simple method applies the slide transition to a page + public static void setSlideTransition( XDrawPage xPage, + com.sun.star.presentation.FadeEffect eEffect, + com.sun.star.presentation.AnimationSpeed eSpeed, + int nChange, + int nDuration ) + { + // the following test is only sensible if you do not exactly know + // what type of page xPage is, for this purpose it can been tested + // if the com.sun.star.presentation.DrawPage service is supported + XServiceInfo xInfo = UnoRuntime.queryInterface( + XServiceInfo.class, xPage ); + if ( xInfo.supportsService( "com.sun.star.presentation.DrawPage" ) ) + { + try + { + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xPage ); + xPropSet.setPropertyValue( "Effect", eEffect ); + xPropSet.setPropertyValue( "Speed", eSpeed ); + xPropSet.setPropertyValue( "Change", Integer.valueOf( nChange ) ); + xPropSet.setPropertyValue( "Duration", Integer.valueOf( nDuration ) ); + } + catch( Exception ex ) + { + } + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/ShapeHelper.java b/odk/examples/DevelopersGuide/Drawing/ShapeHelper.java new file mode 100644 index 000000000..44b9b28a7 --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/ShapeHelper.java @@ -0,0 +1,142 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiServiceFactory; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +import com.sun.star.beans.XPropertySet; + +import com.sun.star.container.XEnumeration; +import com.sun.star.container.XEnumerationAccess; + +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; + +import com.sun.star.text.ControlCharacter; +import com.sun.star.text.XText; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextRange; + + +public class ShapeHelper +{ + // __________ static helper methods __________ + + public static XPropertySet createAndInsertShape( XComponent xDrawDoc, + XShapes xShapes, Point aPos, Size aSize, String sShapeType ) + throws java.lang.Exception + { + XShape xShape = createShape( xDrawDoc, aPos, aSize, sShapeType ); + xShapes.add( xShape ); + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xShape ); + return xPropSet; + } + + /** create a Shape + */ + public static XShape createShape( XComponent xDrawDoc, + Point aPos, Size aSize, String sShapeType ) + throws java.lang.Exception + { + XShape xShape = null; + XMultiServiceFactory xFactory = + UnoRuntime.queryInterface( + XMultiServiceFactory.class, xDrawDoc ); + Object xObj = xFactory.createInstance( sShapeType ); + xShape = UnoRuntime.queryInterface( + XShape.class, xObj ); + xShape.setPosition( aPos ); + xShape.setSize( aSize ); + return xShape; + } + + /** + add text to a shape. the return value is the PropertySet + of the text range that has been added + */ + public static XPropertySet addPortion( XShape xShape, String sText, boolean bNewParagraph ) + throws com.sun.star.lang.IllegalArgumentException + { + XText xText = UnoRuntime.queryInterface( XText.class, xShape ); + + XTextCursor xTextCursor = xText.createTextCursor(); + xTextCursor.gotoEnd( false ); + if ( bNewParagraph == true ) + { + xText.insertControlCharacter( xTextCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + xTextCursor.gotoEnd( false ); + } + XTextRange xTextRange = UnoRuntime.queryInterface( XTextRange.class, xTextCursor ); + xTextRange.setString( sText ); + xTextCursor.gotoEnd( true ); + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xTextRange ); + return xPropSet; + } + + public static void setPropertyForLastParagraph( XShape xText, String sPropName, + Object aValue ) + throws com.sun.star.beans.UnknownPropertyException, + com.sun.star.beans.PropertyVetoException, + com.sun.star.lang.IllegalArgumentException, + com.sun.star.lang.WrappedTargetException, + com.sun.star.container.NoSuchElementException + { + XEnumerationAccess xEnumerationAccess = UnoRuntime.queryInterface( XEnumerationAccess.class, xText ); + if ( xEnumerationAccess.hasElements() ) + { + XEnumeration xEnumeration = xEnumerationAccess.createEnumeration(); + while( xEnumeration.hasMoreElements () ) + { + Object xObj = xEnumeration.nextElement(); + if ( xEnumeration.hasMoreElements() == false ) + { + XTextContent xTextContent = UnoRuntime.queryInterface( + XTextContent.class, xObj ); + XPropertySet xParaPropSet = UnoRuntime.queryInterface( XPropertySet.class, xTextContent ); + xParaPropSet.setPropertyValue( sPropName, aValue ); + } + } + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/SimplePresentation.odp b/odk/examples/DevelopersGuide/Drawing/SimplePresentation.odp new file mode 100644 index 000000000..3f40f7660 Binary files /dev/null and b/odk/examples/DevelopersGuide/Drawing/SimplePresentation.odp differ diff --git a/odk/examples/DevelopersGuide/Drawing/StyleDemo.java b/odk/examples/DevelopersGuide/Drawing/StyleDemo.java new file mode 100644 index 000000000..3f9b083be --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/StyleDemo.java @@ -0,0 +1,164 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.XPropertySetInfo; + +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XDrawPage; +import com.sun.star.drawing.XDrawPages; +import com.sun.star.drawing.XDrawPagesSupplier; + +import com.sun.star.frame.XModel; + + + +// __________ Implementation __________ + +// StyleDemo + +public class StyleDemo +{ + public static void main( String args[] ) + { + XComponent xComponent = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xComponent = Helper.createDocument( xOfficeContext, + "private:factory/simpress", "_blank", 0, pPropValues ); + + + + + /* The first part of this demo will set each "CharColor" Property + that is available within the styles of the document to red. It + will also print each family and style name to the standard output */ + XModel xModel = + UnoRuntime.queryInterface( + XModel.class, xComponent ); + com.sun.star.style.XStyleFamiliesSupplier xSFS = + UnoRuntime.queryInterface( + com.sun.star.style.XStyleFamiliesSupplier.class, xModel ); + + com.sun.star.container.XNameAccess xFamilies = xSFS.getStyleFamilies(); + + // the element should now contain at least two Styles. The first is + // "graphics" and the other one is the name of the Master page + String[] Families = xFamilies.getElementNames(); + for ( int i = 0; i < Families.length; i++ ) + { + // this is the family + System.out.println( "\n" + Families[ i ] ); + + // and now all available styles + Object aFamilyObj = xFamilies.getByName( Families[ i ] ); + com.sun.star.container.XNameAccess xStyles = + UnoRuntime.queryInterface( + com.sun.star.container.XNameAccess.class, aFamilyObj ); + String[] Styles = xStyles.getElementNames(); + for( int j = 0; j < Styles.length; j++ ) + { + System.out.println( " " + Styles[ j ] ); + Object aStyleObj = xStyles.getByName( Styles[ j ] ); + com.sun.star.style.XStyle xStyle = UnoRuntime.queryInterface( + com.sun.star.style.XStyle.class, aStyleObj ); + // now we have the XStyle Interface and the CharColor for + // all styles is exemplary be set to red. + XPropertySet xStylePropSet = UnoRuntime.queryInterface( XPropertySet.class, xStyle ); + XPropertySetInfo xStylePropSetInfo = + xStylePropSet.getPropertySetInfo(); + if ( xStylePropSetInfo.hasPropertyByName( "CharColor" ) ) + { + xStylePropSet.setPropertyValue( "CharColor", + Integer.valueOf( 0xff0000 ) ); + } + } + } + + + + /* now create a rectangle and apply the "title1" style of + the "graphics" family */ + + Object obj = xFamilies.getByName( "graphics" ); + com.sun.star.container.XNameAccess xStyles = UnoRuntime.queryInterface(com.sun.star.container.XNameAccess.class, + obj ); + obj = xStyles.getByName( "title1" ); + com.sun.star.style.XStyle xTitle1Style = UnoRuntime.queryInterface( com.sun.star.style.XStyle.class, obj ); + + XDrawPagesSupplier xDrawPagesSupplier = UnoRuntime.queryInterface( XDrawPagesSupplier.class, xComponent ); + XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages(); + XDrawPage xDrawPage = UnoRuntime.queryInterface( + XDrawPage.class, xDrawPages.getByIndex( 0 )); + XShapes xShapes = UnoRuntime.queryInterface(XShapes.class, + xDrawPage ); + XShape xShape = ShapeHelper.createShape( xComponent, new Point( 0, 0 ), + new Size( 5000, 5000 ), "com.sun.star.drawing.RectangleShape" ); + xShapes.add( xShape ); + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xShape ); + xPropSet.setPropertyValue( "Style", xTitle1Style ); + + } + catch( Exception ex ) + { + System.out.println( ex ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Drawing/TextDemo.java b/odk/examples/DevelopersGuide/Drawing/TextDemo.java new file mode 100644 index 000000000..c03075c7d --- /dev/null +++ b/odk/examples/DevelopersGuide/Drawing/TextDemo.java @@ -0,0 +1,153 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.lang.XComponent; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.drawing.XDrawPage; +import com.sun.star.drawing.TextFitToSizeType; + +import com.sun.star.style.LineSpacing; +import com.sun.star.style.LineSpacingMode; +import com.sun.star.style.ParagraphAdjust; + + + +// __________ Implementation __________ + +// text demo + +public class TextDemo +{ + public static void main( String args[] ) + { + XComponent xDrawDoc = null; + try + { + // get the remote office context of a running office (a new office + // instance is started if necessary) + com.sun.star.uno.XComponentContext xOfficeContext = Helper.connect(); + + // suppress Presentation Autopilot when opening the document + // properties are the same as described for + // com.sun.star.document.MediaDescriptor + PropertyValue[] pPropValues = new PropertyValue[ 1 ]; + pPropValues[ 0 ] = new PropertyValue(); + pPropValues[ 0 ].Name = "Silent"; + pPropValues[ 0 ].Value = Boolean.TRUE; + + xDrawDoc = Helper.createDocument( xOfficeContext, + "private:factory/sdraw", "_blank", 0, pPropValues ); + + XDrawPage xPage = PageHelper.getDrawPageByIndex( xDrawDoc, 0 ); + XShapes xShapes = UnoRuntime.queryInterface( XShapes.class, xPage ); + + + XShape xRectangle; + XPropertySet xTextPropSet, xShapePropSet; + LineSpacing aLineSpacing = new LineSpacing(); + aLineSpacing.Mode = LineSpacingMode.PROP; + + + + // first shape + xRectangle = ShapeHelper.createShape( xDrawDoc, + new Point( 0, 0 ), + new Size( 15000, 7500 ), + "com.sun.star.drawing.RectangleShape" ); + xShapes.add( xRectangle ); + xShapePropSet = UnoRuntime.queryInterface( XPropertySet.class, xRectangle ); + + + // first paragraph + xTextPropSet = ShapeHelper.addPortion( xRectangle, "Portion1", false ); + xTextPropSet.setPropertyValue( "CharColor", Integer.valueOf( 0xff0000 ) ); + xTextPropSet = ShapeHelper.addPortion( xRectangle, "Portion2", false ); + xTextPropSet.setPropertyValue( "CharColor", Integer.valueOf( 0x8080ff ) ); + aLineSpacing.Height = 100; + ShapeHelper.setPropertyForLastParagraph( xRectangle, "ParaLineSpacing", + aLineSpacing ); + + // second paragraph + xTextPropSet = ShapeHelper.addPortion( xRectangle, "Portion3", true ); + xTextPropSet.setPropertyValue( "CharColor", Integer.valueOf( 0xff ) ); + aLineSpacing.Height = 200; + ShapeHelper.setPropertyForLastParagraph( xRectangle, "ParaLineSpacing", + aLineSpacing ); + + + + // second shape + xRectangle = ShapeHelper.createShape( xDrawDoc, + new Point( 0, 10000 ), + new Size( 21000, 12500 ), + "com.sun.star.drawing.RectangleShape" ); + xShapes.add( xRectangle ); + xShapePropSet = UnoRuntime.queryInterface( XPropertySet.class, xRectangle ); + xShapePropSet.setPropertyValue( "TextFitToSize", + TextFitToSizeType.PROPORTIONAL ); + xShapePropSet.setPropertyValue( "TextLeftDistance", Integer.valueOf(2500)); + xShapePropSet.setPropertyValue( "TextRightDistance", Integer.valueOf(2500)); + xShapePropSet.setPropertyValue( "TextUpperDistance", Integer.valueOf(2500)); + xShapePropSet.setPropertyValue( "TextLowerDistance", Integer.valueOf(2500)); + xTextPropSet = ShapeHelper.addPortion( xRectangle, + "using TextFitToSize", false ); + xTextPropSet.setPropertyValue( "ParaAdjust", ParagraphAdjust.CENTER ); + xTextPropSet.setPropertyValue( "CharColor", Integer.valueOf(0xff00)); + xTextPropSet = ShapeHelper.addPortion(xRectangle, + "and a Border distance of 2,5 cm", + true ); + xTextPropSet.setPropertyValue( "CharColor", Integer.valueOf( 0xff0000 ) ); + + } + catch( Exception ex ) + { + System.out.println( ex ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/Addons.xcu b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/Addons.xcu new file mode 100644 index 000000000..2cae63627 --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/Addons.xcu @@ -0,0 +1,68 @@ + + + + + + + + + Foo E~xtension + + + + + vnd.sun.star.script:DialogWithHelp.Module1.main?language=Basic&location=application + + + + + + _self + + + + Start Foo Dialog... + + + + + + + + + + + + vnd.sun.star.script:DialogWithHelp.Module1.main?language=Basic&location=application + + + Foo Toolbar Item + Foo Toolbar Eintrag + + + _self + + + com.sun.star.text.TextDocument + + + + + + diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/Dialog1.xdl b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/Dialog1.xdl new file mode 100644 index 000000000..90fc473ad --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/Dialog1.xdl @@ -0,0 +1,27 @@ + + + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/Module1.xba b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/Module1.xba new file mode 100644 index 000000000..976a0e59f --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/Module1.xba @@ -0,0 +1,33 @@ + + + +REM ***** BASIC ***** + +Sub Main + DialogLibraries.loadLibrary( "DialogWithHelp" ) + oDlg = CreateUnoDialog( DialogLibraries.DialogWithHelp.Dialog1 ) + oDlg.execute() +End Sub + +Sub HandleDoIt + msgbox "I did it!" +End Sub + + + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/dialog.xlb b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/dialog.xlb new file mode 100644 index 000000000..bd7d00efd --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/dialog.xlb @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/script.xlb b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/script.xlb new file mode 100644 index 000000000..423177601 --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/DialogWithHelp/script.xlb @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/META-INF/manifest.xml b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/META-INF/manifest.xml new file mode 100644 index 000000000..bdf108308 --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/META-INF/manifest.xml @@ -0,0 +1,23 @@ + + + + + + + diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/Makefile b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/Makefile new file mode 100644 index 000000000..171dd5393 --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/Makefile @@ -0,0 +1,117 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the DialogWithHelp example of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=ExtDialogWithHelp +SAMPLE_GEN_OUT=$(OUT_MISC)/$(SAMPLE_NAME) + +COMP_NAME=DialogWithHelp +COMP_GEN_OUT=$(SAMPLE_GEN_OUT)/$(COMP_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_UNOPKG_MANIFEST = $(COMP_GEN_OUT)/META-INF/manifest.xml +COMP_REGISTERFLAG=$(COMP_GEN_OUT)$(PS)devguide_basic_$(COMP_NAME)_register_component.flag + +COMP_LIBRARY_FILES=\ + DialogWithHelp/dialog.xlb\ + DialogWithHelp/script.xlb\ + DialogWithHelp/Module1.xba\ + DialogWithHelp/Dialog1.xdl + +COMP_MISC_FILES=\ + META-INF/manifest.xml\ + Addons.xcu\ + description.xml + +COMP_HELP_FILES=\ + help/de/com.foocorp.foo-ext/page1.xhp\ + help/de/com.foocorp.foo-ext/page2.xhp\ + help/de/com.foocorp.foo-ext/subfolder/anotherpage.xhp\ + help/en/com.foocorp.foo-ext/page1.xhp\ + help/en/com.foocorp.foo-ext/page2.xhp\ + help/en/com.foocorp.foo-ext/subfolder/anotherpage.xhp\ + +# Targets +.PHONY: ALL +ALL : $(SAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_LIBRARY_FILES) $(COMP_MISC_FILES) $(COMP_HELP_FILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ $(COMP_LIBRARY_FILES) + $(SDK_ZIP) $@ $(COMP_MISC_FILES) + $(SDK_ZIP) $@ $(COMP_HELP_FILES) + +$(COMP_REGISTERFLAG) : $(COMP_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(COMP_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(SAMPLE_NAME) : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The "$(QM)DialogWithHelp$(QM)" library was installed in your office installation + @echo if SDK_AUTO_DEPLOYMENT = YES. You can use it in the BASIC IDE as a normal + @echo Basic library. You also will find a new top level menu "$(QM)Foo Extension$(QM)" + @echo with one menu entry "$(QM)Start Foo Dialog$(QM)" to start it directly. If a + @echo document is active there is also a "$(QM)Foo Toolbar Item$(QM)" doing the same. + @echo All help index entries provided by the help content start with Foo. + @echo -------------------------------------------------------------------------------- + +$(COMP_NAME).odt.load : $(COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(COMP_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/description.xml b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/description.xml new file mode 100644 index 000000000..f5540bb2b --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/description.xml @@ -0,0 +1,25 @@ + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/page1.xhp b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/page1.xhp new file mode 100644 index 000000000..d5ec9d530 --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/page1.xhp @@ -0,0 +1,90 @@ + + + + + +DE Extension foo page1 DE +/com.foocorp.foo-ext/page1.xhp + + + + +Foo Einzel-Eintrag für page1 +Foo Alle Seiten;page1 + + +Foo Einzel-Eintrag page1, nur swriter/sdraw + +DE Extension foo page1 DE +Dies ist "page1" der Extension foo Hilfe. +Kommentar am Ende des Paragraphen +Einige Links... +Einige Links... + +Dies ist ein Link zu "page2" der Extension foo Hilfe. + +Dies ist ein Link zu einer Sektion innerhalb einer Hilfe-Datei (unten in dieser Datei, kann aber auch in einer anderen Datei sein). + +Dies ist ein Link zu einer Hilfe-Seite in der installierten Hilfe. +Etwas Füll-Text +Ich mag Füll-Text. Ich mag Füll-Text. Ich mag Füll-Text. +Ich mag Füll-Text. Ich mag Füll-Text. Ich mag Füll-Text. +Ich mag Füll-Text. Ich mag Füll-Text. Ich mag Füll-Text. +Ich mag Füll-Text. Ich mag Füll-Text. Ich mag Füll-Text. +Ich mag Füll-Text. Ich mag Füll-Text. Ich mag Füll-Text. +Ich mag Füll-Text. Ich mag Füll-Text. Ich mag Füll-Text. +

+Section "target" + +This is a section within the file page1.xhp. The section has the name "target". + +
+Noch mehr Füll-Text +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +Dieser Text füllt die Seite um die Section "target" oben anzeigen zu können. +
+ +Diese Section zeigt einen Link der durch Einfügen der "linkvar" Variable aus subfolder/anotherpage.xhp erzeugt wurde. + +
+ + diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/page2.xhp b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/page2.xhp new file mode 100644 index 000000000..9cafd0aaa --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/page2.xhp @@ -0,0 +1,44 @@ + + + + + +DE Extension foo page2 DE +/com.foocorp.foo-ext/page2.xhp + + + + +Foo Alle Seiten;page2 + +DE Extension foo page2 DE +Dies ist "page2" der Extension foo Hilfe. +Einige Links... + +Dies ist ein Link zu einer Sektion in "page1". + +Dies ist ein Link zu einer Hilfe-Seite in der installierten Hilfe. +
+ +Diese Section zeigt einen Link der durch Einfügen der "linkvar" Variable aus subfolder/anotherpage.xhp erzeugt wurde. + + +
+ +
diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/subfolder/anotherpage.xhp b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/subfolder/anotherpage.xhp new file mode 100644 index 000000000..1a8c29f4d --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/de/com.foocorp.foo-ext/subfolder/anotherpage.xhp @@ -0,0 +1,117 @@ + + + + + +DE Extension foo subfolder/anotherpage DE +/com.foocorp.foo-ext/subfolder/anotherpage.xhp + + + + +Foo Alle Seiten;subfolder/anotherpage + +DE Extension foo subfolder/anotherpage DE +Dies ist subfolder/anotherpage der Extension foo Hilfe. +Comment at end of paragraph + + +Hier klicken, um den eindrucksvollen Foo Dialog zu öffnen + +Hilfe für den Foo Dialog +Der Foo Dialog ist ein sehr wichtiger Dialog, der... + + + +Dieser Knopf bringt es! +Hilfe für den "Do It !" Knopf +Der "Do It !" Knopf tut es! +Etwas fülltext +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Dieser Text füllt die Seite. +Variable, die einen Link definiert + + +Link zu page2, definert als variable in subfolder/anotherpage.xhp + + + + diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/page1.xhp b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/page1.xhp new file mode 100644 index 000000000..5cbaf7cce --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/page1.xhp @@ -0,0 +1,90 @@ + + + + + +Extension foo page1 +/com.foocorp.foo-ext/page1.xhp + + + + +Foo Single level entry page1 +Foo All Pages;page1 + + +Foo Single level entry page1, swriter/sdraw only + +Extension foo page1 +This is "page1" of extension foo help. +Comment at end of paragraph +Some links... +Some links... + +This is a link to "page2" of extension foo help. + +This is a link to a section within a help file (down in this file, but can be in another file as well). + +This is a link to a help page in the installed help. +Some fill text +I like fill text. I like fill text. I like fill text. +I like fill text. I like fill text. I like fill text. +I like fill text. I like fill text. I like fill text. +I like fill text. I like fill text. I like fill text. +I like fill text. I like fill text. I like fill text. +I like fill text. I like fill text. I like fill text. +
+Section "target" + +This is a section within the file page1.xhp. The section has the name "target". + +
+Some more fill text +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +This text fills the page allowing to show section "target" at the top. +
+ +This section shows a link created by embedding the "linkvar" variable defined in subfolder/anotherpage.xhp. + +
+ +
diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/page2.xhp b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/page2.xhp new file mode 100644 index 000000000..66b3156de --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/page2.xhp @@ -0,0 +1,43 @@ + + + + + +Extension foo page2 +/com.foocorp.foo-ext/page2.xhp + + + + +Foo All Pages;page2 + +Extension foo page2 +This is "page2" of extension foo help. +Some links... + +This is a link to a section within page1. + +This is a link to a file of the already installed help. +
+ +This section shows a link created by embedding the "linkvar" variable defined in subfolder/anotherpage.xhp. + +
+ +
diff --git a/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/subfolder/anotherpage.xhp b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/subfolder/anotherpage.xhp new file mode 100644 index 000000000..30a31a720 --- /dev/null +++ b/odk/examples/DevelopersGuide/Extensions/DialogWithHelp/help/en/com.foocorp.foo-ext/subfolder/anotherpage.xhp @@ -0,0 +1,117 @@ + + + + + +Extension foo subfolder/anotherpage +/com.foocorp.foo-ext/subfolder/anotherpage.xhp + + + + +Foo All Pages;subfolder/anotherpage + +Extension foo subfolder/anotherpage +This is subfolder/anotherpage of extension foo help. +Comment at end of paragraph + + +Click here to open the impressing Foo Dialog + +Help for the Foo Dialog +The Foo Dialog is a very important dialog that... + + + +This button really does it!! +Help for the "Do It !" button +The "Do It !" button does it! +Some fill text +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +This text fills the page. +Variable defining a link + + +Link to page2 defined as variable in subfolder/anotherpage.xhp + + + + diff --git a/odk/examples/DevelopersGuide/FirstSteps/FirstConnection.java b/odk/examples/DevelopersGuide/FirstSteps/FirstConnection.java new file mode 100644 index 000000000..9506b0070 --- /dev/null +++ b/odk/examples/DevelopersGuide/FirstSteps/FirstConnection.java @@ -0,0 +1,61 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +public class FirstConnection { + + public static void main(String[] args) { + try { + // get the remote office component context + com.sun.star.uno.XComponentContext xContext = + com.sun.star.comp.helper.Bootstrap.bootstrap(); + + System.out.println("Connected to a running office ..."); + + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + String available = (null != xMCF ? "available" : "not available"); + System.out.println( "remote ServiceManager is " + available ); + } + catch (java.lang.Exception e){ + e.printStackTrace(); + } + finally { + System.exit(0); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/FirstSteps/FirstLoadComponent.java b/odk/examples/DevelopersGuide/FirstSteps/FirstLoadComponent.java new file mode 100644 index 000000000..70e531df3 --- /dev/null +++ b/odk/examples/DevelopersGuide/FirstSteps/FirstLoadComponent.java @@ -0,0 +1,162 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.uno.XComponentContext; +import com.sun.star.comp.helper.Bootstrap; +import com.sun.star.container.XEnumeration; +import com.sun.star.container.XEnumerationAccess; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XController; +import com.sun.star.frame.XModel; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.sheet.XCellAddressable; +import com.sun.star.sheet.XCellRangesQuery; +import com.sun.star.sheet.XSheetCellRanges; +import com.sun.star.sheet.XSpreadsheet; +import com.sun.star.sheet.XSpreadsheetDocument; +import com.sun.star.sheet.XSpreadsheetView; +import com.sun.star.sheet.XSpreadsheets; +import com.sun.star.table.XCell; +import com.sun.star.uno.UnoRuntime; + +public class FirstLoadComponent { + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + try { + // get the remote office component context + XComponentContext xRemoteContext = Bootstrap.bootstrap(); + if (xRemoteContext == null) { + System.err.println("ERROR: Could not bootstrap default Office."); + } + + XMultiComponentFactory xRemoteServiceManager = xRemoteContext.getServiceManager(); + + Object desktop = xRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", xRemoteContext); + XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, desktop); + + PropertyValue[] loadProps = new PropertyValue[0]; + XComponent xSpreadsheetComponent = xComponentLoader.loadComponentFromURL("private:factory/scalc", "_blank", 0, loadProps); + + XSpreadsheetDocument xSpreadsheetDocument = UnoRuntime.queryInterface(XSpreadsheetDocument.class, + xSpreadsheetComponent); + + XSpreadsheets xSpreadsheets = xSpreadsheetDocument.getSheets(); + xSpreadsheets.insertNewByName("MySheet", (short)0); + com.sun.star.uno.Type elemType = xSpreadsheets.getElementType(); + + System.out.println(elemType.getTypeName()); + Object sheet = xSpreadsheets.getByName("MySheet"); + XSpreadsheet xSpreadsheet = UnoRuntime.queryInterface( + XSpreadsheet.class, sheet); + + XCell xCell = xSpreadsheet.getCellByPosition(0, 0); + xCell.setValue(21); + xCell = xSpreadsheet.getCellByPosition(0, 1); + xCell.setValue(21); + xCell = xSpreadsheet.getCellByPosition(0, 2); + xCell.setFormula("=sum(A1:A2)"); + + XPropertySet xCellProps = UnoRuntime.queryInterface( + XPropertySet.class, xCell); + xCellProps.setPropertyValue("CellStyle", "Result"); + + XModel xSpreadsheetModel = UnoRuntime.queryInterface( + XModel.class, xSpreadsheetComponent); + XController xSpreadsheetController = xSpreadsheetModel.getCurrentController(); + XSpreadsheetView xSpreadsheetView = UnoRuntime.queryInterface(XSpreadsheetView.class, + xSpreadsheetController); + xSpreadsheetView.setActiveSheet(xSpreadsheet); + + // ********************************************************* + // example for use of enum types + xCellProps.setPropertyValue("VertJustify", + com.sun.star.table.CellVertJustify.TOP); + + + // ********************************************************* + // example for a sequence of PropertyValue structs + // create an array with one PropertyValue struct, it contains + // references only + loadProps = new PropertyValue[1]; + + // instantiate PropertyValue struct and set its member fields + PropertyValue asTemplate = new PropertyValue(); + asTemplate.Name = "AsTemplate"; + asTemplate.Value = Boolean.TRUE; + + // assign PropertyValue struct to array of references for PropertyValue + // structs + loadProps[0] = asTemplate; + + // load calc file as template + //xSpreadsheetComponent = xComponentLoader.loadComponentFromURL( + // "file:///c:/temp/DataAnalysys.ods", "_blank", 0, loadProps); + + // ********************************************************* + // example for use of XEnumerationAccess + XCellRangesQuery xCellQuery = UnoRuntime.queryInterface(XCellRangesQuery.class, sheet); + XSheetCellRanges xFormulaCells = xCellQuery.queryContentCells( + (short)com.sun.star.sheet.CellFlags.FORMULA); + XEnumerationAccess xFormulas = xFormulaCells.getCells(); + XEnumeration xFormulaEnum = xFormulas.createEnumeration(); + + while (xFormulaEnum.hasMoreElements()) { + Object formulaCell = xFormulaEnum.nextElement(); + xCell = UnoRuntime.queryInterface(XCell.class, formulaCell); + XCellAddressable xCellAddress = UnoRuntime.queryInterface(XCellAddressable.class, xCell); + System.out.println("Formula cell in column " + + xCellAddress.getCellAddress().Column + + ", row " + xCellAddress.getCellAddress().Row + + " contains " + xCell.getFormula()); + } + + } + catch (java.lang.Exception e){ + e.printStackTrace(); + } + finally { + System.exit( 0 ); + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/FirstSteps/FirstUnoContact.java b/odk/examples/DevelopersGuide/FirstSteps/FirstUnoContact.java new file mode 100644 index 000000000..9f4de1a6e --- /dev/null +++ b/odk/examples/DevelopersGuide/FirstSteps/FirstUnoContact.java @@ -0,0 +1,61 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +public class FirstUnoContact { + + public static void main(String[] args) { + try { + // get the remote office component context + com.sun.star.uno.XComponentContext xContext = + com.sun.star.comp.helper.Bootstrap.bootstrap(); + + System.out.println("Connected to a running office ..."); + + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + String available = (xMCF != null ? "available" : "not available"); + System.out.println( "remote ServiceManager is " + available ); + } + catch (java.lang.Exception e){ + e.printStackTrace(); + } + finally { + System.exit(0); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/FirstSteps/HelloTextTableShape.java b/odk/examples/DevelopersGuide/FirstSteps/HelloTextTableShape.java new file mode 100644 index 000000000..2dd4e9c0e --- /dev/null +++ b/odk/examples/DevelopersGuide/FirstSteps/HelloTextTableShape.java @@ -0,0 +1,439 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lang.XComponent; +import com.sun.star.uno.XComponentContext; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.PropertyValue; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XText; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextContent; +import com.sun.star.table.XCellRange; +import com.sun.star.table.XCell; +import com.sun.star.table.TableBorder; +import com.sun.star.table.BorderLine; +import com.sun.star.drawing.XShape; +import com.sun.star.awt.Size; +import com.sun.star.awt.Point; +import com.sun.star.sheet.XSpreadsheetDocument; +import com.sun.star.container.XIndexAccess; +import com.sun.star.drawing.XDrawPagesSupplier; +import com.sun.star.drawing.XDrawPageSupplier; +import com.sun.star.drawing.XDrawPage; + +public class HelloTextTableShape { + + private XComponentContext xRemoteContext = null; + private XMultiComponentFactory xRemoteServiceManager = null; + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + HelloTextTableShape helloTextTableShape1 = new HelloTextTableShape(); + try { + helloTextTableShape1.useDocuments(); + } + catch (java.lang.Exception e){ + System.err.println(e.getMessage()); + e.printStackTrace(); + } + finally { + System.exit(0); + } + + } + + protected void useDocuments() throws java.lang.Exception { + useWriter(); + useCalc(); + useDraw(); + } + + protected void useWriter() throws java.lang.Exception { + try { + // create new writer document and get text, then manipulate text + XComponent xWriterComponent = newDocComponent("swriter"); + XTextDocument xTextDocument = UnoRuntime.queryInterface( + XTextDocument.class, xWriterComponent); + XText xText = xTextDocument.getText(); + + manipulateText(xText); + + // get internal service factory of the document + XMultiServiceFactory xWriterFactory = UnoRuntime.queryInterface( + XMultiServiceFactory.class, xWriterComponent); + + // insert TextTable and get cell text, then manipulate text in cell + Object table = xWriterFactory.createInstance("com.sun.star.text.TextTable"); + XTextContent xTextContentTable = UnoRuntime.queryInterface( + XTextContent.class, table); + + xText.insertTextContent(xText.getEnd(), xTextContentTable, false); + + XCellRange xCellRange = UnoRuntime.queryInterface( + XCellRange.class, table); + XCell xCell = xCellRange.getCellByPosition(0, 1); + XText xCellText = UnoRuntime.queryInterface(XText.class, xCell); + + manipulateText(xCellText); + manipulateTable(xCellRange); + + // insert RectangleShape and get shape text, then manipulate text + Object writerShape = xWriterFactory.createInstance( + "com.sun.star.drawing.RectangleShape"); + XShape xWriterShape = UnoRuntime.queryInterface( + XShape.class, writerShape); + xWriterShape.setSize(new Size(10000, 10000)); + XTextContent xTextContentShape = UnoRuntime.queryInterface( + XTextContent.class, writerShape); + + xText.insertTextContent(xText.getEnd(), xTextContentShape, false); + + XPropertySet xShapeProps = UnoRuntime.queryInterface( + XPropertySet.class, writerShape); + // wrap text inside shape + xShapeProps.setPropertyValue("TextContourFrame", Boolean.TRUE); + + + XText xShapeText = UnoRuntime.queryInterface(XText.class, writerShape); + + manipulateText(xShapeText); + manipulateShape(xWriterShape); + +/* more code snippets used in the manual: + + Object bookmark = xWriterFactory.createInstance ( "com.sun.star.text.Bookmark" ); + // name the bookmark + XNamed xNamed = (XNamed) UnoRuntime.queryInterface ( + XNamed.class, bookmark ); + xNamed.setName("MyUniqueBookmarkName"); + + // get XTextContent interface and insert it at the end of the document + XTextContent xTextContent = (XTextContent) UnoRuntime.queryInterface ( + XTextContent.class, bookmark ); + //mxDocText.insertTextContent ( mxDocText.getEnd(), xTextContent, false ); + xText.insertTextContent ( xText.getEnd(), xTextContent, false ); + + //query BookmarksSupplier + XBookmarksSupplier xBookmarksSupplier = (XBookmarksSupplier)UnoRuntime.queryInterface( + XBookmarksSupplier.class, xWriterComponent); + XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks(); + Object foundBookmark = xNamedBookmarks.getByName("MyUniqueBookmarkName"); + XTextContent xFoundBookmark = (XTextContent)UnoRuntime.queryInterface(XTextContent.class, foundBookmark); + XTextRange xFound = xFoundBookmark.getAnchor(); + xFound.setString(" The throat mike, glued to her neck, " + + "looked as much as possible like an analgesic dermadisk."); + + + + + // first query the XTextTablesSupplier interface from our document + XTextTablesSupplier xTablesSupplier = (XTextTablesSupplier) UnoRuntime.queryInterface( + XTextTablesSupplier.class, xWriterComponent); + // get the tables collection + XNameAccess xNamedTables = xTablesSupplier.getTextTables(); + + // now query the XIndexAccess from the tables collection + XIndexAccess xIndexedTables = (XIndexAccess) UnoRuntime.queryInterface( + XIndexAccess.class, xNamedTables); + + // we need properties + XPropertySet xTableProps = null; + + // get the tables + for (int i = 0; i < xIndexedTables.getCount(); i++) { + //Object table = xIndexedTables.getByIndex(i); + table = xIndexedTables.getByIndex(i); + xTableProps = (XPropertySet) UnoRuntime.queryInterface( + XPropertySet.class, table); + xTableProps.setPropertyValue("BackColor", Integer.valueOf(0xC8FFB9)); + } + */ + } + catch( com.sun.star.lang.DisposedException e ) { //works from Patch 1 + xRemoteContext = null; + throw e; + } + + } + + protected void useCalc() throws java.lang.Exception { + try { + // create new calc document and manipulate cell text + XComponent xCalcComponent = newDocComponent("scalc"); + XSpreadsheetDocument xSpreadsheetDocument = + UnoRuntime.queryInterface( + XSpreadsheetDocument .class, xCalcComponent); + Object sheets = xSpreadsheetDocument.getSheets(); + XIndexAccess xIndexedSheets = UnoRuntime.queryInterface( + XIndexAccess.class, sheets); + Object sheet = xIndexedSheets.getByIndex(0); + + //get cell A2 in first sheet + XCellRange xSpreadsheetCells = UnoRuntime.queryInterface( + XCellRange.class, sheet); + XCell xCell = xSpreadsheetCells.getCellByPosition(0,1); + XPropertySet xCellProps = UnoRuntime.queryInterface( + XPropertySet.class, xCell); + xCellProps.setPropertyValue("IsTextWrapped", Boolean.TRUE); + + XText xCellText = UnoRuntime.queryInterface(XText.class, xCell); + + manipulateText(xCellText); + manipulateTable(xSpreadsheetCells); + + // get internal service factory of the document + XMultiServiceFactory xCalcFactory = UnoRuntime.queryInterface( + XMultiServiceFactory.class, xCalcComponent); + // get Drawpage + XDrawPageSupplier xDrawPageSupplier = UnoRuntime.queryInterface(XDrawPageSupplier.class, sheet); + XDrawPage xDrawPage = xDrawPageSupplier.getDrawPage(); + + // create and insert RectangleShape and get shape text, then manipulate text + Object calcShape = xCalcFactory.createInstance( + "com.sun.star.drawing.RectangleShape"); + XShape xCalcShape = UnoRuntime.queryInterface( + XShape.class, calcShape); + xCalcShape.setSize(new Size(10000, 10000)); + xCalcShape.setPosition(new Point(7000, 3000)); + + xDrawPage.add(xCalcShape); + + XPropertySet xShapeProps = UnoRuntime.queryInterface( + XPropertySet.class, calcShape); + // wrap text inside shape + xShapeProps.setPropertyValue("TextContourFrame", Boolean.TRUE); + + + XText xShapeText = UnoRuntime.queryInterface(XText.class, calcShape); + + manipulateText(xShapeText); + manipulateShape(xCalcShape); + + } + catch( com.sun.star.lang.DisposedException e ) { //works from Patch 1 + xRemoteContext = null; + throw e; + } + + } + + protected void useDraw() throws java.lang.Exception { + try { + //create new draw document and insert ractangle shape + XComponent xDrawComponent = newDocComponent("sdraw"); + XDrawPagesSupplier xDrawPagesSupplier = + UnoRuntime.queryInterface( + XDrawPagesSupplier.class, xDrawComponent); + + Object drawPages = xDrawPagesSupplier.getDrawPages(); + XIndexAccess xIndexedDrawPages = UnoRuntime.queryInterface( + XIndexAccess.class, drawPages); + Object drawPage = xIndexedDrawPages.getByIndex(0); + XDrawPage xDrawPage = UnoRuntime.queryInterface(XDrawPage.class, drawPage); + + // get internal service factory of the document + XMultiServiceFactory xDrawFactory = + UnoRuntime.queryInterface( + XMultiServiceFactory.class, xDrawComponent); + + Object drawShape = xDrawFactory.createInstance( + "com.sun.star.drawing.RectangleShape"); + XShape xDrawShape = UnoRuntime.queryInterface(XShape.class, drawShape); + xDrawShape.setSize(new Size(10000, 20000)); + xDrawShape.setPosition(new Point(5000, 5000)); + xDrawPage.add(xDrawShape); + + XText xShapeText = UnoRuntime.queryInterface(XText.class, drawShape); + XPropertySet xShapeProps = UnoRuntime.queryInterface( + XPropertySet.class, drawShape); + + // wrap text inside shape + xShapeProps.setPropertyValue("TextContourFrame", Boolean.TRUE); + + manipulateText(xShapeText); + manipulateShape(xDrawShape); + } + catch( com.sun.star.lang.DisposedException e ) { //works from Patch 1 + xRemoteContext = null; + throw e; + } + + + } + + protected void manipulateText(XText xText) throws com.sun.star.uno.Exception { + // simply set whole text as one string + xText.setString("He lay flat on the brown, pine-needled floor of the forest, " + + "his chin on his folded arms, and high overhead the wind blew in the tops " + + "of the pine trees."); + + // create text cursor for selecting and formatting + XTextCursor xTextCursor = xText.createTextCursor(); + XPropertySet xCursorProps = UnoRuntime.queryInterface( + XPropertySet.class, xTextCursor); + + // use cursor to select "He lay" and apply bold italic + xTextCursor.gotoStart(false); + xTextCursor.goRight((short)6, true); + // from CharacterProperties + xCursorProps.setPropertyValue("CharPosture", + com.sun.star.awt.FontSlant.ITALIC); + xCursorProps.setPropertyValue("CharWeight", + new Float(com.sun.star.awt.FontWeight.BOLD)); + + // add more text at the end of the text using insertString + xTextCursor.gotoEnd(false); + xText.insertString(xTextCursor, " The mountainside sloped gently where he lay; " + + "but below it was steep and he could see the dark of the oiled road " + + "winding through the pass. There was a stream alongside the road " + + "and far down the pass he saw a mill beside the stream and the falling water " + + "of the dam, white in the summer sunlight.", false); + // after insertString the cursor is behind the inserted text, insert more text + xText.insertString(xTextCursor, "\n \"Is that the mill?\" he asked.", false); + } + + protected void manipulateTable(XCellRange xCellRange) throws com.sun.star.uno.Exception { + + String backColorPropertyName = ""; + XPropertySet xTableProps = null; + + // enter column titles and a cell value + XCell xCell = xCellRange.getCellByPosition(0,0); + XText xCellText = UnoRuntime.queryInterface(XText.class, xCell); + xCellText.setString("Quotation"); + xCell = xCellRange.getCellByPosition(1,0); + xCellText = UnoRuntime.queryInterface(XText.class, xCell); + xCellText.setString("Year"); + xCell = xCellRange.getCellByPosition(1,1); + xCell.setValue(1940); + XCellRange xSelectedCells = xCellRange.getCellRangeByName("A1:B1"); + XPropertySet xCellProps = UnoRuntime.queryInterface( + XPropertySet.class, xSelectedCells); + + // format table headers and table borders + // we need to distinguish text and sheet tables: + // property name for cell colors is different in text and sheet cells + // we want to apply TableBorder to whole text table, but only to sheet cells with content + XServiceInfo xServiceInfo = UnoRuntime.queryInterface( + XServiceInfo.class, xCellRange); + if (xServiceInfo.supportsService("com.sun.star.sheet.Spreadsheet")) { + backColorPropertyName = "CellBackColor"; + xSelectedCells = xCellRange.getCellRangeByName("A1:B2"); + xTableProps = UnoRuntime.queryInterface( + XPropertySet.class, xSelectedCells); + } + else if (xServiceInfo.supportsService("com.sun.star.text.TextTable")) { + backColorPropertyName = "BackColor"; + xTableProps = UnoRuntime.queryInterface( + XPropertySet.class, xCellRange); + } + // set cell background color + xCellProps.setPropertyValue(backColorPropertyName, Integer.valueOf(0x99CCFF)); + + // set table borders + // create description for blue line, width 10 + BorderLine theLine = new BorderLine(); + theLine.Color = 0x000099; + theLine.OuterLineWidth = 10; + // apply line description to all border lines and make them valid + TableBorder bord = new TableBorder(); + bord.VerticalLine = bord.HorizontalLine = + bord.LeftLine = bord.RightLine = + bord.TopLine = bord.BottomLine = + theLine; + bord.IsVerticalLineValid = bord.IsHorizontalLineValid = + bord.IsLeftLineValid = bord.IsRightLineValid = + bord.IsTopLineValid = bord.IsBottomLineValid = + true; + + xTableProps.setPropertyValue("TableBorder", bord); + + bord = (TableBorder)xTableProps.getPropertyValue("TableBorder"); + theLine = bord.TopLine; + int col = theLine.Color; + System.out.println(col); + } + + protected void manipulateShape(XShape xShape) throws com.sun.star.uno.Exception { + XPropertySet xShapeProps = UnoRuntime.queryInterface(XPropertySet.class, xShape); + xShapeProps.setPropertyValue("FillColor", Integer.valueOf(0x99CCFF)); + xShapeProps.setPropertyValue("LineColor", Integer.valueOf(0x000099)); + xShapeProps.setPropertyValue("RotateAngle", Integer.valueOf(3000)); + + xShapeProps.setPropertyValue("TextLeftDistance", Integer.valueOf(0)); + xShapeProps.setPropertyValue("TextRightDistance", Integer.valueOf(0)); + xShapeProps.setPropertyValue("TextUpperDistance", Integer.valueOf(0)); + xShapeProps.setPropertyValue("TextLowerDistance", Integer.valueOf(0)); + } + + + protected XComponent newDocComponent(String docType) throws java.lang.Exception { + String loadUrl = "private:factory/" + docType; + xRemoteServiceManager = this.getRemoteServiceManager(); + Object desktop = xRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", xRemoteContext); + XComponentLoader xComponentLoader = UnoRuntime.queryInterface( + XComponentLoader.class, desktop); + PropertyValue[] loadProps = new PropertyValue[0]; + return xComponentLoader.loadComponentFromURL(loadUrl, "_blank", 0, loadProps); + } + + protected XMultiComponentFactory getRemoteServiceManager() throws java.lang.Exception { + if (xRemoteContext == null && xRemoteServiceManager == null) { + try { + // First step: get the remote office component context + xRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + xRemoteServiceManager = xRemoteContext.getServiceManager(); + } + catch( Exception e) { + e.printStackTrace(); + System.exit(1); + } + } + return xRemoteServiceManager; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/FirstSteps/Makefile b/odk/examples/DevelopersGuide/FirstSteps/Makefile new file mode 100644 index 000000000..53077d093 --- /dev/null +++ b/odk/examples/DevelopersGuide/FirstSteps/Makefile @@ -0,0 +1,100 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the FirstSteps examples of the Developers Guide. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=FirstStepsExamples +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +APP1_NAME=FirstUnoContact +APP1_JAR=$(OUT_APP_CLASS)/$(APP1_NAME).jar +APP2_NAME=FirstLoadComponent +APP2_JAR=$(OUT_APP_CLASS)/$(APP2_NAME).jar +APP3_NAME=HelloTextTableShape +APP3_JAR=$(OUT_APP_CLASS)/$(APP3_NAME).jar + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : \ + $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_APP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(OUT_APP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(OUT_APP_CLASS)/%.jar : $(OUT_APP_CLASS)/%.mf $(OUT_APP_CLASS)/%.class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(OUT_APP_CLASS)/$(APP1_NAME).class +$(APP2_JAR) : $(OUT_APP_CLASS)/$(APP2_NAME).mf $(OUT_APP_CLASS)/$(APP2_NAME).class +$(APP3_JAR) : $(OUT_APP_CLASS)/$(APP3_NAME).mf $(OUT_APP_CLASS)/$(APP3_NAME).class + +$(EXAMPLE_NAME) : $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP2_NAME).run + @echo $(MAKE) $(APP3_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/FirstSteps/build_FirstUnoContact.xml b/odk/examples/DevelopersGuide/FirstSteps/build_FirstUnoContact.xml new file mode 100644 index 000000000..4dec9aa7e --- /dev/null +++ b/odk/examples/DevelopersGuide/FirstSteps/build_FirstUnoContact.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+
+
+ + + + + + + + + + + + + + + + + + + +
diff --git a/odk/examples/DevelopersGuide/Forms/BooleanValidator.java b/odk/examples/DevelopersGuide/Forms/BooleanValidator.java new file mode 100644 index 000000000..eb8851c2a --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/BooleanValidator.java @@ -0,0 +1,84 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +import com.sun.star.uno.AnyConverter; + +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +public class BooleanValidator extends ControlValidator +{ + private boolean m_preventChecked; + + /** Creates a new instance of BooleanValidator */ + public BooleanValidator( boolean preventChecked ) + { + m_preventChecked = preventChecked; + } + + public String explainInvalid( Object Value ) + { + try + { + if ( AnyConverter.isVoid( Value ) ) + return "'indetermined' is not an allowed state"; + boolean value = ((Boolean)Value).booleanValue(); + if ( m_preventChecked && ( value == true ) ) + return "no no no. Don't check it."; + } + catch( java.lang.Exception e ) + { + return "ooops. Unknown error"; + } + return ""; + } + + public boolean isValid( Object Value ) + { + try + { + if ( AnyConverter.isVoid( Value ) ) + return false; + + boolean value = ((Boolean)Value).booleanValue(); + if ( m_preventChecked && ( value == true ) ) + return false; + return true; + } + catch( java.lang.Exception e ) + { + } + return false; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/ButtonOperator.java b/odk/examples/DevelopersGuide/Forms/ButtonOperator.java new file mode 100644 index 000000000..890ea7251 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/ButtonOperator.java @@ -0,0 +1,219 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +// java base stuff +import java.util.ArrayList; + +import com.sun.star.awt.ActionEvent; +import com.sun.star.awt.XActionListener; +import com.sun.star.awt.XButton; +import com.sun.star.beans.XPropertySet; +import com.sun.star.form.runtime.FormOperations; +import com.sun.star.form.runtime.XFeatureInvalidation; +import com.sun.star.form.runtime.XFormOperations; +import com.sun.star.lang.EventObject; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + + +/**************************************************************************/ +/** a helper class for operating the buttons +*/ +public class ButtonOperator implements XActionListener, XFeatureInvalidation +{ + private XComponentContext m_componentContext; + private DocumentHelper m_aDocument; + private XPropertySet m_form; + private XFormOperations m_formOperations; + + private ArrayList m_aButtons; + + /* ------------------------------------------------------------------ */ + /** ctor + */ + public ButtonOperator( XComponentContext xCtx, DocumentHelper aDocument, XPropertySet _form ) + { + m_componentContext = xCtx; + m_aDocument = aDocument; + m_form = _form; + m_aButtons = new ArrayList(); + } + + /* ------------------------------------------------------------------ */ + private short getAssociatedFormFeature( XPropertySet _buttonModel ) + { + short formFeature = -1; + try + { + formFeature = Short.valueOf( (String)_buttonModel.getPropertyValue( "Tag" ) ); + } + catch( com.sun.star.uno.Exception e ) + { + } + return formFeature; + } + + /* ------------------------------------------------------------------ */ + /** gets the button which we operate and which is responsible for a given URL + */ + private XPropertySet getButton( short _formFeature ) + { + for ( int i=0; i < m_aButtons.size(); ++i ) + { + XPropertySet button = m_aButtons.get( i ); + if ( _formFeature == getAssociatedFormFeature( button ) ) + return button; + } + return null; + } + + /* ------------------------------------------------------------------ */ + /** announces a button which the operator should be responsible for + */ + private int getButtonIndex( XPropertySet xButton ) + { + int nPos = -1; + for ( int i=0; ( i < m_aButtons.size() ) && ( -1 == nPos ); ++i ) + { + if ( xButton.equals( m_aButtons.get( i ) ) ) + nPos = i; + } + return nPos; + } + + /* ------------------------------------------------------------------ */ + /** announces a button which the operator should be responsible for + */ + public void addButton( XPropertySet _buttonModel, short _formFeature ) throws java.lang.Exception + { + // the current view to the document + DocumentViewHelper aCurrentView = m_aDocument.getCurrentView(); + + // add a listener so we get noticed if the user presses the button + XButton xButtonControl = UnoRuntime.queryInterface( XButton.class, + aCurrentView.getFormControl( _buttonModel ) ); + xButtonControl.addActionListener( this ); + + _buttonModel.setPropertyValue( "Tag", String.valueOf( _formFeature ) ); + + // remember the button + m_aButtons.add( _buttonModel ); + } + + /* ------------------------------------------------------------------ */ + public void revokeButton( XPropertySet xButtonModel ) + { + int nPos = getButtonIndex( xButtonModel ); + if ( -1 < nPos ) + { + m_aButtons.remove( nPos ); + } + } + + /* ================================================================== + = XActionListener + ================================================================== */ + /* ------------------------------------------------------------------ */ + /* called when a button has been pressed + */ + public void actionPerformed( ActionEvent aEvent ) throws com.sun.star.uno.RuntimeException + { + // get the model's name + XPropertySet buttonModel = FLTools.getModel( aEvent.Source, XPropertySet.class ); + try + { + short formFeature = getAssociatedFormFeature( buttonModel ); + if ( formFeature != -1 ) + m_formOperations.execute( formFeature ); + } + catch( final com.sun.star.uno.Exception e ) + { + } + } + + /* ------------------------------------------------------------------ */ + /* (to be) called when the form layer has been switched to alive mode + * @todo + * register as listener somewhere ... + */ + public void onFormsAlive() + { + m_formOperations = FormOperations.createWithFormController( + m_componentContext, m_aDocument.getCurrentView().getFormController( m_form ) ); + m_formOperations.setFeatureInvalidation( this ); + invalidateAllFeatures(); + } + + /* ================================================================== + = XEventListener + ================================================================== */ + public void disposing( EventObject aEvent ) + { + // not interested in + } + + /* ================================================================== + = XFeatureInvalidation + ================================================================== */ + private void updateButtonState( XPropertySet _buttonModel, short _formFeature ) + { + try + { + _buttonModel.setPropertyValue( "Enabled", m_formOperations.isEnabled( _formFeature ) ); + } + catch( com.sun.star.uno.Exception e ) + { + } + } + + public void invalidateFeatures( short[] _features ) throws com.sun.star.uno.RuntimeException + { + for ( int i=0; i<_features.length; ++i ) + { + XPropertySet buttonModel = getButton( _features[i] ); + if ( buttonModel != null ) + updateButtonState( buttonModel, _features[i] ); + } + } + + public void invalidateAllFeatures() throws com.sun.star.uno.RuntimeException + { + for ( XPropertySet buttonModel : m_aButtons ) + { + updateButtonState( buttonModel, getAssociatedFormFeature( buttonModel ) ); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/ComponentTreeTraversal.java b/odk/examples/DevelopersGuide/Forms/ComponentTreeTraversal.java new file mode 100644 index 000000000..be9bc22fb --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/ComponentTreeTraversal.java @@ -0,0 +1,92 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.container.*; +import com.sun.star.lang.*; + +/**************************************************************************/ +/** an abstract interface for components doing an action on a form component +*/ +interface IFormComponentAction +{ + public abstract void handle( Object aFormComponent ) throws java.lang.Exception; +} + +/**************************************************************************/ +/** a helper class for travelling a form component tree +*/ +class ComponentTreeTraversal implements IFormComponentAction +{ + /* ------------------------------------------------------------------ */ + /** Indicator method to decide whether to step down the tree. + +

The default implementation checks if the container given is a grid + control model or a FormComponents + instance.

+ */ + protected boolean shouldStepInto( XIndexContainer xContainer ) + { + // step down the tree, if possible + XServiceInfo xSI = UNO.queryServiceInfo( xContainer ); + if ( null != xSI + && ( xSI.supportsService( "com.sun.star.form.FormComponents" ) + || xSI.supportsService( "com.sun.star.form.component.GridControl" ) + ) + ) + { + return true; + } + else + { + return false; + } + } + /* ------------------------------------------------------------------ */ + public void handle( Object aFormComponent ) throws com.sun.star.uno.Exception + { + XIndexContainer xCont = UNO.queryIndexContainer( aFormComponent ); + if ( ( null != xCont ) + && shouldStepInto( xCont ) + ) + { + for ( int i=0; i 1 ) ) + // don't step into sub forms - we only handle the form we were originally + // applied to + return false; + + return true; + } + + /* ------------------------------------------------------------------ */ + @Override + public void handle( Object aFormComponent ) throws com.sun.star.uno.Exception + { + // entering this nesting level + ++m_nLevel; + + // check if the component has a DataField property + XPropertySet xCompProps = UNO.queryPropertySet( aFormComponent ); + XPropertySetInfo xPSI = null; + if ( null != xCompProps ) + xPSI = xCompProps.getPropertySetInfo(); + + if ( ( null != xPSI ) && xPSI.hasPropertyByName( "DataField" ) ) + { // indeed it has... + String sDataField = (String)xCompProps.getPropertyValue( "DataField" ); + if ( sDataField.equals( m_sDataField ) ) + { // we found a control model which is bound to what we're looking for + xCompProps.setPropertyValue( "ReadOnly", m_aLockIt ); + } + } + + // allow the super class to step down, if possible + super.handle( aFormComponent ); + + // leaving this nesting level + --m_nLevel; + } +} + +/**************************************************************************/ +/** a class which automatically handles control locking. +

The class has to be bound to a form. Upon every movement of the form, + all controls which are bound to a (to be specified) field are locked + on existing and unlocked on new records.

+*/ +class ControlLock implements XRowSetListener +{ + private XPropertySet m_xForm; + private String m_sDataField; + private boolean m_bLockingEnabled; + private boolean m_bPreviousRoundLock; + + /* ------------------------------------------------------------------ */ + ControlLock( XPropertySet xForm, String sBoundDataField ) + { + m_xForm = xForm; + m_sDataField = sBoundDataField; + m_bLockingEnabled = false; + m_bPreviousRoundLock = false; + } + + /* ------------------------------------------------------------------ */ + /** updates the locks on the affected controls + */ + private void updateLocks( ) + { + try + { + // first determine if we need to lock + Boolean aIsNewRecord = (Boolean)m_xForm.getPropertyValue( "IsNew" ); + + boolean bNeedLock = m_bLockingEnabled && !aIsNewRecord.booleanValue(); + + if ( m_bPreviousRoundLock != bNeedLock ) + { + LockControlModels aLocker = new LockControlModels( m_sDataField, bNeedLock ); + aLocker.handle( m_xForm ); + m_bPreviousRoundLock = bNeedLock; + } + + // please note that we choose the expensive way here: We always loop through + // _all_ control models belonging to the form. This clearly slows down the + // whole process. + // A better solution would be to cache the affected control models. Then we + // could either rely on the fact that the model hierarchy is static, or we + // could add ourself as container listener to the form. + } + catch(com.sun.star.uno.Exception e) + { + System.out.println(e); + e.printStackTrace(); + } + } + + /* ------------------------------------------------------------------ */ + /** enables the locking in general +

If the control models are really locked depends on the current + record of the form: on the insert row, controls are never locked.

+ */ + public void enableLock( boolean bLock ) + { + // remember this new setting + m_bLockingEnabled = bLock; + + // add or remove ourself as listener to get notified of cursor moves + XRowSet xRowSet = UnoRuntime.queryInterface( + XRowSet.class, m_xForm ); + if ( m_bLockingEnabled ) + { + xRowSet.addRowSetListener( this ); + } + else + { + xRowSet.removeRowSetListener( this ); + } + + // update the locks + updateLocks(); + } + + /* ================================================================== + = UNO callbacks + ================================================================== */ + + /* ------------------------------------------------------------------ */ + // XResetListener overridables + /* ------------------------------------------------------------------ */ + public void cursorMoved( EventObject aEvent ) throws com.sun.star.uno.RuntimeException + { + updateLocks( ); + } + + /* ------------------------------------------------------------------ */ + public void rowChanged( EventObject aEvent ) throws com.sun.star.uno.RuntimeException + { + // not interested in + } + + /* ------------------------------------------------------------------ */ + public void rowSetChanged( EventObject aEvent ) throws com.sun.star.uno.RuntimeException + { + // not interested in + } + + /* ------------------------------------------------------------------ */ + // XEventListener overridables + /* ------------------------------------------------------------------ */ + public void disposing( EventObject aEvent ) + { + // not interested in + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/ControlValidation.java b/odk/examples/DevelopersGuide/Forms/ControlValidation.java new file mode 100644 index 000000000..4b176a371 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/ControlValidation.java @@ -0,0 +1,85 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.beans.*; + +public class ControlValidation extends DocumentBasedExample +{ + /** Creates a new instance of ControlValidation */ + public ControlValidation() + { + super( DocumentType.WRITER ); + } + + /* ------------------------------------------------------------------ */ + /* public test methods */ + /* ------------------------------------------------------------------ */ + @Override + protected void prepareDocument() throws com.sun.star.uno.Exception, java.lang.Exception + { + super.prepareDocument(); + + SingleControlValidation validation; + XPropertySet focusField; + + validation = new SingleControlValidation( m_document, 5, 5, "DatabaseFormattedField", new NumericValidator() ); + focusField = validation.getInputField(); + validation.setExplanatoryText( "Please enter a number between 0 and 100, with at most 1 decimal digit" ); + + validation = new SingleControlValidation( m_document, 90, 5, "DatabaseTextField", new TextValidator() ); + validation.setExplanatoryText( "Please enter a text whose length is a multiple of 3, and which does not contain the letter 'Z'" ); + + validation = new SingleControlValidation( m_document, 5, 55, "DatabaseDateField", new DateValidator() ); + validation.setExplanatoryText( "Please enter a date in the current month" ); + validation.getInputField().setPropertyValue( "Dropdown", Boolean.TRUE ); + + validation = new SingleControlValidation( m_document, 90, 55, "DatabaseTimeField", new TimeValidator() ); + validation.setExplanatoryText( "Please enter a time. Valid values are all full hours." ); + + validation = new SingleControlValidation( m_document, 5, 110, "DatabaseCheckBox", new BooleanValidator( false ) ); + validation.setExplanatoryText( "Please check (well, or uncheck) the box. Don't leave it in indetermined state." ); + validation.getInputField().setPropertyValue( "TriState", Boolean.TRUE ); + + validation = new SingleControlValidation( m_document, 90, 110, "DatabaseRadioButton", new BooleanValidator( true ), 3, 0 ); + validation.setExplanatoryText( "Please check any but the first button" ); + + validation = new SingleControlValidation( m_document, 5, 165, "DatabaseListBox", new ListSelectionValidator( ), 1, 24 ); + validation.setExplanatoryText( "Please select not more than two entries." ); + validation.getInputField().setPropertyValue( "MultiSelection", Boolean.TRUE ); + validation.getInputField().setPropertyValue( "StringItemList", new String[] { "first", "second", "third", "forth", "fivth" } ); + + // switch to alive mode + m_document.getCurrentView( ).toggleFormDesignMode( ); + m_document.getCurrentView( ).grabControlFocus( focusField ); + + // wait for the user telling us to exit + waitForUserInput(); + } + + /* ------------------------------------------------------------------ */ + /** class entry point + */ + public static void main(String argv[]) throws java.lang.Exception + { + ControlValidation aSample = new ControlValidation(); + aSample.run( argv ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/ControlValidator.java b/odk/examples/DevelopersGuide/Forms/ControlValidator.java new file mode 100644 index 000000000..c29dec558 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/ControlValidator.java @@ -0,0 +1,52 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +// base class for components validating the content of form controls + +public abstract class ControlValidator implements com.sun.star.form.validation.XValidator +{ + + /** Creates a new instance of ControlValidator */ + public ControlValidator() + { + } + + public void addValidityConstraintListener(com.sun.star.form.validation.XValidityConstraintListener xValidityConstraintListener) + { + } + + public void removeValidityConstraintListener(com.sun.star.form.validation.XValidityConstraintListener xValidityConstraintListener) + { + } + + protected boolean isVoid( Object Value ) + { + try + { + return ( com.sun.star.uno.AnyConverter.getType(Value).getTypeClass() + == com.sun.star.uno.TypeClass.VOID ); + } + catch( java.lang.ClassCastException e ) + { + } + return false; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/DataAwareness.java b/odk/examples/DevelopersGuide/Forms/DataAwareness.java new file mode 100644 index 000000000..fbb3b7fe5 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/DataAwareness.java @@ -0,0 +1,940 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.beans.PropertyChangeEvent; +import com.sun.star.beans.XPropertyChangeListener; +import com.sun.star.beans.XPropertySet; + + +// __________ Imports __________ +import com.sun.star.beans.XPropertySetInfo; + +// base classes +import com.sun.star.container.XIndexContainer; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNamed; +import com.sun.star.form.FormComponentType; +import com.sun.star.form.ListSourceType; +import com.sun.star.form.XGridColumnFactory; +import com.sun.star.form.XReset; +import com.sun.star.form.XResetListener; +import com.sun.star.form.runtime.FormFeature; +import com.sun.star.lang.EventObject; +import com.sun.star.lang.XComponent; +import com.sun.star.sdb.CommandType; +import com.sun.star.sdb.XColumnUpdate; +import com.sun.star.sdbc.ResultSetConcurrency; +import com.sun.star.sdbc.XConnection; +import com.sun.star.sdbc.XDataSource; +import com.sun.star.sdbc.XStatement; +import com.sun.star.sdbcx.XColumnsSupplier; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; + +/**************************************************************************/ +/** a class for enumerating a form component tree +*/ +class PrintComponentTree extends ComponentTreeTraversal +{ + private String m_sPrefix; + + public PrintComponentTree() + { + m_sPrefix = ""; + } + + @Override + public void handle( Object aFormComponent ) throws com.sun.star.uno.Exception + { + // the name of the child + XNamed xName = UnoRuntime.queryInterface( XNamed.class, aFormComponent ); + + // if it's a form control model, check it's type + XPropertySet xProps = UNO.queryPropertySet( aFormComponent ); + String sTypeName = FLTools.classifyFormComponentType( xProps ); + + String sName; + if ( null == xName ) + sName = ""; + else + sName = xName.getName(); + + // print the component's name + if ( 0 != sTypeName.length() ) + { + System.out.println( m_sPrefix + sName + " (" + sTypeName + ")" ); + } + else + { + System.out.println( m_sPrefix + sName ); + } + + // let the super class step down the tree + m_sPrefix = m_sPrefix + " "; + super.handle( aFormComponent ); + m_sPrefix = m_sPrefix.substring( 0, m_sPrefix.length() - 1 ); + } +} + +/**************************************************************************/ +/** a class revoking button models from a ButtonOperator instance +*/ +class RevokeButtons extends ComponentTreeTraversal +{ + private ButtonOperator m_aOperator; + + public RevokeButtons( ButtonOperator aOperator ) + { + m_aOperator = aOperator; + } + + @Override + public void handle( Object aFormComponent ) throws com.sun.star.uno.Exception + { + // check if it's a button + XPropertySet xProps = UNO.queryPropertySet( aFormComponent ); + XPropertySetInfo xPI = null; + if ( null != xProps ) + xPI = xProps.getPropertySetInfo(); + if ( ( null != xPI ) && xPI.hasPropertyByName( "ClassId" ) ) + { + Short nClassId = (Short)xProps.getPropertyValue( "ClassId" ); + if ( FormComponentType.COMMANDBUTTON == nClassId.shortValue() ) + { + // yes, it is + m_aOperator.revokeButton( xProps ); + } + } + + // let the super class step down the tree (if possible) + super.handle( aFormComponent ); + } +} + +/**************************************************************************/ +public class DataAwareness extends DocumentBasedExample implements XPropertyChangeListener, XResetListener +{ + /* ================================================================== */ + private HsqlDatabase m_database; + + private static final String s_tableNameSalesmen = "SALESMEN"; + private static final String s_tableNameCustomers = "CUSTOMERS"; + private static final String s_tableNameSales = "SALES"; + + private XPropertySet m_xMasterForm; + private ButtonOperator m_aOperator; + + private KeyGenerator m_aSalesmanKeyGenerator; + private KeyGenerator m_aSalesKeyGenerator; + private ControlLock m_aSalesmenLocker; + private ControlLock m_aSalesLocker; + private GridFieldValidator m_aSalesNameValidator; + + private boolean m_bDefaultSalesDate; + private boolean m_bProtectKeyFields; + private boolean m_bAllowEmptySales; + + /* ------------------------------------------------------------------ */ + public DataAwareness() + { + super( DocumentType.WRITER ); + m_bDefaultSalesDate = false; + m_bProtectKeyFields = false; + m_bAllowEmptySales = false; + } + + /* ================================================================== + = form components + ================================================================== */ + + /* ------------------------------------------------------------------ */ + /** enumerates and prints all the elements in the given container, together with the container itself + */ + protected void enumFormComponents( XNameAccess xContainer ) throws java.lang.Exception + { + String sObjectName; + + XNamed xNameAcc = UnoRuntime.queryInterface( XNamed.class, xContainer ); + if ( null == xNameAcc ) + sObjectName = ""; + else + sObjectName = xNameAcc.getName(); + System.out.println( "enumerating the container named \"" + sObjectName + + "\"\n" ); + + PrintComponentTree aPrinter = new PrintComponentTree(); + aPrinter.handle( xContainer ); + } + + /* ------------------------------------------------------------------ */ + /** enumerates and prints all form elements in the document + */ + protected void enumFormComponents( ) throws java.lang.Exception + { + enumFormComponents( m_document.getFormComponentTreeRoot() ); + } + + /* ================================================================== + = UNO callbacks + ================================================================== */ + + /* ------------------------------------------------------------------ */ + // XResetListener overridables + /* ------------------------------------------------------------------ */ + public boolean approveReset( EventObject aEvent ) throws com.sun.star.uno.RuntimeException + { + // not interested in vetoing this + return true; + } + + /* ------------------------------------------------------------------ */ + public void resetted( EventObject aEvent ) throws com.sun.star.uno.RuntimeException + { + // check if this reset occurred because we're on a new record + XPropertySet xFormProps = UNO.queryPropertySet( aEvent.Source ); + try + { + Boolean aIsNew = (Boolean)xFormProps.getPropertyValue( "IsNew" ); + if ( aIsNew.booleanValue() ) + { // yepp + + if ( !m_bDefaultSalesDate ) + { // we're interested to do all this only if the user told us to default the sales date + // to "today" + // As date fields do this defaulting automatically, the semantics is inverted here: + // If we're told to default, we must do nothing, if we should not default, we must + // reset the value which the date field set automatically. + + Integer aConcurrency = (Integer)xFormProps.getPropertyValue( "ResultSetConcurrency" ); + if ( ResultSetConcurrency.READ_ONLY != aConcurrency.intValue() ) + { + // we're going to modify the record, though after that, to the user, it should look + // like it has not been modified + // So we need to ensure that we do not change the IsModified property with whatever we do + Object aModifiedFlag = xFormProps.getPropertyValue( "IsModified" ); + + + // get the columns of our master form + XColumnsSupplier xSuppCols = UnoRuntime.queryInterface( + XColumnsSupplier.class, xFormProps ); + XNameAccess xCols = xSuppCols.getColumns(); + + // and update the date column with a NULL value + XColumnUpdate xDateColumn = UnoRuntime.queryInterface( + XColumnUpdate.class, xCols.getByName( "SALEDATE" ) ); + xDateColumn.updateNull(); + + + // then restore the flag + xFormProps.setPropertyValue( "IsModified", aModifiedFlag ); + } + } + } + } + catch( com.sun.star.uno.Exception e ) + { + System.out.println(e); + e.printStackTrace(); + } + } + + /* ------------------------------------------------------------------ */ + // XPropertyChangeListener overridables + /* ------------------------------------------------------------------ */ + public void propertyChange( PropertyChangeEvent aEvent ) throws com.sun.star.uno.RuntimeException + { + try + { + // did it come from a radio button or checkbox? + if ( aEvent.PropertyName.equals( "State" ) ) + { // yep + Short aNewState = (Short)aEvent.NewValue; + + XPropertySet xModel = UNO.queryPropertySet( aEvent.Source ); + String sName = (String)xModel.getPropertyValue( "Name" ); + + Short aClassId = (Short)xModel.getPropertyValue( "ClassId" ); + if ( FormComponentType.RADIOBUTTON == aClassId.shortValue() ) + { + String sRefValue = (String)xModel.getPropertyValue( "RefValue" ); + + short nNewValue = ((Short)aEvent.NewValue).shortValue(); + if ( sName.equals( "KeyGen" ) ) + { + // it's one of the options for key generation + if ( sRefValue.equals( "none" ) ) + { // no automatic generation at all + m_aSalesmanKeyGenerator.stopGenerator( ); + m_aSalesKeyGenerator.stopGenerator( ); + } + else + { + boolean bGenerateOnReset = true; + if ( sRefValue.equals( "update" ) ) + { // generate on update + bGenerateOnReset = ( 0 == nNewValue ); + } + else if ( sRefValue.equals( "reset" ) ) + { // generate on reset + bGenerateOnReset = ( 0 != nNewValue ); + } + m_aSalesmanKeyGenerator.activateKeyGenerator( bGenerateOnReset ); + m_aSalesKeyGenerator.activateKeyGenerator( bGenerateOnReset ); + } + } + } + else if ( FormComponentType.CHECKBOX == aClassId.shortValue() ) + { + boolean bEnabled = ( 0 != aNewState.shortValue() ); + if ( sName.equals( "defaultdate" ) ) + { + m_bDefaultSalesDate = bEnabled; + } + else if ( sName.equals( "protectkeys" ) ) + { + m_bProtectKeyFields = bEnabled; + m_aSalesmenLocker.enableLock( m_bProtectKeyFields ); + m_aSalesLocker.enableLock( m_bProtectKeyFields ); + } + else if ( sName.equals( "emptysales" ) ) + { + m_bAllowEmptySales = bEnabled; + m_aSalesNameValidator.enableColumnWatch( m_bAllowEmptySales ); + } + } + } + } + catch(com.sun.star.uno.Exception e) + { + System.out.println(e); + e.printStackTrace(); + } + } + + /* ------------------------------------------------------------------ */ + // XEventListener overridables + /* ------------------------------------------------------------------ */ + @Override + public void disposing( EventObject aEvent ) + { + // simply disambiguate + super.disposing( aEvent ); + } + + /* ================================================================== + = miscellaneous + ================================================================== */ + + /* ------------------------------------------------------------------ */ + /** skips line feeds in the input stream + + @returns + the first character which does not belong to a line feed + */ + protected int skipLineFeeds( java.io.InputStream aInput ) throws java.io.IOException + { + // read characters, until we encounter something which is not a line feed character + int nChar = aInput.read( ); + while ( ( 13 == nChar ) || ( 10 == nChar ) ) + nChar = aInput.read( ); + + // now read everything which is behind this single character we are interested in + while ( 0 < aInput.available() ) + aInput.read( ); + + return nChar; + } + + /* ================================================================== + = table handling + ================================================================== */ + /* ------------------------------------------------------------------ */ + /** checks if a given table exists. + +

The check is made using a SELECT statement, so even if the connection + is a n SDB-level connection, which may filter tables in its table + supplier, the result may be reliable...

+ */ + protected boolean existsInvisibleTable( XConnection xConn, String sTableName ) throws java.lang.Exception + { + String sStatement = "SELECT * FROM "; + sStatement += sTableName; + sStatement += " WHERE 0=1"; + + boolean bSuccess = false; + try + { + XStatement xStatement = xConn.createStatement(); + xStatement.execute( sStatement ); + // if we reached this point, the table probably exists + bSuccess = true; + } + catch(com.sun.star.sdbc.SQLException e) + { + } + return bSuccess; + } + + /* ------------------------------------------------------------------ */ + /** add a specified table name to the table filter of the given data source. + */ + protected void makeTableVisible( XDataSource xDS, String sTableName ) throws java.lang.Exception + { + // get the table filter + XPropertySet xDSP = UNO.queryPropertySet( xDS ); + String[] aCurrentFilter = (String[])xDSP.getPropertyValue( "TableFilter" ); + + // check if the table name is already part of it + String sAllTables = "*"; // all tables + + for ( int i=0; i if and only if the creation succeeded + */ + protected boolean createTableSalesman( XConnection xConn ) throws java.lang.Exception + { + String sCreateStatement = "CREATE TABLE " + s_tableNameSalesmen + " "; + sCreateStatement += "(SNR INTEGER NOT NULL, "; + sCreateStatement += "FIRSTNAME VARCHAR(50), "; + sCreateStatement += "LASTNAME VARCHAR(100), "; + sCreateStatement += "STREET VARCHAR(50), "; + sCreateStatement += "STATE VARCHAR(50), "; + sCreateStatement += "ZIP INTEGER, "; + sCreateStatement += "BIRTHDATE DATE, "; + sCreateStatement += "PRIMARY KEY(SNR))"; + + if ( implCreateTable( xConn, sCreateStatement, s_tableNameSalesmen) ) + { + String sInsertionPrefix = "INSERT INTO " + s_tableNameSalesmen + " VALUES "; + + implExecuteStatement( xConn, sInsertionPrefix + "(1, 'Joseph', 'Smith', 'Bond Street', 'CA', 95460, '1946-07-02')" ); + implExecuteStatement( xConn, sInsertionPrefix + "(2, 'Frank', 'Jones', 'Lake silver', 'CA', 95460, '1963-12-24')" ); + implExecuteStatement( xConn, sInsertionPrefix + "(3, 'Jane', 'Esperansa', '23 Hollywood driver', 'CA', 95460, '1972-04-01')" ); + + return true; + } + return false; + } + + /* ------------------------------------------------------------------ */ + /** creates the table CUSTOMERS + + @return + if and only if the creation succeeded + */ + protected boolean createTableCustomer( XConnection xConn ) throws java.lang.Exception + { + String sCreateStatement = "CREATE TABLE " + s_tableNameCustomers + " "; + sCreateStatement += "(COS_NR INTEGER NOT NULL, "; + sCreateStatement += "LASTNAME VARCHAR(100), "; + sCreateStatement += "STREET VARCHAR(50), "; + sCreateStatement += "CITY VARCHAR(50), "; + sCreateStatement += "STATE VARCHAR(50), "; + sCreateStatement += "ZIP INTEGER, "; + sCreateStatement += "PRIMARY KEY(COS_NR))"; + + if ( implCreateTable( xConn, sCreateStatement, s_tableNameCustomers ) ) + { + String sInsertionPrefix = "INSERT INTO " + s_tableNameCustomers + " VALUES "; + + implExecuteStatement( xConn, sInsertionPrefix + "(100, 'Acme, Inc.', '99 Market Street', 'Groundsville', 'CA', 95199)" ); + implExecuteStatement( xConn, sInsertionPrefix + "(101, 'Superior BugSoft', '1 Party Place', 'Mendocino', 'CA', 95460)"); + implExecuteStatement( xConn, sInsertionPrefix + "(102, 'WeKnowAll, Inc.', '100 Coffee Lane', 'Meadows', 'CA', 93699)"); + + return true; + } + return false; + } + + /* ------------------------------------------------------------------ */ + /** creates the table SALES + + @return + if and only if the creation succeeded + */ + protected boolean createTableSales( XConnection xConn ) throws java.lang.Exception + { + String sCreateStatement = "CREATE TABLE " + s_tableNameSales + " "; + sCreateStatement += "(SALENR INTEGER NOT NULL, "; + sCreateStatement += "COS_NR INTEGER NOT NULL, "; + sCreateStatement += "SNR INTEGER NOT NULL, "; + sCreateStatement += "NAME VARCHAR(50), "; + sCreateStatement += "SALEDATE DATE, "; + sCreateStatement += "PRICE DECIMAL(8,2), "; + sCreateStatement += "PRIMARY KEY(SALENR))"; + + if ( implCreateTable( xConn, sCreateStatement, s_tableNameSales ) ) + { + String sInsertionPrefix = "INSERT INTO " + s_tableNameSales + " VALUES "; + + implExecuteStatement( xConn, sInsertionPrefix + "(1, 100, 1, 'Fruits', '2005-02-12', 39.99)" ); + implExecuteStatement( xConn, sInsertionPrefix + "(2, 101, 3, 'Beef', '2005-10-18', 15.78)" ); + implExecuteStatement( xConn, sInsertionPrefix + "(3, 102, 3, 'Orange Juice', '2005-09-08', 25.63)" ); + implExecuteStatement( xConn, sInsertionPrefix + "(4, 101, 2, 'Oil', '2005-03-01', 12.30)" ); + + return true; + } + + return false; + } + + /* ------------------------------------------------------------------ */ + /** ensures that the tables we need for our example exist + */ + protected void ensureTables() throws java.lang.Exception + { + // get the data source + XDataSource xDS = m_database.getDataSource(); + XPropertySet xDSProps = UNO.queryPropertySet( xDS ); + + // connect to this data source + XConnection xConn = xDS.getConnection( "", "" ); + XComponent xConnComp = UNO.queryComponent( xConn ); + + createTableSalesman( xConn ); + createTableCustomer( xConn ); + createTableSales( xConn ); + + // free the resources acquired by the connection + xConnComp.dispose(); + } + + /* ================================================================== + = sample document handling + ================================================================== */ + + /* ------------------------------------------------------------------ */ + /** creates the button used for demonstrating (amongst others) event handling + @param nXPos + x-position of the to be inserted shape + @param nYPos + y-position of the to be inserted shape + @param nXSize + width of the to be inserted shape + @param sName + the name of the model in the form component hierarchy + @param sLabel + the label of the button control + @param sActionURL + the URL of the action which should be triggered by the button + @return + the model of the newly created button + */ + protected XPropertySet createButton( int nXPos, int nYPos, int nXSize, String sName, String sLabel, short _formFeature ) throws java.lang.Exception + { + XPropertySet xButton = m_formLayer.createControlAndShape( "CommandButton", nXPos, nYPos, nXSize, 6 ); + // the name for referring to it later: + xButton.setPropertyValue( "Name", sName ); + // the label + xButton.setPropertyValue( "Label", sLabel ); + // use the name as help text + xButton.setPropertyValue( "HelpText", sName ); + // don't want buttons to be accessible by the "tab" key - this would be uncomfortable when traveling + // with records with "tab" + xButton.setPropertyValue( "Tabstop", Boolean.FALSE ); + // similar, they should not steal the focus when clicked + xButton.setPropertyValue( "FocusOnClick", Boolean.FALSE ); + + m_aOperator.addButton( xButton, _formFeature ); + + return xButton; + } + + /* ------------------------------------------------------------------ */ + /** creates a column in a grid + @param xGridModel + specifies the model of the grid where the new column should be inserted + @param sColumnService + specifies the service name of the column to create (e.g. "NumericField") + @param sDataField + specifies the database field to which the column should be bound + @param nWidth + specifies the column width (in mm). If 0, no width is set. + @return + the newly created column + */ + XPropertySet createGridColumn( Object aGridModel, String sColumnService, String sDataField, int nWidth ) + throws com.sun.star.uno.Exception + { + // the container to insert columns into + XIndexContainer xColumnContainer = UNO.queryIndexContainer( aGridModel ); + // the factory for creating column models + XGridColumnFactory xColumnFactory = UnoRuntime.queryInterface( + XGridColumnFactory.class, aGridModel ); + + // (let) create the new col + XInterface xNewCol = xColumnFactory.createColumn( sColumnService ); + XPropertySet xColProps = UNO.queryPropertySet( xNewCol ); + + // some props + // the field the column is bound to + xColProps.setPropertyValue( "DataField", sDataField ); + // the "display name" of the column + xColProps.setPropertyValue( "Label", sDataField ); + // the name of the column within its parent + xColProps.setPropertyValue( "Name", sDataField ); + + if ( nWidth > 0 ) + xColProps.setPropertyValue( "Width", Integer.valueOf( nWidth * 10 ) ); + + // insert + xColumnContainer.insertByIndex( xColumnContainer.getCount(), xNewCol ); + + // outta here + return xColProps; + } + + /* ------------------------------------------------------------------ */ + /** creates a column in a grid + */ + XPropertySet createGridColumn( Object aGridModel, String sColumnService, String sDataField ) + throws com.sun.star.uno.Exception + { + return createGridColumn( aGridModel, sColumnService, sDataField ); + } + + /* ------------------------------------------------------------------ */ + /** creates our sample document + */ + @Override + protected void prepareDocument() throws com.sun.star.uno.Exception, java.lang.Exception + { + super.prepareDocument(); + + m_database = new HsqlDatabase( m_xCtx ); + + // ensure that we have the tables needed for our example + ensureTables(); + + + /* create some shapes */ + XPropertySet xSNRField = m_formLayer.insertControlLine( "NumericField", "SNR", "", 3 ); + m_formLayer.insertControlLine( "TextField", "FIRSTNAME", "", 11); + m_formLayer.insertControlLine( "TextField", "LASTNAME", "", 19 ); + m_formLayer.insertControlLine( "TextField", "STREET", "", 27 ); + m_formLayer.insertControlLine( "TextField", "STATE", "", 35 ); + XPropertySet xZipField = m_formLayer.insertControlLine( "NumericField", "ZIP", "", 43 ); + m_formLayer.insertControlLine( "FormattedField", "BIRTHDATE", "", 51 ); + + // for the salesman number / zip code, we don't want to have decimal places: + xSNRField.setPropertyValue( "DecimalAccuracy", Short.valueOf( (short)0 ) ); + xZipField.setPropertyValue( "DecimalAccuracy", Short.valueOf( (short)0 ) ); + + + /** need the form the control models belong to + for this, we simply obtain the parent for any of the control models we have + + Note that this involves knowledge about the implementation: If a control shape is + inserted into a document, where the control model does not belong to the form component + hierarchy, yet, it is automatically inserted into the first form, which is created + if necessary. + */ + m_xMasterForm = FLTools.getParent( xZipField ); + + // set the data source signature at the form + m_xMasterForm.setPropertyValue( "DataSourceName", m_database.getDocumentURL() ); + m_xMasterForm.setPropertyValue( "CommandType", Integer.valueOf( CommandType.TABLE ) ); + m_xMasterForm.setPropertyValue( "Command", "SALESMEN" ); + + + // insert the buttons + // create our button operator, if necessary + m_aOperator = new ButtonOperator( m_xCtx, m_document, m_xMasterForm ); + + createButton( 2, 63, 8, "first", "<<", FormFeature.MoveToFirst ); + createButton( 12, 63, 8, "prev", "<", FormFeature.MoveToPrevious ); + createButton( 22, 63, 8, "next", ">", FormFeature.MoveToNext ); + createButton( 32, 63, 8, "last", ">>", FormFeature.MoveToLast ); + createButton( 42, 63, 8, "new", ">*", FormFeature.MoveToInsertRow ); + createButton( 58, 63, 13, "reload", "reload", FormFeature.ReloadForm ); + + + // create a sub form for the sales + + // for this, first create a sub form and bind it to the SALES table + XIndexContainer xSalesForm = m_document.createSubForm( m_xMasterForm, "Sales" ); + XPropertySet xSalesFormProps = UNO.queryPropertySet( xSalesForm ); + + xSalesFormProps.setPropertyValue( "DataSourceName", m_database.getDocumentURL() ); + xSalesFormProps.setPropertyValue( "CommandType", Integer.valueOf( CommandType.COMMAND ) ); + + String sCommand = "SELECT * FROM "; + sCommand += s_tableNameSales; + sCommand += " WHERE " + s_tableNameSales + ".SNR = :salesmen"; + xSalesFormProps.setPropertyValue( "Command", sCommand ); + + // the master-details connection + String[] aMasterFields = new String[] { "SNR" }; // the field in the master form + String[] aDetailFields = new String[] { "salesmen" }; // the name in the detail form + xSalesFormProps.setPropertyValue( "MasterFields", aMasterFields ); + xSalesFormProps.setPropertyValue( "DetailFields", aDetailFields ); + + // the create thr grid model + XPropertySet xSalesGridModel = m_formLayer.createControlAndShape( "GridControl", 2, 80, 162, 40, xSalesForm ); + xSalesGridModel.setPropertyValue( "Name", "SalesTable" ); + XPropertySet xKeyColumn = createGridColumn( xSalesGridModel, "NumericField", "SALENR", 12 ); + XPropertySet xCustomerColumn = createGridColumn( xSalesGridModel, "ListBox", "COS_NR", 40 ); + XPropertySet xSalesNameColumn = createGridColumn( xSalesGridModel, "TextField", "NAME", 25 ); + createGridColumn( xSalesGridModel, "DateField", "SALEDATE", 24 ); + createGridColumn( xSalesGridModel, "CurrencyField", "PRICE", 16 ); + + // please note that a better solution for the SALEDATE field would have been to use + // a FormattedField. But we want to demonstrate some effects with DateFields here ... + + m_aSalesNameValidator = new GridFieldValidator( m_xCtx, xSalesNameColumn ); + m_aSalesNameValidator.enableColumnWatch( m_bAllowEmptySales ); + + xKeyColumn.setPropertyValue( "DecimalAccuracy", Short.valueOf( (short)0 ) ); + + // init the list box which is for choosing the customer a sale belongs to + xCustomerColumn.setPropertyValue( "BoundColumn", Short.valueOf( (short)1 ) ); + xCustomerColumn.setPropertyValue( "Label", "Customer" ); + xCustomerColumn.setPropertyValue( "ListSourceType", ListSourceType.SQL ); + + String sListSource = "SELECT LASTNAME, COS_NR FROM "; + sListSource += s_tableNameCustomers; + String[] aListSource = new String[] { sListSource }; + xCustomerColumn.setPropertyValue( "ListSource", aListSource ); + + // We want to demonstrate how to reset fields to NULL, we do this with the SALEDATE field + // above. For this, we add as reset listener to the form + XReset xFormReset = UNO.queryReset( xSalesForm ); + xFormReset.addResetListener( this ); + + + + // the option for filtering the sales form + XIndexContainer xSalesFilterForm = m_document.createSiblingForm( xSalesForm, "SalesFilter" ); + XPropertySet xSFFProps = UNO.queryPropertySet( xSalesFilterForm ); + XPropertySet xLabel = m_formLayer.createControlAndShape( "FixedText", 2, 125, 35, 6, xSalesFilterForm ); + xLabel.setPropertyValue( "Label", "show only sales since" ); + xLabel.setPropertyValue( "Name", "FilterLabel" ); + + XPropertySet xFilterSelection = m_formLayer.createControlAndShape( "ListBox", 40, 125, 59, 6, xSalesFilterForm ); + xFilterSelection.setPropertyValue( "Name", "FilterList" ); + xFilterSelection.setPropertyValue( "LabelControl", xLabel ); + XPropertySet xManualFilter = m_formLayer.createControlAndShape( "DateField", 104, 125, 30, 6, xSalesFilterForm ); + xManualFilter.setPropertyValue( "Name", "ManualFilter" ); + XPropertySet xApplyFilter = m_formLayer.createControlAndShape( "CommandButton", 139, 125, 25, 6, xSalesFilterForm ); + xApplyFilter.setPropertyValue( "Name", "ApplyFilter" ); + xApplyFilter.setPropertyValue( "DefaultButton", Boolean.TRUE ); + new SalesFilter( m_document, xSalesFormProps, xFilterSelection, + xManualFilter, xApplyFilter ); + + + + // the options section + // for this, we need a form which is a sibling of our master form (don't want to interfere + // the controls which represent options only with the controls which are used for data access) + + XIndexContainer xOptionsForm = m_document.createSiblingForm( m_xMasterForm, "Options" ); + + xLabel = m_formLayer.createControlAndShape( "GroupBox", 98, 0, 66, 62, xOptionsForm ); + xLabel.setPropertyValue( "Name", "Options" ); + xLabel.setPropertyValue( "Label", "Options" ); + + // radio buttons which controls how we generate unique keys + xLabel = m_formLayer.createControlAndShape( "GroupBox", 103, 5, 56, 25, xOptionsForm ); + xLabel.setPropertyValue( "Label", "key generation" ); + xLabel.setPropertyValue( "Name", "KeyGeneration" ); + XPropertySet xKeyGen = m_formLayer.createControlAndShape( "RadioButton", 106, 11, 50, 6, xOptionsForm ); + xKeyGen.setPropertyValue( "Name", "KeyGen" ); + xKeyGen.setPropertyValue( "Label", "no automatic generation" ); + xKeyGen.setPropertyValue( "RefValue", "none" ); + xKeyGen.addPropertyChangeListener( "State", this ); + + xKeyGen = m_formLayer.createControlAndShape( "RadioButton", 106, 17, 50, 6, xOptionsForm ); + xKeyGen.setPropertyValue( "Name", "KeyGen" ); + xKeyGen.setPropertyValue( "Label", "before inserting a record" ); + xKeyGen.setPropertyValue( "RefValue", "update" ); + xKeyGen.addPropertyChangeListener( "State", this ); + + xKeyGen = m_formLayer.createControlAndShape( "RadioButton", 106, 23, 50, 6, xOptionsForm ); + xKeyGen.setPropertyValue( "Name", "KeyGen" ); + xKeyGen.setPropertyValue( "Label", "when moving to a new record" ); + xKeyGen.setPropertyValue( "RefValue", "reset" ); + xKeyGen.addPropertyChangeListener( "State", this ); + + // initialize listeners + // master form - key generation + m_aSalesmanKeyGenerator = new KeyGenerator( m_xMasterForm, "SNR", m_xCtx ); + m_aSalesmanKeyGenerator.activateKeyGenerator( true ); + // master form - control locking + m_aSalesmenLocker = new ControlLock( m_xMasterForm, "SNR" ); + m_aSalesmenLocker.enableLock( m_bProtectKeyFields ); + + // details form - key generation + m_aSalesKeyGenerator = new KeyGenerator( xSalesFormProps, "SALENR", m_xCtx ); + m_aSalesKeyGenerator.activateKeyGenerator( true ); + + // details form - control locking + m_aSalesLocker = new ControlLock( xSalesFormProps, "SALENR" ); + m_aSalesLocker.enableLock( m_bProtectKeyFields ); + + // initially, we want to generate keys when moving to a new record + xKeyGen.setPropertyValue( "DefaultState", Short.valueOf( (short)1 ) ); + + + // second options block + xLabel = m_formLayer.createControlAndShape( "GroupBox", 103, 33, 56, 25, xOptionsForm ); + xLabel.setPropertyValue( "Name", "Misc" ); + xLabel.setPropertyValue( "Label", "Miscellaneous" ); + + XPropertySet xCheck = m_formLayer.createControlAndShape( "CheckBox", 106, 39, 60, 6, xOptionsForm ); + xCheck.setPropertyValue( "Name", "defaultdate" ); + xCheck.setPropertyValue( "Label", "default sales date to \"today\"" ); + xCheck.setPropertyValue( "HelpText", "When checked, newly entered sales records are pre-filled with today's date, else left empty." ); + xCheck.addPropertyChangeListener( "State", this ); + + xCheck = m_formLayer.createControlAndShape( "CheckBox", 106, 45, 60, 6, xOptionsForm ); + xCheck.setPropertyValue( "Name", "protectkeys" ); + xCheck.setPropertyValue( "Label", "protect key fields from editing" ); + xCheck.setPropertyValue( "HelpText", "When checked, you cannot modify the values in the table's key fields (SNR and SALENR)" ); + xCheck.addPropertyChangeListener( "State", this ); + + xCheck = m_formLayer.createControlAndShape( "CheckBox", 106, 51, 60, 6, xOptionsForm ); + xCheck.setPropertyValue( "Name", "emptysales" ); + xCheck.setPropertyValue( "Label", "check for empty sales names" ); + xCheck.setPropertyValue( "HelpText", "When checked, you cannot enter empty values into the NAME column of the 'Sales' table." ); + xCheck.addPropertyChangeListener( "State", this ); + + // dump the form component tree + enumFormComponents( ); + } + + /* ------------------------------------------------------------------ */ + @Override + protected void onFormsAlive() + { + m_aOperator.onFormsAlive(); + } + + /* ------------------------------------------------------------------ */ + /** performs any cleanup before exiting the program + */ + @Override + protected void cleanUp( ) throws java.lang.Exception + { + // remove the listeners at the buttons + RevokeButtons aRevoke = new RevokeButtons( m_aOperator ); + aRevoke.handle( m_document.getFormComponentTreeRoot( ) ); + + // remove the key generator listeners from the form + m_aSalesmanKeyGenerator.stopGenerator( ); + m_aSalesKeyGenerator.stopGenerator( ); + + // and the control lockers + m_aSalesmenLocker.enableLock( false ); + m_aSalesLocker.enableLock( false ); + + // the validator for the grid column + m_aSalesNameValidator.enableColumnWatch( false ); + + // remove our own reset listener from the form + XNameAccess xMasterAsNames = UnoRuntime.queryInterface( + XNameAccess.class, m_xMasterForm ); + XReset xFormReset = UNO.queryReset( xMasterAsNames.getByName( "Sales" ) ); + xFormReset.removeResetListener( this ); + + super.cleanUp(); + } + + /* ------------------------------------------------------------------ */ + /** class entry point + */ + public static void main(String argv[]) throws java.lang.Exception + { + DataAwareness aSample = new DataAwareness(); + aSample.run( argv ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/DateValidator.java b/odk/examples/DevelopersGuide/Forms/DateValidator.java new file mode 100644 index 000000000..646dfac79 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/DateValidator.java @@ -0,0 +1,91 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +public class DateValidator extends ControlValidator +{ + + /** Creates a new instance of NumericValidator */ + public DateValidator( ) + { + } + + public String explainInvalid( Object Value ) + { + try + { + if ( isVoid( Value ) ) + return "empty input"; + + com.sun.star.util.Date dateValue = (com.sun.star.util.Date)Value; + if ( isDedicatedInvalidDate( dateValue ) ) + return "this is no valid date"; + + if ( !isNextMonthsDate( dateValue ) ) + return "date must denote a day in the current month"; + } + catch( java.lang.Exception e ) + { + return "oops. What did you enter for this to happen?"; + } + return ""; + } + + public boolean isValid( Object Value ) + { + try + { + if ( isVoid( Value ) ) + return false; + + com.sun.star.util.Date dateValue = (com.sun.star.util.Date) + com.sun.star.uno.AnyConverter.toObject( + com.sun.star.util.Date.class, Value); + if ( isDedicatedInvalidDate( dateValue ) ) + return false; + + if ( !isNextMonthsDate( dateValue ) ) + return false; + return true; + } + catch( java.lang.Exception e ) + { + e.printStackTrace( System.err ); + } + return false; + } + + private boolean isDedicatedInvalidDate( com.sun.star.util.Date dateValue ) + { + return ( dateValue.Day == 0 ) && ( dateValue.Month == 0 ) && ( dateValue.Year == 0 ); + } + + private boolean isNextMonthsDate( com.sun.star.util.Date dateValue ) + { + int overallMonth = dateValue.Year * 12 + dateValue.Month - 1; + + int todaysMonth = new java.util.Date().getMonth(); + int todaysYear = new java.util.Date().getYear() + 1900; + int todaysOverallMonth = todaysYear * 12 + todaysMonth; + + return overallMonth == todaysOverallMonth; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/DocumentBasedExample.java b/odk/examples/DevelopersGuide/Forms/DocumentBasedExample.java new file mode 100644 index 000000000..34735221f --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/DocumentBasedExample.java @@ -0,0 +1,219 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.util.XCloseable; + +public abstract class DocumentBasedExample implements com.sun.star.lang.XEventListener +{ + /// the initial remote context from the office + protected XComponentContext m_xCtx; + /// our current test document + protected DocumentHelper m_document; + protected FormLayer m_formLayer; + private DocumentType m_documentType; + + /** Creates a new instance of DocumentBasedExample */ + public DocumentBasedExample( DocumentType documentType ) + { + bootstrapUNO(); + m_documentType = documentType; + } + + /* ------------------------------------------------------------------ */ + private void bootstrapUNO() + { + try + { + /* + final XComponentContext componentContext = com.sun.star.comp.helper.Bootstrap. + createInitialComponentContext( null ); + final XMultiComponentFactory localServiceManager = componentContext.getServiceManager(); + + final XUnoUrlResolver urlResolver = (XUnoUrlResolver) UnoRuntime.queryInterface( + XUnoUrlResolver.class, localServiceManager.createInstanceWithContext( + "com.sun.star.bridge.UnoUrlResolver", componentContext) ); + + final String connectStr = "uno:pipe,name=;urp;StarOffice.ComponentContext"; + final Object initialObject = urlResolver.resolve( connectStr ); + + m_xCtx = (XComponentContext)UnoRuntime.queryInterface( XComponentContext.class, + initialObject ); + */ + + // get the remote office component context + m_xCtx = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + } + catch (java.lang.Exception e) + { + e.printStackTrace( System.err ); + System.exit(1); + } + } + + /* ------------------------------------------------------------------ */ + /** main method for running the sample + */ + public void run( String argv[] ) + { + try + { + // collect whatever parameters were given + collectParameters( argv ); + + // prepare our sample document + prepareDocument(); + + // switch the document view's form layer to alive mode + m_document.getCurrentView().toggleFormDesignMode(); + onFormsAlive(); + + // grab the focus to the first control + m_document.getCurrentView().grabControlFocus(); + + + // wait for the user to confirm that we can exit + if ( waitForUserInput() ) + { + // clean up + cleanUp(); + } + + // if waitForUserInput returns false, the user closed the document manually - no need to do a clean up + // then + } + catch(com.sun.star.uno.Exception e) + { + System.out.println(e); + e.printStackTrace(); + } + catch(java.lang.Exception e) + { + System.out.println(e); + e.printStackTrace(); + } + + System.exit(0); + } + + /* ------------------------------------------------------------------ */ + /** collect the RuntimeArguments + */ + private void collectParameters(String argv[]) + { + // not interested in. Derived classes may want to use it. + } + + /* ------------------------------------------------------------------ */ + /** prepares a new document to work with + */ + protected void prepareDocument() throws com.sun.star.uno.Exception, java.lang.Exception + { + m_document = DocumentHelper.blankDocument(m_xCtx, m_documentType); + m_document.getDocument( ).addEventListener( this ); + m_formLayer = new FormLayer( m_document ); + } + + /* ------------------------------------------------------------------ */ + /** called when the form layer has been switched to alive mode + */ + protected void onFormsAlive() + { + } + + /* ------------------------------------------------------------------ */ + /** performs any cleanup before exiting the program + */ + protected void cleanUp( ) throws java.lang.Exception + { + // do not listen at the document any longer + m_document.getDocument().removeEventListener( this ); + + // close the document + closeDocument(); + } + + /* ------------------------------------------------------------------ */ + /** closes our document, if we have an open one + */ + private void closeDocument() + { + try + { + // close our document + if ( m_document != null ) + { + XCloseable closeDoc = UnoRuntime.queryInterface( XCloseable.class, + m_document.getDocument() ); + if (closeDoc != null) + closeDoc.close( true ); + else + m_document.getDocument().dispose(); + } + } + catch ( com.sun.star.uno.Exception e ) + { + e.printStackTrace( System.err ); + } + } + + /* ------------------------------------------------------------------ */ + /* internal methods */ + /* ------------------------------------------------------------------ */ + /** waits for the user to press a key (on the console where she started + the java program) or the document to be closed by the user. + + @return if the user pressed a key on the console, + if she closed the document + */ + protected boolean waitForUserInput() throws java.lang.Exception + { + synchronized (this) + { + WaitForInput aWait = new WaitForInput( this ); + aWait.start(); + wait(); + + // if the waiter thread is done, the user pressed enter + boolean bKeyPressed = aWait.isDone(); + if ( !bKeyPressed ) + aWait.interrupt(); + + return bKeyPressed; + } + } + + /* ------------------------------------------------------------------ */ + /* XEventListener overridables */ + /* ------------------------------------------------------------------ */ + public void disposing( com.sun.star.lang.EventObject eventObject ) + { + if ( m_document.getDocument().equals( eventObject.Source ) ) + { + // notify ourself that we can stop waiting for user input + synchronized (this) + { + notify(); + } + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/DocumentHelper.java b/odk/examples/DevelopersGuide/Forms/DocumentHelper.java new file mode 100644 index 000000000..abfda37c4 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/DocumentHelper.java @@ -0,0 +1,306 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +/**************************************************************************/ +import com.sun.star.uno.*; +import com.sun.star.lang.*; +import com.sun.star.drawing.*; +import com.sun.star.frame.*; +import com.sun.star.form.*; +import com.sun.star.beans.*; +import com.sun.star.container.*; + +/**************************************************************************/ +/** provides a small wrapper around a document +*/ +public class DocumentHelper +{ + /// the remote office context + private XComponentContext m_remoteContext; + /// the remote service manager + private XMultiServiceFactory m_orb; + protected XComponent m_documentComponent; + + /* ------------------------------------------------------------------ */ + public XComponent getDocument( ) + { + return m_documentComponent; + } + + /* ------------------------------------------------------------------ */ + public XComponentContext getContext( ) + { + return m_remoteContext; + } + + /* ------------------------------------------------------------------ */ + public XMultiServiceFactory getOrb( ) + { + return m_orb; + } + + /* ------------------------------------------------------------------ */ + public DocumentHelper( XComponentContext xContext, XComponent document ) + { + m_remoteContext = xContext; + m_orb = UnoRuntime.queryInterface( + XMultiServiceFactory.class, m_remoteContext.getServiceManager()); + m_documentComponent = document; + } + + /* ------------------------------------------------------------------ */ + protected static XComponent implCreateBlankDocument( XComponentContext xCtx, String factoryURL ) throws com.sun.star.uno.Exception + { + XComponentLoader aLoader = UnoRuntime.queryInterface( + XComponentLoader.class, + xCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.frame.Desktop", xCtx )); + + return UNO.queryComponent( + aLoader.loadComponentFromURL( factoryURL, "_blank", 0, new PropertyValue[ 0 ] ) + ); + } + + + + /* ------------------------------------------------------------------ */ + public static DocumentHelper blankDocument( XComponentContext xCtx, DocumentType eType ) throws com.sun.star.uno.Exception + { + XComponent document = implCreateBlankDocument( xCtx, getDocumentFactoryURL( eType ) ); + if ( eType == DocumentType.CALC ) + return new SpreadsheetDocument( xCtx, document ); + + return new DocumentHelper( xCtx, document ); + } + + /* ------------------------------------------------------------------ */ + /** retrieves the current view of the document + @return + the view component, queried for the interface described by aInterfaceClass + */ + public DocumentViewHelper getCurrentView( ) + { + // get the model interface for the document + XModel xDocModel = UnoRuntime.queryInterface(XModel.class, m_documentComponent ); + // get the current controller for the document - as a controller is tied to a view, + // this gives us the currently active view for the document. + XController xController = xDocModel.getCurrentController(); + + if ( classify() == DocumentType.CALC ) + return new SpreadsheetView( m_orb, this, xController ); + + return new DocumentViewHelper( m_orb, this, xController ); + } + + /* ------------------------------------------------------------------ */ + /** creates a new form which is a child of the given form components container + + @param xParentContainer + The parent container for the new form + @param sInitialName + The initial name of the form. May be null, in this case the default (which + is an implementation detail) applies. + */ + private XIndexContainer createSubForm( XIndexContainer xParentContainer, String sInitialName ) + throws com.sun.star.uno.Exception + { + // create a new form + Object xNewForm = m_orb.createInstance( "com.sun.star.form.component.DataForm" ); + + // insert + xParentContainer.insertByIndex( xParentContainer.getCount(), xNewForm ); + + // set the name if necessary + if ( null != sInitialName ) + { + XPropertySet xFormProps = UNO.queryPropertySet( xNewForm ); + xFormProps.setPropertyValue( "Name", sInitialName ); + } + + // outta here + return UnoRuntime.queryInterface( XIndexContainer.class, xNewForm ); + } + + /* ------------------------------------------------------------------ */ + /** creates a new form which is a child of the given form components container + + @param aParentContainer + The parent container for the new form + @param sInitialName + The initial name of the form. May be null, in this case the default (which + is an implementation detail) applies. + */ + public XIndexContainer createSubForm( Object aParentContainer, String sInitialName ) + throws com.sun.star.uno.Exception + { + XIndexContainer xParentContainer = UnoRuntime.queryInterface( + XIndexContainer.class, aParentContainer ); + return createSubForm( xParentContainer, sInitialName ); + } + + /* ------------------------------------------------------------------ */ + /** creates a form which is a sibling of the given form + @param aForm + A sinbling of the to be created form. + + @param sInitialName + The initial name of the form. May be null, in this case the default (which + is an implementation detail) applies. + */ + public XIndexContainer createSiblingForm( Object aForm, String sInitialName ) throws com.sun.star.uno.Exception + { + // get the parent + XChild xAsChild = UnoRuntime.queryInterface( XChild.class, aForm ); + XIndexContainer xContainer = UnoRuntime.queryInterface( + XIndexContainer.class, xAsChild.getParent() ); + // append a new form to this parent container + return createSubForm( xContainer, sInitialName ); + } + + /* ------------------------------------------------------------------ */ + /** retrieves the document model which a given form component belongs to + */ + public static DocumentHelper getDocumentForComponent( Object aFormComponent, XComponentContext xCtx ) + { + XChild xChild = UnoRuntime.queryInterface( XChild.class, aFormComponent ); + XModel xModel = null; + while ( ( null != xChild ) && ( null == xModel ) ) + { + XInterface xParent = (XInterface)xChild.getParent(); + xModel = UnoRuntime.queryInterface( XModel.class, xParent ); + xChild = UnoRuntime.queryInterface( XChild.class, xParent ); + } + + return new DocumentHelper( xCtx, xModel ); + } + + /* ------------------------------------------------------------------ */ + /** returns a URL which can be used to create a document of a certain type + */ + private static String getDocumentFactoryURL( DocumentType eType ) + { + if ( eType == DocumentType.WRITER ) + return "private:factory/swriter"; + if ( eType == DocumentType.CALC ) + return "private:factory/scalc"; + if ( eType == DocumentType.DRAWING ) + return "private:factory/sdraw"; + return "private:factory/swriter"; + } + + /* ------------------------------------------------------------------ */ + /** classifies a document + */ + public DocumentType classify( ) + { + XServiceInfo xSI = UnoRuntime.queryInterface( + XServiceInfo.class, m_documentComponent ); + + if ( xSI.supportsService( "com.sun.star.text.TextDocument" ) ) + return DocumentType.WRITER; + else if ( xSI.supportsService( "com.sun.star.sheet.SpreadsheetDocument" ) ) + return DocumentType.CALC; + else if ( xSI.supportsService( "com.sun.star.drawing.DrawingDocument" ) ) + return DocumentType.DRAWING; + + return DocumentType.UNKNOWN; + } + /* ------------------------------------------------------------------ */ + /** retrieves a com.sun.star.drawing.DrawPage of the document, denoted by index + * @param index + * the index of the draw page
+ * @throws + * com.sun.star.lang.IndexOutOfBoundsException + * com.sun.star.lang.WrappedTargetException + */ + protected XDrawPage getDrawPage( int index ) throws com.sun.star.lang.IndexOutOfBoundsException, com.sun.star.lang.WrappedTargetException + { + XDrawPagesSupplier xSuppPages = UnoRuntime.queryInterface( + XDrawPagesSupplier.class, getDocument() ); + XDrawPages xPages = xSuppPages.getDrawPages(); + + return UnoRuntime.queryInterface( XDrawPage.class, xPages.getByIndex( index ) ); + } + + /* ------------------------------------------------------------------ */ + /** retrieves the DrawPage of the document + */ + protected XDrawPage getMainDrawPage( ) throws com.sun.star.uno.Exception + { + XDrawPage xReturn; + + // in case of a Writer document, this is rather easy: simply ask the XDrawPageSupplier + XDrawPageSupplier xSuppPage = UnoRuntime.queryInterface( + XDrawPageSupplier.class, getDocument() ); + if ( null != xSuppPage ) + xReturn = xSuppPage.getDrawPage(); + else + { // the model itself is no draw page supplier - okay, it may be a Writer or Calc document + // (or any other multi-page document) + XDrawPagesSupplier xSuppPages = UnoRuntime.queryInterface( + XDrawPagesSupplier.class, getDocument() ); + XDrawPages xPages = xSuppPages.getDrawPages(); + + xReturn = UnoRuntime.queryInterface( XDrawPage.class, xPages.getByIndex( 0 ) ); + + // Note that this is no really error-proof code: If the document model does not support the + // XDrawPagesSupplier interface, or if the pages collection returned is empty, this will break. + } + + return xReturn; + } + + /* ------------------------------------------------------------------ */ + /** retrieves the root of the hierarchy of form components + */ + protected XNameContainer getFormComponentTreeRoot( ) throws com.sun.star.uno.Exception + { + XFormsSupplier xSuppForms = UnoRuntime.queryInterface( + XFormsSupplier.class, getMainDrawPage( ) ); + + XNameContainer xFormsCollection = null; + if ( null != xSuppForms ) + { + xFormsCollection = xSuppForms.getForms(); + } + return xFormsCollection; + } + + /* ------------------------------------------------------------------ */ + /** creates a component at the service factory provided by the document + */ + public XInterface createInstance( String serviceSpecifier ) throws com.sun.star.uno.Exception + { + XMultiServiceFactory xORB = UnoRuntime.queryInterface( XMultiServiceFactory.class, + m_documentComponent ); + return (XInterface)xORB.createInstance( serviceSpecifier ); + } + + /* ------------------------------------------------------------------ */ + /** creates a component at the service factory provided by the document + */ + public XInterface createInstanceWithArguments( String serviceSpecifier, Object[] arguments ) throws com.sun.star.uno.Exception + { + XMultiServiceFactory xORB = UnoRuntime.queryInterface( XMultiServiceFactory.class, + m_documentComponent ); + return (XInterface) xORB.createInstanceWithArguments( serviceSpecifier, arguments ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/DocumentType.java b/odk/examples/DevelopersGuide/Forms/DocumentType.java new file mode 100644 index 000000000..3a8e83beb --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/DocumentType.java @@ -0,0 +1,40 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +/** a helper "enumeration class" for classifying a document type +*/ +public class DocumentType extends com.sun.star.uno.Enum +{ + private DocumentType( int value ) + { + super( value ); + } + + + + public static final DocumentType WRITER = new DocumentType(0); + public static final DocumentType CALC = new DocumentType(1); + public static final DocumentType DRAWING = new DocumentType(2); + public static final DocumentType UNKNOWN = new DocumentType(-1); + + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/DocumentViewHelper.java b/odk/examples/DevelopersGuide/Forms/DocumentViewHelper.java new file mode 100644 index 000000000..771b22784 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/DocumentViewHelper.java @@ -0,0 +1,215 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +import com.sun.star.awt.XControl; +import com.sun.star.awt.XControlModel; +import com.sun.star.awt.XWindow; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XIndexContainer; +import com.sun.star.form.FormComponentType; +import com.sun.star.form.XForm; +import com.sun.star.form.runtime.XFormController; +import com.sun.star.frame.XController; +import com.sun.star.frame.XDispatch; +import com.sun.star.frame.XDispatchProvider; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.util.URL; +import com.sun.star.util.XURLTransformer; +import com.sun.star.view.XControlAccess; +import com.sun.star.view.XFormLayerAccess; + + +/**************************************************************************/ +/** provides a small wrapper around a document view +*/ +class DocumentViewHelper +{ + private XMultiServiceFactory m_orb; + private XController m_controller; + private DocumentHelper m_document; + + /* ------------------------------------------------------------------ */ + final protected XController getController() + { + return m_controller; + } + + /* ------------------------------------------------------------------ */ + final protected DocumentHelper getDocument() + { + return m_document; + } + + /* ------------------------------------------------------------------ */ + public DocumentViewHelper( XMultiServiceFactory orb, DocumentHelper document, XController controller ) + { + m_orb = orb; + m_document = document; + m_controller = controller; + } + + /* ------------------------------------------------------------------ */ + /** Quick access to a given interface of the view + @param aInterfaceClass + the class of the interface which shall be returned + */ + private T get( Class aInterfaceClass ) + { + return UnoRuntime.queryInterface( aInterfaceClass, m_controller ); + } + + /* ------------------------------------------------------------------ */ + /** retrieves a dispatcher for the given URL, obtained at the current view of the document + @param aURL + a one-element array. The first element must contain a valid + URL::Complete value. Upon return, the URL is correctly + parsed. + @return + the dispatcher for the URL in question + */ + private XDispatch getDispatcher( URL[] aURL ) throws java.lang.Exception + { + XDispatch xReturn = null; + + // go get the current view + XController xController = get( XController.class ); + // go get the dispatch provider of its frame + XDispatchProvider xProvider = UnoRuntime.queryInterface( + XDispatchProvider.class, xController.getFrame() ); + if ( null != xProvider ) + { + // need a URLTransformer + XURLTransformer xTransformer = UnoRuntime.queryInterface( + XURLTransformer.class, m_orb.createInstance( "com.sun.star.util.URLTransformer" ) ); + xTransformer.parseStrict( aURL ); + + xReturn = xProvider.queryDispatch( aURL[0], "", 0 ); + } + return xReturn; + } + + + + /* ------------------------------------------------------------------ */ + /* retrieves the form controller belonging to a given logical form + */ + public XFormController getFormController( Object _form ) + { + XFormLayerAccess formLayer = get( XFormLayerAccess.class ); + return formLayer.getFormController( UnoRuntime.queryInterface( XForm.class, _form ) ); + } + + /* ------------------------------------------------------------------ */ + /** retrieves a control within the current view of a document + @param xModel + specifies the control model whose control should be located + @return + the control tied to the model + */ + private XControl getFormControl( XControlModel xModel ) throws com.sun.star.uno.Exception + { + // the current view of the document + XControlAccess xCtrlAcc = get( XControlAccess.class ); + // delegate the task of looking for the control + return xCtrlAcc.getControl( xModel ); + } + + /* ------------------------------------------------------------------ */ + public XControl getFormControl( Object aModel ) throws com.sun.star.uno.Exception + { + XControlModel xModel = UnoRuntime.queryInterface( XControlModel.class, aModel ); + return getFormControl( xModel ); + } + + /* ------------------------------------------------------------------ */ + public T getFormControl( Object aModel, Class aInterfaceClass ) throws com.sun.star.uno.Exception + { + XControlModel xModel = UnoRuntime.queryInterface( XControlModel.class, aModel ); + return UnoRuntime.queryInterface( aInterfaceClass, getFormControl( xModel ) ); + } + + /* ------------------------------------------------------------------ */ + /** toggles the design mode of the form layer of active view of our sample document + */ + protected void toggleFormDesignMode( ) throws java.lang.Exception + { + // get a dispatcher for the toggle URL + URL[] aToggleURL = new URL[] { new URL() }; + aToggleURL[0].Complete = ".uno:SwitchControlDesignMode"; + XDispatch xDispatcher = getDispatcher( aToggleURL ); + + // dispatch the URL - this will result in toggling the mode + PropertyValue[] aDummyArgs = new PropertyValue[] { }; + xDispatcher.dispatch( aToggleURL[0], aDummyArgs ); + } + + /* ------------------------------------------------------------------ */ + /** sets the focus to a specific control + @param xModel + a control model. The focus is set to that control which is part of our view + and associated with the given model. + */ + public void grabControlFocus( Object xModel ) throws com.sun.star.uno.Exception + { + // look for the control from the current view which belongs to the model + XControl xControl = getFormControl( xModel ); + + // the focus can be set to an XWindow only + XWindow xControlWindow = UnoRuntime.queryInterface( XWindow.class, + xControl ); + + // grab the focus + xControlWindow.setFocus(); + } + + /* ------------------------------------------------------------------ */ + /** sets the focus to the first control + */ + protected void grabControlFocus( ) throws java.lang.Exception + { + // the forms container of our document + XIndexContainer xForms = UNO.queryIndexContainer( m_document.getFormComponentTreeRoot( ) ); + // the first form + XIndexContainer xForm = UNO.queryIndexContainer( xForms.getByIndex( 0 ) ); + + // the first control model which is no FixedText (FixedText's can't have the focus) + for ( int i = 0; i fallback to the component name + sLabel = getName( aFormComponent ); + } + } + + return sLabel; + } + + + + /* ------------------------------------------------------------------ */ + /** retrieves the parent of the given object + */ + private static T getParent( Object aComponent, Class aInterfaceClass ) + { + XChild xAsChild = UnoRuntime.queryInterface( XChild.class, aComponent ); + + return UnoRuntime.queryInterface( aInterfaceClass, xAsChild.getParent() ); + } + + /* ------------------------------------------------------------------ */ + /** retrieves the parent of the given object + */ + static XPropertySet getParent( Object aComponent ) + { + return getParent( aComponent, XPropertySet.class ); + } + + /* ------------------------------------------------------------------ */ + /** disposes the component given + */ + public static void disposeComponent( Object xComp ) throws java.lang.RuntimeException + { + XComponent xComponent = UnoRuntime.queryInterface( XComponent.class, + xComp ); + if ( null != xComponent ) + xComponent.dispose(); + } + + /* ------------------------------------------------------------------ */ + /** gets the XControlModel for a control + */ + public static T getModel( Object aControl, Class aInterfaceClass ) + { + XControl xControl = UnoRuntime.queryInterface( + XControl.class, aControl ); + XControlModel xModel = null; + if ( null != xControl ) + xModel = xControl.getModel(); + + return UnoRuntime.queryInterface( aInterfaceClass, xModel ); + } + + /* ------------------------------------------------------------------ */ + /** retrieves the type of a form component. +

Speaking strictly, the function recognizes more than form components. Especially, + it survives a null argument. which means it can be safely applied to the a top-level + forms container; and it is able to classify grid columns (which are no form components) + as well.

+ */ + public static String classifyFormComponentType( XPropertySet xComponent ) throws com.sun.star.uno.Exception + { + String sType = ""; + + XServiceInfo xSI = UNO.queryServiceInfo( xComponent ); + + XPropertySetInfo xPSI = null; + if ( null != xComponent ) + xPSI = xComponent.getPropertySetInfo(); + + if ( ( null != xPSI ) && xPSI.hasPropertyByName( "ClassId" ) ) + { + // get the ClassId property + XPropertySet xCompProps = UNO.queryPropertySet( xComponent ); + + Short nClassId = (Short)xCompProps.getPropertyValue( "ClassId" ); + switch ( nClassId.intValue() ) + { + case FormComponentType.COMMANDBUTTON: sType = "Command button"; break; + case FormComponentType.RADIOBUTTON : sType = "Radio button"; break; + case FormComponentType.IMAGEBUTTON : sType = "Image button"; break; + case FormComponentType.CHECKBOX : sType = "Check Box"; break; + case FormComponentType.LISTBOX : sType = "List Box"; break; + case FormComponentType.COMBOBOX : sType = "Combo Box"; break; + case FormComponentType.GROUPBOX : sType = "Group Box"; break; + case FormComponentType.FIXEDTEXT : sType = "Fixed Text"; break; + case FormComponentType.GRIDCONTROL : sType = "Grid Control"; break; + case FormComponentType.FILECONTROL : sType = "File Control"; break; + case FormComponentType.HIDDENCONTROL: sType = "Hidden Control"; break; + case FormComponentType.IMAGECONTROL : sType = "Image Control"; break; + case FormComponentType.DATEFIELD : sType = "Date Field"; break; + case FormComponentType.TIMEFIELD : sType = "Time Field"; break; + case FormComponentType.NUMERICFIELD : sType = "Numeric Field"; break; + case FormComponentType.CURRENCYFIELD: sType = "Currency Field"; break; + case FormComponentType.PATTERNFIELD : sType = "Pattern Field"; break; + + case FormComponentType.TEXTFIELD : + // there are two known services with this class id: the usual text field, + // and the formatted field + sType = "Text Field"; + if ( ( null != xSI ) && xSI.supportsService( "com.sun.star.form.component.FormattedField" ) ) + { + sType = "Formatted Field"; + } + break; + + default: + break; + } + } + else + { + if ( ( null != xSI ) && xSI.supportsService( "com.sun.star.form.component.DataForm" ) ) + { + sType = "Form"; + } + } + + return sType; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/FormLayer.java b/odk/examples/DevelopersGuide/Forms/FormLayer.java new file mode 100644 index 000000000..11a9ce952 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/FormLayer.java @@ -0,0 +1,272 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +import com.sun.star.uno.UnoRuntime; + +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.XPropertySetInfo; +import com.sun.star.container.XIndexContainer; +import com.sun.star.container.XIndexAccess; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.drawing.XControlShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.awt.Size; +import com.sun.star.awt.Point; +import com.sun.star.awt.XControlModel; +import com.sun.star.text.TextContentAnchorType; +import com.sun.star.drawing.XDrawPage; + +public class FormLayer +{ + private DocumentHelper m_document; + private int m_insertPage; + + /* ------------------------------------------------------------------ */ + /** Creates a new instance of FormLayer */ + public FormLayer( DocumentHelper _document ) + { + m_document = _document; + m_insertPage = -1; + } + + + + + + /* ------------------------------------------------------------------ */ + /** creates a control in the document + +

Note that control here is an incorrect terminology. What the method really does is + it creates a control shape, together with a control model, and inserts them into the document model. + This will result in every view to this document creating a control described by the model-shape pair. +

+ + @param sFormComponentService + the service name of the form component to create, e.g. "TextField" + @param nXPos + the abscissa of the position of the newly inserted shape + @param nXPos + the ordinate of the position of the newly inserted shape + @param nWidth + the width of the newly inserted shape + @param nHeight + the height of the newly inserted shape + @param xParentForm + the form to use as parent for the newly create form component. May be null, in this case + a default parent is chosen by the implementation + @return + the property access to the control's model + */ + protected XPropertySet createControlAndShape( String sFormComponentService, int nXPos, + int nYPos, int nWidth, int nHeight, XIndexContainer xParentForm ) throws java.lang.Exception + { + // let the document create a shape + XMultiServiceFactory xDocAsFactory = UnoRuntime.queryInterface( + XMultiServiceFactory.class, m_document.getDocument() ); + XControlShape xShape = UnoRuntime.queryInterface( XControlShape.class, + xDocAsFactory.createInstance( "com.sun.star.drawing.ControlShape" ) ); + + // position and size of the shape + xShape.setSize( new Size( nWidth * 100, nHeight * 100 ) ); + xShape.setPosition( new Point( nXPos * 100, nYPos * 100 ) ); + + // adjust the anchor so that the control is tied to the page + XPropertySet xShapeProps = UNO.queryPropertySet( xShape ); + TextContentAnchorType eAnchorType = TextContentAnchorType.AT_PARAGRAPH; + xShapeProps.setPropertyValue( "AnchorType", eAnchorType ); + + // create the form component (the model of a form control) + String sQualifiedComponentName = "com.sun.star.form.component." + sFormComponentService; + XControlModel xModel = UnoRuntime.queryInterface( XControlModel.class, + m_document.getOrb().createInstance( sQualifiedComponentName ) ); + + // insert the model into the form component hierarchy, if the caller gave us a location + if ( null != xParentForm ) + { + xParentForm.insertByIndex( xParentForm.getCount(), xModel ); + } + + // knitt them + xShape.setControl( xModel ); + + // add the shape to the shapes collection of the document + XDrawPage pageWhereToInsert = ( m_insertPage != -1 ) ? m_document.getDrawPage( m_insertPage ) : m_document.getMainDrawPage(); + + XShapes xDocShapes = UnoRuntime.queryInterface( XShapes.class, pageWhereToInsert ); + xDocShapes.add( xShape ); + + // some initializations which are the same for all controls + XPropertySet xModelProps = UNO.queryPropertySet( xModel ); + try + { + XPropertySetInfo xPSI = xModelProps.getPropertySetInfo(); + if ( xPSI.hasPropertyByName( "Border" ) ) + { + if ( ((Short)xModelProps.getPropertyValue( "Border" )).shortValue() == com.sun.star.awt.VisualEffect.LOOK3D ) + xModelProps.setPropertyValue( "Border", Short.valueOf( com.sun.star.awt.VisualEffect.FLAT ) ); + } + if ( xPSI.hasPropertyByName( "VisualEffect" ) ) + xModelProps.setPropertyValue( "VisualEffect", Short.valueOf( com.sun.star.awt.VisualEffect.FLAT ) ); + if ( m_document.classify() != DocumentType.CALC ) + if ( xPSI.hasPropertyByName( "BorderColor" ) ) + xModelProps.setPropertyValue( "BorderColor", Integer.valueOf( 0x00C0C0C0 ) ); + } + catch( com.sun.star.uno.Exception e ) + { + System.err.println(e); + e.printStackTrace( System.err ); + } + return xModelProps; + } + + /* ------------------------------------------------------------------ */ + /** creates a control in the document + +

Note that control here is an incorrect terminology. What the method really does is + it creates a control shape, together with a control model, and inserts them into the document model. + This will result in every view to this document creating a control described by the model-shape pair. +

+ + @param sFormComponentService + the service name of the form component to create, e.g. "TextField" + @param nXPos + the abscissa of the position of the newly inserted shape + @param nXPos + the ordinate of the position of the newly inserted shape + @param nWidth + the width of the newly inserted shape + @param nHeight + the height of the newly inserted shape + @return + the property access to the control's model + */ + protected XPropertySet createControlAndShape( String sFormComponentService, int nXPos, + int nYPos, int nWidth, int nHeight ) throws java.lang.Exception + { + return createControlAndShape( sFormComponentService, nXPos, nYPos, nWidth, nHeight, null ); + } + + /* ------------------------------------------------------------------ */ + /** creates a line of controls, consisting of a label and a field for data input. + +

In opposite to the second form of this method, here the height of the field, + as well as the abscissa of the label, are under the control of the caller.

+ + @param sControlType + specifies the type of the data input control + @param sFieldName + specifies the field name the text field should be bound to + @param sControlNamePostfix + specifies a postfix to append to the logical control names + @param nYPos + specifies the Y position of the line to start at + @param nHeight + the height of the field + @return + the control model of the created data input field + */ + protected XPropertySet insertControlLine( String sControlType, String sFieldName, String sControlNamePostfix, int nXPos, int nYPos, int nHeight ) + throws java.lang.Exception + { + // insert the label control + XPropertySet xLabelModel = createControlAndShape( "FixedText", nXPos, nYPos, 25, 6 ); + xLabelModel.setPropertyValue( "Label", sFieldName ); + + // insert the text field control + XPropertySet xFieldModel = createControlAndShape( sControlType, nXPos + 26, nYPos, 40, nHeight ); + xFieldModel.setPropertyValue( "DataField", sFieldName ); + // knit it to its label component + xFieldModel.setPropertyValue( "LabelControl", xLabelModel ); + + // some names, so later on we can find them + xLabelModel.setPropertyValue( "Name", sFieldName + sControlNamePostfix + "_Label" ); + xFieldModel.setPropertyValue( "Name", sFieldName + sControlNamePostfix ); + + return xFieldModel; + } + + /* ------------------------------------------------------------------ */ + /** creates a line of controls, consisting of a label and a field for data input. + + @param sControlType + specifies the type of the data input control + @param sFieldName + specifies the field name the text field should be bound to + @param nYPos + specifies the Y position of the line to start at + @return + the control model of the created data input field + */ + protected XPropertySet insertControlLine( String sControlType, String sFieldName, String sControlNamePostfix, int nYPos ) + throws java.lang.Exception + { + return insertControlLine( sControlType, sFieldName, sControlNamePostfix, 2, nYPos, 6 ); + } + + /* ------------------------------------------------------------------ */ + /** retrieves the radio button model with the given name and the given ref value + * @param form + * the parent form of the radio button model to find + * @param name + * the name of the radio button + * @param refValue + * the reference value of the radio button + */ + public XPropertySet getRadioModelByRefValue( XPropertySet form, String name, String refValue ) throws com.sun.star.uno.Exception, java.lang.Exception + { + XIndexAccess indexAccess = UnoRuntime.queryInterface( XIndexAccess.class, + form ); + + for ( int i=0; iActually, the mechanism for validating the field is not restricted to + grid control fields. Instead, it can be used for any bound controls.

+*/ +class GridFieldValidator implements XUpdateListener +{ + private XComponentContext m_xCtx; + private XPropertySet m_xWatchedColumn; + + private boolean m_bWatching; + + /* ------------------------------------------------------------------ */ + public GridFieldValidator( XComponentContext xCtx, XPropertySet xWatchedGridColumn ) + { + // remember + m_xCtx = xCtx; + m_xWatchedColumn = xWatchedGridColumn; + DocumentHelper.getDocumentForComponent(xWatchedGridColumn, + xCtx); + + m_bWatching = false; + } + + /* ------------------------------------------------------------------ */ + public void enableColumnWatch( boolean bEnable ) + { + if ( bEnable == m_bWatching ) + return; + + XUpdateBroadcaster xUpdate = UnoRuntime.queryInterface( + XUpdateBroadcaster.class, m_xWatchedColumn ); + + if ( bEnable ) + xUpdate.addUpdateListener( this ); + else + xUpdate.removeUpdateListener( this ); + + m_bWatching = bEnable; + } + + /* ------------------------------------------------------------------ */ + /** shows a message that we can't do several things due to an implementation error + */ + private void showInvalidValueMessage( ) + { + try + { + // build the message we want to show + String sMessage = "The column \""; + sMessage += FLTools.getLabel( m_xWatchedColumn ); + sMessage += "\" is not allowed to contain empty strings."; + + SQLContext aError = new SQLContext( + "Invalid Value Entered", + null, + "S1000", + 0, + new Any( new Type(), null ), + sMessage + ); + + // instantiate an interaction handler who can handle SQLExceptions + XInteractionHandler xHandler = UnoRuntime.queryInterface( + XInteractionHandler.class, + m_xCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.task.InteractionHandler", m_xCtx ) ); + + // create a new request and execute it + InteractionRequest aRequest = new InteractionRequest( aError ); + xHandler.handle( aRequest ); + } + catch( com.sun.star.uno.Exception e ) + { + System.out.println(e); + e.printStackTrace(); + } + } + + /* ------------------------------------------------------------------ */ + // XUpdateListener overridables + /* ------------------------------------------------------------------ */ + public boolean approveUpdate( EventObject aEvent ) throws com.sun.star.uno.RuntimeException + { + boolean bApproved = true; + try + { + // the control model which fired the event + XPropertySet xSourceProps = UNO.queryPropertySet( aEvent.Source ); + + String sNewText = (String)xSourceProps.getPropertyValue( "Text" ); + if ( 0 == sNewText.length() ) + { + // say that the value is invalid + showInvalidValueMessage( ); + bApproved = false; + + // reset the control value + // for this, we take the current value from the row set field the control + // is bound to, and forward it to the control model + XColumn xBoundColumn = UNO.queryColumn( xSourceProps.getPropertyValue( "BoundField" ) ); + if ( null != xBoundColumn ) + { + xSourceProps.setPropertyValue( "Text", xBoundColumn.getString() ); + } + } + } + catch( com.sun.star.uno.Exception e ) + { + System.out.println(e); + e.printStackTrace(); + } + return bApproved; + } + + /* ------------------------------------------------------------------ */ + public void updated( EventObject aEvent ) throws com.sun.star.uno.RuntimeException + { + } + + /* ------------------------------------------------------------------ */ + // XEventListener overridables + /* ------------------------------------------------------------------ */ + public void disposing( EventObject aEvent ) + { + // not interested in + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/HsqlDatabase.java b/odk/examples/DevelopersGuide/Forms/HsqlDatabase.java new file mode 100644 index 000000000..fd2cd6ccf --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/HsqlDatabase.java @@ -0,0 +1,184 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XNameAccess; +import com.sun.star.frame.XStorable; +import com.sun.star.sdb.XOfficeDatabaseDocument; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XCloseable; +import com.sun.star.sdbc.XConnection; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.sdb.XDocumentDataSource; +import com.sun.star.sdbc.XDataSource; +import com.sun.star.uno.XComponentContext; +import java.io.File; + +import com.sun.star.util.CloseVetoException; + +public class HsqlDatabase +{ + private XComponentContext m_context; + // the URL of the temporary file used for the database document + private String m_databaseDocumentFile; + // the database document + private XOfficeDatabaseDocument m_databaseDocument; + // the data source belonging to the database document + // the default connection + private XConnection m_connection; + + + public HsqlDatabase( XComponentContext _context ) throws Exception + { + m_context = _context; + createDBDocument(); + } + + + public HsqlDatabase( XComponentContext _context, String _existingDocumentURL ) throws Exception + { + m_context = _context; + createDBDocument( _existingDocumentURL ); + } + + + private void createDBDocument( String _docURL ) throws Exception + { + m_databaseDocumentFile = _docURL; + + XNameAccess dbContext = UnoRuntime.queryInterface( XNameAccess.class, + m_context.getServiceManager().createInstanceWithContext( "com.sun.star.sdb.DatabaseContext", m_context ) ); + XDocumentDataSource dataSource = UnoRuntime.queryInterface( XDocumentDataSource.class, + dbContext.getByName( _docURL ) ); + + m_databaseDocument = dataSource.getDatabaseDocument(); + } + + /** creates an empty database document in a temporary location + */ + private void createDBDocument() throws Exception + { + File documentFile = File.createTempFile("testdb",".odb"); + documentFile.deleteOnExit(); + m_databaseDocumentFile = URLHelper.getFileURLFromSystemPath( documentFile ); + + m_databaseDocument = UnoRuntime.queryInterface( + XOfficeDatabaseDocument.class, m_context.getServiceManager().createInstanceWithContext( + "com.sun.star.sdb.OfficeDatabaseDocument", m_context ) ); + + XPropertySet dsProperties = UnoRuntime.queryInterface( XPropertySet.class, m_databaseDocument.getDataSource() ); + dsProperties.setPropertyValue("URL", "sdbc:embedded:hsqldb"); + + XStorable storable = UnoRuntime.queryInterface( XStorable.class, m_databaseDocument ); + storable.storeAsURL( m_databaseDocumentFile, new PropertyValue[]{} ); + } + + /** closes the database document + * + * Any CloseVetoExceptions fired by third parties are ignored, and any reference to the + * database document is released. + */ + private void close() + { + // close connection + XCloseable closeConn = UnoRuntime.queryInterface( XCloseable.class, + m_connection ); + if ( closeConn != null ) + { + try + { + closeConn.close(); + } + catch( SQLException e ) + { + } + } + m_connection = null; + + // close document + com.sun.star.util.XCloseable closeDoc = UnoRuntime.queryInterface( + com.sun.star.util.XCloseable.class, m_databaseDocument ); + if ( closeDoc != null ) + { + try + { + closeDoc.close( true ); + } + catch( CloseVetoException e ) + { + } + } + m_databaseDocument = null; + } + + /** closes the document, and deletes the underlying file + */ + private void closeAndDelete() + { + close(); + + if ( m_databaseDocumentFile != null ) + { + try + { + File file = new File(m_databaseDocumentFile); + file.delete(); + } + catch(Exception e) + { + } + m_databaseDocumentFile = null; + } + } + + /** returns the underlying database document + */ + public XOfficeDatabaseDocument getDatabaseDocument() + { + return m_databaseDocument; + } + + /** returns the associated data source + */ + public XDataSource getDataSource() + { + return m_databaseDocument.getDataSource(); + } + + + + /** returns the URL of the ODB document represented by this instance + */ + public String getDocumentURL() + { + return m_databaseDocumentFile; + } + + + + @Override + protected void finalize() throws Throwable + { + closeAndDelete(); + super.finalize(); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/InteractionRequest.java b/odk/examples/DevelopersGuide/Forms/InteractionRequest.java new file mode 100644 index 000000000..52ec3b8ef --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/InteractionRequest.java @@ -0,0 +1,71 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.ArrayList; + +import com.sun.star.task.XInteractionContinuation; +import com.sun.star.task.XInteractionRequest; + +/**************************************************************************/ +/** helper class for implementing an interaction request. +*/ +class InteractionRequest implements XInteractionRequest +{ + private Object m_aRequest; + private ArrayList m_aContinuations; + + /* ------------------------------------------------------------------ */ + public InteractionRequest( Object aRequest ) + { + m_aRequest = aRequest; + m_aContinuations = new ArrayList(); + } + + + + /* ------------------------------------------------------------------ */ + public Object getRequest( ) + { + return m_aRequest; + } + + /* ------------------------------------------------------------------ */ + public XInteractionContinuation[] getContinuations( ) + { + return m_aContinuations.toArray( new XInteractionContinuation[ m_aContinuations.size() ] ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/KeyGenerator.java b/odk/examples/DevelopersGuide/Forms/KeyGenerator.java new file mode 100644 index 000000000..43e5acdfa --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/KeyGenerator.java @@ -0,0 +1,434 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.*; +import com.sun.star.beans.*; +import com.sun.star.form.*; +import com.sun.star.lang.*; +import com.sun.star.sdb.*; +import com.sun.star.sdbc.*; +import com.sun.star.sdbcx.*; +import com.sun.star.container.*; +import com.sun.star.awt.*; + +/**************************************************************************/ +/** base class for helpers dealing with unique column values +*/ +class UniqueColumnValue +{ + /* ------------------------------------------------------------------ */ + /** extracts the name of the table a form is based on. + +

This method works for forms based directly on tables, and for forms based on statements, which + themself are based on one table.
+ Everything else (especially forms based on queries) is not yet implemented.

+ */ + private String extractTableName( XPropertySet xForm ) throws com.sun.star.uno.Exception + { + String sReturn; + + Integer aCommandType = (Integer)xForm.getPropertyValue( "CommandType" ); + String sCommand = (String)xForm.getPropertyValue( "Command" ); + + if ( CommandType.COMMAND == aCommandType.intValue() ) + { + // get the connection from the form + XConnection xFormConn = UnoRuntime.queryInterface( XConnection.class, + xForm.getPropertyValue( "ActiveConnection" ) ); + // and let it create a composer for us + XSQLQueryComposerFactory xComposerFac = + UnoRuntime.queryInterface( + XSQLQueryComposerFactory.class, xFormConn ); + XSQLQueryComposer xComposer = xComposerFac.createQueryComposer( ); + + // let this composer analyze the command + xComposer.setQuery( sCommand ); + + // and ask it for the table(s) + XTablesSupplier xSuppTables = UnoRuntime.queryInterface( + XTablesSupplier.class, xComposer ); + XNameAccess xTables = xSuppTables.getTables(); + + // simply take the first table name + String[] aNames = xTables.getElementNames( ); + sCommand = aNames[0]; + } + + return sCommand; + } + + /* ------------------------------------------------------------------ */ + /** generates a statement which can be used to create a unique (in all conscience) value + for the column given. +

Currently, the implementation uses a very simple approach - it just determines the maximum of currently + existing values in the column. If your concrete data source supports a more sophisticated approach of generating + unique values, you probably want to adjust the SELECT statement below accordingly.

+ + @returns + a String which can be used as statement to retrieve a unique value for the given column. + The result set resulting from such an execution contains the value in its first column. + */ + private String composeUniqueyKeyStatement( XPropertySet xForm, String sFieldName ) throws com.sun.star.uno.Exception + { + String sStatement = "SELECT MAX( "; + sStatement += sFieldName; + sStatement += ") + 1 FROM "; + // the table name is a property of the form + sStatement += extractTableName( xForm ); + + // note that the implementation is imperfect (besides the problem that MAX is not a really good solution + // for a database with more that one client): + // It does not quote the field and the table name. This needs to be done if the database is intolerant + // against such things - the XDatabaseMetaData, obtained from the connection, would be needed then + // Unfortunately, there is no UNO service doing this - it would need to be implemented manually. + + return sStatement; + } + + /* ------------------------------------------------------------------ */ + /** generates a unique (in all conscience) key into the column given + @param xForm + the form which contains the column in question + @param sFieldName + the name of the column + */ + private int generatePrimaryKey( XPropertySet xForm, String sFieldName ) throws com.sun.star.uno.Exception + { + // get the current connection of the form + XConnection xConn = UnoRuntime.queryInterface( + XConnection.class, xForm.getPropertyValue( "ActiveConnection" ) ); + // let it create a new statement + XStatement xStatement = xConn.createStatement(); + + // build the query string to determine a free value + String sStatement = composeUniqueyKeyStatement( xForm, sFieldName ); + + // execute the query + XResultSet xResults = xStatement.executeQuery( sStatement ); + + // move the result set to the first record + xResults.next( ); + + // get the value + XRow xRow = UnoRuntime.queryInterface( XRow.class, xResults ); + int nFreeValue = xRow.getInt( 1 ); + + // dispose the temporary objects + FLTools.disposeComponent( xStatement ); + // this should get rid of the result set, too + + return nFreeValue; + } + + /* ------------------------------------------------------------------ */ + /** inserts a unique (in all conscience) key into the column given + @param xForm + the form which contains the column in question + @param sFieldName + the name of the column + */ + public void insertPrimaryKey( XPropertySet xForm, String sFieldName ) throws com.sun.star.uno.Exception + { + // check the privileges + Integer aConcurrency = (Integer)xForm.getPropertyValue( "ResultSetConcurrency" ); + if ( ResultSetConcurrency.READ_ONLY != aConcurrency.intValue() ) + { + // get the column object + XColumnsSupplier xSuppCols = UnoRuntime.queryInterface( + XColumnsSupplier.class, xForm ); + XNameAccess xCols = xSuppCols.getColumns(); + XColumnUpdate xCol = UnoRuntime.queryInterface( + XColumnUpdate.class, xCols.getByName( sFieldName ) ); + + xCol.updateInt( generatePrimaryKey( xForm, sFieldName ) ); + } + } +} + +/**************************************************************************/ +/** base class for helpers dealing with unique column values +*/ +class KeyGeneratorForReset extends UniqueColumnValue implements XResetListener +{ + /* ------------------------------------------------------------------ */ + private DocumentViewHelper m_aView; + private String m_sFieldName; + + /* ------------------------------------------------------------------ */ + /** ctor + @param aView + the view which shall be used to focus controls + @param sFieldName + the name of the field for which keys should be generated + */ + public KeyGeneratorForReset( String sFieldName, DocumentViewHelper aView ) + { + m_sFieldName = sFieldName; + m_aView = aView; + } + + /* ------------------------------------------------------------------ */ + /** sets the focus to the first control which is no fixed text, and not the + one we're defaulting + */ + private void defaultNewRecordFocus( XPropertySet xForm ) throws com.sun.star.uno.Exception + { + XIndexAccess xFormAsContainer = UnoRuntime.queryInterface( + XIndexAccess.class, xForm ); + for ( int i = 0; i set the focus into the respective control + XControlModel xCM = UNO.queryControlModel( xModel ); + m_aView.grabControlFocus( xCM); + break; + } + } + + /* ------------------------------------------------------------------ */ + // XResetListener overridables + /* ------------------------------------------------------------------ */ + public boolean approveReset( com.sun.star.lang.EventObject rEvent ) throws com.sun.star.uno.RuntimeException + { + // not interested in vetoing this + return true; + } + + /* ------------------------------------------------------------------ */ + public void resetted( com.sun.star.lang.EventObject aEvent ) throws com.sun.star.uno.RuntimeException + { + // check if this reset occurred because we're on a new record + XPropertySet xFormProps = UNO.queryPropertySet( aEvent.Source ); + try + { + Boolean aIsNew = (Boolean)xFormProps.getPropertyValue( "IsNew" ); + if ( aIsNew.booleanValue() ) + { // yepp + + // we're going to modify the record, though after that, to the user, it should look + // like it has not been modified + // So we need to ensure that we do not change the IsModified property with whatever we do + Object aModifiedFlag = xFormProps.getPropertyValue( "IsModified" ); + + // now set the value + insertPrimaryKey( xFormProps, m_sFieldName ); + + // then restore the flag + xFormProps.setPropertyValue( "IsModified", aModifiedFlag ); + + // still one thing ... would be nice to have the focus in a control which is + // the one which's value we just defaulted + defaultNewRecordFocus( xFormProps ); + } + } + catch( com.sun.star.uno.Exception e ) + { + System.out.println(e); + e.printStackTrace(); + } + } + /* ------------------------------------------------------------------ */ + // XEventListener overridables + /* ------------------------------------------------------------------ */ + public void disposing( EventObject aEvent ) + { + // not interested in + } +} + + +/**************************************************************************/ +/** base class for helpers dealing with unique column values +*/ +class KeyGeneratorForUpdate extends UniqueColumnValue implements XRowSetApproveListener +{ + /* ------------------------------------------------------------------ */ + private String m_sFieldName; + + /* ------------------------------------------------------------------ */ + public KeyGeneratorForUpdate( String sFieldName ) + { + m_sFieldName = sFieldName; + } + + /* ------------------------------------------------------------------ */ + // XRowSetApproveListener overridables + /* ------------------------------------------------------------------ */ + public boolean approveCursorMove( com.sun.star.lang.EventObject aEvent ) throws com.sun.star.uno.RuntimeException + { + // not interested in vetoing moves + return true; + } + + /* ------------------------------------------------------------------ */ + public boolean approveRowChange( RowChangeEvent aEvent ) throws com.sun.star.uno.RuntimeException + { + if ( RowChangeAction.INSERT == aEvent.Action ) + { + try + { + // the affected form + XPropertySet xFormProps = UNO.queryPropertySet( aEvent.Source ); + // insert a new unique value + insertPrimaryKey( xFormProps, m_sFieldName ); + } + catch( com.sun.star.uno.Exception e ) + { + System.out.println(e); + e.printStackTrace(); + } + } + return true; + } + + /* ------------------------------------------------------------------ */ + public boolean approveRowSetChange( com.sun.star.lang.EventObject aEvent ) throws com.sun.star.uno.RuntimeException + { + // not interested in vetoing executions of the row set + return true; + } + /* ------------------------------------------------------------------ */ + // XEventListener overridables + /* ------------------------------------------------------------------ */ + public void disposing( EventObject aEvent ) + { + // not interested in + } +} + +/**************************************************************************/ +/** allows to generate unique keys for a field of a Form +*/ +public class KeyGenerator +{ + /* ------------------------------------------------------------------ */ + private KeyGeneratorForReset m_aResetKeyGenerator; + private KeyGeneratorForUpdate m_aUpdateKeyGenerator; + private boolean m_bResetListening; + private boolean m_bUpdateListening; + + private XPropertySet m_xForm; + + /* ------------------------------------------------------------------ */ + /** ctor + @param xForm + specified the form to operate on + @param sFieldName + specifies the field which's value should be manipulated + */ + public KeyGenerator( XPropertySet xForm, String sFieldName, + XComponentContext xCtx ) + { + m_xForm = xForm; + + DocumentHelper aDocument = DocumentHelper.getDocumentForComponent( xForm, xCtx ); + + m_aResetKeyGenerator = new KeyGeneratorForReset( sFieldName, aDocument.getCurrentView() ); + m_aUpdateKeyGenerator = new KeyGeneratorForUpdate( sFieldName ); + + m_bResetListening = m_bUpdateListening = false; + } + + /* ------------------------------------------------------------------ */ + /** stops any actions on the form + */ + public void stopGenerator( ) + { + XReset xFormReset = UNO.queryReset( m_xForm ); + xFormReset.removeResetListener( m_aResetKeyGenerator ); + + XRowSetApproveBroadcaster xFormBroadcaster = UnoRuntime.queryInterface( + XRowSetApproveBroadcaster.class, m_xForm ); + xFormBroadcaster.removeRowSetApproveListener( m_aUpdateKeyGenerator ); + + m_bUpdateListening = m_bResetListening = false; + } + + /* ------------------------------------------------------------------ */ + /** activates one of our two key generators + */ + public void activateKeyGenerator( boolean bGenerateOnReset ) + { + // for resets + XReset xFormReset = UNO.queryReset( m_xForm ); + // for approving actions + XRowSetApproveBroadcaster xFormBroadcaster = UnoRuntime.queryInterface( + XRowSetApproveBroadcaster.class, m_xForm ); + + if ( bGenerateOnReset ) + { + if ( !m_bResetListening ) + xFormReset.addResetListener( m_aResetKeyGenerator ); + if ( m_bUpdateListening ) + xFormBroadcaster.removeRowSetApproveListener( m_aUpdateKeyGenerator ); + + m_bUpdateListening = false; + m_bResetListening = true; + } + else + { + if ( m_bResetListening ) + xFormReset.removeResetListener( m_aResetKeyGenerator ); + if ( !m_bUpdateListening ) + xFormBroadcaster.addRowSetApproveListener( m_aUpdateKeyGenerator ); + + m_bResetListening = false; + m_bUpdateListening = true; + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/ListSelectionValidator.java b/odk/examples/DevelopersGuide/Forms/ListSelectionValidator.java new file mode 100644 index 000000000..8a8909390 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/ListSelectionValidator.java @@ -0,0 +1,59 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +public class ListSelectionValidator extends ControlValidator +{ + /** Creates a new instance of ListSelectionValidator */ + public ListSelectionValidator() + { + } + + public String explainInvalid( Object Value ) + { + try + { + short[] selectionIndexes = (short[])Value; + if ( selectionIndexes.length > 2 ) + return "please 2 entries, at most"; + } + catch( java.lang.Exception e ) + { + return "oops. What's this?"; + } + return ""; + } + + public boolean isValid( Object Value ) + { + try + { + short[] selectionIndexes = (short[])Value; + if ( selectionIndexes.length > 2 ) + return false; + return true; + } + catch( java.lang.Exception e ) + { + } + return false; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/Makefile b/odk/examples/DevelopersGuide/Forms/Makefile new file mode 100644 index 000000000..54cf7aad9 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/Makefile @@ -0,0 +1,196 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Forms example of the Developers Guide. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=FormsExamples +SAMPLE_CLASS_OUT=$(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT=$(OUT_MISC)/$(SAMPLE_NAME) + +APP1_NAME=DataAwareness +APP1_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(APP1_NAME) +APP1_JAR=$(SAMPLE_CLASS_OUT)/$(APP1_NAME).jar +APP2_NAME=ValueBinding +APP2_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(APP2_NAME) +APP2_JAR=$(SAMPLE_CLASS_OUT)/$(APP2_NAME).jar +APP3_NAME=SpreadsheetValueBinding +APP3_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(APP3_NAME) +APP3_JAR=$(SAMPLE_CLASS_OUT)/$(APP3_NAME).jar +APP4_NAME=ControlValidation +APP4_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(APP4_NAME) +APP4_JAR=$(SAMPLE_CLASS_OUT)/$(APP4_NAME).jar + +COMMON_CLASS_OUT = $(SAMPLE_CLASS_OUT)/common +COMMON_JAVAFILES = \ + ButtonOperator.java \ + ComponentTreeTraversal.java \ + ControlLock.java \ + DocumentHelper.java \ + DocumentType.java \ + DocumentViewHelper.java \ + FLTools.java \ + FormLayer.java \ + GridFieldValidator.java \ + InteractionRequest.java \ + KeyGenerator.java \ + SalesFilter.java \ + UNO.java \ + SpreadsheetView.java \ + WaitForInput.java \ + DocumentBasedExample.java \ + TableCellTextBinding.java \ + SpreadsheetDocument.java \ + NumericValidator.java \ + TextValidator.java \ + BooleanValidator.java \ + ListSelectionValidator.java \ + DateValidator.java \ + TimeValidator.java \ + ControlValidator.java \ + SingleControlValidation.java \ + HsqlDatabase.java \ + RowSet.java \ + URLHelper.java + +COMMON_CLASSFILES = $(patsubst %.java,$(COMMON_CLASS_OUT)/%.class,$(COMMON_JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)\ + $(PATH_SEPARATOR)$(COMMON_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : \ + FormsExample + +include $(SETTINGS)/stdtarget.mk + +$(COMMON_CLASSFILES) : $(COMMON_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(COMMON_CLASS_OUT) $^ + +# rule for client/example application manifest file +$(SAMPLE_GEN_OUT)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(APP1_CLASS_OUT)/$(APP1_NAME).class : $(APP1_NAME).java $(COMMON_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(APP1_CLASS_OUT) $< + +$(APP2_CLASS_OUT)/$(APP2_NAME).class : $(APP2_NAME).java $(COMMON_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(APP2_CLASS_OUT) $< + +$(APP3_CLASS_OUT)/$(APP3_NAME).class : $(APP3_NAME).java $(COMMON_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(APP3_CLASS_OUT) $< + +$(APP4_CLASS_OUT)/$(APP4_NAME).class : $(APP4_NAME).java $(COMMON_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(APP4_CLASS_OUT) $< + +$(APP1_JAR) : $(SAMPLE_GEN_OUT)/$(APP1_NAME).mf $(APP1_CLASS_OUT)/$(APP1_NAME).class $(COMMON_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +$(SDK_JAR) cvfm $@ $< -C $(APP1_CLASS_OUT) . + +$(SDK_JAR) uvf $@ -C $(COMMON_CLASS_OUT) . + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP2_JAR) : $(SAMPLE_GEN_OUT)/$(APP2_NAME).mf $(APP2_CLASS_OUT)/$(APP2_NAME).class $(COMMON_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +$(SDK_JAR) cvfm $@ $< -C $(APP2_CLASS_OUT) . + +$(SDK_JAR) uvf $@ -C $(COMMON_CLASS_OUT) . + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP3_JAR) : $(SAMPLE_GEN_OUT)/$(APP3_NAME).mf $(APP3_CLASS_OUT)/$(APP3_NAME).class $(COMMON_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +$(SDK_JAR) cvfm $@ $< -C $(APP3_CLASS_OUT) . + +$(SDK_JAR) uvf $@ -C $(COMMON_CLASS_OUT) . + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP4_JAR) : $(SAMPLE_GEN_OUT)/$(APP4_NAME).mf $(APP4_CLASS_OUT)/$(APP4_NAME).class $(COMMON_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +$(SDK_JAR) cvfm $@ $< -C $(APP4_CLASS_OUT) . + +$(SDK_JAR) uvf $@ -C $(COMMON_CLASS_OUT) . + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +FormsExample : $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) $(APP4_JAR) + @echo -------------------------------------------------------------------------------- + @echo "$(QM)$(APP1_NAME)$(QM)" demonstrates various things around data aware controls. + @echo "$(QM)$(APP2_NAME)$(QM)" demonstrates the use of value bindings for form controls. + @echo "$(QM)$(APP3_NAME)$(QM)" demonstrates the usage of the com.sun.star.table.CellValueBinding service + @echo "$(QM)$(APP4_NAME)$(QM)" demonstrates the form control validation API + + @echo Please use one of the following commands to run an example: + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP2_NAME).run + @echo $(MAKE) $(APP3_NAME).run + @echo $(MAKE) $(APP4_NAME).run + @echo - + @echo Note: The data awareness example needs a running data source with name + @echo $(SQM) $(SQM)"$(QM)OO_SDK_Demo_DB$(QM)". Make sure that you have created such a data source, + @echo - + @echo The document "$(QM)ProgrammaticScriptAssignment.odt$(QM)" demonstrates + @echo how you can programmatically create form controls, and associated + @echo scripts with certain events. + @echo - + @echo $(MAKE) ProgrammaticScriptAssignment.odt.load + @echo -------------------------------------------------------------------------------- + +ProgrammaticScriptAssignment.odt.load : $(COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +%.run: $(SAMPLE_CLASS_OUT)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) diff --git a/odk/examples/DevelopersGuide/Forms/NumericValidator.java b/odk/examples/DevelopersGuide/Forms/NumericValidator.java new file mode 100644 index 000000000..4df77af20 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/NumericValidator.java @@ -0,0 +1,77 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +public class NumericValidator extends ControlValidator +{ + + /** Creates a new instance of NumericValidator */ + public NumericValidator( ) + { + } + + public String explainInvalid( Object Value ) + { + try + { + double value = ((Double)Value).doubleValue(); + if ( Double.compare( Double.NaN, value ) == 0 ) + return "This is NotANumber"; + if ( !isProperRange( value ) ) + return "The value must be between 0 and 100"; + if ( !isProperDigitCount( value ) ) + return "The value must have at most one decimal digit"; + } + catch( java.lang.Exception e ) + { + return "This is no valid number"; + } + return ""; + } + + public boolean isValid( Object Value ) + { + try + { + double value = ((Double)Value).doubleValue(); + if ( Double.compare( Double.NaN, value ) == 0 ) + return false; + if ( !isProperRange( value ) ) + return false; + if ( !isProperDigitCount( value ) ) + return false; + return true; + } + catch( java.lang.Exception e ) + { + } + return false; + } + + private boolean isProperRange( double value) + { + return ( value >= 0 ) && ( value <= 100 ); + } + + private boolean isProperDigitCount( double value) + { + return ( Math.floor( value * 10 ) == value * 10 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/ProgrammaticScriptAssignment.odt b/odk/examples/DevelopersGuide/Forms/ProgrammaticScriptAssignment.odt new file mode 100644 index 000000000..40b952d94 Binary files /dev/null and b/odk/examples/DevelopersGuide/Forms/ProgrammaticScriptAssignment.odt differ diff --git a/odk/examples/DevelopersGuide/Forms/RowSet.java b/odk/examples/DevelopersGuide/Forms/RowSet.java new file mode 100644 index 000000000..93e62cacf --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/RowSet.java @@ -0,0 +1,283 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XIndexAccess; +import com.sun.star.container.XNameAccess; +import com.sun.star.io.XInputStream; +import com.sun.star.sdbc.SQLException; +import com.sun.star.sdbc.XArray; +import com.sun.star.sdbc.XBlob; +import com.sun.star.sdbc.XClob; +import com.sun.star.sdbc.XRef; +import com.sun.star.sdbc.XRow; +import com.sun.star.sdbc.XRowSet; +import com.sun.star.sdbc.XRowSetListener; +import com.sun.star.sdbcx.XColumnsSupplier; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.util.Date; +import com.sun.star.util.DateTime; +import com.sun.star.util.Time; + +public class RowSet implements XRowSet, XRow +{ + private XRowSet m_rowSet; + private XRow m_row; + private XPropertySet m_rowSetProps; + + public RowSet( XComponentContext _context, String _dataSource, int _commandType, String _command ) + { + try + { + m_rowSetProps = UnoRuntime.queryInterface( + XPropertySet.class, _context.getServiceManager().createInstanceWithContext( "com.sun.star.sdb.RowSet", _context ) ); + m_rowSetProps.setPropertyValue( "DataSourceName", _dataSource ); + m_rowSetProps.setPropertyValue( "CommandType", Integer.valueOf( _commandType ) ); + m_rowSetProps.setPropertyValue( "Command", _command ); + + m_rowSet = UnoRuntime.queryInterface( XRowSet.class, m_rowSetProps ); + m_row = UnoRuntime.queryInterface( XRow.class, m_rowSetProps ); + } + catch ( Exception e ) + { + e.printStackTrace(System.err); + throw new java.lang.InstantiationError(); + } + } + + // misc + public int getColumnCount() + { + XColumnsSupplier suppCols = UnoRuntime.queryInterface( + XColumnsSupplier.class, m_rowSet ); + XIndexAccess columns = UnoRuntime.queryInterface( + XIndexAccess.class, suppCols.getColumns() ); + return columns.getCount(); + } + + // XRowSet + public void execute() throws SQLException + { + m_rowSet.execute(); + } + + public void addRowSetListener( XRowSetListener _listener ) + { + m_rowSet.addRowSetListener( _listener ); + } + + public void removeRowSetListener( XRowSetListener _listener ) + { + m_rowSet.removeRowSetListener( _listener ); + } + + public boolean next() throws SQLException + { + return m_rowSet.next(); + } + + public boolean isBeforeFirst() throws SQLException + { + return m_rowSet.isBeforeFirst(); + } + + public boolean isAfterLast() throws SQLException + { + return m_rowSet.isAfterLast(); + } + + public boolean isFirst() throws SQLException + { + return m_rowSet.isFirst(); + } + + public boolean isLast() throws SQLException + { + return m_rowSet.isLast(); + } + + public void beforeFirst() throws SQLException + { + m_rowSet.beforeFirst(); + } + + public void afterLast() throws SQLException + { + m_rowSet.afterLast(); + } + + public boolean first() throws SQLException + { + return m_rowSet.first(); + } + + public boolean last() throws SQLException + { + return m_rowSet.last(); + } + + public int getRow() throws SQLException + { + return m_rowSet.getRow(); + } + + public boolean absolute(int i) throws SQLException + { + return m_rowSet.absolute(i); + } + + public boolean relative(int i) throws SQLException + { + return m_rowSet.relative(i); + } + + public boolean previous() throws SQLException + { + return m_rowSet.previous(); + } + + public void refreshRow() throws SQLException + { + m_rowSet.refreshRow(); + } + + public boolean rowUpdated() throws SQLException + { + return m_rowSet.rowUpdated(); + } + + public boolean rowInserted() throws SQLException + { + return m_rowSet.rowInserted(); + } + + public boolean rowDeleted() throws SQLException + { + return m_rowSet.rowDeleted(); + } + + // XRow + public Object getStatement() throws SQLException + { + return m_rowSet.getStatement(); + } + + public boolean wasNull() throws SQLException + { + return m_row.wasNull(); + } + + public String getString(int i) throws SQLException + { + return m_row.getString(i); + } + + public boolean getBoolean(int i) throws SQLException + { + return m_row.getBoolean(i); + } + + public byte getByte(int i) throws SQLException + { + return m_row.getByte(i); + } + + public short getShort(int i) throws SQLException + { + return m_row.getShort(i); + } + + public int getInt(int i) throws SQLException + { + return m_row.getInt(i); + } + + public long getLong(int i) throws SQLException + { + return m_row.getLong(i); + } + + public float getFloat(int i) throws SQLException + { + return m_row.getFloat(i); + } + + public double getDouble(int i) throws SQLException + { + return m_row.getDouble(i); + } + + public byte[] getBytes(int i) throws SQLException + { + return m_row.getBytes(i); + } + + public Date getDate(int i) throws SQLException + { + return m_row.getDate(i); + } + + public Time getTime(int i) throws SQLException + { + return m_row.getTime(i); + } + + public DateTime getTimestamp(int i) throws SQLException + { + return m_row.getTimestamp(i); + } + + public XInputStream getBinaryStream(int i) throws SQLException + { + return m_row.getBinaryStream(i); + } + + public XInputStream getCharacterStream(int i) throws SQLException + { + return m_row.getCharacterStream(i); + } + + public Object getObject(int i, XNameAccess xNameAccess) throws SQLException + { + return m_row.getObject(i, xNameAccess); + } + + public XRef getRef(int i) throws SQLException + { + return m_row.getRef(i); + } + + public XBlob getBlob(int i) throws SQLException + { + return m_row.getBlob(i); + } + + public XClob getClob(int i) throws SQLException + { + return m_row.getClob(i); + } + + public XArray getArray(int i) throws SQLException + { + return m_row.getArray(i); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/SalesFilter.java b/odk/examples/DevelopersGuide/Forms/SalesFilter.java new file mode 100644 index 000000000..753135bd3 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/SalesFilter.java @@ -0,0 +1,510 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.*; +import com.sun.star.beans.*; +import com.sun.star.form.*; +import com.sun.star.lang.*; +import com.sun.star.awt.*; + +import java.util.Calendar; +import java.util.GregorianCalendar; + +/**************************************************************************/ +/** helper class for filtering the sales form +*/ +class SalesFilter implements XActionListener, XPropertyChangeListener, XResetListener +{ + private DocumentHelper m_aDocument; + private XPropertySet m_xSalesForm; + + private XPropertySet m_xFilterList; + private XPropertySet m_xManualFilter; + private XPropertySet m_xApplyFilter; + + private boolean m_bSettingsDirty; + private boolean m_bSettingDate; + private boolean m_bAdjustingFilterList; + private short m_nPreviousFilterIndex; + private java.util.ArrayList m_aFilterDates; + + /* ------------------------------------------------------------------ */ + public SalesFilter( DocumentHelper aDocument, XPropertySet xSalesForm, + XPropertySet xFilterListBox, XPropertySet xManualFilterEdit, XPropertySet xStartFilterButton ) + { + m_aFilterDates = new java.util.ArrayList(); + m_bSettingsDirty = false; + m_bSettingDate = false; + m_bAdjustingFilterList = false; + m_nPreviousFilterIndex = -1; + initFilterDates(); + + + // remember the components + m_aDocument = aDocument; + m_xSalesForm = xSalesForm; + + m_xFilterList = xFilterListBox; + m_xManualFilter = xManualFilterEdit; + m_xApplyFilter = xStartFilterButton; + + try + { + + // init control models + m_xFilterList.setPropertyValue( "Dropdown", Boolean.TRUE ); + m_xFilterList.setPropertyValue( "LineCount", Short.valueOf( (short)11 ) ); + m_xFilterList.setPropertyValue( "StringItemList", new String[] { "ever (means no filter)", "this morning", "1 week ago", "1 month ago", "1 year ago", "" } ); + m_xFilterList.setPropertyValue( "DefaultSelection", new short[] { (short)0 } ); + + m_xApplyFilter.setPropertyValue( "Label", "Apply Filter" ); + + updateFilterControl(); + updateApplyButton(); + + + // add as listener to the events which require action + + // want to know about changed selection + m_xFilterList.addPropertyChangeListener( "SelectedItems", this ); + m_xManualFilter.addPropertyChangeListener( "Date", this ); + + // want to know about the date field being reset + XReset xReset = UNO.queryReset( m_xManualFilter ); + xReset.addResetListener( this ); + + // for the button, we can add to the control only, not to the model + // - clicking a button is something which happens on the _control_. + DocumentViewHelper aView = m_aDocument.getCurrentView(); + XButton xButton = aView.getFormControl( m_xApplyFilter, XButton.class ); + xButton.addActionListener( this ); + } + catch ( com.sun.star.uno.Exception e ) + { + System.out.println(e); + e.printStackTrace(); + } + } + + /* ================================================================== + = helper + ================================================================== */ + /* ------------------------------------------------------------------ */ + private void initFilterDates() + { + m_aFilterDates.clear(); + java.util.Date aNowAndHere = new java.util.Date(); + aNowAndHere.setHours( 0 ); + aNowAndHere.setMinutes( 0 ); + aNowAndHere.setSeconds( 0 ); + + // for every list entry, we add a java.util.Date to m_aFilterDates indicating + // since when the sales should be listed + + // ever + m_aFilterDates.add( null ); + + // this morning + m_aFilterDates.add( aNowAndHere ); + + // one week ago + GregorianCalendar aCalendar = new GregorianCalendar( ); + aCalendar.setTime( aNowAndHere ); + aCalendar.add( Calendar.DATE, -7 ); + m_aFilterDates.add( aCalendar.getTime() ); + + // one month ago + aCalendar.setTime( aNowAndHere ); + aCalendar.add( Calendar.MONTH, -1 ); + m_aFilterDates.add( aCalendar.getTime() ); + + // one year ago + aCalendar.setTime( aNowAndHere ); + aCalendar.add( Calendar.YEAR, -1 ); + m_aFilterDates.add( aCalendar.getTime() ); + + // the custom date + m_aFilterDates.add( null ); + } + + /* ------------------------------------------------------------------ */ + /** translates a date from the AWT Toolkit format to a java.util.date, or + vice versa. + */ + private Object translateDate( Object aDate ) throws java.lang.Exception + { + Object aReturn = null; + + GregorianCalendar aCalDate = new GregorianCalendar(); + if ( aDate.getClass().equals( Class.forName( "java.util.Date" ) ) ) + { + aCalDate.setTime( (java.util.Date)aDate ); + + int nDate = aCalDate.get( Calendar.YEAR ); + nDate = nDate * 100 + aCalDate.get( Calendar.MONTH ) + 1; + nDate = nDate * 100 + aCalDate.get( Calendar.DAY_OF_MONTH ); + + aReturn = Integer.valueOf( nDate ); + } + else if ( aDate.getClass().equals( Class.forName( "java.lang.Integer" ) ) ) + { + int nToolkitDate = ((Integer)aDate).intValue(); + aCalDate.set( Calendar.DAY_OF_MONTH, ( nToolkitDate % 100 ) ); + nToolkitDate /= 100; + aCalDate.set( Calendar.MONTH, ( nToolkitDate % 100 ) - 1 ); + nToolkitDate /= 100; + aCalDate.set( Calendar.YEAR, ( nToolkitDate % 10000 ) ); + + // default the time + aCalDate.set( Calendar.HOUR_OF_DAY, 0 ); + aCalDate.set( Calendar.MINUTE, 0 ); + aCalDate.set( Calendar.SECOND, 0 ); + + aReturn = aCalDate.getTime(); + } + + return aReturn; + } + + /* ------------------------------------------------------------------ */ + /** translates the given date into the ODBC date notation, which then can be used + for setting a filter at a row set + */ + private String getOdbcDate( Object aDate ) throws java.lang.Exception + { + String sOdbcDate = ""; + if ( null != aDate ) + { + if ( !aDate.getClass().equals( Class.forName( "java.util.Date" ) ) ) + aDate = translateDate( aDate ); + + if ( aDate.getClass().equals( Class.forName( "java.util.Date" ) ) ) + { + GregorianCalendar aCal = new GregorianCalendar(); + aCal.setTime( (java.util.Date)aDate ); + + sOdbcDate += "{D '"; + sOdbcDate += (Integer.valueOf( aCal.get( Calendar.YEAR ) ) ).toString(); + sOdbcDate += "-"; + + int nMonth = aCal.get( Calendar.MONTH ) + 1; + if ( nMonth < 10 ) + sOdbcDate += "0"; + sOdbcDate += (Integer.valueOf( nMonth ) ).toString(); + sOdbcDate += "-"; + + int nDay = aCal.get( Calendar.DAY_OF_MONTH ); + if ( nDay < 10 ) + sOdbcDate += "0"; + sOdbcDate += (Integer.valueOf( nDay ) ).toString(); + sOdbcDate += "'}"; + } + } + return sOdbcDate; + } + + /* ------------------------------------------------------------------ */ + private void updateApplyButton() + { + try + { + m_xApplyFilter.setPropertyValue( "Enabled", Boolean.valueOf( m_bSettingsDirty ) ); + } + catch ( com.sun.star.uno.Exception e ) + { + System.out.println(e); + e.printStackTrace(); + } + } + + /* ------------------------------------------------------------------ */ + /** creates a normalized calendar object from the given java.util.Date + */ + private GregorianCalendar getCalendarObject( java.util.Date aDate ) + { + // the date part + GregorianCalendar aReturn = null; + if ( null != aDate ) + { + aReturn = new GregorianCalendar( ); + aReturn.setTime( aDate ); + + // normalize the time part + aReturn.set( Calendar.HOUR_OF_DAY, 0 ); + aReturn.set( Calendar.MINUTE, 0 ); + aReturn.set( Calendar.SECOND, 0 ); + } + + return aReturn; + } + + /* ------------------------------------------------------------------ */ + final private short getCurrentSelectedFilter( ) throws com.sun.star.uno.Exception + { + short[] aSelected = (short[])m_xFilterList.getPropertyValue( "SelectedItems" ); + if ( 0 < aSelected.length ) + return aSelected[0]; + return -1; + } + + /* ------------------------------------------------------------------ */ + /** checks if the given filter index refers to the "" entry which + allows the user to manually enter a date + */ + final private boolean isManualFilter( short nFilterIndex ) + { + return ( 5 == nFilterIndex ); + } + + /* ------------------------------------------------------------------ */ + private void updateFilterControl() + { + try + { + if ( isManualFilter( m_nPreviousFilterIndex ) ) + { // previously, the "custom" filter date was selected + // -> remember the date entered + Object aDate = translateDate( m_xManualFilter.getPropertyValue( "Date" ) ); + m_aFilterDates.set( m_nPreviousFilterIndex, aDate ); + } + + // check the current selection + if ( !m_bAdjustingFilterList ) + { + m_nPreviousFilterIndex = getCurrentSelectedFilter( ); + + // custom filter? + boolean bCustomFilter = isManualFilter( m_nPreviousFilterIndex ); + m_xManualFilter.setPropertyValue( "Enabled", Boolean.valueOf( bCustomFilter ) ); + if ( bCustomFilter ) + m_aDocument.getCurrentView().grabControlFocus( m_xManualFilter ); + + m_bSettingDate = true; + Object aSelectedDateLimit = m_aFilterDates.get( m_nPreviousFilterIndex ); + if ( null != aSelectedDateLimit ) + { + // translate this date into one the AWT Toolkit understands + Integer aTKDate = (Integer)translateDate( aSelectedDateLimit ); + m_xManualFilter.setPropertyValue( "Date", aTKDate ); + } + else + m_xManualFilter.setPropertyValue( "Date", new Any( new Type(), null ) ); + m_bSettingDate = false; + } + } + catch ( java.lang.Exception e ) + { + System.out.println(e); + e.printStackTrace(); + } + } + + /* ------------------------------------------------------------------ */ + /** compares the date part of two calendars +

For some strange reason I do not understand, GregorianCalendar.equals( GregorianCalendar ) + seems to always return false, as well as . Thus here is a method which compare two calendars, + restricted to their date part

+ */ + private boolean equalDate( Calendar aLHS, Calendar aRHS ) + { + if ( ( null == aLHS ) != ( null == aRHS ) ) + // only one of them is null + return false; + + if ( null == aLHS ) + // both are null + return true; + + return ( aLHS.get( Calendar.YEAR ) == aRHS.get( Calendar.YEAR ) ) + && ( aLHS.get( Calendar.MONTH ) == aRHS.get( Calendar.MONTH ) ) + && ( aLHS.get( Calendar.DAY_OF_MONTH ) == aRHS.get( Calendar.DAY_OF_MONTH ) ); + } + + /* ------------------------------------------------------------------ */ + /** adds the current user filter to the list of date filters + @return + the index of the newly added date filter in the filter list + */ + private short addCurrentFilter( ) throws java.lang.Exception + { + // the current string items + String[] aOldFilterItems = (String[])m_xFilterList.getPropertyValue( "StringItemList" ); + + // translate this into a vector - much more comfort to work with a vector than with an array... + java.util.ArrayList aFilterItems = new java.util.ArrayList(); + for ( int i=0; i 10 ) // (6 standard items + 5 user defined items) + { + // the first (and thus oldest) user defined item + aFilterItems.remove( 6 ); + // keep our date vector synchron + m_aFilterDates.remove( 6 ); + } + + // add the current user defined filter + aFilterItems.add( aDate.toString() ); + m_aFilterDates.add( aDate ); + + // write back the string item list + m_bAdjustingFilterList = true; + String[] aNewFilterItems = new String[ aFilterItems.size() ]; + for ( int i=0; iindex
with a cell + */ + public com.sun.star.form.binding.XValueBinding createListIndexBinding( short sheet, short column, short row ) + { + return createCellBinding( sheet, column, row, true ); + } + + /** creates a value binding for a given cell, with or without support for integer value exchange + */ + private com.sun.star.form.binding.XValueBinding createCellBinding( short sheet, short column, short row, boolean supportIntegerValues ) + { + com.sun.star.form.binding.XValueBinding cellBinding = null; + try + { + CellAddress address = new CellAddress( sheet, column, row ); + Object[] initParam = new Object[] { new NamedValue( "BoundCell", address ) }; + cellBinding = UnoRuntime.queryInterface( + com.sun.star.form.binding.XValueBinding.class, + createInstanceWithArguments( + supportIntegerValues ? "com.sun.star.table.ListPositionCellBinding" + : "com.sun.star.table.CellValueBinding", + initParam + ) + ); + } + catch( com.sun.star.uno.Exception e ) + { + System.err.println( e ); + e.printStackTrace( System.err ); + } + return cellBinding; + } + + /** creates a source of list entries associated with a (one-column) cell range + */ + public com.sun.star.form.binding.XListEntrySource createListEntrySource( short sheet, short column, + short topRow, short bottomRow ) + { + com.sun.star.form.binding.XListEntrySource entrySource = null; + try + { + CellRangeAddress rangeAddress = new CellRangeAddress( sheet, column, + topRow, column, bottomRow ); + Object[] initParam = new Object[] { new NamedValue( "CellRange", rangeAddress ) }; + entrySource = UnoRuntime.queryInterface( + com.sun.star.form.binding.XListEntrySource.class, + createInstanceWithArguments( + "com.sun.star.table.CellRangeListSource", initParam ) ); + } + catch( com.sun.star.uno.Exception e ) + { + System.err.println( e ); + e.printStackTrace( System.err ); + } + return entrySource; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/SpreadsheetValueBinding.java b/odk/examples/DevelopersGuide/Forms/SpreadsheetValueBinding.java new file mode 100644 index 000000000..1f08f2e7e --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/SpreadsheetValueBinding.java @@ -0,0 +1,125 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.uno.UnoRuntime; + +import com.sun.star.beans.XPropertySet; +import com.sun.star.table.XCellRange; +import com.sun.star.text.XTextRange; +import com.sun.star.form.binding.XValueBinding; +import com.sun.star.form.binding.XBindableValue; +import com.sun.star.form.binding.XListEntrySource; +import com.sun.star.form.binding.XListEntrySink; + +public class SpreadsheetValueBinding extends DocumentBasedExample +{ + /** Creates a new instance of SpreadsheetValueBinding */ + public SpreadsheetValueBinding() + { + super( DocumentType.CALC ); + } + + /* ------------------------------------------------------------------ */ + @Override + protected void prepareDocument() throws com.sun.star.uno.Exception, java.lang.Exception + { + super.prepareDocument(); + + SpreadsheetDocument document = (SpreadsheetDocument)m_document; + + final short sheet = (short)0; + final short exchangeColumn = (short)1; // B + final short exchangeRow = (short)1; // 2 + final Integer backColor = Integer.valueOf( 0x00E0E0E0 ); + + + // a numeric control + XPropertySet numericControl = m_formLayer.insertControlLine( "NumericField", + "enter a value", "", 30 ); + numericControl.setPropertyValue( "ValueMin", Short.valueOf( (short)1 ) ); + numericControl.setPropertyValue( "ValueMax", Short.valueOf( (short)5 ) ); + numericControl.setPropertyValue( "Value", Short.valueOf( (short)1 ) ); + numericControl.setPropertyValue( "DecimalAccuracy", Short.valueOf( (short)0 ) ); + numericControl.setPropertyValue( "Spin", Boolean.TRUE ); + + // bind the control model to cell B2 + implBind( numericControl, document.createCellBinding( sheet, exchangeColumn, exchangeRow ) ); + + + // insert a list box + XPropertySet listBox = m_formLayer.insertControlLine( "ListBox", + "select an entry", "", 2, 40, 20 ); + listBox.setPropertyValue( "Dropdown", Boolean.FALSE ); + + // a list binding for cell range C1-C5 + final short listSourceSheet = (short)1; + final short column = (short)0; + final short topRow = (short)0; + final short bottomRow = (short)4; + XListEntrySource entrySource = document.createListEntrySource( + listSourceSheet, column, topRow, bottomRow ); + + // bind it to the list box + XListEntrySink consumer = UnoRuntime.queryInterface( + XListEntrySink.class, listBox ); + consumer.setListEntrySource( entrySource ); + + // and also put the list selection index into cell B2 + implBind( listBox, document.createListIndexBinding( sheet, exchangeColumn, exchangeRow ) ); + + + // fill the cells which we just bound the listbox to + XCellRange exchangeSheet = document.getSheet( listSourceSheet ); + String[] listContent = new String[] { "first", "second", "third", "forth", "fivth" }; + for ( short row = topRow; row <= bottomRow; ++row ) + { + XTextRange cellText = UnoRuntime.queryInterface( + XTextRange.class, exchangeSheet.getCellByPosition( column, row ) ); + cellText.setString( listContent[row] ); + } + + // some coloring + XPropertySet exchangeCell = UNO.queryPropertySet( + document.getSheet( sheet ).getCellByPosition( exchangeColumn, exchangeRow ) + ); + exchangeCell.setPropertyValue( "CellBackColor", backColor ); + numericControl.setPropertyValue( "BackgroundColor", backColor ); + listBox.setPropertyValue( "BackgroundColor", backColor ); + } + + /* ------------------------------------------------------------------ */ + private void implBind( XPropertySet controlModel, XValueBinding binding ) throws com.sun.star.form.binding.IncompatibleTypesException + { + XBindableValue bindable = UnoRuntime.queryInterface( + XBindableValue.class, controlModel + ); + bindable.setValueBinding( binding ); + } + + /* ------------------------------------------------------------------ */ + /** class entry point + */ + public static void main(String argv[]) throws java.lang.Exception + { + SpreadsheetValueBinding aSample = new SpreadsheetValueBinding(); + aSample.run( argv ); + } + } + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/SpreadsheetView.java b/odk/examples/DevelopersGuide/Forms/SpreadsheetView.java new file mode 100644 index 000000000..63a8e6a98 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/SpreadsheetView.java @@ -0,0 +1,35 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.lang.*; +import com.sun.star.frame.*; + +public class SpreadsheetView extends DocumentViewHelper +{ + + /** Creates a new instance of SpreadsheetView */ + public SpreadsheetView( XMultiServiceFactory orb, DocumentHelper document, XController controller ) + { + super( orb, document, controller ); + } + + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/TableCellTextBinding.java b/odk/examples/DevelopersGuide/Forms/TableCellTextBinding.java new file mode 100644 index 000000000..23a9e4226 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/TableCellTextBinding.java @@ -0,0 +1,199 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +import com.sun.star.uno.Type; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.table.XCell; +import com.sun.star.util.XModifyListener; +import com.sun.star.text.XTextRange; + +/** a value binding to be connected to a form control + + This binding synchronizes the text contained in a table cell (which you must + pass upon construction) to the text in an XBindableValue. + + Well, in real it does not synchronize both directions. The ValueBinding + service has not much room for own activity: It allows notification of changes + in the own value, and it allows external instances to set the current value. + + Note that we implement this binding as a separate thread, which is (more or + less permanently) polling for a new text at the cell. This is unfortunate, but + sadly the Writer table cells do not support actively notifying changes in their + content to other interested parties. +*/ +public class TableCellTextBinding + extends java.lang.Thread + implements com.sun.star.form.binding.XValueBinding, + com.sun.star.util.XModifyBroadcaster +{ + private XTextRange m_cellText; + private Object m_writeSignal; + private String m_newCellText; + private String m_lastKnownCellText; + private boolean m_haveNewCellText; + private java.util.List m_listeners; + + /** Creates a new instance of TableCellTextBinding */ + public TableCellTextBinding( XCell cell ) + { + m_cellText = UnoRuntime.queryInterface( XTextRange.class, cell ); + + m_newCellText = ""; + m_listeners = new java.util.LinkedList(); + + start(); + } + + /** retrieves the list of data types which this binding can exchange + */ + public com.sun.star.uno.Type[] getSupportedValueTypes() + { + try + { + // well, only strings here ... + return new Type[] { + getStringType() + }; + } + catch( java.lang.Exception e ) + { + } + return new Type[] { }; + } + + /** retrieves the current value + */ + public Object getValue(com.sun.star.uno.Type type) throws com.sun.star.form.binding.IncompatibleTypesException + { + if ( !type.equals( getStringType() ) ) + throw new com.sun.star.form.binding.IncompatibleTypesException(); + + return m_cellText.getString(); + } + + /** sets a new value + */ + public void setValue(Object obj) throws com.sun.star.form.binding.IncompatibleTypesException + { + String text; + try + { + text = (String)obj; + } + catch( java.lang.ClassCastException e ) + { + throw new com.sun.star.form.binding.IncompatibleTypesException(); + } + // remember the new text + synchronized( m_newCellText ) + { + m_newCellText = text; + m_haveNewCellText = true; + } + // and wake up the thread which is waiting for it + synchronized( m_writeSignal ) + { + m_writeSignal.notify(); + } + } + + /** determines whether a given value type is supported + */ + public boolean supportsType(com.sun.star.uno.Type type) + { + return type.equals( getStringType() ); + } + + /** retrieves the UNO type for the string class + */ + private static final Type getStringType() + { + return new com.sun.star.uno.Type( String.class ); + } + + /** runs the thread + */ + @Override + public void run() + { + try + { + m_writeSignal = new Object(); + while ( true ) + { + // go sleep a while + synchronized( m_writeSignal ) + { + m_writeSignal.wait( 200 ); + } + + // if there's new text in the control, propagate it to the cell + synchronized ( m_newCellText ) + { + if ( m_haveNewCellText ) + { + m_cellText.setString( m_newCellText ); + m_lastKnownCellText = m_newCellText; + } + m_haveNewCellText = false; + } + + // if there's new text in the cell, propagate it to the control + String currentCellText = m_cellText.getString(); + if ( !currentCellText.equals( m_lastKnownCellText ) ) + { + m_lastKnownCellText = currentCellText; + // notify the modification + synchronized( m_listeners ) + { + com.sun.star.lang.EventObject eventSource = new com.sun.star.lang.EventObject( this ); + + java.util.Iterator loop = m_listeners.iterator(); + while ( loop.hasNext() ) + { + loop.next().modified( eventSource ); + } + } + } + } + } + catch( java.lang.Exception e ) + { + e.printStackTrace(System.err); + } + } + + public void addModifyListener(com.sun.star.util.XModifyListener xModifyListener) + { + synchronized( m_listeners ) + { + m_listeners.add( xModifyListener ); + } + } + + public void removeModifyListener(com.sun.star.util.XModifyListener xModifyListener) + { + synchronized( m_listeners ) + { + m_listeners.remove( xModifyListener ); + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/TextValidator.java b/odk/examples/DevelopersGuide/Forms/TextValidator.java new file mode 100644 index 000000000..241bd8778 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/TextValidator.java @@ -0,0 +1,78 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +public class TextValidator extends ControlValidator +{ + + /** Creates a new instance of NumericValidator */ + public TextValidator( ) + { + } + + public String explainInvalid( Object Value ) + { + try + { + String value = (String)Value; + if ( containsZs( value ) ) + return "No Z's allowed here"; + if ( !isProperChunks( value ) ) + return "Need 3 * n characters"; + } + catch( java.lang.Exception e ) + { + return "ooops. Unknown error"; + } + return ""; + } + + public boolean isValid( Object Value ) + { + try + { + String value = (String)Value; + if ( containsZs( value ) ) + return false; + if ( !isProperChunks( value ) ) + return false; + return true; + } + catch( java.lang.Exception e ) + { + } + return false; + } + + private boolean isProperChunks( String value ) + { + return ( value.length() % 3 ) == 0; + } + + private boolean containsZs( String value ) + { + if ( ( value.indexOf( 'Z' ) != -1 ) + || ( value.indexOf( 'z' ) != -1 ) + ) + return true; + return false; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/TimeValidator.java b/odk/examples/DevelopersGuide/Forms/TimeValidator.java new file mode 100644 index 000000000..d5f1503d8 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/TimeValidator.java @@ -0,0 +1,83 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +public class TimeValidator extends ControlValidator +{ + + /** Creates a new instance of NumericValidator */ + public TimeValidator( ) + { + } + + public String explainInvalid( Object Value ) + { + try + { + if ( isVoid( Value ) ) + return "empty input"; + + com.sun.star.util.Time timeValue = (com.sun.star.util.Time)Value; + if ( isInvalidTime( timeValue ) ) + return "this is no valid time"; + if ( !isFullHour( timeValue ) ) + return "time must denote a full hour"; + } + catch( java.lang.Exception e ) + { + return "this is no valid time"; + } + return ""; + } + + public boolean isValid( Object Value ) + { + try + { + if ( isVoid( Value ) ) + return false; + + com.sun.star.util.Time timeValue = (com.sun.star.util.Time) + com.sun.star.uno.AnyConverter.toObject( + com.sun.star.util.Time.class, Value); + if ( isInvalidTime( timeValue ) ) + return false; + if ( !isFullHour( timeValue ) ) + return false; + return true; + } + catch( java.lang.Exception e ) + { + e.printStackTrace( System.err ); + } + return false; + } + + private boolean isInvalidTime( com.sun.star.util.Time timeValue ) + { + return ( timeValue.Hours == -1 ) && ( timeValue.Minutes == -1 ) && ( timeValue.Seconds == -1 ) && ( timeValue.NanoSeconds == -1 ); + } + + private boolean isFullHour( com.sun.star.util.Time timeValue ) + { + return ( timeValue.Minutes == 0 ) && ( timeValue.Seconds == 0 ) && ( timeValue.NanoSeconds == 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/UNO.java b/odk/examples/DevelopersGuide/Forms/UNO.java new file mode 100644 index 000000000..f2e6fc611 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/UNO.java @@ -0,0 +1,89 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.*; +import com.sun.star.beans.*; +import com.sun.star.awt.*; +import com.sun.star.container.*; +import com.sun.star.form.*; +import com.sun.star.lang.*; +import com.sun.star.sdb.*; + +public class UNO +{ + public static XPropertySet queryPropertySet( Object aObject ) + { + return UnoRuntime.queryInterface( XPropertySet.class, aObject ); + } + public static XControlModel queryControlModel( Object aObject ) + { + return UnoRuntime.queryInterface( XControlModel.class, aObject ); + } + public static XIndexContainer queryIndexContainer( Object aObject ) + { + return UnoRuntime.queryInterface( XIndexContainer.class, aObject ); + } + public static XReset queryReset( Object aObject ) + { + return UnoRuntime.queryInterface( XReset.class, aObject ); + } + public static XServiceInfo queryServiceInfo( Object aObject ) + { + return UnoRuntime.queryInterface( XServiceInfo.class, aObject ); + } + public static XColumn queryColumn( Object aObject ) + { + return UnoRuntime.queryInterface( XColumn.class, aObject ); + } + + public static XComponent queryComponent( Object aObject ) + { + return UnoRuntime.queryInterface( XComponent.class, aObject ); + } + + + +/* replace Foo with the identifier of your choice. + + Why does Java not have templates? + + public static XFoo queryFoo( Object aObject ) + { + return (XFoo)UnoRuntime.queryInterface( XFoo.class, aObject ); + } +*/ +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/URLHelper.java b/odk/examples/DevelopersGuide/Forms/URLHelper.java new file mode 100644 index 000000000..d1d361676 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/URLHelper.java @@ -0,0 +1,65 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import java.io.File; +import java.net.MalformedURLException; + +public class URLHelper +{ + /** + * Because the office need URLs for loading/saving documents + * we must convert used system paths. + * And java use another notation for file URLs ... correct it. + * + * @param aSystemPath + * represent the file in system notation + * + * @return [String] + * a file url which represent the given system path + */ + public static String getFileURLFromSystemPath( File aSystemPath ) + { + String sFileURL = null; + try + { + sFileURL = aSystemPath.toURI().toURL().toString(); + } + catch( MalformedURLException exWrong ) + { + sFileURL = null; + } + + // problem of java: file URL's are coded with 1 slash instead of 2 or 3 ones! + // => correct this problem first, otherwise office can't use these URL's + if( + (sFileURL != null ) && + (sFileURL.startsWith("file:/") == true ) && + (sFileURL.startsWith("file://") == false) + ) + { + StringBuffer sWorkBuffer = new StringBuffer(sFileURL); + sWorkBuffer.insert(6,"//"); + sFileURL = sWorkBuffer.toString(); + } + + return sFileURL; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/ValueBinding.java b/odk/examples/DevelopersGuide/Forms/ValueBinding.java new file mode 100644 index 000000000..273f04cda --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/ValueBinding.java @@ -0,0 +1,82 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.uno.UnoRuntime; + +import com.sun.star.beans.XPropertySet; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XText; +import com.sun.star.text.XTextTable; +import com.sun.star.text.XTextCursor; +import com.sun.star.form.binding.XValueBinding; +import com.sun.star.form.binding.XBindableValue; + +public class ValueBinding extends DocumentBasedExample +{ + /** Creates a new instance of ValueBinding */ + public ValueBinding() + { + super( DocumentType.WRITER ); + } + + /* ------------------------------------------------------------------ */ + @Override + protected void prepareDocument() throws com.sun.star.uno.Exception, java.lang.Exception + { + super.prepareDocument(); + + // insert a table with exactly one cell. The content of this table will be synced with + // the content of a form control + XTextDocument textDoc = UnoRuntime.queryInterface( XTextDocument.class, m_document.getDocument() ); + XText documentText = textDoc.getText(); + XTextCursor textCursor = documentText.createTextCursor(); + documentText.insertString( textCursor, "Below, there's a table cell, and a text field. ", false ); + documentText.insertString( textCursor, "Both are linked via an external value binding.\n", false ); + documentText.insertString( textCursor, "That means that anything you insert into the table cell is reflected in the ", false ); + documentText.insertString( textCursor, "text field, and vice versa.\n", false ); + + XTextTable table = UnoRuntime.queryInterface( XTextTable.class, + m_document.createInstance( "com.sun.star.text.TextTable" ) + ); + table.initialize( 1, 1 ); + documentText.insertTextContent( textCursor, table, false ); + + // insert our sample control + XPropertySet textControl = m_formLayer.insertControlLine( "DatabaseTextField", "enter some text", "", 30 ); + + // create a value binding for the first cell of the table + XValueBinding cellBinding = new TableCellTextBinding( table.getCellByName( "A1" ) ); + // and bind it to the control + XBindableValue bindable = UnoRuntime.queryInterface( + XBindableValue.class, textControl + ); + bindable.setValueBinding( cellBinding ); + } + + /* ------------------------------------------------------------------ */ + /** class entry point + */ + public static void main(String argv[]) throws java.lang.Exception + { + ValueBinding aSample = new ValueBinding(); + aSample.run( argv ); + } + } + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Forms/WaitForInput.java b/odk/examples/DevelopersGuide/Forms/WaitForInput.java new file mode 100644 index 000000000..e5891ada4 --- /dev/null +++ b/odk/examples/DevelopersGuide/Forms/WaitForInput.java @@ -0,0 +1,58 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ +class WaitForInput extends java.lang.Thread +{ + private Object m_aToNotify; + private boolean m_bDone; + + public WaitForInput( Object aToNotify ) + { + m_aToNotify = aToNotify; + m_bDone = false; + } + + public boolean isDone() + { + return m_bDone; + } + + @Override + public void run() + { + try + { + System.out.println( "\npress 'enter' to exit demo" ); + System.in.read(); + + m_bDone = true; + // notify that the user pressed the key + synchronized (m_aToNotify) + { + m_aToNotify.notify(); + } + } + catch( java.lang.Exception e ) + { + // not really interested in + System.err.println( e ); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/GUI/DialogDocument.java b/odk/examples/DevelopersGuide/GUI/DialogDocument.java new file mode 100644 index 000000000..4b535534d --- /dev/null +++ b/odk/examples/DevelopersGuide/GUI/DialogDocument.java @@ -0,0 +1,146 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.awt.PushButtonType; +import com.sun.star.awt.Rectangle; +import com.sun.star.awt.VclWindowPeerAttribute; +import com.sun.star.awt.WindowAttribute; +import com.sun.star.awt.WindowClass; +import com.sun.star.awt.XToolkit; +import com.sun.star.awt.XView; +import com.sun.star.awt.XWindow; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XMultiPropertySet; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XFrame; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + + +public class DialogDocument extends UnoDialogSample { + + public DialogDocument(XComponentContext _xContext, XMultiComponentFactory _xMCF) { + super(_xContext, _xMCF); + } + + public static void main(String args[]){ + DialogDocument oDialogDocument = null; + try { + XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if(xContext != null ) + System.out.println("Connected to a running office ..."); + XMultiComponentFactory xMCF = xContext.getServiceManager(); + oDialogDocument = new DialogDocument(xContext, xMCF); + oDialogDocument.initialize( new String[] {"Height", "Moveable", "Name","PositionX","PositionY", "Step", "TabIndex","Title","Width"}, + new Object[] { Integer.valueOf(400), Boolean.TRUE, "Dialog1", Integer.valueOf(102),Integer.valueOf(41), Integer.valueOf(1), Short.valueOf((short) 0), "Document-Dialog", Integer.valueOf(300)}); + oDialogDocument.createWindowPeer(); + Object oFTHeaderModel = oDialogDocument.m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel"); + XMultiPropertySet xFTHeaderModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oFTHeaderModel); + xFTHeaderModelMPSet.setPropertyValues( + new String[] {"Height", "Label", "Name", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(8), "This code-sample demonstrates how to display an office document in a dialog window", "HeaderLabel", Integer.valueOf(6), Integer.valueOf(6), Integer.valueOf(300)}); + // add the model to the NameContainer of the dialog model + oDialogDocument.m_xDlgModelNameContainer.insertByName("Headerlabel", oFTHeaderModel); + oDialogDocument.showDocumentinDialogWindow(oDialogDocument.m_xWindowPeer, new Rectangle(40, 50, 420, 550), "private:factory/swriter"); + + oDialogDocument.insertButton(oDialogDocument, 126, 370, 50, "~Close dialog", (short) PushButtonType.OK_value); + oDialogDocument.executeDialog(); + }catch( Exception ex ) { + ex.printStackTrace(System.err); + } finally{ + //make sure always to dispose the component and free the memory! + if (oDialogDocument != null){ + if (oDialogDocument.m_xComponent != null) { + oDialogDocument.m_xComponent.dispose(); + } + } + } + + System.exit( 0 ); + } + + public void showDocumentinDialogWindow(XWindowPeer _xParentWindowPeer, Rectangle _aRectangle, String _sUrl){ + try { + // The Toolkit is the creator of all windows... + Object oToolkit = m_xMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", m_xContext); + XToolkit xToolkit = UnoRuntime.queryInterface(XToolkit.class, oToolkit); + + // set up a window description and create the window. A parent window is always necessary for this... + com.sun.star.awt.WindowDescriptor aWindowDescriptor = new com.sun.star.awt.WindowDescriptor(); + // a simple window is enough for this purpose... + aWindowDescriptor.Type = WindowClass.SIMPLE; + aWindowDescriptor.WindowServiceName = "dockingwindow"; + // assign the parent window peer as described in the idl description... + aWindowDescriptor.Parent = _xParentWindowPeer; + aWindowDescriptor.ParentIndex = 1; + aWindowDescriptor.Bounds = _aRectangle; + + // set the window attributes... + // The attribute CLIPCHILDREN causes the parent to not repaint the areas of the children... + aWindowDescriptor.WindowAttributes = VclWindowPeerAttribute.CLIPCHILDREN + WindowAttribute.BORDER + WindowAttribute.SHOW; + XWindowPeer xWindowPeer = xToolkit.createWindow(aWindowDescriptor); + XWindow xWindow = UnoRuntime.queryInterface(XWindow.class, xWindowPeer); + XView xView = UnoRuntime.queryInterface(XView.class, xWindow); + + // create a frame and initialize it with the created window... + Object oFrame = m_xMCF.createInstanceWithContext("com.sun.star.frame.Frame", m_xContext); + // The frame should be of global scope because it's within the responsibility to dispose it after usage + m_xFrame = UnoRuntime.queryInterface(XFrame.class, oFrame); + m_xFrame.initialize(xWindow); + + // load the document and open it in preview mode + XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, m_xFrame); + PropertyValue[] aPropertyValues = new PropertyValue[2]; + PropertyValue aPropertyValue = new PropertyValue(); + aPropertyValue.Name = "Preview"; + aPropertyValue.Value = Boolean.TRUE; + aPropertyValues[0] = aPropertyValue; + aPropertyValue = new PropertyValue(); + aPropertyValue.Name = "ReadOnly"; + aPropertyValue.Value = Boolean.TRUE; + aPropertyValues[1] = aPropertyValue; + xComponentLoader.loadComponentFromURL(_sUrl, "_self", 0, aPropertyValues); + } catch (com.sun.star.lang.IllegalArgumentException ex) { + throw new java.lang.RuntimeException("cannot happen...", ex); + } catch (com.sun.star.uno.Exception ex) { + throw new java.lang.RuntimeException("cannot happen...", ex); + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/GUI/ImageControlSample.java b/odk/examples/DevelopersGuide/GUI/ImageControlSample.java new file mode 100644 index 000000000..060b5e681 --- /dev/null +++ b/odk/examples/DevelopersGuide/GUI/ImageControlSample.java @@ -0,0 +1,166 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.awt.PushButtonType; +import com.sun.star.awt.XDialog; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XMultiPropertySet; +import com.sun.star.beans.XPropertySet; +import com.sun.star.graphic.XGraphic; +import com.sun.star.graphic.XGraphicProvider; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.ucb.XFileIdentifierConverter; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + + +public class ImageControlSample extends UnoDialogSample{ + /** + * Creates a new instance of ImageControlSample + */ + public ImageControlSample(XComponentContext _xContext, XMultiComponentFactory _xMCF){ + super(_xContext, _xMCF); + super.createDialog(_xMCF); + } + + // to start this script pass a parameter denoting the system path to a graphic to be displayed + public static void main(String args[]) { + ImageControlSample oImageControlSample = null; + try { + if (args.length == 0) { + System.out.println("Please pass a parameter denoting the system path to your graphic!"); + return; + } + XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if(xContext != null ){ + System.out.println("Connected to a running office ..."); + } + XMultiComponentFactory xMCF = xContext.getServiceManager(); + oImageControlSample = new ImageControlSample(xContext, xMCF); + oImageControlSample.initialize( new String[] {"Height", "Moveable", "Name","PositionX","PositionY", "Step", "TabIndex","Title","Width"}, + new Object[] { Integer.valueOf(100), Boolean.TRUE, "MyTestDialog", Integer.valueOf(102),Integer.valueOf(41), Integer.valueOf(0), Short.valueOf((short) 0), "OpenOffice", Integer.valueOf(230)}); + Object oFTHeaderModel = oImageControlSample.m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel"); + XMultiPropertySet xFTHeaderModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oFTHeaderModel); + xFTHeaderModelMPSet.setPropertyValues( + new String[] {"Height", "Label", "MultiLine", "Name", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(16), "This code-sample demonstrates how to create an ImageControlSample within a dialog", Boolean.TRUE, "HeaderLabel", Integer.valueOf(6), Integer.valueOf(6), Integer.valueOf(210)}); + // add the model to the NameContainer of the dialog model + oImageControlSample.m_xDlgModelNameContainer.insertByName("Headerlabel", oFTHeaderModel); + XPropertySet xICModelPropertySet = oImageControlSample.insertImageControl(68, 30, 32, 90); + oImageControlSample.insertButton(oImageControlSample, 90, 75, 50, "~Close dialog", (short) PushButtonType.OK_value); + oImageControlSample.createWindowPeer(); + // note: due to issue i76718 ("Setting graphic at a controlmodel required dialog peer") the graphic of the image control + // may not be set before the peer of the dialog has been created. + XGraphic xGraphic = oImageControlSample.getGraphic(oImageControlSample.m_xMCF, args[0]); + xICModelPropertySet.setPropertyValue("Graphic", xGraphic); + oImageControlSample.xDialog = UnoRuntime.queryInterface(XDialog.class, oImageControlSample.m_xDialogControl); + oImageControlSample.executeDialog(); + }catch( Exception e ) { + System.err.println( e + e.getMessage()); + e.printStackTrace(); + } finally{ + //make sure always to dispose the component and free the memory! + if (oImageControlSample != null){ + if (oImageControlSample.m_xComponent != null){ + oImageControlSample.m_xComponent.dispose(); + } + } + } + System.exit( 0 ); + } + + + public XPropertySet insertImageControl(int _nPosX, int _nPosY, int _nHeight, int _nWidth){ + XPropertySet xICModelPropertySet = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "ImageControl"); + // convert the system path to the image to a FileUrl + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oICModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlImageControlModel"); + XMultiPropertySet xICModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oICModel); + xICModelPropertySet =UnoRuntime.queryInterface(XPropertySet.class, oICModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + // The image is not scaled + xICModelMPSet.setPropertyValues( + new String[] {"Border", "Height", "Name", "PositionX", "PositionY", "ScaleImage", "Width"}, + new Object[] { Short.valueOf((short) 1), Integer.valueOf(_nHeight), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Boolean.FALSE, Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oICModel); + }catch (com.sun.star.uno.Exception ex){ + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xICModelPropertySet; + } + + +// creates a UNO graphic object that can be used to be assigned +// to the property "Graphic" of a controlmodel + public XGraphic getGraphic(XMultiComponentFactory _xMCF, String _sImageSystemPath){ + XGraphic xGraphic = null; + try{ + java.io.File oFile = new java.io.File(_sImageSystemPath); + Object oFCProvider = _xMCF.createInstanceWithContext("com.sun.star.ucb.FileContentProvider", this.m_xContext); + XFileIdentifierConverter xFileIdentifierConverter = UnoRuntime.queryInterface(XFileIdentifierConverter.class, oFCProvider); + String sImageUrl = xFileIdentifierConverter.getFileURLFromSystemPath(_sImageSystemPath, oFile.getAbsolutePath()); + + // create a GraphicProvider at the global service manager... + Object oGraphicProvider = m_xMCF.createInstanceWithContext("com.sun.star.graphic.GraphicProvider", m_xContext); + XGraphicProvider xGraphicProvider = UnoRuntime.queryInterface(XGraphicProvider.class, oGraphicProvider); + // create the graphic object + PropertyValue[] aPropertyValues = new PropertyValue[1]; + PropertyValue aPropertyValue = new PropertyValue(); + aPropertyValue.Name = "URL"; + aPropertyValue.Value = sImageUrl; + aPropertyValues[0] = aPropertyValue; + xGraphic = xGraphicProvider.queryGraphic(aPropertyValues); + return xGraphic; + }catch (com.sun.star.uno.Exception ex){ + throw new java.lang.RuntimeException("cannot happen...", ex); + }} +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/GUI/Makefile b/odk/examples/DevelopersGuide/GUI/Makefile new file mode 100644 index 000000000..6eb18efdc --- /dev/null +++ b/odk/examples/DevelopersGuide/GUI/Makefile @@ -0,0 +1,141 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the GUI examples of the Developers Guide. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=GUIExamples +SAMPLE_CLASS_OUT = $(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT = $(OUT_MISC)/$(SAMPLE_NAME) + + +APP1_NAME=DialogDocument +APP1_JAR=$(SAMPLE_CLASS_OUT)/$(APP1_NAME).jar +APP2_NAME=MessageBox +APP2_JAR=$(SAMPLE_CLASS_OUT)/$(APP2_NAME).jar +APP3_NAME=UnoDialogSample +APP3_JAR=$(SAMPLE_CLASS_OUT)/$(APP3_NAME).jar +APP4_NAME=UnoDialogSample2 +APP4_JAR=$(SAMPLE_CLASS_OUT)/$(APP4_NAME).jar +APP5_NAME=UnoMenu +APP5_JAR=$(SAMPLE_CLASS_OUT)/$(APP5_NAME).jar +APP6_NAME=UnoMenu2 +APP6_JAR=$(SAMPLE_CLASS_OUT)/$(APP6_NAME).jar +APP7_NAME=ImageControlSample +APP7_JAR=$(SAMPLE_CLASS_OUT)/$(APP7_NAME).jar + +APP_JAVAFILES = \ + RoadmapItemStateChangeListener.java \ + UnoDialogSample.java \ + UnoMenu.java + +APP_CLASSFILES = $(patsubst %.java,$(SAMPLE_CLASS_OUT)/%.class,$(APP_JAVAFILES)) +# $(SAMPLE_CLASS_OUT)/UnoDialogSample\&RoadmapItemStateChangeListener.class + +APP_CLASSNAMES = $(patsubst %.java,%.class,$(APP_JAVAFILES)) +#APP_CLASSNAMES = $(patsubst $(SAMPLE_CLASS_OUT)/%.class,%.class,$(APP_CLASSFILES)) + + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : \ + GUIExamples + + +include $(SETTINGS)/stdtarget.mk + + +$(APP_CLASSFILES) : $(APP_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SAMPLE_CLASS_OUT) $(APP_JAVAFILES) + +$(SAMPLE_CLASS_OUT)/%.class : %.java $(APP_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SAMPLE_CLASS_OUT) $< + +$(SAMPLE_CLASS_OUT)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(SAMPLE_CLASS_OUT)/%.jar : $(SAMPLE_CLASS_OUT)/%.mf $(SAMPLE_CLASS_OUT)/%.class $(APP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class $(APP_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP1_JAR) : $(SAMPLE_CLASS_OUT)/$(APP1_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP1_NAME).class +$(APP2_JAR) : $(SAMPLE_CLASS_OUT)/$(APP2_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP2_NAME).class +$(APP3_JAR) : $(SAMPLE_CLASS_OUT)/$(APP3_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP3_NAME).class +$(APP4_JAR) : $(SAMPLE_CLASS_OUT)/$(APP4_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP4_NAME).class +$(APP5_JAR) : $(SAMPLE_CLASS_OUT)/$(APP5_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP5_NAME).class +$(APP6_JAR) : $(SAMPLE_CLASS_OUT)/$(APP6_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP6_NAME).class +$(APP7_JAR) : $(SAMPLE_CLASS_OUT)/$(APP7_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP7_NAME).class + +GUIExamples : $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) $(APP4_JAR) $(APP5_JAR) $(APP6_JAR) $(APP7_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP2_NAME).run + @echo $(MAKE) $(APP3_NAME).run + @echo $(MAKE) $(APP4_NAME).run + @echo $(MAKE) $(APP5_NAME).run + @echo $(MAKE) $(APP6_NAME).run + @echo $(MAKE) $(APP7_NAME).run + @echo -------- + +%.run: $(SAMPLE_CLASS_OUT)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +$(APP7_NAME).run: $(SAMPLE_CLASS_OUT)/$(APP7_NAME).jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< .$(PS)oologo.gif + + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) diff --git a/odk/examples/DevelopersGuide/GUI/MessageBox.java b/odk/examples/DevelopersGuide/GUI/MessageBox.java new file mode 100644 index 000000000..cff15262d --- /dev/null +++ b/odk/examples/DevelopersGuide/GUI/MessageBox.java @@ -0,0 +1,237 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.awt.MessageBoxType; +import com.sun.star.awt.XMessageBox; +import com.sun.star.awt.XMessageBoxFactory; +import com.sun.star.awt.XVclWindowPeer; +import com.sun.star.awt.XWindow; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.XModel; +import com.sun.star.util.XCloseable; +import com.sun.star.frame.XFramesSupplier; +import com.sun.star.lang.IllegalArgumentException; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + + + +public class MessageBox { + + protected XComponentContext m_xContext = null; + protected com.sun.star.lang.XMultiComponentFactory m_xMCF; + + /** Creates a new instance of MessageBox */ + public MessageBox(XComponentContext _xContext, XMultiComponentFactory _xMCF){ + m_xContext = _xContext; + m_xMCF = _xMCF; + } + + public static void main(String args[]) { + XComponent xComp = null; + try { + XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if(xContext != null ) + System.out.println("Connected to a running office ..."); + XMultiComponentFactory xMCF = xContext.getServiceManager(); + + MessageBox oMessageBox = new MessageBox(xContext, xMCF); + + //load default text document to get an active frame + xComp = oMessageBox.createDefaultTextDocument(); + + XWindowPeer xWindowPeer = oMessageBox.getWindowPeerOfFrame(xComp); + if (xWindowPeer != null) { + XVclWindowPeer xVclWindowPeer = UnoRuntime.queryInterface(XVclWindowPeer.class, xWindowPeer); + boolean bisHighContrast = oMessageBox.isHighContrastModeActivated(xVclWindowPeer); + oMessageBox.showErrorMessageBox(xWindowPeer, "My Sampletitle", "HighContrastMode is enabled: " + bisHighContrast); + } else{ + System.out.println("Could not retrieve current frame"); + } + + } catch( Exception e ) { + System.err.println( e + e.getMessage()); + e.printStackTrace(); + } finally { + if (xComp != null) { + try { + XCloseable xClose = UnoRuntime.queryInterface(XCloseable.class, xComp); + if (xClose != null) { + xClose.close(false); + } else { + xComp.dispose(); + } + } catch (com.sun.star.util.CloseVetoException e) { + System.err.println( e + e.getMessage()); + e.printStackTrace(); + } + } + } + + System.exit( 0 ); + } + + // helper method to get the window peer of a document or if no + // document is specified it tries to get the active frame + // which is potentially dangerous + public XWindowPeer getWindowPeerOfFrame(XComponent xComp) { + try { + XFrame xFrame = null; + + if (xComp != null) { + XModel xModel = UnoRuntime.queryInterface(XModel.class, xComp); + xFrame = xModel.getCurrentController().getFrame(); + + } else { + // Note: This method is potentially dangerous and should only be used for debugging + // purposes as it relies on the platform dependent window handler... + Object oDesktop = m_xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", m_xContext); + XFramesSupplier xFramesSupplier = UnoRuntime.queryInterface(XFramesSupplier.class, oDesktop); + xFrame = xFramesSupplier.getActiveFrame(); + } + + if (xFrame != null){ + XWindow xWindow = xFrame.getContainerWindow(); + if (xWindow != null){ + XWindowPeer xWindowPeer = UnoRuntime.queryInterface(XWindowPeer.class, xWindow); + return xWindowPeer; + } + } + } catch (com.sun.star.uno.Exception ex) { + ex.printStackTrace(); + } + return null; + } + + XComponent createDefaultTextDocument() { + + XComponent xComp = null; + try { + Object oDesktop = m_xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", m_xContext); + + // get the component laoder from the desktop to create a new + // text document + com.sun.star.frame.XComponentLoader xCLoader =UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,oDesktop); + + com.sun.star.beans.PropertyValue[] args = new com.sun.star.beans.PropertyValue [1]; + args[0] = new com.sun.star.beans.PropertyValue(); + args[0].Name = "Hidden"; + args[0].Value = Boolean.TRUE; + String strDoc = "private:factory/swriter"; + + xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, args); + + } catch(com.sun.star.uno.Exception ex) { + ex.printStackTrace(); + } + return xComp; + } + + /** shows an error messagebox + * @param _xParentWindowPeer the windowpeer of the parent window + * @param _sTitle the title of the messagebox + * @param _sMessage the message of the messagebox + */ + public void showErrorMessageBox(XWindowPeer _xParentWindowPeer, String _sTitle, String _sMessage) { + XComponent xComponent = null; + try { + Object oToolkit = m_xMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", m_xContext); + XMessageBoxFactory xMessageBoxFactory = UnoRuntime.queryInterface(XMessageBoxFactory.class, oToolkit); + XMessageBox xMessageBox = xMessageBoxFactory.createMessageBox(_xParentWindowPeer, MessageBoxType.ERRORBOX, com.sun.star.awt.MessageBoxButtons.BUTTONS_OK, _sTitle, _sMessage); + xComponent = UnoRuntime.queryInterface(XComponent.class, xMessageBox); + if (xMessageBox != null){ + xMessageBox.execute(); + } + } catch (com.sun.star.uno.Exception ex) { + ex.printStackTrace(System.err); + } finally{ + //make sure always to dispose the component and free the memory! + if (xComponent != null){ + xComponent.dispose(); + } + } + } + + + /** @param _xVclWindowPeer the windowpeer of a dialog control or the dialog itself + * @return true if HighContrastMode is activated or false if HighContrastMode is deactivated + */ + public boolean isHighContrastModeActivated(XVclWindowPeer _xVclWindowPeer) { + boolean bIsActivated = false; + + try { + if (_xVclWindowPeer != null){ + int nUIColor = AnyConverter.toInt(_xVclWindowPeer.getProperty("DisplayBackgroundColor")); + int nRed = getRedColorShare(nUIColor); + int nGreen = getGreenColorShare(nUIColor); + int nBlue = getBlueColorShare(nUIColor); + int nLuminance = (( nBlue*28 + nGreen*151 + nRed*77 ) / 256 ); + boolean bisactivated = (nLuminance <= 25); + return bisactivated; + } else{ + return false; + } + } catch (IllegalArgumentException e) { + e.printStackTrace(System.err); + } + return bIsActivated; + } + + public static int getRedColorShare(int _nColor) { + int nRed = _nColor/65536; + return nRed; + } + + public static int getGreenColorShare(int _nColor) { + int nRedModulo = _nColor % 65536; + int nGreen = nRedModulo / 256; + return nGreen; + } + + public static int getBlueColorShare(int _nColor) { + int nRedModulo = _nColor % 65536; + int nGreenModulo = (nRedModulo % 256); + int nBlue = nGreenModulo; + return nBlue; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/GUI/RoadmapItemStateChangeListener.java b/odk/examples/DevelopersGuide/GUI/RoadmapItemStateChangeListener.java new file mode 100644 index 000000000..9a9db63cd --- /dev/null +++ b/odk/examples/DevelopersGuide/GUI/RoadmapItemStateChangeListener.java @@ -0,0 +1,69 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.awt.XItemListener; +import com.sun.star.lang.EventObject; +import com.sun.star.beans.XPropertySet; +import com.sun.star.uno.UnoRuntime; + + +public class RoadmapItemStateChangeListener implements XItemListener { + private final com.sun.star.lang.XMultiServiceFactory m_xMSFDialogModel; + + public RoadmapItemStateChangeListener(com.sun.star.lang.XMultiServiceFactory xMSFDialogModel) { + m_xMSFDialogModel = xMSFDialogModel; + } + + public void itemStateChanged(com.sun.star.awt.ItemEvent itemEvent) { + try { + // get the new ID of the roadmap that is supposed to refer to the new step of the dialogmodel + int nNewID = itemEvent.ItemId; + XPropertySet xDialogModelPropertySet = UnoRuntime.queryInterface(XPropertySet.class, m_xMSFDialogModel); + int nOldStep = ((Integer) xDialogModelPropertySet.getPropertyValue("Step")).intValue(); + // in the following line "ID" and "Step" are mixed together. + // In fact in this case they denote the same + if (nNewID != nOldStep){ + xDialogModelPropertySet.setPropertyValue("Step", Integer.valueOf(nNewID)); + } + } catch (com.sun.star.uno.Exception exception) { + exception.printStackTrace(System.err); + } + } + + public void disposing(EventObject eventObject) { + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/GUI/SystemDialog.java b/odk/examples/DevelopersGuide/GUI/SystemDialog.java new file mode 100644 index 000000000..62c6e3e03 --- /dev/null +++ b/odk/examples/DevelopersGuide/GUI/SystemDialog.java @@ -0,0 +1,188 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.beans.XPropertySet; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XInitialization; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.ui.dialogs.XExecutableDialog; +import com.sun.star.ui.dialogs.XFilePicker; +import com.sun.star.ui.dialogs.XFilePickerControlAccess; +import com.sun.star.ui.dialogs.XFilterManager; +import com.sun.star.ui.dialogs.XFolderPicker2; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.util.thePathSettings; + + +public class SystemDialog { + + protected XComponentContext m_xContext = null; + protected com.sun.star.lang.XMultiComponentFactory m_xMCF; + + /** Creates a new instance of MessageBox */ + public SystemDialog(XComponentContext _xContext, XMultiComponentFactory _xMCF){ + m_xContext = _xContext; + m_xMCF = _xMCF; + } + + public static void main(String args[]){ + try { + XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if(xContext != null ) + System.out.println("Connected to a running office ..."); + XMultiComponentFactory xMCF = xContext.getServiceManager(); + SystemDialog oSystemDialog = new SystemDialog(xContext, xMCF); + oSystemDialog.raiseSaveAsDialog(); + oSystemDialog.raiseFolderPicker(oSystemDialog.getWorkPath(), "My Title"); + }catch( Exception e ) { + System.err.println( e + e.getMessage()); + e.printStackTrace(); + } + + System.exit( 0 ); + } + + + public String raiseSaveAsDialog() { + String sStorePath = ""; + XComponent xComponent = null; + try { + // the filepicker is instantiated with the global Multicomponentfactory... + Object oFilePicker = m_xMCF.createInstanceWithContext("com.sun.star.ui.dialogs.FilePicker", m_xContext); + XFilePicker xFilePicker = UnoRuntime.queryInterface(XFilePicker.class, oFilePicker); + + // the defaultname is the initially proposed filename... + xFilePicker.setDefaultName("MyExampleDocument"); + + // set the initial displaydirectory. In this example the user template directory is used + Object oPathSettings = thePathSettings.get(m_xContext); + XPropertySet xPropertySet = com.sun.star.uno.UnoRuntime.queryInterface(XPropertySet.class, oPathSettings); + String sTemplateUrl = (String) xPropertySet.getPropertyValue("Template_writable"); + xFilePicker.setDisplayDirectory(sTemplateUrl); + + // set the filters of the dialog. The filternames may be retrieved from + // http://wiki.openoffice.org/wiki/Framework/Article/Filter + XFilterManager xFilterManager = UnoRuntime.queryInterface(XFilterManager.class, xFilePicker); + xFilterManager.appendFilter("OpenDocument Text Template", "writer8_template"); + xFilterManager.appendFilter("OpenDocument Text", "writer8"); + + // choose the template that defines the capabilities of the filepicker dialog + XInitialization xInitialize = UnoRuntime.queryInterface(XInitialization.class, xFilePicker); + short[] listAny = new short[] { com.sun.star.ui.dialogs.TemplateDescription.FILESAVE_AUTOEXTENSION }; + xInitialize.initialize(listAny); + + // add a control to the dialog to add the extension automatically to the filename... + XFilePickerControlAccess xFilePickerControlAccess = UnoRuntime.queryInterface(XFilePickerControlAccess.class, xFilePicker); + xFilePickerControlAccess.setValue(com.sun.star.ui.dialogs.ExtendedFilePickerElementIds.CHECKBOX_AUTOEXTENSION, (short) 0, Boolean.TRUE); + + xComponent = UnoRuntime.queryInterface(XComponent.class, xFilePicker); + + // execute the dialog... + XExecutableDialog xExecutable = UnoRuntime.queryInterface(XExecutableDialog.class, xFilePicker); + short nResult = xExecutable.execute(); + + // query the resulting path of the dialog... + if (nResult == com.sun.star.ui.dialogs.ExecutableDialogResults.OK){ + String[] sPathList = xFilePicker.getFiles(); + if (sPathList.length > 0){ + sStorePath = sPathList[0]; + } + } + } catch (com.sun.star.uno.Exception exception) { + exception.printStackTrace(); + } finally{ + //make sure always to dispose the component and free the memory! + if (xComponent != null){ + xComponent.dispose(); + } + } + return sStorePath; + } + + public String getWorkPath(){ + String sWorkUrl = ""; + try{ + // retrieve the configured Work path... + Object oPathSettings = thePathSettings.get(m_xContext); + XPropertySet xPropertySet = com.sun.star.uno.UnoRuntime.queryInterface(XPropertySet.class, oPathSettings); + sWorkUrl = (String) xPropertySet.getPropertyValue("Work"); + } catch (com.sun.star.uno.Exception exception) { + exception.printStackTrace(); + } + return sWorkUrl; + } + + /** raises a folderpicker in which the user can browse and select a path + * @param _sDisplayDirectory the path to the directory that is initially displayed + * @param _sTitle the title of the folderpicker + * @return the path to the folder that the user has selected. if the user has closed + * the folderpicker by clicking the "Cancel" button + * an empty string is returned + * @see com.sun.star.ui.dialogs.FolderPicker + */ + public String raiseFolderPicker(String _sDisplayDirectory, String _sTitle) { + String sReturnFolder = ""; + XComponent xComponent = null; + try { + // instantiate the folder picker and retrieve the necessary interfaces... + Object oFolderPicker = m_xMCF.createInstanceWithContext("com.sun.star.ui.dialogs.FolderPicker", m_xContext); + XFolderPicker2 xFolderPicker = UnoRuntime.queryInterface(XFolderPicker2.class, oFolderPicker); + XExecutableDialog xExecutable = UnoRuntime.queryInterface(XExecutableDialog.class, oFolderPicker); + xComponent = UnoRuntime.queryInterface(XComponent.class, oFolderPicker); + xFolderPicker.setDisplayDirectory(_sDisplayDirectory); + // set the dialog title... + xFolderPicker.setTitle(_sTitle); + // show the dialog... + short nResult = xExecutable.execute(); + + // User has clicked "Select" button... + if (nResult == com.sun.star.ui.dialogs.ExecutableDialogResults.OK){ + sReturnFolder = xFolderPicker.getDirectory(); + } + + }catch( Exception exception ) { + exception.printStackTrace(System.err); + } finally{ + //make sure always to dispose the component and free the memory! + if (xComponent != null){ + xComponent.dispose(); + } + } + // return the selected path. If the user has clicked cancel an empty string is + return sReturnFolder; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/GUI/UnoDialogSample.java b/odk/examples/DevelopersGuide/GUI/UnoDialogSample.java new file mode 100644 index 000000000..c49dbfd77 --- /dev/null +++ b/odk/examples/DevelopersGuide/GUI/UnoDialogSample.java @@ -0,0 +1,1373 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.awt.ActionEvent; +import com.sun.star.awt.AdjustmentEvent; +import com.sun.star.awt.AdjustmentType; +import com.sun.star.awt.FocusChangeReason; +import com.sun.star.awt.FocusEvent; +import com.sun.star.awt.ItemEvent; +import com.sun.star.awt.KeyEvent; +import com.sun.star.awt.MouseEvent; +import com.sun.star.awt.PushButtonType; +import com.sun.star.awt.SpinEvent; +import com.sun.star.awt.TextEvent; +import com.sun.star.awt.XActionListener; +import com.sun.star.awt.XAdjustmentListener; +import com.sun.star.awt.XButton; +import com.sun.star.awt.XCheckBox; +import com.sun.star.awt.XComboBox; +import com.sun.star.awt.XControl; +import com.sun.star.awt.XControlContainer; +import com.sun.star.awt.XControlModel; +import com.sun.star.awt.XDialog; +import com.sun.star.awt.XFixedText; +import com.sun.star.awt.XFocusListener; +import com.sun.star.awt.XItemEventBroadcaster; +import com.sun.star.awt.XItemListener; +import com.sun.star.awt.XKeyListener; +import com.sun.star.awt.XListBox; +import com.sun.star.awt.XMouseListener; +import com.sun.star.awt.XPointer; +import com.sun.star.awt.XReschedule; +import com.sun.star.awt.XScrollBar; +import com.sun.star.awt.XSpinField; +import com.sun.star.awt.XSpinListener; +import com.sun.star.awt.XTextComponent; +import com.sun.star.awt.XTextListener; +import com.sun.star.awt.XToolkit; +import com.sun.star.awt.XTopWindow; +import com.sun.star.awt.XWindow; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.beans.XMultiPropertySet; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XIndexContainer; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNameContainer; +import com.sun.star.frame.XDesktop; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.XModel; +import com.sun.star.lang.EventObject; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; +import com.sun.star.ucb.XFileIdentifierConverter; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.util.XNumberFormats; +import com.sun.star.util.XNumberFormatsSupplier; +import com.sun.star.util.Date; +import com.sun.star.util.Time; +import com.sun.star.util.thePathSettings; + + +// Suggestion: hand the position and width over as parameters + +public class UnoDialogSample implements XTextListener, XSpinListener, XActionListener, XFocusListener, XMouseListener, XItemListener, XAdjustmentListener, XKeyListener { + protected XComponentContext m_xContext = null; + protected com.sun.star.lang.XMultiComponentFactory m_xMCF; + protected XMultiServiceFactory m_xMSFDialogModel; + private XModel m_xModel; + protected XNameContainer m_xDlgModelNameContainer; + protected XControlContainer m_xDlgContainer; +// protected XNameAccess m_xDlgModelNameAccess; + protected XControl m_xDialogControl; + protected XDialog xDialog; + + protected XWindowPeer m_xWindowPeer = null; + + protected XFrame m_xFrame = null; + protected XComponent m_xComponent = null; + + + /** + * Creates a new instance of UnoDialogSample + */ + public UnoDialogSample(XComponentContext _xContext, XMultiComponentFactory _xMCF) { + m_xContext = _xContext; + m_xMCF = _xMCF; + createDialog(m_xMCF); + } + + + public static void main(String args[]) { + UnoDialogSample oUnoDialogSample = null; + + try { + XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if(xContext != null ) + System.out.println("Connected to a running office ..."); + XMultiComponentFactory xMCF = xContext.getServiceManager(); + oUnoDialogSample = new UnoDialogSample(xContext, xMCF); + oUnoDialogSample.initialize( new String[] {"Height", "Moveable", "Name","PositionX","PositionY", "Step", "TabIndex","Title","Width"}, + new Object[] { Integer.valueOf(380), Boolean.TRUE, "MyTestDialog", Integer.valueOf(102),Integer.valueOf(41), Integer.valueOf(0), Short.valueOf((short) 0), "OpenOffice", Integer.valueOf(380)}); + Object oFTHeaderModel = oUnoDialogSample.m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel"); + XMultiPropertySet xFTHeaderModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oFTHeaderModel); + xFTHeaderModelMPSet.setPropertyValues( + new String[] {"Height", "Label", "Name", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(8), "This code-sample demonstrates how to create various controls in a dialog", "HeaderLabel", Integer.valueOf(106), Integer.valueOf(6), Integer.valueOf(300)}); + // add the model to the NameContainer of the dialog model + oUnoDialogSample.m_xDlgModelNameContainer.insertByName("Headerlabel", oFTHeaderModel); + oUnoDialogSample.insertFixedText(oUnoDialogSample, 106, 18, 100, 0, "My ~Label"); + oUnoDialogSample.insertCurrencyField(oUnoDialogSample, 106, 30, 60); + oUnoDialogSample.insertProgressBar(106, 44, 100, 100); + oUnoDialogSample.insertHorizontalFixedLine(106, 58, 100, "My FixedLine"); + oUnoDialogSample.insertEditField(oUnoDialogSample, oUnoDialogSample, 106, 72, 60); + oUnoDialogSample.insertTimeField(106, 96, 50, new Time(0,(short)0,(short)0,(short)10,false), new Time((short)0,(short)0,(short)0,(short)0,false), new Time((short)0,(short)0,(short)0,(short)17,false)); + oUnoDialogSample.insertDateField(oUnoDialogSample, 166, 96, 50); + oUnoDialogSample.insertGroupBox(102, 124, 70, 100); + oUnoDialogSample.insertPatternField(106, 136, 50); + oUnoDialogSample.insertNumericField(106, 152, 50, 0.0, 1000.0, 500.0, 100.0, (short) 1); + oUnoDialogSample.insertCheckBox(oUnoDialogSample, 106, 168, 150); + oUnoDialogSample.insertRadioButtonGroup((short) 50, 130, 200, 150); + oUnoDialogSample.insertListBox(106, 230, 50, 0, new String[]{"First Item", "Second Item"}); + oUnoDialogSample.insertComboBox(106, 250, 50); + oUnoDialogSample.insertFormattedField(oUnoDialogSample, 106, 270, 100); + oUnoDialogSample.insertVerticalScrollBar(oUnoDialogSample, 230, 230, 52); + oUnoDialogSample.insertFileControl(oUnoDialogSample, 106, 290, 200 ); + oUnoDialogSample.insertButton(oUnoDialogSample, 106, 320, 50, "~Close dialog", (short) PushButtonType.OK_value); + oUnoDialogSample.createWindowPeer(); + oUnoDialogSample.addRoadmap(); + oUnoDialogSample.insertRoadmapItem(0, true, "Introduction", 1); + oUnoDialogSample.insertRoadmapItem(1, true, "Documents", 2); + oUnoDialogSample.xDialog = UnoRuntime.queryInterface(XDialog.class, oUnoDialogSample.m_xDialogControl); + oUnoDialogSample.executeDialog(); + }catch( Exception e ) { + System.err.println( e + e.getMessage()); + e.printStackTrace(); + } finally{ + //make sure always to dispose the component and free the memory! + if (oUnoDialogSample != null){ + if (oUnoDialogSample.m_xComponent != null){ + oUnoDialogSample.m_xComponent.dispose(); + } + } + } + + System.exit( 0 ); + } + + + protected void createDialog(XMultiComponentFactory _xMCF) { + try { + Object oDialogModel = _xMCF.createInstanceWithContext("com.sun.star.awt.UnoControlDialogModel", m_xContext); + + // The XMultiServiceFactory of the dialogmodel is needed to instantiate the controls... + m_xMSFDialogModel = UnoRuntime.queryInterface(XMultiServiceFactory.class, oDialogModel); + + // The named container is used to insert the created controls into... + m_xDlgModelNameContainer = UnoRuntime.queryInterface(XNameContainer.class, oDialogModel); + + // create the dialog... + Object oUnoDialog = _xMCF.createInstanceWithContext("com.sun.star.awt.UnoControlDialog", m_xContext); + m_xDialogControl = UnoRuntime.queryInterface(XControl.class, oUnoDialog); + + // The scope of the control container is public... + m_xDlgContainer = UnoRuntime.queryInterface(XControlContainer.class, oUnoDialog); + + UnoRuntime.queryInterface(XTopWindow.class, m_xDlgContainer); + + // link the dialog and its model... + XControlModel xControlModel = UnoRuntime.queryInterface(XControlModel.class, oDialogModel); + m_xDialogControl.setModel(xControlModel); + } catch (com.sun.star.uno.Exception exception) { + exception.printStackTrace(System.err); + } + } + + + + + + + public short executeDialog() { + if (m_xWindowPeer == null) { + createWindowPeer(); + } + xDialog = UnoRuntime.queryInterface(XDialog.class, m_xDialogControl); + m_xComponent = UnoRuntime.queryInterface(XComponent.class, m_xDialogControl); + return xDialog.execute(); + } + + + + + public XItemListener getRoadmapItemStateChangeListener(){ + return new RoadmapItemStateChangeListener(m_xMSFDialogModel); + } + + + public void initialize(String[] PropertyNames, Object[] PropertyValues) { + try{ + XMultiPropertySet xMultiPropertySet = UnoRuntime.queryInterface(XMultiPropertySet.class, m_xDlgModelNameContainer); + xMultiPropertySet.setPropertyValues(PropertyNames, PropertyValues); + } catch (com.sun.star.uno.Exception ex) { + ex.printStackTrace(System.err); + }} + + + + /** + * create a peer for this + * dialog, using the given + * peer as a parent. + */ + private XWindowPeer createWindowPeer(XWindowPeer _xWindowParentPeer) { + try{ + if (_xWindowParentPeer == null){ + XWindow xWindow = UnoRuntime.queryInterface(XWindow.class, m_xDlgContainer); + xWindow.setVisible(false); + Object tk = m_xMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", m_xContext); + XToolkit xToolkit = UnoRuntime.queryInterface(XToolkit.class, tk); + UnoRuntime.queryInterface(XReschedule.class, xToolkit); + m_xDialogControl.createPeer(xToolkit, _xWindowParentPeer); + m_xWindowPeer = m_xDialogControl.getPeer(); + return m_xWindowPeer; + } + } catch (com.sun.star.uno.Exception exception) { + exception.printStackTrace(System.err); + } + return null; + } + + + + + + + /** + * Creates a peer for this + * dialog, using the active OO frame + * as the parent window. + */ + public XWindowPeer createWindowPeer() { + return createWindowPeer(null); + } + + + + + + + + private XFixedText insertFixedText(XMouseListener _xMouseListener, int _nPosX, int _nPosY, int _nWidth, int _nStep, String _sLabel){ + XFixedText xFixedText = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "Label"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oFTModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel"); + XMultiPropertySet xFTModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oFTModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + + xFTModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "PositionX", "PositionY", "Step", "Width"}, + new Object[] { Integer.valueOf(8), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Integer.valueOf(_nStep), Integer.valueOf(_nWidth)}); + // add the model to the NameContainer of the dialog model + m_xDlgModelNameContainer.insertByName(sName, oFTModel); + + // The following property may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + XPropertySet xFTPSet = UnoRuntime.queryInterface(XPropertySet.class, oFTModel); + xFTPSet.setPropertyValue("Label", _sLabel); + + // reference the control by the Name + XControl xFTControl = m_xDlgContainer.getControl(sName); + xFixedText = UnoRuntime.queryInterface(XFixedText.class, xFTControl); + XWindow xWindow = UnoRuntime.queryInterface(XWindow.class, xFTControl); + xWindow.addMouseListener(_xMouseListener); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xFixedText; + } + + + private XTextComponent insertCurrencyField(XTextListener _xTextListener, int _nPositionX, int _nPositionY, int _nWidth){ + XTextComponent xTextComponent = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "CurrencyField"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oCFModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlCurrencyFieldModel"); + XMultiPropertySet xCFModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oCFModel); + + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xCFModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(12), sName, Integer.valueOf(_nPositionX), Integer.valueOf(_nPositionY), Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oCFModel); + XPropertySet xCFModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oCFModel); + + // The following properties may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + xCFModelPSet.setPropertyValue("PrependCurrencySymbol", Boolean.TRUE); + xCFModelPSet.setPropertyValue("CurrencySymbol", "$"); + xCFModelPSet.setPropertyValue("Value", new Double(2.93)); + + // add a textlistener that is notified on each change of the controlvalue... + Object oCFControl = m_xDlgContainer.getControl(sName); + xTextComponent = UnoRuntime.queryInterface(XTextComponent.class, oCFControl); + xTextComponent.addTextListener(_xTextListener); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xTextComponent; + } + + + + private XPropertySet insertProgressBar(int _nPosX, int _nPosY, int _nWidth, int _nProgressMax){ + XPropertySet xPBModelPSet = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "ProgressBar"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oPBModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlProgressBarModel"); + + XMultiPropertySet xPBModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oPBModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xPBModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(8), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oPBModel); + xPBModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oPBModel); + + // The following properties may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + xPBModelPSet.setPropertyValue("ProgressValueMin", Integer.valueOf(0)); + xPBModelPSet.setPropertyValue("ProgressValueMax", Integer.valueOf(_nProgressMax)); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xPBModelPSet; + } + + + + public void insertHorizontalFixedLine(int _nPosX, int _nPosY, int _nWidth, String _sLabel){ + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "FixedLine"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oFLModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFixedLineModel"); + XMultiPropertySet xFLModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oFLModel); + + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xFLModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "Orientation", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(8), sName, Integer.valueOf(0), Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oFLModel); + + // The following property may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + XPropertySet xFLPSet = UnoRuntime.queryInterface(XPropertySet.class, oFLModel); + xFLPSet.setPropertyValue("Label", _sLabel); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + } + + + + private void insertGroupBox(int _nPosX, int _nPosY, int _nHeight, int _nWidth){ + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "FrameControl"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oGBModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlGroupBoxModel"); + XMultiPropertySet xGBModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oGBModel); + + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xGBModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(_nHeight), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oGBModel); + + // The following property may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + XPropertySet xGBPSet = UnoRuntime.queryInterface(XPropertySet.class, oGBModel); + xGBPSet.setPropertyValue("Label", "~My GroupBox"); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + } + + + + private XTextComponent insertEditField(XTextListener _xTextListener, XFocusListener _xFocusListener, int _nPosX, int _nPosY, int _nWidth){ + XTextComponent xTextComponent = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "TextField"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oTFModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlEditModel"); + XMultiPropertySet xTFModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oTFModel); + + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xTFModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "PositionX", "PositionY", "Text", "Width"}, + new Object[] { Integer.valueOf(12), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), "MyText", Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oTFModel); + XPropertySet xTFModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oTFModel); + + // The following property may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + xTFModelPSet.setPropertyValue("EchoChar", Short.valueOf((short) '*')); + XControl xTFControl = m_xDlgContainer.getControl(sName); + + // add a textlistener that is notified on each change of the controlvalue... + xTextComponent = UnoRuntime.queryInterface(XTextComponent.class, xTFControl); + XWindow xTFWindow = UnoRuntime.queryInterface(XWindow.class, xTFControl); + xTFWindow.addFocusListener(_xFocusListener); + xTextComponent.addTextListener(_xTextListener); + xTFWindow.addKeyListener(this); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xTextComponent; + } + + private XPropertySet insertTimeField(int _nPosX, int _nPosY, int _nWidth, Time _aTime, Time _aTimeMin, Time _aTimeMax){ + XPropertySet xTFModelPSet = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "TimeField"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oTFModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlTimeFieldModel"); + XMultiPropertySet xTFModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oTFModel); + + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xTFModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "PositionX", "PositionY", "Spin", "Width"}, + new Object[] { Integer.valueOf(12), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Boolean.TRUE, Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oTFModel); + xTFModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oTFModel); + + // The following properties may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + xTFModelPSet.setPropertyValue("TimeFormat", Short.valueOf((short) 5)); + xTFModelPSet.setPropertyValue("TimeMin", _aTimeMin); + xTFModelPSet.setPropertyValue("TimeMax", _aTimeMax); + xTFModelPSet.setPropertyValue("Time", _aTime); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xTFModelPSet; + } + + + + private XPropertySet insertDateField(XSpinListener _xSpinListener, int _nPosX, int _nPosY, int _nWidth){ + XPropertySet xDFModelPSet = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "DateField"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oDFModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlDateFieldModel"); + XMultiPropertySet xDFModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oDFModel); + + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xDFModelMPSet.setPropertyValues( + new String[] {"Dropdown", "Height", "Name", "PositionX", "PositionY", "Width"}, + new Object[] {Boolean.TRUE, Integer.valueOf(12), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oDFModel); + xDFModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oDFModel); + + // The following properties may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + xDFModelPSet.setPropertyValue("DateFormat", Short.valueOf((short) 7)); + xDFModelPSet.setPropertyValue("DateMin", new Date((short)1, (short)4, (short)2007)); + xDFModelPSet.setPropertyValue("DateMax", new Date((short)1, (short)5, (short)2007)); + xDFModelPSet.setPropertyValue("Date", new Date((short)15, (short)4, (short)2000)); + Object oDFControl = m_xDlgContainer.getControl(sName); + + // add a SpinListener that is notified on each change of the controlvalue... + XSpinField xSpinField = UnoRuntime.queryInterface(XSpinField.class, oDFControl); + xSpinField.addSpinListener(_xSpinListener); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xDFModelPSet; + } + + + private XPropertySet insertPatternField(int _nPosX, int _nPosY, int _nWidth){ + XPropertySet xPFModelPSet = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "PatternField"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oPFModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlPatternFieldModel"); + XMultiPropertySet xPFModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oPFModel); + + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xPFModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(12), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oPFModel); + xPFModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oPFModel); + + // The following properties may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + xPFModelPSet.setPropertyValue("LiteralMask", "__.05.2007"); + // Allow only numbers for the first two digits... + xPFModelPSet.setPropertyValue("EditMask", "NNLLLLLLLL"); + // verify the user input immediately... + xPFModelPSet.setPropertyValue("StrictFormat", Boolean.TRUE); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xPFModelPSet; + } + + + private XPropertySet insertNumericField( int _nPosX, int _nPosY, int _nWidth, + double _fValueMin, double _fValueMax, double _fValue, + double _fValueStep, short _nDecimalAccuracy){ + XPropertySet xNFModelPSet = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "NumericField"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oNFModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlNumericFieldModel"); + XMultiPropertySet xNFModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oNFModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xNFModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "PositionX", "PositionY", "Spin", "StrictFormat", "Width"}, + new Object[] { Integer.valueOf(12), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Boolean.TRUE, Boolean.TRUE, Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oNFModel); + xNFModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oNFModel); + // The following properties may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + xNFModelPSet.setPropertyValue("ValueMin", new Double(_fValueMin)); + xNFModelPSet.setPropertyValue("ValueMax", new Double(_fValueMax)); + xNFModelPSet.setPropertyValue("Value", new Double(_fValue)); + xNFModelPSet.setPropertyValue("ValueStep", new Double(_fValueStep)); + xNFModelPSet.setPropertyValue("ShowThousandsSeparator", Boolean.TRUE); + xNFModelPSet.setPropertyValue("DecimalAccuracy", Short.valueOf(_nDecimalAccuracy)); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xNFModelPSet; + } + + + + private XPropertySet insertVerticalScrollBar(XAdjustmentListener _xAdjustmentListener, int _nPosX, int _nPosY, int _nHeight){ + XPropertySet xSBModelPSet = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "ScrollBar"); + + Integer NOrientation = Integer.valueOf(com.sun.star.awt.ScrollBarOrientation.VERTICAL); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oSBModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlScrollBarModel"); + XMultiPropertySet xSBModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oSBModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xSBModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "Orientation", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(_nHeight), sName, NOrientation, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Integer.valueOf(8)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oSBModel); + + xSBModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oSBModel); + // The following properties may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + xSBModelPSet.setPropertyValue("ScrollValueMin", Integer.valueOf(0)); + xSBModelPSet.setPropertyValue("ScrollValueMax", Integer.valueOf(100)); + xSBModelPSet.setPropertyValue("ScrollValue", Integer.valueOf(5)); + xSBModelPSet.setPropertyValue("LineIncrement", Integer.valueOf(2)); + xSBModelPSet.setPropertyValue("BlockIncrement", Integer.valueOf(10)); + + // Add an Adjustment that will listen to changes of the scrollbar... + XControl xSBControl = m_xDlgContainer.getControl(sName); + XScrollBar xScrollBar = UnoRuntime.queryInterface(XScrollBar.class, xSBControl); + xScrollBar.addAdjustmentListener(_xAdjustmentListener); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xSBModelPSet; + } + + + /** makes a String unique by appending a numerical suffix + * @param _xElementContainer the com.sun.star.container.XNameAccess container + * that the new Element is going to be inserted to + * @param _sElementName the StemName of the Element + */ + public static String createUniqueName(XNameAccess _xElementContainer, String _sElementName) { + boolean bElementexists = true; + int i = 1; + String BaseName = _sElementName; + while (bElementexists) { + bElementexists = _xElementContainer.hasByName(_sElementName); + if (bElementexists) { + i += 1; + _sElementName = BaseName + Integer.toString(i); + } + } + return _sElementName; + } + + + private XCheckBox insertCheckBox(XItemListener _xItemListener, int _nPosX, int _nPosY, int _nWidth){ + XCheckBox xCheckBox = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "CheckBox"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oCBModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlCheckBoxModel"); + + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + XMultiPropertySet xCBMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oCBModel); + xCBMPSet.setPropertyValues( + new String[] {"Height", "Label", "Name", "PositionX", "PositionY", "Width" } , + new Object[] {Integer.valueOf(8), "~Include page number", sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Integer.valueOf(_nWidth)}); + + // The following property may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + XPropertySet xCBModelPSet = UnoRuntime.queryInterface(XPropertySet.class, xCBMPSet); + xCBModelPSet.setPropertyValue("TriState", Boolean.TRUE); + xCBModelPSet.setPropertyValue("State", Short.valueOf((short) 1)); + + // add the model to the NameContainer of the dialog model + m_xDlgModelNameContainer.insertByName(sName, oCBModel); + XControl xCBControl = m_xDlgContainer.getControl(sName); + xCheckBox = UnoRuntime.queryInterface(XCheckBox.class, xCBControl); + // An ActionListener will be notified on the activation of the button... + xCheckBox.addItemListener(_xItemListener); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xCheckBox; + } + + + + + private void insertRadioButtonGroup(short _nTabIndex, int _nPosX, int _nPosY, int _nWidth){ + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "OptionButton"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oRBModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlRadioButtonModel"); + XMultiPropertySet xRBMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oRBModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xRBMPSet.setPropertyValues( + new String[] {"Height", "Label", "Name", "PositionX", "PositionY", "State", "TabIndex", "Width" } , + new Object[] {Integer.valueOf(8), "~First Option", sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Short.valueOf((short) 1), Short.valueOf(_nTabIndex++),Integer.valueOf(_nWidth)}); + // add the model to the NameContainer of the dialog model + m_xDlgModelNameContainer.insertByName(sName, oRBModel); + + // create a unique name by means of an own implementation... + sName = createUniqueName(m_xDlgModelNameContainer, "OptionButton"); + + oRBModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlRadioButtonModel"); + xRBMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oRBModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xRBMPSet.setPropertyValues( + new String[] {"Height", "Label", "Name", "PositionX", "PositionY", "TabIndex", "Width" } , + new Object[] {Integer.valueOf(8), "~Second Option", sName, Integer.valueOf(130), Integer.valueOf(214), Short.valueOf(_nTabIndex), Integer.valueOf(150)}); + // add the model to the NameContainer of the dialog model + m_xDlgModelNameContainer.insertByName(sName, oRBModel); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + } + + + private XListBox insertListBox(int _nPosX, int _nPosY, int _nWidth, int _nStep, String[] _sStringItemList){ + XListBox xListBox = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "ListBox"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oListBoxModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlListBoxModel"); + XMultiPropertySet xLBModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oListBoxModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xLBModelMPSet.setPropertyValues( + new String[] {"Dropdown", "Height", "Name", "PositionX", "PositionY", "Step", "StringItemList", "Width" } , + new Object[] {Boolean.TRUE, Integer.valueOf(12), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Integer.valueOf(_nStep), _sStringItemList, Integer.valueOf(_nWidth)}); + // The following property may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + XPropertySet xLBModelPSet = UnoRuntime.queryInterface(XPropertySet.class, xLBModelMPSet); + xLBModelPSet.setPropertyValue("MultiSelection", Boolean.TRUE); + short[] nSelItems = new short[] {(short) 1, (short) 3}; + xLBModelPSet.setPropertyValue("SelectedItems", nSelItems); + // add the model to the NameContainer of the dialog model + m_xDlgModelNameContainer.insertByName(sName, xLBModelMPSet); + XControl xControl = m_xDlgContainer.getControl(sName); + // retrieve a ListBox that is more convenient to work with than the Model of the ListBox... + xListBox = UnoRuntime.queryInterface(XListBox.class, xControl); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xListBox; + } + + + private XComboBox insertComboBox(int _nPosX, int _nPosY, int _nWidth){ + XComboBox xComboBox = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "ComboBox"); + + String[] sStringItemList = new String[]{"First Entry", "Second Entry", "Third Entry", "Fourth Entry"}; + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oComboBoxModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlComboBoxModel"); + XMultiPropertySet xCbBModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oComboBoxModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xCbBModelMPSet.setPropertyValues( + new String[] {"Dropdown", "Height", "Name", "PositionX", "PositionY", "StringItemList", "Width" } , + new Object[] {Boolean.TRUE, Integer.valueOf(12), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), sStringItemList, Integer.valueOf(_nWidth)}); + + // The following property may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + XPropertySet xCbBModelPSet = UnoRuntime.queryInterface(XPropertySet.class, xCbBModelMPSet); + xCbBModelPSet.setPropertyValue("MaxTextLen", Short.valueOf((short) 10)); + xCbBModelPSet.setPropertyValue("ReadOnly", Boolean.FALSE); + + // add the model to the NameContainer of the dialog model + m_xDlgModelNameContainer.insertByName(sName, xCbBModelMPSet); + XControl xControl = m_xDlgContainer.getControl(sName); + + // retrieve a ListBox that is more convenient to work with than the Model of the ListBox... + xComboBox = UnoRuntime.queryInterface(XComboBox.class, xControl); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xComboBox; + } + + + + private XPropertySet insertFormattedField(XSpinListener _xSpinListener, int _nPosX, int _nPosY, int _nWidth){ + XPropertySet xFFModelPSet = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "FormattedField"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oFFModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFormattedFieldModel"); + XMultiPropertySet xFFModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oFFModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xFFModelMPSet.setPropertyValues( + new String[] {"EffectiveValue", "Height", "Name", "PositionX", "PositionY", "StrictFormat", "Spin", "Width"}, + new Object[] { new Double(12348), Integer.valueOf(12), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Boolean.TRUE, Boolean.TRUE, Integer.valueOf(_nWidth)}); + + xFFModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oFFModel); + // to define a numberformat you always need a locale... + com.sun.star.lang.Locale aLocale = new com.sun.star.lang.Locale(); + aLocale.Country = "US"; + aLocale.Language = "en"; + // this Format is only compliant to the english locale! + String sFormatString = "NNNNMMMM DD, YYYY"; + + // a NumberFormatsSupplier has to be created first "in the open countryside"... + Object oNumberFormatsSupplier = m_xMCF.createInstanceWithContext("com.sun.star.util.NumberFormatsSupplier", m_xContext); + XNumberFormatsSupplier xNumberFormatsSupplier = UnoRuntime.queryInterface(XNumberFormatsSupplier.class, oNumberFormatsSupplier); + XNumberFormats xNumberFormats = xNumberFormatsSupplier.getNumberFormats(); + // is the numberformat already defined? + int nFormatKey = xNumberFormats.queryKey(sFormatString, aLocale, true); + if (nFormatKey == -1){ + // if not then add it to the NumberFormatsSupplier + nFormatKey = xNumberFormats.addNew(sFormatString, aLocale); + } + + // The following property may also be set with XMultiPropertySet but we + // use the XPropertySet interface merely for reasons of demonstration + xFFModelPSet.setPropertyValue("FormatsSupplier", xNumberFormatsSupplier); + xFFModelPSet.setPropertyValue("FormatKey", Integer.valueOf(nFormatKey)); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oFFModel); + + // finally we add a Spin-Listener to the control + XControl xFFControl = m_xDlgContainer.getControl(sName); + // add a SpinListener that is notified on each change of the controlvalue... + XSpinField xSpinField = UnoRuntime.queryInterface(XSpinField.class, xFFControl); + xSpinField.addSpinListener(_xSpinListener); + + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xFFModelPSet; + } + + + + + private XTextComponent insertFileControl(XTextListener _xTextListener, int _nPosX, int _nPosY, int _nWidth){ + XTextComponent xTextComponent = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "FileControl"); + + // retrieve the configured Work path... + Object oPathSettings = thePathSettings.get(m_xContext); + XPropertySet xPropertySet = com.sun.star.uno.UnoRuntime.queryInterface(XPropertySet.class, oPathSettings); + String sWorkUrl = (String) xPropertySet.getPropertyValue("Work"); + + // convert the Url to a system path that is "human readable"... + Object oFCProvider = m_xMCF.createInstanceWithContext("com.sun.star.ucb.FileContentProvider", m_xContext); + XFileIdentifierConverter xFileIdentifierConverter = UnoRuntime.queryInterface(XFileIdentifierConverter.class, oFCProvider); + String sSystemWorkPath = xFileIdentifierConverter.getSystemPathFromFileURL(sWorkUrl); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oFCModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFileControlModel"); + + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + XMultiPropertySet xFCModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oFCModel); + xFCModelMPSet.setPropertyValues( + new String[] {"Height", "Name", "PositionX", "PositionY", "Text", "Width"}, + new Object[] { Integer.valueOf(14), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), sSystemWorkPath, Integer.valueOf(_nWidth)}); + + // The controlmodel is not really available until inserted to the Dialog container + m_xDlgModelNameContainer.insertByName(sName, oFCModel); + XPropertySet xFCModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oFCModel); + + // add a textlistener that is notified on each change of the controlvalue... + XControl xFCControl = m_xDlgContainer.getControl(sName); + xTextComponent = UnoRuntime.queryInterface(XTextComponent.class, xFCControl); + XWindow xFCWindow = UnoRuntime.queryInterface(XWindow.class, xFCControl); + xTextComponent.addTextListener(_xTextListener); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xTextComponent; + } + + + public XButton insertButton(XActionListener _xActionListener, int _nPosX, int _nPosY, int _nWidth, String _sLabel, short _nPushButtonType){ + XButton xButton = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "CommandButton"); + + // create a controlmodel at the multiservicefactory of the dialog model... + Object oButtonModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlButtonModel"); + XMultiPropertySet xButtonMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oButtonModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xButtonMPSet.setPropertyValues( + new String[] {"Height", "Label", "Name", "PositionX", "PositionY", "PushButtonType", "Width" } , + new Object[] {Integer.valueOf(14), _sLabel, sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Short.valueOf(_nPushButtonType), Integer.valueOf(_nWidth)}); + + // add the model to the NameContainer of the dialog model + m_xDlgModelNameContainer.insertByName(sName, oButtonModel); + XControl xButtonControl = m_xDlgContainer.getControl(sName); + xButton = UnoRuntime.queryInterface(XButton.class, xButtonControl); + // An ActionListener will be notified on the activation of the button... + xButton.addActionListener(_xActionListener); + } catch (com.sun.star.uno.Exception ex) { + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + return xButton; + } + + + + public XFrame getCurrentFrame(){ + XFrame xRetFrame = null; + try { + Object oDesktop = m_xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", m_xContext); + XDesktop xDesktop = UnoRuntime.queryInterface(XDesktop.class, oDesktop); + xRetFrame = xDesktop.getCurrentFrame(); + } catch (com.sun.star.uno.Exception ex) { + ex.printStackTrace(); + } + return xRetFrame; + } + + + public void textChanged(TextEvent textEvent) { + try { + // get the control that has fired the event, + XControl xControl = UnoRuntime.queryInterface(XControl.class, textEvent.Source); + XControlModel xControlModel = xControl.getModel(); + XPropertySet xPSet = UnoRuntime.queryInterface(XPropertySet.class, xControlModel); + String sName = (String) xPSet.getPropertyValue("Name"); + // just in case the listener has been added to several controls, + // we make sure we refer to the right one + if (sName.equals("TextField1")){ + String sText = (String) xPSet.getPropertyValue("Text"); + System.out.println(sText); + // insert your code here to validate the text of the control... + } + }catch (com.sun.star.uno.Exception ex){ + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + } + + + + public void up(SpinEvent spinEvent) { + try { + // get the control that has fired the event, + XControl xControl = UnoRuntime.queryInterface(XControl.class, spinEvent.Source); + XControlModel xControlModel = xControl.getModel(); + XPropertySet xPSet = UnoRuntime.queryInterface(XPropertySet.class, xControlModel); + String sName = (String) xPSet.getPropertyValue("Name"); + // just in case the listener has been added to several controls, + // we make sure we refer to the right one + if (sName.equals("FormattedField1")){ + double fvalue = AnyConverter.toDouble(xPSet.getPropertyValue("EffectiveValue")); + System.out.println("Controlvalue: " + fvalue); + // insert your code here to validate the value of the control... + } + }catch (com.sun.star.uno.Exception ex){ + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + } + + + public void down(SpinEvent spinEvent) { + } + + public void last(SpinEvent spinEvent) { + } + + public void first(SpinEvent spinEvent) { + } + + public void disposing(EventObject rEventObject) { + } + + + public void actionPerformed(ActionEvent rEvent) { + try{ + // get the control that has fired the event, + XControl xControl = UnoRuntime.queryInterface(XControl.class, rEvent.Source); + XControlModel xControlModel = xControl.getModel(); + XPropertySet xPSet = UnoRuntime.queryInterface(XPropertySet.class, xControlModel); + String sName = (String) xPSet.getPropertyValue("Name"); + // just in case the listener has been added to several controls, + // we make sure we refer to the right one + if (sName.equals("CommandButton1")) { + + } + }catch (com.sun.star.uno.Exception ex){ + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + } + + + public void focusLost(FocusEvent _focusEvent) { + short nFocusFlags = _focusEvent.FocusFlags; + int nFocusChangeReason = nFocusFlags & FocusChangeReason.TAB; + if (nFocusChangeReason == FocusChangeReason.TAB) { + // get the window of the Window that has gained the Focus... + // Note that the xWindow is just a representation of the controlwindow + // but not of the control itself + XWindow xWindow = UnoRuntime.queryInterface(XWindow.class, _focusEvent.NextFocus); + } + } + + + public void focusGained(FocusEvent focusEvent) { + } + + public void mouseReleased(MouseEvent mouseEvent) { + } + + public void mousePressed(MouseEvent mouseEvent) { + } + + public void mouseExited(MouseEvent mouseEvent) { + } + + public void mouseEntered(MouseEvent _mouseEvent) { + try { + // retrieve the control that the event has been invoked at... + XControl xControl = UnoRuntime.queryInterface(XControl.class, _mouseEvent.Source); + Object tk = m_xMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", m_xContext); + XToolkit xToolkit = UnoRuntime.queryInterface(XToolkit.class, tk); + // create the peer of the control by passing the windowpeer of the parent + // in this case the windowpeer of the control + xControl.createPeer(xToolkit, m_xWindowPeer); + // create a pointer object "in the open countryside" and set the type accordingly... + Object oPointer = this.m_xMCF.createInstanceWithContext("com.sun.star.awt.Pointer", this.m_xContext); + XPointer xPointer = UnoRuntime.queryInterface(XPointer.class, oPointer); + xPointer.setType(com.sun.star.awt.SystemPointer.REFHAND); + // finally set the created pointer at the windowpeer of the control + xControl.getPeer().setPointer(xPointer); + } catch (com.sun.star.uno.Exception ex) { + throw new java.lang.RuntimeException("cannot happen...", ex); + } + } + + + + public void itemStateChanged(ItemEvent itemEvent) { + try{ + // retrieve the control that the event has been invoked at... + XCheckBox xCheckBox = UnoRuntime.queryInterface(XCheckBox.class, itemEvent.Source); + // retrieve the control that we want to disable or enable + XControl xControl = UnoRuntime.queryInterface(XControl.class, m_xDlgContainer.getControl("CommandButton1")); + XPropertySet xModelPropertySet = UnoRuntime.queryInterface(XPropertySet.class, xControl.getModel()); + short nState = xCheckBox.getState(); + boolean bdoEnable = true; + switch (nState){ + case 1: // checked + bdoEnable = true; + break; + case 0: // not checked + case 2: // don't know + bdoEnable = false; + break; + } + // Alternatively we could have done it also this way: + // bdoEnable = (nState == 1); + xModelPropertySet.setPropertyValue("Enabled", Boolean.valueOf(bdoEnable)); + }catch (com.sun.star.uno.Exception ex){ + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.beans.PropertyVetoException + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + } + + + public void adjustmentValueChanged(AdjustmentEvent _adjustmentEvent) { + switch (_adjustmentEvent.Type.getValue()){ + case AdjustmentType.ADJUST_ABS_value: + System.out.println( "The event has been triggered by dragging the thumb..." ); + break; + case AdjustmentType.ADJUST_LINE_value: + System.out.println( "The event has been triggered by a single line move.." ); + break; + case AdjustmentType.ADJUST_PAGE_value: + System.out.println( "The event has been triggered by a block move..." ); + break; + } + System.out.println( "The value of the scrollbar is: " + _adjustmentEvent.Value); + } + + + +// Globally available object variables of the roadmapmodel + XPropertySet m_xRMPSet; + private XSingleServiceFactory m_xSSFRoadmap; + private XIndexContainer m_xRMIndexCont; + + public void addRoadmap() { + XPropertySet xDialogModelPropertySet = null; + try { + // create a unique name by means of an own implementation... + String sRoadmapName = createUniqueName(m_xDlgModelNameContainer, "Roadmap"); + + xDialogModelPropertySet = UnoRuntime.queryInterface(XPropertySet.class, m_xMSFDialogModel); + // Similar to the office assistants the roadmap is adjusted to the height of the dialog + // where a certain space is left at the bottom for the buttons... + int nDialogHeight = ((Integer) xDialogModelPropertySet.getPropertyValue("Height")).intValue(); + + // instantiate the roadmapmodel... + Object oRoadmapModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlRoadmapModel"); + + // define the properties of the roadmapmodel + XMultiPropertySet xRMMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oRoadmapModel); + xRMMPSet.setPropertyValues( new String[] {"Complete", "Height", "Name", "PositionX", "PositionY", "Text", "Width" }, + new Object[] {Boolean.FALSE, Integer.valueOf(nDialogHeight - 26), sRoadmapName, Integer.valueOf(0), Integer.valueOf(0), "Steps", Integer.valueOf(85)}); + m_xRMPSet = UnoRuntime.queryInterface(XPropertySet.class, oRoadmapModel); + + // add the roadmapmodel to the dialog container... + m_xDlgModelNameContainer.insertByName(sRoadmapName, oRoadmapModel); + + // the roadmapmodel is a SingleServiceFactory to instantiate the roadmapitems... + m_xSSFRoadmap = UnoRuntime.queryInterface(XSingleServiceFactory.class, oRoadmapModel); + m_xRMIndexCont = UnoRuntime.queryInterface(XIndexContainer.class, oRoadmapModel); + + // add the itemlistener to the control... + XControl xRMControl = this.m_xDlgContainer.getControl(sRoadmapName); + XItemEventBroadcaster xRMBroadcaster = UnoRuntime.queryInterface(XItemEventBroadcaster.class, xRMControl); + xRMBroadcaster.addItemListener( getRoadmapItemStateChangeListener() ); + } catch (java.lang.Exception jexception) { + jexception.printStackTrace(System.err); + } + } + + /* + * To fully understand the example one has to be aware that the passed ???Index??? parameter + * refers to the position of the roadmap item in the roadmapmodel container + * whereas the variable ???_ID??? directly references to a certain step of dialog. + */ + public void insertRoadmapItem(int Index, boolean _bEnabled, String _sLabel, int _ID) { + try { + // a roadmap is a SingleServiceFactory that can only create roadmapitems that are the only possible + // element types of the container + Object oRoadmapItem = m_xSSFRoadmap.createInstance(); + XPropertySet xRMItemPSet = UnoRuntime.queryInterface(XPropertySet.class, oRoadmapItem); + xRMItemPSet.setPropertyValue("Label", _sLabel); + // sometimes steps are supposed to be set disabled depending on the program logic... + xRMItemPSet.setPropertyValue("Enabled", Boolean.valueOf(_bEnabled)); + // in this context the "ID" is meant to refer to a step of the dialog + xRMItemPSet.setPropertyValue("ID", Integer.valueOf(_ID)); + m_xRMIndexCont.insertByIndex(Index, oRoadmapItem); + } catch (com.sun.star.uno.Exception exception) { + exception.printStackTrace(System.err); + } + } + + + public void keyReleased(KeyEvent keyEvent) { + } + + public void keyPressed(KeyEvent keyEvent) { + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/GUI/UnoDialogSample2.java b/odk/examples/DevelopersGuide/GUI/UnoDialogSample2.java new file mode 100644 index 000000000..3e38886a1 --- /dev/null +++ b/odk/examples/DevelopersGuide/GUI/UnoDialogSample2.java @@ -0,0 +1,263 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.awt.PushButtonType; +import com.sun.star.awt.XDialog; +import com.sun.star.awt.XListBox; +import com.sun.star.beans.MethodConcept; +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XIntrospection; +import com.sun.star.beans.XIntrospectionAccess; +import com.sun.star.beans.XMultiPropertySet; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XTypeProvider; +import com.sun.star.reflection.XIdlMethod; +import com.sun.star.uno.Type; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + +public class UnoDialogSample2 extends UnoDialogSample { + XIntrospectionAccess m_xIntrospectionAccess = null; + Object m_oUnoObject = null; + // define some constants used to set positions and sizes + // of controls. For further information see + // http://ui.openoffice.org/knowledge/DialogSpecificationandGuidelines.odt + static final int nFixedTextHeight = 8; + static final int nControlMargin = 6; + static final int nDialogWidth = 250; + static final int nDialogHeight = 140; + // the default roadmap width == 80 MAPs + static final int nRoadmapWidth = 80; + static final int nButtonHeight = 14; + static final int nButtonWidth = 50; + + + public UnoDialogSample2(XComponentContext _xContext, XMultiComponentFactory _xMCF, Object _oUnoObject) { + super(_xContext, _xMCF); + try { + m_oUnoObject = _oUnoObject; + Object o = m_xMCF.createInstanceWithContext("com.sun.star.beans.Introspection", m_xContext); + XIntrospection xIntrospection = UnoRuntime.queryInterface(XIntrospection.class, o ); + // the variable m_xIntrospectionAccess offers functionality to access all methods and properties + // of a variable + m_xIntrospectionAccess = xIntrospection.inspect(_oUnoObject); + } catch (com.sun.star.uno.Exception ex) { + ex.printStackTrace(); + } + } + + public static void main(String args[]) { + UnoDialogSample2 oUnoDialogSample2 = null; + try { + XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if(xContext != null ) + System.out.println("Connected to a running office ..."); + XMultiComponentFactory xMCF = xContext.getServiceManager(); + PropertyValue[] aPropertyValues = new PropertyValue[]{}; + // create an arbitrary Uno-Object - in this case an empty writer document... + Object oDesktop =xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext); + XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, oDesktop); + Object oUnoObject = xComponentLoader.loadComponentFromURL("private:factory/swriter", "_default", 0, aPropertyValues); + + // define some coordinates where to position the controls + final int nButtonPosX = (nDialogWidth/2) - (nButtonWidth/2); + final int nButtonPosY = nDialogHeight - nButtonHeight - nControlMargin; + final int nControlPosX = nRoadmapWidth + 2*nControlMargin; + final int nControlWidth = nDialogWidth - 3*nControlMargin - nRoadmapWidth; + final int nListBoxHeight = nDialogHeight - 4*nControlMargin - nButtonHeight; + oUnoDialogSample2 = new UnoDialogSample2(xContext, xMCF, oUnoObject); + oUnoDialogSample2.initialize( new String[] {"Height", "Moveable", "Name","PositionX","PositionY", "Step", "TabIndex","Title","Width"}, + new Object[] { Integer.valueOf(nDialogHeight), Boolean.TRUE, "Dialog1", Integer.valueOf(102),Integer.valueOf(41), Integer.valueOf(1), Short.valueOf((short) 0), "Inspect a Uno-Object", Integer.valueOf(nDialogWidth)}); + String sIntroLabel = "This Dialog lists information about a given Uno-Object.\nIt offers a view to inspect all supported servicenames, exported interfaces, methods and properties."; + oUnoDialogSample2.insertMultiLineFixedText(nControlPosX, 27, nControlWidth, 4, 1, sIntroLabel); + // get the data from the UNO object... + String[] sSupportedServiceNames = oUnoDialogSample2.getSupportedServiceNames(); + String[] sInterfaceNames = oUnoDialogSample2.getExportedInterfaceNames(); + String[] sMethodNames = oUnoDialogSample2.getMethodNames(); + String[] sPropertyNames = oUnoDialogSample2.getPropertyNames(); + // add controls to the dialog... + oUnoDialogSample2.insertListBox(nControlPosX, nControlMargin, nListBoxHeight, nControlWidth, 2, sSupportedServiceNames); + oUnoDialogSample2.insertListBox(nControlPosX, nControlMargin, nListBoxHeight, nControlWidth, 3, sInterfaceNames); + oUnoDialogSample2.insertListBox(nControlPosX, nControlMargin, nListBoxHeight, nControlWidth, 4, sMethodNames); + oUnoDialogSample2.insertListBox(nControlPosX, nControlMargin, nListBoxHeight, nControlWidth, 5, sPropertyNames); + oUnoDialogSample2.insertButton(oUnoDialogSample2, nButtonPosX, nButtonPosY, nButtonWidth, "~Close", (short) PushButtonType.OK_value); + oUnoDialogSample2.insertHorizontalFixedLine(0, nButtonPosY - nControlMargin - 4, nDialogWidth, ""); + // create the windowpeer; + // it must be kept in mind that it must be created after the insertion of the controls + // (see http://qa.openoffice.org/issues/show_bug.cgi?id=75129) + oUnoDialogSample2.createWindowPeer(); + // add the roadmap control. Note that the roadmap may not be created before the windowpeer of the dialog exists + // (see http://qa.openoffice.org/issues/show_bug.cgi?id=67369) + oUnoDialogSample2.addRoadmap(); + oUnoDialogSample2.insertRoadmapItem(0, true, "Introduction", 1); + oUnoDialogSample2.insertRoadmapItem(1, true, "Supported Services", 2); + oUnoDialogSample2.insertRoadmapItem(2, true, "Interfaces", 3); + oUnoDialogSample2.insertRoadmapItem(3, true, "Methods", 4); + oUnoDialogSample2.insertRoadmapItem(4, true, "Properties", 5); + oUnoDialogSample2.m_xRMPSet.setPropertyValue("CurrentItemID", Short.valueOf((short) 1)); + oUnoDialogSample2.m_xRMPSet.setPropertyValue("Complete", Boolean.TRUE); + oUnoDialogSample2.xDialog = UnoRuntime.queryInterface(XDialog.class, oUnoDialogSample2.m_xDialogControl); + oUnoDialogSample2.xDialog.execute(); + }catch( Exception ex ) { + ex.printStackTrace(System.err); + } + finally{ + //make sure always to dispose the component and free the memory! + if (oUnoDialogSample2 != null){ + if (oUnoDialogSample2.m_xComponent != null){ + oUnoDialogSample2.m_xComponent.dispose(); + } + } + } + + System.exit( 0 ); + } + + + public String[] getMethodNames() { + String[] sMethodNames = new String[]{}; + try { + XIdlMethod[] xIdlMethods = m_xIntrospectionAccess.getMethods(MethodConcept.ALL); + sMethodNames = new String[xIdlMethods.length]; + for (int i = 0; i < xIdlMethods.length; i++){ + sMethodNames[i] = xIdlMethods[i].getName(); + } + } + catch( Exception e ) { + System.err.println( e ); + } + return sMethodNames; + } + + // returns the names of all supported servicenames of a UNO object + public String[] getSupportedServiceNames() { + String[] sSupportedServiceNames = new String[]{}; + // If the Uno-Object supports "com.sun.star.lang.XServiceInfo" + // this will give access to all supported servicenames + XServiceInfo xServiceInfo = UnoRuntime.queryInterface( XServiceInfo.class, m_oUnoObject); + if ( xServiceInfo != null ) { + sSupportedServiceNames = xServiceInfo.getSupportedServiceNames(); + } + return sSupportedServiceNames; + } + + // returns the names of all properties of a UNO object + protected String[] getPropertyNames() { + String[] sPropertyNames = new String[]{}; + try { + Property[] aProperties = m_xIntrospectionAccess.getProperties(com.sun.star.beans.PropertyConcept.ATTRIBUTES + com.sun.star.beans.PropertyConcept.PROPERTYSET); + sPropertyNames = new String[aProperties.length]; + for (int i = 0; i < aProperties.length; i++){ + sPropertyNames[i] = aProperties[i].Name; + } + } + catch( Exception e ) { + System.err.println( e ); + } + return sPropertyNames; + } + + + // returns the names of all exported interfaces of a UNO object + protected String[] getExportedInterfaceNames(){ + Type[] aTypes = new Type[]{}; + String[] sTypeNames = new String[]{}; + // The XTypeProvider interfaces offers access to all exported interfaces + XTypeProvider xTypeProvider = UnoRuntime.queryInterface( XTypeProvider.class, m_oUnoObject); + if ( xTypeProvider != null ) { + aTypes = xTypeProvider.getTypes(); + sTypeNames = new String[aTypes.length]; + for (int i = 0; i < aTypes.length - 1; i++){ + sTypeNames[i] = aTypes[i].getTypeName(); + } + } + return sTypeNames; + } + + + + public XListBox insertListBox(int _nPosX, int _nPosY, int _nHeight, int _nWidth, int _nStep, String[] _sStringItemList) { + XListBox xListBox = null; + try{ + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "ListBox"); + // create a controlmodel at the multiservicefactory of the dialog model... + Object oListBoxModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlListBoxModel"); + XMultiPropertySet xLBModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oListBoxModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xLBModelMPSet.setPropertyValues( + new String[] {"Dropdown", "Height", "Name", "PositionX", "PositionY", "ReadOnly", "Step", "StringItemList", "Width" } , + new Object[] {Boolean.FALSE, Integer.valueOf(_nHeight), sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Boolean.TRUE, Integer.valueOf(_nStep), _sStringItemList, Integer.valueOf(_nWidth)}); + m_xDlgModelNameContainer.insertByName(sName, xLBModelMPSet); + }catch (com.sun.star.uno.Exception ex) { + throw new java.lang.RuntimeException("cannot happen...", ex); + } + return xListBox; + } + + + public void insertMultiLineFixedText(int _nPosX, int _nPosY, int _nWidth, int _nLineCount, int _nStep, String _sLabel) { + try { + // create a unique name by means of an own implementation... + String sName = createUniqueName(m_xDlgModelNameContainer, "Label"); + int nHeight = _nLineCount * nFixedTextHeight; + // create a controlmodel at the multiservicefactory of the dialog model... + Object oFTModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel"); + XMultiPropertySet xFTModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oFTModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xFTModelMPSet.setPropertyValues( + new String[] {"Height", "Label", "MultiLine", "Name", "PositionX", "PositionY", "Step", "Width"}, + new Object[] { Integer.valueOf(nHeight), _sLabel, Boolean.TRUE, sName, Integer.valueOf(_nPosX), Integer.valueOf(_nPosY), Integer.valueOf(_nStep), Integer.valueOf(_nWidth)}); + // add the model to the NameContainer of the dialog model + m_xDlgModelNameContainer.insertByName(sName, oFTModel); + }catch (com.sun.star.uno.Exception ex){ + /* perform individual exception handling here. + * Possible exception types are: + * com.sun.star.lang.IllegalArgumentException, + * com.sun.star.lang.WrappedTargetException, + * com.sun.star.container.ElementExistException, + * com.sun.star.beans.PropertyVetoException, + * com.sun.star.beans.UnknownPropertyException, + * com.sun.star.uno.Exception + */ + ex.printStackTrace(System.err); + } + } + +}// end of class + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/GUI/UnoMenu.java b/odk/examples/DevelopersGuide/GUI/UnoMenu.java new file mode 100644 index 000000000..10d89c837 --- /dev/null +++ b/odk/examples/DevelopersGuide/GUI/UnoMenu.java @@ -0,0 +1,186 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.awt.MenuEvent; +import com.sun.star.awt.MenuItemStyle; +import com.sun.star.awt.Rectangle; +import com.sun.star.awt.WindowAttribute; +import com.sun.star.awt.WindowClass; +import com.sun.star.awt.XMenuBar; +import com.sun.star.awt.XMenuListener; +import com.sun.star.awt.XPopupMenu; +import com.sun.star.awt.XToolkit; +import com.sun.star.awt.XTopWindow; +import com.sun.star.awt.XWindow; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.XFramesSupplier; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + +public class UnoMenu extends UnoDialogSample implements XMenuListener { +private XTopWindow mxTopWindow = null; + +public UnoMenu(XComponentContext _xContext, XMultiComponentFactory _xMCF) { + super(_xContext, _xMCF); +} + + public static void main(String args[]){ + UnoMenu oUnoMenu = null; + try { + XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if(xContext != null ) + System.out.println("Connected to a running office ..."); + XMultiComponentFactory xMCF = xContext.getServiceManager(); + oUnoMenu = new UnoMenu(xContext, xMCF); + oUnoMenu.mxTopWindow = oUnoMenu.showTopWindow( new Rectangle(100, 100, 500, 500)); //oUnoDialogSample.m_xWindowPeer, + oUnoMenu.addMenuBar(oUnoMenu.mxTopWindow, oUnoMenu); + }catch( Exception ex ) { + ex.printStackTrace(System.err); + } + } + + + public XPopupMenu getPopupMenu(){ + XPopupMenu xPopupMenu = null; + try{ + // create a popup menu + Object oPopupMenu = m_xMCF.createInstanceWithContext("com.sun.star.awt.PopupMenu", m_xContext); + xPopupMenu = UnoRuntime.queryInterface(XPopupMenu.class, oPopupMenu); + + // ID must start be > 0 + short nId = 1; + short nPos = 0; + + xPopupMenu.insertItem(nId++, "First Entry", MenuItemStyle.AUTOCHECK, nPos++); + xPopupMenu.insertItem(nId++, "First Radio Entry", (short) (MenuItemStyle.RADIOCHECK + MenuItemStyle.AUTOCHECK), nPos++); + xPopupMenu.insertItem(nId++, "Second Radio Entry", (short) (MenuItemStyle.RADIOCHECK + MenuItemStyle.AUTOCHECK), nPos++); + xPopupMenu.insertItem(nId++, "Third RadioEntry",(short) (MenuItemStyle.RADIOCHECK + MenuItemStyle.AUTOCHECK), nPos++); + xPopupMenu.insertSeparator(nPos++); + xPopupMenu.insertItem(nId++, "Fifth Entry", (short) (MenuItemStyle.CHECKABLE + MenuItemStyle.AUTOCHECK), nPos++); + xPopupMenu.insertItem(nId++, "Fourth Entry", (short) (MenuItemStyle.CHECKABLE + MenuItemStyle.AUTOCHECK), nPos++); + xPopupMenu.insertItem(nId++, "Sixth Entry", (short) 0, nPos++); + xPopupMenu.insertItem(nId++, "Close Dialog", (short) 0, nPos++); + + xPopupMenu.enableItem((short) 2, false); + xPopupMenu.checkItem((short) 3, true); + + xPopupMenu.addMenuListener(this); + }catch( Exception e ) { + throw new java.lang.RuntimeException("cannot happen...", e); + } + return xPopupMenu; + } + + + private void addMenuBar(XTopWindow _xTopWindow, XMenuListener _xMenuListener){ + try{ + // create a menubar at the global MultiComponentFactory... + Object oMenuBar = m_xMCF.createInstanceWithContext("com.sun.star.awt.MenuBar", m_xContext); + // add the menu items... + XMenuBar xMenuBar = UnoRuntime.queryInterface(XMenuBar.class, oMenuBar); + xMenuBar.insertItem((short) 1, "~First MenuBar Item", com.sun.star.awt.MenuItemStyle.AUTOCHECK, (short) 0); + xMenuBar.insertItem((short) 2, "~Second MenuBar Item", com.sun.star.awt.MenuItemStyle.AUTOCHECK, (short) 1); + xMenuBar.setPopupMenu((short) 1, getPopupMenu()); + xMenuBar.addMenuListener(_xMenuListener); + _xTopWindow.setMenuBar(xMenuBar); + }catch( Exception e ) { + throw new java.lang.RuntimeException("cannot happen...", e); + }} + + protected void closeDialog(){ + XComponent xComponent = UnoRuntime.queryInterface(XComponent.class, mxTopWindow); + if (xComponent != null){ + xComponent.dispose(); + } + + // to ensure that the Java application terminates + System.exit( 0 ); + } + + private XTopWindow showTopWindow( Rectangle _aRectangle){ + XTopWindow xTopWindow = null; + try { + // The Toolkit is the creator of all windows... + Object oToolkit = m_xMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", m_xContext); + XToolkit xToolkit = UnoRuntime.queryInterface(XToolkit.class, oToolkit); + + // set up a window description and create the window. A parent window is always necessary for this... + com.sun.star.awt.WindowDescriptor aWindowDescriptor = new com.sun.star.awt.WindowDescriptor(); + // a TopWindow is contains a title bar and is able to include menus... + aWindowDescriptor.Type = WindowClass.TOP; + // specify the position and height of the window on the parent window + aWindowDescriptor.Bounds = _aRectangle; + // set the window attributes... + aWindowDescriptor.WindowAttributes = WindowAttribute.SHOW + WindowAttribute.MOVEABLE + WindowAttribute.SIZEABLE + WindowAttribute.CLOSEABLE; + + // create the window... + XWindowPeer xWindowPeer = xToolkit.createWindow(aWindowDescriptor); + XWindow xWindow = UnoRuntime.queryInterface(XWindow.class, xWindowPeer); + + // create a frame and initialize it with the created window... + Object oFrame = m_xMCF.createInstanceWithContext("com.sun.star.frame.Frame", m_xContext); + m_xFrame = UnoRuntime.queryInterface(XFrame.class, oFrame); + + Object oDesktop = m_xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", m_xContext); + XFramesSupplier xFramesSupplier = UnoRuntime.queryInterface(XFramesSupplier.class, oDesktop); + m_xFrame.setCreator(xFramesSupplier); + // get the XTopWindow interface... + xTopWindow = UnoRuntime.queryInterface(XTopWindow.class, xWindow); + } catch (com.sun.star.lang.IllegalArgumentException ex) { + ex.printStackTrace(); + } catch (com.sun.star.uno.Exception ex) { + ex.printStackTrace(); + } + return xTopWindow; + } + + + + public void itemSelected(MenuEvent menuEvent){ + // find out which menu item has been triggered, + // by getting the menu-id... + switch (menuEvent.MenuId){ + case 1: + // add your menu-item-specific code here: + break; + case 2: + // add your menu-item-specific code here: + break; + case 8: + closeDialog(); + default: + + } + } + + public void itemHighlighted(MenuEvent menuEvent) { + } + + public void itemDeactivated(MenuEvent menuEvent) { + } + + public void itemActivated(MenuEvent menuEvent) { + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/GUI/UnoMenu2.java b/odk/examples/DevelopersGuide/GUI/UnoMenu2.java new file mode 100644 index 000000000..8658fb66a --- /dev/null +++ b/odk/examples/DevelopersGuide/GUI/UnoMenu2.java @@ -0,0 +1,120 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.awt.MouseEvent; +import com.sun.star.awt.Rectangle; +import com.sun.star.awt.XControl; +import com.sun.star.awt.XWindow; +import com.sun.star.beans.XMultiPropertySet; +import com.sun.star.lang.EventObject; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + + +public class UnoMenu2 extends UnoMenu { + +public UnoMenu2(XComponentContext _xContext, XMultiComponentFactory _xMCF) { + super(_xContext, _xMCF); +} + + public static void main(String args[]){ + UnoMenu2 oUnoMenu2 = null; + try { + XComponentContext xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if(xContext != null ) + System.out.println("Connected to a running office ..."); + XMultiComponentFactory xMCF = xContext.getServiceManager(); + oUnoMenu2 = new UnoMenu2(xContext, xMCF); + oUnoMenu2.initialize( new String[] {"Height", "Moveable", "Name","PositionX","PositionY", "Step", "TabIndex","Title","Width"}, + new Object[] { Integer.valueOf(140), Boolean.TRUE, "Dialog1", Integer.valueOf(102),Integer.valueOf(41), Integer.valueOf(1), Short.valueOf((short) 0), "Menu-Dialog", Integer.valueOf(200)}); + + Object oFTHeaderModel = oUnoMenu2.m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel"); + XMultiPropertySet xFTHeaderModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oFTHeaderModel); + xFTHeaderModelMPSet.setPropertyValues( + new String[] {"Height", "Label", "Name", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(8), "This code-sample demonstrates the creation of a popup-menu", "HeaderLabel", Integer.valueOf(6), Integer.valueOf(6), Integer.valueOf(200)}); + // add the model to the NameContainer of the dialog model + oUnoMenu2.m_xDlgModelNameContainer.insertByName("Headerlabel", oFTHeaderModel); + oUnoMenu2.addLabelForPopupMenu(); + oUnoMenu2.executeDialog(); + }catch( Exception ex ) { + ex.printStackTrace(System.err); + } + finally{ + //make sure always to dispose the component and free the memory! + if (oUnoMenu2 != null) { + if (oUnoMenu2.m_xComponent != null){ + oUnoMenu2.m_xComponent.dispose(); + } + } + System.exit( 0 ); + }} + + + public void addLabelForPopupMenu(){ + try{ + String sName = "lblPopup"; + Object oFTModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel"); + XMultiPropertySet xFTModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oFTModel); + // Set the properties at the model - keep in mind to pass the property names in alphabetical order! + xFTModelMPSet.setPropertyValues( + new String[] {"Height", "Label", "Name", "PositionX", "PositionY", "Width"}, + new Object[] { Integer.valueOf(8), "Right-click here", sName, Integer.valueOf(50), Integer.valueOf(50), Integer.valueOf(100)}); + // add the model to the NameContainer of the dialog model + m_xDlgModelNameContainer.insertByName(sName, oFTModel); + XWindow xWindow = UnoRuntime.queryInterface(XWindow.class, m_xDlgContainer.getControl(sName)); + xWindow.addMouseListener(this); + }catch( Exception e ) { + System.err.println( e + e.getMessage()); + e.printStackTrace(); + }} + + @Override + protected void closeDialog(){ + xDialog.endExecute(); + } + + @Override + public void mouseReleased(MouseEvent mouseEvent) { + } + + @Override + public void mousePressed(MouseEvent mouseEvent) { + if (mouseEvent.PopupTrigger){ + Rectangle aPos = new Rectangle(mouseEvent.X, mouseEvent.Y, 0, 0); + XControl xControl = UnoRuntime.queryInterface(XControl.class, mouseEvent.Source); + getPopupMenu().execute( xControl.getPeer(), aPos, com.sun.star.awt.PopupMenuDirection.EXECUTE_DEFAULT); + } + } + + @Override + public void mouseExited(MouseEvent mouseEvent) { + } + + @Override + public void mouseEntered(MouseEvent mouseEvent) { + } + + @Override + public void disposing(EventObject eventObject) { + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/GUI/oologo.gif b/odk/examples/DevelopersGuide/GUI/oologo.gif new file mode 100644 index 000000000..eb5e679c0 Binary files /dev/null and b/odk/examples/DevelopersGuide/GUI/oologo.gif differ diff --git a/odk/examples/DevelopersGuide/OfficeBean/Makefile b/odk/examples/DevelopersGuide/OfficeBean/Makefile new file mode 100644 index 000000000..09c10d05d --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeBean/Makefile @@ -0,0 +1,90 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OOoBean of the Developers Guide + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +OUT_COMP_CLASS = $(OUT_CLASS)/OOoBeanViewer + +PACKAGE = org/libreoffice/sdk/examples/developers_guide/office_bean + +JAVAFILES = \ + OOoBeanViewer.java \ + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/$(PACKAGE)/%.class,$(JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),\ + $(PATH_SEPARATOR)$(URE_CLASSES_DIR)/libreoffice.jar\ + $(PATH_SEPARATOR)$(OFFICE_CLASSES_DIR)/officebean.jar\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + +# Targets +.PHONY: ALL +ifeq "$(OS)" "MACOSX" +ALL : + @printf 'This example does not work on macOS\n' +else +ALL : \ + OOoBeanViewer +endif + +include $(SETTINGS)/stdtarget.mk + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + javac $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(JAVAFILES) + +OOoBeanViewer: $(CLASSFILES) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) OOoBeanViewer.run + @echo -------------------------------------------------------------------------------- + +%.run: $(CLASSFILES) + $(SDK_JAVA) -classpath "$(SDK_CLASSPATH)" $(subst /,.,$(PACKAGE)).$(basename $@) + +%.dbg: $(JAR1_JAR) + jdb -classpath "$(SDK_CLASSPATH)" $(subst /,.,$(PACKAGE)).$(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + diff --git a/odk/examples/DevelopersGuide/OfficeBean/OOoBeanViewer.java b/odk/examples/DevelopersGuide/OfficeBean/OOoBeanViewer.java new file mode 100644 index 000000000..f87eb3678 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeBean/OOoBeanViewer.java @@ -0,0 +1,410 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +package org.libreoffice.sdk.examples.developers_guide.office_bean; + +import com.sun.star.comp.beans.OOoBean; +import javax.swing.filechooser.*; +import javax.swing.*; +import java.io.*; + +/* A simple Applet that contains the SimpleBean. + * + * This applet is a sample implementation of the + * OpenOffice.org bean. + * When initially loaded the applet has two buttons + * one for opening an existent file and one to open + * a blank document of a given type supported by + * OpenOffice.org eg. Writer, Calc, Impress, ... + * + */ + +public class OOoBeanViewer extends java.applet.Applet +{ + + /** + * Private variables declaration - GUI components + */ + private java.awt.Panel rightPanel; + private java.awt.Panel bottomPanel; + private javax.swing.JButton closeButton; + private javax.swing.JButton terminateButton; + private javax.swing.JButton newDocumentButton; + private javax.swing.JPopupMenu documentTypePopUp; + private javax.swing.JCheckBox menuBarButton; + private javax.swing.JCheckBox mainBarButton; + private javax.swing.JCheckBox toolBarButton; + private javax.swing.JCheckBox statusBarButton; + private javax.swing.JButton storeDocumentButton; + private javax.swing.JButton loadDocumentButton; + private javax.swing.JButton syswinButton; + private JTextField documentURLTextField; + private JMenuItem item; + private JFileChooser fileChooser; + private byte buffer[]; + + /** + * Private variables declaration - SimpleBean variables + */ + private OOoBean aBean; + + /** + * Initialize the Applet + */ + public void init() + { + //The aBean needs to be initialized to add it to the applet + aBean = new OOoBean(); + + //Initialize GUI components + rightPanel = new java.awt.Panel(); + bottomPanel = new java.awt.Panel(); + closeButton = new javax.swing.JButton("close"); + terminateButton = new javax.swing.JButton("terminate"); + newDocumentButton = new javax.swing.JButton("new document..."); + documentTypePopUp = new javax.swing.JPopupMenu(); + storeDocumentButton = new javax.swing.JButton("store to buffer"); + loadDocumentButton = new javax.swing.JButton("load from buffer"); + syswinButton = new javax.swing.JButton("release/acquire"); + + menuBarButton = new javax.swing.JCheckBox("MenuBar"); + menuBarButton.setSelected( aBean.isMenuBarVisible() ); + + mainBarButton = new javax.swing.JCheckBox("MainBar"); + mainBarButton.setSelected( aBean.isStandardBarVisible() ); + + toolBarButton = new javax.swing.JCheckBox("ToolBar"); + toolBarButton.setSelected( aBean.isToolBarVisible() ); + + statusBarButton = new javax.swing.JCheckBox("StatusBar"); + statusBarButton.setSelected( aBean.isStatusBarVisible() ); + + documentURLTextField = new javax.swing.JTextField(); + + //Set up the Popup Menu to create a blank document + documentTypePopUp.setToolTipText("Create an empty document"); + + item = documentTypePopUp.add("Text Document"); + item.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + createBlankDoc("private:factory/swriter", + "New text document"); + } + }); + + item = documentTypePopUp.add("Presentation Document"); + item.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + createBlankDoc("private:factory/simpress", + "New presentation document"); + } + }); + + item = documentTypePopUp.add("Drawing Document"); + item.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + createBlankDoc("private:factory/sdraw", + "New drawing document"); + } + }); + + item = documentTypePopUp.add("Formula Document"); + item.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + createBlankDoc("private:factory/smath", + "New formula document"); + } + }); + + item = documentTypePopUp.add("Spreadsheet Document"); + item.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + createBlankDoc("private:factory/scalc", + "New spreadsheet document"); + } + }); + + syswinButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + try + { + aBean.releaseSystemWindow(); + aBean.aquireSystemWindow(); + } + catch ( com.sun.star.comp.beans.NoConnectionException aExc ) + {} + catch ( com.sun.star.comp.beans.SystemWindowException aExc ) + {} + } + }); + + storeDocumentButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + try + { + buffer = aBean.storeToByteArray( null, null ); + } + catch ( Throwable aExc ) + { + System.err.println( "storeToBuffer failed: " + aExc ); + aExc.printStackTrace( System.err ); + } + } + }); + + loadDocumentButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + try + { + aBean.loadFromByteArray( buffer, null ); + } + catch ( Throwable aExc ) + { + System.err.println( "loadFromBuffer failed: " + aExc ); + aExc.printStackTrace( System.err ); + } + } + }); + + closeButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + close(); + } + }); + + terminateButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + terminate(); + } + }); + + newDocumentButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + documentTypePopUp.show((java.awt.Component)evt.getSource(), 0,0); + } + }); + + menuBarButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + aBean.setMenuBarVisible( !aBean.isMenuBarVisible() ); + } + }); + + mainBarButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + aBean.setStandardBarVisible( !aBean.isStandardBarVisible() ); + } + }); + + toolBarButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + aBean.setToolBarVisible( !aBean.isToolBarVisible() ); + } + }); + + statusBarButton.addActionListener(new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent evt) + { + aBean.setStatusBarVisible( !aBean.isStatusBarVisible() ); + } + }); + + documentURLTextField.setEditable(false); + documentURLTextField.setPreferredSize(new java.awt.Dimension(200, 30)); + + rightPanel.setLayout( new java.awt.GridLayout(10,1) ); + rightPanel.add(closeButton); + rightPanel.add(terminateButton); + rightPanel.add(newDocumentButton); + rightPanel.add(storeDocumentButton); + rightPanel.add(loadDocumentButton); + rightPanel.add(syswinButton); + rightPanel.add(menuBarButton); + rightPanel.add(mainBarButton); + rightPanel.add(toolBarButton); + rightPanel.add(statusBarButton); + + //bottomPanel.setLayout( new java.awt.GridLayout(1,1) ); + bottomPanel.setLayout( new java.awt.BorderLayout() ); + bottomPanel.add(documentURLTextField); + + setLayout(new java.awt.BorderLayout()); + + add(aBean, java.awt.BorderLayout.CENTER); + add(rightPanel, java.awt.BorderLayout.EAST); + add(bottomPanel, java.awt.BorderLayout.SOUTH); + } + + /** + * Create a blank document of type desc + * + * @param url The private internal URL of the OpenOffice.org + * document describing the document + * @param desc A description of the document to be created + */ + private void createBlankDoc(String url, String desc) + { + //Create a blank document + try + { + documentURLTextField.setText(desc); + //Get the office process to load the URL + aBean.loadFromURL( url, null ); + + aBean.aquireSystemWindow(); + } + catch ( com.sun.star.comp.beans.SystemWindowException aExc ) + { + System.err.println( "OOoBeanViewer.1:" ); + aExc.printStackTrace(); + } + catch ( com.sun.star.comp.beans.NoConnectionException aExc ) + { + System.err.println( "OOoBeanViewer.2:" ); + aExc.printStackTrace(); + } + catch ( Exception aExc ) + { + System.err.println( "OOoBeanViewer.3:" ); + aExc.printStackTrace(); + //return; + } + } + + /** closes the bean viewer, leaves OOo running. + */ + private void close() + { + setVisible(false); + aBean.stopOOoConnection(); + stop(); + System.exit(0); + } + + /** closes the bean viewer and tries to terminate OOo. + */ + private void terminate() + { + setVisible(false); + com.sun.star.frame.XDesktop xDesktop = null; + try { + xDesktop = aBean.getOOoDesktop(); + } + catch ( com.sun.star.comp.beans.NoConnectionException aExc ) {} // ignore + aBean.stopOOoConnection(); + stop(); + if ( xDesktop != null ) + xDesktop.terminate(); + System.exit(0); + } + + /** + * An ExitListener listening for windowClosing events + */ + private class ExitListener extends java.awt.event.WindowAdapter + { + /** + * windowClosed + * + * @param e A WindowEvent for a closed Window event + */ + public void windowClosed( java.awt.event.WindowEvent e) + { + close(); + } + + /** + * windowClosing for a closing window event + * + * @param e A WindowEvent for a closing window event + */ + public void windowClosing( java.awt.event.WindowEvent e) + { + ((java.awt.Window)e.getSource()).dispose(); + } + } + + public static void main(String args[]) + { + java.awt.Frame frame = new java.awt.Frame("OpenOffice.org Demo"); + OOoBeanViewer aViewer = new OOoBeanViewer(); + + frame.setLayout(new java.awt.BorderLayout()); + + frame.addWindowListener( aViewer.new ExitListener() ); + + aViewer.init(); + aViewer.start(); + + frame.add(aViewer); + frame.setLocation( 200, 200 ); + frame.setSize( 800, 480 ); + frame.show(); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeBean/OfficeIconColor16.jpg b/odk/examples/DevelopersGuide/OfficeBean/OfficeIconColor16.jpg new file mode 100644 index 000000000..cd9c5a602 Binary files /dev/null and b/odk/examples/DevelopersGuide/OfficeBean/OfficeIconColor16.jpg differ diff --git a/odk/examples/DevelopersGuide/OfficeBean/OfficeIconColor32.jpg b/odk/examples/DevelopersGuide/OfficeBean/OfficeIconColor32.jpg new file mode 100644 index 000000000..ccab06b51 Binary files /dev/null and b/odk/examples/DevelopersGuide/OfficeBean/OfficeIconColor32.jpg differ diff --git a/odk/examples/DevelopersGuide/OfficeBean/OfficeIconMono16.jpg b/odk/examples/DevelopersGuide/OfficeBean/OfficeIconMono16.jpg new file mode 100644 index 000000000..cd9c5a602 Binary files /dev/null and b/odk/examples/DevelopersGuide/OfficeBean/OfficeIconMono16.jpg differ diff --git a/odk/examples/DevelopersGuide/OfficeBean/OfficeIconMono32.jpg b/odk/examples/DevelopersGuide/OfficeBean/OfficeIconMono32.jpg new file mode 100644 index 000000000..ccab06b51 Binary files /dev/null and b/odk/examples/DevelopersGuide/OfficeBean/OfficeIconMono32.jpg differ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Clipboard/Clipboard.java b/odk/examples/DevelopersGuide/OfficeDev/Clipboard/Clipboard.java new file mode 100644 index 000000000..742fed8ed --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Clipboard/Clipboard.java @@ -0,0 +1,212 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.XComponentContext; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.frame.Desktop; +import com.sun.star.frame.XDesktop2; +import com.sun.star.datatransfer.DataFlavor; +import com.sun.star.datatransfer.UnsupportedFlavorException; +import com.sun.star.datatransfer.XTransferable; +import com.sun.star.datatransfer.clipboard.XClipboard; +import com.sun.star.datatransfer.clipboard.SystemClipboard; +import com.sun.star.datatransfer.clipboard.XSystemClipboard; +import com.sun.star.text.XTextDocument; +import com.sun.star.uno.AnyConverter; + + +// Demonstrates the usage of the clipboard service + + +public class Clipboard +{ + public static void main(String[] args) + { + try + { + // get the remote office context. If necessary a new office + // process is started + XComponentContext xOfficeContext = + com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + // create a new test document + XDesktop2 xDesktop = Desktop.create(xOfficeContext); + com.sun.star.lang.XComponent xComponent = + xDesktop.loadComponentFromURL("private:factory/swriter", + "_blank", 0, new com.sun.star.beans.PropertyValue[0]); + { + XTextDocument xDoc =UnoRuntime.queryInterface(XTextDocument.class, xComponent); + xDoc.getText().setString("In the first step, paste the current content of the clipboard in the document!\nThe text \"Hello world!\" shall be insert at the current cursor position below.\n\nIn the second step, please select some words and put it into the clipboard! ...\n\nCurrent clipboard content = "); + + // ensure that the document content is optimal visible + com.sun.star.frame.XModel xModel = + UnoRuntime.queryInterface( + com.sun.star.frame.XModel.class, xDoc); + // get the frame for later usage + com.sun.star.frame.XFrame xFrame = + xModel.getCurrentController().getFrame(); + + com.sun.star.view.XViewSettingsSupplier xViewSettings = + UnoRuntime.queryInterface( + com.sun.star.view.XViewSettingsSupplier.class, + xModel.getCurrentController()); + xViewSettings.getViewSettings().setPropertyValue( + "ZoomType", Short.valueOf((short)0)); + } + // test document will be closed later + + XSystemClipboard xClipboard = SystemClipboard.create(xOfficeContext); + + + // registering as clipboard listener + + + ClipboardListener aClipListener= new ClipboardListener(); + + xClipboard.addClipboardListener(aClipListener); + + // Read ClipBoard + readClipBoard(xClipboard); + + + // becoming a clipboard owner + + + System.out.println("Becoming a clipboard owner..."); + System.out.println(""); + + ClipboardOwner aClipOwner = new ClipboardOwner(); + xClipboard.setContents(new TextTransferable("Hello World!"), aClipOwner); + int iFirst = 0; + + while (aClipOwner.isClipboardOwner()) + { + if (iFirst != 2) { + if (iFirst == 1) { + System.out.println("Change clipboard ownership by putting something into the clipboard!\n"); + System.out.print("Still clipboard owner..."); + } else { + System.out.println("Still clipboard owner..."); + } + ++iFirst; + } else { + System.out.print("."); + } + Thread.sleep(1000); + } + + // Read ClipBoard again + readClipBoard(xClipboard); + + + // unregistering as clipboard listener + + xClipboard.removeClipboardListener(aClipListener); + + // close test document + com.sun.star.util.XCloseable xCloseable = UnoRuntime.queryInterface(com.sun.star.util.XCloseable.class, + xComponent ); + + if (xCloseable != null ) { + xCloseable.close(false); + } else + { + xComponent.dispose(); + } + + System.exit(0); + } + catch( Exception ex ) + { + ex.printStackTrace(); + } + } + + public static void readClipBoard(XClipboard xClipboard) + throws java.lang.Exception + { + + // get a list of formats currently on the clipboard + + + XTransferable xTransferable = xClipboard.getContents(); + + DataFlavor[] aDflvArr = xTransferable.getTransferDataFlavors(); + + // print all available formats + + System.out.println("Reading the clipboard..."); + System.out.println("Available clipboard formats:"); + + DataFlavor aUniFlv = null; + + for (int i=0;i $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(APP1_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(APP1_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(EXAMPLE_NAME) : $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/OfficeDev/Clipboard/TextTransferable.java b/odk/examples/DevelopersGuide/OfficeDev/Clipboard/TextTransferable.java new file mode 100644 index 000000000..82a2b316a --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Clipboard/TextTransferable.java @@ -0,0 +1,88 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.datatransfer.DataFlavor; +import com.sun.star.datatransfer.UnsupportedFlavorException; +import com.sun.star.datatransfer.XTransferable; +import com.sun.star.uno.Type; + + +// A simple transferable containing only +// one format, unicode text + + +public class TextTransferable implements XTransferable +{ + public TextTransferable(String aText) + { + text = aText; + } + + // XTransferable methods + + public Object getTransferData(DataFlavor aFlavor) throws UnsupportedFlavorException + { + if ( !aFlavor.MimeType.equalsIgnoreCase( UNICODE_CONTENT_TYPE ) ) + throw new UnsupportedFlavorException(); + + return text; + } + + public DataFlavor[] getTransferDataFlavors() + { + DataFlavor[] adf = new DataFlavor[1]; + + DataFlavor uniflv = new DataFlavor( + UNICODE_CONTENT_TYPE, + "Unicode Text", + new Type(String.class) ); + + adf[0] = uniflv; + + return adf; + } + + public boolean isDataFlavorSupported(DataFlavor aFlavor) + { + return aFlavor.MimeType.equalsIgnoreCase(UNICODE_CONTENT_TYPE); + } + +// members + + private final String text; + private static final String UNICODE_CONTENT_TYPE = "text/plain;charset=utf-16"; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/ContextMenuInterceptor.java b/odk/examples/DevelopersGuide/OfficeDev/ContextMenuInterceptor.java new file mode 100644 index 000000000..d73554972 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/ContextMenuInterceptor.java @@ -0,0 +1,253 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.beans.XPropertySet; +import com.sun.star.ui.ActionTriggerSeparatorType; +import com.sun.star.ui.ContextMenuInterceptorAction; +import com.sun.star.ui.XContextMenuInterceptor; +import com.sun.star.uno.UnoRuntime; + +public class ContextMenuInterceptor implements XContextMenuInterceptor { + + /** + *Description of the Method + * + *@param args Description of Parameter + */ + public static void main(String args[]) + { + try { + OfficeConnect aConnect = OfficeConnect.createConnection(); + + com.sun.star.frame.XDesktop xDesktop = + aConnect.createRemoteInstance( + com.sun.star.frame.XDesktop.class,"com.sun.star.frame.Desktop"); + + // create a new test document + com.sun.star.frame.XComponentLoader xCompLoader = + UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, xDesktop); + + com.sun.star.lang.XComponent xComponent = + xCompLoader.loadComponentFromURL("private:factory/swriter", + "_blank", 0, new com.sun.star.beans.PropertyValue[0]); + + // initialize the test document + com.sun.star.frame.XFrame xFrame = null; + { + com.sun.star.text.XTextDocument xDoc =UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class, + xComponent); + + String infoMsg = "All context menus of the created document frame contains now a 'Help' entry with the submenus 'Content', 'Help on Help' and 'Tips'.\n\nPress 'Return' in the shell to remove the context menu interceptor and finish the example!"; + xDoc.getText().setString(infoMsg); + + // ensure that the document content is optimal visible + com.sun.star.frame.XModel xModel = + UnoRuntime.queryInterface( + com.sun.star.frame.XModel.class, xDoc); + // get the frame for later usage + xFrame = xModel.getCurrentController().getFrame(); + + com.sun.star.view.XViewSettingsSupplier xViewSettings = + UnoRuntime.queryInterface( + com.sun.star.view.XViewSettingsSupplier.class, xModel.getCurrentController()); + xViewSettings.getViewSettings().setPropertyValue( + "ZoomType", Short.valueOf((short)0)); + } + // test document will be closed later + + // reuse the frame + com.sun.star.frame.XController xController = xFrame.getController(); + if ( xController != null ) { + com.sun.star.ui.XContextMenuInterception xContextMenuInterception = + UnoRuntime.queryInterface( + com.sun.star.ui.XContextMenuInterception.class, xController ); + if( xContextMenuInterception != null ) { + ContextMenuInterceptor aContextMenuInterceptor = new ContextMenuInterceptor(); + com.sun.star.ui.XContextMenuInterceptor xContextMenuInterceptor = + UnoRuntime.queryInterface( + com.sun.star.ui.XContextMenuInterceptor.class, aContextMenuInterceptor ); + xContextMenuInterception.registerContextMenuInterceptor( xContextMenuInterceptor ); + + System.out.println( "\n ... all context menus of the created document frame contains now a 'Help' entry with the\n submenus 'Content', 'Help on Help' and 'Tips'.\n\nPress 'Return' to remove the context menu interceptor and finish the example!"); + + java.io.BufferedReader reader + = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); + reader.read(); + + xContextMenuInterception.releaseContextMenuInterceptor( + xContextMenuInterceptor ); + System.out.println( " ... context menu interceptor removed!" ); + } + } + + // close test document + com.sun.star.util.XCloseable xCloseable = UnoRuntime.queryInterface(com.sun.star.util.XCloseable.class, + xComponent ); + + if (xCloseable != null ) { + xCloseable.close(false); + } else + { + xComponent.dispose(); + } + } + catch ( com.sun.star.uno.RuntimeException ex ) { + // something strange has happened! + System.out.println( " Sample caught exception! " + ex ); + System.exit(1); + } + catch ( java.lang.Exception ex ) { + // catch java exceptions and do something useful + System.out.println( " Sample caught exception! " + ex ); + System.exit(1); + } + + System.out.println(" ... exit!\n"); + System.exit( 0 ); + } + + /** + *Description of the Method + */ + public ContextMenuInterceptorAction notifyContextMenuExecute( + com.sun.star.ui.ContextMenuExecuteEvent aEvent ) throws RuntimeException { + + try { + + // Retrieve context menu container and query for service factory to + // create sub menus, menu entries and separators + com.sun.star.container.XIndexContainer xContextMenu = aEvent.ActionTriggerContainer; + com.sun.star.lang.XMultiServiceFactory xMenuElementFactory = + UnoRuntime.queryInterface( + com.sun.star.lang.XMultiServiceFactory.class, xContextMenu ); + if ( xMenuElementFactory != null ) { + // create root menu entry and sub menu + com.sun.star.beans.XPropertySet xRootMenuEntry = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, + xMenuElementFactory.createInstance( "com.sun.star.ui.ActionTrigger" )); + + // create a line separator for our new help sub menu + com.sun.star.beans.XPropertySet xSeparator = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, + xMenuElementFactory.createInstance( "com.sun.star.ui.ActionTriggerSeparator" )); + + Short aSeparatorType = Short.valueOf( ActionTriggerSeparatorType.LINE ); + xSeparator.setPropertyValue( "SeparatorType", aSeparatorType ); + + // query sub menu for index container to get access + com.sun.star.container.XIndexContainer xSubMenuContainer = + UnoRuntime.queryInterface( + com.sun.star.container.XIndexContainer.class, + xMenuElementFactory.createInstance( + "com.sun.star.ui.ActionTriggerContainer" )); + + // initialize root menu entry + xRootMenuEntry.setPropertyValue( "Text", "Help"); + xRootMenuEntry.setPropertyValue( "CommandURL", "slot:5410"); + xRootMenuEntry.setPropertyValue( "HelpURL", "5410"); + xRootMenuEntry.setPropertyValue( "SubContainer", xSubMenuContainer ); + + // create menu entries for the new sub menu + + // initialize help/content menu entry + XPropertySet xMenuEntry = UnoRuntime.queryInterface( + XPropertySet.class, xMenuElementFactory.createInstance( + "com.sun.star.ui.ActionTrigger" )); + + xMenuEntry.setPropertyValue( "Text", "Content" ); + xMenuEntry.setPropertyValue( "CommandURL", "slot:5401" ); + xMenuEntry.setPropertyValue( "HelpURL", "5401" ); + + // insert menu entry to sub menu + xSubMenuContainer.insertByIndex( 0, xMenuEntry ); + + // initialize help/help on help + xMenuEntry = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, + xMenuElementFactory.createInstance( + "com.sun.star.ui.ActionTrigger" )); + xMenuEntry.setPropertyValue("Text", "Help on Help"); + xMenuEntry.setPropertyValue("CommandURL", "slot:5400"); + xMenuEntry.setPropertyValue("HelpURL", "5400"); + + // insert menu entry to sub menu + xSubMenuContainer.insertByIndex( 1, xMenuEntry ); + + // initialize help/tips + xMenuEntry = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, + xMenuElementFactory.createInstance( + "com.sun.star.ui.ActionTrigger" )); + xMenuEntry.setPropertyValue( "Text", "Tips" ); + xMenuEntry.setPropertyValue( "CommandURL", "slot:5404" ); + xMenuEntry.setPropertyValue( "HelpURL", "5404" ); + + // insert menu entry to sub menu + xSubMenuContainer.insertByIndex( 2, xMenuEntry ); + + // add separator into the given context menu + xContextMenu.insertByIndex( 0, xSeparator ); + + // add new sub menu into the given context menu + xContextMenu.insertByIndex( 0, xRootMenuEntry ); + + // The controller should execute the modified context menu and stop notifying other + // interceptors. + return com.sun.star.ui.ContextMenuInterceptorAction.EXECUTE_MODIFIED; + } + } + catch ( com.sun.star.beans.UnknownPropertyException ex ) { + // do something useful + // we used an unknown property + } + catch ( com.sun.star.lang.IndexOutOfBoundsException ex ) { + // do something useful + // we used an invalid index for accessing a container + } + catch ( com.sun.star.uno.Exception ex ) { + // something strange has happened! + } + catch ( java.lang.Exception ex ) { + // catch java exceptions and something useful + } + + return com.sun.star.ui.ContextMenuInterceptorAction.IGNORED; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/CustomizeView.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/CustomizeView.java new file mode 100644 index 000000000..f19429585 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/CustomizeView.java @@ -0,0 +1,285 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.awt.*; +import javax.swing.*; +import java.awt.event.*; + +/** + * Makes it possible to change some states of currently loaded + * document (e.g. enable/disable menubar, toolbar, objectbar) + * + */ +public class CustomizeView extends JPanel + implements IShutdownListener +{ + /** + * These const URL's describe feature for toggling some properties of loaded document. + * Dispatch it with the corresponding parameter to the frame. + */ + private static final String FEATUREURL_MENUBAR = "slot:6661" ; + private static final String FEATUREURL_TOOLBAR = "slot:5909" ; + private static final String FEATUREURL_OBJECTBAR = "slot:5905" ; + + private static final String FEATUREPROP_MENUBAR = "MenuBarVisible" ; + private static final String FEATUREPROP_TOOLBAR = "ToolBarVisible" ; + private static final String FEATUREPROP_OBJECTBAR = "ObjectBarVisible" ; + + private static final String ACTION_MENUBAR = "toggle_menu" ; + private static final String ACTION_TOOLBAR = "toggle_toolbar" ; + private static final String ACTION_OBJECTBAR = "toggle_objectbar" ; + + private static final String MENUBAR_ON = "menubar on" ; + private static final String TOOLBAR_ON = "toolbar on" ; + private static final String OBJECTBAR_ON = "objectbar on" ; + + private static final String MENUBAR_OFF = "menubar off" ; + private static final String TOOLBAR_OFF = "toolbar off" ; + private static final String OBJECTBAR_OFF = "objectbar off" ; + + + // member + + /** + * @member m_cbMenuBar reference to checkbox for toggling menubar + * @member m_cbToolBar reference to checkbox for toggling toolbar + * @member m_cbObjectBar reference to checkbox for toggling objectbar + * + * @member m_aMenuBarListener listener for status events of the menu bar + * @member m_aToolBarListener listener for status events of the tool bar + * @member m_aObjectBarListener listener for status events of the object bar + */ + private final JCheckBox m_cbMenuBar ; + private final JCheckBox m_cbToolBar ; + private final JCheckBox m_cbObjectBar ; + + private StatusListener m_aMenuBarListener ; + private StatusListener m_aToolBarListener ; + private StatusListener m_aObjectBarListener; + + + + /** + * ctor + * Create view controls on startup and initialize it. + * We don't start listening here. see setFrame()! + */ + CustomizeView() + { + this.setLayout(new GridLayout(3,0)); + + m_cbMenuBar = new JCheckBox(MENUBAR_OFF , false); + m_cbToolBar = new JCheckBox(TOOLBAR_OFF , false); + m_cbObjectBar = new JCheckBox(OBJECTBAR_OFF, false); + + m_cbMenuBar.setEnabled (false); + m_cbToolBar.setEnabled (false); + m_cbObjectBar.setEnabled(false); + + m_cbMenuBar.setActionCommand (ACTION_MENUBAR ); + m_cbToolBar.setActionCommand (ACTION_TOOLBAR ); + m_cbObjectBar.setActionCommand(ACTION_OBJECTBAR); + + this.add(m_cbMenuBar ); + this.add(m_cbToolBar ); + this.add(m_cbObjectBar); + } + + + + /** + * set new frame for this view + * We start listening for frame action/status and click events instandly. + * If an event occurs, we use it to synchronize our controls + * with states of a (maybe) new document view of this frame. + * + * @param xFrame + * the reference to the frame, which provides the + * possibility to get the required status information + * + * Attention: We don't accept new frames here. + * We get one after startup and work with it. + * That's it! + */ + public void setFrame(com.sun.star.frame.XFrame xFrame) + { + if (xFrame==null) + return; + + // be listener for click events + // They will toggle the UI controls. + ClickListener aMenuBarHandler = new ClickListener(FEATUREURL_MENUBAR ,FEATUREPROP_MENUBAR ,xFrame); + ClickListener aToolBarHandler = new ClickListener(FEATUREURL_TOOLBAR ,FEATUREPROP_TOOLBAR ,xFrame); + ClickListener aObjectBarHandler = new ClickListener(FEATUREURL_OBJECTBAR,FEATUREPROP_OBJECTBAR,xFrame); + + m_cbMenuBar.addActionListener (aMenuBarHandler ); + m_cbToolBar.addActionListener (aToolBarHandler ); + m_cbObjectBar.addActionListener(aObjectBarHandler); + + // be frame action listener + // The callback will update listener connections + // for status updates automatically! + m_aMenuBarListener = new StatusListener(m_cbMenuBar ,MENUBAR_ON ,MENUBAR_OFF ,xFrame, FEATUREURL_MENUBAR ); + m_aToolBarListener = new StatusListener(m_cbToolBar ,TOOLBAR_ON ,TOOLBAR_OFF ,xFrame, FEATUREURL_TOOLBAR ); + m_aObjectBarListener = new StatusListener(m_cbObjectBar,OBJECTBAR_ON,OBJECTBAR_OFF,xFrame, FEATUREURL_OBJECTBAR); + + m_aMenuBarListener.startListening(); + m_aToolBarListener.startListening(); + m_aObjectBarListener.startListening(); + } + + + + /* + * react for click events of the used check boxes + * We use our internal set dispatch objects to + * call it. This calls toggle the menu/object- or toolbar. + * Note: Because we are listener status events too - hopefully + * we get a notification, if toggling was successfully or not. + * We use this information to update our check boxes again. + * But such update doesn't force (hopefully) an action event. Otherwise + * we can produce a never ending recursion! + */ + private class ClickListener implements ActionListener, + com.sun.star.lang.XEventListener + { + /// URL, to toggle the requested UI item + private final String m_sURL; + /// name of the property which must be used in combination with the URL + private final String m_sProp; + /// we must use this frame to dispatch a request + private com.sun.star.frame.XFrame m_xFrame; + + + + /** + * ctor + * It initialize an instance of this class only. + */ + private ClickListener( String sURL , + String sProp , + com.sun.star.frame.XFrame xFrame ) + { + m_sURL = sURL ; + m_sProp = sProp ; + m_xFrame = xFrame; + } + + + + /** + * callback for action events + * Such events occur, if someone clicked the + * JCheckBox control, on which we are registered. + * Such events do not occur, if we set it programmatically + * (e.g. if we get status events to -> see class StatusListener too) + * + * @param aEvent + * describes the check box and its state + * we can use to toggle the requested office + * resource. + */ + public void actionPerformed(ActionEvent aEvent) + { + synchronized(this) + { + if (m_xFrame==null) + return; + } + + // define parameters for following dispatch + boolean bState = ((JCheckBox)aEvent.getSource()).isSelected(); + + // prepare the dispatch + com.sun.star.util.URL aURL = FunctionHelper.parseURL(m_sURL); + if (aURL==null) + return; + + com.sun.star.beans.PropertyValue[] lProperties = new com.sun.star.beans.PropertyValue[1]; + lProperties[0] = new com.sun.star.beans.PropertyValue(); + lProperties[0].Name = m_sProp; + lProperties[0].Value = Boolean.valueOf(bState); + + // execute (dispatch) it into the frame + if (m_xFrame==null) + return; + FunctionHelper.execute(m_xFrame,aURL,lProperties,null); + } + + + + /** + * callback for disposing events + * Internally we save a reference to an office frame. + * Of course he can die and inform us then. We should react + * and forget his reference. + * + * @param aEvent + * describes the source which fire this event + * Must be our internal saved frame. Otherwise + * somewhere know us without a registration ... + */ + public void disposing(com.sun.star.lang.EventObject aEvent) + { + synchronized(this) + { + m_xFrame = null; + } + } + } + + + + /** + * If this java application shutdown - we must cancel all current existing + * listener connections. Otherwise the office will run into some + * DisposedExceptions if it tries to use these forgotten listener references. + * And of course it can die doing that. + * We are registered at a central object to be informed if the VM will exit. + * So we can react. + */ + public void shutdown() + { + m_aMenuBarListener.shutdown(); + m_aToolBarListener.shutdown(); + m_aObjectBarListener.shutdown(); + + m_aMenuBarListener = null; + m_aToolBarListener = null; + m_aObjectBarListener = null; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Desk.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Desk.java new file mode 100644 index 000000000..7ce2682fe --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Desk.java @@ -0,0 +1,93 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +// __________ Implementation __________ + +/** + * TODO + * + */ +public class Desk +{ + + + /** + * main + * Establish connection to a remote office and starts the demo application. + * User can overwrite some of necessary start options by using command line parameters. + * + * syntax: Desk [mode={inplace|outplace}] [file=] + * + * @param lArguments command line arguments + * mode describe using mode of document view {inplace/outplace} + * default=inplace + * file name of first file which should be open + * default="private:factory/swriter" to open empty writer document + */ + public static void main(String[] lArguments) + { + // Analyze command line parameters. + String sMode = "inplace"; + String sFile = "private:factory/swriter"; + + for(int i=0; inew menu to open new document inside this java application + */ + private com.sun.star.frame.XFrame mxFrame ; + + private StatusView maStatusView ; + private NativeView maDocumentView ; + private CustomizeView maCustomizeView ; + private Interceptor maInterceptor ; + + private final String msName; + + private final JButton mbtSave; + private final JButton mbtExport; + + private boolean mbDead ; + + + + /** + * ctor + * Create view controls on startup and initialize it with default values. + */ + DocumentView() + { + this.setSize( new Dimension(800,600) ); + + JPanel paMainPanel = (JPanel)this.getContentPane(); + + // create and add command buttons to a panel + // it will be a sub panel of later layouted UI + JButton mbtOpen = new JButton("Open ..." ); + mbtSave = new JButton("Save" ); + mbtExport = new JButton("Save as HTML ..."); + JButton mbtExit = new JButton("Exit" ); + + mbtOpen.setEnabled (true ); + mbtSave.setEnabled (false); + mbtExport.setEnabled(false); + mbtExit.setEnabled (true ); + + mbtOpen.setActionCommand (COMMAND_OPEN ); + mbtSave.setActionCommand (COMMAND_SAVE ); + mbtExport.setActionCommand(COMMAND_EXPORT); + mbtExit.setActionCommand (COMMAND_EXIT ); + + Reactor aListener = new Reactor(); + mbtOpen.addActionListener (aListener); + mbtSave.addActionListener (aListener); + mbtExport.addActionListener(aListener); + mbtExit.addActionListener (aListener); + + JPanel paCommands = new JPanel( new GridLayout(4,0) ); + paCommands.add(mbtOpen); + paCommands.add(mbtSave); + paCommands.add(mbtExport); + paCommands.add(mbtExit); + + // create view to show status information of opened file + maStatusView = new StatusView(); + + // create view for toggle different bar's of document + maCustomizeView = new CustomizeView(); + + paCommands.setBorder ( new TitledBorder(BorderFactory.createEtchedBorder(),"Commands") ); + maStatusView.setBorder ( new TitledBorder(BorderFactory.createEtchedBorder(),"Status Information") ); + maCustomizeView.setBorder( new TitledBorder(BorderFactory.createEtchedBorder(),"Customize Document View") ); + + // layout the whole UI + JPanel paTest = new JPanel(new GridLayout(3,0)); + paTest.add(paCommands ); + paTest.add(maStatusView ); + paTest.add(maCustomizeView); + JScrollPane paScroll = new JScrollPane(); + paScroll.getViewport().add(paTest,null); + + if(ViewContainer.mbInplace) + { + // create view to show opened documents + // This special view is necessary for inplace mode only! + maDocumentView = new NativeView(); + + JSplitPane paSplit = new JSplitPane(); + paSplit.setOneTouchExpandable( true ); + + paSplit.setLeftComponent (maDocumentView); + paSplit.setRightComponent(paScroll ); + + paMainPanel.add(paSplit); + } + else + { + paMainPanel.add(paScroll); + } + + // Register this new view on our global view container. + msName = FunctionHelper.getUniqueFrameName(); + this.setTitle(msName); + ViewContainer.getGlobalContainer().addView(this); + ViewContainer.getGlobalContainer().addListener(this); + // be listener for closing the application + this.enableEvents(AWTEvent.WINDOW_EVENT_MASK); + } + + + + /** + * Create the view frame for showing the office documents on demand. + * Depending on given command line parameter we create + * an office XFrame and initialize it with a window. This + * window can be a pure toolkit window (means toolkit of office!) + * or a plugged java canvas - office window combination. + */ + public void createFrame() + { + // create view frame (as a XFrame!) here + // Look for right view mode set by user command line parameter. + // First try to get a new unambiguous frame name from our global ViewContainer. + if(ViewContainer.mbInplace) + { + // inplace document view can't be initialized without a visible parent window hierarchy! + // So make sure that we are visible in every case! + this.setVisible(true); + mxFrame = FunctionHelper.createViewFrame(msName,maDocumentView); + } + else + mxFrame = FunctionHelper.createViewFrame(msName,null); + + if(mxFrame!=null) + { + // start interception + maInterceptor = new Interceptor(mxFrame); + maInterceptor.startListening(); + + // start listening for status events and actualization + // of our status view + // (of course for our CustomizeView too) + maStatusView.setFrame (mxFrame); + maCustomizeView.setFrame(mxFrame); + + // be listener for closing the remote target view frame + com.sun.star.lang.XComponent xBroadcaster = UnoRuntime.queryInterface( + com.sun.star.lang.XComponent.class, + mxFrame); + + if(xBroadcaster!=null) + xBroadcaster.addEventListener(this); + } + } + + + + /** + * Different ways to load any URL from outside (may be by the command line) + * into this document view or to save it. + */ + public void load(String sURL) + { + load(sURL,new com.sun.star.beans.PropertyValue[0]); + } + + + + public void load(String sURL, com.sun.star.beans.PropertyValue[] lArguments) + { + com.sun.star.lang.XComponent xDocument = FunctionHelper.loadDocument(mxFrame,sURL,lArguments); + if(xDocument!=null) + { + mbtSave.setEnabled (true); + mbtExport.setEnabled(true); + } + else + { + mbtSave.setEnabled (false); + mbtExport.setEnabled(false); + } + } + + + + private void save() + { + com.sun.star.frame.XController xController = mxFrame.getController(); + if (xController==null) + return; + com.sun.star.frame.XModel xDocument = xController.getModel(); + if (xDocument==null) + return; + FunctionHelper.saveDocument(xDocument); + } + + + + private void exportHTML(String sURL) + { + com.sun.star.frame.XController xController = mxFrame.getController(); + if (xController==null) + return; + com.sun.star.frame.XModel xDocument = xController.getModel(); + if (xDocument==null) + return; + FunctionHelper.saveAsHTML(xDocument,sURL); + } + + + + /** + * Overridden so we can react for window closing of this view. + */ + @Override + protected void processWindowEvent(WindowEvent aEvent) + { + if (aEvent.getID()!=WindowEvent.WINDOW_CLOSING) + { + super.processWindowEvent(aEvent); + } + else + if (FunctionHelper.closeFrame(mxFrame)) + { + mxFrame = null; + shutdown(); + super.processWindowEvent(aEvent); + } + } + + + + /** + * Here we can react for System.exit() normally. + * But we use it for disposing() or windowClosing() too. + */ + public void shutdown() + { + if (mbDead) + return; + mbDead=true; + + // force these sub view to release her remote + // references too! + maStatusView.shutdown(); + maCustomizeView.shutdown(); + + maStatusView = null; + maCustomizeView = null; + + // disable all interceptions + maInterceptor.shutdown(); + maInterceptor = null; + + // close the frame and his document + // Releasing of our listener connections for disposing() + // will be forced automatically then. Because the frame + // will call us back ... + if (mxFrame!=null) + FunctionHelper.closeFrame(mxFrame); + + // deregister this view in the global container + // Normally we should die afterwards by garbage collection ... + // In cease this was the last view - it force a system.exit(). + // But then we are no longer a member of the global container + // of possible shutdown listener ... and this method should be + // called again. + ViewContainer.getGlobalContainer().removeView(this); + } + + + + /** + * callback from our internal saved frame + * which wishes to die. It's not necessary to remove listener connections + * here. Because the broadcaster do it automatically. + * We have to release all references to him only. + * + * @param aSource + * describe the broadcaster of this event + * Must be our internal saved frame. + */ + public void disposing(com.sun.star.lang.EventObject aSource) + { + mxFrame = null; + } + + + + /** + * This inner class is used to react for events of our own UI controls. + * So we can start different actions then. + */ + private class Reactor implements ActionListener + { + + + /** + * This method react for pressed buttons or selected check boxes. + */ + public void actionPerformed(ActionEvent aEvent) + { + String sCommand = aEvent.getActionCommand(); + + // open any file from disk + if( sCommand.equals(COMMAND_OPEN) ) + { + String sURL = FunctionHelper.askUserForFileURL(DocumentView.this,true); + if(sURL!=null) + DocumentView.this.load(sURL); + } + else + + // save current document + if( sCommand.equals(COMMAND_SAVE) ) + { + DocumentView.this.save(); + } + else + + // export current document to html + if( sCommand.equals(COMMAND_EXPORT)) + { + String sURL = FunctionHelper.askUserForFileURL(DocumentView.this,false); + if(sURL!=null) + DocumentView.this.exportHTML(sURL); + } + else + + // exit application + if( sCommand.equals(COMMAND_EXIT) ) + { + // This will force deleting of this and + // all other currently opened views automatically! + System.exit(0); + } + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/FunctionHelper.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/FunctionHelper.java new file mode 100644 index 000000000..fa24cde96 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/FunctionHelper.java @@ -0,0 +1,939 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.AnyConverter; + +import java.awt.*; +import javax.swing.*; +import java.io.*; +import java.net.*; + +// __________ Implementation __________ + +/** + * Is a collection of basic features. + * This helper shows different functionality of framework api + * in an example manner. You can use the follow ones: + * (1) parse URL's + * (2) create frames (inside/outside a java application) + * (3) dispatches (with[out] notifications) + * (4) loading/saving documents + * (5) convert documents to HTML (if possible) + * (6) close documents (and her frames) correctly + * + * There exist some other helper functionality too, which + * doesn't use or demonstrate the office api: + * (a) getting file names by using a file chosser + */ +public class FunctionHelper +{ + + + /** + * This convert a URL (formatted as a string) to a struct com.sun.star.util.URL. + * It use a special service to do that: the URLTransformer. + * Because some API calls need it and it's not allowed to set "Complete" + * part of the util struct only. The URL must be parsed. + * + * @param sURL + * URL for parsing in string notation + * + * @return [com.sun.star.util.URL] + * URL in UNO struct notation + */ + public static com.sun.star.util.URL parseURL(String sURL) + { + com.sun.star.util.URL aURL = null; + + if (sURL==null || sURL.equals("")) + { + System.out.println("wrong using of URL parser"); + return null; + } + + try + { + com.sun.star.uno.XComponentContext xOfficeCtx = + OfficeConnect.getOfficeContext(); + + // Create special service for parsing of given URL. + com.sun.star.util.XURLTransformer xParser = + UnoRuntime.queryInterface( + com.sun.star.util.XURLTransformer.class, + xOfficeCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.util.URLTransformer", xOfficeCtx)); + + // Because it's an in/out parameter we must use an array of URL objects. + com.sun.star.util.URL[] aParseURL = new com.sun.star.util.URL[1]; + aParseURL[0] = new com.sun.star.util.URL(); + aParseURL[0].Complete = sURL; + + // Parse the URL + xParser.parseStrict(aParseURL); + + aURL = aParseURL[0]; + } + catch(com.sun.star.uno.RuntimeException exRuntime) + { + // Any UNO method of this scope can throw this exception. + // Reset the return value only. + } + catch(com.sun.star.uno.Exception exUno) + { + // "createInstance()" method of used service manager can throw it. + // Then it wasn't possible to get the URL transformer. + // Return default instead of really parsed URL. + } + + return aURL; + } + + + + /** + * create a new empty target frame + * Attention: Currently we must use special service com.sun.star.frame.Task instead of Frame. + * Because desktop environment accept this special frame type only as direct children. + * Note - This service will be deprecated and must be replaces by com.sun.star.frame.Frame in + * further versions. To feature prove we use both service names. If for new versions + * the deprecated one not exist we get an empty frame, we can try to use the new service. + * + * @param xSMGR + * we need the remote service manager to create this task/frame service + * + * @return [com.sun.star.frame.XFrame] + * the new created frame reference in case of success or null otherwise + */ + private static com.sun.star.frame.XFrame impl_createEmptyFrame( + com.sun.star.uno.XComponentContext xCtx ) + { + com.sun.star.frame.XFrame xFrame = null; + + try{ + xFrame = UnoRuntime.queryInterface( + com.sun.star.frame.XFrame.class, + xCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.frame.Task", xCtx)); + } catch(com.sun.star.uno.Exception ex1) {} + + if (xFrame==null) + { + try{ + xFrame = UnoRuntime.queryInterface( + com.sun.star.frame.XFrame.class, + xCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.frame.Frame", xCtx)); + } catch(com.sun.star.uno.Exception ex2) {} + } + + return xFrame; + } + + + + /** + * create a new window which can be used as container window of an office frame + * We know two modes for creation: + * - the office window will be a child of one of our java windows + * - the office will be a normal system window outside this java application + * This behaviour will be regulated by the second parameter of this operation. + * If a parentview is given the first mode will be activated - otherwise + * the second one. + * + * Note: First mode (creation of a child window) can be reached by two different + * ways. + * - pack the required window handle of our java window inside a UNO object + * to transport it to the remote office toolkit and get a child office + * window. + * This is the old way. It's better to use the second one - but to be + * future prove this old one should be tried too. + * - it's possible to pass the native window handle directly to the toolkit. + * A special interface method was enabled to accept that. + * + * The right way to create an office window should be then: + * - try to use second creation mode (directly using of the window handle) + * - if it failed ... use the old way by packing the handle inside an object + * + * @param xSMGR + * we need a service manager to be able to create remote office + * services + * + * @param aParentView + * the java window as parent for the office window if an inplace office + * is required. If it is set to null the created office window will be + * a normal system window outside of our java application. + * + * @return [com.sun.star.awt.XWindow] + * The new created office window which can be used to set it as + * a ContainerWindow on an empty office frame. + */ + private static com.sun.star.awt.XWindow impl_createWindow( + com.sun.star.uno.XComponentContext xCtx, NativeView aParentView ) + { + com.sun.star.awt.XWindow xWindow = null; + com.sun.star.awt.XWindowPeer xPeer = null; + com.sun.star.awt.XToolkit xToolkit = null; + + // get access to toolkit of remote office to create the container window of + // new target frame + try{ + xToolkit = UnoRuntime.queryInterface( + com.sun.star.awt.XToolkit.class, + xCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.awt.Toolkit", xCtx)); + } + catch(com.sun.star.uno.Exception ex) + { + return null; + } + + // mode 1) create an external system window + if (aParentView==null) + { + // Describe the properties of the container window. + com.sun.star.awt.WindowDescriptor aDescriptor = + new com.sun.star.awt.WindowDescriptor(); + aDescriptor.Type = com.sun.star.awt.WindowClass.TOP; + aDescriptor.WindowServiceName = "window"; + aDescriptor.ParentIndex = -1; + aDescriptor.Parent = null; + aDescriptor.Bounds = new com.sun.star.awt.Rectangle(0,0,0,0); + aDescriptor.WindowAttributes = com.sun.star.awt.WindowAttribute.BORDER | + com.sun.star.awt.WindowAttribute.MOVEABLE | + com.sun.star.awt.WindowAttribute.SIZEABLE | + com.sun.star.awt.WindowAttribute.CLOSEABLE; + + try{ + xPeer = xToolkit.createWindow( aDescriptor ); + } catch(com.sun.star.lang.IllegalArgumentException exIllegal) {} + } + // mode 2) create an internal office window as child of our given java + // parent window + else + { + // try new version of creation first: directly using of the window + // handle. The old implementation of the corresponding toolkit method + // requires a process ID. If this id isn't the right one a null object + // is returned. But normally nobody outside the office knows this id. + // New version of this method ignore the id parameter and creation will + // work. + // Note: You must be sure if your window handle can be really used by + // the remote office. Means if this java client and the remote office + // use the same display! + com.sun.star.awt.XSystemChildFactory xChildFactory = + UnoRuntime.queryInterface( + com.sun.star.awt.XSystemChildFactory.class, xToolkit); + + try + { + Integer nHandle = aParentView.getHWND(); + short nSystem = (short)aParentView.getNativeWindowSystemType(); + byte[] lProcID = new byte[0]; + + xPeer = xChildFactory.createSystemChild(nHandle, + lProcID, nSystem); + + if (xPeer==null) + { + // mode 3) OK - new version doesn't work. It requires the + // process id which we don't have. + // So we must use the old way to get the right window peer. + // Pack the handle inside a wrapper object. + JavaWindowPeerFake aWrapper = new + JavaWindowPeerFake(aParentView); + + com.sun.star.awt.XWindowPeer xParentPeer = + UnoRuntime.queryInterface( + com.sun.star.awt.XWindowPeer.class, aWrapper); + + com.sun.star.awt.WindowDescriptor aDescriptor = + new com.sun.star.awt.WindowDescriptor(); + aDescriptor.Type = com.sun.star.awt.WindowClass.TOP; + aDescriptor.WindowServiceName = "workwindow"; + aDescriptor.ParentIndex = 1; + aDescriptor.Parent = xParentPeer; + aDescriptor.Bounds = new com.sun.star.awt.Rectangle(0,0,0,0); + if (nSystem == com.sun.star.lang.SystemDependent.SYSTEM_WIN32) + aDescriptor.WindowAttributes = + com.sun.star.awt.WindowAttribute.SHOW; + else + aDescriptor.WindowAttributes = + com.sun.star.awt.WindowAttribute.SYSTEMDEPENDENT; + + try{ + xPeer = xToolkit.createWindow( aDescriptor ); + } catch(com.sun.star.lang.IllegalArgumentException exIllegal) {} + } + } + catch(java.lang.RuntimeException exJRun) + { + // This exception is thrown by the native JNI code if it try to get + // the systemw window handle. A possible reason can be an invisible + // java window. In this case it should be enough to set return + // values to null. All other resources (which was created before) + // will be freed automatically if scope will be leaved. + System.out.println("May be the NativeView object wasn't really visible at calling time of getNativeWindow()?"); + xPeer = null; + xWindow = null; + } + } + + // It doesn't matter which way was used to get the window peer. + // Cast it to the right return interface and return it. + xWindow = UnoRuntime.queryInterface( + com.sun.star.awt.XWindow.class, + xPeer); + + return xWindow; + } + + + + /** + * This method create a new empty child frame on desktop instance of remote office. + * It use a special JNI functionality to pass the office XWindow over a java window. + * This java window can be inserted into another java window container for complex layouting. + * If this parent java window isn't used, a top level system window will be created. + * The resulting office frame isn't plugged into this java application. + * + * @param sName + * name to set it on the new created frame + * + * @param aParentView + * java window which should be used as parent window of new created office frame window + * May be set to null. + * + * @return [com.sun.star.frame.XFrame] + * reference to the new created frame for success or null if it failed + */ + public static com.sun.star.frame.XFrame createViewFrame(String sName, NativeView aParentView) + { + com.sun.star.frame.XFrame xFrame = null; + + try + { + com.sun.star.uno.XComponentContext xCtx = + OfficeConnect.getOfficeContext(); + + // create an empty office frame first + xFrame = impl_createEmptyFrame(xCtx); + + // create an office window then + // Depending from the given parameter aParentView it will be a child or a top level + // system window. (see impl method for further information) + // But before we call this helper - prepare the possible parent window: show it. + // JNI calls to get system window handle of java window can't work without that! + if (aParentView!=null) + aParentView.setVisible(true); + com.sun.star.awt.XWindow xWindow = impl_createWindow(xCtx, aParentView); + + // pass the window the frame as his new container window. + // It's necessary to do it first - before you call anything else there. + // Otherwise the frame throws some exceptions for "uninitialized state". + xFrame.initialize( xWindow ); + + // Insert the new frame in desktop hierarchy. + // Use XFrames interface to do so. It provides access to the child frame container of that instance. + com.sun.star.frame.XFramesSupplier xTreeRoot = UnoRuntime.queryInterface( + com.sun.star.frame.XFramesSupplier.class, + xCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.frame.Desktop", xCtx)); + com.sun.star.frame.XFrames xChildContainer = xTreeRoot.getFrames(); + xChildContainer.append(xFrame); + + // Make some further initializations on frame and window. + xWindow.setVisible(true); + xFrame.setName(sName); + } + catch(com.sun.star.uno.RuntimeException exRuntime) + { + // Any UNO method of this scope can throw this exception. + // So the frame can be already created and he must be freed + // correctly. May be he was inserted into the desktop tree too ... + if(xFrame!=null) + { + // Try to dispose the frame. He should deregister himself at the desktop object + // and free all internal used resources (e.g. the container window) automatically. + // It's possible to do that here - because frame has no component inside yet. + // So nobody can disagree with that. + // After the dispose() call forget all references to this frame and let him die. + // If a new exception will occur ... no general solution exist then. + // Nobody can guarantee if next call will work or not. + com.sun.star.lang.XComponent xComponent = UnoRuntime.queryInterface( + com.sun.star.lang.XComponent.class, + xFrame); + xComponent.dispose(); + xComponent = null; + xFrame = null; + } + } + catch(com.sun.star.uno.Exception exUno) + { + // "createInstance()" method of used service manager can throw it. + // If it occurred during creation of desktop service the frame already was created. + // Free it by decreasing his refcount. Changes on the desktop tree couldn't exist. + // Without the desktop service that wasn't possible. So no further rollbacks must follow. + if(xFrame!=null) + { + com.sun.star.lang.XComponent xComponent = UnoRuntime.queryInterface( + com.sun.star.lang.XComponent.class, + xFrame); + xComponent.dispose(); + xComponent = null; + xFrame = null; + } + } + + return xFrame; + } + + + + /** + * Dispatch a URL to given frame. + * Caller can register himself for following status events for dispatched + * URL too. But nobody guarantee that such notifications will occur. + * (see dispatchWithNotification() if you interest on that) + * The returned dispatch object should be hold alive by caller + * till he doesn't need it any longer. Otherwise the dispatcher can(!) + * die by decreasing his refcount. + * + * @param xFrame frame which should be the target of this dispatch + * @param aURL full parsed and converted office URL for dispatch + * @param lProperties optional arguments for dispatch + * @param xListener optional listener which is registered automatically for status events + * (Note: Deregistration is part of this listener himself!) + * + * @return [XDispatch] It's the used dispatch object and can be used for deregistration of an optional listener. + * Otherwise caller can ignore it. + */ + public static com.sun.star.frame.XDispatch execute(com.sun.star.frame.XFrame xFrame , + com.sun.star.util.URL aURL , + com.sun.star.beans.PropertyValue[] lProperties, + com.sun.star.frame.XStatusListener xListener ) + { + com.sun.star.frame.XDispatch xDispatcher = null; + + try + { + // Query the frame for right interface which provides access to all available dispatch objects. + com.sun.star.frame.XDispatchProvider xProvider = UnoRuntime.queryInterface( + com.sun.star.frame.XDispatchProvider.class, + xFrame); + + // Ask him for right dispatch object for given URL. + // Force given frame as target for following dispatch by using "". + // It means the same like "_self". + xDispatcher = xProvider.queryDispatch(aURL,"",0); + + // Dispatch the URL into the frame. + if(xDispatcher!=null) + { + if(xListener!=null) + xDispatcher.addStatusListener(xListener,aURL); + + xDispatcher.dispatch(aURL,lProperties); + } + } + catch(com.sun.star.uno.RuntimeException exUno) + { + // Any UNO method of this scope can throw this exception. + // But there will be nothing to do then - because + // we haven't changed anything inside the remote objects + // except method "addStatusListener(). + // But in this case the source of this exception has to + // rollback all his operations. There is no chance to + // make anything right then. + // Reset the return value to a default - that's it. + exUno.printStackTrace(); + xDispatcher = null; + } + + return xDispatcher; + } + + + + + + + + /** + * Load document specified by a URL into given frame synchronously. + * The result of this operation will be the loaded document for success + * or null if loading failed. + * + * @param xFrame frame which should be the target of this load call + * @param sURL unparsed URL for loading + * @param lProperties optional arguments + * + * @return [XComponent] the loaded document for success or null if it's failed + */ + public static com.sun.star.lang.XComponent loadDocument( + com.sun.star.frame.XFrame xFrame, String sURL, + com.sun.star.beans.PropertyValue[] lProperties) + { + com.sun.star.lang.XComponent xDocument = null; + String sOldName = null; + + try + { + com.sun.star.uno.XComponentContext xCtx = + OfficeConnect.getOfficeContext(); + + // First prepare frame for loading + // We must address it inside the frame tree without any complications. + // So we set an unambiguous (we hope it) name and use it later. + // Don't forget to reset original name after that. + sOldName = xFrame.getName(); + String sTarget = "odk_officedev_desk"; + xFrame.setName(sTarget); + + // Get access to the global component loader of the office + // for synchronous loading the document. + com.sun.star.frame.XComponentLoader xLoader = + UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, + xCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.frame.Desktop", xCtx)); + + // Load the document into the target frame by using his name and + // special search flags. + xDocument = xLoader.loadComponentFromURL( + sURL, + sTarget, + com.sun.star.frame.FrameSearchFlag.CHILDREN, + lProperties); + + // don't forget to restore old frame name... + xFrame.setName(sOldName); + } + catch(com.sun.star.io.IOException exIO) + { + // Can be thrown by "loadComponentFromURL()" call. + // The only thing we should do then is to reset changed frame name! + exIO.printStackTrace(); + xDocument = null; + if(sOldName!=null) + xFrame.setName(sOldName); + } + catch(com.sun.star.lang.IllegalArgumentException exIllegal) + { + // Can be thrown by "loadComponentFromURL()" call. + // The only thing we should do then is to reset changed frame name! + exIllegal.printStackTrace(); + xDocument = null; + if(sOldName!=null) + xFrame.setName(sOldName); + } + catch(com.sun.star.uno.RuntimeException exRuntime) + { + // Any UNO method of this scope can throw this exception. + // The only thing we can try(!) is to reset changed frame name. + exRuntime.printStackTrace(); + xDocument = null; + if(sOldName!=null) + xFrame.setName(sOldName); + } + catch(com.sun.star.uno.Exception exUno) + { + // "createInstance()" method of used service manager can throw it. + // The only thing we should do then is to reset changed frame name! + exUno.printStackTrace(); + xDocument = null; + if(sOldName!=null) + xFrame.setName(sOldName); + } + + return xDocument; + } + + + + /** + * Save currently loaded document of given frame. + * + * @param xDocument document for saving changes + */ + public static void saveDocument(com.sun.star.lang.XComponent xDocument) + { + try + { + // Check for supported model functionality. + // Normally the application documents (text, spreadsheet ...) do so + // but some other ones (e.g. db components) doesn't do that. + // They can't be save then. + com.sun.star.frame.XModel xModel = UnoRuntime.queryInterface( + com.sun.star.frame.XModel.class, + xDocument); + if(xModel!=null) + { + // Check for modifications => break save process if there is nothing to do. + com.sun.star.util.XModifiable xModified = UnoRuntime.queryInterface( + com.sun.star.util.XModifiable.class, + xModel); + if(xModified.isModified()) + { + com.sun.star.frame.XStorable xStore = UnoRuntime.queryInterface( + com.sun.star.frame.XStorable.class, + xModel); + + xStore.store(); + } + } + } + catch(com.sun.star.io.IOException exIO) + { + // Can be thrown by "store()" call. + // But there is nothing we can do then. + exIO.printStackTrace(); + } + catch(com.sun.star.uno.RuntimeException exUno) + { + // Any UNO method of this scope can throw this exception. + // But there is nothing we can do then. + exUno.printStackTrace(); + } + } + + + + /** + * It try to export given document in HTML format. + * Current document will be converted to HTML and moved to new place on disk. + * A "new" file will be created by given URL (may be overwritten + * if it already exist). Right filter will be used automatically if factory of + * this document support it. If no valid filter can be found for export, + * nothing will be done here. + * + * @param xDocument document which should be exported + * @param sURL target URL for converted document + */ + public static void saveAsHTML(com.sun.star.lang.XComponent xDocument, + String sURL ) + { + try + { + // First detect factory of this document. + // Ask for the supported service name of this document. + // If information is available it can be used to find out which + // filter exist for HTML export. Normally this filter should be searched + // inside the filter configuration but this little demo doesn't do so. + // (see service com.sun.star.document.FilterFactory for further + // information too) + // Well known filter names are used directly. They must exist in current + // office installation. Otherwise this code will fail. But to prevent + // this code against missing filters it check for existing state of it. + com.sun.star.lang.XServiceInfo xInfo = UnoRuntime.queryInterface(com.sun.star.lang.XServiceInfo.class, + xDocument); + + if(xInfo!=null) + { + // Find out possible filter name. + String sFilter = null; + if(xInfo.supportsService("com.sun.star.text.TextDocument")) + sFilter = "HTML (StarWriter)"; + else + if(xInfo.supportsService("com.sun.star.text.WebDocument")) + sFilter = "HTML"; + else + if(xInfo.supportsService("com.sun.star.sheet.SpreadsheetDocument")) + sFilter = "HTML (StarCalc)"; + + // Check for existing state of this filter. + if(sFilter!=null) + { + com.sun.star.uno.XComponentContext xCtx = + OfficeConnect.getOfficeContext(); + + com.sun.star.container.XNameAccess xFilterContainer = + UnoRuntime.queryInterface( + com.sun.star.container.XNameAccess.class, + xCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.document.FilterFactory", xCtx)); + + if(!xFilterContainer.hasByName(sFilter)) + sFilter=null; + } + + // Use this filter for export. + if(sFilter!=null) + { + // Export can be forced by saving the document and using a + // special filter name which can write needed format. Build + // necessary argument list now. + // Use special flag "Overwrite" too, to prevent operation + // against possible exceptions, if file already exist. + com.sun.star.beans.PropertyValue[] lProperties = + new com.sun.star.beans.PropertyValue[2]; + lProperties[0] = new com.sun.star.beans.PropertyValue(); + lProperties[0].Name = "FilterName"; + lProperties[0].Value = sFilter; + lProperties[1] = new com.sun.star.beans.PropertyValue(); + lProperties[1].Name = "Overwrite"; + lProperties[1].Value = Boolean.TRUE; + + com.sun.star.frame.XStorable xStore = + UnoRuntime.queryInterface( + com.sun.star.frame.XStorable.class, xDocument); + + xStore.storeAsURL(sURL,lProperties); + } + } + } + catch(com.sun.star.io.IOException exIO) + { + // Can be thrown by "store()" call. + // Do nothing then. Saving failed - that's it. + exIO.printStackTrace(); + } + catch(com.sun.star.uno.RuntimeException exRuntime) + { + // Can be thrown by any uno call. + // Do nothing here. Saving failed - that's it. + exRuntime.printStackTrace(); + } + catch(com.sun.star.uno.Exception exUno) + { + // Can be thrown by "createInstance()" call of service manager. + // Do nothing here. Saving failed - that's it. + exUno.printStackTrace(); + } + } + + + + + + + + /* + * Try to close the frame instead of the document. + * It shows the possible interface to do so. + * + * @param xFrame + * frame which should be closed + * + * @return in case frame could be closed + * otherwise + */ + public static boolean closeFrame(com.sun.star.frame.XFrame xFrame) + { + boolean bClosed = false; + + try + { + // first try the new way: use new interface XCloseable + // It replace the deprecated XTask::close() and should be preferred ... + // if it can be queried. + com.sun.star.util.XCloseable xCloseable = + UnoRuntime.queryInterface( + com.sun.star.util.XCloseable.class, xFrame); + if (xCloseable!=null) + { + // We deliver the ownership of this frame not to the (possible) + // source which throw a CloseVetoException. We wish to have it + // under our own control. + try + { + xCloseable.close(false); + bClosed = true; + } + catch( com.sun.star.util.CloseVetoException exVeto ) + { + bClosed = false; + } + } + else + { + // OK: the new way isn't possible. Try the old one. + com.sun.star.frame.XTask xTask = UnoRuntime.queryInterface(com.sun.star.frame.XTask.class, + xFrame); + if (xTask!=null) + { + // return value doesn't interest here. Because + // we forget this task ... + bClosed = xTask.close(); + } + } + } + catch (com.sun.star.lang.DisposedException exDisposed) + { + // Of course - this task can be already dead - means disposed. + // But for us it's not important. Because we tried to close it too. + // And "already disposed" or "closed" should be the same ... + bClosed = true; + } + + return bClosed; + } + + + + /** + * Try to find a unique frame name, which isn't currently used inside + * remote office instance. Because we create top level frames + * only, it's enough to check the names of existing child frames on the + * desktop only. + * + * should represent a unique frame name, which currently isn't + * used inside the remote office frame tree + * (Couldn't guaranteed for a real multithreaded environment. + * But we try it ...) + */ + private static final String BASEFRAMENAME = "Desk View "; + + public static String getUniqueFrameName() + { + String sName = null; + + com.sun.star.uno.XComponentContext xCtx = OfficeConnect.getOfficeContext(); + + try + { + com.sun.star.frame.XFramesSupplier xSupplier = + UnoRuntime.queryInterface( + com.sun.star.frame.XFramesSupplier.class, + xCtx.getServiceManager().createInstanceWithContext( + "com.sun.star.frame.Desktop", xCtx)); + + com.sun.star.container.XIndexAccess xContainer = + UnoRuntime.queryInterface( + com.sun.star.container.XIndexAccess.class, + xSupplier.getFrames()); + + int nCount = xContainer.getCount(); + for (int i=0; i + * dialog is opened in "file open" mode - + * otherwise in "file save" mode. + */ + public static String askUserForFileURL(Component aParent,boolean bOpen) + { + String sFileURL = null; + int nDecision = JFileChooser.CANCEL_OPTION; + JFileChooser aChooser = null; + + // set last visited directory on new file chosser + // (if this information is available) + if( maLastDir==null ) + aChooser = new JFileChooser(); + else + aChooser = new JFileChooser(maLastDir); + + // decide between file open/save dialog + if( bOpen ) + nDecision = aChooser.showOpenDialog(aParent); + else + nDecision = aChooser.showSaveDialog(aParent); + + // react for "OK" result only + if(nDecision == JFileChooser.APPROVE_OPTION) + { + // save current directory as last visited one + maLastDir = aChooser.getCurrentDirectory(); + // get file URL from the dialog + try + { + sFileURL = aChooser.getSelectedFile().toURI().toURL().toExternalForm(); + } + catch( MalformedURLException ex ) + { + ex.printStackTrace(); + sFileURL = null; + } + // problem of java: file URL's are coded with 1 slash instead of 3 ones! + // => correct this problem first, otherwise office can't use these URL's + if( + ( sFileURL !=null ) && + ( sFileURL.startsWith("file:/") ) && + ( !sFileURL.startsWith("file://") ) + ) + { + StringBuffer sWorkBuffer = new StringBuffer(sFileURL); + sWorkBuffer.insert(6,"//"); + sFileURL = sWorkBuffer.toString(); + } + } + + return sFileURL; + } + + + + /** + * @member maLastDir save the last visited directory of used file open/save dialog + * @member mnViewCount we try to set unique names on every frame we create (that's why we must count it) + */ + private static File maLastDir = null; + private static int mnViewCount = 0 ; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/IOnewayLink.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/IOnewayLink.java new file mode 100644 index 000000000..c6732155d --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/IOnewayLink.java @@ -0,0 +1,71 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.ArrayList; + +// __________ Implementation __________ + +/** + * We need a generic interface to forward any oneway uno interface method + * by using threads to the original object. Reason: + * It's not allowed to call synchronous back to the office if a java object + * was called in a oneway declared interface method. Then it must be + * executed asynchronous. To do so - a thread can be created which use this + * interface. It get the object, which has to be called back and the type and + * parameter of the original request. + * + */ +public interface IOnewayLink +{ + + + /** + * @param nRequest + * The two user of this callback can define a unique number, + * which identify the type of original interface method. So the called + * interface object can decide, which action will be necessary. + * + * @param lParams + * If the original method used parameters, they will be coded here in + * a generic way. Only the called interface object know (it depends + * from the original request - see nRequest too), how this list must + * be interpreted. + * Note: Atomic types (e.g. int, long) will be transported as objects + * too (Integer, Long)! + */ + void execOneway( int nRequest, ArrayList lParams ); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/IShutdownListener.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/IShutdownListener.java new file mode 100644 index 000000000..753d364d0 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/IShutdownListener.java @@ -0,0 +1,48 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Implementation __________ + +/** + * Listener interface to get information about application shutdown + * if java virtual machine dies. + * + */ +public interface IShutdownListener +{ + void shutdown(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Install.txt b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Install.txt new file mode 100644 index 000000000..79a1ee2bf --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Install.txt @@ -0,0 +1,10 @@ +(1) goto "./nativelib/" directory and build it +(2) build this directory +(3) expand your class path to include all jar files of an office installation + (means all files in path "/program/classes") +(4) goto "api//class" +(5) copy from an existing java installation the runtime library "jawt" (e.g. jawt.dll for windows) + into this directory +(6) copy "api//bin/nativelib.dll" (for windows) to "api//class" +(7) start an office : "soffice --accept=socket,host=localhost,port=2083;urp;" +(8) goto "api//class" and start java applet: "java -jar desktop.jar" diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Interceptor.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Interceptor.java new file mode 100644 index 000000000..380f8da3c --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Interceptor.java @@ -0,0 +1,655 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +// Imports + +import java.util.ArrayList; + +import com.sun.star.frame.FrameActionEvent; +import com.sun.star.uno.UnoRuntime; + +// Implementation + +/* + * This class can be used to intercept dispatched URL's + * on any frame used in this demo application. + * It intercept all URL's which try to create a new empty frame. + * (e.g. "private:factory/swriter") + * Nobody can guarantee that this interception will be really used - + * because another interceptor (registered at a later time then this one!) + * will be called before this one. + * Implementation is executed inside a new thread to prevent application + * against possible deadlocks. This deadlocks can occur if + * synchronous/asynchronous ... normal ones and oneway calls are mixed. + * Notifications of listener will be oneway mostly - her reactions can + * be synchronous then. => deadlocks are possible + */ +public class Interceptor implements com.sun.star.frame.XFrameActionListener, + com.sun.star.frame.XDispatchProviderInterceptor, + com.sun.star.frame.XDispatch, + com.sun.star.frame.XInterceptorInfo, + IShutdownListener, + IOnewayLink +{ + + + /** + * const + * All these URL's are intercepted by this implementation. + */ + private static final String[] INTERCEPTED_URLS = { "private:factory/*" , + ".uno:SaveAs" , + "slot:5300" , + ".uno:Quit" }; + + + + /* + * @member m_xMaster use this interceptor if he doesn't handle queried dispatch request + * @member m_xSlave we can forward all unhandled requests to this slave interceptor + * @member m_xFrame intercepted frame + * @member m_bDead there exist more than one way to finish an object of this class - we must know it sometimes + */ + private com.sun.star.frame.XDispatchProvider m_xMaster ; + private com.sun.star.frame.XDispatchProvider m_xSlave ; + private com.sun.star.frame.XFrame m_xFrame ; + private boolean m_bIsActionListener ; + private boolean m_bIsRegistered ; + private boolean m_bDead ; + + + + /* + * ctor + * Initialize the new interceptor. Given frame reference can be used to + * register this interceptor on it automatically later. + * + * @seealso startListening() + * + * @param xFrame + * this interceptor will register himself at this frame to intercept dispatched URLs + */ + Interceptor(/*IN*/ com.sun.star.frame.XFrame xFrame) + { + m_xFrame = xFrame ; + m_xSlave = null ; + m_xMaster = null ; + m_bIsRegistered = false ; + m_bIsActionListener = false ; + m_bDead = false ; + } + + + + /* + * start working as frame action listener really. + * We will be frame action listener here. In case + * we get a frame action which indicates, that we should + * update our interception. Because such using of an interceptor + * isn't guaranteed - in case a newer one was registered... + */ + public void startListening() + { + com.sun.star.frame.XFrame xFrame = null; + synchronized(this) + { + if (m_bDead) + return; + if (m_xFrame==null) + return; + if (m_bIsActionListener) + return; + xFrame = m_xFrame; + } + m_xFrame.addFrameActionListener(this); + synchronized(this) + { + m_bIsActionListener=true; + } + } + + + + /* + * In case we got a oneway listener callback - we had to use the office + * asynchronous then. This method is the callback from the started thread + * (started inside the original oneway method). We found all parameters of + * the original request packed inside a vector. Here we unpack it and + * call the right internal helper method, which implements the right + * functionality. + * + * @seealso frameAction() + * @seealso dispatch() + * + * @param nRequest + * indicates, which was the original request (identifies the + * original called method) + * + * @param lParams + * the vector with all packed parameters of the original request + */ + public void execOneway(/*IN*/ int nRequest,/*IN*/ ArrayList lParams ) + { + synchronized(this) + { + if (m_bDead) + return; + } + + // was it frameAction()? + if (nRequest==OnewayExecutor.REQUEST_FRAMEACTION) + { + impl_frameAction((FrameActionEvent) lParams.get(0)); + } + else + // was it dispatch()? + if (nRequest==OnewayExecutor.REQUEST_DISPATCH) + { + com.sun.star.util.URL[] lOutURL = new com.sun.star.util.URL[1]; + com.sun.star.beans.PropertyValue[][] lOutProps = new com.sun.star.beans.PropertyValue[1][]; + + OnewayExecutor.decodeDispatch( + lParams , + lOutURL , + lOutProps ); + impl_dispatch(lOutURL[0],lOutProps[0]); + } + } + + + + /* + * callback for frame action events + * We use it to update our interception. Because if a new component was loaded into + * the frame or another interceptor was registered, we should refresh our connection + * to the frame. Otherwise we can't guarantee full functionality here. + * + * Note: Don't react synchronous in an asynchronous listener callback. So use a thread + * here to update anything. + * + * @seealso impl_frameAction() + * + * @param aEvent + * describes the action + */ + public /*ONEWAY*/ void frameAction(/*IN*/ com.sun.star.frame.FrameActionEvent aEvent) + { + synchronized(this) + { + if (m_bDead) + return; + } + + boolean bHandle = false; + switch(aEvent.Action.getValue()) + { + case com.sun.star.frame.FrameAction.COMPONENT_ATTACHED_value : bHandle=true; break; + case com.sun.star.frame.FrameAction.COMPONENT_DETACHING_value : bHandle=true; break; + case com.sun.star.frame.FrameAction.COMPONENT_REATTACHED_value : bHandle=true; break; + // Don't react for CONTEXT_CHANGED here. Ok it indicates, that may another interceptor + // was registered at the frame ... but if we register ourself there - we get a context + // changed too :-( Best way to produce a never ending recursion ... + // May be that somewhere find a safe mechanism to detect own produced frame action events + // and ignore it. + case com.sun.star.frame.FrameAction.CONTEXT_CHANGED_value : + System.out.println("Time to update interception ... but may it will start a recursion. So I let it :-("); + bHandle=false; + break; + } + + // ignore some events + if (! bHandle) + return; + + // pack the event and start thread - which call us back later + ArrayList lOutParams = new ArrayList(); + lOutParams.add(aEvent); + + OnewayExecutor aExecutor = new OnewayExecutor( this , + OnewayExecutor.REQUEST_FRAMEACTION , + lOutParams ); + aExecutor.start(); + } + + + + /* + * Indicates using of us as an interceptor. + * Now we have to react for the requests, we are registered. + * That means: load new empty documents - triggered by the new menu of the office. + * Because it's oneway - use thread for loading! + * + * @seealso impl_dispatch() + * + * @param aURL + * describes the document, which should be loaded + * + * @param lArguments + * optional parameters for loading + */ + public /*ONEWAY*/ void dispatch(/*IN*/ com.sun.star.util.URL aURL,/*IN*/ com.sun.star.beans.PropertyValue[] lArguments) + { + synchronized(this) + { + if (m_bDead) + return; + } + + com.sun.star.util.URL[] lInURL = new com.sun.star.util.URL[1]; + com.sun.star.beans.PropertyValue[][] lInArguments = new com.sun.star.beans.PropertyValue[1][]; + lInURL[0] = aURL ; + lInArguments[0] = lArguments; + + ArrayList lOutParams = OnewayExecutor.encodeDispatch( + lInURL , + lInArguments ); + OnewayExecutor aExecutor = new OnewayExecutor( this , + OnewayExecutor.REQUEST_DISPATCH , + lOutParams ); + aExecutor.start(); + } + + + + + /* + * Internal callback for frame action events, triggered by the used + * OnewayExecutor thread we started in frameAction(). + * We use it to update our interception on the internal saved frame. + * + * @param aEvent + * describes the action + */ + private void impl_frameAction(/*IN*/ com.sun.star.frame.FrameActionEvent aEvent) + { + synchronized(this) + { + if (m_bDead) + return; + } + + // deregistration will be done every time... + // But may it's not necessary to establish a new registration! + // Don't look for ignoring actions - it was done already inside original frameAction() call! + boolean bRegister = false; + + // analyze the event and decide which reaction is useful + switch(aEvent.Action.getValue()) + { + case com.sun.star.frame.FrameAction.COMPONENT_ATTACHED_value : bRegister = true ; break; + case com.sun.star.frame.FrameAction.COMPONENT_REATTACHED_value : bRegister = true ; break; + case com.sun.star.frame.FrameAction.COMPONENT_DETACHING_value : bRegister = false; break; + } + + com.sun.star.frame.XFrame xFrame = null ; + boolean bIsRegistered = false; + synchronized(this) + { + bIsRegistered = m_bIsRegistered; + m_bIsRegistered = false; + xFrame = m_xFrame; + } + + com.sun.star.frame.XDispatchProviderInterception xRegistration = UnoRuntime.queryInterface( + com.sun.star.frame.XDispatchProviderInterception.class, + xFrame); + + if(xRegistration==null) + return; + + if (bIsRegistered) + xRegistration.releaseDispatchProviderInterceptor(this); + + if (! bRegister) + return; + + xRegistration.registerDispatchProviderInterceptor(this); + synchronized(this) + { + m_bIsRegistered = true; + } + } + + + + /* + * Implementation of interface XDispatchProviderInterceptor + * These functions are used to build a list of interceptor objects + * connected in both ways. + * Searching for a right interceptor is made by forwarding any request + * from toppest master to lowest slave of this hierarchy. + * If an interceptor wish to handle the request he can break that + * and return himself as a dispatcher. + */ + public com.sun.star.frame.XDispatchProvider getSlaveDispatchProvider() + { + synchronized(this) + { + return m_xSlave; + } + } + + + + public void setSlaveDispatchProvider(com.sun.star.frame.XDispatchProvider xSlave) + { + synchronized(this) + { + m_xSlave = xSlave; + } + } + + + + public com.sun.star.frame.XDispatchProvider getMasterDispatchProvider() + { + synchronized(this) + { + return m_xMaster; + } + } + + + + public void setMasterDispatchProvider(com.sun.star.frame.XDispatchProvider xMaster) + { + synchronized(this) + { + m_xMaster = xMaster; + } + } + + + + /* + * Implementation of interface XDispatchProvider + * These functions are called from our master if he will not handle the outstanding request. + * Given parameter should be checked if they are right for us. If it's true, the returned + * dispatcher should be this implementation himself; otherwise call should be forwarded + * to the slave. + * + * @param aURL + * describes the request, which should be handled + * + * @param sTarget + * specifies the target frame for this request + * + * @param nSearchFlags + * optional search flags, if sTarget isn't a special one + * + * @return [XDispatch] + * a dispatch object, which can handle the given URL + * May be NULL! + */ + public com.sun.star.frame.XDispatch queryDispatch(/*IN*/ com.sun.star.util.URL aURL,/*IN*/ String sTarget,/*IN*/ int nSearchFlags) + { + synchronized(this) + { + if (m_bDead) + return null; + } + + // intercept loading empty documents into new created frames + if( + (sTarget.compareTo ("_blank" ) == 0 ) && + (aURL.Complete.startsWith("private:factory")) + ) + { + System.out.println("intercept private:factory"); + return this; + } + + // intercept opening the SaveAs dialog + if (aURL.Complete.startsWith(".uno:SaveAs")) + { + System.out.println("intercept SaveAs by returning null!"); + return null; + } + + // intercept "File->Exit" inside the menu + if ( + (aURL.Complete.startsWith("slot:5300")) || + (aURL.Complete.startsWith(".uno:Quit")) + ) + { + System.out.println("intercept File->Exit"); + return this; + } + + synchronized(this) + { + if (m_xSlave!=null) + return m_xSlave.queryDispatch(aURL, sTarget, nSearchFlags); + } + + return null; + } + + + + public com.sun.star.frame.XDispatch[] queryDispatches(/*IN*/ com.sun.star.frame.DispatchDescriptor[] lDescriptor) + { + synchronized(this) + { + if (m_bDead) + return null; + } + // Resolve any request separately by using own "dispatch()" method. + // Note: Don't pack return list if "null" objects occur! + int nCount = lDescriptor.length; + com.sun.star.frame.XDispatch[] lDispatcher = new com.sun.star.frame.XDispatch[nCount]; + for(int i=0; iClass to pass the system window handle to the OpenOffice.org toolkit.

+ */ +class JavaWindowPeerFake implements com.sun.star.awt.XSystemDependentWindowPeer, + com.sun.star.awt.XWindowPeer +{ + private final NativeView maView; + + public JavaWindowPeerFake(NativeView aNative) + { + maView = aNative; + } + + + /** + * Implementation of XSystemDependentWindowPeer (that's all we really need). + * This method is called back from the Office toolkit to retrieve the system data. + */ + public java.lang.Object getWindowHandle(byte[] aProcessId, short aSystem) + throws com.sun.star.uno.RuntimeException + { + Object aReturn = null; + if(aSystem==maView.maSystem) + aReturn = maView.maHandle; + return aReturn; + } + + /** not really needed. + */ + public com.sun.star.awt.XToolkit getToolkit() + throws com.sun.star.uno.RuntimeException + { + return null; + } + + public void setPointer(com.sun.star.awt.XPointer xPointer) + throws com.sun.star.uno.RuntimeException + { + } + + public void setBackground(int nColor) + throws com.sun.star.uno.RuntimeException + { + } + + public void invalidate(short nFlags) + throws com.sun.star.uno.RuntimeException + { + } + + public void invalidateRect(com.sun.star.awt.Rectangle aRect,short nFlags) + throws com.sun.star.uno.RuntimeException + { + } + + public void dispose() + throws com.sun.star.uno.RuntimeException + { + } + + public void addEventListener(com.sun.star.lang.XEventListener xListener) + throws com.sun.star.uno.RuntimeException + { + } + + public void removeEventListener(com.sun.star.lang.XEventListener xListener) + throws com.sun.star.uno.RuntimeException + { + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Makefile b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Makefile new file mode 100644 index 000000000..b4179de72 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/Makefile @@ -0,0 +1,131 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OfficeDevDestopEnvironment example of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=OfficeDevDesktopEnv +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +APP1_NAME=DesktopExample +APP1_JAR=$(OUT_APP_CLASS)/$(APP1_NAME).jar + +APP1_JAVAFILES = \ + CustomizeView.java \ + Desk.java \ + DocumentView.java \ + FunctionHelper.java \ + Interceptor.java \ + IOnewayLink.java \ + IShutdownListener.java \ + JavaWindowPeerFake.java \ + NativeView.java \ + OfficeConnect.java \ + OnewayExecutor.java \ + StatusListener.java \ + StatusView.java \ + ViewContainer.java + +APP1_CLASSFILES = $(patsubst %.java,$(OUT_APP_CLASS)/%.class,$(APP1_JAVAFILES)) +APP1_CLASSNAMES = $(patsubst %.java,%.class,$(APP1_JAVAFILES)) \ + CustomizeView$(QUOTE)$$ClickListener.class \ + DocumentView$(QUOTE)$$*.class + + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + +ifeq "$(OS)" "WIN" +SUBDIR= nativelib/windows +else +SUBDIR= nativelib/unix +endif + +# Targets +.PHONY: ALL +ifeq "$(OS)" "MACOSX" +ALL : + @printf 'This example does not work on macOS\n' +else +ALL : $(SUBDIR) \ + $(EXAMPLE_NAME) +endif + +include $(SETTINGS)/stdtarget.mk + +.PHONY : $(SUBDIR) +$(SUBDIR) : + $(MAKE) -C $@ + +$(APP1_CLASSFILES) : $(APP1_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $(APP1_JAVAFILES) + +$(OUT_APP_CLASS)/$(APP1_NAME).mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: Desk>> $@ + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(APP1_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(APP1_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(EXAMPLE_NAME) : $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) DesktopExample.run + @echo ------ + @echo If you want to run the $(JAR1_JAR) file please set your + @echo CLASSPATH = $(SDK_CLASSPATH) + @echo Start the example with jar -jar $(JAR1_JAR) + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + $(MAKE) -C $(SUBDIR) clean + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/NativeView.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/NativeView.java new file mode 100644 index 000000000..273290e55 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/NativeView.java @@ -0,0 +1,186 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import java.awt.*; + +// __________ Implementation __________ + +/** + * Class to pass the system window handle to the OpenOffice.org toolkit. + * It use special JNI methods to get the system handle of used java window. + * + * Attention! + * Use JNI functions on already visible canvas objects only! + * Otherwise they can make some trouble. + * + */ + +public class NativeView extends java.awt.Canvas +{ + + + /** + * ctor + * Does nothing really. + * We can use our JNI mechanism for an already visible + * canvas only. So we override the method for showing ("setVisible()") + * and make our initialization there. But we try to show an empty clean + * window till there. + */ + public NativeView() + { + maHandle = null; + maSystem = 0; + this.setBackground(Color.white); + } + + + + /** + * Override this method to make necessary initializations here. + * (e.g. get the window handle and necessary system information) + * + * Why here? + * Because the handle seems to be available for already visible windows + * only. So it's the best place to get it. Special helper method + * can be called more than ones - but call native code one times only + * and safe the handle and the system type on our members maHandle/maSystem! + */ + @Override + public void setVisible(boolean bState) + { + getHWND(); + } + + + + /** + * to guarantee right resize handling inside a swing container + * (e.g. JSplitPane) we must provide some information about our + * preferred/minimum and maximum size. + */ + @Override + public Dimension getPreferredSize() + { + return new Dimension(500,300); + } + + @Override + public Dimension getMaximumSize() + { + return new Dimension(1024,768); + } + + @Override + public Dimension getMinimumSize() + { + return new Dimension(100,100); + } + + + + /** + * Override paint routine to show provide against + * repaint errors if no office view is really plugged + * into this canvas. + * If handle is present - we shouldn't paint anything further. + * May the remote window is already plugged. In such case we + * shouldn't paint it over. + */ + @Override + public void paint(Graphics aGraphic) + { + if(maHandle==null) + { + Dimension aSize = getSize(); + aGraphic.clearRect(0,0,aSize.width,aSize.height); + } + } + + + + /** + * JNI interface of this class + * These two methods are implemented by using JNI mechanismen. + * The will be used to get the platform dependent window handle + * of a java awt canvas. This handle can be used to create an office + * window as direct child of it. So it's possible to plug Office + * windows in a java UI container. + * + * Note: + * Native code for Windows registers a special function pointer to handle + * window messages... But if it doesn't check for an already-registered + * instance of this handler it will do it twice and produce a stack overflow + * because such method calls itself in a never-ending loop... + * So we try to use the JNI code one time only and save already-obtained + * information inside this class. + */ + public native int getNativeWindowSystemType(); + private native long getNativeWindow(); // private! => use getHWND() with cache mechanism! + + public Integer getHWND() + { + if(maHandle==null) + { + maHandle = Integer.valueOf((int)getNativeWindow()); + maSystem = getNativeWindowSystemType(); + } + return maHandle; + } + + + + /** + * for using of the JNI methods it's necessary to load + * system library which exports it. + */ + static + { + System.loadLibrary("nativeview"); + } + + + + /** + * @member maHandle system window handle + * @member maSystem info about currently used platform + */ + public Integer maHandle ; + public int maSystem ; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/OfficeConnect.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/OfficeConnect.java new file mode 100644 index 000000000..617e38047 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/OfficeConnect.java @@ -0,0 +1,127 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + + + +// __________ Implementation __________ + +/** + * support ONE singleton uno connection to a running office installation! + * Can be used to open/use/close connection to uno environment of an office. If + * necessary a new office instance is started. + * ctor isn't available from outside. You should call static function + * "getConnection()" to open or use internal set connection which is created one + * times only. + * + */ +public class OfficeConnect +{ + + + /** + * At first call we create static connection object and open connection to an + * office - a new office instance is started if necessary + * Then - and for all further requests we return these static connection member. + */ + public static synchronized void createConnection() + { + if (maConnection == null) + maConnection = new OfficeConnect(); + } + + + + + + + + /** + * ctor + * We try to open the connection in our ctor ... transparently for user. + * After it was successful you will find an internal set member + * m_xRemoteContext which means remote component context of the connected office. + * The context can be used to get the remote service manager from the office. + * We made it private to support singleton pattern of these implementation. + * see getConnection() for further information + */ + private OfficeConnect() + { + try + { + // get the remote office context. If necessary a new office + // process is started + mxOfficeContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + mxServiceManager = mxOfficeContext.getServiceManager(); + } + catch (java.lang.Exception ex) + { + System.err.println("connection failed" + ex); + ex.printStackTrace(System.err); + System.exit(1); + + } + } + + + + + + + + /** + * returns remote component context of the connected office + */ + public static synchronized com.sun.star.uno.XComponentContext getOfficeContext() + { + return mxOfficeContext; + } + + + + /** + * member + */ + // singleton connection instance + private static OfficeConnect maConnection; + + // reference to the office component context + private static com.sun.star.uno.XComponentContext mxOfficeContext; + // reference to remote service manager of singleton connection object + private static com.sun.star.lang.XMultiComponentFactory mxServiceManager; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/OnewayExecutor.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/OnewayExecutor.java new file mode 100644 index 000000000..4eb7f80a7 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/OnewayExecutor.java @@ -0,0 +1,189 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.ArrayList; + +// __________ Implementation __________ + +/** + * It's not allowed to call synchronous back inside a oneway interface call. + * (see IOnewayLink too). So we start a thread (implemented by this class), which + * gets all necessary parameters from the original called object and + * call it back later inside his run() method. So the execution of such oneway call + * will be asynchronous. It works in a generic way and can be used or any type + * of oneway request. Because the source and the target of this call-link knows, + * which method was used and which parameters must be handled. + * + */ +class OnewayExecutor extends Thread +{ + + + /** + * const + * We define some request for some well known oneway interface + * calls here too. So they mustn't be declared more than ones. + * Of course it's not necessary to use it ... but why not :-) + */ + + public static final int REQUEST_FRAMEACTION = 1 ; + + + + public static final int REQUEST_DISPATCH = 5 ; + + + + + + + /** + * @member m_rLink the object, which wishes to be called back by this thread + * @member m_nRequest describes the type of the original request (means the + * called oneway method) + * @member m_lParams list of parameters of the original request + */ + private final IOnewayLink m_rLink ; + private final int m_nRequest ; + private final ArrayList m_lParams ; + + + + /** + * ctor + * It's initialize this thread with all necessary parameters. + * It gets the object, which wishes to be called back and the type + * and parameters of the original request. + * + * @param nRequest + * The two user of this callback can define a unique number, + * which identify the type of original interface method. + * So the called interface object can decide, which action will be + * necessary. + * + * @param lParams + * If the original method used parameters, they will be coded here in + * a generic way. Only the called interface object know (it depends + * from the original request - see nRequest too), how this list must + * be interpreted. + * Note: Atomic types (e.g. int, long) will be transported as objects + * too (Integer, Long)! + */ + public OnewayExecutor( IOnewayLink rLink , + int nRequest , + ArrayList lParams ) + { + m_rLink = rLink ; + m_nRequest = nRequest; + m_lParams = lParams ; + + if (m_rLink==null) + System.out.println("ctor ... m_rLink == null"); + if (m_lParams==null) + System.out.println("ctor ... m_lParams == null"); + } + + + + /** + * implements the thread function + * Here we call the internal set link object back and + * give him all necessary parameters. + * After that we die by ourselves ... + */ + @Override + public void run() + { + if (m_rLink==null) + System.out.println("run ... m_rLink == null"); + if (m_lParams==null) + System.out.println("run ... m_lParams == null"); + + if (m_rLink!=null) + m_rLink.execOneway( m_nRequest, m_lParams ); + } + + + + /** + * static helper! + * To make conversion of the generic parameter list to the original + * one easier - you can use this helper methods. They know how such list + * must be coded. It's not a must to use it - but you can ... + */ + + + + public static ArrayList encodeDispatch( + com.sun.star.util.URL[] aURL, + com.sun.star.beans.PropertyValue[][] lArgs) + { + int nLength = lArgs.length+1; + int nPos = 0; + ArrayList lParams = new ArrayList(nLength); + + lParams.add( aURL[0] ); + --nLength; + + while (nLength>0) + { + lParams.add( lArgs[0][nPos] ); + --nLength; + ++nPos ; + } + return lParams; + } + + public static void decodeDispatch( + ArrayList lParams, + com.sun.star.util.URL[] aURL, + com.sun.star.beans.PropertyValue[][] lArgs) + { + int nLength = lParams.size()-1; + int nPos = 0; + + lArgs[0] = new com.sun.star.beans.PropertyValue[nLength]; + aURL[0] = (com.sun.star.util.URL) lParams.get(0); + + while (nPos lParams ) + { + synchronized(this) + { + if (m_bDead) + return; + } + // was it frameAction()? + if (nRequest==OnewayExecutor.REQUEST_FRAMEACTION) + { + impl_frameAction((FrameActionEvent) lParams.get(0)); + } + } + + + + /** + * This is the callback method for such frame action events, we listen for. + * Because it's a oneway method we start a thread as reaction. This thread call + * us back and we can do necessary things there. + * But we shouldn't start such action - if it's not really necessary. + * So we check before, if we are interested on this event really. + * + * @see #impl_frameAction + * + * @param aEvent + * describes the action, which triggered this event + */ + public /*ONEWAY*/ void frameAction(/*IN*/ com.sun.star.frame.FrameActionEvent aEvent) + { + synchronized(this) + { + if (m_bDead) + return; + } + boolean bHandle = false; + switch(aEvent.Action.getValue()) + { + case com.sun.star.frame.FrameAction.COMPONENT_ATTACHED_value : bHandle=true; break; + case com.sun.star.frame.FrameAction.COMPONENT_DETACHING_value : bHandle=true; break; + case com.sun.star.frame.FrameAction.COMPONENT_REATTACHED_value : bHandle=true; break; + case com.sun.star.frame.FrameAction.CONTEXT_CHANGED_value : bHandle=true; break; + } + + if (! bHandle) + return; + + ArrayList lOutParams = new ArrayList(); + lOutParams.add(aEvent); + + OnewayExecutor aExecutor = new OnewayExecutor( this , + OnewayExecutor.REQUEST_FRAMEACTION , + lOutParams ); + aExecutor.start(); + } + + + + /** + * This is the callback method for the status we listen for and wish to show it + * on our UI control. Of course it's a oneway method... but we don't call back + * to the office synchronously here. We update our UI only. So we don't leave this + * java process. In such case it's not necessary to use threads to decouple it. + * Do it here and now... + * + * @param aEvent + * describes the status, we can use to update our UI control + */ + public /*ONEWAY*/ void statusChanged(/*IN*/ com.sun.star.frame.FeatureStateEvent aEvent) + { + synchronized(this) + { + if (m_bDead) + return; + + // enable/disable the control. + // Means: if the feature isn't available currently - we can't show a status really here. + // Then we should colorize it gray... + m_rControl.setEnabled(aEvent.IsEnabled); + + // Only if status is enabled we can look for his value! + if (aEvent.IsEnabled) + { + // look for the right type of the UI control + // Following actions depend on it. + + + // it's a check box + if (m_rControl instanceof JCheckBox) + { + JCheckBox aBox = (JCheckBox)m_rControl; + + // State must be a boolean value too. Otherwise must + // ignore this event. + if ( ! (aEvent.State instanceof Boolean ) ) + return; + + boolean bState = ((Boolean)(aEvent.State)).booleanValue(); + aBox.setSelected(bState); + if (bState) + aBox.setText(m_sTrueText); + else + aBox.setText(m_sFalseText); + } + else + + // it's a label + if (m_rControl instanceof JLabel) + { + JLabel aLabel = (JLabel)m_rControl; + + // Detect type of state value + // and set it on internal well known UI control + // But do it only, if value really change. + if(aEvent.State instanceof String) + { + String sState = (String)aEvent.State; + aLabel.setText(sState); + } + else + if(aEvent.State instanceof Boolean) + { + boolean bState = ((Boolean)aEvent.State).booleanValue(); + if (bState) + aLabel.setText(m_sTrueText); + else + aLabel.setText(m_sFalseText); + } + else + if(aEvent.State instanceof Float) + { + String sState = ((Float)aEvent.State).toString(); + aLabel.setText(sState); + } + } + } + } + } + + + + /** + * Internal call back for frame action events, triggered by the used + * OnewayExecutor thread we started in frameAction(). + * We use it to update internal saved dispatch object and the corresponding + * listener connection for status events. + * + * @param aEvent + * describes the action + */ + private void impl_frameAction(/*IN*/ com.sun.star.frame.FrameActionEvent aEvent) + { + synchronized(this) + { + if (m_bDead) + return; + } + // Don't look for ignoring actions - it was done already inside original frameAction() call! + // deregistration as status listener will be done here every time - but registration only, if necessary! + boolean bRegister = false; + switch(aEvent.Action.getValue()) + { + case com.sun.star.frame.FrameAction.COMPONENT_ATTACHED_value : bRegister=true ; break; + case com.sun.star.frame.FrameAction.COMPONENT_DETACHING_value : bRegister=false; break; + case com.sun.star.frame.FrameAction.COMPONENT_REATTACHED_value : bRegister=true ; break; + case com.sun.star.frame.FrameAction.CONTEXT_CHANGED_value : bRegister=true ; break; + } + + boolean bIsStatusListener = false; + com.sun.star.frame.XFrame xFrame = null ; + com.sun.star.frame.XDispatch xDispatch = null ; + com.sun.star.util.URL aURL = null ; + synchronized(this) + { + bIsStatusListener = m_bIsStatusListener; + m_bIsStatusListener = false; + + xDispatch = m_xDispatch; + m_xDispatch = null; + + aURL = m_aURL; + xFrame = m_xFrame; + } + + if (bIsStatusListener) + xDispatch.removeStatusListener(this,aURL); + xDispatch = null; + + if (! bRegister) + return; + + com.sun.star.frame.XDispatchProvider xProvider = UnoRuntime.queryInterface( + com.sun.star.frame.XDispatchProvider.class, + xFrame); + + if (xProvider==null) + return; + + xDispatch = xProvider.queryDispatch(aURL,"",0); + + if (xDispatch==null) + return; + + xDispatch.addStatusListener(this,aURL); + synchronized(this) + { + m_xDispatch = xDispatch; + m_bIsStatusListener = true; + } + } + + + + /** + * callback for disposing events + * Our dispatch or frame object inform us about his following dead ... + * So we must forget his reference. But it's not necessary to + * remove listener connections here. Because the broadcaster + * forget us automatically. The only thing we have to do: release + * his reference and let him die! + * + * @param aEvent + * describes the source which fire this event + * Must be our internal saved dispatch or frame. Otherwise + * somewhere know us without a registration ... + */ + public /*ONEWAY*/ void disposing(/*IN*/ com.sun.star.lang.EventObject aEvent) + { + synchronized(this) + { + if (m_bDead) + return; + if (m_xFrame!=null && UnoRuntime.areSame(aEvent.Source,m_xFrame)) + { + m_bIsActionListener = false; + m_xFrame = null ; + } + else + if (m_xDispatch!=null && UnoRuntime.areSame(aEvent.Source,m_xDispatch)) + { + m_bIsStatusListener = false; + m_xDispatch = null ; + m_aURL = null ; + } + } + shutdown(); + } + + + + /** + * If this java application shutdown - we must cancel all current existing + * listener connections. Otherwise the office will run into some + * DisposedExceptions if it tries to use these forgotten listener references. + * And of course it can die doing that. + * We are registered at a central object to be informed if the VM will exit. + * So we can react. + */ + public void shutdown() + { + boolean bIsActionListener = false; + boolean bIsStatusListener = false; + com.sun.star.frame.XFrame xFrame = null ; + com.sun.star.frame.XDispatch xDispatch = null ; + com.sun.star.util.URL aURL = null ; + synchronized(this) + { + // don't react a second time here! + if (m_bDead) + return; + m_bDead = true; + + bIsActionListener = m_bIsActionListener; + m_bIsActionListener = false; + + bIsStatusListener = m_bIsStatusListener; + m_bIsStatusListener = false; + + xFrame = m_xFrame; + m_xFrame = null; + + xDispatch = m_xDispatch; + m_xDispatch = null; + + aURL = m_aURL; + m_aURL = null; + } + + if (bIsStatusListener) + xDispatch.removeStatusListener(this,aURL); + xDispatch = null ; + aURL = null ; + + if (bIsActionListener) + xFrame.removeFrameActionListener(this); + xFrame = null ; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/StatusView.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/StatusView.java new file mode 100644 index 000000000..92ae178ad --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/StatusView.java @@ -0,0 +1,264 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import java.awt.*; +import javax.swing.*; + +// __________ Implementation __________ + +/** + * Implement a view to show status information + * of currently loaded document of a document view. + * It uses separate listener threads to get this information + * and actualize it automatically, if frame broadcast changes of + * his contained document. + * Threads are necessary to prevent this view against deadlocks. + * These deadlocks can occur if a listener will be notified + * by the office in an "oneway" method and try to call back + * to the office by using a synchronous method. + * UNO must guarantee order of all these calls ... and if + * the source of arrived event holds a mutex and our synchronous + * call needs this mutex too => a deadlock occurs. + * Why? UNO had created a new thread for our synchronous call + * inside the office process and so exist different threads + * for this constellation. + * + */ +public class StatusView extends JPanel + implements IShutdownListener +{ + + + /** + * const + * These URL's describe available feature states. + */ + private static final String FEATUREURL_FONT = "slot:10007"; + private static final String FEATUREURL_SIZE = "slot:10015"; + private static final String FEATUREURL_BOLD = "slot:10009"; + private static final String FEATUREURL_ITALIC = "slot:10008"; + private static final String FEATUREURL_UNDERLINE = "slot:10014"; + + + + /** + * const + * These values are used to show current state of showed feature. + */ + private static final String FONT_OFF = "unknown" ; + private static final String SIZE_OFF = "0.0" ; + private static final String BOLD_OFF = "-" ; + private static final String ITALIC_OFF = "-" ; + private static final String UNDERLINE_OFF = "-" ; + + private static final String FONT_ON = "" ; + private static final String SIZE_ON = "" ; + private static final String BOLD_ON = "X" ; + private static final String ITALIC_ON = "X" ; + private static final String UNDERLINE_ON = "X" ; + + + + /** + * @member mlaFontValue shows status of font name + * @member mlaSizeValue shows status of font size + * @member mlaBoldValue shows status of font style bold + * @member mlaUnderlineValue shows status of font style underline + * @member mlaItalicValue shows status of font style italic + * + * @member maFontListener threadsafe(!) helper to listen for status event which describe font name + * @member maSizeListener threadsafe(!) helper to listen for status event which describe font size + * @member maBoldListener threadsafe(!) helper to listen for status event which describe font style bold + * @member maUnderlineListener threadsafe(!) helper to listen for status event which describe font style underline + * @member maItalicListener threadsafe(!) helper to listen for status event which describe font style italic + */ + private final JLabel m_laFontValue ; + private final JLabel m_laSizeValue ; + private final JLabel m_laBoldValue ; + private final JLabel m_laUnderlineValue ; + private final JLabel m_laItalicValue ; + + private StatusListener m_aFontListener ; + private StatusListener m_aSizeListener ; + private StatusListener m_aBoldListener ; + private StatusListener m_aUnderlineListener ; + private StatusListener m_aItalicListener ; + + + + /** + * ctor + * Create view controls on startup and initialize it with default values. + * Filling of view items can be done by special set-methods. + * We don't start listening here! see setFrame() for that ... + */ + StatusView() + { + this.setLayout(new GridBagLayout()); + + GridBagConstraints aConstraint = new GridBagConstraints(); + aConstraint.anchor = GridBagConstraints.NORTHWEST; + aConstraint.insets = new Insets(2,2,2,2); + aConstraint.gridy = 0; + aConstraint.gridx = 0; + + JLabel laFont = new JLabel("Font" ); + JLabel laSize = new JLabel("Size" ); + JLabel laBold = new JLabel("Bold" ); + JLabel laUnderline = new JLabel("Underline"); + JLabel laItalic = new JLabel("Italic" ); + + m_laFontValue = new JLabel(); + m_laSizeValue = new JLabel(); + m_laBoldValue = new JLabel(); + m_laUnderlineValue = new JLabel(); + m_laItalicValue = new JLabel(); + + aConstraint.gridx = 0; + this.add( laFont, aConstraint ); + aConstraint.gridx = 1; + this.add( m_laFontValue, aConstraint ); + + ++aConstraint.gridy; + + aConstraint.gridx = 0; + this.add( laSize, aConstraint ); + aConstraint.gridx = 1; + this.add( m_laSizeValue, aConstraint ); + + ++aConstraint.gridy; + + aConstraint.gridx = 0; + this.add( laSize, aConstraint ); + aConstraint.gridx = 1; + this.add( m_laSizeValue, aConstraint ); + + ++aConstraint.gridy; + + aConstraint.gridx = 0; + this.add( laBold, aConstraint ); + aConstraint.gridx = 1; + this.add( m_laBoldValue, aConstraint ); + + ++aConstraint.gridy; + + aConstraint.gridx = 0; + this.add( laUnderline, aConstraint ); + aConstraint.gridx = 1; + this.add( m_laUnderlineValue, aConstraint ); + + ++aConstraint.gridy; + + aConstraint.gridx = 0; + this.add( laItalic, aConstraint ); + aConstraint.gridx = 1; + this.add( m_laItalicValue, aConstraint ); + + m_laFontValue.setEnabled (false); + m_laSizeValue.setEnabled (false); + m_laBoldValue.setEnabled (false); + m_laItalicValue.setEnabled (false); + m_laUnderlineValue.setEnabled(false); + + m_laFontValue.setText (FONT_OFF ); + m_laSizeValue.setText (SIZE_OFF ); + m_laBoldValue.setText (BOLD_OFF ); + m_laItalicValue.setText (ITALIC_OFF ); + m_laUnderlineValue.setText(UNDERLINE_OFF); + } + + + + /* + * Set new frame for this view and start listening for events immediately. + * We create one status listener for every control we wish to update. + * And because the environment of the frame can be changed - these + * listener refresh himself internally for frame action events too. + * So we register it as such frame action listener only here. + * Rest is done automatically... + * + * @param xFrame + * will be used as source of possible status events + */ + public void setFrame(com.sun.star.frame.XFrame xFrame) + { + if (xFrame==null) + return; + + // create some listener on given frame for available status events + // Created listener instances will register themselves on this frame and + // show it received information automatically on set UI controls. + m_aFontListener = new StatusListener(m_laFontValue ,FONT_ON ,FONT_OFF ,xFrame, FEATUREURL_FONT ); + m_aSizeListener = new StatusListener(m_laSizeValue ,SIZE_ON ,SIZE_OFF ,xFrame, FEATUREURL_SIZE ); + m_aBoldListener = new StatusListener(m_laBoldValue ,BOLD_ON ,BOLD_OFF ,xFrame, FEATUREURL_BOLD ); + m_aItalicListener = new StatusListener(m_laItalicValue ,ITALIC_ON ,ITALIC_OFF ,xFrame, FEATUREURL_ITALIC ); + m_aUnderlineListener = new StatusListener(m_laUnderlineValue,UNDERLINE_ON,UNDERLINE_OFF,xFrame, FEATUREURL_UNDERLINE); + + m_aFontListener.startListening(); + m_aSizeListener.startListening(); + m_aBoldListener.startListening(); + m_aItalicListener.startListening(); + m_aUnderlineListener.startListening(); + } + + + + /** + * If this java application shutdown - we must cancel all current existing + * listener connections. Otherwise the office will run into some + * DisposedExceptions if it tries to use these forgotten listener references. + * And of course it can die doing that. + * We are registered at a central object to be informed if the VM will exit. + * So we can react. + */ + public void shutdown() + { + m_aFontListener.shutdown(); + m_aSizeListener.shutdown(); + m_aBoldListener.shutdown(); + m_aItalicListener.shutdown(); + m_aUnderlineListener.shutdown(); + + m_aFontListener = null; + m_aSizeListener = null; + m_aBoldListener = null; + m_aItalicListener = null; + m_aUnderlineListener = null; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/ViewContainer.java b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/ViewContainer.java new file mode 100644 index 000000000..d859f2035 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/ViewContainer.java @@ -0,0 +1,260 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import java.util.*; + +// __________ Implementation __________ + +/** + * It's implement a static container which hold + * all opened documents and her views alive. + * It's possible to register/deregister such views, + * to get information about these and it provides + * some global functionality - like termination of + * this demo application. + * + */ +public class ViewContainer extends Thread +{ + + + /** + * provides a singleton view container + * Necessary for terminate(9 functionality to be able + * to call Runtime.runFinilization(). + * + * @return a reference to the singleton ViewContainer instance + */ + public static synchronized ViewContainer getGlobalContainer() + { + if (maSingleton==null) + maSingleton=new ViewContainer(); + return maSingleton; + } + + + + /** + * ctor + * It's private - because nobody should create any instance + * expect the only global one, which will be created by ourself! + */ + private ViewContainer() + { + mlViews = new ArrayList(); + mlListener = new ArrayList(); + mbShutdownActive = false ; + Runtime.getRuntime().addShutdownHook(this); + } + + + + /** + * This register a new view inside this global container + * (if it doesn't already exist). + * + * @param aView view which wishes to be registered inside this container + */ + public void addView(Object aView) + { + synchronized(mlViews) + { + if(!mlViews.contains(aView)) + mlViews.add(aView); + } + } + + + + /** + * This deregister a view from this global container. + * Normally it should be the last reference to the view + * and her finalize() method should be called. + * If last view will be closed here - we terminate these + * java application too. Because there is no further + * visible frame anymore. + * + * @param aView + * view object which wishes to be deregistered + */ + public void removeView(Object aView) + { + int nViewCount = 0; + synchronized(mlViews) + { + if(mlViews.contains(aView)) + mlViews.remove(aView); + + nViewCount = mlViews.size(); + + if (nViewCount<1) + mlViews = null; + } + // If this view is a registered shutdown listener on this view container + // too, we must call his interface and forget him as possible listener. + // It's necessary to guarantee his dead ... + boolean bShutdownView = false; + synchronized(mlListener) + { + bShutdownView = mlListener.contains(aView); + if (bShutdownView) + mlListener.remove(aView); + } + if (bShutdownView) + ((IShutdownListener)aView).shutdown(); + + // We use a system.exit() to finish the whole application. + // And further we have registered THIS instance as a possible shutdown + // hook at the runtime class. So our run() method will be called. + // Our view container should be empty - but + // our listener container can include some references. + // These objects will be informed then and release e.g. some + // remote references. + if (nViewCount<1) + { + boolean bNecessary = false; + synchronized(this) + { + bNecessary = ! mbShutdownActive; + } + if (bNecessary) + { + System.out.println("call exit(0)!"); + System.exit(0); + } + } + } + + + + /** + * add/remove listener for possible shutdown events + */ + public void addListener( IShutdownListener rListener ) + { + synchronized(mlListener) + { + if ( ! mlListener.contains(rListener) ) + mlListener.add(rListener); + } + } + + + + private void removeListener( IShutdownListener rListener ) + { + synchronized(mlListener) + { + if ( mlListener.contains(rListener) ) + mlListener.remove(rListener); + } + } + + + + /** + * Is called from current runtime system of the java machine + * on shutdown. We inform all current registered listener and + * views. They should deinitialize her internal things then. + */ + @Override + public void run() + { + synchronized(this) + { + if (mbShutdownActive) + return; + mbShutdownActive=true; + } + + while( true ) + { + IShutdownListener aListener = null; + synchronized(mlListener) + { + if (!mlListener.isEmpty()) + aListener = mlListener.get(0); + } + if (aListener==null) + break; + + aListener.shutdown(); + // May this listener has deregistered himself. + // But if not we must do it for him. Our own + // method "removeListener()" ignore requests for + // already gone listener objects. + removeListener(aListener); + } + + if (mlViews!=null) + { + synchronized(mlViews) + { + mlViews.clear(); + mlViews = null; + } + } + + if (mlListener!=null) + { + synchronized(mlListener) + { + mlListener.clear(); + mlListener = null; + } + } + } + + + + /** + * @member mbInplace indicates using of inplace office frames instead of outplace ones + * @member maSingleton singleton instance of this view container + * @member mlViews list of all currently registered document views + * @member mlListener list of all currently registered shutdown listener + * @member mbShutdownActive if this shutdown hook already was started it's not a good idea to + * call System.exit() again for other conditions. + * We suppress it by using this variable! + */ + public static boolean mbInplace = false ; + private static ViewContainer maSingleton = null ; + private ArrayList mlViews ; + private ArrayList mlListener ; + private boolean mbShutdownActive ; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/Makefile b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/Makefile new file mode 100644 index 000000000..aa7a158b8 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/Makefile @@ -0,0 +1,72 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OfficeDevDesktopEnvironment native library of the Developers Guide. + +PRJ=../../../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SHL_NAME=nativeview +SHL_LIBRARY=$(SHAREDLIB_OUT)/$(SHAREDLIB_PRE)$(SHL_NAME).$(SHAREDLIB_EXT) + +OUT_SHL_SLO=$(OUT_SLO)/nativeview + +CFILES = nativeview.c + +SLOFILES = $(patsubst %.c,$(OUT_SHL_SLO)/%.$(OBJ_EXT),$(CFILES)) + + +# Targets +.PHONY: ALL +ALL : $(SHL_LIBRARY) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_SHL_SLO)/%.$(OBJ_EXT) : %.c + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS_JNI) $(CC_INCLUDES) $(SDK_JAVA_INCLUDES) $(CC_DEFINES_JNI) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +$(SHAREDLIB_OUT)/$(SHAREDLIB_PRE)$(SHL_NAME).$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(LIBRARY_LINK_FLAGS) $(LINK_LIBS) $(LINK_JAVA_LIBS) -o $@ $< \ + -ljawt $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STDC++LIB) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_SHL_SLO)) + -$(DEL) $(subst /,$(PS),$(SHAREDLIB_OUT))$(PS)*$(SHL_NAME)*.* diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/nativeview.c b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/nativeview.c new file mode 100644 index 000000000..7f4bc1472 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/nativeview.c @@ -0,0 +1,112 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include +#include + +#include "jawt.h" +#include "jawt_md.h" +#include "nativeview.h" + +#define MY_ASSERT(X,S) if (!X) { fprintf(stderr,S); return 0L;} + +#define SYSTEM_WIN32 1 +#define SYSTEM_WIN16 2 +#define SYSTEM_JAVA 3 +#define SYSTEM_OS2 4 +#define SYSTEM_MAC 5 +#define SYSTEM_XWINDOW 6 + +/*****************************************************************************/ +/* + * Class: NativeView + * Method: getNativeWindowSystemType + * Signature: ()I + */ +JNIEXPORT jint JNICALL Java_NativeView_getNativeWindowSystemType + (JNIEnv * env, jobject obj_this) +{ + return SYSTEM_XWINDOW; +} + +/*****************************************************************************/ +/* + * Class: NativeView + * Method: getNativeWindow + * Signature: ()J + */ +JNIEXPORT jlong JNICALL Java_NativeView_getNativeWindow + (JNIEnv * env, jobject obj_this) +{ + jboolean result ; + jint lock ; + JAWT awt ; + JAWT_DrawingSurface* ds ; + JAWT_DrawingSurfaceInfo* dsi ; + JAWT_X11DrawingSurfaceInfo* dsi_x11 ; + Drawable drawable; + + /* Get the AWT */ + awt.version = JAWT_VERSION_1_3; + result = JAWT_GetAWT(env, &awt); + MY_ASSERT(result != JNI_FALSE,"wrong jawt version"); + + /* Get the drawing surface */ + if ((ds = awt.GetDrawingSurface(env, obj_this)) == NULL) + return 0L; + + /* Lock the drawing surface */ + lock = ds->Lock(ds); + MY_ASSERT((lock & JAWT_LOCK_ERROR)==0,"can't lock the drawing surface"); + + /* Get the drawing surface info */ + dsi = ds->GetDrawingSurfaceInfo(ds); + + /* Get the platform-specific drawing info */ + dsi_x11 = (JAWT_X11DrawingSurfaceInfo*)dsi->platformInfo; + drawable = dsi_x11->drawable; + + /* Free the drawing surface info */ + ds->FreeDrawingSurfaceInfo(dsi); + /* Unlock the drawing surface */ + ds->Unlock(ds); + /* Free the drawing surface */ + awt.FreeDrawingSurface(ds); + + return (jlong)drawable; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/nativeview.h b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/nativeview.h new file mode 100644 index 000000000..81de2d9f1 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/unix/nativeview.h @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class org_openoffice_OpenOffice */ + +#ifndef _Included_NativeView +#define _Included_NativeView +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: org_openoffice_OpenOffice + * Method: getNativeWindowSystemType + * Signature: ()I + */ +JNIEXPORT jint JNICALL Java_NativeView_getNativeWindowSystemType + (JNIEnv *, jobject); + +/* + * Class: org_openoffice_OpenOffice + * Method: getNativeWindow + * Signature: ()J + */ +JNIEXPORT jlong JNICALL Java_NativeView_getNativeWindow + (JNIEnv *, jobject); + +#ifdef __cplusplus +} +#endif +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/Makefile b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/Makefile new file mode 100644 index 000000000..62980a2ee --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/Makefile @@ -0,0 +1,77 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OfficeDevDesktopEnvironment native library of the Developers Guide. + +PRJ=../../../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SHL_NAME=nativeview +SHL_LIBRARY=$(SHAREDLIB_OUT)/$(SHAREDLIB_PRE)$(SHL_NAME).$(SHAREDLIB_EXT) + +OUT_SHL_SLO=$(OUT_SLO)/nativeview +OUT_SHL_MISC=$(OUT_MISC)/nativeview + +CFILES = nativeview.c + +SLOFILES = $(patsubst %.c,$(OUT_SHL_SLO)/%.$(OBJ_EXT),$(CFILES)) + +# Targets +.PHONY: ALL +ALL : \ + $(SHL_LIBRARY) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_SHL_SLO)/%.$(OBJ_EXT) : %.c + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS_JNI) $(CC_INCLUDES) $(SDK_JAVA_INCLUDES) $(CC_DEFINES_JNI) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +$(SHAREDLIB_OUT)/$(SHAREDLIB_PRE)$(SHL_NAME).$(SHAREDLIB_EXT) : $(SLOFILES) $(SHL_NAME).def + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_SHL_MISC)) + $(LINK) $(LIBRARY_LINK_FLAGS) /DEF:$(SHL_NAME).def /OUT:$@ \ + /MAP:$(OUT_SHL_MISC)/$(SHL_NAME).map $(LINK_JAVA_LIBS) \ + $(SLOFILES) jawt.lib $(LIBO_SDK_LDFLAGS_STDLIBS) user32.lib + $(LINK_MANIFEST) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_SHL_SLO)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_SHL_MISC)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SHAREDLIB_OUT))$(PS)*$(SHL_NAME)*.*) diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.c b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.c new file mode 100644 index 000000000..b7b13d6c6 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.c @@ -0,0 +1,181 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include + +#include "jawt.h" +#include "jawt_md.h" +#include "NativeView.h" + +#define MY_ASSERT(X,S) if (!X) { fprintf(stderr,"%s\n",S); return 0L;} + +#define SYSTEM_WIN32 1 +#define SYSTEM_WIN16 2 +#define SYSTEM_JAVA 3 +#define SYSTEM_OS2 4 +#define SYSTEM_MAC 5 +#define SYSTEM_XWINDOW 6 + +// property name to register own window procedure on hwnd +#define OLD_PROC_KEY "oldwindowproc" +// signature of this window procedure +static LRESULT APIENTRY NativeViewWndProc( HWND , UINT , WPARAM , LPARAM ); + +/***************************************************************************** + * + * Class : NativeView + * Method : getNativeWindowSystemType + * Signature : ()I + * Description: returns an identifier for the current operating system + */ +JNIEXPORT jint JNICALL Java_NativeView_getNativeWindowSystemType + (JNIEnv * env, jobject obj_this) +{ + return SYSTEM_WIN32; +} + +/***************************************************************************** + * + * Class : NativeView + * Method : getNativeWindow + * Signature : ()J + * Description: returns the native systemw window handle of this object + */ +JNIEXPORT jlong JNICALL Java_NativeView_getNativeWindow + (JNIEnv * env, jobject obj_this) +{ + jboolean result ; + jint lock ; + JAWT awt ; + JAWT_DrawingSurface* ds ; + JAWT_DrawingSurfaceInfo* dsi ; + JAWT_Win32DrawingSurfaceInfo* dsi_win ; + HDC hdc ; + HWND hWnd ; + LONG hFuncPtr; + + /* Get the AWT */ + awt.version = JAWT_VERSION_1_3; + result = JAWT_GetAWT(env, &awt); + MY_ASSERT(result!=JNI_FALSE,"wrong jawt version"); + + /* Get the drawing surface */ + if ((ds = awt.GetDrawingSurface(env, obj_this)) == NULL) + return 0L; + + /* Lock the drawing surface */ + lock = ds->Lock(ds); + MY_ASSERT((lock & JAWT_LOCK_ERROR)==0,"can't lock the drawing surface"); + + /* Get the drawing surface info */ + dsi = ds->GetDrawingSurfaceInfo(ds); + + /* Get the platform-specific drawing info */ + dsi_win = (JAWT_Win32DrawingSurfaceInfo*)dsi->platformInfo; + hdc = dsi_win->hdc; + hWnd = dsi_win->hwnd; + + /* Free the drawing surface info */ + ds->FreeDrawingSurfaceInfo(dsi); + /* Unlock the drawing surface */ + ds->Unlock(ds); + /* Free the drawing surface */ + awt.FreeDrawingSurface(ds); + + /* Register own window procedure + Do it one times only! Otherwise + multiple instances will be registered + and calls on such construct produce + a stack overflow. + */ + if (GetProp( hWnd, OLD_PROC_KEY )==0) + { + hFuncPtr = SetWindowLong( hWnd, GWL_WNDPROC, (DWORD)NativeViewWndProc ); + SetProp( hWnd, OLD_PROC_KEY, (HANDLE)hFuncPtr ); + } + + return (jlong)hWnd; +} + +/***************************************************************************** + * + * Class : - + * Method : NativeViewWndProc + * Signature : - + * Description: registered window handler to intercept window messages between + * java and office process + */ +static LRESULT APIENTRY NativeViewWndProc( + HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) +{ + HANDLE hFuncPtr; + + /* resize new created child window to fill out the java window complete */ + if (uMsg==WM_PARENTNOTIFY) + { + if (wParam == WM_CREATE) + { + RECT rect; + HWND hChild = (HWND) lParam; + + GetClientRect(hWnd, &rect); + + SetWindowPos(hChild, + NULL, + rect.left, + rect.top, + rect.right - rect.left, + rect.bottom - rect.top, + SWP_NOZORDER); + } + } + /* handle normal resize events */ + else if(uMsg==WM_SIZE) + { + WORD newHeight = HIWORD(lParam); + WORD newWidth = LOWORD(lParam); + HWND hChild = GetWindow(hWnd, GW_CHILD); + + if (hChild != NULL) + SetWindowPos(hChild, NULL, 0, 0, newWidth, newHeight, SWP_NOZORDER); + } + + /* forward request to original handler which is intercepted by this window procedure */ + hFuncPtr = GetProp(hWnd, OLD_PROC_KEY); + MY_ASSERT(hFuncPtr,"lost original window proc handler"); + return CallWindowProc( hFuncPtr, hWnd, uMsg, wParam, lParam); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.def b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.def new file mode 100644 index 000000000..f9ba2a78b --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.def @@ -0,0 +1,3 @@ +EXPORTS +Java_NativeView_getNativeWindowSystemType +Java_NativeView_getNativeWindow diff --git a/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.h b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.h new file mode 100644 index 000000000..81de2d9f1 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DesktopEnvironment/nativelib/windows/nativeview.h @@ -0,0 +1,66 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class org_openoffice_OpenOffice */ + +#ifndef _Included_NativeView +#define _Included_NativeView +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: org_openoffice_OpenOffice + * Method: getNativeWindowSystemType + * Signature: ()I + */ +JNIEXPORT jint JNICALL Java_NativeView_getNativeWindowSystemType + (JNIEnv *, jobject); + +/* + * Class: org_openoffice_OpenOffice + * Method: getNativeWindow + * Signature: ()J + */ +JNIEXPORT jlong JNICALL Java_NativeView_getNativeWindow + (JNIEnv *, jobject); + +#ifdef __cplusplus +} +#endif +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DisableCommands/DisableCommandsTest.java b/odk/examples/DevelopersGuide/OfficeDev/DisableCommands/DisableCommandsTest.java new file mode 100644 index 000000000..0d4b09bf0 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DisableCommands/DisableCommandsTest.java @@ -0,0 +1,397 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.configuration.theDefaultProvider; +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.util.XURLTransformer; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.text.XTextDocument; + +/* + * Provides example code how to enable/disable + * commands. + */ +public class DisableCommandsTest { + + /* + * A list of command names + */ + final private static String[] aCommandURLTestSet = + { + "Open", + "About", + "SelectAll", + "Quit", + }; + + private static XComponentContext xRemoteContext = null; + private static XMultiComponentFactory xRemoteServiceManager = null; + private static XURLTransformer xTransformer = null; + private static XMultiServiceFactory xConfigProvider = null; + + /* + * @param args the command line arguments + */ + public static void main(String[] args) { + + try { + // get the remote office context. If necessary a new office + // process is started + xRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + xRemoteServiceManager = xRemoteContext.getServiceManager(); + + Object transformer = xRemoteServiceManager.createInstanceWithContext( + "com.sun.star.util.URLTransformer", xRemoteContext ); + xTransformer = UnoRuntime.queryInterface(com.sun.star.util.XURLTransformer.class, + transformer ); + + xConfigProvider = theDefaultProvider.get(xRemoteContext); + + // create a new test document + Object oDesktop = xRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", xRemoteContext); + + XComponentLoader xCompLoader =UnoRuntime.queryInterface(XComponentLoader.class, oDesktop); + + com.sun.star.lang.XComponent xComponent = + xCompLoader.loadComponentFromURL("private:factory/swriter", + "_blank", 0, new com.sun.star.beans.PropertyValue[0]); + { + XTextDocument xDoc =UnoRuntime.queryInterface(XTextDocument.class, xComponent); + xDoc.getText().setString("You can now check the disabled commands. The " + +"following commands are disabled:\n\n" + +" Open...\n Exit\n Select All\n " + +"About StarOffice|OpenOffice\n\nPress " + + "\"return\" in the shell where you have " + + "started the example to enable the " + + "commands!\n\nCheck the commands again and " + + "press once more \"return\" to finish the " + + "example and close the document."); + + // ensure that the document content is optimal visible + com.sun.star.frame.XModel xModel = + UnoRuntime.queryInterface( + com.sun.star.frame.XModel.class, xDoc); + // get the frame for later usage + com.sun.star.frame.XFrame xFrame = + xModel.getCurrentController().getFrame(); + + com.sun.star.view.XViewSettingsSupplier xViewSettings = + UnoRuntime.queryInterface( + com.sun.star.view.XViewSettingsSupplier.class, + xModel.getCurrentController()); + xViewSettings.getViewSettings().setPropertyValue( + "ZoomType", Short.valueOf((short)0)); + } + // test document will be closed later + + // First we need a defined starting point. So we have to remove + // all commands from the disabled set! + enableCommands(); + + // Check if the commands are usable + testCommands( false ); + + // Disable the commands + disableCommands(); + + // Now the commands shouldn't be usable anymore + testCommands( true ); + + // you can now check the test document and see which commands are + // disabled + System.out.println("\nYou can now check the disabled commands.\n" + +"Please press 'return' to enable the commands!"); + waitForUserInput(); + + // Remove disable commands to make Office usable again + enableCommands(); + + // you can check the test document again and see that the commands + // are enabled now + System.out.println("Check again the now enabled commands.\n" + +"Please press 'return' to finish the example and " + +"close the document!"); + waitForUserInput(); + + // close test document + com.sun.star.util.XCloseable xCloseable = UnoRuntime.queryInterface(com.sun.star.util.XCloseable.class, + xComponent ); + + if (xCloseable != null ) { + xCloseable.close(false); + } else + { + xComponent.dispose(); + } + } + catch (java.lang.Exception e){ + e.printStackTrace(); + } + finally { + System.exit(0); + } + } + + /** + * Wait for user input -> until the user press 'return' + */ + private static void waitForUserInput() throws java.io.IOException { + + java.io.BufferedReader reader + = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); + + reader.read(); + } + + /** + * Test the commands that we enabled/disabled + */ + private static void testCommands( boolean bDisabledCmds ) + throws com.sun.star.uno.Exception + { + // We need the desktop to get access to the current frame + Object desktop = xRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", xRemoteContext ); + com.sun.star.frame.XDesktop xDesktop = UnoRuntime.queryInterface(com.sun.star.frame.XDesktop.class, desktop ); + com.sun.star.frame.XFrame xFrame = xDesktop.getCurrentFrame(); + com.sun.star.frame.XDispatchProvider xDispatchProvider = null; + if ( xFrame != null ) + { + // We have a frame. Now we need access to the dispatch provider. + xDispatchProvider = + UnoRuntime.queryInterface( + com.sun.star.frame.XDispatchProvider.class, xFrame ); + if ( xDispatchProvider != null ) + { + // As we have the dispatch provider we can now check if we get + // a dispatch object or not. + for ( int n = 0; n < aCommandURLTestSet.length; n++ ) + { + // Prepare the URL + com.sun.star.util.URL[] aURL = new com.sun.star.util.URL[1]; + aURL[0] = new com.sun.star.util.URL(); + com.sun.star.frame.XDispatch xDispatch = null; + + aURL[0].Complete = ".uno:" + aCommandURLTestSet[n]; + xTransformer.parseSmart( aURL, ".uno:" ); + + // Try to get a dispatch object for our URL + xDispatch = xDispatchProvider.queryDispatch( aURL[0], "", 0 ); + + if ( xDispatch != null ) + { + if ( bDisabledCmds ) + System.out.println( + "Something is wrong, I got dispatch object for " + + aURL[0].Complete ); + else + System.out.println( "Ok, dispatch object for " + + aURL[0].Complete ); + } + else + { + if ( !bDisabledCmds ) + System.out.println("Something is wrong, I cannot get dispatch object for " + aURL[0].Complete ); + else + System.out.println( "Ok, no dispatch object for " + + aURL[0].Complete ); + } + resetURL( aURL[0] ); + } + } + else + System.out.println( "Couldn't get XDispatchProvider from Frame!" ); + } + else + System.out.println( "Couldn't get current Frame from Desktop!" ); + } + + /** + * Ensure that there are no disabled commands in the user layer. The + * implementation removes all commands from the disabled set! + */ + private static void enableCommands() { + // Set the root path for our configuration access + com.sun.star.beans.PropertyValue[] lParams = + new com.sun.star.beans.PropertyValue[1]; + + lParams[0] = new com.sun.star.beans.PropertyValue(); + lParams[0].Name = "nodepath"; + lParams[0].Value = "/org.openoffice.Office.Commands/Execute/Disabled"; + + try { + // Create configuration update access to have write access to the + // configuration + Object xAccess = xConfigProvider.createInstanceWithArguments( + "com.sun.star.configuration.ConfigurationUpdateAccess", + lParams ); + + com.sun.star.container.XNameAccess xNameAccess = + UnoRuntime.queryInterface( + com.sun.star.container.XNameAccess.class, xAccess ); + + if ( xNameAccess != null ) { + // We need the XNameContainer interface to remove the nodes by name + com.sun.star.container.XNameContainer xNameContainer = + UnoRuntime.queryInterface( + com.sun.star.container.XNameContainer.class, xAccess ); + + // Retrieves the names of all Disabled nodes + String[] aCommandsSeq = xNameAccess.getElementNames(); + for ( int n = 0; n < aCommandsSeq.length; n++ ) { + try { + // remove the node + xNameContainer.removeByName( aCommandsSeq[n] ); + } + catch ( com.sun.star.lang.WrappedTargetException e ) { + } + catch ( com.sun.star.container.NoSuchElementException e ) { + } + } + } + + // Commit our changes + com.sun.star.util.XChangesBatch xFlush = + UnoRuntime.queryInterface( + com.sun.star.util.XChangesBatch.class, xAccess); + + xFlush.commitChanges(); + } + catch ( com.sun.star.uno.Exception e ) { + System.out.println( "Exception detected!" ); + System.out.println( e ); + } + } + + /** + * Disable all commands defined in the aCommandURLTestSet array + */ + private static void disableCommands() { + // Set the root path for our configuration access + com.sun.star.beans.PropertyValue[] lParams = + new com.sun.star.beans.PropertyValue[1]; + + lParams[0] = new com.sun.star.beans.PropertyValue(); + lParams[0].Name = "nodepath"; + lParams[0].Value = "/org.openoffice.Office.Commands/Execute/Disabled"; + + try { + // Create configuration update access to have write access to the + // configuration + Object xAccess = xConfigProvider.createInstanceWithArguments( + "com.sun.star.configuration.ConfigurationUpdateAccess", + lParams ); + + com.sun.star.lang.XSingleServiceFactory xSetElementFactory = + UnoRuntime.queryInterface( + com.sun.star.lang.XSingleServiceFactory.class, xAccess ); + + com.sun.star.container.XNameContainer xNameContainer = + UnoRuntime.queryInterface( + com.sun.star.container.XNameContainer.class, xAccess ); + + if ( xSetElementFactory != null && xNameContainer != null ) { + Object[] aArgs = new Object[0]; + + for ( int i = 0; i < aCommandURLTestSet.length; i++ ) { + // Create the nodes with the XSingleServiceFactory of the + // configuration + Object xNewElement = + xSetElementFactory.createInstanceWithArguments( aArgs ); + + if ( xNewElement != null ) { + // We have a new node. To set the properties of the node + // we need the XPropertySet interface. + com.sun.star.beans.XPropertySet xPropertySet = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, + xNewElement ); + + if ( xPropertySet != null ) { + // Create a unique node name. + String aCmdNodeName = "Command-"; + aCmdNodeName += i; + + // Insert the node into the Disabled set + xPropertySet.setPropertyValue( "Command", + aCommandURLTestSet[i] ); + xNameContainer.insertByName( aCmdNodeName, + xNewElement ); + } + } + } + + // Commit our changes + com.sun.star.util.XChangesBatch xFlush = + UnoRuntime.queryInterface( + com.sun.star.util.XChangesBatch.class, xAccess); + xFlush.commitChanges(); + } + } + catch ( com.sun.star.uno.Exception e ) + { + System.err.println( "Exception detected!" + e); + e.printStackTrace(); + } + } + + /** + * reset URL so it can be reused + * + * @param aURL + * the URL that should be reset + */ + private static void resetURL( com.sun.star.util.URL aURL ) + { + aURL.Protocol = ""; + aURL.User = ""; + aURL.Password = ""; + aURL.Server = ""; + aURL.Port = 0; + aURL.Path = ""; + aURL.Name = ""; + aURL.Arguments = ""; + aURL.Mark = ""; + aURL.Main = ""; + aURL.Complete = ""; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/DisableCommands/Makefile b/odk/examples/DevelopersGuide/OfficeDev/DisableCommands/Makefile new file mode 100644 index 000000000..0d60cb414 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/DisableCommands/Makefile @@ -0,0 +1,91 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OfficeDevDisableCommandsTest example of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=OfficeDevDisableCommandsTest +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +APP1_NAME=DisableCommandsTest +APP1_JAR=$(OUT_APP_CLASS)/$(APP1_NAME).jar + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_APP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(OUT_APP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(OUT_APP_CLASS)/%.jar : $(OUT_APP_CLASS)/%.mf $(OUT_APP_CLASS)/%.class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(OUT_APP_CLASS)/$(APP1_NAME).class + +$(EXAMPLE_NAME) : $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/AsciiReplaceFilter.java b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/AsciiReplaceFilter.java new file mode 100644 index 000000000..5ab5fb3b1 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/AsciiReplaceFilter.java @@ -0,0 +1,702 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +package FilterDevelopment.AsciiFilter; + +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.AnyConverter; +import com.sun.star.lang.XInitialization; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.container.XNamed; +import com.sun.star.document.XImporter; +import com.sun.star.document.XExporter; +import com.sun.star.document.XFilter; + +/*-************************************************************************ + @title implements a filter to import pure ascii text files + @description This filter can use an existing In/OutputStream of given + MediaDescriptor or use an existing URL instead of that + to open the file directly. But for second case the local + file system will be used only. There is no support for remote. + + During import/export special functionality can be used to + e.g. to change some characters inside the file content + or replace some strings (no using of regular expressions!). + User can decide at runtime which functionality really should + be used by selecting it in an extra filter property dialog. + + So we show how a filter works for import/export, use or create + streams and how a filter can offer properties for filtering + which can be edit by the user. + ************************************************************************-*/ + +public class AsciiReplaceFilter +{ + public static class _AsciiReplaceFilter extends WeakBase + implements XInitialization , + XServiceInfo , + XNamed , + XImporter , + XExporter , + XFilter + { + + + // the supported service names, the first one being the service name of the component itself + private static final String[] m_serviceNames = { "com.sun.star.comp.ansifilter.AsciiReplaceFilter" , "com.sun.star.document.ImportFilter", "com.sun.star.document.ExportFilter" }; + + // filterprocess states + private static final int FILTERPROC_RUNS = 0; + private static final int FILTERPROC_BREAK = 1; + private static final int FILTERPROC_STOPPED = 2; + + + // member + + + /// The initial component context, that gives access to the service manager, supported singletons, ... + private XComponentContext m_Ctx; + /// The service manager, that gives access to all registered services and which is passed to the FilterOptions class for instantiating a ucb service + private XMultiComponentFactory m_xMCF; + /// we must provide our name + private String m_sInternalName; + /// saved document reference for import or export (depends on other member m_bImport!) + private com.sun.star.text.XTextDocument m_xDocument; + /// because we implement an import AND an export filter, we must know which one is required + private boolean m_bImport; + // we need a flag to cancel any running filter operation + private int m_nFilterProcState; + + + // native interface + /** + * special debug helper to get an idea how expensive + * the implemented filter operations are really. + * May be useful for own purposes. + * + * To see the output inside an office environment + * use "soffice ...params... >output.txt" + */ + private final long m_nStart; + private long m_nLast ; + + private void measure( String sText ) + { + long nNow = System.currentTimeMillis(); + System.err.println(sText+"\t"+(nNow-m_nStart)+"\t"+(nNow-m_nLast)); + m_nLast = nNow; + } + + + // native interface + /** + * The constructor to initialize every instance + * + * @param Context + * the component context of the office + */ + public _AsciiReplaceFilter(XComponentContext Context ) + { + measure("ctor started"); + try + { + m_Ctx = Context ; + m_xMCF = m_Ctx.getServiceManager() ; + } + catch( Exception e ) + { + e.printStackTrace(); + } + + // these are safe, thus no errorhandling needed: + m_sInternalName = "" ; + m_xDocument = null ; + m_bImport = true ; + m_nFilterProcState = FILTERPROC_STOPPED ; + + m_nLast = System.currentTimeMillis(); + m_nStart = m_nLast; + } + + + // interface XInitialization + /** + * used for initializing after creation + * If an instance of this service is created by UNO we will be called + * automatically after that to get optional parameters of this creation call. + * E.g.: The service com.sun.star.document.FilterFactory use such mechanism + * to pass our own configuration data to this instance. + * + * @param lArguments + * This array of arbitrary objects represent our own filter configuration + * and may optional given parameters of the createWithArguments() call. + * + * @throws com.sun.star.uno.Exception + * Every exception will not be handled, but will be + * passed to the caller. + */ + public void initialize( Object[] lArguments ) throws com.sun.star.uno.Exception + { + measure("initialize {"); + + if (lArguments.length<1) + return; + + // lArguments[0] = own configuration data + com.sun.star.beans.PropertyValue[] lConfig = (com.sun.star.beans.PropertyValue[])lArguments[0]; + + /* + // lArguments[1..n] = optional arguments of create request + for (int n=1; n0 && !bBreaked) + { + // copy data from stream to temp. buffer + sBuffer.append( new String(lData[0]) ); + measure("buffer append ["+nRead+"]"); + + nRead = aOptions.m_xInput.readBytes( lData, 2048 ); + measure("read next bytes"); + + // check for cancelled filter proc on every loop! + synchronized(this) + { + if (m_nFilterProcState==FILTERPROC_BREAK) + { + m_nFilterProcState = FILTERPROC_STOPPED; + return false; + } + } + measure("break check"); + } + + // Make some replacements inside the buffer. + String sText = implts_replace( sBuffer, aOptions ); + measure("replace"); + + // copy current buffer to the document model. + // Create a new paragraph for every line inside original file. + // May not all data could be read - but that doesn't matter here. + // Reason: somewhere cancelled this function. + // But check for optional replace request before... + int nStart = 0; + int nEnd = -1; + int nLength = sText.length(); + + com.sun.star.text.XTextRange xCursor = UnoRuntime.queryInterface( + com.sun.star.text.XTextRange.class, + xText.createTextCursor()); + + while (true) + { + nEnd = sText.indexOf('\n',nStart); + + if (nEnd==-1 && nStartJavaLoader + * + * @param sImplName + * The implementation name of the component. + * + * @return Returns a XSingleComponentFactory for + * creating the component. + * + * @see com.sun.star.comp.loader.JavaLoader + */ + + public static XSingleComponentFactory __getComponentFactory(String sImplName) + { + XSingleComponentFactory xFactory = null; + + if ( sImplName.equals( _AsciiReplaceFilter.class.getName() ) ) + xFactory = com.sun.star.lib.uno.helper.Factory.createComponentFactory(_AsciiReplaceFilter.class, + _AsciiReplaceFilter.m_serviceNames); + return xFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/FilterOptions.java b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/FilterOptions.java new file mode 100644 index 000000000..18c45da85 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/FilterOptions.java @@ -0,0 +1,225 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +package FilterDevelopment.AsciiFilter; + +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.uno.UnoRuntime; + +/*-************************************************************************ + @title helper to analyze necessary option properties of our filter + @description Our filter needs some necessary properties for working: + - a stream for input or output + - or a URL for creating such streams + - information about required action on filtering + + @attention This class mustn't be threadsafe - because instances of it + are used temp. only - not as members. So no concurrent access + should occur. + Another reason: it would be very difficult to safe every + access on our internal member. To do so - we must implement + special methods instead of allowing pure member access. + ************************************************************************-*/ + +public class FilterOptions +{ + + // public member to provide these options to our outside filter class + public com.sun.star.io.XInputStream m_xInput ; + public com.sun.star.io.XOutputStream m_xOutput ; + public boolean m_bStreamOwner ; + private String m_sURL ; + public String m_sOld ; + public String m_sNew ; + public boolean m_bCaseChange ; + public boolean m_bLower ; + + + // private members for internal things + private final XMultiComponentFactory m_xMCF; + private final XComponentContext m_Ctx; + + + // interface + /** + * creates a new instance of this class + * It use the given MediaDescriptor to find right + * properties for initialization of the internal members. + * To do so it use another interface method analyze() + * which can be used after creation of an object instance + * to set a new descriptor here. + * + * @param xMCF + * we need it to create special help service top open + * streams in case they are not already a part of given + * MediaDescriptor + * + * @param bImport + * we must know which stream member should be valid initialized + * + * @param lDescriptor + * the initial MediaDescriptor to set internal member from it + */ + public FilterOptions( XMultiComponentFactory xMCF , + XComponentContext Context , + boolean bImport , + com.sun.star.beans.PropertyValue[] lDescriptor ) + { + m_xMCF = xMCF; + m_Ctx = Context; + analyze(bImport, lDescriptor); + } + + /** + * analyze given MediaDescriptor to find values for our internal member + * It reset all members to defaults before - to prevent us against + * mixed descriptor values! + * + * @param bImport + * we must know which stream member should be valid initialized + * + * @param lDescriptor + * the new MediaDescriptor to set internal member from it + */ + private void analyze( boolean bImport , + com.sun.star.beans.PropertyValue[] lDescriptor ) + { + m_xInput = null ; + m_xOutput = null ; + m_bStreamOwner = false ; + m_sURL = null ; + m_sOld = ""; + m_sNew = ""; + m_bCaseChange = false ; + m_bLower = false ; + + for ( int i=0; i $@ + +$(COMP_CLASSFILES) : $(COMP_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(COMP_CLASS_OUT) $(COMP_JAVAFILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_MANIFESTFILE) $(COMP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(COMP_CLASS_OUT) . + +# rule for component package manifest +$(SAMPLE_GEN_OUT)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)TypeDetection.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_JAR) TypeDetection.xcu $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ TypeDetection.xcu + $(SDK_ZIP) -u $@ $(COMP_COMPONENTS) + cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_ZIP) -u ../../bin/$(@F) $( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(SAMPLE_NAME) : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The "$(QM)$(COMP_NAME)$(QM)" Java component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use the "$(QM)ASCII Replace$(QM)" filter in your office installation, see the + @echo example description. + @echo -------------------------------------------------------------------------------- + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/SampleFilter.components b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/SampleFilter.components new file mode 100644 index 000000000..6b2545df9 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/SampleFilter.components @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/TypeDetection.xcu b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/TypeDetection.xcu new file mode 100644 index 000000000..c2eb32ef2 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/AsciiFilter/TypeDetection.xcu @@ -0,0 +1,46 @@ + + + + + + + 0,text/plain,,,txt,0 + + + ASCII + + + + + + + 0,ascii,com.sun.star.text.TextDocument,com.sun.star.comp.ansifilter.AsciiReplaceFilter,268959747,,0,, + + + true + + + + + ASCII Replace + ASCII Konvertierung + + + + diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/FlatXmlTypeDetection.xcu b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/FlatXmlTypeDetection.xcu new file mode 100644 index 000000000..2ac9a2440 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/FlatXmlTypeDetection.xcu @@ -0,0 +1,88 @@ + + + + + + + 0 + devguide.officedev.samples.filter.FlatXmlDetect + + fods + + false + devguide_FlatXMLFilter_Cpp_calc + + DevGuide FlatXML Calc + + doctype:office:document + + + 0 + devguide.officedev.samples.filter.FlatXmlDetect + + fodg + + false + devguide_FlatXMLFilter_Cpp_draw + + DevGuide FlatXML Draw + + doctype:office:document + + + 0 + devguide.officedev.samples.filter.FlatXmlDetect + + fodp + + false + devguide_FlatXMLFilter_Cpp_impress + + DevGuide FlatXML Impress + + doctype:office:document + + + 0 + devguide.officedev.samples.filter.FlatXmlDetect + + fodt + + false + devguide_FlatXMLFilter_Cpp_writer + + DevGuide FlatXML Writer + + doctype:office:document + + + 0 + devguide.officedev.samples.filter.FlatXmlDetect + + fodm + + false + devguide_FlatXMLFilter_Cpp_master + + DevGuide FlatXML Master + + doctype:office:document + + + diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/Makefile b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/Makefile new file mode 100644 index 000000000..2a9e24186 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/Makefile @@ -0,0 +1,155 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the filterdetection component for the FlatXmlFilter of the Developers Guide. + +PRJ=../../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=FlatXmlTypeDetection +COMP_IMPL_NAME=$(COMP_NAME).uno.$(SHAREDLIB_EXT) +OUT_COMP_INC = $(OUT_INC)/$(COMP_NAME) +OUT_COMP_GEN = $(OUT_MISC)/$(COMP_NAME) +OUT_COMP_SLO=$(OUT_SLO)/$(COMP_NAME) +COMP_RDB_NAME = $(COMP_NAME).uno.rdb +COMP_RDB = $(OUT_COMP_GEN)/$(COMP_RDB_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_UNOPKG_MANIFEST = $(OUT_COMP_GEN)/$(COMP_NAME)/META-INF/manifest.xml +COMP_COMPONENTS = $(OUT_COMP_GEN)/$(COMP_NAME).components + +REGISTERFLAG = $(OUT_MISC)/devguide_$(COMP_NAME)_register_component.flag + +CXXFILES = filterdetect.cxx \ + fdcomp.cxx + +SLOFILES = $(patsubst %.cxx,$(OUT_COMP_SLO)/%.$(OBJ_EXT),$(CXXFILES)) + +# Targets +.PHONY: ALL +ALL : \ + XMLFilterDetect + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_SLO)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +ifeq "$(OS)" "WIN" +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)) + $(LINK) $(COMP_LINK_FLAGS) /OUT:$@ \ + /MAP:$(OUT_COMP_GEN)/$(subst $(SHAREDLIB_EXT),map,$(@F)) $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) msvcprt.lib $(LIBO_SDK_LDFLAGS_STDLIBS) + $(LINK_MANIFEST) +else +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(COMP_LINK_FLAGS) $(LINK_LIBS) -o $@ $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS) $@ +endif +endif + +# rule for component package manifest +$(OUT_COMP_GEN)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)FlatXmlTypeDetection.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components;platform=$(UNOPKG_PLATFORM)$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +$(COMP_COMPONENTS) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)components xmlns="$(QM)http://openoffice.org/2010/uno-components$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)component loader="$(QM)com.sun.star.loader.SharedLibrary$(QM)" uri="$(QM)$(UNOPKG_PLATFORM)/$(COMP_IMPL_NAME)$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)devguide.officedev.samples.filter.FlatXmlDetect$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)com.sun.star.document.ExtendedTypeDetection$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/component$(CSEP) >> $@ + @echo $(OSEP)/components$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(SHAREDLIB_OUT)/$(COMP_IMPL_NAME) FlatXmlTypeDetection.xcu $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)/$(UNOPKG_PLATFORM)) + $(COPY) $(subst /,$(PS),$<) $(subst /,$(PS),$(OUT_COMP_GEN)/$(UNOPKG_PLATFORM)) + $(SDK_ZIP) $@ FlatXmlTypeDetection.xcu + cd $(subst /,$(PS),$(OUT_COMP_GEN)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_NAME).components + cd $(subst /,$(PS),$(OUT_COMP_GEN)) && $(SDK_ZIP) -u ../../bin/$(@F) $(UNOPKG_PLATFORM)/$( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +XMLFilterDetect : $(REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The FlatXMLFilterDetection component is installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You will use this component implicitly in your office installation when you have + @echo installed a FlatXMLFilter component C++ or Java. + @echo -------------------------------------------------------------------------------- + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_SLO)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_COMPONENTS)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(REGISTERFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SHAREDLIB_OUT)/$(COMP_NAME).*)) diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/fdcomp.cxx b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/fdcomp.cxx new file mode 100644 index 000000000..37b7a9360 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/fdcomp.cxx @@ -0,0 +1,84 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include + +#include +#include +#include +#include +#include + +#include "filterdetect.hxx" + +using namespace ::rtl; +using namespace ::cppu; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::registry; + +extern "C" +{ +SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory( + const char * pImplName, void * pServiceManager, void * pRegistryKey ) +{ + void * pRet = 0; + + OUString implName = OUString::createFromAscii( pImplName ); + if ( pServiceManager && implName.equals(FilterDetect_getImplementationName()) ) + { + Reference< XSingleComponentFactory > xFactory( createSingleComponentFactory( + FilterDetect_createInstance, + OUString::createFromAscii( pImplName ), + FilterDetect_getSupportedServiceNames() ) ); + + if (xFactory.is()) + { + xFactory->acquire(); + pRet = xFactory.get(); + } + } + return pRet; +} + +SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( + char const ** ppEnvTypeName, uno_Environment **) +{ + *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/filterdetect.cxx b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/filterdetect.cxx new file mode 100644 index 000000000..8ced96d3b --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/filterdetect.cxx @@ -0,0 +1,247 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include "filterdetect.hxx" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace com::sun::star::uno; +using namespace com::sun::star::document; +using namespace com::sun::star::lang; +using namespace com::sun::star::io; +using namespace com::sun::star::beans; +using namespace com::sun::star::xml::sax; +using namespace com::sun::star::xml; +using namespace com::sun::star::task; +using namespace com::sun::star::frame; +using namespace com::sun::star::container; +using namespace com::sun::star::ucb; + +using ::rtl::OUString; +using ::rtl::OString; + + +OUString SAL_CALL FilterDetect::detect(Sequence< PropertyValue >& aArguments ) + throw( RuntimeException ) +{ + // type name to return + OUString sOriginalTypeName; + OUString sTypeName; + OUString sURL; + // stream of the document to be detected + Reference< XInputStream > xInStream; + for ( sal_Int32 i = 0 ; i < aArguments.getLength(); i++) + { + OUString aName = aArguments[i].Name; + if ( aName == "TypeName" ) + aArguments[i].Value >>= sOriginalTypeName; + if ( aName == "URL" ) + aArguments[i].Value >>= sURL; + if ( aName == "InputStream" ) + aArguments[i].Value >>= xInStream; + } + + if (!xInStream.is()) + { + // open the stream if it was not supplied by the framework + Reference< XSimpleFileAccess3 > xSFI(SimpleFileAccess::create(mxContext)); + if (sURL.getLength() > 0) + { + try + { + xInStream = xSFI->openFileRead( sURL); + } + catch( Exception& ) + { + return sTypeName; + } + } else { + // failed to access UCB + return sTypeName; + } + } + + // flatxml starts with an office:document element. this element + // contains a class="..." attribute by which we can deduct the + // type of document that is to be loaded + + // WARNING: + // parsing the plain text of the document is an easy way to do this + // but not the purest solution, since namespaces and other xml details + // may lead to another syntactic expression of the same document. + // this example works for the way the office serializes its XML stream + // but might need extension for other data sources... + static OString aDocToken("office:document"); + // static OString aClassToken("office:class=\""); + static OString aMimeTypeToken("office:mimetype=\""); + + sal_Int32 nHeadSize = 4096; + Sequence< sal_Int8 > aHeadData(nHeadSize); + + // rewind seekable stream + Reference< XSeekable > xSeek(xInStream, UNO_QUERY); + if (xSeek.is()) + xSeek->seek(0); + + long bytestRead = xInStream->readBytes(aHeadData, nHeadSize); + + OString aHead = OString((const char *)aHeadData.getConstArray(), bytestRead).toAsciiLowerCase(); + + // check for document element of flatxml format + if (aHead.indexOf(aDocToken) >= 0) + { + // read document class + sal_Int32 n = aHead.indexOf(aMimeTypeToken); + if (n >= 0) + { + n += aMimeTypeToken.getLength(); + OString aMimeType = aHead.copy(n, aHead.indexOf('\"', n) - n); + // return type for class found + if (aMimeType.equals("application/x-vnd.oasis.opendocument.text") || + aMimeType.equals("application/vnd.oasis.opendocument.text")) + sTypeName = "devguide_FlatXMLType_Cpp_writer"; + else if (aMimeType.equals("application/x-vnd.oasis.opendocument.text-master") || + aMimeType.equals("application/vnd.oasis.opendocument.text-master")) + sTypeName = "devguide_FlatXMLType_Cpp_master"; + else if (aMimeType.equals("application/x-vnd.oasis.openoffice.text-global") || + aMimeType.equals("application/vnd.oasis.openoffice.text-global")) + sTypeName = "devguide_FlatXMLType_Cpp_master"; + else if (aMimeType.equals("application/x-vnd.oasis.opendocument.spreadsheet") || + aMimeType.equals("application/vnd.oasis.opendocument.spreadsheet")) + sTypeName = "devguide_FlatXMLType_Cpp_calc"; + else if (aMimeType.equals("application/x-vnd.oasis.opendocument.drawing") || + aMimeType.equals("application/vnd.oasis.opendocument.drawing")) + sTypeName = "devguide_FlatXMLType_Cpp_draw"; + else if (aMimeType.equals("application/x-vnd.oasis.opendocument.presentation") || + aMimeType.equals("application/vnd.oasis.opendocument.presentation")) + sTypeName = "devguide_FlatXMLType_Cpp_impress"; + } + } + return sTypeName; +} + + +// XInitialization +void SAL_CALL FilterDetect::initialize( const Sequence< Any >& aArguments ) + throw (Exception, RuntimeException) +{ + Sequence < PropertyValue > aAnySeq; + sal_Int32 nLength = aArguments.getLength(); + if ( nLength && ( aArguments[0] >>= aAnySeq ) ) + { + const PropertyValue * pValue = aAnySeq.getConstArray(); + nLength = aAnySeq.getLength(); + for ( sal_Int32 i = 0 ; i < nLength; i++) + { + if ( pValue[i].Name == "Type" ) + { + pValue[i].Value >>= msFilterName; + } + else if ( pValue[i].Name == "UserData" ) + { + pValue[i].Value >>= msUserData; + } + else if ( pValue[i].Name == "TemplateName" ) + { + pValue[i].Value>>=msTemplateName; + } + } + } +} + +OUString FilterDetect_getImplementationName () + throw (RuntimeException) +{ + return OUString( "devguide.officedev.samples.filter.FlatXmlDetect" ); +} + +#define SERVICE_NAME1 "com.sun.star.document.ExtendedTypeDetection" + +Sequence< OUString > SAL_CALL FilterDetect_getSupportedServiceNames( ) + throw (RuntimeException) +{ + Sequence < OUString > aRet(2); + OUString* pArray = aRet.getArray(); + pArray[0] = OUString ( SERVICE_NAME1 ); + return aRet; +} +#undef SERVICE_NAME1 +#undef SERVICE_NAME2 + +Reference< XInterface > SAL_CALL FilterDetect_createInstance( const Reference< XComponentContext > & rContext) + throw( Exception ) +{ + return (cppu::OWeakObject*) new FilterDetect( rContext ); +} + +// XServiceInfo +OUString SAL_CALL FilterDetect::getImplementationName( ) + throw (RuntimeException) +{ + return FilterDetect_getImplementationName(); +} + +sal_Bool SAL_CALL FilterDetect::supportsService( const OUString& rServiceName ) + throw (RuntimeException) +{ + return cppu::supportsService(this, rServiceName); +} + +Sequence< OUString > SAL_CALL FilterDetect::getSupportedServiceNames( ) + throw (RuntimeException) +{ + return FilterDetect_getSupportedServiceNames(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/filterdetect.hxx b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/filterdetect.hxx new file mode 100644 index 000000000..aa9d82b7a --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilterDetection/filterdetect.hxx @@ -0,0 +1,122 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_EXAMPLES_OFFICEDEV_FILTERDEVELOPMENT_FLATXMLFILTERDETECTION_FILTERDETECT_HXX +#define INCLUDED_EXAMPLES_OFFICEDEV_FILTERDEVELOPMENT_FLATXMLFILTERDETECTION_FILTERDETECT_HXX + + +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace com { namespace sun { namespace star { namespace uno { + class XComponentContext; +} } } } + +enum FilterType +{ + FILTER_IMPORT, + FILTER_EXPORT +}; + +/* This component will be instantiated for both import or export. Whether it calls + * setSourceDocument or setTargetDocument determines which Impl function the filter + * member calls */ +class FilterDetect : public cppu::WeakImplHelper3 +{ +protected: + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mxContext; + ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent > mxDoc; + ::rtl::OUString msFilterName; + ::com::sun::star::uno::Sequence< ::rtl::OUString > msUserData; + ::rtl::OUString msTemplateName; + + sal_Bool SAL_CALL exportImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) + throw (::com::sun::star::uno::RuntimeException); + + sal_Bool SAL_CALL importImpl( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aDescriptor ) + throw (::com::sun::star::uno::RuntimeException); + +public: + FilterDetect( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > &rxContext) + : mxContext( rxContext ) {} + + virtual ~FilterDetect() {} + + //XExtendedFilterDetection + virtual ::rtl::OUString SAL_CALL detect( com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& lDescriptor ) + 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); + + // 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); +}; + + +::rtl::OUString FilterDetect_getImplementationName() + throw ( ::com::sun::star::uno::RuntimeException ); + +sal_Bool SAL_CALL FilterDetect_supportsService( const ::rtl::OUString& ServiceName ) + throw ( ::com::sun::star::uno::RuntimeException ); + +::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL FilterDetect_getSupportedServiceNames( ) + throw ( ::com::sun::star::uno::RuntimeException ); + +::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > +SAL_CALL FilterDetect_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > & rContext) + throw ( ::com::sun::star::uno::Exception ); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/FlatXml.cxx b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/FlatXml.cxx new file mode 100644 index 000000000..58dda0443 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/FlatXml.cxx @@ -0,0 +1,349 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace ::rtl; +using namespace ::cppu; +using namespace ::osl; +using namespace ::com::sun::star::beans; +using namespace ::com::sun::star::io; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::registry; +using namespace ::com::sun::star::xml; +using namespace ::com::sun::star::xml::sax; + +namespace XFlatXml { + +class XFlatXml : public WeakImplHelper3< XImportFilter, XExportFilter, XDocumentHandler> +{ +private: + // the UNO ServiceFactory + Reference< XMultiServiceFactory > m_rServiceFactory; + + // DocumentHandler interface of the css::xml::sax::Writer service + Reference < XExtendedDocumentHandler > m_rDocumentHandler; + + // controls pretty-printing + sal_Bool m_bPrettyPrint; + +public: + + // ctor... + XFlatXml( const Reference< XMultiServiceFactory > &r ) + : m_rServiceFactory(r) + , m_bPrettyPrint(sal_True) + {} + + // XImportFilter + virtual sal_Bool SAL_CALL importer( + const Sequence& aSourceData, + const Reference& xHandler, + const Sequence& msUserData) + throw(RuntimeException); + + // XExportFilter + virtual sal_Bool SAL_CALL exporter( + const Sequence& aSourceData, + const Sequence& msUserData) + throw(RuntimeException); + + // XDocumentHandler + virtual void SAL_CALL startDocument() + throw (SAXException,RuntimeException); + virtual void SAL_CALL endDocument() + throw (SAXException, RuntimeException); + virtual void SAL_CALL startElement(const OUString& str, const Reference& attriblist) + throw (SAXException,RuntimeException); + virtual void SAL_CALL endElement(const OUString& str) + throw (SAXException, RuntimeException); + virtual void SAL_CALL characters(const OUString& str) + throw (SAXException, RuntimeException); + virtual void SAL_CALL ignorableWhitespace(const OUString& str) + throw (SAXException, RuntimeException); + virtual void SAL_CALL processingInstruction(const OUString& str, const OUString& str2) + throw (com::sun::star::xml::sax::SAXException,RuntimeException); + virtual void SAL_CALL setDocumentLocator(const Reference& doclocator) + throw (SAXException,RuntimeException); +}; + +sal_Bool XFlatXml::importer( + const Sequence& aSourceData, + const Reference& xHandler, + const Sequence& msUserData) + throw (RuntimeException) +{ + // get information from media descriptor + // the input stream that represents the imported file + // is most important here since we need to supply it to + // the sax parser that drives the supplied document handler + sal_Int32 nLength = aSourceData.getLength(); + OUString aName, aFileName, aURL; + Reference< XInputStream > xInputStream; + for ( sal_Int32 i = 0 ; i < nLength; i++) + { + aName = aSourceData[i].Name; + if ( aName == "InputStream" ) + aSourceData[i].Value >>= xInputStream; + else if ( aName == "FileName" ) + aSourceData[i].Value >>= aFileName; + else if ( aName == "URL" ) + aSourceData[i].Value >>= aURL; + } + + // we need an input stream + OSL_ASSERT(xInputStream.is()); + if (!xInputStream.is()) return sal_False; + + // rewind seekable stream + Reference< XSeekable > xSeek(xInputStream, UNO_QUERY); + if (xSeek.is()) + xSeek->seek(0); + + + // create SAX parser that will read the document file + // and provide events to xHandler passed to this call + Reference < XParser > xSaxParser( m_rServiceFactory->createInstance( + "com.sun.star.xml.sax.Parser"), UNO_QUERY ); + OSL_ASSERT(xSaxParser.is()); + if(!xSaxParser.is())return sal_False; + + // let the parser try to send the sax event to the document handler + try + { + InputSource aInput; + aInput.sSystemId = aURL; + aInput.sPublicId = aURL; + aInput.aInputStream = xInputStream; + xSaxParser->setDocumentHandler(xHandler); + xSaxParser->parseStream(aInput); + } + catch( Exception &exc) + { + // something went wrong + OSL_FAIL(rtl::OUStringToOString(exc.Message,RTL_TEXTENCODING_UTF8).getStr()); + return sal_False; + } + + // done + return sal_True; +} + +sal_Bool XFlatXml::exporter( + const Sequence& aSourceData, + const Sequence& msUserData) + throw (RuntimeException) +{ + + // read source data + // we are especially interested in the output stream + // since that is where our xml-writer will push the data + // from its data-source interface + OUString aName, sURL; + Reference rOutputStream; + sal_Int32 nLength = aSourceData.getLength(); + for ( sal_Int32 i = 0 ; i < nLength; i++) + { + aName = aSourceData[i].Name; + if ( aName == "OutputStream" ) + aSourceData[i].Value >>= rOutputStream; + else if ( aName == "URL" ) + aSourceData[i].Value >>= sURL; + } + + if (!m_rDocumentHandler.is()) { + // get the document writer + m_rDocumentHandler = Reference( + m_rServiceFactory->createInstance("com.sun.star.xml.sax.Writer"), + UNO_QUERY); + OSL_ASSERT(m_rDocumentHandler.is()); + if (!m_rDocumentHandler.is()) return sal_False; + } + // get data source interface ... + Reference< XActiveDataSource > rDataSource(m_rDocumentHandler, UNO_QUERY); + OSL_ASSERT(rDataSource.is()); + if (!rDataSource.is()) return sal_False; + OSL_ASSERT(rOutputStream.is()); + if (!rOutputStream.is()) return sal_False; + // ... and set output stream + rDataSource->setOutputStream(rOutputStream); + + return sal_True; +} + +// for the DocumentHandler implementation, we just proxy the +// events to the XML writer that we created upon the output stream +// that was provided by the XMLFilterAdapter +void XFlatXml::startDocument() throw (SAXException,RuntimeException){ + OSL_ASSERT(m_rDocumentHandler.is()); + m_rDocumentHandler->startDocument(); +} + +void XFlatXml::endDocument() throw (SAXException,RuntimeException){ + OSL_ASSERT(m_rDocumentHandler.is()); + m_rDocumentHandler->endDocument(); +} + +void XFlatXml::startElement(const OUString& str, const Reference& attriblist) + throw (SAXException, RuntimeException) +{ + OSL_ASSERT(m_rDocumentHandler.is()); + m_rDocumentHandler->startElement(str, attriblist); +} + +void XFlatXml::endElement(const OUString& str) + throw (SAXException, RuntimeException) +{ + OSL_ASSERT(m_rDocumentHandler.is()); + m_rDocumentHandler->endElement(str); +} + +void XFlatXml::characters(const OUString& str) + throw (SAXException, RuntimeException) +{ + OSL_ASSERT(m_rDocumentHandler.is()); + m_rDocumentHandler->characters(str); +} + +void XFlatXml::ignorableWhitespace(const OUString& str) + throw (SAXException, RuntimeException) +{ + OSL_ASSERT(m_rDocumentHandler.is()); + if (!m_bPrettyPrint) return; + m_rDocumentHandler->ignorableWhitespace(str); +} + +void XFlatXml::processingInstruction(const OUString& str, const OUString& str2) + throw (SAXException, RuntimeException) +{ + OSL_ASSERT(m_rDocumentHandler.is()); + m_rDocumentHandler->processingInstruction(str, str2); +} + +void XFlatXml::setDocumentLocator(const Reference& doclocator) + throw (SAXException, RuntimeException) +{ + OSL_ASSERT(m_rDocumentHandler.is()); + m_rDocumentHandler->setDocumentLocator(doclocator); +} + + +// Component management + +Reference< XInterface > SAL_CALL CreateInstance( const Reference< XMultiServiceFactory > &r) +{ + return Reference< XInterface >(( OWeakObject *)new XFlatXml(r)); +} + +Sequence< OUString > getSupportedServiceNames() +{ + static Sequence < OUString > *pNames = 0; + if( ! pNames ) + { + MutexGuard guard( Mutex::getGlobalMutex() ); + if( !pNames ) + { + static Sequence< OUString > seqNames(1); + seqNames.getArray()[0] = OUString( + "devguide.officedev.samples.filter.FlatXmlCpp"); + pNames = &seqNames; + } + } + return *pNames; +} + +} + +using namespace XFlatXml; +#define IMPLEMENTATION_NAME "devguide.officedev.samples.filter.FlatXmlCpp" + + +extern "C" +{ +SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory( + const char * pImplName, void * pServiceManager, void * pRegistryKey ) +{ + void * pRet = 0; + + if (pServiceManager && rtl_str_compare( pImplName, IMPLEMENTATION_NAME ) == 0) + { + Reference< XSingleServiceFactory > xFactory( createSingleFactory( + reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), + OUString::createFromAscii( pImplName ), + CreateInstance, getSupportedServiceNames() ) ); + + if (xFactory.is()) + { + xFactory->acquire(); + pRet = xFactory.get(); + } + } + return pRet; +} + +SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( + char const ** ppEnvTypeName, uno_Environment **) +{ + *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; +} + +} // extern "C" + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/FlatXmlFilter_cpp.xcu b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/FlatXmlFilter_cpp.xcu new file mode 100644 index 000000000..7113a16e1 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/FlatXmlFilter_cpp.xcu @@ -0,0 +1,103 @@ + + + + + + + 0 + devguide_FlatXMLType_Cpp_calc + com.sun.star.sheet.SpreadsheetDocument + + devguide.officedev.samples.filter.FlatXmlCpp, ,com.sun.star.comp.Calc.XMLOasisImporter,com.sun.star.comp.Calc.XMLOasisExporter + com.sun.star.comp.Writer.XmlFilterAdaptor + + + + + DevGuide FlatXML Calc + DevGuide FlatXML Calc + + IMPORT EXPORT ALIEN 3RDPARTYFILTER + + + 0 + devguide_FlatXMLType_Cpp_draw + com.sun.star.drawing.DrawingDocument + + devguide.officedev.samples.filter.FlatXmlCpp, ,com.sun.star.comp.DrawingLayer.XMLOasisImporter,com.sun.star.comp.DrawingLayer.XMLOasisExporter + com.sun.star.comp.Writer.XmlFilterAdaptor + + + + + DevGuide FlatXML Draw + DevGuide FlatXML Draw + + IMPORT EXPORT ALIEN 3RDPARTYFILTER + + + 0 + devguide_FlatXMLType_Cpp_impress + com.sun.star.presentation.PresentationDocument + + devguide.officedev.samples.filter.FlatXmlCpp, ,com.sun.star.comp.Impress.XMLOasisImporter,com.sun.star.comp.Impress.XMLOasisExporter + com.sun.star.comp.Writer.XmlFilterAdaptor + + + + + DevGuide FlatXML Impress + DevGuide FlatXML Impress + + IMPORT EXPORT ALIEN 3RDPARTYFILTER + + + 0 + devguide_FlatXMLType_Cpp_writer + com.sun.star.text.TextDocument + + devguide.officedev.samples.filter.FlatXmlCpp, ,com.sun.star.comp.Writer.XMLOasisImporter,com.sun.star.comp.Writer.XMLOasisExporter + com.sun.star.comp.Writer.XmlFilterAdaptor + + + + + DevGuide FlatXML Writer + DevGuide FlatXML Writer + + IMPORT EXPORT ALIEN 3RDPARTYFILTER + + + 0 + devguide_FlatXMLType_Cpp_master + com.sun.star.text.GlobalDocument + + devguide.officedev.samples.filter.FlatXmlCpp, ,com.sun.star.comp.Writer.XMLOasisImporter,com.sun.star.comp.Writer.XMLOasisExporter + com.sun.star.comp.Writer.XmlFilterAdaptor + + + + + DevGuide FlatXML Master + DevGuide FlatXML Master + + IMPORT EXPORT ALIEN 3RDPARTYFILTER + + + diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/Makefile b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/Makefile new file mode 100644 index 000000000..73e4b7e2a --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_cpp/Makefile @@ -0,0 +1,153 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the C++ FlatXmlFilter component example of the Developers Guide. + +PRJ=../../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=FlatXmlFilter_cpp +COMP_IMPL_NAME=$(COMP_NAME).uno.$(SHAREDLIB_EXT) +OUT_COMP_INC = $(OUT_INC)/$(COMP_NAME) +OUT_COMP_GEN = $(OUT_MISC)/$(COMP_NAME) +OUT_COMP_SLO=$(OUT_SLO)/$(COMP_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_UNOPKG_MANIFEST = $(OUT_COMP_GEN)/$(COMP_NAME)/META-INF/manifest.xml +COMP_COMPONENTS = $(OUT_COMP_GEN)/$(COMP_NAME).components + +COMP_REGISTERFLAG = $(OUT_MISC)/devguide_$(COMP_NAME)_register_component.flag + +CXXFILES = FlatXml.cxx + +SLOFILES = $(patsubst %.cxx,$(OUT_COMP_SLO)/%.$(OBJ_EXT),$(CXXFILES)) + +# Targets +.PHONY: ALL +ALL : \ + FlatXmlFilterCppExample + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_SLO)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +ifeq "$(OS)" "WIN" +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)) + $(LINK) $(COMP_LINK_FLAGS) /OUT:$@ \ + /MAP:$(OUT_COMP_GEN)/$(subst $(SHAREDLIB_EXT),map,$(@F)) $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) msvcprt.lib $(LIBO_SDK_LDFLAGS_STDLIBS) + $(LINK_MANIFEST) +else +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(COMP_LINK_FLAGS) $(LINK_LIBS) -o $@ $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS) $@ +endif +endif + +# rule for component package manifest +$(OUT_COMP_GEN)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)FlatXmlFilter_cpp.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components;platform=$(UNOPKG_PLATFORM)$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +$(COMP_COMPONENTS) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)components xmlns="$(QM)http://openoffice.org/2010/uno-components$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)component loader="$(QM)com.sun.star.loader.SharedLibrary$(QM)" uri="$(QM)$(UNOPKG_PLATFORM)/$(COMP_IMPL_NAME)$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)devguide.officedev.samples.filter.FlatXmlCpp$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)devguide.officedev.samples.filter.FlatXmlCpp$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/component$(CSEP) >> $@ + @echo $(OSEP)/components$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(SHAREDLIB_OUT)/$(COMP_IMPL_NAME) FlatXmlFilter_cpp.xcu $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)/$(UNOPKG_PLATFORM)) + $(COPY) $(subst /,$(PS),$<) $(subst /,$(PS),$(OUT_COMP_GEN)/$(UNOPKG_PLATFORM)) + $(SDK_ZIP) $@ FlatXmlFilter_cpp.xcu + cd $(subst /,$(PS),$(OUT_COMP_GEN)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_NAME).components + cd $(subst /,$(PS),$(OUT_COMP_GEN)) && $(SDK_ZIP) -u ../../bin/$(@F) $(UNOPKG_PLATFORM)/$( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +FlatXmlFilterCppExample : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The C++ FlatXmlFilter component is installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use the filters "$(QM)DevGuide FlatXML ...$(QM)" inside your office installation + @echo after you have installed the "$(QM)FlatXmlTypeDetection.uno.pkg"$(QM) as well. + @echo -------------------------------------------------------------------------------- + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_SLO)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_COMPONENTS))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_REGISTERFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_TYPEFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SHAREDLIB_OUT)/$(COMP_NAME).*)) diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXml.java b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXml.java new file mode 100644 index 000000000..6ba341977 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXml.java @@ -0,0 +1,267 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.*; +import com.sun.star.lang.*; +import com.sun.star.beans.*; + +import com.sun.star.comp.loader.FactoryHelper; +import com.sun.star.registry.XRegistryKey; + +import com.sun.star.xml.*; +import com.sun.star.xml.sax.*; + +import com.sun.star.io.XInputStream; +import com.sun.star.io.XOutputStream; +import com.sun.star.io.XActiveDataSource; + + + +public class FlatXml implements XImportFilter, XExportFilter, XServiceName, + XServiceInfo, XDocumentHandler, XTypeProvider +{ + + /* + * private data members + */ + private final XMultiServiceFactory m_xServiceFactory; + private XExtendedDocumentHandler m_xHandler; + private static final boolean m_bPrettyPrint = true; + + private static final String __serviceName = "devguide.officedev.samples.filter.FlatXmlJava"; + private static final String __implName = "FlatXml"; + private static final String[] __supportedServiceNames = { + "devguide.officedev.samples.filter.FlatXmlJava" + }; + + public FlatXml(XMultiServiceFactory f) { + m_xServiceFactory = f; + } + + // --- XTypeProvider --- + public byte[] getImplementationId() { + return new byte[0]; + } + + // --- XServiceName --- + public String getServiceName() { + return __serviceName; + } + + // --- XServiceInfo --- + public boolean supportsService(String sName) { + for (int i = 0; i < __supportedServiceNames.length; i++) { + if (__supportedServiceNames[i].equals(sName)) return true; + } + return false; + } + public String getImplementationName() { + return this.getClass().getName(); + } + public String[] getSupportedServiceNames() { + return __supportedServiceNames; + } + + public com.sun.star.uno.Type[] getTypes() { + Type[] typeReturn = {}; + try { + typeReturn = new Type[] { + new Type( XTypeProvider.class ), + new Type( XExportFilter.class ), + new Type( XImportFilter.class ), + new Type( XServiceName.class ), + new Type( XServiceInfo.class ) + }; + } catch( java.lang.Exception exception ) { + return null; + } + return typeReturn; + } + + public boolean importer(PropertyValue[] aSourceData, XDocumentHandler xDocHandler, String[] msUserData) + throws com.sun.star.uno.RuntimeException, com.sun.star.lang.IllegalArgumentException + { + String sName = null; + String sFileName = null; + String sURL = null; + com.sun.star.io.XInputStream xin = null; + + try { + + for (int i = 0 ; i < aSourceData.length; i++) + { + sName = aSourceData[i].Name; + if (sName.equals("InputStream")) + xin = (XInputStream)AnyConverter.toObject(XInputStream.class, aSourceData[i].Value); + if (sName.equals("URL")) + sURL=(String)AnyConverter.toObject(String.class, aSourceData[i].Value); + if (sName.equals("FileName")) + sFileName=(String)AnyConverter.toObject(String.class, aSourceData[i].Value); + } + + Object tmpObj=m_xServiceFactory.createInstance("com.sun.star.xml.sax.Parser"); + if (tmpObj == null) return false; + + XParser xParser = UnoRuntime.queryInterface(XParser.class , tmpObj); + if (xParser == null) return false; + + InputSource aInput = new InputSource(); + aInput.sSystemId = sURL; + aInput.aInputStream =xin; + xParser.setDocumentHandler ( xDocHandler ); + xParser.parseStream ( aInput ); + } catch (com.sun.star.uno.Exception e){ + e.printStackTrace(); + return false; + } + + // done... + return true; + } + + public boolean exporter(PropertyValue[] aSourceData, String[] msUserData) + throws com.sun.star.uno.RuntimeException, com.sun.star.lang.IllegalArgumentException + { + try { + String sURL = null; + String sName = null; + XOutputStream xos = null; + + // get interesting values from sourceData + for (int i = 0 ; i < aSourceData.length; i++) + { + sName = aSourceData[i].Name; + if (sName.equals("OutputStream")) + xos = (XOutputStream)AnyConverter.toObject(XOutputStream.class, aSourceData[i].Value); + if (sName.equals("URL")) + sURL=(String)AnyConverter.toObject(String.class, aSourceData[i].Value); + } + + // prepare the XML writer + Object tmpObj = null; + if (m_xHandler == null) + { + tmpObj = m_xServiceFactory.createInstance("com.sun.star.xml.sax.Writer"); + if (tmpObj != null) + m_xHandler = UnoRuntime.queryInterface(XExtendedDocumentHandler.class, tmpObj); + } + if (m_xHandler == null) + return false; + + // Connect the provided output stream to the writer + XActiveDataSource xADSource = UnoRuntime.queryInterface( + XActiveDataSource.class, m_xHandler); + + if (xADSource != null && xos != null) + xADSource.setOutputStream(xos); + else + return false; + } catch (com.sun.star.uno.Exception e){ + return false; + } + + // done ... + return true; + } + + public void startDocument () + throws com.sun.star.xml.sax.SAXException + { + m_xHandler.startDocument(); + } + + public void endDocument() + throws com.sun.star.xml.sax.SAXException + { + m_xHandler.endDocument(); + } + + public void startElement (String str, com.sun.star.xml.sax.XAttributeList xattribs) + throws com.sun.star.xml.sax.SAXException + { + m_xHandler.startElement(str, xattribs); + } + + public void endElement(String str) + throws com.sun.star.xml.sax.SAXException + { + m_xHandler.endElement(str); + } + + public void characters(String str) + throws com.sun.star.xml.sax.SAXException + { + m_xHandler.characters(str); + } + + public void ignorableWhitespace(String str) + throws com.sun.star.xml.sax.SAXException + { + if (!m_bPrettyPrint) return; + else m_xHandler.ignorableWhitespace(str); + } + + public void processingInstruction(String aTarget, String aData) + throws com.sun.star.xml.sax.SAXException + { + m_xHandler.processingInstruction(aTarget, aData); + } + + public void setDocumentLocator(XLocator xLocator) + throws com.sun.star.xml.sax.SAXException + { + m_xHandler.setDocumentLocator(xLocator); + } + + + // component management + + public static XSingleServiceFactory __getServiceFactory(String implName, + XMultiServiceFactory multiFactory, XRegistryKey regKey) + { + XSingleServiceFactory xSingleServiceFactory = null; + if (implName.equals(__implName) ) { + try { + xSingleServiceFactory = FactoryHelper.getServiceFactory( + Class.forName(implName), __serviceName, multiFactory, regKey); + } catch (java.lang.ClassNotFoundException e) { + return null; + } + } + return xSingleServiceFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXmlFilter_java.components b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXmlFilter_java.components new file mode 100644 index 000000000..87359c3ec --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXmlFilter_java.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXmlFilter_java.xcu b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXmlFilter_java.xcu new file mode 100644 index 000000000..8bb6e2350 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/FlatXmlFilter_java.xcu @@ -0,0 +1,103 @@ + + + + + + + 0 + devguide_FlatXMLType_Cpp_calc + com.sun.star.sheet.SpreadsheetDocument + + devguide.officedev.samples.filter.FlatXmlJava, ,com.sun.star.comp.Calc.XMLOasisImporter,com.sun.star.comp.Calc.XMLOasisExporter + com.sun.star.comp.Writer.XmlFilterAdaptor + + + + + DevGuide FlatXML Calc + DevGuide FlatXML Calc + + IMPORT EXPORT ALIEN 3RDPARTYFILTER + + + 0 + devguide_FlatXMLType_Cpp_draw + com.sun.star.drawing.DrawingDocument + + devguide.officedev.samples.filter.FlatXmlJava, ,com.sun.star.comp.DrawingLayer.XMLOasisImporter,com.sun.star.comp.DrawingLayer.XMLOasisExporter + com.sun.star.comp.Writer.XmlFilterAdaptor + + + + + DevGuide FlatXML Draw + DevGuide FlatXML Draw + + IMPORT EXPORT ALIEN 3RDPARTYFILTER + + + 0 + devguide_FlatXMLType_Cpp_impress + com.sun.star.presentation.PresentationDocument + + devguide.officedev.samples.filter.FlatXmlJava, ,com.sun.star.comp.Impress.XMLOasisImporter,com.sun.star.comp.Impress.XMLOasisExporter + com.sun.star.comp.Writer.XmlFilterAdaptor + + + + + DevGuide FlatXML Impress + DevGuide FlatXML Impress + + IMPORT EXPORT ALIEN 3RDPARTYFILTER + + + 0 + devguide_FlatXMLType_Cpp_writer + com.sun.star.text.TextDocument + + devguide.officedev.samples.filter.FlatXmlJava, ,com.sun.star.comp.Writer.XMLOasisImporter,com.sun.star.comp.Writer.XMLOasisExporter + com.sun.star.comp.Writer.XmlFilterAdaptor + + + + + DevGuide FlatXML Writer + DevGuide FlatXML Writer + + IMPORT EXPORT ALIEN 3RDPARTYFILTER + + + 0 + devguide_FlatXMLType_Cpp_master + com.sun.star.text.GlobalDocument + + devguide.officedev.samples.filter.FlatXmlJava, ,com.sun.star.comp.Writer.XMLOasisImporter,com.sun.star.comp.Writer.XMLOasisExporter + com.sun.star.comp.Writer.XmlFilterAdaptor + + + + + DevGuide FlatXML Master + DevGuide FlatXML Master + + IMPORT EXPORT ALIEN 3RDPARTYFILTER + + + diff --git a/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/Makefile b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/Makefile new file mode 100644 index 000000000..58366b7d5 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/FilterDevelopment/FlatXmlFilter_java/Makefile @@ -0,0 +1,142 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java FlatXMLFilter component example of the Developers Guide. + +PRJ=../../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=FlatXmlFilter_java +OUT_COMP_CLASS = $(OUT_CLASS)/$(COMP_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME = $(COMP_NAME).uno.jar +COMP_JAR = $(OUT_COMP_CLASS)/$(COMP_JAR_NAME) +COMP_MANIFESTFILE = $(OUT_COMP_CLASS)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(OUT_COMP_CLASS)/$(COMP_NAME)/META-INF/manifest.xml +COMP_REGISTERFLAG = $(OUT_MISC)$(PS)devguide_$(COMP_NAME)_register_component.flag +COMP_COMPONENTS=$(COMP_NAME).components + +JAVAFILES = \ + FlatXml.java \ + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(JAVAFILES)) + + +#$(COMP_NAME)_CLASSFILES = FlatXml.class FlatXml$(dlr)_FlatXml.class + +$(COMP_NAME)_CLASSFILES = *.class + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : \ + FlatXmlFilterJavaExample + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_CLASS)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo RegistrationClassName: FlatXml> $@ + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(JAVAFILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_MANIFESTFILE) $(CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_JAR) cvfm $(@F) $( $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)FlatXmlFilter_java.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_JAR) FlatXmlFilter_java.xcu $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ FlatXmlFilter_java.xcu + $(SDK_ZIP) -u $@ $(COMP_COMPONENTS) + cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_ZIP) -u ../../bin/$(@F) $( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +FlatXmlFilterJavaExample : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The Java FlatXmlFilter component is installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use the filters "$(QM)DevGuide FlatXML ...$(QM)" inside your office installation + @echo after you have installed the "$(QM)FlatXmlTypeDetection.uno.pkg"$(QM) as well. + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.class + $(SDK_JAVA) -classpath "$(SDK_CLASSPATH)" $(basename $@) + +%.local: $(OUT_COMP_CLASS)/%.class + $(SDK_JAVA) -classpath "$(SDK_CLASSPATH)" $(basename $@) local + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_REGISTERFLAG))) diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/LinguisticExamples.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/LinguisticExamples.java new file mode 100644 index 000000000..9cbd481cb --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/LinguisticExamples.java @@ -0,0 +1,360 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// used interfaces +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.linguistic2.XLinguServiceManager; +import com.sun.star.linguistic2.XSpellChecker; +import com.sun.star.linguistic2.XHyphenator; +import com.sun.star.linguistic2.XThesaurus; +import com.sun.star.linguistic2.XSpellAlternatives; +import com.sun.star.linguistic2.XHyphenatedWord; +import com.sun.star.linguistic2.XPossibleHyphens; +import com.sun.star.linguistic2.XMeaning; +import com.sun.star.linguistic2.XSearchableDictionaryList; +import com.sun.star.linguistic2.XLinguServiceEventListener; +import com.sun.star.linguistic2.LinguServiceEvent; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.PropertyValue; +import com.sun.star.lang.EventObject; +import com.sun.star.lang.Locale; +import com.sun.star.uno.UnoRuntime; + +public class LinguisticExamples +{ + // The remote office context + protected XComponentContext mxRemoteContext = null; + // The MultiServiceFactory interface of the Office + protected XMultiComponentFactory mxRemoteServiceManager = null; + + // The LinguServiceManager interface + protected XLinguServiceManager mxLinguSvcMgr = null; + + // The SpellChecker interface + protected XSpellChecker mxSpell = null; + + // The Hyphenator interface + protected XHyphenator mxHyph = null; + + // The Thesaurus interface + protected XThesaurus mxThes = null; + + // The DictionaryList interface + protected XSearchableDictionaryList mxDicList = null; + + // The LinguProperties interface + protected XPropertySet mxLinguProps = null; + + + public static void main(String args[]) + { + // Create an instance of the class and call its begin method + try { + LinguisticExamples aExample = new LinguisticExamples(); + aExample.Connect(); + aExample.Run(); + } catch (Exception e) { + System.err.println("failed to run examples"); + e.printStackTrace(); + } + } + + + public void Connect() + throws java.lang.Exception + { + // get the remote office context. If necessary a new office + // process is started + mxRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + mxRemoteServiceManager = mxRemoteContext.getServiceManager(); + } + + + /** Get the LinguServiceManager to be used. For example to access spell + checker, thesaurus and hyphenator, also the component may choose to + register itself as listener to it in order to get notified of relevant + events. */ + public boolean GetLinguSvcMgr() + throws com.sun.star.uno.Exception + { + if (mxRemoteContext != null && mxRemoteServiceManager != null) { + Object aObj = mxRemoteServiceManager.createInstanceWithContext( + "com.sun.star.linguistic2.LinguServiceManager", mxRemoteContext ); + mxLinguSvcMgr = UnoRuntime.queryInterface(XLinguServiceManager.class, aObj); + } + return mxLinguSvcMgr != null; + } + + + /** Get the SpellChecker to be used. + */ + public boolean GetSpell() + throws com.sun.star.uno.RuntimeException + { + if (mxLinguSvcMgr != null) + mxSpell = mxLinguSvcMgr.getSpellChecker(); + return mxSpell != null; + } + + /** Get the Hyphenator to be used. + */ + public boolean GetHyph() + throws com.sun.star.uno.RuntimeException + { + if (mxLinguSvcMgr != null) + mxHyph = mxLinguSvcMgr.getHyphenator(); + return mxHyph != null; + } + + /** Get the Thesaurus to be used. + */ + public boolean GetThes() + throws com.sun.star.uno.RuntimeException + { + if (mxLinguSvcMgr != null) + mxThes = mxLinguSvcMgr.getThesaurus(); + return mxThes != null; + } + + + public void Run() + throws Exception + { + GetLinguSvcMgr(); + + + // list of property values to used in function calls below. + // Only properties with values different from the (default) values + // in the LinguProperties property set need to be supllied. + // Thus we may stay with an empty list in order to use the ones + // from the property set. + PropertyValue[] aEmptyProps = new PropertyValue[0]; + + // use american english as language + Locale aLocale = new Locale("en","US",""); + + + + // another list of property values to used in function calls below. + // Only properties with values different from the (default) values + // in the LinguProperties property set need to be supllied. + PropertyValue[] aProps = new PropertyValue[1]; + aProps[0] = new PropertyValue(); + aProps[0].Name = "IsGermanPreReform"; + aProps[0].Value = Boolean.TRUE; + + + GetSpell(); + if (mxSpell != null) + { + // test with correct word + String aWord = "horseback"; + boolean bIsCorrect = mxSpell.isValid( aWord, aLocale, aEmptyProps ); + System.out.println( aWord + ": " + bIsCorrect ); + + // test with incorrect word + aWord = "course"; + bIsCorrect = mxSpell.isValid( aWord, aLocale , aEmptyProps ); + System.out.println( aWord + ": " + bIsCorrect ); + + + aWord = "house"; + XSpellAlternatives xAlt = mxSpell.spell( aWord, aLocale, aEmptyProps ); + if (xAlt == null) + System.out.println( aWord + " is correct." ); + else + { + System.out.println( aWord + " is not correct. A list of proposals follows." ); + String[] aAlternatives = xAlt.getAlternatives(); + if (aAlternatives.length == 0) + System.out.println( "no proposal found." ); + else + { + for (int i = 0; i < aAlternatives.length; ++i) + System.out.println( aAlternatives[i] ); + } + } + } + + + GetHyph(); + if (mxHyph != null) + { + // maximum number of characters to remain before the hyphen + // character in the resulting word of the hyphenation + short nMaxLeading = 6; + + XHyphenatedWord xHyphWord = mxHyph.hyphenate( "waterfall", + aLocale, nMaxLeading , + aEmptyProps ); + if (xHyphWord == null) + System.out.println( "no valid hyphenation position found" ); + else + { + System.out.println( "valid hyphenation pos found at " + + xHyphWord.getHyphenationPos() + + " in " + xHyphWord.getWord() ); + System.out.println( "hyphenation char will be after char " + + xHyphWord.getHyphenPos() + + " in " + xHyphWord.getHyphenatedWord() ); + } + + + //! Note: 'aProps' needs to have set 'IsGermanPreReform' to true! + xHyphWord = mxHyph.queryAlternativeSpelling( "Schiffahrt", + new Locale("de","DE",""), (short)4, aProps ); + if (xHyphWord == null) + System.out.println( "no alternative spelling found at specified position." ); + else + { + if (xHyphWord.isAlternativeSpelling()) + System.out.println( "alternative spelling detected!" ); + System.out.println( "valid hyphenation pos found at " + + xHyphWord.getHyphenationPos() + + " in " + xHyphWord.getWord() ); + System.out.println( "hyphenation char will be after char " + + xHyphWord.getHyphenPos() + + " in " + xHyphWord.getHyphenatedWord() ); + } + + + XPossibleHyphens xPossHyph = mxHyph.createPossibleHyphens("waterfall", + aLocale, + aEmptyProps ); + if (xPossHyph == null) + System.out.println( "no hyphenation positions found." ); + else + System.out.println( xPossHyph.getPossibleHyphens() ); + } + + + GetThes(); + if (mxThes != null) + { + XMeaning[] xMeanings = mxThes.queryMeanings("house", aLocale, + aEmptyProps ); + if (xMeanings == null) + System.out.println( "nothing found." ); + else + { + for (int i = 0; i < xMeanings.length; ++i) + { + System.out.println( "Meaning: " + xMeanings[i].getMeaning() ); + String[] aSynonyms = xMeanings[i].querySynonyms(); + for (int k = 0; k < aSynonyms.length; ++k) + System.out.println( " Synonym: " + aSynonyms[k] ); + } + } + } + + + + XLinguServiceEventListener aClient = new Client(); + + // get access to LinguProperties property set + Object aObj = mxRemoteServiceManager.createInstanceWithContext( + "com.sun.star.linguistic2.LinguProperties", mxRemoteContext); + XPropertySet aLinguProps = UnoRuntime.queryInterface( + XPropertySet.class,aObj); + + // set a spellchecker and hyphenator property value to a defined state + try { + aLinguProps.setPropertyValue("IsGermanPreReform", Boolean.TRUE); + } catch (Exception e) { + } + + // now add the client as listener to the service manager to + // get informed when spellchecking or hyphenation may produce + // different results then before. + mxLinguSvcMgr.addLinguServiceManagerListener(aClient); + + // change that property value in order to trigger a property change + // event that eventually results in the listeners + // 'processLinguServiceEvent' function being called + try { + aLinguProps.setPropertyValue("IsGermanPreReform", Boolean.FALSE); + } catch (Exception e) { + } + + //! keep the listener and the program alive until the event will + //! be launched. + //! There is a voluntary delay before launching the event! + // Of course this code would usually not be in a *real* client + // its + synchronized(this) { + try { + this.wait(4000); + } catch(Exception e) { + + } + } + + //! remove listener before program termination. + //! should not be omitted. + mxLinguSvcMgr.removeLinguServiceManagerListener(aClient); + + + System.exit(0); + } + + /** simple sample implementation of a clients XLinguServiceEventListener + * interface implementation + */ + private class Client + implements XLinguServiceEventListener + { + public void disposing ( EventObject aEventObj ) + { + //! any references to the EventObjects source have to be + //! released here now! + + System.out.println("object listened to will be disposed"); + } + + public void processLinguServiceEvent( LinguServiceEvent aServiceEvent ) + { + //! do here whatever you think needs to be done depending + //! on the event received (e.g. trigger background spellchecking + //! or hyphenation again.) + + System.out.println("Listener called"); + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/Makefile b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/Makefile new file mode 100644 index 000000000..95b6204c0 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/Makefile @@ -0,0 +1,231 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OfficeDevLinguistic examples of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=OfficeDevLinguisticExample +OUT_COMP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +COMP1_NAME=SampleHyphenator +COMP1_PACKAGE = $(OUT_BIN)/$(COMP1_NAME).$(UNOOXT_EXT) +COMP1_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP1_NAME).$(UNOOXT_EXT)") +COMP1_JAR_NAME = $(COMP1_NAME).uno.jar +COMP1_JAR = $(OUT_COMP_CLASS)/$(COMP1_JAR_NAME) +COMP1_MANIFESTFILE = $(OUT_COMP_CLASS)/$(COMP1_NAME).uno.Manifest +COMP1_UNOPKG_MANIFEST = $(OUT_COMP_CLASS)/$(COMP1_NAME)/META-INF/manifest.xml +COMP1_COMPONENTS=$(COMP1_NAME).components + +COMP2_NAME=SampleSpellChecker +COMP2_PACKAGE = $(OUT_BIN)/$(COMP2_NAME).$(UNOOXT_EXT) +COMP2_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP2_NAME).$(UNOOXT_EXT)") +COMP2_JAR_NAME = $(COMP2_NAME).uno.jar +COMP2_JAR = $(OUT_COMP_CLASS)/$(COMP2_JAR_NAME) +COMP2_MANIFESTFILE = $(OUT_COMP_CLASS)/$(COMP2_NAME).uno.Manifest +COMP2_UNOPKG_MANIFEST = $(OUT_COMP_CLASS)/$(COMP2_NAME)/META-INF/manifest.xml +COMP2_COMPONENTS=$(COMP2_NAME).components + +COMP3_NAME=SampleThesaurus +COMP3_PACKAGE = $(OUT_BIN)/$(COMP3_NAME).$(UNOOXT_EXT) +COMP3_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP3_NAME).$(UNOOXT_EXT)") +COMP3_JAR_NAME = $(COMP3_NAME).uno.jar +COMP3_JAR = $(OUT_COMP_CLASS)/$(COMP3_JAR_NAME) +COMP3_MANIFESTFILE = $(OUT_COMP_CLASS)/$(COMP3_NAME).uno.Manifest +COMP3_UNOPKG_MANIFEST = $(OUT_COMP_CLASS)/$(COMP3_NAME)/META-INF/manifest.xml +COMP3_COMPONENTS=$(COMP2_NAME).components + +APP1_NAME=LinguisticExamples +APP1_JAR=$(OUT_COMP_CLASS)/$(APP1_NAME).jar + +REGISTERFLAG = $(OUT_MISC)/devguide_officedevlinguistic_register_component.flag + +JAVAFILES = \ + OneInstanceFactory.java \ + PropChgHelper.java \ + PropChgHelper_Hyph.java \ + PropChgHelper_Spell.java \ + XHyphenatedWord_impl.java \ + XMeaning_impl.java \ + XPossibleHyphens_impl.java \ + XSpellAlternatives_impl.java \ + SampleHyphenator.java \ + SampleSpellChecker.java \ + SampleThesaurus.java + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(JAVAFILES)) + +$(COMP1_NAME)_CLASSFILES = XHyphenatedWord_impl.class \ + XPossibleHyphens_impl.class \ + PropChgHelper.class \ + PropChgHelper_Hyph.class \ + OneInstanceFactory.class \ + $(COMP1_NAME).class + +$(COMP2_NAME)_CLASSFILES = XSpellAlternatives_impl.class \ + PropChgHelper_Spell.class \ + PropChgHelper.class \ + OneInstanceFactory.class \ + $(COMP2_NAME).class + +$(COMP3_NAME)_CLASSFILES = XMeaning_impl.class \ + OneInstanceFactory.class \ + $(COMP3_NAME).class + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + +.PHONY: ALL +ALL : $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_CLASS)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo RegistrationClassName: $(basename $(basename $(@F)))> $@ + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(JAVAFILES) + +# NOTE: because of gnu make problems with full qualified paths, the pattern +# rules for the component jars and the packages doesn't work proper and we +# defined explicit rules + +# rule for component package manifest +$(OUT_COMP_CLASS)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(OUT_COMP_CLASS)/,,$(@D))).components$(QM)"/$(CSEP) >> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +$(COMP1_JAR) : $(COMP1_MANIFESTFILE) $(CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_JAR) cvfm $(@F) $( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(OUT_COMP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $< + +$(OUT_COMP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(APP1_JAR) : $(OUT_COMP_CLASS)/$(APP1_NAME).mf $(OUT_COMP_CLASS)/$(APP1_NAME).class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(basename $(@F)).class $(basename $(@F))$(QUOTE)$$Client.class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + + +$(EXAMPLE_NAME) : $(REGISTERFLAG) $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo -------- + @echo Before you can run the examples the components "$(QM)$(COMP1_NAME)$(QM)", + @echo "$(QM)$(COMP2_NAME)$(QM)" and "$(QM)$(COMP3_NAME)$(QM)" must be deployed. + @echo The components will be automatically deployed if SDK_AUTO_DEPLOYMENT = YES. + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP1_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP2_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP3_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(REGISTERFLAG))) diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/OneInstanceFactory.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/OneInstanceFactory.java new file mode 100644 index 000000000..5e1fdd60b --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/OneInstanceFactory.java @@ -0,0 +1,155 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XInitialization; +import com.sun.star.beans.XPropertySet; +import com.sun.star.uno.XComponentContext; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; + +import java.lang.reflect.Constructor; + + +// purpose of this class is to provide a service factory that instantiates +// the services only once (as long as this factory itself exists) +// and returns only reference to that instance. + + +public class OneInstanceFactory implements + XSingleComponentFactory, + XServiceInfo +{ + private final Class aMyClass; + private final String aSvcImplName; + private final String[] aSupportedSvcNames; + private XInterface xInstantiatedService; + + public OneInstanceFactory( + Class aMyClass, + String aSvcImplName, + String[] aSupportedSvcNames ) + { + this.aMyClass = aMyClass; + this.aSvcImplName = aSvcImplName; + this.aSupportedSvcNames = aSupportedSvcNames; + xInstantiatedService = null; + } + + + // XSingleComponentFactory + + public Object createInstanceWithContext( XComponentContext context ) + throws com.sun.star.uno.Exception, + com.sun.star.uno.RuntimeException + { + if (xInstantiatedService == null) + { + //!! the here used services all have exact one constructor!! + Constructor [] aCtor = aMyClass.getConstructors(); + try { + xInstantiatedService = (XInterface) aCtor[0].newInstance( (Object[])null ); + } + catch( Exception e ) { + } + + //!! workaround for services not always being created + //!! via 'createInstanceWithArguments' + XInitialization xIni = UnoRuntime.queryInterface( + XInitialization.class, createInstanceWithContext(context)); + if (xIni != null) + { + Object[] aArguments = new Object[]{ null, null }; + if (context != null) + { + XPropertySet xPropSet = UnoRuntime.queryInterface( + XPropertySet.class, + context.getServiceManager().createInstanceWithContext( + "com.sun.star.linguistic2.LinguProperties", + context ) ); + aArguments[0] = xPropSet; + } + xIni.initialize( aArguments ); + } + } + return xInstantiatedService; + } + + public Object createInstanceWithArgumentsAndContext( Object[] aArguments, XComponentContext context ) + throws com.sun.star.uno.Exception, + com.sun.star.uno.RuntimeException + { + if (xInstantiatedService == null) + { + XInitialization xIni = UnoRuntime.queryInterface( + XInitialization.class, createInstanceWithContext( context )); + if (xIni != null) + xIni.initialize( aArguments ); + } + return xInstantiatedService; + } + + + + // XServiceInfo + + public boolean supportsService( String aServiceName ) + throws com.sun.star.uno.RuntimeException + { + boolean bFound = false; + int nCnt = aSupportedSvcNames.length; + for (int i = 0; i < nCnt && !bFound; ++i) + { + if (aServiceName.equals( aSupportedSvcNames[i] )) + bFound = true; + } + return bFound; + } + + public String getImplementationName() + throws com.sun.star.uno.RuntimeException + { + return aSvcImplName; + } + + public String[] getSupportedServiceNames() + throws com.sun.star.uno.RuntimeException + { + return aSupportedSvcNames; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper.java new file mode 100644 index 000000000..46fcff061 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper.java @@ -0,0 +1,193 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.linguistic2.XLinguServiceEventBroadcaster; +import com.sun.star.linguistic2.XLinguServiceEventListener; +import com.sun.star.linguistic2.LinguServiceEvent; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.XPropertyChangeListener; +import com.sun.star.beans.PropertyChangeEvent; +import com.sun.star.lang.EventObject; +import com.sun.star.uno.XInterface; + +import java.util.ArrayList; + +public class PropChgHelper implements + XPropertyChangeListener, + XLinguServiceEventBroadcaster +{ + private final XInterface xEvtSource; + private final String[] aPropNames; + private XPropertySet xPropSet; + private final ArrayList aLngSvcEvtListeners; + + public PropChgHelper( + XInterface xEvtSource, + String[] aPropNames ) + { + this.xEvtSource = xEvtSource; + this.aPropNames = aPropNames; + xPropSet = null; + aLngSvcEvtListeners = new ArrayList(); + } + + public XInterface GetEvtSource() + { + return xEvtSource; + } + + public XPropertySet GetPropSet() + { + return xPropSet; + } + + + + public void LaunchEvent( LinguServiceEvent aEvt ) + { + int nCnt = aLngSvcEvtListeners.size(); + for (int i = 0; i < nCnt; ++i) + { + XLinguServiceEventListener xLstnr = + aLngSvcEvtListeners.get(i); + if (xLstnr != null) + xLstnr.processLinguServiceEvent( aEvt ); + } + } + + public void AddAsListenerTo( XPropertySet xPropertySet ) + { + // do not listen any longer to the old property set (if any) + RemoveAsListener(); + + // set new property set to be used and register as listener to it + xPropSet = xPropertySet; + if (xPropSet != null) + { + int nLen = aPropNames.length; + for (int i = 0; i < nLen; ++i) + { + if (aPropNames[i].length() != 0) + { + try { + xPropSet.addPropertyChangeListener( + aPropNames[i], this ); + } + catch( Exception e ) { + } + } + } + } + } + + private void RemoveAsListener() + { + if (xPropSet != null) + { + int nLen = aPropNames.length; + for (int i = 0; i < nLen; ++i) + { + if (aPropNames[i].length() != 0) + { + try { + xPropSet.removePropertyChangeListener( + aPropNames[i], this ); + } + catch( Exception e ) { + } + } + } + + xPropSet = null; + } + } + + // __________ interface methods __________ + + + // XEventListener + + public void disposing( EventObject aSource ) + throws com.sun.star.uno.RuntimeException + { + if (aSource.Source == xPropSet) + { + RemoveAsListener(); + } + } + + + // XPropertyChangeListener + + public void propertyChange( PropertyChangeEvent aEvt ) + throws com.sun.star.uno.RuntimeException + { + // will be overridden in derived classes + } + + + // XLinguServiceEventBroadcaster + + public boolean addLinguServiceEventListener( + XLinguServiceEventListener xListener ) + throws com.sun.star.uno.RuntimeException + { + boolean bRes = false; + if (xListener != null) + { + bRes = aLngSvcEvtListeners.add( xListener ); + } + return bRes; + } + + public boolean removeLinguServiceEventListener( + XLinguServiceEventListener xListener ) + throws com.sun.star.uno.RuntimeException + { + boolean bRes = false; + if (xListener != null) + { + int nIdx = aLngSvcEvtListeners.indexOf( xListener ); + if (nIdx != -1) + { + aLngSvcEvtListeners.remove( nIdx ); + bRes = true; + } + } + return bRes; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper_Hyph.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper_Hyph.java new file mode 100644 index 000000000..0945e413f --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper_Hyph.java @@ -0,0 +1,81 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.linguistic2.LinguServiceEvent; +import com.sun.star.linguistic2.LinguServiceEventFlags; +import com.sun.star.beans.PropertyChangeEvent; +import com.sun.star.uno.XInterface; + +public class PropChgHelper_Hyph extends PropChgHelper +{ + public PropChgHelper_Hyph( + XInterface xEvtSource, + String[] aPropNames ) + { + super( xEvtSource, aPropNames ); + } + + + // XPropertyChangeListener + + @Override + public void propertyChange( PropertyChangeEvent aEvt ) + throws com.sun.star.uno.RuntimeException + { + { + short nLngSvcFlags = 0; + if (aEvt.PropertyName.equals( "IsIgnoreControlCharacters" )) + { + // nothing to be done + } + else if (aEvt.PropertyName.equals( "IsUseDictionaryList" ) || + aEvt.PropertyName.equals( "IsGermanPreReform" ) || + aEvt.PropertyName.equals( "HyphMinLeading" ) || + aEvt.PropertyName.equals( "HyphMinTrailing" ) || + aEvt.PropertyName.equals( "HyphMinWordLength" )) + { + nLngSvcFlags = LinguServiceEventFlags.HYPHENATE_AGAIN; + } + + if (nLngSvcFlags != 0) + { + LinguServiceEvent aEvent = new LinguServiceEvent( GetEvtSource(), nLngSvcFlags ); + LaunchEvent( aEvent ); + } + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper_Spell.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper_Spell.java new file mode 100644 index 000000000..edd0498db --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/PropChgHelper_Spell.java @@ -0,0 +1,105 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.linguistic2.LinguServiceEvent; +import com.sun.star.linguistic2.LinguServiceEventFlags; +import com.sun.star.beans.PropertyChangeEvent; +import com.sun.star.uno.XInterface; + +public class PropChgHelper_Spell extends PropChgHelper +{ + public PropChgHelper_Spell( + XInterface xEvtSource, + String[] aPropNames ) + { + super( xEvtSource, aPropNames ); + } + + + // XPropertyChangeListener + + @Override + public void propertyChange( PropertyChangeEvent aEvt ) + throws com.sun.star.uno.RuntimeException + { + { + short nLngSvcFlags = 0; + boolean bSCWA = false; // SPELL_CORRECT_WORDS_AGAIN ? + boolean bSWWA = false; // SPELL_WRONG_WORDS_AGAIN ? + + boolean bVal = ((Boolean) aEvt.NewValue).booleanValue(); + + if (aEvt.PropertyName.equals( "IsIgnoreControlCharacters" )) + { + // nothing to be done + } + else if (aEvt.PropertyName.equals( "IsGermanPreReform" )) + { + bSCWA = bSWWA = true; + } + else if (aEvt.PropertyName.equals( "IsUseDictionaryList" )) + { + bSCWA = bSWWA = true; + } + else if (aEvt.PropertyName.equals( "IsSpellUpperCase" )) + { + bSCWA = !bVal; // FALSE->TRUE change? + bSWWA = !bSCWA; // TRUE->FALSE change? + } + else if (aEvt.PropertyName.equals( "IsSpellWithDigits" )) + { + bSCWA = !bVal; // FALSE->TRUE change? + bSWWA = !bSCWA; // TRUE->FALSE change? + } + else if (aEvt.PropertyName.equals( "IsSpellCapitalization" )) + { + bSCWA = !bVal; // FALSE->TRUE change? + bSWWA = !bSCWA; // TRUE->FALSE change? + } + + if (bSCWA) + nLngSvcFlags |= LinguServiceEventFlags.SPELL_CORRECT_WORDS_AGAIN; + if (bSWWA) + nLngSvcFlags |= LinguServiceEventFlags.SPELL_WRONG_WORDS_AGAIN; + if (nLngSvcFlags != 0) + { + LinguServiceEvent aEvent = new LinguServiceEvent( GetEvtSource(), nLngSvcFlags ); + LaunchEvent( aEvent ); + } + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleHyphenator.components b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleHyphenator.components new file mode 100644 index 000000000..bf083b386 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleHyphenator.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleHyphenator.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleHyphenator.java new file mode 100644 index 000000000..930d42c32 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleHyphenator.java @@ -0,0 +1,514 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// uno +import com.sun.star.lib.uno.helper.ComponentBase; +import com.sun.star.uno.UnoRuntime; + +// factories +import com.sun.star.lang.XSingleComponentFactory; + +// supported Interfaces +import com.sun.star.linguistic2.XHyphenator; +import com.sun.star.linguistic2.XLinguServiceEventBroadcaster; +import com.sun.star.lang.XInitialization; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XServiceDisplayName; + +// Exceptions +import com.sun.star.uno.Exception; +import com.sun.star.lang.IllegalArgumentException; + +//used Interfaces +import com.sun.star.linguistic2.XLinguServiceEventListener; +import com.sun.star.linguistic2.XHyphenatedWord; +import com.sun.star.linguistic2.XPossibleHyphens; +import com.sun.star.lang.Locale; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.PropertyValue; +import com.sun.star.uno.AnyConverter; +import java.util.ArrayList; + +public class SampleHyphenator extends ComponentBase implements + XHyphenator, + XLinguServiceEventBroadcaster, + XInitialization, + XServiceDisplayName, + XServiceInfo +{ + PropChgHelper_Hyph aPropChgHelper; + ArrayList aEvtListeners; + boolean bDisposing; + + public SampleHyphenator() + { + // names of relevant properties to be used + String[] aProps = new String[] + { + "IsIgnoreControlCharacters", + "IsUseDictionaryList", + "IsGermanPreReform", + "HyphMinLeading", + "HyphMinTrailing", + "HyphMinWordLength" + }; + aPropChgHelper = new PropChgHelper_Hyph( this, aProps ); + aEvtListeners = new ArrayList(); + bDisposing = false; + } + + private boolean IsEqual( Locale aLoc1, Locale aLoc2 ) + { + return aLoc1.Language.equals( aLoc2.Language ) && + aLoc1.Country .equals( aLoc2.Country ) && + aLoc1.Variant .equals( aLoc2.Variant ); + } + + private boolean GetValueToUse( + String aPropName, + boolean bDefaultVal, + PropertyValue[] aProps ) + { + boolean bRes = bDefaultVal; + + try + { + // use temporary value if supplied + for (int i = 0; i < aProps.length; ++i) + { + if (aPropName.equals( aProps[i].Name )) + { + Object aObj = aProps[i].Value; + if (AnyConverter.isBoolean( aObj )) + { + bRes = AnyConverter.toBoolean( aObj ); + return bRes; + } + } + } + + // otherwise use value from property set (if available) + XPropertySet xPropSet = aPropChgHelper.GetPropSet(); + if (xPropSet != null) // should always be the case + { + Object aObj = xPropSet.getPropertyValue( aPropName ); + if (AnyConverter.isBoolean( aObj )) + bRes = AnyConverter.toBoolean( aObj ); + } + } + catch (Exception e) { + bRes = bDefaultVal; + } + + return bRes; + } + + private short GetValueToUse( + String aPropName, + short nDefaultVal, + PropertyValue[] aProps ) + { + short nRes = nDefaultVal; + + try + { + // use temporary value if supplied + for (int i = 0; i < aProps.length; ++i) + { + if (aPropName.equals( aProps[i].Name )) + { + Object aObj = aProps[i].Value; + if (AnyConverter.isShort( aObj )) + { + nRes = AnyConverter.toShort( aObj ); + return nRes; + } + } + } + + // otherwise use value from property set (if available) + XPropertySet xPropSet = aPropChgHelper.GetPropSet(); + if (xPropSet != null) // should always be the case + { + Object aObj = xPropSet.getPropertyValue( aPropName ); + if (AnyConverter.isShort( aObj )) + nRes = AnyConverter.toShort( aObj ); + } + } + catch (Exception e) { + nRes = nDefaultVal; + } + + return nRes; + } + + // __________ interface methods __________ + + + + //XSupportedLocales + + public Locale[] getLocales() + throws com.sun.star.uno.RuntimeException + { + Locale aLocales[] = + { + new Locale( "de", "DE", "" ), + new Locale( "en", "US", "" ) + }; + + return aLocales; + } + + public boolean hasLocale( Locale aLocale ) + throws com.sun.star.uno.RuntimeException + { + boolean bRes = false; + if ( IsEqual( aLocale, new Locale( "de", "DE", "" ) ) || + IsEqual( aLocale, new Locale( "en", "US", "" ) )) + bRes = true; + return bRes; + } + + + //XHyphenator + + public XHyphenatedWord hyphenate( + String aWord, Locale aLocale, + short nMaxLeading, PropertyValue[] aProperties ) + throws com.sun.star.uno.RuntimeException, + IllegalArgumentException + { + if (IsEqual( aLocale, new Locale() ) || aWord.length() == 0) + return null; + + // linguistic is currently not allowed to throw exceptions + // thus we return null fwhich means 'word cannot be hyphenated' + if (!hasLocale( aLocale )) + return null; + + // get values of relevant properties that may be used. + //! The values for 'IsIgnoreControlCharacters' and 'IsUseDictionaryList' + //! are handled by the dispatcher! Thus there is no need to access + //! them here. + boolean bIsIgnoreControlCharacters = GetValueToUse( "IsIgnoreControlCharacters", true, aProperties ); + boolean bIsUseDictionaryList = GetValueToUse( "IsUseDictionaryList", true, aProperties ); + boolean bIsGermanPreReform = GetValueToUse( "IsGermanPreReform", false, aProperties ); + short nHyphMinLeading = GetValueToUse( "HyphMinLeading", (short)2, aProperties ); + short nHyphMinTrailing = GetValueToUse( "HyphMinTrailing", (short)2, aProperties ); + short nHyphMinWordLen = GetValueToUse( "HyphMinWordLength", (short)5, aProperties ); + + XHyphenatedWord xRes = null; + + if (aWord.length() >= nHyphMinWordLen) + { + String aHyphenatedWord = aWord; + short nHyphenationPos = -1; + short nHyphenPos = -1; + + //!! This code needs to be replaced by code calling the actual + //!! implementation of your hyphenator + if (IsEqual( aLocale, new Locale( "de", "DE", "" ) ) ) + { + if (bIsGermanPreReform && aWord.equals( "Schiffahrt" )) + { + // Note: there is only one position where the word + // can be hyphenated... + + aHyphenatedWord = "Schifffahrt"; + nHyphenationPos = 4; + nHyphenPos = 5; + } + else if (!bIsGermanPreReform && aWord.equals( "Schifffahrt" )) + { + nHyphenationPos = nHyphenPos = 5; + } + } + else if (IsEqual( aLocale, new Locale( "en", "US", "" ) ) ) + { + int nLast = aWord.length() - 1 - nHyphMinTrailing; + + if ( aWord.equals( "waterfall" ) ) + { + if (4 <= nLast) + nHyphenationPos = nHyphenPos = 4; + else + nHyphenationPos = nHyphenPos = 1; + } + else if ( aWord.equals( "driving" ) ) + { + nHyphenationPos = nHyphenPos = 3; + } + } + + // check if hyphenation pos is valid, + // a value of -1 indicates that hyphenation is not possible + if ( nHyphenationPos != -1 && + (nHyphenationPos > nHyphMinLeading) && + (nHyphenationPos < aWord.length() - nHyphMinTrailing)) + { + xRes = new XHyphenatedWord_impl(aWord, aLocale, + nHyphenationPos, aHyphenatedWord, nHyphenPos); + } + } + return xRes; + } + + public XHyphenatedWord queryAlternativeSpelling( + String aWord, Locale aLocale, + short nIndex, PropertyValue[] aProperties ) + throws com.sun.star.uno.RuntimeException, + IllegalArgumentException + { + if (IsEqual( aLocale, new Locale() ) || aWord.length() == 0) + return null; + + // linguistic is currently not allowed to throw exceptions + // thus we return null which means 'word cannot be hyphenated' + if (!hasLocale( aLocale )) + return null; + + // get values of relevant properties that may be used. + //! The values for 'IsIgnoreControlCharacters' and 'IsUseDictionaryList' + //! are handled by the dispatcher! Thus there is no need to access + //! them here. + boolean bIsIgnoreControlCharacters = GetValueToUse( "IsIgnoreControlCharacters", true, aProperties ); + boolean bIsUseDictionaryList = GetValueToUse( "IsUseDictionaryList", true, aProperties ); + boolean bIsGermanPreReform = GetValueToUse( "IsGermanPreReform", false, aProperties ); + short nHyphMinLeading = GetValueToUse( "HyphMinLeading", (short)2, aProperties ); + short nHyphMinTrailing = GetValueToUse( "HyphMinTrailing", (short)2, aProperties ); + short nHyphMinWordLen = GetValueToUse( "HyphMinWordLength", (short)5, aProperties ); + + XHyphenatedWord xRes = null; + + //!! This code needs to be replaced by code calling the actual + //!! implementation of your hyphenator + if ( IsEqual( aLocale, new Locale( "de", "DE", "" ) ) ) + { + // there is an alternative spelling only when the + // word is hyphenated between the "ff" and old german spelling + // is set. + if (aWord.equals( "Schiffahrt" ) && + bIsGermanPreReform && nIndex == 4) + { + xRes = new XHyphenatedWord_impl(aWord, aLocale, + (short)4, "Schifffahrt", (short)5 ); + } + } + else if ( IsEqual( aLocale, new Locale( "en", "US", "" ) ) ) + { + // There are no alternative spellings in the English language + } + + return xRes; + } + + public XPossibleHyphens createPossibleHyphens( + String aWord, Locale aLocale, + PropertyValue[] aProperties ) + throws com.sun.star.uno.RuntimeException, + IllegalArgumentException + { + if (IsEqual( aLocale, new Locale() ) || aWord.length() == 0) + return null; + + // linguistic is currently not allowed to throw exceptions + // thus we return null which means 'word cannot be hyphenated' + if (!hasLocale( aLocale )) + return null; + + // get values of relevant properties that may be used. + //! The values for 'IsIgnoreControlCharacters' and 'IsUseDictionaryList' + //! are handled by the dispatcher! Thus there is no need to access + //! them here. + boolean bIsIgnoreControlCharacters = GetValueToUse( "IsIgnoreControlCharacters", true, aProperties ); + boolean bIsUseDictionaryList = GetValueToUse( "IsUseDictionaryList", true, aProperties ); + boolean bIsGermanPreReform = GetValueToUse( "IsGermanPreReform", false, aProperties ); + short nHyphMinLeading = GetValueToUse( "HyphMinLeading", (short)2, aProperties ); + short nHyphMinTrailing = GetValueToUse( "HyphMinTrailing", (short)2, aProperties ); + short nHyphMinWordLen = GetValueToUse( "HyphMinWordLength", (short)5, aProperties ); + + XPossibleHyphens xRes = null; + + //!! This code needs to be replaced by code calling the actual + //!! implementation of your hyphenator + if ( IsEqual( aLocale, new Locale( "de", "DE", "" ) ) ) + { + if (bIsGermanPreReform && aWord.equals( "Schiffahrt" )) + { + short aPos[] = new short[] { (short) 4 }; + xRes = new XPossibleHyphens_impl(aWord, aLocale, + "Schiff=fahrt", aPos); + } + else if (!bIsGermanPreReform && aWord.equals( "Schifffahrt" )) + { + short aPos[] = new short[] { (short) 5 }; + xRes = new XPossibleHyphens_impl(aWord, aLocale, + "Schiff=fahrt", aPos); + } + } + else if ( IsEqual( aLocale, new Locale( "en", "US", "" ) ) ) + { + if ( aWord.equals( "waterfall" ) ) + { + short aPos[] = new short[] + { (short) 1, (short) 4 }; + xRes = new XPossibleHyphens_impl(aWord, aLocale, + "wa=ter=fall", aPos); + } + else if ( aWord.equals( "driving" ) ) + { + short aPos[] = new short[] + { (short) 3 }; + xRes = new XPossibleHyphens_impl(aWord, aLocale, + "driv=ing", aPos); + } + } + + return xRes; + } + + + //XLinguServiceEventBroadcaster + + public boolean addLinguServiceEventListener ( + XLinguServiceEventListener xLstnr ) + throws com.sun.star.uno.RuntimeException + { + boolean bRes = false; + if (!bDisposing && xLstnr != null) + bRes = aPropChgHelper.addLinguServiceEventListener( xLstnr ); + return bRes; + } + + public boolean removeLinguServiceEventListener( + XLinguServiceEventListener xLstnr ) + throws com.sun.star.uno.RuntimeException + { + boolean bRes = false; + if (!bDisposing && xLstnr != null) + bRes = aPropChgHelper.removeLinguServiceEventListener( xLstnr ); + return bRes; + } + + + // XServiceDisplayName + + public String getServiceDisplayName( Locale aLocale ) + throws com.sun.star.uno.RuntimeException + { + return "Java Samples"; + } + + + // XInitialization + + public void initialize( Object[] aArguments ) + throws com.sun.star.uno.Exception, + com.sun.star.uno.RuntimeException + { + int nLen = aArguments.length; + if (2 == nLen) + { + XPropertySet xPropSet = UnoRuntime.queryInterface( + XPropertySet.class, aArguments[0]); + // start listening to property changes + aPropChgHelper.AddAsListenerTo( xPropSet ); + } + } + + + + // XServiceInfo + + public boolean supportsService( String aServiceName ) + throws com.sun.star.uno.RuntimeException + { + String[] aServices = getSupportedServiceNames_Static(); + int i, nLength = aServices.length; + boolean bResult = false; + + for( i = 0; !bResult && i < nLength; ++i ) + bResult = aServiceName.equals( aServices[ i ] ); + + return bResult; + } + + public String getImplementationName() + throws com.sun.star.uno.RuntimeException + { + return _aSvcImplName; + } + + public String[] getSupportedServiceNames() + throws com.sun.star.uno.RuntimeException + { + return getSupportedServiceNames_Static(); + } + + // __________ static things __________ + + public static String _aSvcImplName = SampleHyphenator.class.getName(); + + public static String[] getSupportedServiceNames_Static() + { + String[] aResult = { "com.sun.star.linguistic2.Hyphenator" }; + return aResult; + } + + + /** + * Returns a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XComponentServiceFactory for creating the component + * @param aImplName the name of the implementation for which a service is desired + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleComponentFactory __getComponentFactory( + String aImplName ) + { + XSingleComponentFactory xSingleComponentFactory = null; + if( aImplName.equals( _aSvcImplName ) ) + { + xSingleComponentFactory = new OneInstanceFactory( + SampleHyphenator.class, _aSvcImplName, + getSupportedServiceNames_Static() ); + } + return xSingleComponentFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleSpellChecker.components b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleSpellChecker.components new file mode 100644 index 000000000..bb489918b --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleSpellChecker.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleSpellChecker.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleSpellChecker.java new file mode 100644 index 000000000..dc7ddfddd --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleSpellChecker.java @@ -0,0 +1,457 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// uno +import com.sun.star.lib.uno.helper.ComponentBase; +import com.sun.star.uno.UnoRuntime; + +// factories +import com.sun.star.lang.XSingleComponentFactory; + +// supported Interfaces +import com.sun.star.linguistic2.XSpellChecker; +import com.sun.star.linguistic2.XLinguServiceEventBroadcaster; +import com.sun.star.lang.XInitialization; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XServiceDisplayName; + +// Exceptions +import com.sun.star.uno.Exception; +import com.sun.star.lang.IllegalArgumentException; + +//used Interfaces +import com.sun.star.linguistic2.XLinguServiceEventListener; +import com.sun.star.linguistic2.XSpellAlternatives; +import com.sun.star.linguistic2.SpellFailure; +import com.sun.star.lang.Locale; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.PropertyValue; +import com.sun.star.uno.AnyConverter; +import java.util.ArrayList; + +public class SampleSpellChecker extends ComponentBase implements + XSpellChecker, + XLinguServiceEventBroadcaster, + XInitialization, + XServiceDisplayName, + XServiceInfo +{ + PropChgHelper_Spell aPropChgHelper; + ArrayList aEvtListeners; + boolean bDisposing; + + public SampleSpellChecker() + { + // names of relevant properties to be used + String[] aProps = new String[] + { + "IsIgnoreControlCharacters", + "IsUseDictionaryList", + "IsGermanPreReform", + "IsSpellUpperCase", + "IsSpellWithDigits", + "IsSpellCapitalization" + }; + aPropChgHelper = new PropChgHelper_Spell( this, aProps ); + aEvtListeners = new ArrayList(); + bDisposing = false; + } + + private boolean IsEqual( Locale aLoc1, Locale aLoc2 ) + { + return aLoc1.Language.equals( aLoc2.Language ) && + aLoc1.Country .equals( aLoc2.Country ) && + aLoc1.Variant .equals( aLoc2.Variant ); + } + + private boolean GetValueToUse( + String aPropName, + boolean bDefaultVal, + PropertyValue[] aProps ) + { + boolean bRes = bDefaultVal; + + try + { + // use temporary value if supplied + for (int i = 0; i < aProps.length; ++i) + { + if (aPropName.equals( aProps[i].Name )) + { + Object aObj = aProps[i].Value; + if (AnyConverter.isBoolean( aObj )) + { + bRes = AnyConverter.toBoolean( aObj ); + return bRes; + } + } + } + + // otherwise use value from property set (if available) + XPropertySet xPropSet = aPropChgHelper.GetPropSet(); + if (xPropSet != null) // should always be the case + { + Object aObj = xPropSet.getPropertyValue( aPropName ); + if (AnyConverter.isBoolean( aObj )) + bRes = AnyConverter.toBoolean( aObj ); + } + } + catch (Exception e) { + bRes = bDefaultVal; + } + + return bRes; + } + + private boolean IsUpper( String aWord, Locale aLocale ) + { + java.util.Locale aLang = new java.util.Locale( + aLocale.Language, aLocale.Country, aLocale.Variant ); + return aWord.equals( aWord.toUpperCase( aLang ) ); + } + + private boolean HasDigits( String aWord ) + { + int nLen = aWord.length(); + for (int i = 0; i < nLen; ++i) + { + if (Character.isDigit( aWord.charAt(i) )) + return true; + } + return false; + } + + private short GetSpellFailure( + String aWord, + Locale aLocale, + PropertyValue[] aProperties ) + { + short nRes = -1; + + //!! This code needs to be replaced by code calling the actual + //!! implementation of your spellchecker + boolean bIsGermanPreReform = GetValueToUse( "IsGermanPreReform", false, aProperties ); + if (IsEqual( aLocale, new Locale( "de", "DE", "" ) )) + { + if (bIsGermanPreReform && aWord.equals( "Schifffahrt" )) + nRes = SpellFailure.SPELLING_ERROR; + else if (!bIsGermanPreReform && aWord.equals( "Schiffahrt" )) + nRes = SpellFailure.SPELLING_ERROR; + } + else if (IsEqual( aLocale, new Locale( "en", "US", "" ) )) + { + // words with 'u', 'U' and 'arizona' are defined to be incorrect + boolean bIsValid = !(aWord.indexOf( "u" ) != -1 || aWord.indexOf( "U" ) != -1) + && !aWord.equals( "arizona" ); + + if (!bIsValid) + { + // default value (no other SpellFailure type is applicable) + nRes = SpellFailure.SPELLING_ERROR; + + if (aWord.equals( "arizona" )) + nRes = SpellFailure.CAPTION_ERROR; + else if (aWord.equals( "house" )) + nRes = SpellFailure.SPELLING_ERROR; + else if (aWord.equals( "course" )) + nRes = SpellFailure.IS_NEGATIVE_WORD; + } + } + + return nRes; + } + + private XSpellAlternatives GetProposals( + String aWord, + Locale aLocale, + PropertyValue[] aProperties ) + { + short nType = SpellFailure.SPELLING_ERROR; + String[] aProposals = null; + + // get values of relevant properties that may be used. + //! The values for 'IsIgnoreControlCharacters' and 'IsUseDictionaryList' + //! are handled by the dispatcher! Thus there is no need to access + //! them here. + boolean bIsGermanPreReform = GetValueToUse( "IsGermanPreReform", false, aProperties ); + boolean bIsSpellWithDigits = GetValueToUse( "IsSpellWithDigits", false, aProperties ); + boolean bIsSpellUpperCase = GetValueToUse( "IsSpellUpperCase", false, aProperties ); + boolean bIsSpellCapitalization = GetValueToUse( "IsSpellCapitalization", true, aProperties ); + + //!! This code needs to be replaced by code calling the actual + //!! implementation of your spellchecker + if (IsEqual( aLocale, new Locale( "de", "DE", "" ) )) + { + if (bIsGermanPreReform && aWord.equals( "Schifffahrt" )) + { + nType = SpellFailure.SPELLING_ERROR; + aProposals = new String[]{ "Schiffahrt" }; + } + else if (!bIsGermanPreReform && aWord.equals( "Schiffahrt" )) + { + nType = SpellFailure.SPELLING_ERROR; + aProposals = new String[]{ "Schifffahrt" }; + } + } + else if (IsEqual( aLocale, new Locale( "en", "US", "" ) )) + { + if (aWord.equals( "arizona" )) + { + nType = SpellFailure.CAPTION_ERROR; + aProposals = new String[]{ "Arizona" }; + } + else if (aWord.equals( "house" )) + { + nType = SpellFailure.SPELLING_ERROR; + aProposals = new String[]{ "horse", "home" }; + } + else if (aWord.equals( "course" )) + { + nType = SpellFailure.IS_NEGATIVE_WORD; + aProposals = new String[]{ "line", "plan", "approach" }; + } + } + + // always return a result if word is incorrect, + // proposals may be empty though. + return new XSpellAlternatives_impl( aWord, aLocale, + nType, aProposals ); + } + + // __________ interface methods __________ + + + + //XSupportedLocales + + public Locale[] getLocales() + throws com.sun.star.uno.RuntimeException + { + Locale aLocales[] = + { + new Locale( "de", "DE", "" ), + new Locale( "en", "US", "" ) + }; + + return aLocales; + } + + public boolean hasLocale( Locale aLocale ) + throws com.sun.star.uno.RuntimeException + { + boolean bRes = false; + if ( IsEqual( aLocale, new Locale( "de", "DE", "" ) ) || + IsEqual( aLocale, new Locale( "en", "US", "" ) )) + bRes = true; + return bRes; + } + + + + //XSpellChecker + + public boolean isValid( + String aWord, Locale aLocale, + PropertyValue[] aProperties ) + throws com.sun.star.uno.RuntimeException, + IllegalArgumentException + { + if (IsEqual( aLocale, new Locale() ) || aWord.length() == 0) + return true; + + // linguistic is currently not allowed to throw exceptions + // thus we return null which means 'word cannot be spelled' + if (!hasLocale( aLocale )) + return true; + + // get values of relevant properties that may be used. + //! The values for 'IsIgnoreControlCharacters' and 'IsUseDictionaryList' + //! are handled by the dispatcher! Thus there is no need to access + //! them here. + boolean bIsGermanPreReform = GetValueToUse( "IsGermanPreReform", false, aProperties ); + boolean bIsSpellWithDigits = GetValueToUse( "IsSpellWithDigits", false, aProperties ); + boolean bIsSpellUpperCase = GetValueToUse( "IsSpellUpperCase", false, aProperties ); + boolean bIsSpellCapitalization = GetValueToUse( "IsSpellCapitalization", true, aProperties ); + + short nFailure = GetSpellFailure( aWord, aLocale, aProperties ); + if (nFailure != -1) + { + // postprocess result for errors that should be ignored + if ( (!bIsSpellUpperCase && IsUpper( aWord, aLocale )) + || (!bIsSpellWithDigits && HasDigits( aWord )) + || (!bIsSpellCapitalization + && nFailure == SpellFailure.CAPTION_ERROR) + ) + nFailure = -1; + } + + return nFailure == -1; + } + + + public XSpellAlternatives spell( + String aWord, Locale aLocale, + PropertyValue[] aProperties ) + throws com.sun.star.uno.RuntimeException, + IllegalArgumentException + { + if (IsEqual( aLocale, new Locale() ) || aWord.length() == 0) + return null; + + // linguistic is currently not allowed to throw exceptions + // thus we return null fwhich means 'word cannot be spelled' + if (!hasLocale( aLocale )) + return null; + + XSpellAlternatives xRes = null; + if (!isValid( aWord, aLocale, aProperties )) + { + xRes = GetProposals( aWord, aLocale, aProperties ); + } + return xRes; + } + + + + //XLinguServiceEventBroadcaster + + public boolean addLinguServiceEventListener ( + XLinguServiceEventListener xLstnr ) + throws com.sun.star.uno.RuntimeException + { + boolean bRes = false; + if (!bDisposing && xLstnr != null) + bRes = aPropChgHelper.addLinguServiceEventListener( xLstnr ); + return bRes; + } + + public boolean removeLinguServiceEventListener( + XLinguServiceEventListener xLstnr ) + throws com.sun.star.uno.RuntimeException + { + boolean bRes = false; + if (!bDisposing && xLstnr != null) + bRes = aPropChgHelper.removeLinguServiceEventListener( xLstnr ); + return bRes; + } + + + // XServiceDisplayName + + public String getServiceDisplayName( Locale aLocale ) + throws com.sun.star.uno.RuntimeException + { + return "Java Samples"; + } + + + // XInitialization + + public void initialize( Object[] aArguments ) + throws com.sun.star.uno.Exception, + com.sun.star.uno.RuntimeException + { + int nLen = aArguments.length; + if (2 == nLen) + { + XPropertySet xPropSet = UnoRuntime.queryInterface( + XPropertySet.class, aArguments[0]); + // start listening to property changes + aPropChgHelper.AddAsListenerTo( xPropSet ); + } + } + + + // XServiceInfo + + public boolean supportsService( String aServiceName ) + throws com.sun.star.uno.RuntimeException + { + String[] aServices = getSupportedServiceNames_Static(); + int i, nLength = aServices.length; + boolean bResult = false; + + for( i = 0; !bResult && i < nLength; ++i ) + bResult = aServiceName.equals( aServices[ i ] ); + + return bResult; + } + + public String getImplementationName() + throws com.sun.star.uno.RuntimeException + { + return _aSvcImplName; + } + + public String[] getSupportedServiceNames() + throws com.sun.star.uno.RuntimeException + { + return getSupportedServiceNames_Static(); + } + + // __________ static things __________ + + public static String _aSvcImplName = SampleSpellChecker.class.getName(); + + public static String[] getSupportedServiceNames_Static() + { + String[] aResult = { "com.sun.star.linguistic2.SpellChecker" }; + return aResult; + } + + + /** + * Returns a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XSingleComponentFactory for creating the component + * @param aImplName the name of the implementation for which a service is desired + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleComponentFactory __getComponentFactory( + String aImplName ) + { + XSingleComponentFactory xSingleComponentFactory = null; + if( aImplName.equals( _aSvcImplName ) ) + { + xSingleComponentFactory = new OneInstanceFactory( + SampleSpellChecker.class, _aSvcImplName, + getSupportedServiceNames_Static() ); + } + return xSingleComponentFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleThesaurus.components b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleThesaurus.components new file mode 100644 index 000000000..025f42451 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleThesaurus.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleThesaurus.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleThesaurus.java new file mode 100644 index 000000000..f5c437095 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/SampleThesaurus.java @@ -0,0 +1,293 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// uno +import com.sun.star.lib.uno.helper.ComponentBase; +import com.sun.star.uno.UnoRuntime; + +// factories +import com.sun.star.lang.XSingleComponentFactory; + +// supported Interfaces +import com.sun.star.linguistic2.XThesaurus; +import com.sun.star.lang.XInitialization; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XServiceDisplayName; + +// Exceptions +import com.sun.star.uno.Exception; +//used Interfaces +import com.sun.star.linguistic2.XMeaning; +import com.sun.star.lang.Locale; +import com.sun.star.beans.XPropertySet; +import com.sun.star.beans.PropertyValue; +import com.sun.star.uno.AnyConverter; +import java.util.ArrayList; + +public class SampleThesaurus extends ComponentBase implements + XThesaurus, + XInitialization, + XServiceDisplayName, + XServiceInfo +{ + PropChgHelper aPropChgHelper; + ArrayList aEvtListeners; + boolean bDisposing; + + public SampleThesaurus() + { + // names of relevant properties to be used + String[] aProps = new String[] + { + "IsIgnoreControlCharacters", + "IsUseDictionaryList", + "IsGermanPreReform", + }; + + // this service has no listeners thus we may use the base class, + // which is here basically used only to keep track of the + // property set (and its lifetime) since it gets used in the + // 'GetValueToUse' function + aPropChgHelper = new PropChgHelper( this, aProps ); + + aEvtListeners = new ArrayList(); + bDisposing = false; + } + + private boolean IsEqual( Locale aLoc1, Locale aLoc2 ) + { + return aLoc1.Language.equals( aLoc2.Language ) && + aLoc1.Country .equals( aLoc2.Country ) && + aLoc1.Variant .equals( aLoc2.Variant ); + } + + private boolean GetValueToUse( + String aPropName, + boolean bDefaultVal, + PropertyValue[] aProps ) + { + boolean bRes = bDefaultVal; + + try + { + // use temporary value if supplied + for (int i = 0; i < aProps.length; ++i) + { + if (aPropName.equals( aProps[i].Name )) + { + Object aObj = aProps[i].Value; + if (AnyConverter.isBoolean( aObj )) + { + bRes = AnyConverter.toBoolean( aObj ); + return bRes; + } + } + } + + // otherwise use value from property set (if available) + XPropertySet xPropSet = aPropChgHelper.GetPropSet(); + if (xPropSet != null) // should always be the case + { + Object aObj = xPropSet.getPropertyValue( aPropName ); + if (AnyConverter.isBoolean( aObj )) + bRes = AnyConverter.toBoolean( aObj ); + } + } + catch (Exception e) { + bRes = bDefaultVal; + } + + return bRes; + } + + // __________ interface methods __________ + + + + //XSupportedLocales + + public Locale[] getLocales() + throws com.sun.star.uno.RuntimeException + { + Locale aLocales[] = + { + new Locale( "en", "US", "" ) + }; + + return aLocales; + } + + public boolean hasLocale( Locale aLocale ) + throws com.sun.star.uno.RuntimeException + { + boolean bRes = false; + if (IsEqual( aLocale, new Locale( "en", "US", "" ) )) + bRes = true; + return bRes; + } + + + //XThesaurus + + public XMeaning[] queryMeanings( + String aTerm, Locale aLocale, + PropertyValue[] aProperties ) + throws com.sun.star.lang.IllegalArgumentException, + com.sun.star.uno.RuntimeException + { + if (IsEqual( aLocale, new Locale() ) || aTerm.length() == 0) + return null; + + // linguistic is currently not allowed to throw exceptions + // thus we return null fwhich means 'word cannot be looked up' + if (!hasLocale( aLocale )) + return null; + + // get values of relevant properties that may be used. + //! The values for 'IsIgnoreControlCharacters' and 'IsUseDictionaryList' + //! are handled by the dispatcher! Thus there is no need to access + //! them here. + boolean bIsGermanPreReform = GetValueToUse( "IsGermanPreReform", false, aProperties ); + + XMeaning[] aRes = null; + + //!! This code needs to be replaced by code calling the actual + //!! implementation of your thesaurus + if (aTerm.equals( "house" ) && + IsEqual( aLocale, new Locale( "en", "US", "" ) ) ) + { + aRes = new XMeaning[] + { + new XMeaning_impl( "a building where one lives", + new String[]{ "home", "place", "dwelling" } ), + new XMeaning_impl( "a group of people sharing common ancestry", + new String[]{ "family", "clan", "kindred" } ), + new XMeaning_impl( "to provide with lodging", + new String[]{ "room", "board", "put up" } ) + }; + } + + return aRes; + } + + + + // XServiceDisplayName + + public String getServiceDisplayName( Locale aLocale ) + throws com.sun.star.uno.RuntimeException + { + return "Java Samples"; + } + + + // XInitialization + + public void initialize( Object[] aArguments ) + throws com.sun.star.uno.Exception, + com.sun.star.uno.RuntimeException + { + int nLen = aArguments.length; + if (2 == nLen) + { + XPropertySet xPropSet = UnoRuntime.queryInterface( + XPropertySet.class, aArguments[0]); + // start listening to property changes + aPropChgHelper.AddAsListenerTo( xPropSet ); + } + } + + + // XServiceInfo + + public boolean supportsService( String aServiceName ) + throws com.sun.star.uno.RuntimeException + { + String[] aServices = getSupportedServiceNames_Static(); + int i, nLength = aServices.length; + boolean bResult = false; + + for( i = 0; !bResult && i < nLength; ++i ) + bResult = aServiceName.equals( aServices[ i ] ); + + return bResult; + } + + public String getImplementationName() + throws com.sun.star.uno.RuntimeException + { + return _aSvcImplName; + } + + public String[] getSupportedServiceNames() + throws com.sun.star.uno.RuntimeException + { + return getSupportedServiceNames_Static(); + } + + // __________ static things __________ + + public static String _aSvcImplName = SampleThesaurus.class.getName(); + + public static String[] getSupportedServiceNames_Static() + { + String[] aResult = { "com.sun.star.linguistic2.Thesaurus" }; + return aResult; + } + + + /** + * Returns a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XSingleComponentFactory for creating the component + * @param aImplName the name of the implementation for which a service is desired + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleComponentFactory __getComponentFactory( + String aImplName ) + { + XSingleComponentFactory xSingleComponentFactory = null; + if( aImplName.equals( _aSvcImplName ) ) + { + xSingleComponentFactory = new OneInstanceFactory( + SampleThesaurus.class, _aSvcImplName, + getSupportedServiceNames_Static() ); + } + return xSingleComponentFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XHyphenatedWord_impl.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XHyphenatedWord_impl.java new file mode 100644 index 000000000..47963441b --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XHyphenatedWord_impl.java @@ -0,0 +1,100 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lang.Locale; + +public class XHyphenatedWord_impl implements + com.sun.star.linguistic2.XHyphenatedWord +{ + private String aWord; + private String aHyphenatedWord; + private final short nHyphenPos; + private final short nHyphenationPos; + private Locale aLang; + private final boolean bIsAltSpelling; + + public XHyphenatedWord_impl( + String aWord, + Locale aLang, + short nHyphenationPos, + String aHyphenatedWord, + short nHyphenPos ) + { + this.aWord = aWord; + this.aLang = aLang; + this.nHyphenationPos = nHyphenationPos; + this.aHyphenatedWord = aHyphenatedWord; + this.nHyphenPos = nHyphenPos; + this.bIsAltSpelling = (aWord != aHyphenatedWord); + + //!! none of these cases should ever occur! + //!! values provided only for safety + if (this.aWord == null) + this.aWord = ""; + if (this.aLang == null) + this.aLang = new Locale(); + if (this.aHyphenatedWord == null) + this.aHyphenatedWord = ""; + } + + + // XHyphenatedWord + public String getWord() throws com.sun.star.uno.RuntimeException + { + return aWord; + } + public Locale getLocale() throws com.sun.star.uno.RuntimeException + { + return aLang; + } + public short getHyphenationPos() throws com.sun.star.uno.RuntimeException + { + return nHyphenationPos; + } + public String getHyphenatedWord() throws com.sun.star.uno.RuntimeException + { + return aHyphenatedWord; + } + public short getHyphenPos() throws com.sun.star.uno.RuntimeException + { + return nHyphenPos; + } + public boolean isAlternativeSpelling() throws com.sun.star.uno.RuntimeException + { + return bIsAltSpelling; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XMeaning_impl.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XMeaning_impl.java new file mode 100644 index 000000000..5e30ef22e --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XMeaning_impl.java @@ -0,0 +1,71 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + + +public class XMeaning_impl implements + com.sun.star.linguistic2.XMeaning +{ + private String aMeaning; + private String[] aSynonyms; + + public XMeaning_impl ( String aMeaning, String[] aSynonyms ) + { + this.aMeaning = aMeaning; + this.aSynonyms = aSynonyms; + + //!! none of these cases should ever occur! + //!! values provided only for safety + if (this.aMeaning == null) + this.aMeaning = ""; + + // a meaning without synonyms may be OK though. + // still for safety an empty existing array has to be provided. + if (this.aSynonyms == null) + this.aSynonyms = new String[]{}; + } + + // XMeaning + public String getMeaning() throws com.sun.star.uno.RuntimeException + { + return aMeaning; + } + public String[] querySynonyms() throws com.sun.star.uno.RuntimeException + { + return aSynonyms; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XPossibleHyphens_impl.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XPossibleHyphens_impl.java new file mode 100644 index 000000000..e64752029 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XPossibleHyphens_impl.java @@ -0,0 +1,92 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lang.Locale; + +public class XPossibleHyphens_impl implements + com.sun.star.linguistic2.XPossibleHyphens +{ + private String aWord; + private String aHyphWord; + private short[] aOrigHyphenPos; + private Locale aLang; + + public XPossibleHyphens_impl( + String aWord, + Locale aLang, + String aHyphWord, + short[] aOrigHyphenPos) + { + this.aWord = aWord; + this.aLang = aLang; + this.aHyphWord = aHyphWord; + this.aOrigHyphenPos = aOrigHyphenPos; + + //!! none of these cases should ever occur! + //!! values provided only for safety + if (this.aWord == null) + this.aWord = ""; + if (this.aLang == null) + this.aLang = new Locale(); + if (this.aHyphWord == null) + this.aHyphWord = ""; + + // having no hyphenation positions is OK though. + // still for safety an empty existing array has to be provided. + if (this.aOrigHyphenPos == null) + this.aOrigHyphenPos = new short[]{}; + } + + // XPossibleHyphens + public String getWord() throws com.sun.star.uno.RuntimeException + { + return aWord; + } + + public Locale getLocale() throws com.sun.star.uno.RuntimeException + { + return aLang; + } + public String getPossibleHyphens() throws com.sun.star.uno.RuntimeException + { + return aHyphWord; + } + public short[] getHyphenationPositions() throws com.sun.star.uno.RuntimeException + { + return aOrigHyphenPos; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XSpellAlternatives_impl.java b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XSpellAlternatives_impl.java new file mode 100644 index 000000000..d2e9ecbea --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Linguistic/XSpellAlternatives_impl.java @@ -0,0 +1,94 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lang.Locale; + + +public class XSpellAlternatives_impl implements + com.sun.star.linguistic2.XSpellAlternatives +{ + private String aWord; + private Locale aLanguage; + private String[] aAlt; // list of alternatives, may be empty. + private final short nType; // type of failure + + public XSpellAlternatives_impl( + String aWord, + Locale aLanguage, + short nFailureType, + String[] aAlt ) + { + this.aWord = aWord; + this.aLanguage = aLanguage; + this.aAlt = aAlt; + this.nType = nFailureType; + + //!! none of these cases should ever occur! + //!! values provided only for safety + if (this.aWord == null) + this.aWord = ""; + if (this.aLanguage == null) + this.aLanguage = new Locale(); + + // having no alternatives is OK though. + // still for safety an empty existing array has to be provided. + if (this.aAlt == null) + this.aAlt = new String[]{}; + } + + // XSpellAlternatives + public String getWord() throws com.sun.star.uno.RuntimeException + { + return aWord; + } + public Locale getLocale() throws com.sun.star.uno.RuntimeException + { + return aLanguage; + } + public short getFailureType() throws com.sun.star.uno.RuntimeException + { + return nType; + } + public short getAlternativesCount() throws com.sun.star.uno.RuntimeException + { + return (short) aAlt.length; + } + public String[] getAlternatives() throws com.sun.star.uno.RuntimeException + { + return aAlt; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Makefile b/odk/examples/DevelopersGuide/OfficeDev/Makefile new file mode 100644 index 000000000..88c4df966 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Makefile @@ -0,0 +1,105 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OfficeDev examples of the Developers Guide. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=OfficeDevExamples +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +APP1_NAME=ContextMenuInterceptor +APP1_JAR=$(OUT_APP_CLASS)/$(APP1_NAME).jar +APP2_NAME=Number_Formats +APP2_JAR=$(OUT_APP_CLASS)/$(APP2_NAME).jar + +APP1_JAVAFILES = \ + MenuElement.java \ + OfficeConnect.java \ + ContextMenuInterceptor.java \ + +APP1_CLASSFILES = $(patsubst %.java,$(OUT_APP_CLASS)/%.class,$(APP1_JAVAFILES)) +APP1_CLASSNAMES = $(patsubst %.java,%.class,$(APP1_JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_APP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(OUT_APP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(APP1_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(APP1_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP2_JAR) : $(OUT_APP_CLASS)/$(APP2_NAME).mf $(OUT_APP_CLASS)/$(APP2_NAME).class + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(basename $(@F)).class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + + +$(EXAMPLE_NAME) : $(APP1_JAR) $(APP2_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP2_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/OfficeDev/MenuElement.java b/odk/examples/DevelopersGuide/OfficeDev/MenuElement.java new file mode 100644 index 000000000..c3e8f751a --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/MenuElement.java @@ -0,0 +1,58 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; + +// A helper class to determine the menu element type +public class MenuElement +{ + public static boolean IsMenuEntry( com.sun.star.beans.XPropertySet xMenuElement ) { + com.sun.star.lang.XServiceInfo xServiceInfo = + UnoRuntime.queryInterface( + com.sun.star.lang.XServiceInfo.class, xMenuElement ); + + return xServiceInfo.supportsService( "com.sun.star.ui.ActionTrigger" ); + } + + public static boolean IsMenuSeparator( com.sun.star.beans.XPropertySet xMenuElement ) { + com.sun.star.lang.XServiceInfo xServiceInfo = + UnoRuntime.queryInterface( + com.sun.star.lang.XServiceInfo.class, xMenuElement ); + + return xServiceInfo.supportsService( "com.sun.star.ui.ActionTriggerSeparator" ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/Number_Formats.java b/odk/examples/DevelopersGuide/OfficeDev/Number_Formats.java new file mode 100644 index 000000000..dedd084e5 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/Number_Formats.java @@ -0,0 +1,245 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.beans.PropertyValue; +import com.sun.star.container.XIndexAccess; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.sheet.XSpreadsheet; +import com.sun.star.sheet.XSpreadsheets; +import com.sun.star.sheet.XSpreadsheetDocument; +import com.sun.star.table.XCell; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + + +// __________ Implementation __________ + +/** Create a spreadsheet document and provide access to a sheet framework that + is then used to modify some number formats. + */ +public class Number_Formats +{ + // __________ public members and methods __________ + + + + + public static void main( String args[] ) + { + try + { + Number_Formats aSample = new Number_Formats( args ); + aSample.doFunction(); + } + catch( Exception ex ) + { + System.err.println( "Sample caught exception! " + ex ); + ex.printStackTrace(); + System.exit(1); + } + + System.out.println( "Sample done." ); + System.exit(0); + } + + + + public void doFunction() throws RuntimeException, Exception + { + // Assume: + // com.sun.star.sheet.XSpreadsheetDocument maSpreadsheetDoc; + // com.sun.star.sheet.XSpreadsheet maSheet; + + // Query the number formats supplier of the spreadsheet document + com.sun.star.util.XNumberFormatsSupplier xNumberFormatsSupplier = + UnoRuntime.queryInterface( + com.sun.star.util.XNumberFormatsSupplier.class, maSpreadsheetDoc ); + + // Get the number formats from the supplier + com.sun.star.util.XNumberFormats xNumberFormats = + xNumberFormatsSupplier.getNumberFormats(); + + // Query the XNumberFormatTypes interface + com.sun.star.util.XNumberFormatTypes xNumberFormatTypes = + UnoRuntime.queryInterface( + com.sun.star.util.XNumberFormatTypes.class, xNumberFormats ); + + // Get the number format index key of the default currency format, + // note the empty locale for default locale + com.sun.star.lang.Locale aLocale = new com.sun.star.lang.Locale(); + int nCurrencyKey = xNumberFormatTypes.getStandardFormat( + com.sun.star.util.NumberFormat.CURRENCY, aLocale ); + + // Get cell range B3:B11 + com.sun.star.table.XCellRange xCellRange = + maSheet.getCellRangeByPosition( 1, 2, 1, 10 ); + + // Query the property set of the cell range + com.sun.star.beans.XPropertySet xCellProp = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xCellRange ); + + // Set number format to default currency + xCellProp.setPropertyValue( "NumberFormat", Integer.valueOf(nCurrencyKey) ); + + // Get cell B3 + com.sun.star.table.XCell xCell = maSheet.getCellByPosition( 1, 2 ); + + // Query the property set of the cell + xCellProp = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xCell ); + + // Get the number format index key of the cell's properties + int nIndexKey = ((Integer) xCellProp.getPropertyValue( "NumberFormat" )).intValue(); + if ( nIndexKey != nCurrencyKey ) + System.out.println( "Number format doesn't match!" ); + + // Get the properties of the number format + com.sun.star.beans.XPropertySet xProp = xNumberFormats.getByKey( nIndexKey ); + + // Get the format code string of the number format's properties + String aFormatCode = (String) xProp.getPropertyValue( "FormatString" ); + System.out.println( "FormatString: `" + aFormatCode + "'" ); + + // Create an arbitrary format code + aFormatCode = "\"wonderful \"" + aFormatCode; + + // Test if it's already present + nIndexKey = xNumberFormats.queryKey( aFormatCode, aLocale, false ); + + // If not, add to number formats collection + if ( nIndexKey == -1 ) + { + try + { + nIndexKey = xNumberFormats.addNew( aFormatCode, aLocale ); + } + catch( com.sun.star.util.MalformedNumberFormatException ex ) + { + System.err.println( "Bad number format code: " + ex ); + ex.printStackTrace(); + nIndexKey = -1; + } + } + + // Set the new format at the cell + if ( nIndexKey != -1 ) + xCellProp.setPropertyValue( "NumberFormat", Integer.valueOf(nIndexKey) ); + + + // Set column containing the example values to optimal width to show + // the new format of cell B3 + com.sun.star.table.XColumnRowRange xColRowRange = + UnoRuntime.queryInterface(com.sun.star.table.XColumnRowRange.class, + maSheet); + + com.sun.star.container.XIndexAccess xIndexAccess = + UnoRuntime.queryInterface(com.sun.star.container.XIndexAccess.class, + xColRowRange.getColumns()); + + com.sun.star.beans.XPropertySet xColPropSet = + UnoRuntime.queryInterface(com.sun.star.beans.XPropertySet.class, + xIndexAccess.getByIndex(1)); + + xColPropSet.setPropertyValue( "OptimalWidth", Boolean.TRUE ); + } + + + + public Number_Formats( String[] args ) throws java.lang.Exception + { + // get the remote office context. If necessary a new office + // process is started + XComponentContext aOfficeContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + XMultiComponentFactory aServiceManager = aOfficeContext.getServiceManager(); + + // create a new spreadsheet document + XComponentLoader aLoader = UnoRuntime.queryInterface( + XComponentLoader.class, aServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", aOfficeContext) ); + + maSpreadsheetDoc = UnoRuntime.queryInterface( + XSpreadsheetDocument.class, + aLoader.loadComponentFromURL( "private:factory/scalc", + "_blank", + 0, + new PropertyValue[ 0 ] ) ); + + if ( !initSpreadsheet() ) + System.exit( 0 ); + } + + + // __________ private members and methods __________ + + private final XSpreadsheetDocument maSpreadsheetDoc; + private XSpreadsheet maSheet; // the first sheet + + + + + /** init the first sheet + */ + private boolean initSpreadsheet() + { + boolean bOk = true; + XSpreadsheets aSheets = maSpreadsheetDoc.getSheets(); + try + { + XIndexAccess aSheetsIA = UnoRuntime.queryInterface( XIndexAccess.class, aSheets ); + maSheet = UnoRuntime.queryInterface(XSpreadsheet.class, aSheetsIA.getByIndex( 0 )); + + // enter some values in B3:B11 + for( int iCounter=1; iCounter < 10; iCounter++ ) + { + XCell aCell = maSheet.getCellByPosition( 1, 1 + iCounter ); + aCell.setValue( iCounter ); + } + } + catch( Exception ex ) + { + System.err.println( "Couldn't initialize Spreadsheet Document: " + ex ); + ex.printStackTrace(); + bOk = false; + } + return bOk; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/OfficeConnect.java b/odk/examples/DevelopersGuide/OfficeDev/OfficeConnect.java new file mode 100644 index 000000000..d8db72aad --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/OfficeConnect.java @@ -0,0 +1,140 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// __________ Imports __________ + +import com.sun.star.uno.UnoRuntime; + +// __________ Implementation __________ + +/** + * support ONE singleton uno connection to a running office installation! + * Can be used to open/use/close connection to uno environment of an already running office. + * ctor isn't available from outside. You should call static function "getConnection()" + * to open or use internal set connection which is created one times only. + * + */ +public class OfficeConnect +{ + + + /** + * At first call we create static connection object and get the remote office + * context and the remote office service manager. A new office process is + * started if necessary. + * Then - and for all further requests we return these static connection member. + */ + public static synchronized OfficeConnect createConnection() + throws java.lang.Exception + { + if (maConnection == null) + { + maConnection = new OfficeConnect(); + } + return maConnection; + } + + + + + + + + /** + * ctor + * We try to open the connection in our ctor ... transparently for the user. + * We made it private to support singleton pattern of these implementation. + * see getConnection() for further information + */ + private OfficeConnect() throws java.lang.Exception + { + // get the remote office context. If necessary a new office + // process is started + mxOfficeContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + mxServiceManager = mxOfficeContext.getServiceManager(); + } + + + + /** + * create uno components inside remote office process + * After connection of these process to a running office we have access to remote service manager of it. + * So we can use it to create all existing services. Use this method to create components by name and + * get her interface. Casting of it to right target interface is part of your implementation. + * + * @param aType describe class type of created service + * Returned object can be casted directly to this one. + * Uno query was done by this method automatically. + * @param sServiceSpecifier name of service which should be created + * @return Description of the Returned Value + */ + public T createRemoteInstance(Class aType, String sServiceSpecifier) + { + T aResult = null; + try + { + aResult = UnoRuntime.queryInterface( + aType, mxServiceManager.createInstanceWithContext( + sServiceSpecifier, mxOfficeContext)); + } + catch (com.sun.star.uno.Exception ex) + { + System.err.println("Couldn't create Service of type " + sServiceSpecifier + ": " + ex); + ex.printStackTrace(); + System.exit(0); + } + return aResult; + } + + + + + + + + /** + * member + */ + // singleton connection instance + private static OfficeConnect maConnection; + + // reference to remote office context + private final com.sun.star.uno.XComponentContext mxOfficeContext; + // reference to remote service manager + private final com.sun.star.lang.XMultiComponentFactory mxServiceManager; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/PathSettings/Makefile b/odk/examples/DevelopersGuide/OfficeDev/PathSettings/Makefile new file mode 100644 index 000000000..bc55266ef --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/PathSettings/Makefile @@ -0,0 +1,91 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OfficeDevPathSettingsTest example of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=OfficeDevPathSettingsTest +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +APP1_NAME=PathSettingsTest +APP1_JAR=$(OUT_APP_CLASS)/$(APP1_NAME).jar + +SDK_CLASSPATH=$(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_APP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(OUT_APP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(OUT_APP_CLASS)/%.jar : $(OUT_APP_CLASS)/%.mf $(OUT_APP_CLASS)/%.class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(OUT_APP_CLASS)/$(APP1_NAME).class + +$(EXAMPLE_NAME) : $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/OfficeDev/PathSettings/PathSettingsTest.java b/odk/examples/DevelopersGuide/OfficeDev/PathSettings/PathSettingsTest.java new file mode 100644 index 000000000..f8a17a16b --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/PathSettings/PathSettingsTest.java @@ -0,0 +1,164 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.beans.XPropertySet; +import com.sun.star.util.thePathSettings; + +/* + * Provides example code how to access and use the + * path pathsettings service. + */ +public class PathSettingsTest { + + /* + * List of pre-defined path variables supported by + * the path settings service. + */ + private static String[] predefinedPathProperties = { + "Addin", + "AutoCorrect", + "AutoText", + "Backup", + "Basic", + "Bitmap", + "Config", + "Dictionary", + "Favorite", + "Filter", + "Gallery", + "Graphic", + "Help", + "Linguistic", + "Module", + "Palette", + "Plugin", + "Storage", + "Temp", + "Template", + "UIConfig", + "UserConfig", + "UserDictionary", + "Work" + }; + + /* + * @param args the command line arguments + */ + public static void main(String[] args) { + + XComponentContext xRemoteContext = null; + XPropertySet xPathSettingsService = null; + + try { + // get the remote office context. If necessary a new office + // process is started + xRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + Object pathSubst = thePathSettings.get( xRemoteContext ); + xPathSettingsService = UnoRuntime.queryInterface( + XPropertySet.class, pathSubst); + + /* Work with path settings */ + workWithPathSettings( xPathSettingsService ); + } + catch (java.lang.Exception e){ + e.printStackTrace(); + } + finally { + System.exit(0); + } + } + + /* + * Retrieve and set path properties from path settings service + * @param xPathSettingsService the path settings service + */ + public static void workWithPathSettings( XPropertySet xPathSettingsService ) + { + if ( xPathSettingsService != null ) { + for ( int i=0; i $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(OUT_APP_CLASS)/%.jar : $(OUT_APP_CLASS)/%.mf $(OUT_APP_CLASS)/%.class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(OUT_APP_CLASS)/$(APP1_NAME).class + +$(EXAMPLE_NAME) : $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/OfficeDev/PathSubstitution/PathSubstitutionTest.java b/odk/examples/DevelopersGuide/OfficeDev/PathSubstitution/PathSubstitutionTest.java new file mode 100644 index 000000000..98fd919c9 --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/PathSubstitution/PathSubstitutionTest.java @@ -0,0 +1,116 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.util.XStringSubstitution; + +public class PathSubstitutionTest { + + /* + * List of pre-defined path variables supported by + * the path substitution service. + */ + private static String[] predefinedPathVariables = { + "$(home)","$(inst)","$(prog)","$(temp)","$(user)", "$(username)", + "$(work)","$(path)","$(langid)","$(vlang)" + }; + + /* + * @param args the command line arguments + */ + public static void main(String[] args) { + + XComponentContext xRemoteContext = null; + XMultiComponentFactory xRemoteServiceManager = null; + XStringSubstitution xPathSubstService = null; + + try { + // get the remote office context. If necessary a new office + // process is started + xRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + xRemoteServiceManager = xRemoteContext.getServiceManager(); + + Object pathSubst = xRemoteServiceManager.createInstanceWithContext( + "com.sun.star.comp.framework.PathSubstitution", xRemoteContext ); + xPathSubstService = UnoRuntime.queryInterface( + XStringSubstitution.class, pathSubst); + + /* Work with path variables */ + workWithPathVariables( xPathSubstService ); + } + catch (java.lang.Exception e){ + e.printStackTrace(); + } + finally { + System.exit(0); + } + } + + public static void workWithPathVariables( XStringSubstitution xPathSubstService ) + { + if ( xPathSubstService != null ) { + for ( int i=0; i $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(APP1_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(APP1_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(EXAMPLE_NAME) : $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/OfficeDev/TerminationTest/TerminateListener.java b/odk/examples/DevelopersGuide/OfficeDev/TerminationTest/TerminateListener.java new file mode 100644 index 000000000..fd902daee --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/TerminationTest/TerminateListener.java @@ -0,0 +1,59 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.frame.TerminationVetoException; +import com.sun.star.frame.XTerminateListener; + +public class TerminateListener implements XTerminateListener { + + public void notifyTermination(com.sun.star.lang.EventObject eventObject) { + System.out.println("about to terminate..."); + } + + public void queryTermination(com.sun.star.lang.EventObject eventObject) + throws TerminationVetoException { + + // test if we can terminate now + if (TerminationTest.isAtWork()) { + System.out.println("Terminate while we are at work? You can't mean it serious ;-)!"); + throw new TerminationVetoException(); + } + } + + public void disposing(com.sun.star.lang.EventObject eventObject) { + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/OfficeDev/TerminationTest/TerminationTest.java b/odk/examples/DevelopersGuide/OfficeDev/TerminationTest/TerminationTest.java new file mode 100644 index 000000000..3d0fdde2e --- /dev/null +++ b/odk/examples/DevelopersGuide/OfficeDev/TerminationTest/TerminationTest.java @@ -0,0 +1,100 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.frame.XDesktop; + +public class TerminationTest { + + private static boolean atWork = false; + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + + XComponentContext xRemoteContext = null; + XMultiComponentFactory xRemoteServiceManager = null; + XDesktop xDesktop = null; + + try { + // get the remote office context. If necessary a new office + // process is started + xRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + xRemoteServiceManager = xRemoteContext.getServiceManager(); + + Object desktop = xRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", xRemoteContext); + xDesktop = UnoRuntime.queryInterface(XDesktop.class, desktop); + + TerminateListener terminateListener = new TerminateListener(); + xDesktop.addTerminateListener(terminateListener); + + atWork = true; + // try to terminate while we are at work + boolean terminated = xDesktop.terminate(); + System.out.println("The Office " + + (terminated ? + "has been terminated" : + "is still running, we are at work")); + + // no longer at work + atWork = false; + // once more: try to terminate + terminated = xDesktop.terminate(); + System.out.println("The Office " + + (terminated ? + "has been terminated" : + "is still running. Someone else prevents termination, " + + "e.g. the quickstarter")); + } + catch (java.lang.Exception e){ + e.printStackTrace(); + } + finally { + System.exit(0); + } + + + } + public static boolean isAtWork() { + return atWork; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ProfUNO/CppBinding/Makefile b/odk/examples/DevelopersGuide/ProfUNO/CppBinding/Makefile new file mode 100644 index 000000000..5e4a06138 --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/CppBinding/Makefile @@ -0,0 +1,117 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the ProfUNO cpp binding example of the Developers Guide + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=ProfUnoCppBinding +SAMPLE_INC_OUT = $(OUT_INC)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT = $(OUT_MISC)/$(SAMPLE_NAME) +SAMPLE_OBJ_OUT=$(OUT_OBJ)/$(SAMPLE_NAME) + +APP1_NAME=office_connect +APP1_BINARY=$(OUT_BIN)/$(APP1_NAME)$(EXE_EXT) + +APP2_NAME=string_samples +APP2_BINARY=$(OUT_BIN)/$(APP2_NAME)$(EXE_EXT) + +ENV_OFFICE_TYPES=-env:URE_MORE_TYPES=$(URLPREFIX)$(OFFICE_TYPES) + +CXXFILES = \ + office_connect.cxx \ + string_samples.cxx + +# Targets +.PHONY: ALL +ALL : \ + ProUNOCppBindingExample + +include $(SETTINGS)/stdtarget.mk + +$(SAMPLE_OBJ_OUT)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(SAMPLE_INC_OUT) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +$(OUT_BIN)/%$(EXE_EXT) : $(SAMPLE_OBJ_OUT)/%.$(OBJ_EXT) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) +ifeq "$(OS)" "WIN" + $(LINK) $(EXE_LINK_FLAGS) /OUT:$@ /MAP:$(SAMPLE_GEN_OUT)/$(subst $(EXE_EXT),.map,$(@F)) \ + $< $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) +else + $(LINK) $(EXE_LINK_FLAGS) $(LINK_LIBS) -o $@ $< \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) $(STDC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS_BIN) $@ +endif +endif + +$(OUT_BIN)/office_connect$(EXE_EXT) : $(SAMPLE_OBJ_OUT)/office_connect.$(OBJ_EXT) + +$(OUT_BIN)/string_samples$(EXE_EXT) : $(SAMPLE_OBJ_OUT)/string_samples.$(OBJ_EXT) + +ProUNOCppBindingExample : $(APP1_BINARY) $(APP2_BINARY) + @echo -------------------------------------------------------------------------------- + @echo Note: For the "$(QM)$(APP1_NAME)$(QM)" example you need a running office listening + @echo $(SQM) $(SQM)on port 2083. The example use the defaultBootstrap_InitialComponentContext method and provides + @echo $(SQM) $(SQM)the additional office types via the UNO environment variable -env:URE_MORE_TYPES=... + @echo $(SQM) $(SQM)Before you can run this example you have to start your office in listening mode. + @echo - + @echo $(SQM) $(SQM)soffice "$(QM)--accept=socket,host=localhost,port=2083;urp;StarOffice.ServiceManager$(QM)" + @echo ----- + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP2_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_BIN)/%$(EXE_EXT) + cd $(subst /,$(PS),$(OUT_BIN)) && $(basename $@) + +$(API1_NAME).run: $(API1_BINARY) + cd $(subst /,$(PS),$(OUT_BIN)) && $(basename $@) $(ENV_OFFICE_TYPES) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_INC_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_OBJ_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_BIN)/$(APP1_NAME)*)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_BIN)/$(APP2_NAME)*)) diff --git a/odk/examples/DevelopersGuide/ProfUNO/CppBinding/office_connect.cxx b/odk/examples/DevelopersGuide/ProfUNO/CppBinding/office_connect.cxx new file mode 100644 index 000000000..c51ca17f8 --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/CppBinding/office_connect.cxx @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include + +#include + +#include +#include +#include +#include + +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::bridge; +using namespace cppu; + +using ::rtl::OString; +using ::rtl::OUString; +using ::rtl::OUStringToOString; + +SAL_IMPLEMENT_MAIN() +{ + // create the initial component context + Reference< XComponentContext > rComponentContext = + defaultBootstrap_InitialComponentContext(); + + // retrieve the servicemanager from the context + Reference< XMultiComponentFactory > rServiceManager = + rComponentContext->getServiceManager(); + + // instantiate a sample service with the servicemanager. + Reference< XInterface > rInstance = + rServiceManager->createInstanceWithContext( + "com.sun.star.bridge.UnoUrlResolver", + rComponentContext ); + + // Query for the XUnoUrlResolver interface + Reference< XUnoUrlResolver > rResolver( rInstance, UNO_QUERY ); + + if( ! rResolver.is() ) + { + printf( "Error: Couldn't instantiate com.sun.star.bridge.UnoUrlResolver service\n" ); + return 1; + } + try + { + // resolve the uno-url + rInstance = rResolver->resolve( OUString( + "uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" ) ); + + if( ! rInstance.is() ) + { + printf( "StarOffice.ServiceManager is not exported from remote counterpart\n" ); + return 1; + } + + // query for the simpler XMultiServiceFactory interface, sufficient for scripting + Reference< XMultiServiceFactory > rOfficeServiceManager (rInstance, UNO_QUERY); + + if( ! rInstance.is() ) + { + printf( "XMultiServiceFactory interface is not exported for StarOffice.ServiceManager\n" ); + return 1; + } + + printf( "Connected successfully to the office\n" ); + } + catch( Exception &e ) + { + OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ); + printf( "Error: %s\n", o.pData->buffer ); + return 1; + } + return 0; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ProfUNO/CppBinding/string_samples.cxx b/odk/examples/DevelopersGuide/ProfUNO/CppBinding/string_samples.cxx new file mode 100644 index 000000000..ecb21116a --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/CppBinding/string_samples.cxx @@ -0,0 +1,87 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include + +#include + +#include +#include + +using rtl::OUString; +using rtl::OUStringBuffer; +using rtl::OString; + +SAL_IMPLEMENT_MAIN() +{ + // string concatenation + + sal_Int32 n = 42; + double pi = 3.14159; + + // give it an initial size, should be a good guess. + // stringbuffer extends if necessary + OUStringBuffer buf( 128 ); + + // append an ascii string + buf.append( "pi ( here " ); + + // numbers can be simply appended + buf.append( pi ); + + // lets the compiler count the stringlength, so this is more efficient than + // the above appendAscii call, where length of the string must be calculated at + // runtime + buf.append( " ) multiplied with " ); + buf.append( n ); + buf.append( " gives " ); + buf.append( (double)( n * pi ) ); + buf.append( "." ); + + // now transfer the buffer into the string. + // afterwards buffer is empty and may be reused again ! + OUString string = buf.makeStringAndClear(); + + // I could of course also used the OStringBuffer directly + OString oString = rtl::OUStringToOString( string , RTL_TEXTENCODING_ASCII_US ); + + // just to print something + printf( "%s\n" ,oString.getStr() ); + + return 0; +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/ConnectionAwareClient.java b/odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/ConnectionAwareClient.java new file mode 100644 index 000000000..136400544 --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/ConnectionAwareClient.java @@ -0,0 +1,255 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.awt.*; +import java.awt.event.*; + +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.connection.XConnector; +import com.sun.star.connection.XConnection; + +import com.sun.star.beans.XPropertySet; + +import com.sun.star.lang.XComponent; + +import com.sun.star.bridge.XBridgeFactory; +import com.sun.star.bridge.XBridge; + + +public class ConnectionAwareClient extends java.awt.Frame + implements ActionListener , com.sun.star.lang.XEventListener +{ + private final Button _btnWriter; + private final Label _txtLabel; + private final String _url; + + private final XComponentContext _ctx; + + private com.sun.star.frame.XComponentLoader _officeComponentLoader; + + public ConnectionAwareClient( XComponentContext ctx , String url ) + { + _url = url; + _ctx = ctx; + + Panel p1 = new Panel(); + _btnWriter = new Button("New writer"); + Button _btnCalc = new Button("New calc"); + _txtLabel = new Label( "disconnected" ); + + _btnWriter.addActionListener(this); + _btnCalc.addActionListener(this); + p1.add( _btnWriter ); + p1.add( _btnCalc ); + p1.add( _txtLabel ); + + addWindowListener( + new WindowAdapter() + { + @Override + public void windowClosing(WindowEvent event) + { + System.exit(0); + } + } + ); + + add( p1 ); + } + + public void disposing( com.sun.star.lang.EventObject event ) + { + // remote bridge has gone down, because the office crashed or was terminated. + _officeComponentLoader = null; + _txtLabel.setText( "disconnected" ); + } + + public void actionPerformed( ActionEvent event ) + { + try + { + String sUrl; + if( event.getSource() == _btnWriter ) + { + sUrl = "private:factory/swriter"; + } + else + { + sUrl = "private:factory/scalc"; + } + getComponentLoader().loadComponentFromURL( + sUrl, "_blank", 0,new com.sun.star.beans.PropertyValue[0] ); + _txtLabel.setText( "connected" ); + } + catch ( com.sun.star.connection.NoConnectException exc ) + { + _txtLabel.setText( exc.getMessage() ); + } + catch ( com.sun.star.uno.Exception exc ) + { + _txtLabel.setText( exc.getMessage() ); + throw new java.lang.RuntimeException( exc ); + } + } + + /** separates the uno-url into 3 different parts. + */ + protected static String[] parseUnoUrl( String url ) + { + String [] aRet = new String [3]; + + if( ! url.startsWith( "uno:" ) ) + { + return null; + } + + int semicolon = url.indexOf( ';' ); + if( semicolon == -1 ) + return null; + + aRet[0] = url.substring( 4 , semicolon ); + int nextSemicolon = url.indexOf( ';' , semicolon+1); + + if( semicolon == -1 ) + return null; + aRet[1] = url.substring( semicolon+1, nextSemicolon ); + + aRet[2] = url.substring( nextSemicolon+1); + return aRet; + } + + + + protected com.sun.star.frame.XComponentLoader getComponentLoader() + throws com.sun.star.uno.Exception + { + XComponentLoader officeComponentLoader = _officeComponentLoader; + + if( officeComponentLoader == null ) + { + // instantiate connector service + Object x = _ctx.getServiceManager().createInstanceWithContext( + "com.sun.star.connection.Connector", _ctx ); + + XConnector xConnector = UnoRuntime.queryInterface(XConnector.class, x); + + String a[] = parseUnoUrl( _url ); + if( null == a ) + { + throw new com.sun.star.uno.Exception( "Couldn't parse uno-url "+ _url ); + } + + // connect using the connection string part of the uno-url only. + XConnection connection = xConnector.connect( a[0] ); + + x = _ctx.getServiceManager().createInstanceWithContext( + "com.sun.star.bridge.BridgeFactory", _ctx ); + + XBridgeFactory xBridgeFactory = UnoRuntime.queryInterface( + XBridgeFactory.class , x ); + + // create a nameless bridge with no instance provider + // using the middle part of the uno-url + XBridge bridge = xBridgeFactory.createBridge( "" , a[1] , connection , null ); + + // query for the XComponent interface and add this as event listener + XComponent xComponent = UnoRuntime.queryInterface( + XComponent.class, bridge ); + xComponent.addEventListener( this ); + + // get the remote instance + x = bridge.getInstance( a[2] ); + + // Did the remote server export this object ? + if( null == x ) + { + throw new com.sun.star.uno.Exception( + "Server didn't provide an instance for" + a[2], null ); + } + + // Query the initial object for its main factory interface + XMultiComponentFactory xOfficeMultiComponentFactory = UnoRuntime.queryInterface( XMultiComponentFactory.class, x ); + + // retrieve the component context (it's not yet exported from the office) + // Query for the XPropertySet interface. + XPropertySet xProperySet = UnoRuntime.queryInterface( XPropertySet.class, xOfficeMultiComponentFactory ); + + // Get the default context from the office server. + Object oDefaultContext = + xProperySet.getPropertyValue( "DefaultContext" ); + + // Query for the interface XComponentContext. + XComponentContext xOfficeComponentContext = + UnoRuntime.queryInterface( + XComponentContext.class, oDefaultContext ); + + + // now create the desktop service + // NOTE: use the office component context here ! + Object oDesktop = xOfficeMultiComponentFactory.createInstanceWithContext( + "com.sun.star.frame.Desktop", xOfficeComponentContext ); + + officeComponentLoader = UnoRuntime.queryInterface( XComponentLoader.class, oDesktop ); + + if( officeComponentLoader == null ) + { + throw new com.sun.star.uno.Exception( + "Couldn't instantiate com.sun.star.frame.Desktop" , null ); + } + _officeComponentLoader = officeComponentLoader; + } + return officeComponentLoader; + } + + public static void main( String [] args ) throws java.lang.Exception + { + if( args.length != 1 ) + { + System.out.println( "usage: ConnectionAwareClient uno-url" ); + return; + } + XComponentContext ctx = + com.sun.star.comp.helper.Bootstrap.createInitialComponentContext( null ); + + ConnectionAwareClient connAware = new ConnectionAwareClient( ctx, args[0]); + connAware.pack(); + connAware.setVisible( true ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/Makefile b/odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/Makefile new file mode 100644 index 000000000..84920642c --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/Makefile @@ -0,0 +1,85 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the ProfUNO interprocess example of the Developers Guide. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=ProfUNOInterprocessExamples +OUT_APP_CLASS=$(OUT_CLASS)/$(EXAMPLE_NAME) + +JAVAFILES = \ + ConnectionAwareClient.java \ + UrlResolver.java + +CLASSFILES = $(patsubst %.java,$(OUT_APP_CLASS)/%.class,$(JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_APP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(EXAMPLE_NAME) : $(CLASSFILES) + @echo -------------------------------------------------------------------------------- + @echo Note: For these examples you need a running office listening on port 2083. + @echo $(SQM) $(SQM)Before you run these examples you have to start your office with + @echo - + @echo $(SQM) $(SQM)soffice "$(QM)--accept=socket,host=localhost,port=2083;urp;StarOffice.ServiceManager$(QM)" + @echo ----- + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) ConnectionAwareClient.run + @echo $(MAKE) UrlResolver.run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.class + $(SDK_JAVA) -classpath "$(SDK_CLASSPATH)" $(basename $@) "uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/UrlResolver.java b/odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/UrlResolver.java new file mode 100644 index 000000000..b05c4b7b5 --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/InterprocessConn/UrlResolver.java @@ -0,0 +1,112 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.bridge.XUnoUrlResolver; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XMultiComponentFactory; + + +class UrlResolver +{ + public static void main( String [] args ) throws java.lang.Exception + { + if( args.length != 1 ) + { + System.out.println( "usage: UrlResolver uno-url\n" + + " uno-url The uno-url identifying the object to\n" + + " be imported, for instance\n" + + " uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" + + " (use \" on unix shells to avoid ;-problems" ); + System.exit( 1 ); + } + + // create default local component context + XComponentContext xLocalContext = + com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null); + + // initial serviceManager + XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager(); + + // create a urlresolver + Object urlResolver = xLocalServiceManager.createInstanceWithContext( + "com.sun.star.bridge.UnoUrlResolver", xLocalContext ); + + // query for the XUnoUrlResolver interface + XUnoUrlResolver xUrlResolver = + UnoRuntime.queryInterface( XUnoUrlResolver.class, urlResolver ); + + try + { + // Import the object + Object rInitialObject = xUrlResolver.resolve( args[0] ); + + // XComponentContext + if( null != rInitialObject ) + { + System.out.println( "initial object successfully retrieved" ); + } + else + { + System.out.println( "given initial-object name unknown at server side" ); + } + } + catch( com.sun.star.connection.NoConnectException e ) + { + System.out.println( "Couldn't connect to remote server" ); + System.out.println( e.getMessage() ); + } + catch( com.sun.star.connection.ConnectionSetupException e ) + { + System.out.println( "Couldn't access necessary local resource to establish the interprocess connection" ); + System.out.println( e.getMessage() ); + } + catch( com.sun.star.lang.IllegalArgumentException e ) + { + System.out.println( "uno-url is syntactical illegal ( " + args[0] + " )" ); + System.out.println( e.getMessage() ); + } + catch( com.sun.star.uno.RuntimeException e ) + { + System.out.println( "RuntimeException" ); + System.out.println( e.getMessage() ); + } + finally { + System.exit(0); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ProfUNO/Lifetime/Makefile b/odk/examples/DevelopersGuide/ProfUNO/Lifetime/Makefile new file mode 100644 index 000000000..2b3347459 --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/Lifetime/Makefile @@ -0,0 +1,112 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the ProfUNO lifetime example of the Developers Guide + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMPONENT_NAME=ProfUnoLifetime +OUT_COMP_CLASS=$(OUT_CLASS)/$(COMPONENT_NAME) +OUT_COMP_INC=$(OUT_INC)/$(COMPONENT_NAME) +OUT_COMP_GEN=$(OUT_MISC)/$(COMPONENT_NAME) +OUT_COMP_OBJ=$(OUT_OBJ)/$(COMPONENT_NAME) + +JAVAFILES = \ + MyUnoObject.java + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/JavaComp/%.class,$(JAVAFILES)) + +CXXFILES = object_lifetime.cxx + +OBJFILES = $(patsubst %.cxx,$(OUT_COMP_OBJ)/%.$(OBJ_EXT),$(CXXFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : \ + ProUNOLifetimeExamples + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $< + +$(OUT_COMP_OBJ)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +$(OUT_BIN)/$(COMPONENT_NAME)$(EXE_EXT) : $(OBJFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)) +ifeq "$(OS)" "WIN" + $(LINK) $(EXE_LINK_FLAGS) /OUT:$@ /MAP:$(OUT_COMP_GEN)/$(subst $(EXE_EXT),.map,$(@F)) \ + $(OBJFILES) $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) +else + $(LINK) $(EXE_LINK_FLAGS) $(LINK_LIBS) -o $@ $(OBJFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) $(STDC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS_BIN) $@ +endif +endif + +ProUNOLifetimeExamples : $(OUT_BIN)/$(COMPONENT_NAME)$(EXE_EXT) $(OUT_COMP_CLASS)/MyUnoObject.class + @echo -------------------------------------------------------------------------------- + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) MyUnoObject.run + @echo $(MAKE) ProfUnoLifetime.runexe + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.class + $(SDK_JAVA) -classpath "$(SDK_CLASSPATH)" $(basename $@) + +%.runexe: $(OUT_BIN)/%$(EXE_EXT) + cd $(subst /,$(PS),$(OUT_BIN)) && $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_OBJ)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_BIN)/$(COMPONENT_NAME)$(EXE_EXT))) diff --git a/odk/examples/DevelopersGuide/ProfUNO/Lifetime/MyUnoObject.java b/odk/examples/DevelopersGuide/ProfUNO/Lifetime/MyUnoObject.java new file mode 100644 index 000000000..516481a8f --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/Lifetime/MyUnoObject.java @@ -0,0 +1,63 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +class MyUnoObject implements com.sun.star.uno.XInterface +{ + + @Override + protected void finalize() throws Throwable { + System.out.println( "finalizer called" ); + super.finalize(); + } + + public static void main( String args[] ) throws InterruptedException + { + com.sun.star.uno.XInterface a = new MyUnoObject(); + a = null; + + // ask the garbage collector politely + System.gc(); + synchronized( Thread.currentThread() ) + { + // wait a second + Thread.currentThread().wait( 1000 ); + } + System.out.println( "leaving" ); + + // It is java VM dependent, whether the finalizer was called or not + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ProfUNO/Lifetime/object_lifetime.cxx b/odk/examples/DevelopersGuide/ProfUNO/Lifetime/object_lifetime.cxx new file mode 100644 index 000000000..f92731d37 --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/Lifetime/object_lifetime.cxx @@ -0,0 +1,71 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include + +#include + +class MyOWeakObject : public ::cppu::OWeakObject +{ +public: + MyOWeakObject() { fprintf( stdout, "constructed\n" ); } + ~MyOWeakObject() { fprintf( stdout, "destructed\n" ); } +}; + + +void simple_object_creation_and_destruction() +{ + // create the UNO object + com::sun::star::uno::XInterface * p = new MyOWeakObject(); + + // acquire it, refcount becomes one + p->acquire(); + + fprintf( stdout, "before release\n" ); + + // release it, refcount drops to zero + p->release(); + + fprintf( stdout, "after release\n" ); +} + + +int main() +{ + simple_object_creation_and_destruction(); + return 0; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_cpp/Makefile b/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_cpp/Makefile new file mode 100644 index 000000000..de4604e82 --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_cpp/Makefile @@ -0,0 +1,100 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the SimpleBootstrap_cpp example of the SDK. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +APP_NAME=SimpleBootstrap_cpp + +OUT_APP_INC = $(OUT_INC)/$(APP_NAME) +OUT_APP_GEN = $(OUT_MISC)/$(APP_NAME) +OUT_APP_OBJ=$(OUT_OBJ)/$(APP_NAME) + +CXXFILES = SimpleBootstrap_cpp.cxx + +OBJFILES = $(patsubst %.cxx,$(OUT_SLO_COMP)/%.$(OBJ_EXT),$(CXXFILES)) + +# Targets +.PHONY: ALL +ALL : \ + SimpleBootstrapCppExample + +include $(SETTINGS)/stdtarget.mk + +$(OUT_APP_OBJ)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(OUT_APP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +$(OUT_BIN)/_$(APP_NAME)$(EXE_EXT) : $(OUT_APP_OBJ)/$(APP_NAME).$(OBJ_EXT) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_APP_GEN)) +ifeq "$(OS)" "WIN" + $(LINK) $(EXE_LINK_FLAGS) /OUT:$@ /MAP:$(OUT_APP_GEN)/$(basename $(@F)).map \ + $< $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) +else + $(LINK) $(EXE_LINK_FLAGS) $(LINK_LIBS) -o $@ $< \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) $(STDC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS_BIN) $@ +endif +endif + +$(OUT_BIN)/$(APP_NAME)$(EXE_EXT) : $(OUT_BIN)/_$(APP_NAME)$(EXE_EXT) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(COPY) $(subst /,$(PS),$(BIN_DIR)/unoapploader$(EXE_EXT)) $(subst /,$(PS),$@) +# workaround for touch problem under Windows with full qualified paths + make -t $@ + +SimpleBootstrapCppExample : $(OUT_BIN)/$(APP_NAME)$(EXE_EXT) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) SimpleBootstrap_cpp.run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_BIN)/SimpleBootstrap_cpp$(EXE_EXT) + cd $(subst /,$(PS),$(OUT_BIN)) && $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_OBJ)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_BIN)/*SimpleBootstrap*)) diff --git a/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_cpp/SimpleBootstrap_cpp.cxx b/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_cpp/SimpleBootstrap_cpp.cxx new file mode 100644 index 000000000..fe7354d48 --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_cpp/SimpleBootstrap_cpp.cxx @@ -0,0 +1,104 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include + +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::frame; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; + +SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv) +{ + try + { + // get the remote office component context + Reference< XComponentContext > xContext( ::cppu::bootstrap() ); + if ( !xContext.is() ) + { + fprintf(stderr, "no component context!\n"); + return 1; + } + + // get the remote office service manager + Reference< XMultiComponentFactory > xServiceManager( + xContext->getServiceManager() ); + if ( !xServiceManager.is() ) + { + fprintf(stderr, "no service manager!\n"); + return 1; + } + + // get an instance of the remote office desktop UNO service + // and query the XComponentLoader interface + Reference < XDesktop2 > xComponentLoader = Desktop::create(xContext); + + // open a spreadsheet document + Reference< XComponent > xComponent( xComponentLoader->loadComponentFromURL( + OUString( "private:factory/scalc" ), + OUString( "_blank" ), 0, + Sequence < ::com::sun::star::beans::PropertyValue >() ) ); + if ( !xComponent.is() ) + { + fprintf(stderr, "opening spreadsheet document failed!\n"); + return 1; + } + } + catch ( ::cppu::BootstrapException & e ) + { + fprintf(stderr, "caught BootstrapException: %s\n", + OUStringToOString( e.getMessage(), RTL_TEXTENCODING_ASCII_US ).getStr()); + return 1; + } + catch ( Exception & e ) + { + fprintf(stderr, "caught UNO exception: %s\n", + OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ).getStr()); + return 1; + } + + return 0; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/Makefile b/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/Makefile new file mode 100644 index 000000000..819a61042 --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/Makefile @@ -0,0 +1,90 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the SimpleBootstrap_java example. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMPONENT_NAME=SimpleBootstrap_java +OUT_COMP_CLASS = $(OUT_CLASS)/$(COMPONENT_NAME) + +COMPONENT_JAR_NAME = $(COMPONENT_NAME).jar +COMPONENT_JAR = $(OUT_CLASS)/$(COMPONENT_JAR_NAME) + +JAVAFILES = \ + SimpleBootstrap_java.java + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + +# Targets +.PHONY: ALL +ALL : \ + SimpleBootstrapJavaExample + +include $(SETTINGS)/stdtarget.mk + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(JAVAFILES) + +$(OUT_CLASS)/%.jar : manifest.mf $(CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(OUT_COMP_CLASS) . + $(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +SimpleBootstrapJavaExample : $(COMPONENT_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) SimpleBootstrap_java.run + @echo -------------------------------------------------------------------------------- + +# Setting the optional system property "com.sun.star.lib.loader.unopath" to the office +# program path ensures that the configured SDK office is used. If the system property +# is not specified, the default office installation is used. +%.run: $(COMPONENT_JAR) + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $(COMPONENT_JAR) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMPONENT_JAR))) diff --git a/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/SimpleBootstrap_java.java b/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/SimpleBootstrap_java.java new file mode 100644 index 000000000..0146dcb6d --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/SimpleBootstrap_java.java @@ -0,0 +1,77 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.beans.PropertyValue; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XMultiComponentFactory; + +public class SimpleBootstrap_java { + + public static void main(String[] args) { + + try { + // get the remote office component context + XComponentContext xContext = + com.sun.star.comp.helper.Bootstrap.bootstrap(); + + // get the remote office service manager + XMultiComponentFactory xServiceManager = + xContext.getServiceManager(); + + // get an instance of the remote office desktop UNO service + Object desktop = xServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext ); + + // query the XComponentLoader interface from the desktop + XComponentLoader xComponentLoader = + UnoRuntime.queryInterface( + XComponentLoader.class, desktop ); + + // load a spreadsheet document + String loadURL = "private:factory/scalc"; + PropertyValue[] loadProps = new PropertyValue[0]; + xComponentLoader.loadComponentFromURL( + loadURL, "_blank", 0, loadProps); + } + catch (java.lang.Exception e){ + e.printStackTrace(); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/manifest.mf b/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/manifest.mf new file mode 100644 index 000000000..e1326fa0b --- /dev/null +++ b/odk/examples/DevelopersGuide/ProfUNO/SimpleBootstrap_java/manifest.mf @@ -0,0 +1,4 @@ +Main-Class: com.sun.star.lib.loader.Loader + +Name: com/sun/star/lib/loader/Loader.class +Application-Class: SimpleBootstrap_java diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/META-INF/manifest.xml b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/META-INF/manifest.xml new file mode 100644 index 000000000..e7bf06b4e --- /dev/null +++ b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/META-INF/manifest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/Makefile b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/Makefile new file mode 100644 index 000000000..0df943224 --- /dev/null +++ b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/Makefile @@ -0,0 +1,128 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OOoBean of the Developers Guide + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=SayHello +SAMPLE_CLASS_OUT = $(OUT_CLASS)/ScriptingFramework/$(SAMPLE_NAME) +SAMPLE_GEN_OUT = $(OUT_MISC)/ScriptingFramework + +SCRIPT_NAME=SayHello +SCRIPT_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(SCRIPT_NAME) +SCRIPT_GEN_OUT=$(SAMPLE_GEN_OUT)/$(SCRIPT_NAME) +SCRIPT_JAR_NAME=$(SCRIPT_NAME).jar +SCRIPT_JAR=$(SAMPLE_CLASS_OUT)/$(SCRIPT_JAR_NAME) +SCRIPT_PACKAGE = $(OUT_BIN)/$(SCRIPT_NAME).$(UNOOXT_EXT) +SCRIPT_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(SCRIPT_NAME).$(UNOOXT_EXT)") +SCRIPT_REGISTERFLAG=$(SCRIPT_GEN_OUT)$(PS)devguide_scriptingframework_$(SCRIPT_NAME)_register_scriptpkg.flag + +JAVAFILES = \ + SayHello/SayHello.java + +CLASSFILES = $(patsubst %.java,$(SCRIPT_CLASS_OUT)/%.class,$(subst $(SAMPLE_NAME)/,,$(JAVAFILES))) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)) + +# Targets +.PHONY: ALL +ALL : \ + SayHelloExample + +include $(SETTINGS)/stdtarget.mk + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SCRIPT_CLASS_OUT) $(JAVAFILES) + +$(SCRIPT_JAR) : $(CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvf $@ $(CLASSNAMES) -C $(SCRIPT_CLASS_OUT) . + +# rule for component package file +$(SCRIPT_PACKAGE) : $(SCRIPT_JAR) META-INF/manifest.xml $(SCRIPT_NAME)/parcel-descriptor.xml + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ META-INF/manifest.xml $(SCRIPT_NAME)/parcel-descriptor.xml + cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)/..) && $(SDK_ZIP) -u ../../bin/$(@F) $(SAMPLE_NAME)/$(SCRIPT_JAR_NAME) + +$(SCRIPT_REGISTERFLAG) : $(SCRIPT_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(SCRIPT_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + + +SayHelloExample : $(SCRIPT_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The "$(QM)$(SCRIPT_NAME)$(QM)" scripting package was installed in your office installation + @echo if SDK_AUTO_DEPLOYMENT = YES. If you want to run the script, start the Office + @echo and use the Tools/Macros/Run Macro menu item. + @echo You can also load the document "$(QM)$(SCRIPT_NAME).odt$(QM)" and press the button to run the + @echo script. + @echo - + @echo $(MAKE) $(SCRIPT_NAME).odt.load + @echo -------------------------------------------------------------------------------- + +$(SCRIPT_NAME).odt.load : $(SCRIPT_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +%.run: $(CLASSFILES) + $(SDK_JAVA) -classpath "$(SDK_CLASSPATH)" $(subst /,.,$(PACKAGE)).$(basename $@) + +%.dbg: $(JAR1_JAR) + jdb -classpath "$(SDK_CLASSPATH)" $(subst /,.,$(PACKAGE)).$(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SCRIPT_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SCRIPT_PACKAGE_URL))) + diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello.odt b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello.odt new file mode 100644 index 000000000..e18331915 Binary files /dev/null and b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello.odt differ diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello/SayHello.java b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello/SayHello.java new file mode 100644 index 000000000..22fd05188 --- /dev/null +++ b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello/SayHello.java @@ -0,0 +1,65 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.script.provider.XScriptContext; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.lang.XComponent; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextRange; +import com.sun.star.text.XText; +import com.sun.star.beans.PropertyValue; +import com.sun.star.awt.ActionEvent; + +public class SayHello +{ + public static void start(XScriptContext ctxt, ActionEvent e) + throws Exception + { + SayHello.start(ctxt); + } + + public static void start(XScriptContext ctxt) + throws Exception + { + // getting the text document object + XTextDocument xTextDocument = createDocument(ctxt); + + XText xText = xTextDocument.getText(); + XTextRange xTextRange = xText.getEnd(); + xTextRange.setString("Hello"); + } + + private static XTextDocument createDocument(XScriptContext ctxt) + throws Exception + { + XComponentLoader loader = UnoRuntime.queryInterface( + XComponentLoader.class, ctxt.getDesktop()); + + XComponent comp = loader.loadComponentFromURL( + "private:factory/swriter", "_blank", 4, new PropertyValue[0]); + + XTextDocument doc = UnoRuntime.queryInterface( XTextDocument.class, comp); + + return doc; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello/parcel-descriptor.xml b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello/parcel-descriptor.xml new file mode 100644 index 000000000..f1c395a3f --- /dev/null +++ b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/SayHello/parcel-descriptor.xml @@ -0,0 +1,33 @@ + + + + + diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/build.xml b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/build.xml new file mode 100644 index 000000000..b79ac64ae --- /dev/null +++ b/odk/examples/DevelopersGuide/ScriptingFramework/SayHello/build.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/META-INF/manifest.xml b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/META-INF/manifest.xml new file mode 100644 index 000000000..0b86e92ad --- /dev/null +++ b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/META-INF/manifest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/Makefile b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/Makefile new file mode 100644 index 000000000..6fa4046bd --- /dev/null +++ b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/Makefile @@ -0,0 +1,130 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OOoBean of the Developers Guide + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=ScriptSelector +SAMPLE_CLASS_OUT = $(OUT_CLASS)/ScriptingFramework/$(SAMPLE_NAME) +SAMPLE_GEN_OUT = $(OUT_MISC)/ScriptingFramework + +SCRIPT_NAME=ScriptSelector +SCRIPT_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(SCRIPT_NAME) +SCRIPT_GEN_OUT=$(SAMPLE_GEN_OUT)/$(SCRIPT_NAME) +SCRIPT_JAR_NAME=$(SCRIPT_NAME).jar +SCRIPT_JAR=$(SAMPLE_CLASS_OUT)/$(SCRIPT_JAR_NAME) +SCRIPT_PACKAGE = $(OUT_BIN)/$(SCRIPT_NAME).$(UNOOXT_EXT) +SCRIPT_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(SCRIPT_NAME).$(UNOOXT_EXT)") +SCRIPT_REGISTERFLAG=$(SCRIPT_GEN_OUT)$(PS)devguide_scriptingframework_$(SCRIPT_NAME)_register.flag + +JAVAFILES = \ + ScriptSelector/ScriptSelector.java + +CLASSFILES = $(patsubst %.java,$(SCRIPT_CLASS_OUT)/%.class,$(subst $(SAMPLE_NAME)/,,$(JAVAFILES))) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)) + +# Targets +.PHONY: ALL +ALL : ScriptSelectorExample + +include $(SETTINGS)/stdtarget.mk + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SCRIPT_CLASS_OUT) $(JAVAFILES) + +$(SCRIPT_JAR) : $(CLASSFILES) $(SCRIPT_NAME)/container.gif $(SCRIPT_NAME)/script.gif $(SCRIPT_NAME)/soffice.gif + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(COPY) $(subst /,$(PS),$(SCRIPT_NAME)/container.gif) $(subst /,$(PS),$(SCRIPT_CLASS_OUT)) + $(COPY) $(subst /,$(PS),$(SCRIPT_NAME)/script.gif) $(subst /,$(PS),$(SCRIPT_CLASS_OUT)) + $(COPY) $(subst /,$(PS),$(SCRIPT_NAME)/soffice.gif) $(subst /,$(PS),$(SCRIPT_CLASS_OUT)) + $(SDK_JAR) cvf $@ -C $(SCRIPT_CLASS_OUT) . + +# rule for component package file +$(SCRIPT_PACKAGE) : $(SCRIPT_JAR) META-INF/manifest.xml $(SCRIPT_NAME)/parcel-descriptor.xml + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ META-INF/manifest.xml $(SCRIPT_NAME)/parcel-descriptor.xml + cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)/..) && $(SDK_ZIP) -u ../../bin/$(@F) $(SAMPLE_NAME)/$(SCRIPT_JAR_NAME) + +$(SCRIPT_REGISTERFLAG) : $(SCRIPT_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(SCRIPT_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + + +ScriptSelectorExample : $(SCRIPT_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The "$(QM)$(SCRIPT_NAME)$(QM)" scripting package was installed in your office installation + @echo if SDK_AUTO_DEPLOYMENT = YES. If you want to run the script, start the Office + @echo and use the Tools/Macros/Run Macro menu item. + @echo You can also load the document "$(QM)$(SCRIPT_NAME).odt$(QM)" and press the button to run + @echo the script. + @echo - + @echo $(MAKE) $(SCRIPT_NAME).odt.load + @echo -------------------------------------------------------------------------------- + +$(SCRIPT_NAME).odt.load : $(SCRIPT_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +%.run: $(CLASSFILES) + $(SDK_JAVA) -classpath "$(SDK_CLASSPATH)" $(subst /,.,$(PACKAGE)).$(basename $@) + +%.dbg: $(JAR1_JAR) + jdb -classpath "$(SDK_CLASSPATH)" $(subst /,.,$(PACKAGE)).$(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SCRIPT_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SCRIPT_PACKAGE_URL))) + diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector.odt b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector.odt new file mode 100644 index 000000000..323bb6edd Binary files /dev/null and b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector.odt differ diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/ScriptSelector.java b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/ScriptSelector.java new file mode 100644 index 000000000..fcf01a4c9 --- /dev/null +++ b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/ScriptSelector.java @@ -0,0 +1,353 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import javax.swing.*; +import javax.swing.tree.*; +import javax.swing.event.*; +import javax.swing.border.*; +import java.awt.*; +import java.awt.event.*; +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.beans.*; +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; +import com.sun.star.script.provider.XScriptProviderFactory; + +public class ScriptSelector { + + private static final int BIG_GAP = 10; + private static final int MED_GAP = 5; + + private static final String MSP_FACTORY = + "/singletons/com.sun.star.script.provider." + + "theMasterScriptProviderFactory"; + + private static final String BROWSE_FACTORY = + "/singletons/com.sun.star.script.browse.theBrowseNodeFactory"; + + private ScriptSelectorPanel selectorPanel; + + public void show(final XScriptContext ctxt) + { + try { + XBrowseNode root = getRootNode(ctxt); + + Object obj = ctxt.getComponentContext().getValueByName(MSP_FACTORY); + + XScriptProviderFactory fac = UnoRuntime.queryInterface(XScriptProviderFactory.class, obj); + + final XScriptProvider msp = + fac.createScriptProvider(new Any(new Type(), null)); + + final JFrame client = new JFrame("Script"); + + selectorPanel = new ScriptSelectorPanel(root); + + final JButton runButton, closeButton; + + runButton = new JButton("Run"); + runButton.setEnabled(false); + + closeButton = new JButton("Close"); + + JPanel northButtons = + new JPanel(new GridLayout(2, 1, MED_GAP, MED_GAP)); + + northButtons.add(runButton); + northButtons.add(closeButton); + + JPanel southButtons = + new JPanel(new GridLayout(3, 1, MED_GAP, MED_GAP)); + + selectorPanel.tree.addTreeSelectionListener( + new TreeSelectionListener() { + public void valueChanged(TreeSelectionEvent e) { + XBrowseNode xbn = selectorPanel.getSelection(); + XPropertySet props = UnoRuntime.queryInterface(XPropertySet.class, xbn); + + 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(); + } + } + }; + + runButton.addActionListener(listener); + closeButton.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 show(final XScriptContext ctxt, + final com.sun.star.awt.MouseEvent e) + { + show(ctxt); + } + + public void show(final XScriptContext ctxt, + final com.sun.star.awt.ActionEvent e) + { + show(ctxt); + } + + private XBrowseNode getRootNode(XScriptContext ctxt) { + + XBrowseNode result = null; + + XComponentContext xcc = ctxt.getComponentContext(); + XBrowseNodeFactory xBrowseFac = UnoRuntime.queryInterface( + XBrowseNodeFactory.class, xcc.getValueByName(BROWSE_FACTORY)); + + result = UnoRuntime.queryInterface( + XBrowseNode.class, xBrowseFac.createView( + BrowseNodeFactoryViewTypes.MACROSELECTOR ) ); + + return result; + } +} + +class ScriptSelectorPanel extends JPanel { + + private final XBrowseNode myrootnode; + public JTextField textField; + public JTree tree; + + 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) { + @Override + public String toString() { + return ((XBrowseNode)getUserObject()).getName(); + } + }; + initNodes(myrootnode, top); + DefaultTreeModel 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 = 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); + } + + + + + + private void initNodes(XBrowseNode parent, DefaultMutableTreeNode top) { + if ( parent == null || !parent.hasChildNodes() ) + { + 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]) { + @Override + 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 final ImageIcon sofficeIcon; + private final ImageIcon scriptIcon; + private final 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")); + } + + @Override + 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; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/container.gif b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/container.gif new file mode 100644 index 000000000..3a345f9bf Binary files /dev/null and b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/container.gif differ diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/parcel-descriptor.xml b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/parcel-descriptor.xml new file mode 100644 index 000000000..e5fc8a53d --- /dev/null +++ b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/parcel-descriptor.xml @@ -0,0 +1,33 @@ + + + + + diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/script.gif b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/script.gif new file mode 100644 index 000000000..d3b3768ca Binary files /dev/null and b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/script.gif differ diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/soffice.gif b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/soffice.gif new file mode 100644 index 000000000..88124d87d Binary files /dev/null and b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/ScriptSelector/soffice.gif differ diff --git a/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/build.xml b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/build.xml new file mode 100644 index 000000000..c29003046 --- /dev/null +++ b/odk/examples/DevelopersGuide/ScriptingFramework/ScriptSelector/build.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Spreadsheet/DataPilotReadme.txt b/odk/examples/DevelopersGuide/Spreadsheet/DataPilotReadme.txt new file mode 100644 index 000000000..7876b6a33 --- /dev/null +++ b/odk/examples/DevelopersGuide/Spreadsheet/DataPilotReadme.txt @@ -0,0 +1,48 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +ExampleDataPilotSource +====================== + +This example shows how you can implement an external DataPilot +component. + +Simple usage scenario: +====================== +1. build and deploy the component +2. open a new spreadsheet document +3. select for example cell B:2 +4. start the DataPilot dialog + Data->DataPilot->Start... +5. select "External source/interface -> Ok +6. select the example DataPilot + Use the drop down list and select the service + "ExampleDataPilotSource" -> Ok +7. Place some number fields in the field areas + For example: + - select the "ones" field and drop it in the "Row Fields" area + - repeat this step with the "tens" and "hundreds" field + - select the "thousands" field and drop it in the "Column Fields" + area. + -> press Ok +8. you see a matrix with rows and columns for the selected fields + and a value area with a sum up of all fields valid for this + coordinate. For example cell F:21=1221 (ones=B:21=1, tens=c:21=2 + hundreds=D:21=2 and thousands=F:3=1) + + diff --git a/odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.components b/odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.components new file mode 100644 index 000000000..6212c72d4 --- /dev/null +++ b/odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.components @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.java b/odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.java new file mode 100644 index 000000000..59cac873f --- /dev/null +++ b/odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.java @@ -0,0 +1,304 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +import com.sun.star.sheet.XResultListener; + +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +class ExampleAddInResult implements com.sun.star.sheet.XVolatileResult +{ + private final String aName; + private int nValue; + private final java.util.ArrayList aListeners = new java.util.ArrayList(); + + public ExampleAddInResult( String aNewName ) + { + aName = aNewName; + } + + private com.sun.star.sheet.ResultEvent getResult() + { + com.sun.star.sheet.ResultEvent aEvent = + new com.sun.star.sheet.ResultEvent(); + aEvent.Value = aName + " " + nValue; + aEvent.Source = this; + return aEvent; + } + + public void addResultListener(com.sun.star.sheet.XResultListener aListener) + { + aListeners.add( aListener ); + + // immediately notify of initial value + aListener.modified( getResult() ); + } + + public void removeResultListener(com.sun.star.sheet.XResultListener aListener) + { + aListeners.remove( aListener ); + } + + public void incrementValue() + { + ++nValue; + com.sun.star.sheet.ResultEvent aEvent = getResult(); + + for( XResultListener l : aListeners) + l.modified(aEvent); + } +} + +class ExampleAddInThread extends Thread +{ + private final java.util.HashMap aCounters; + + public ExampleAddInThread( java.util.HashMap aResults ) + { + aCounters = aResults; + } + + @Override + public void run() + { + while ( true ) + { + try + { + sleep(1000); + } + catch( InterruptedException exception ) + { + } + + // increment all counters + for (ExampleAddInResult r : aCounters.values()) + r.incrementValue(); + } + } +} + +public class ExampleAddIn +{ + public static class _ExampleAddIn extends com.sun.star.lib.uno.helper.WeakBase + implements org.openoffice.sheet.addin.XExampleAddIn, + com.sun.star.sheet.XAddIn, + com.sun.star.lang.XServiceName, + com.sun.star.lang.XServiceInfo + { + private static final String aExampleService = "org.openoffice.sheet.addin.ExampleAddIn"; + private static final String aAddInService = "com.sun.star.sheet.AddIn"; + private static final String aImplName = _ExampleAddIn.class.getName(); + + private static final short FUNCTION_INVALID = -1; + + private static final String[] aFunctionNames = + { + "getIncremented", + "getCounter" + }; + private static final String[] aDisplayFunctionNames = + { + "Increment", + "Counter" + }; + private static final String[] aDescriptions = + { + "Increments a value", + "Returns a counter" + }; + private static final String[] aFirstArgumentNames = + { + "Value", + "Name" + }; + private static final String[] aFirstArgumentDescriptions = + { + "The value that is incremented", + "The name of the counter" + }; + + private com.sun.star.lang.Locale aFuncLocale; + private java.util.HashMap aResults; + + public _ExampleAddIn( com.sun.star.lang.XMultiServiceFactory xFactory ) + { + } + + private int getFunctionID( String aProgrammaticFunctionName ) + { + for ( int i = 0; i < aFunctionNames.length; i++ ) + if ( aProgrammaticFunctionName.equals(aFunctionNames[i]) ) + return i; + return FUNCTION_INVALID; + } + + // XExampleAddIn + + public int getIncremented( int nValue ) + { + return nValue + 1; + } + + public com.sun.star.sheet.XVolatileResult getCounter(String aName) + { + if ( aResults == null ) + { + // create the table of results, and start a thread to increment + // all counters + aResults = new java.util.HashMap(); + ExampleAddInThread aThread = new ExampleAddInThread( aResults ); + aThread.start(); + } + + ExampleAddInResult aResult = aResults.get(aName); + if ( aResult == null ) + { + aResult = new ExampleAddInResult(aName); + aResults.put( aName, aResult ); + } + return aResult; + } + + // XAddIn + + public String getProgrammaticFuntionName(String aDisplayName) + { + for ( int i = 0; i < aFunctionNames.length; i++ ) + if ( aDisplayName.equals(aDisplayFunctionNames[i]) ) + return aFunctionNames[i]; + return ""; + } + + public String getDisplayFunctionName(String aProgrammaticName) + { + int nFunction = getFunctionID( aProgrammaticName ); + return ( nFunction == FUNCTION_INVALID ) ? "" : + aDisplayFunctionNames[nFunction]; + } + + public String getFunctionDescription(String aProgrammaticName) + { + int nFunction = getFunctionID( aProgrammaticName ); + return ( nFunction == FUNCTION_INVALID ) ? "" : + aDescriptions[nFunction]; + } + + public String getDisplayArgumentName(String aProgrammaticFunctionName, + int nArgument) + { + // both functions in this example only have a first argument + int nFunction = getFunctionID( aProgrammaticFunctionName ); + return ( nFunction == FUNCTION_INVALID || nArgument != 0) ? "" : + aFirstArgumentNames[nFunction]; + } + + public String getArgumentDescription(String aProgrammaticFunctionName, + int nArgument ) + { + // both functions in this example only have a first argument + int nFunction = getFunctionID( aProgrammaticFunctionName ); + return ( nFunction == FUNCTION_INVALID || nArgument != 0) ? "" : + aFirstArgumentDescriptions[nFunction]; + } + + public String getProgrammaticCategoryName(String aProgrammaticFunctionName) + { + return( "Add-In" ); + } + + public String getDisplayCategoryName(String aProgrammaticFunctionName) + { + return( "Add-In" ); + } + + // XLocalizable + + public void setLocale( com.sun.star.lang.Locale aLocale ) + { + // the locale is stored and used for getLocale, but otherwise + // ignored in this example + aFuncLocale = aLocale; + } + + public com.sun.star.lang.Locale getLocale() + { + return aFuncLocale; + } + + // XServiceName + + public String getServiceName() + { + return aExampleService; + } + + // XServiceInfo + + public String getImplementationName() + { + return aImplName; + } + + public String[] getSupportedServiceNames() + { + String [] aSupportedServices = new String[ 2 ]; + aSupportedServices[ 0 ] = aExampleService; + aSupportedServices[ 1 ] = aAddInService; + return aSupportedServices; + } + + public boolean supportsService( String aService ) + { + return (aService.equals( aExampleService ) || + aService.equals( aAddInService ) ); + } + + } + + + public static com.sun.star.lang.XSingleServiceFactory __getServiceFactory( + String implName, + com.sun.star.lang.XMultiServiceFactory multiFactory, + com.sun.star.registry.XRegistryKey regKey) + { + com.sun.star.lang.XSingleServiceFactory xSingleServiceFactory = null; + if ( implName.equals(_ExampleAddIn.aImplName) ) + xSingleServiceFactory = + com.sun.star.comp.loader.FactoryHelper.getServiceFactory( + _ExampleAddIn.class, _ExampleAddIn.aExampleService, + multiFactory, regKey); + return xSingleServiceFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.ods b/odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.ods new file mode 100644 index 000000000..b86f24915 Binary files /dev/null and b/odk/examples/DevelopersGuide/Spreadsheet/ExampleAddIn.ods differ diff --git a/odk/examples/DevelopersGuide/Spreadsheet/ExampleDataPilotSource.components b/odk/examples/DevelopersGuide/Spreadsheet/ExampleDataPilotSource.components new file mode 100644 index 000000000..f0881c1f5 --- /dev/null +++ b/odk/examples/DevelopersGuide/Spreadsheet/ExampleDataPilotSource.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/DevelopersGuide/Spreadsheet/ExampleDataPilotSource.java b/odk/examples/DevelopersGuide/Spreadsheet/ExampleDataPilotSource.java new file mode 100644 index 000000000..6b10da93c --- /dev/null +++ b/odk/examples/DevelopersGuide/Spreadsheet/ExampleDataPilotSource.java @@ -0,0 +1,990 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +import com.sun.star.sheet.DataPilotFieldFilter; + +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// Example DataPilot source component + +// helper class to hold the settings + +class ExampleSettings +{ + public static final int nDimensionCount = 6; + public static final int nValueDimension = 4; + public static final int nDataDimension = 5; + public static final String [] aDimensionNames = { + "ones", "tens", "hundreds", "thousands", "value", "" }; + + public static final String getMemberName( int nMember ) + { + return String.valueOf( nMember ); + } + + public int nMemberCount = 3; + public java.util.List aColDimensions = new java.util.ArrayList(); + public java.util.List aRowDimensions = new java.util.ArrayList(); +} + +// XPropertySetInfo implementation for getPropertySetInfo + +class ExamplePropertySetInfo implements com.sun.star.beans.XPropertySetInfo +{ + private final com.sun.star.beans.Property[] aProperties; + + public ExamplePropertySetInfo( com.sun.star.beans.Property[] aProps ) + { + aProperties = aProps; + } + + public com.sun.star.beans.Property[] getProperties() + { + return aProperties; + } + + public com.sun.star.beans.Property getPropertyByName( String aName ) + throws com.sun.star.beans.UnknownPropertyException + { + for ( int i=0; i= 0 ) + nDimensions = aSettings.aColDimensions.size(); + else + { + nPosition = aSettings.aRowDimensions.indexOf( Integer.valueOf(nDimension)); + if ( nPosition >= 0 ) + nDimensions = aSettings.aRowDimensions.size(); + } + + if ( nPosition < 0 ) + return new com.sun.star.sheet.MemberResult[0]; + + int nMembers = aSettings.nMemberCount; + int nRepeat = 1; + int nFill = 1; + for ( int i=0; i nPosition ) + nFill *= nMembers; + } + int nSize = nRepeat * nMembers * nFill; + + com.sun.star.sheet.MemberResult[] aResults = + new com.sun.star.sheet.MemberResult[nSize]; + int nResultPos = 0; + for (int nOuter=0; nOuter= 1 ) + { + String aSource = com.sun.star.uno.AnyConverter.toString(aArguments[0]); + if ( aSource != null && aSource.length() > 0) + { + int nValue = Integer.parseInt( aSource ); + if ( nValue >= 2 && nValue <= 10 ) + aSettings.nMemberCount = nValue; + } + } + } + catch ( NumberFormatException e ) + { + System.out.println( "Error: caught exception in " + + "ExampleDataPilotSource.initialize!\nException Message = " + + e.getMessage()); + e.printStackTrace(); + } + catch ( com.sun.star.lang.IllegalArgumentException e ) + { + System.out.println( "Error: caught exception in " + + "ExampleDataPilotSource.initialize!\nException Message = " + + e.getMessage()); + e.printStackTrace(); + } + } + + // XDataPilotResults + + public com.sun.star.sheet.DataResult[][] getResults() + { + int[] nDigits = new int[ExampleSettings.nDimensionCount]; + int nValue = 1; + for (int i=0; i $@ + @echo RegistrationClassName: $(basename $(basename $(@F)))>> $@ + +# IDLs only for component 1 relevant +$(COMP1_GEN_OUT)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -I. -I$(IDL_DIR) -O$(COMP1_GEN_OUT) $^ + +$(COMP1_RDB) : $(COMP1_GENURDFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(REGMERGE) $@ /UCR $< + +$(COMP1_CLASS_OUT)/$(PACKAGE)/%.class : $(COMP1_RDB) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(JAVAMAKER) -nD $(COMP1_GENTYPELIST) -O$(COMP1_CLASS_OUT) $(COMP1_RDB) -X$(URE_TYPES) -X$(OFFICE_TYPES) + +$(COMP1_CLASSFILES) : $(COMP1_JAVAFILES) $(COMP1_GENCLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(COMP1_CLASS_OUT) $(COMP1_JAVAFILES) + +$(COMP2_CLASSFILES) : $(COMP2_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(COMP2_CLASS_OUT) $^ + +$(COMP1_JAR) : $(COMP1_MANIFESTFILE) $(COMP1_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(COMP1_CLASS_OUT) . + +$(COMP2_JAR) : $(COMP2_MANIFESTFILE) $(COMP2_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(COMP2_CLASS_OUT) . + +$(COMP1_UNOPKG_MANIFEST) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-typelibrary;type=RDB$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(COMP1_GEN_OUT)/,,$(@D))).uno.rdb$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP1_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +$(COMP2_UNOPKG_MANIFEST) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP2_COMPONENTS)$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +$(COMP1_PACKAGE) : $(COMP1_RDB) $(COMP1_JAR) $(COMP1_UNOPKG_MANIFEST) $(COMP1_COMPONENTS) + echo "####" $(@) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ $(COMP1_COMPONENTS) + cd $(subst /,$(PS),$(COMP1_GEN_OUT)) && $(SDK_ZIP) -u ../../../bin/$(@F) $( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(SAMPLE_GEN_OUT)/devguide_$(COMP2_NAME)_register_component.flag : $(OUT_BIN)/$(COMP2_NAME).$(UNOOXT_EXT) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP2_NAME).$(UNOOXT_EXT)") + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(APP_CLASSFILES) : $(APP_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SAMPLE_CLASS_OUT) $(APP_JAVAFILES) + +$(APP1_CLASS_OUT)/%.class : %.java $(APP_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(APP1_CLASS_OUT) $< + +$(APP2_CLASS_OUT)/%.class : %.java $(APP_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(APP2_CLASS_OUT) $< + +$(APP3_CLASS_OUT)/%.class : %.java $(APP_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(APP3_CLASS_OUT) $< + +$(SAMPLE_GEN_OUT)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $(basename $(@F))>> $@ + +$(APP1_JAR) : $(APP1_GEN_OUT)/$(APP1_NAME).mf $(APP1_CLASS_OUT)/$(APP1_NAME).class $(APP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +$(SDK_JAR) cvfm $@ $< -C $(APP1_CLASS_OUT) . + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) uvf $(@F) $(APP_CLASSNAMES) + +$(APP2_JAR) : $(APP2_GEN_OUT)/$(APP2_NAME).mf $(APP2_CLASS_OUT)/$(APP2_NAME).class $(APP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +$(SDK_JAR) cvfm $@ $< -C $(APP2_CLASS_OUT) . + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) uvf $(@F) $(APP_CLASSNAMES) + +$(APP3_JAR) : $(APP3_GEN_OUT)/$(APP3_NAME).mf $(APP3_CLASS_OUT)/$(APP3_NAME).class $(APP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +$(SDK_JAR) cvfm $@ $< -C $(APP3_CLASS_OUT) . + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) uvf $(@F) $(APP_CLASSNAMES) + +$(SAMPLE_NAME) : $(COMP1_REGISTERFLAG) $(COMP2_REGISTERFLAG) $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP2_NAME).run + @echo $(MAKE) $(APP3_NAME).run + @echo -------- + @echo The "$(QM)$(COMP1_NAME)$(QM)" and "$(QM)$(COMP2_NAME)$(QM)" component are installed if + @echo SDK_AUTO_DEPLOYMENT = YES. You can use this components inside your office + @echo installation, see the example descriptions. You can also load the "$(QM)ExampleAddIn.ods$(QM)" + @echo document to see how the add-in functions can be used. For more details about the + @echo "$(QM)$(COMP2_NAME)$(QM)" component see the "$(QM)DataPilotReadme.txt"$(QM). + @echo - + @echo $(MAKE) ExampleAddIn.ods.load + @echo -------------------------------------------------------------------------------- + +%.run: $(SAMPLE_CLASS_OUT)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +ExampleAddIn.ods.load : $(COMP1_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP1_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP2_PACKAGE_URL))) diff --git a/odk/examples/DevelopersGuide/Spreadsheet/SpreadsheetDocHelper.java b/odk/examples/DevelopersGuide/Spreadsheet/SpreadsheetDocHelper.java new file mode 100644 index 000000000..0696a866c --- /dev/null +++ b/odk/examples/DevelopersGuide/Spreadsheet/SpreadsheetDocHelper.java @@ -0,0 +1,388 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.frame.XComponentLoader; +import com.sun.star.lang.XComponent; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.RuntimeException; + +// __________ implementation ____________________________________ + +/** This is a helper class for the spreadsheet and table samples. + It connects to a running office and creates a spreadsheet document. + Additionally it contains various helper functions. + */ +public class SpreadsheetDocHelper +{ + +// __ private members ___________________________________________ + + private com.sun.star.uno.XComponentContext mxRemoteContext; + private com.sun.star.lang.XMultiComponentFactory mxRemoteServiceManager; + private com.sun.star.sheet.XSpreadsheetDocument mxDocument; + + + + public SpreadsheetDocHelper( String[] args ) + { + // Connect to a running office and get the service manager + connect(); + + // Create a new spreadsheet document + try + { + mxDocument = initDocument(); + } + catch (Exception ex) + { + System.err.println( "Couldn't create document: " + ex ); + System.err.println( "Error: Couldn't create Document\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + System.exit( 1 ); + } + } + +// __ helper methods ____________________________________________ + + /** Returns the service manager of the connected office. + @return XMultiComponentFactory interface of the service manager. */ + public com.sun.star.lang.XMultiComponentFactory getServiceManager() + { + return mxRemoteServiceManager; + } + + /** Returns the component context of the connected office + @return XComponentContext interface of the context. */ + public com.sun.star.uno.XComponentContext getContext() + { + return mxRemoteContext; + } + + /** Returns the whole spreadsheet document. + @return XSpreadsheetDocument interface of the document. */ + public com.sun.star.sheet.XSpreadsheetDocument getDocument() + { + return mxDocument; + } + + /** Returns the spreadsheet with the specified index (0-based). + @param nIndex The index of the sheet. + @return XSpreadsheet interface of the sheet. */ + public com.sun.star.sheet.XSpreadsheet getSpreadsheet( int nIndex ) + { + // Collection of sheets + com.sun.star.sheet.XSpreadsheets xSheets = mxDocument.getSheets(); + com.sun.star.sheet.XSpreadsheet xSheet = null; + try + { + com.sun.star.container.XIndexAccess xSheetsIA = + UnoRuntime.queryInterface( + com.sun.star.container.XIndexAccess.class, xSheets ); + xSheet = UnoRuntime.queryInterface( + com.sun.star.sheet.XSpreadsheet.class, xSheetsIA.getByIndex(nIndex)); + } + catch (Exception ex) + { + System.err.println( "Error: caught exception in getSpreadsheet()!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + return xSheet; + } + + /** Inserts a new empty spreadsheet with the specified name. + @param aName The name of the new sheet. + @param nIndex The insertion index. + @return The XSpreadsheet interface of the new sheet. */ + public com.sun.star.sheet.XSpreadsheet insertSpreadsheet( + String aName, short nIndex ) + { + // Collection of sheets + com.sun.star.sheet.XSpreadsheets xSheets = mxDocument.getSheets(); + com.sun.star.sheet.XSpreadsheet xSheet = null; + try + { + xSheets.insertNewByName( aName, nIndex ); + xSheet = UnoRuntime.queryInterface(com.sun.star.sheet.XSpreadsheet.class, + xSheets.getByName( aName )); + } + catch (Exception ex) + { + System.err.println( "Error: caught exception in insertSpreadsheet()!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + return xSheet; + } + + +// Methods to fill values into cells. + + /** Writes a double value into a spreadsheet. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aCellName The address of the cell (or a named range). + @param fValue The value to write into the cell. */ + public void setValue( + com.sun.star.sheet.XSpreadsheet xSheet, + String aCellName, + double fValue ) throws RuntimeException, Exception + { + xSheet.getCellRangeByName( aCellName ).getCellByPosition( 0, 0 ).setValue( fValue ); + } + + /** Writes a formula into a spreadsheet. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aCellName The address of the cell (or a named range). + @param aFormula The formula to write into the cell. */ + public void setFormula( + com.sun.star.sheet.XSpreadsheet xSheet, + String aCellName, + String aFormula ) throws RuntimeException, Exception + { + xSheet.getCellRangeByName( aCellName ).getCellByPosition( 0, 0 ).setFormula( aFormula ); + } + + /** Writes a date with standard date format into a spreadsheet. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aCellName The address of the cell (or a named range). + @param nDay The day of the date. + @param nMonth The month of the date. + @param nYear The year of the date. */ + public void setDate( + com.sun.star.sheet.XSpreadsheet xSheet, + String aCellName, + int nDay, int nMonth, int nYear ) throws RuntimeException, Exception + { + // Set the date value. + com.sun.star.table.XCell xCell = xSheet.getCellRangeByName( aCellName ).getCellByPosition( 0, 0 ); + String aDateStr = nMonth + "/" + nDay + "/" + nYear; + xCell.setFormula( aDateStr ); + + // Set standard date format. + com.sun.star.util.XNumberFormatsSupplier xFormatsSupplier = + UnoRuntime.queryInterface( + com.sun.star.util.XNumberFormatsSupplier.class, getDocument() ); + com.sun.star.util.XNumberFormatTypes xFormatTypes = + UnoRuntime.queryInterface( + com.sun.star.util.XNumberFormatTypes.class, xFormatsSupplier.getNumberFormats() ); + int nFormat = xFormatTypes.getStandardFormat( + com.sun.star.util.NumberFormat.DATE, new com.sun.star.lang.Locale() ); + + com.sun.star.beans.XPropertySet xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCell ); + xPropSet.setPropertyValue( "NumberFormat", Integer.valueOf( nFormat ) ); + } + + /** Draws a colored border around the range and writes the headline in the + first cell. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aRange The address of the cell range (or a named range). + @param aHeadline The headline text. */ + public void prepareRange( + com.sun.star.sheet.XSpreadsheet xSheet, + String aRange, String aHeadline ) throws RuntimeException, Exception + { + com.sun.star.beans.XPropertySet xPropSet = null; + com.sun.star.table.XCellRange xCellRange = null; + + // draw border + xCellRange = xSheet.getCellRangeByName( aRange ); + xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCellRange ); + com.sun.star.table.BorderLine aLine = new com.sun.star.table.BorderLine(); + aLine.Color = 0x99CCFF; + aLine.InnerLineWidth = aLine.LineDistance = 0; + aLine.OuterLineWidth = 100; + com.sun.star.table.TableBorder aBorder = new com.sun.star.table.TableBorder(); + aBorder.TopLine = aBorder.BottomLine = aBorder.LeftLine = aBorder.RightLine = aLine; + aBorder.IsTopLineValid = aBorder.IsBottomLineValid = true; + aBorder.IsLeftLineValid = aBorder.IsRightLineValid = true; + xPropSet.setPropertyValue( "TableBorder", aBorder ); + + // draw headline + com.sun.star.sheet.XCellRangeAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class, xCellRange ); + com.sun.star.table.CellRangeAddress aAddr = xAddr.getRangeAddress(); + + xCellRange = xSheet.getCellRangeByPosition( + aAddr.StartColumn, aAddr.StartRow, aAddr.EndColumn, aAddr.StartRow ); + xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCellRange ); + xPropSet.setPropertyValue( "CellBackColor", Integer.valueOf( 0x99CCFF ) ); + // write headline + com.sun.star.table.XCell xCell = xCellRange.getCellByPosition( 0, 0 ); + xCell.setFormula( aHeadline ); + xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCell ); + xPropSet.setPropertyValue( "CharColor", Integer.valueOf( 0x003399 ) ); + xPropSet.setPropertyValue( "CharWeight", new Float( com.sun.star.awt.FontWeight.BOLD ) ); + } + + +// Methods to create cell addresses and range addresses. + + /** Creates a com.sun.star.table.CellAddress and initializes it + with the given range. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aCell The address of the cell (or a named cell). */ + public com.sun.star.table.CellAddress createCellAddress( + com.sun.star.sheet.XSpreadsheet xSheet, + String aCell ) throws RuntimeException, Exception + { + com.sun.star.sheet.XCellAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellAddressable.class, + xSheet.getCellRangeByName( aCell ).getCellByPosition( 0, 0 ) ); + return xAddr.getCellAddress(); + } + + /** Creates a com.sun.star.table.CellRangeAddress and initializes + it with the given range. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aRange The address of the cell range (or a named range). */ + public com.sun.star.table.CellRangeAddress createCellRangeAddress( + com.sun.star.sheet.XSpreadsheet xSheet, String aRange ) + { + com.sun.star.sheet.XCellRangeAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class, + xSheet.getCellRangeByName( aRange ) ); + return xAddr.getRangeAddress(); + } + + +// Methods to convert cell addresses and range addresses to strings. + + /** Returns the text address of the cell. + @param nColumn The column index. + @param nRow The row index. + @return A string containing the cell address. */ + public String getCellAddressString( int nColumn, int nRow ) + { + String aStr = ""; + if (nColumn > 25) + aStr += (char) ('A' + nColumn / 26 - 1); + aStr += (char) ('A' + nColumn % 26); + aStr += (nRow + 1); + return aStr; + } + + /** Returns the text address of the cell range. + @param aCellRange The cell range address. + @return A string containing the cell range address. */ + public String getCellRangeAddressString( + com.sun.star.table.CellRangeAddress aCellRange ) + { + return + getCellAddressString( aCellRange.StartColumn, aCellRange.StartRow ) + + ":" + + getCellAddressString( aCellRange.EndColumn, aCellRange.EndRow ); + } + + /** Returns the text address of the cell range. + @param xCellRange The XSheetCellRange interface of the cell range. + @param bWithSheet true = Include sheet name. + @return A string containing the cell range address. */ + public String getCellRangeAddressString( + com.sun.star.sheet.XSheetCellRange xCellRange, + boolean bWithSheet ) + { + String aStr = ""; + if (bWithSheet) + { + com.sun.star.sheet.XSpreadsheet xSheet = xCellRange.getSpreadsheet(); + com.sun.star.container.XNamed xNamed = UnoRuntime.queryInterface( com.sun.star.container.XNamed.class, xSheet ); + aStr += xNamed.getName() + "."; + } + com.sun.star.sheet.XCellRangeAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class, xCellRange ); + aStr += getCellRangeAddressString( xAddr.getRangeAddress() ); + return aStr; + } + + /** Returns a list of addresses of all cell ranges contained in the collection. + @param xRangesIA The XIndexAccess interface of the collection. + @return A string containing the cell range address list. */ + public String getCellRangeListString( + com.sun.star.container.XIndexAccess xRangesIA ) throws RuntimeException, Exception + { + String aStr = ""; + int nCount = xRangesIA.getCount(); + for (int nIndex = 0; nIndex < nCount; ++nIndex) + { + if (nIndex > 0) + aStr += " "; + Object aRangeObj = xRangesIA.getByIndex( nIndex ); + com.sun.star.sheet.XSheetCellRange xCellRange = UnoRuntime.queryInterface( com.sun.star.sheet.XSheetCellRange.class, aRangeObj ); + aStr += getCellRangeAddressString( xCellRange, false ); + } + return aStr; + } + + + + // Connect to a running office that is accepting connections. + private void connect() + { + if (mxRemoteContext == null && mxRemoteServiceManager == null) { + try { + // First step: get the remote office component context + mxRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + mxRemoteServiceManager = mxRemoteContext.getServiceManager(); + } + catch( Exception e) { + System.err.println("ERROR: can't get a component context from a running office ..."); + e.printStackTrace(); + System.exit(1); + } + } + } + + /** Creates an empty spreadsheet document. + @return The XSpreadsheetDocument interface of the document. */ + private com.sun.star.sheet.XSpreadsheetDocument initDocument() + throws RuntimeException, Exception + { + XComponentLoader aLoader = UnoRuntime.queryInterface( + XComponentLoader.class, + mxRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", mxRemoteContext)); + + XComponent xComponent = aLoader.loadComponentFromURL( + "private:factory/scalc", "_blank", 0, + new com.sun.star.beans.PropertyValue[0] ); + + return UnoRuntime.queryInterface( + com.sun.star.sheet.XSpreadsheetDocument.class, xComponent ); + } + + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Spreadsheet/SpreadsheetSample.java b/odk/examples/DevelopersGuide/Spreadsheet/SpreadsheetSample.java new file mode 100644 index 000000000..ce6555528 --- /dev/null +++ b/odk/examples/DevelopersGuide/Spreadsheet/SpreadsheetSample.java @@ -0,0 +1,1347 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.RuntimeException; +import com.sun.star.uno.AnyConverter; + +// __________ implementation ____________________________________ + +/** Create and modify a spreadsheet document. + */ +public class SpreadsheetSample extends SpreadsheetDocHelper +{ + + + + public static void main( String args[] ) + { + try + { + SpreadsheetSample aSample = new SpreadsheetSample( args ); + aSample.doSampleFunction(); + } + catch (Exception ex) + { + System.out.println( "Error: Sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + System.exit( 1 ); + } + System.out.println( "\nSamples done." ); + System.exit( 0 ); + } + + + + public SpreadsheetSample( String[] args ) + { + super( args ); + } + + + + /** This sample function performs all changes on the document. */ + public void doSampleFunction() + { + try + { + doCellSamples(); + } + catch (Exception ex) + { + System.out.println( "\nError: Cell sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + + try + { + doCellRangeSamples(); + } + catch (Exception ex) + { + System.out.println( "\nError: Cell range sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + + try + { + doCellRangesSamples(); + } + catch (Exception ex) + { + System.out.println( "\nError: Cell range container sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + + try + { + doCellCursorSamples(); + } + catch (Exception ex) + { + System.out.println( "\nError: Cell cursor sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + + try + { + doFormattingSamples(); + } + catch (Exception ex) + { + System.out.println( "\nError: Formatting sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + + try + { + doDocumentSamples(); + } + catch (Exception ex) + { + System.out.println( "\nError: Document sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + + try + { + doDatabaseSamples(); + } + catch( Exception ex ) + { + System.out.println( "\nError: Database sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + + try + { + doDataPilotSamples(); + } + catch (Exception ex) + { + System.out.println( "\nError: Data pilot sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + + try + { + doNamedRangesSamples(); + } + catch( Exception ex ) + { + System.out.println( "\nError: Named ranges sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + + try + { + doFunctionAccessSamples(); + } + catch (Exception ex) + { + System.out.println( "\nError: Function access sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + + try + { + doApplicationSettingsSamples(); + } + catch (Exception ex) + { + System.out.println( "\nError: Application settings sample caught exception!\nException Message = " + + ex.getMessage()); + ex.printStackTrace(); + } + } + + + + /** All samples regarding the service com.sun.star.sheet.SheetCell. */ + private void doCellSamples() throws RuntimeException, Exception + { + System.out.println( "\n*** Samples for service sheet.SheetCell ***\n" ); + com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 0 ); + com.sun.star.table.XCell xCell = null; + com.sun.star.beans.XPropertySet xPropSet = null; + String aText; + prepareRange( xSheet, "A1:C7", "Cells and Cell Ranges" ); + + // --- Get cell B3 by position - (column, row) --- + xCell = xSheet.getCellByPosition( 1, 2 ); + + + // --- Insert two text paragraphs into the cell. --- + com.sun.star.text.XText xText = UnoRuntime.queryInterface( com.sun.star.text.XText.class, xCell ); + com.sun.star.text.XTextCursor xTextCursor = xText.createTextCursor(); + + xText.insertString( xTextCursor, "Text in first line.", false ); + xText.insertControlCharacter( xTextCursor, + com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false ); + xText.insertString( xTextCursor, "And a ", false ); + + // create a hyperlink + com.sun.star.lang.XMultiServiceFactory xServiceMan = UnoRuntime.queryInterface( com.sun.star.lang.XMultiServiceFactory.class, getDocument() ); + Object aHyperlinkObj = xServiceMan.createInstance( "com.sun.star.text.TextField.URL" ); + xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, aHyperlinkObj ); + xPropSet.setPropertyValue( "URL", "http://www.example.org" ); + xPropSet.setPropertyValue( "Representation", "hyperlink" ); + // ... and insert + com.sun.star.text.XTextContent xContent = UnoRuntime.queryInterface( com.sun.star.text.XTextContent.class, aHyperlinkObj ); + xText.insertTextContent( xTextCursor, xContent, false ); + + + // --- Query the separate paragraphs. --- + com.sun.star.container.XEnumerationAccess xParaEA = + UnoRuntime.queryInterface( + com.sun.star.container.XEnumerationAccess.class, xCell ); + com.sun.star.container.XEnumeration xParaEnum = xParaEA.createEnumeration(); + // Go through the paragraphs + while( xParaEnum.hasMoreElements() ) + { + Object aPortionObj = xParaEnum.nextElement(); + com.sun.star.container.XEnumerationAccess xPortionEA = + UnoRuntime.queryInterface( + com.sun.star.container.XEnumerationAccess.class, aPortionObj ); + com.sun.star.container.XEnumeration xPortionEnum = xPortionEA.createEnumeration(); + aText = ""; + // Go through all text portions of a paragraph and construct string. + while( xPortionEnum.hasMoreElements() ) + { + com.sun.star.text.XTextRange xRange = UnoRuntime.queryInterface(com.sun.star.text.XTextRange.class, + xPortionEnum.nextElement()); + aText += xRange.getString(); + } + System.out.println( "Paragraph text: " + aText ); + } + + + // --- Change cell properties. --- + xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCell ); + // from styles.CharacterProperties + xPropSet.setPropertyValue( "CharColor", Integer.valueOf( 0x003399 ) ); + xPropSet.setPropertyValue( "CharHeight", new Float( 20.0 ) ); + // from styles.ParagraphProperties + xPropSet.setPropertyValue( "ParaLeftMargin", Integer.valueOf( 500 ) ); + // from table.CellProperties + xPropSet.setPropertyValue( "IsCellBackgroundTransparent", Boolean.FALSE ); + xPropSet.setPropertyValue( "CellBackColor", Integer.valueOf( 0x99CCFF ) ); + + + // --- Get cell address. --- + com.sun.star.sheet.XCellAddressable xCellAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellAddressable.class, xCell ); + com.sun.star.table.CellAddress aAddress = xCellAddr.getCellAddress(); + aText = "Address of this cell: Column=" + aAddress.Column; + aText += "; Row=" + aAddress.Row; + aText += "; Sheet=" + aAddress.Sheet; + System.out.println( aText ); + + + // --- Insert an annotation --- + com.sun.star.sheet.XSheetAnnotationsSupplier xAnnotationsSupp = + UnoRuntime.queryInterface( + com.sun.star.sheet.XSheetAnnotationsSupplier.class, xSheet ); + com.sun.star.sheet.XSheetAnnotations xAnnotations = xAnnotationsSupp.getAnnotations(); + xAnnotations.insertNew( aAddress, "This is an annotation" ); + + com.sun.star.sheet.XSheetAnnotationAnchor xAnnotAnchor = UnoRuntime.queryInterface( com.sun.star.sheet.XSheetAnnotationAnchor.class, xCell ); + com.sun.star.sheet.XSheetAnnotation xAnnotation = xAnnotAnchor.getAnnotation(); + xAnnotation.setIsVisible( true ); + } + + + + /** All samples regarding the service com.sun.star.sheet.SheetCellRange. */ + private void doCellRangeSamples() throws RuntimeException, Exception + { + System.out.println( "\n*** Samples for service sheet.SheetCellRange ***\n" ); + com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 0 ); + com.sun.star.table.XCellRange xCellRange = null; + com.sun.star.beans.XPropertySet xPropSet = null; + com.sun.star.table.CellRangeAddress aRangeAddress = null; + + // Preparation + setFormula( xSheet, "B5", "First cell" ); + setFormula( xSheet, "B6", "Second cell" ); + // Get cell range B5:B6 by position - (column, row, column, row) + xCellRange = xSheet.getCellRangeByPosition( 1, 4, 1, 5 ); + + + // --- Change cell range properties. --- + xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCellRange ); + // from com.sun.star.styles.CharacterProperties + xPropSet.setPropertyValue( "CharColor", Integer.valueOf( 0x003399 ) ); + xPropSet.setPropertyValue( "CharHeight", new Float( 20.0 ) ); + // from com.sun.star.styles.ParagraphProperties + xPropSet.setPropertyValue( "ParaLeftMargin", Integer.valueOf( 500 ) ); + // from com.sun.star.table.CellProperties + xPropSet.setPropertyValue( "IsCellBackgroundTransparent", Boolean.FALSE ); + xPropSet.setPropertyValue( "CellBackColor", Integer.valueOf( 0x99CCFF ) ); + + + // --- Replace text in all cells. --- + com.sun.star.util.XReplaceable xReplace = UnoRuntime.queryInterface( com.sun.star.util.XReplaceable.class, xCellRange ); + com.sun.star.util.XReplaceDescriptor xReplaceDesc = xReplace.createReplaceDescriptor(); + xReplaceDesc.setSearchString( "cell" ); + xReplaceDesc.setReplaceString( "text" ); + // property SearchWords searches for whole cells! + xReplaceDesc.setPropertyValue( "SearchWords", Boolean.FALSE ); + int nCount = xReplace.replaceAll( xReplaceDesc ); + System.out.println( "Search text replaced " + nCount + " times." ); + + + // --- Merge cells. --- + xCellRange = xSheet.getCellRangeByName( "F3:G6" ); + prepareRange( xSheet, "E1:H7", "XMergeable" ); + com.sun.star.util.XMergeable xMerge = UnoRuntime.queryInterface( com.sun.star.util.XMergeable.class, xCellRange ); + xMerge.merge( true ); + + + // --- Change indentation. --- +/* does not work (bug in XIndent implementation) + prepareRange( xSheet, "I20:I23", "XIndent" ); + setValue( xSheet, "I21", 1 ); + setValue( xSheet, "I22", 1 ); + setValue( xSheet, "I23", 1 ); + + xCellRange = xSheet.getCellRangeByName( "I21:I22" ); + com.sun.star.util.XIndent xIndent = (com.sun.star.util.XIndent) + UnoRuntime.queryInterface( com.sun.star.util.XIndent.class, xCellRange ); + xIndent.incrementIndent(); + + xCellRange = xSheet.getCellRangeByName( "I22:I23" ); + xIndent = (com.sun.star.util.XIndent) + UnoRuntime.queryInterface( com.sun.star.util.XIndent.class, xCellRange ); + xIndent.incrementIndent(); +*/ + + + // --- Column properties. --- + xCellRange = xSheet.getCellRangeByName( "B1" ); + com.sun.star.table.XColumnRowRange xColRowRange = UnoRuntime.queryInterface( com.sun.star.table.XColumnRowRange.class, xCellRange ); + com.sun.star.table.XTableColumns xColumns = xColRowRange.getColumns(); + + Object aColumnObj = xColumns.getByIndex( 0 ); + xPropSet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, aColumnObj ); + xPropSet.setPropertyValue( "Width", Integer.valueOf( 6000 ) ); + + com.sun.star.container.XNamed xNamed = UnoRuntime.queryInterface( com.sun.star.container.XNamed.class, aColumnObj ); + System.out.println( "The name of the wide column is " + xNamed.getName() + "." ); + + + // --- Cell range data --- + prepareRange( xSheet, "A9:C30", "XCellRangeData" ); + + xCellRange = xSheet.getCellRangeByName( "A10:C30" ); + com.sun.star.sheet.XCellRangeData xData = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeData.class, xCellRange ); + Object[][] aValues = + { + { "Name", "Fruit", "Quantity" }, + { "Alice", "Apples", new Double( 3.0 ) }, + { "Alice", "Oranges", new Double( 7.0 ) }, + { "Bob", "Apples", new Double( 3.0 ) }, + { "Alice", "Apples", new Double( 9.0 ) }, + { "Bob", "Apples", new Double( 5.0 ) }, + { "Bob", "Oranges", new Double( 6.0 ) }, + { "Alice", "Oranges", new Double( 3.0 ) }, + { "Alice", "Apples", new Double( 8.0 ) }, + { "Alice", "Oranges", new Double( 1.0 ) }, + { "Bob", "Oranges", new Double( 2.0 ) }, + { "Bob", "Oranges", new Double( 7.0 ) }, + { "Bob", "Apples", new Double( 1.0 ) }, + { "Alice", "Apples", new Double( 8.0 ) }, + { "Alice", "Oranges", new Double( 8.0 ) }, + { "Alice", "Apples", new Double( 7.0 ) }, + { "Bob", "Apples", new Double( 1.0 ) }, + { "Bob", "Oranges", new Double( 9.0 ) }, + { "Bob", "Oranges", new Double( 3.0 ) }, + { "Alice", "Oranges", new Double( 4.0 ) }, + { "Alice", "Apples", new Double( 9.0 ) } + }; + xData.setDataArray( aValues ); + + + // --- Get cell range address. --- + com.sun.star.sheet.XCellRangeAddressable xRangeAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class, xCellRange ); + aRangeAddress = xRangeAddr.getRangeAddress(); + System.out.println( "Address of this range: Sheet=" + aRangeAddress.Sheet ); + System.out.println( "Start column=" + aRangeAddress.StartColumn + "; Start row=" + aRangeAddress.StartRow ); + System.out.println( "End column =" + aRangeAddress.EndColumn + "; End row =" + aRangeAddress.EndRow ); + + + // --- Sheet operation. --- + // uses the range filled with XCellRangeData + com.sun.star.sheet.XSheetOperation xSheetOp = UnoRuntime.queryInterface( com.sun.star.sheet.XSheetOperation.class, xData ); + double fResult = xSheetOp.computeFunction( com.sun.star.sheet.GeneralFunction.AVERAGE ); + System.out.println( "Average value of the data table A10:C30: " + fResult ); + + + // --- Fill series --- + // Prepare the example + setValue( xSheet, "E10", 1 ); + setValue( xSheet, "E11", 4 ); + setDate( xSheet, "E12", 30, 1, 2002 ); + setFormula( xSheet, "I13", "Text 10" ); + setFormula( xSheet, "E14", "Jan" ); + setValue( xSheet, "K14", 10 ); + setValue( xSheet, "E16", 1 ); + setValue( xSheet, "F16", 2 ); + setDate( xSheet, "E17", 28, 2, 2002 ); + setDate( xSheet, "F17", 28, 1, 2002 ); + setValue( xSheet, "E18", 6 ); + setValue( xSheet, "F18", 4 ); + + com.sun.star.sheet.XCellSeries xSeries = null; + // Fill 2 rows linear with end value -> 2nd series is not filled completely + xSeries = getCellSeries( xSheet, "E10:I11" ); + xSeries.fillSeries( com.sun.star.sheet.FillDirection.TO_RIGHT, com.sun.star.sheet.FillMode.LINEAR, + com.sun.star.sheet.FillDateMode.FILL_DATE_DAY, 2, 9 ); + // Add months to a date + xSeries = getCellSeries( xSheet, "E12:I12" ); + xSeries.fillSeries( com.sun.star.sheet.FillDirection.TO_RIGHT, com.sun.star.sheet.FillMode.DATE, + com.sun.star.sheet.FillDateMode.FILL_DATE_MONTH, 1, 0x7FFFFFFF ); + // Fill right to left with a text containing a value + xSeries = getCellSeries( xSheet, "E13:I13" ); + xSeries.fillSeries( com.sun.star.sheet.FillDirection.TO_LEFT, com.sun.star.sheet.FillMode.LINEAR, + com.sun.star.sheet.FillDateMode.FILL_DATE_DAY, 10, 0x7FFFFFFF ); + // Fill with an user defined list + xSeries = getCellSeries( xSheet, "E14:I14" ); + xSeries.fillSeries( com.sun.star.sheet.FillDirection.TO_RIGHT, com.sun.star.sheet.FillMode.AUTO, + com.sun.star.sheet.FillDateMode.FILL_DATE_DAY, 1, 0x7FFFFFFF ); + // Fill bottom to top with a geometric series + xSeries = getCellSeries( xSheet, "K10:K14" ); + xSeries.fillSeries( com.sun.star.sheet.FillDirection.TO_TOP, com.sun.star.sheet.FillMode.GROWTH, + com.sun.star.sheet.FillDateMode.FILL_DATE_DAY, 2, 0x7FFFFFFF ); + // Auto fill + xSeries = getCellSeries( xSheet, "E16:K18" ); + xSeries.fillAuto( com.sun.star.sheet.FillDirection.TO_RIGHT, 2 ); + // Fill series copies cell formats -> draw border here + prepareRange( xSheet, "E9:K18", "XCellSeries" ); + + + // --- Array formulas --- + xCellRange = xSheet.getCellRangeByName( "E21:G23" ); + prepareRange( xSheet, "E20:G23", "XArrayFormulaRange" ); + com.sun.star.sheet.XArrayFormulaRange xArrayFormula = UnoRuntime.queryInterface( com.sun.star.sheet.XArrayFormulaRange.class, xCellRange ); + // Insert a 3x3 unit matrix. + xArrayFormula.setArrayFormula( "=A10:C12" ); + System.out.println( "Array formula is: " + xArrayFormula.getArrayFormula() ); + + + // --- Multiple operations --- + setFormula( xSheet, "E26", "=E27^F26" ); + setValue( xSheet, "E27", 1 ); + setValue( xSheet, "F26", 1 ); + getCellSeries( xSheet, "E27:E31" ).fillAuto( com.sun.star.sheet.FillDirection.TO_BOTTOM, 1 ); + getCellSeries( xSheet, "F26:J26" ).fillAuto( com.sun.star.sheet.FillDirection.TO_RIGHT, 1 ); + setFormula( xSheet, "F33", "=SIN(E33)" ); + setFormula( xSheet, "G33", "=COS(E33)" ); + setFormula( xSheet, "H33", "=TAN(E33)" ); + setValue( xSheet, "E34", 0 ); + setValue( xSheet, "E35", 0.2 ); + getCellSeries( xSheet, "E34:E38" ).fillAuto( com.sun.star.sheet.FillDirection.TO_BOTTOM, 2 ); + prepareRange( xSheet, "E25:J38", "XMultipleOperation" ); + + com.sun.star.table.CellRangeAddress aFormulaRange = createCellRangeAddress( xSheet, "E26" ); + com.sun.star.table.CellAddress aColCell = createCellAddress( xSheet, "E27" ); + com.sun.star.table.CellAddress aRowCell = createCellAddress( xSheet, "F26" ); + + xCellRange = xSheet.getCellRangeByName( "E26:J31" ); + com.sun.star.sheet.XMultipleOperation xMultOp = UnoRuntime.queryInterface( com.sun.star.sheet.XMultipleOperation.class, xCellRange ); + xMultOp.setTableOperation( + aFormulaRange, com.sun.star.sheet.TableOperationMode.BOTH, aColCell, aRowCell ); + + aFormulaRange = createCellRangeAddress( xSheet, "F33:H33" ); + aColCell = createCellAddress( xSheet, "E33" ); + // Row cell not needed + + xCellRange = xSheet.getCellRangeByName( "E34:H38" ); + xMultOp = UnoRuntime.queryInterface( com.sun.star.sheet.XMultipleOperation.class, xCellRange ); + xMultOp.setTableOperation( + aFormulaRange, com.sun.star.sheet.TableOperationMode.COLUMN, aColCell, aRowCell ); + + + // --- Cell Ranges Query --- + xCellRange = xSheet.getCellRangeByName( "A10:C30" ); + com.sun.star.sheet.XCellRangesQuery xRangesQuery = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangesQuery.class, xCellRange ); + com.sun.star.sheet.XSheetCellRanges xCellRanges = + xRangesQuery.queryContentCells( (short)com.sun.star.sheet.CellFlags.STRING ); + System.out.println( + "Cells in A10:C30 containing text: " + + xCellRanges.getRangeAddressesAsString() ); + } + + /** Returns the XCellSeries interface of a cell range. + @param xSheet The spreadsheet containing the cell range. + @param aRange The address of the cell range. + @return The XCellSeries interface. */ + private com.sun.star.sheet.XCellSeries getCellSeries( + com.sun.star.sheet.XSpreadsheet xSheet, String aRange ) + { + return UnoRuntime.queryInterface( + com.sun.star.sheet.XCellSeries.class, xSheet.getCellRangeByName( aRange ) ); + } + + + + /** All samples regarding cell range collections. */ + private void doCellRangesSamples() throws RuntimeException, Exception + { + System.out.println( "\n*** Samples for cell range collections ***\n" ); + + // Create a new cell range container + com.sun.star.lang.XMultiServiceFactory xDocFactory = + UnoRuntime.queryInterface( + com.sun.star.lang.XMultiServiceFactory.class, getDocument() ); + com.sun.star.sheet.XSheetCellRangeContainer xRangeCont = + UnoRuntime.queryInterface( + com.sun.star.sheet.XSheetCellRangeContainer.class, + xDocFactory.createInstance( "com.sun.star.sheet.SheetCellRanges" ) ); + + + // --- Insert ranges --- + insertRange( xRangeCont, 0, 0, 0, 0, 0, false ); // A1:A1 + insertRange( xRangeCont, 0, 0, 1, 0, 2, true ); // A2:A3 + insertRange( xRangeCont, 0, 1, 0, 1, 2, false ); // B1:B3 + + + // --- Query the list of filled cells --- + System.out.print( "All filled cells: " ); + com.sun.star.container.XEnumerationAccess xCellsEA = xRangeCont.getCells(); + com.sun.star.container.XEnumeration xEnum = xCellsEA.createEnumeration(); + while( xEnum.hasMoreElements() ) + { + Object aCellObj = xEnum.nextElement(); + com.sun.star.sheet.XCellAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellAddressable.class, aCellObj ); + com.sun.star.table.CellAddress aAddr = xAddr.getCellAddress(); + System.out.print( getCellAddressString( aAddr.Column, aAddr.Row ) + " " ); + } + System.out.println(); + } + + /** Inserts a cell range address into a cell range container and prints + a message. + @param xContainer The com.sun.star.sheet.XSheetCellRangeContainer interface of the container. + @param nSheet Index of sheet of the range. + @param nStartCol Index of first column of the range. + @param nStartRow Index of first row of the range. + @param nEndCol Index of last column of the range. + @param nEndRow Index of last row of the range. + @param bMerge Determines whether the new range should be merged with the existing ranges. */ + private void insertRange( + com.sun.star.sheet.XSheetCellRangeContainer xContainer, + int nSheet, int nStartCol, int nStartRow, int nEndCol, int nEndRow, + boolean bMerge ) throws RuntimeException, Exception + { + com.sun.star.table.CellRangeAddress aAddress = new com.sun.star.table.CellRangeAddress(); + aAddress.Sheet = (short)nSheet; + aAddress.StartColumn = nStartCol; + aAddress.StartRow = nStartRow; + aAddress.EndColumn = nEndCol; + aAddress.EndRow = nEndRow; + xContainer.addRangeAddress( aAddress, bMerge ); + System.out.println( + "Inserting " + getCellRangeAddressString( aAddress ) + + " " + (bMerge ? " with" : "without") + " merge," + + " resulting list: " + xContainer.getRangeAddressesAsString() ); + } + + + + /** All samples regarding cell cursors. */ + private void doCellCursorSamples() throws RuntimeException, Exception + { + System.out.println( "\n*** Samples for cell cursor ***\n" ); + com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 0 ); + + + // --- Find the array formula using a cell cursor --- + com.sun.star.table.XCellRange xRange = xSheet.getCellRangeByName( "F22" ); + com.sun.star.sheet.XSheetCellRange xCellRange = UnoRuntime.queryInterface( com.sun.star.sheet.XSheetCellRange.class, xRange ); + com.sun.star.sheet.XSheetCellCursor xCursor = xSheet.createCursorByRange( xCellRange ); + + xCursor.collapseToCurrentArray(); + com.sun.star.sheet.XArrayFormulaRange xArray = UnoRuntime.queryInterface( com.sun.star.sheet.XArrayFormulaRange.class, xCursor ); + System.out.println( + "Array formula in " + getCellRangeAddressString( xCursor, false ) + + " contains formula " + xArray.getArrayFormula() ); + + + // --- Find the used area --- + com.sun.star.sheet.XUsedAreaCursor xUsedCursor = UnoRuntime.queryInterface( com.sun.star.sheet.XUsedAreaCursor.class, xCursor ); + xUsedCursor.gotoStartOfUsedArea( false ); + xUsedCursor.gotoEndOfUsedArea( true ); + // xUsedCursor and xCursor are interfaces of the same object - + // so modifying xUsedCursor takes effect on xCursor: + System.out.println( "The used area is: " + getCellRangeAddressString( xCursor, true ) ); + } + + + + /** All samples regarding the formatting of cells and ranges. */ + private void doFormattingSamples() throws RuntimeException, Exception + { + System.out.println( "\n*** Formatting samples ***\n" ); + com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 1 ); + com.sun.star.table.XCellRange xCellRange; + com.sun.star.beans.XPropertySet xPropSet = null; + com.sun.star.container.XIndexAccess xRangeIA = null; + com.sun.star.lang.XMultiServiceFactory xDocServiceManager; + + + // --- Cell styles --- + // get the cell style container + com.sun.star.style.XStyleFamiliesSupplier xFamiliesSupplier = UnoRuntime.queryInterface( com.sun.star.style.XStyleFamiliesSupplier.class, getDocument() ); + com.sun.star.container.XNameAccess xFamiliesNA = xFamiliesSupplier.getStyleFamilies(); + Object aCellStylesObj = xFamiliesNA.getByName( "CellStyles" ); + com.sun.star.container.XNameContainer xCellStylesNA = UnoRuntime.queryInterface( com.sun.star.container.XNameContainer.class, aCellStylesObj ); + + // create a new cell style + xDocServiceManager = UnoRuntime.queryInterface( com.sun.star.lang.XMultiServiceFactory.class, getDocument() ); + Object aCellStyle = xDocServiceManager.createInstance( "com.sun.star.style.CellStyle" ); + String aStyleName = "MyNewCellStyle"; + xCellStylesNA.insertByName( aStyleName, aCellStyle ); + + // modify properties of the new style + xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, aCellStyle ); + xPropSet.setPropertyValue( "CellBackColor", Integer.valueOf( 0x888888 ) ); + xPropSet.setPropertyValue( "IsCellBackgroundTransparent", Boolean.FALSE ); + + + + // --- Query equal-formatted cell ranges --- + // prepare example, use the new cell style + xCellRange = xSheet.getCellRangeByName( "D2:F2" ); + xPropSet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xCellRange ); + xPropSet.setPropertyValue( "CellStyle", aStyleName ); + + xCellRange = xSheet.getCellRangeByName( "A3:G3" ); + xPropSet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xCellRange ); + xPropSet.setPropertyValue( "CellStyle", aStyleName ); + + // All ranges in one container + xCellRange = xSheet.getCellRangeByName( "A1:G3" ); + System.out.println( "Service CellFormatRanges:" ); + com.sun.star.sheet.XCellFormatRangesSupplier xFormatSupp = + UnoRuntime.queryInterface( + com.sun.star.sheet.XCellFormatRangesSupplier.class, xCellRange ); + xRangeIA = xFormatSupp.getCellFormatRanges(); + System.out.println( getCellRangeListString( xRangeIA ) ); + + // Ranges sorted in SheetCellRanges containers + System.out.println( "\nService UniqueCellFormatRanges:" ); + com.sun.star.sheet.XUniqueCellFormatRangesSupplier xUniqueFormatSupp = + UnoRuntime.queryInterface( + com.sun.star.sheet.XUniqueCellFormatRangesSupplier.class, xCellRange ); + com.sun.star.container.XIndexAccess xRangesIA = xUniqueFormatSupp.getUniqueCellFormatRanges(); + int nCount = xRangesIA.getCount(); + for (int nIndex = 0; nIndex < nCount; ++nIndex) + { + Object aRangesObj = xRangesIA.getByIndex( nIndex ); + xRangeIA = UnoRuntime.queryInterface( + com.sun.star.container.XIndexAccess.class, aRangesObj ); + System.out.println( + "Container " + (nIndex + 1) + ": " + getCellRangeListString( xRangeIA ) ); + } + + + // --- Table auto formats --- + // get the global collection of table auto formats, use global service + // manager + com.sun.star.lang.XMultiComponentFactory xServiceManager = getServiceManager(); + + Object aAutoFormatsObj = xServiceManager.createInstanceWithContext( + "com.sun.star.sheet.TableAutoFormats", getContext()); + com.sun.star.container.XNameContainer xAutoFormatsNA = + UnoRuntime.queryInterface( + com.sun.star.container.XNameContainer.class, aAutoFormatsObj ); + + // create a new table auto format and insert into the container + String aAutoFormatName = "Temp_Example"; + boolean bExistsAlready = xAutoFormatsNA.hasByName( aAutoFormatName ); + Object aAutoFormatObj = null; + if (bExistsAlready) + // auto format already exists -> use it + aAutoFormatObj = xAutoFormatsNA.getByName( aAutoFormatName ); + else + { + aAutoFormatObj = xDocServiceManager.createInstance( + "com.sun.star.sheet.TableAutoFormat" ); + xAutoFormatsNA.insertByName( aAutoFormatName, aAutoFormatObj ); + } + // index access to the auto format fields + com.sun.star.container.XIndexAccess xAutoFormatIA = + UnoRuntime.queryInterface( + com.sun.star.container.XIndexAccess.class, aAutoFormatObj ); + + // set properties of all auto format fields + for (int nRow = 0; nRow < 4; ++nRow) + { + int nRowColor = 0; + switch (nRow) + { + case 0: nRowColor = 0x999999; break; + case 1: nRowColor = 0xFFFFCC; break; + case 2: nRowColor = 0xEEEEEE; break; + case 3: nRowColor = 0x999999; break; + } + + for (int nColumn = 0; nColumn < 4; ++nColumn) + { + int nColor = nRowColor; + if ((nColumn == 0) || (nColumn == 3)) + nColor -= 0x333300; + + // get the auto format field and apply properties + Object aFieldObj = xAutoFormatIA.getByIndex( 4 * nRow + nColumn ); + xPropSet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, aFieldObj ); + xPropSet.setPropertyValue( "CellBackColor", Integer.valueOf( nColor ) ); + } + } + + // set the auto format to the spreadsheet + xCellRange = xSheet.getCellRangeByName( "A5:H25" ); + com.sun.star.table.XAutoFormattable xAutoForm = UnoRuntime.queryInterface( com.sun.star.table.XAutoFormattable.class, xCellRange ); + xAutoForm.autoFormat( aAutoFormatName ); + + // remove the auto format + if (!bExistsAlready) + xAutoFormatsNA.removeByName( aAutoFormatName ); + + + // --- Conditional formats --- + xSheet = getSpreadsheet( 0 ); + prepareRange( xSheet, "K20:K23", "Cond. Format" ); + setValue( xSheet, "K21", 1 ); + setValue( xSheet, "K22", 2 ); + setValue( xSheet, "K23", 3 ); + + // get the conditional format object of the cell range + xCellRange = xSheet.getCellRangeByName( "K21:K23" ); + xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCellRange ); + com.sun.star.sheet.XSheetConditionalEntries xEntries = + UnoRuntime.queryInterface( + com.sun.star.sheet.XSheetConditionalEntries.class, + xPropSet.getPropertyValue( "ConditionalFormat" )); + + // create a condition and apply it to the range + com.sun.star.beans.PropertyValue[] aCondition = new com.sun.star.beans.PropertyValue[3]; + aCondition[0] = new com.sun.star.beans.PropertyValue(); + aCondition[0].Name = "Operator"; + aCondition[0].Value = com.sun.star.sheet.ConditionOperator.GREATER; + aCondition[1] = new com.sun.star.beans.PropertyValue(); + aCondition[1].Name = "Formula1"; + aCondition[1].Value = "1"; + aCondition[2] = new com.sun.star.beans.PropertyValue(); + aCondition[2].Name = "StyleName"; + aCondition[2].Value = aStyleName; + xEntries.addNew( aCondition ); + xPropSet.setPropertyValue( "ConditionalFormat", xEntries ); + } + + + + /** All samples regarding the spreadsheet document. */ + private void doDocumentSamples() throws RuntimeException, Exception + { + System.out.println( "\n*** Samples for spreadsheet document ***\n" ); + + + // --- Insert a new spreadsheet --- + com.sun.star.sheet.XSpreadsheet xSheet = insertSpreadsheet( "A new sheet", (short)0x7FFF ); + + + // --- Copy a cell range --- + prepareRange( xSheet, "A1:B3", "Copy from" ); + prepareRange( xSheet, "D1:E3", "To" ); + setValue( xSheet, "A2", 123 ); + setValue( xSheet, "B2", 345 ); + setFormula( xSheet, "A3", "=SUM(A2:B2)" ); + setFormula( xSheet, "B3", "=FORMULA(A3)" ); + + com.sun.star.sheet.XCellRangeMovement xMovement = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeMovement.class, xSheet ); + com.sun.star.table.CellRangeAddress aSourceRange = createCellRangeAddress( xSheet, "A2:B3" ); + com.sun.star.table.CellAddress aDestCell = createCellAddress( xSheet, "D2" ); + xMovement.copyRange( aDestCell, aSourceRange ); + + + // --- Print automatic column page breaks --- + com.sun.star.sheet.XSheetPageBreak xPageBreak = UnoRuntime.queryInterface( com.sun.star.sheet.XSheetPageBreak.class, xSheet ); + com.sun.star.sheet.TablePageBreakData[] aPageBreakArray = xPageBreak.getColumnPageBreaks(); + + System.out.print( "Automatic column page breaks:" ); + for (int nIndex = 0; nIndex < aPageBreakArray.length; ++nIndex) + if (!aPageBreakArray[nIndex].ManualBreak) + System.out.print( " " + aPageBreakArray[nIndex].Position ); + System.out.println(); + + + // --- Document properties --- + com.sun.star.beans.XPropertySet xPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, getDocument() ); + + String aText = "Value of property IsIterationEnabled: "; + aText += AnyConverter.toBoolean(xPropSet.getPropertyValue( "IsIterationEnabled" )); + System.out.println( aText ); + aText = "Value of property IterationCount: "; + aText += AnyConverter.toInt(xPropSet.getPropertyValue( "IterationCount" )); + System.out.println( aText ); + aText = "Value of property NullDate: "; + com.sun.star.util.Date aDate = (com.sun.star.util.Date) + AnyConverter.toObject(com.sun.star.util.Date.class, xPropSet.getPropertyValue( "NullDate" )); + aText += aDate.Year + "-" + aDate.Month + "-" + aDate.Day; + System.out.println( aText ); + + + // --- Data validation --- + prepareRange( xSheet, "A5:C7", "Validation" ); + setFormula( xSheet, "A6", "Insert values between 0.0 and 5.0 below:" ); + + com.sun.star.table.XCellRange xCellRange = xSheet.getCellRangeByName( "A7:C7" ); + com.sun.star.beans.XPropertySet xCellPropSet = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xCellRange ); + // validation properties + com.sun.star.beans.XPropertySet xValidPropSet = UnoRuntime.queryInterface(com.sun.star.beans.XPropertySet.class, + xCellPropSet.getPropertyValue( "Validation" )); + xValidPropSet.setPropertyValue( "Type", com.sun.star.sheet.ValidationType.DECIMAL ); + xValidPropSet.setPropertyValue( "ShowErrorMessage", Boolean.TRUE ); + xValidPropSet.setPropertyValue( "ErrorMessage", "This is an invalid value!" ); + xValidPropSet.setPropertyValue( "ErrorAlertStyle", com.sun.star.sheet.ValidationAlertStyle.STOP ); + // condition + com.sun.star.sheet.XSheetCondition xCondition = UnoRuntime.queryInterface( com.sun.star.sheet.XSheetCondition.class, xValidPropSet ); + xCondition.setOperator( com.sun.star.sheet.ConditionOperator.BETWEEN ); + xCondition.setFormula1( "0.0" ); + xCondition.setFormula2( "5.0" ); + // apply on cell range + xCellPropSet.setPropertyValue( "Validation", xValidPropSet ); + + // --- Scenarios --- + Object[][] aValues = new Object[2][2]; + + aValues[0][0] = new Double( 11 ); + aValues[0][1] = new Double( 12 ); + aValues[1][0] = "Test13"; + aValues[1][1] = "Test14"; + insertScenario( xSheet, "B10:C11", aValues, "First Scenario", "The first scenario." ); + + aValues[0][0] = "Test21"; + aValues[0][1] = "Test22"; + aValues[1][0] = new Double( 23 ); + aValues[1][1] = new Double( 24 ); + insertScenario( xSheet, "B10:C11", aValues, "Second Scenario", "The visible scenario." ); + + aValues[0][0] = new Double( 31 ); + aValues[0][1] = new Double( 32 ); + aValues[1][0] = "Test33"; + aValues[1][1] = "Test34"; + insertScenario( xSheet, "B10:C11", aValues, "Third Scenario", "The last scenario." ); + + // show second scenario + showScenario( xSheet, "Second Scenario" ); + } + + /** Inserts a scenario containing one cell range into a sheet and + applies the value array. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aRange The range address for the scenario. + @param aValueArray The array of cell contents. + @param aScenarioName The name of the new scenario. + @param aScenarioComment The user comment for the scenario. */ + private void insertScenario( + com.sun.star.sheet.XSpreadsheet xSheet, + String aRange, + Object[][] aValueArray, + String aScenarioName, + String aScenarioComment ) throws RuntimeException, Exception + { + // get the cell range with the given address + com.sun.star.table.XCellRange xCellRange = xSheet.getCellRangeByName( aRange ); + + // create the range address sequence + com.sun.star.sheet.XCellRangeAddressable xAddr = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeAddressable.class, xCellRange ); + com.sun.star.table.CellRangeAddress[] aRangesSeq = new com.sun.star.table.CellRangeAddress[1]; + aRangesSeq[0] = xAddr.getRangeAddress(); + + // create the scenario + com.sun.star.sheet.XScenariosSupplier xScenSupp = UnoRuntime.queryInterface( com.sun.star.sheet.XScenariosSupplier.class, xSheet ); + com.sun.star.sheet.XScenarios xScenarios = xScenSupp.getScenarios(); + xScenarios.addNewByName( aScenarioName, aRangesSeq, aScenarioComment ); + + // insert the values into the range + com.sun.star.sheet.XCellRangeData xData = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeData.class, xCellRange ); + xData.setDataArray( aValueArray ); + } + + /** Activates a scenario. + @param xSheet The XSpreadsheet interface of the spreadsheet. + @param aScenarioName The name of the scenario. */ + private void showScenario( + com.sun.star.sheet.XSpreadsheet xSheet, + String aScenarioName ) throws RuntimeException, Exception + { + // get the scenario set + com.sun.star.sheet.XScenariosSupplier xScenSupp = UnoRuntime.queryInterface( com.sun.star.sheet.XScenariosSupplier.class, xSheet ); + com.sun.star.sheet.XScenarios xScenarios = xScenSupp.getScenarios(); + + // get the scenario and activate it + Object aScenarioObj = xScenarios.getByName( aScenarioName ); + com.sun.star.sheet.XScenario xScenario = UnoRuntime.queryInterface( com.sun.star.sheet.XScenario.class, aScenarioObj ); + xScenario.apply(); + } + + + + private void doNamedRangesSamples() throws RuntimeException, Exception + { + System.out.println( "\n*** Samples for named ranges ***\n" ); + com.sun.star.sheet.XSpreadsheetDocument xDocument = getDocument(); + com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 0 ); + + + // --- Named ranges --- + prepareRange( xSheet, "G42:H45", "Named ranges" ); + xSheet.getCellByPosition( 6, 42 ).setValue( 1 ); + xSheet.getCellByPosition( 6, 43 ).setValue( 2 ); + xSheet.getCellByPosition( 7, 42 ).setValue( 3 ); + xSheet.getCellByPosition( 7, 43 ).setValue( 4 ); + + // insert a named range + com.sun.star.beans.XPropertySet xDocProp = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xDocument ); + Object aRangesObj = xDocProp.getPropertyValue( "NamedRanges" ); + com.sun.star.sheet.XNamedRanges xNamedRanges = UnoRuntime.queryInterface( com.sun.star.sheet.XNamedRanges.class, aRangesObj ); + com.sun.star.table.CellAddress aRefPos = new com.sun.star.table.CellAddress(); + aRefPos.Sheet = 0; + aRefPos.Column = 6; + aRefPos.Row = 44; + xNamedRanges.addNewByName( "ExampleName", "SUM(G43:G44)", aRefPos, 0 ); + + // use the named range in formulas + xSheet.getCellByPosition( 6, 44 ).setFormula( "=ExampleName" ); + xSheet.getCellByPosition( 7, 44 ).setFormula( "=ExampleName" ); + + + // --- Label ranges --- + prepareRange( xSheet, "G47:I50", "Label ranges" ); + com.sun.star.table.XCellRange xRange = xSheet.getCellRangeByPosition( 6, 47, 7, 49 ); + com.sun.star.sheet.XCellRangeData xData = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeData.class, xRange ); + Object[][] aValues = + { + { "Apples", "Oranges" }, + { new Double( 5 ), new Double( 7 ) }, + { new Double( 6 ), new Double( 8 ) } + }; + xData.setDataArray( aValues ); + + // insert a column label range + Object aLabelsObj = xDocProp.getPropertyValue( "ColumnLabelRanges" ); + com.sun.star.sheet.XLabelRanges xLabelRanges = UnoRuntime.queryInterface( com.sun.star.sheet.XLabelRanges.class, aLabelsObj ); + com.sun.star.table.CellRangeAddress aLabelArea = new com.sun.star.table.CellRangeAddress(); + aLabelArea.Sheet = 0; + aLabelArea.StartColumn = 6; + aLabelArea.StartRow = 47; + aLabelArea.EndColumn = 7; + aLabelArea.EndRow = 47; + com.sun.star.table.CellRangeAddress aDataArea = new com.sun.star.table.CellRangeAddress(); + aDataArea.Sheet = 0; + aDataArea.StartColumn = 6; + aDataArea.StartRow = 48; + aDataArea.EndColumn = 7; + aDataArea.EndRow = 49; + xLabelRanges.addNew( aLabelArea, aDataArea ); + + // use the label range in formulas + xSheet.getCellByPosition( 8, 48 ).setFormula( "=Apples+Oranges" ); + xSheet.getCellByPosition( 8, 49 ).setFormula( "=Apples+Oranges" ); + } + + + + /** Helper for doDatabaseSamples: get name of first database. */ + private String getFirstDatabaseName() + { + String aDatabase = null; + try + { + com.sun.star.lang.XMultiComponentFactory xServiceManager = getServiceManager(); + com.sun.star.container.XNameAccess xContext = + UnoRuntime.queryInterface( + com.sun.star.container.XNameAccess.class, + xServiceManager.createInstanceWithContext( + "com.sun.star.sdb.DatabaseContext", getContext()) ); + String[] aNames = xContext.getElementNames(); + if ( aNames.length > 0 ) + aDatabase = aNames[0]; + } + catch ( Exception e ) + { + System.out.println( "\nError: caught exception in getFirstDatabaseName()!\n" + + "Exception Message = " + + e.getMessage()); + e.printStackTrace(); + } + return aDatabase; + } + + /** Helper for doDatabaseSamples: get name of first table in a database. */ + private String getFirstTableName( String aDatabase ) + { + if ( aDatabase == null ) + return null; + + String aTable = null; + try + { + com.sun.star.lang.XMultiComponentFactory xServiceManager = getServiceManager(); + com.sun.star.container.XNameAccess xContext = UnoRuntime.queryInterface( com.sun.star.container.XNameAccess.class, + xServiceManager.createInstanceWithContext( + "com.sun.star.sdb.DatabaseContext", getContext()) ); + com.sun.star.sdb.XCompletedConnection xSource = + UnoRuntime.queryInterface( + com.sun.star.sdb.XCompletedConnection.class, + xContext.getByName( aDatabase ) ); + com.sun.star.task.XInteractionHandler xHandler = + UnoRuntime.queryInterface( + com.sun.star.task.XInteractionHandler.class, + xServiceManager.createInstanceWithContext( + "com.sun.star.task.InteractionHandler", getContext()) ); + com.sun.star.sdbcx.XTablesSupplier xSupplier = + UnoRuntime.queryInterface( + com.sun.star.sdbcx.XTablesSupplier.class, + xSource.connectWithCompletion( xHandler ) ); + com.sun.star.container.XNameAccess xTables = xSupplier.getTables(); + String[] aNames = xTables.getElementNames(); + if ( aNames.length > 0 ) + aTable = aNames[0]; + } + catch ( Exception e ) + { + System.out.println( "\nError: caught exception in getFirstTableName()!\n" + + "Exception Message = " + + e.getMessage()); + e.printStackTrace(); + } + return aTable; + } + + private void doDatabaseSamples() throws Exception + { + System.out.println( "\n*** Samples for database operations ***\n" ); + com.sun.star.sheet.XSpreadsheet xSheet = getSpreadsheet( 2 ); + + + // --- put some example data into the sheet --- + com.sun.star.table.XCellRange xRange = xSheet.getCellRangeByName( "B3:D24" ); + com.sun.star.sheet.XCellRangeData xData = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeData.class, xRange ); + Object[][] aValues = + { + { "Name", "Year", "Sales" }, + { "Alice", new Double( 2001 ), new Double( 4.0 ) }, + { "Carol", new Double( 1997 ), new Double( 3.0 ) }, + { "Carol", new Double( 1998 ), new Double( 8.0 ) }, + { "Bob", new Double( 1997 ), new Double( 8.0 ) }, + { "Alice", new Double( 2002 ), new Double( 9.0 ) }, + { "Alice", new Double( 1999 ), new Double( 7.0 ) }, + { "Alice", new Double( 1996 ), new Double( 3.0 ) }, + { "Bob", new Double( 2000 ), new Double( 1.0 ) }, + { "Carol", new Double( 1999 ), new Double( 5.0 ) }, + { "Bob", new Double( 2002 ), new Double( 1.0 ) }, + { "Carol", new Double( 2001 ), new Double( 5.0 ) }, + { "Carol", new Double( 2000 ), new Double( 1.0 ) }, + { "Carol", new Double( 1996 ), new Double( 8.0 ) }, + { "Bob", new Double( 1996 ), new Double( 7.0 ) }, + { "Alice", new Double( 1997 ), new Double( 3.0 ) }, + { "Alice", new Double( 2000 ), new Double( 9.0 ) }, + { "Bob", new Double( 1998 ), new Double( 1.0 ) }, + { "Bob", new Double( 1999 ), new Double( 6.0 ) }, + { "Carol", new Double( 2002 ), new Double( 8.0 ) }, + { "Alice", new Double( 1998 ), new Double( 5.0 ) }, + { "Bob", new Double( 2001 ), new Double( 6.0 ) } + }; + xData.setDataArray( aValues ); + + + // --- filter for second column >= 1998 --- + com.sun.star.sheet.XSheetFilterable xFilter = UnoRuntime.queryInterface( com.sun.star.sheet.XSheetFilterable.class, xRange ); + com.sun.star.sheet.XSheetFilterDescriptor xFilterDesc = + xFilter.createFilterDescriptor( true ); + com.sun.star.sheet.TableFilterField[] aFilterFields = + new com.sun.star.sheet.TableFilterField[1]; + aFilterFields[0] = new com.sun.star.sheet.TableFilterField(); + aFilterFields[0].Field = 1; + aFilterFields[0].IsNumeric = true; + aFilterFields[0].Operator = com.sun.star.sheet.FilterOperator.GREATER_EQUAL; + aFilterFields[0].NumericValue = 1998; + xFilterDesc.setFilterFields( aFilterFields ); + com.sun.star.beans.XPropertySet xFilterProp = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, xFilterDesc ); + xFilterProp.setPropertyValue( "ContainsHeader", Boolean.TRUE ); + xFilter.filter( xFilterDesc ); + + + // --- do the same filter as above, using criteria from a cell range --- + com.sun.star.table.XCellRange xCritRange = xSheet.getCellRangeByName( "B27:B28" ); + com.sun.star.sheet.XCellRangeData xCritData = UnoRuntime.queryInterface( com.sun.star.sheet.XCellRangeData.class, xCritRange ); + Object[][] aCritValues = + { + { "Year" }, + { ">= 1998" } + }; + xCritData.setDataArray( aCritValues ); + com.sun.star.sheet.XSheetFilterableEx xCriteria = UnoRuntime.queryInterface( com.sun.star.sheet.XSheetFilterableEx.class, xCritRange ); + xFilterDesc = xCriteria.createFilterDescriptorByObject( xFilter ); + if ( xFilterDesc != null ) + xFilter.filter( xFilterDesc ); + + + // --- sort by second column, ascending --- + com.sun.star.table.TableSortField[] aSortFields = new com.sun.star.table.TableSortField[1]; + aSortFields[0] = new com.sun.star.table.TableSortField(); + aSortFields[0].Field = 1; + aSortFields[0].IsAscending = false; + aSortFields[0].IsCaseSensitive = false; + + + com.sun.star.beans.PropertyValue[] aSortDesc = new com.sun.star.beans.PropertyValue[2]; + aSortDesc[0] = new com.sun.star.beans.PropertyValue(); + aSortDesc[0].Name = "SortFields"; + aSortDesc[0].Value = aSortFields; + aSortDesc[1] = new com.sun.star.beans.PropertyValue(); + aSortDesc[1].Name = "ContainsHeader"; + aSortDesc[1].Value = Boolean.TRUE; + + com.sun.star.util.XSortable xSort = UnoRuntime.queryInterface( com.sun.star.util.XSortable.class, xRange ); + xSort.sort( aSortDesc ); + + + // --- insert subtotals --- + com.sun.star.sheet.XSubTotalCalculatable xSub = UnoRuntime.queryInterface( com.sun.star.sheet.XSubTotalCalculatable.class, xRange ); + com.sun.star.sheet.XSubTotalDescriptor xSubDesc = xSub.createSubTotalDescriptor( true ); + com.sun.star.sheet.SubTotalColumn[] aColumns = new com.sun.star.sheet.SubTotalColumn[1]; + // calculate sum of third column + aColumns[0] = new com.sun.star.sheet.SubTotalColumn(); + aColumns[0].Column = 2; + aColumns[0].Function = com.sun.star.sheet.GeneralFunction.SUM; + // group by first column + xSubDesc.addNew( aColumns, 0 ); + xSub.applySubTotals( xSubDesc, true ); + + String aDatabase = getFirstDatabaseName(); + String aTableName = getFirstTableName( aDatabase ); + if ( aDatabase != null && aTableName != null ) + { + // --- import from database --- + com.sun.star.beans.PropertyValue[] aImportDesc = new com.sun.star.beans.PropertyValue[3]; + aImportDesc[0] = new com.sun.star.beans.PropertyValue(); + aImportDesc[0].Name = "DatabaseName"; + aImportDesc[0].Value = aDatabase; + aImportDesc[1] = new com.sun.star.beans.PropertyValue(); + aImportDesc[1].Name = "SourceType"; + aImportDesc[1].Value = com.sun.star.sheet.DataImportMode.TABLE; + aImportDesc[2] = new com.sun.star.beans.PropertyValue(); + aImportDesc[2].Name = "SourceObject"; + aImportDesc[2].Value = aTableName; + + com.sun.star.table.XCellRange xImportRange = xSheet.getCellRangeByName( "B35:B35" ); + com.sun.star.util.XImportable xImport = UnoRuntime.queryInterface( com.sun.star.util.XImportable.class, xImportRange ); + xImport.doImport( aImportDesc ); + + + // --- use the temporary database range to find the imported data's size --- + com.sun.star.beans.XPropertySet xDocProp = UnoRuntime.queryInterface( com.sun.star.beans.XPropertySet.class, getDocument() ); + Object aRangesObj = xDocProp.getPropertyValue( "DatabaseRanges" ); + com.sun.star.container.XNameAccess xRanges = + UnoRuntime.queryInterface( + com.sun.star.container.XNameAccess.class, aRangesObj ); + String[] aNames = xRanges.getElementNames(); + for ( int i=0; i +#include + +module org { + module openoffice { + module sheet { + module addin { + /// The interface that the example addin implements + interface XExampleAddIn : com::sun::star::uno::XInterface + { + /// Sample function that just increments a value. + long getIncremented( [in] long nValue ); + + /// Sample function that returns a volatile result. + com::sun::star::sheet::XVolatileResult getCounter( [in] string aName ); + }; + }; + }; + }; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Text/Makefile b/odk/examples/DevelopersGuide/Text/Makefile new file mode 100644 index 000000000..d27923b6f --- /dev/null +++ b/odk/examples/DevelopersGuide/Text/Makefile @@ -0,0 +1,95 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Text example of the Developers Guide. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=TextExample +SAMPLE_CLASS_OUT = $(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT = $(OUT_MISC)/$(SAMPLE_NAME) + +APP1_NAME=TextDocuments +APP1_JAR=$(SAMPLE_CLASS_OUT)/$(APP1_NAME).jar + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : \ + $(SAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(SAMPLE_CLASS_OUT)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SAMPLE_CLASS_OUT) $< + +$(SAMPLE_CLASS_OUT)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(SAMPLE_CLASS_OUT)/%.jar : $(SAMPLE_CLASS_OUT)/%.mf $(SAMPLE_CLASS_OUT)/%.class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP1_JAR) : $(SAMPLE_CLASS_OUT)/$(APP1_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP1_NAME).class + +$(SAMPLE_NAME) : $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(SAMPLE_CLASS_OUT)/%.jar + -$(MKDIR) $(subst /,$(PS),$(SAMPLE_GEN_OUT)/savetest) + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< "$(SAMPLE_GEN_OUT)/savetest" + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) diff --git a/odk/examples/DevelopersGuide/Text/PrintDemo.odt b/odk/examples/DevelopersGuide/Text/PrintDemo.odt new file mode 100644 index 000000000..1b02d883a Binary files /dev/null and b/odk/examples/DevelopersGuide/Text/PrintDemo.odt differ diff --git a/odk/examples/DevelopersGuide/Text/TextDocuments.java b/odk/examples/DevelopersGuide/Text/TextDocuments.java new file mode 100644 index 000000000..20e9f7a58 --- /dev/null +++ b/odk/examples/DevelopersGuide/Text/TextDocuments.java @@ -0,0 +1,1724 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Random; + +import com.sun.star.awt.Point; +import com.sun.star.awt.Size; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XEnumeration; +import com.sun.star.container.XEnumerationAccess; +import com.sun.star.container.XIndexAccess; +import com.sun.star.container.XIndexReplace; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNameContainer; +import com.sun.star.container.XNamed; +import com.sun.star.drawing.XDrawPageSupplier; +import com.sun.star.drawing.XShape; +import com.sun.star.drawing.XShapes; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XController; +import com.sun.star.frame.XDesktop; +import com.sun.star.frame.XModel; +import com.sun.star.frame.XStorable; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.style.NumberingType; +import com.sun.star.style.XStyle; +import com.sun.star.style.XStyleFamiliesSupplier; +import com.sun.star.text.ControlCharacter; +import com.sun.star.text.ReferenceFieldPart; +import com.sun.star.text.ReferenceFieldSource; +import com.sun.star.text.TextColumn; +import com.sun.star.text.TextContentAnchorType; +import com.sun.star.text.XAutoTextEntry; +import com.sun.star.text.XAutoTextGroup; +import com.sun.star.text.XBookmarksSupplier; +import com.sun.star.text.XDependentTextField; +import com.sun.star.text.XDocumentIndex; +import com.sun.star.text.XFootnote; +import com.sun.star.text.XFootnotesSupplier; +import com.sun.star.text.XPageCursor; +import com.sun.star.text.XParagraphCursor; +import com.sun.star.text.XReferenceMarksSupplier; +import com.sun.star.text.XRelativeTextContentInsert; +import com.sun.star.text.XSentenceCursor; +import com.sun.star.text.XSimpleText; +import com.sun.star.text.XText; +import com.sun.star.text.XTextColumns; +import com.sun.star.text.XTextContent; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextDocument; +import com.sun.star.text.XTextField; +import com.sun.star.text.XTextFieldsSupplier; +import com.sun.star.text.XTextFrame; +import com.sun.star.text.XTextRange; +import com.sun.star.text.XTextTable; +import com.sun.star.text.XTextTableCursor; +import com.sun.star.text.XTextTablesSupplier; +import com.sun.star.text.XTextViewCursor; +import com.sun.star.text.XTextViewCursorSupplier; +import com.sun.star.text.XWordCursor; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.util.XRefreshable; +import com.sun.star.view.XPrintable; + + +public class TextDocuments { + // adjust these constant to your local printer! + private static String sOutputDir; + + private static final String aPrinterName = "\\\\so-print\\xml3sof"; + + private XComponentContext mxRemoteContext = null; + private XMultiComponentFactory mxRemoteServiceManager = null; + private XTextDocument mxDoc = null; + private XMultiServiceFactory mxDocFactory = null; + private XMultiServiceFactory mxFactory = null; + private XText mxDocText = null; + private XTextCursor mxDocCursor = null; + private XTextContent mxFishSection = null; + private Random maRandom = null; + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + TextDocuments textDocuments1 = new TextDocuments(); + try { + // output directory for store test; + sOutputDir = args[0]; + + textDocuments1.runDemo(); + } catch (java.lang.Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } finally { + System.exit(0); + } + } + + protected void runDemo() throws java.lang.Exception { + storePrintExample(); // depends on printer name + templateExample(); + viewCursorExample(); // makes changes to the current document, + // use with care + editingExample(); + } + + /** Sample for use of templates + * This sample uses the file TextTemplateWithUserFields.odt from the Samples + * folder. The file contains a number of User text fields (Variables - User) + * and a bookmark which we use to fill in various values + */ + protected void templateExample() throws java.lang.Exception { + // create a small hashtable that simulates a rowset + HashMap recipient = new HashMap(); + recipient.put("Company", "Manatee Books"); + recipient.put("Contact", "Rod Martin"); + recipient.put("ZIP", "34567"); + recipient.put("City", "Fort Lauderdale"); + recipient.put("State", "Florida"); + + // load template with User fields and bookmark + java.io.File sourceFile = new java.io.File("TextTemplateWithUserFields.odt"); + StringBuffer sTemplateFileUrl = new StringBuffer("file:///"); + sTemplateFileUrl.append(sourceFile.getCanonicalPath().replace('\\', '/')); + + XComponent xTemplateComponent = + newDocComponentFromTemplate( sTemplateFileUrl.toString() ); + + // get XTextFieldsSupplier, XBookmarksSupplier interfaces + XTextFieldsSupplier xTextFieldsSupplier = UnoRuntime.queryInterface(XTextFieldsSupplier.class, + xTemplateComponent); + XBookmarksSupplier xBookmarksSupplier = UnoRuntime.queryInterface(XBookmarksSupplier.class, xTemplateComponent); + + // access the TextFields and the TextFieldMasters collections + XNameAccess xNamedFieldMasters = xTextFieldsSupplier.getTextFieldMasters(); + XEnumerationAccess xEnumeratedFields = xTextFieldsSupplier.getTextFields(); + + // iterate over hashtable and insert values into field masters + for(Iterator iter = recipient.keySet().iterator(); iter.hasNext(); ) { + // get column name + String key = iter.next(); + + // access corresponding field master + Object fieldMaster = xNamedFieldMasters.getByName( + "com.sun.star.text.fieldmaster.User." + key); + + // query the XPropertySet interface, we need to set the Content property + XPropertySet xPropertySet = UnoRuntime.queryInterface( + XPropertySet.class, fieldMaster); + + // insert the column value into field master + xPropertySet.setPropertyValue("Content", recipient.get(key)); + } + // afterwards we must refresh the textfields collection + XRefreshable xRefreshable = UnoRuntime.queryInterface( + XRefreshable.class, xEnumeratedFields); + xRefreshable.refresh(); + + // accessing the Bookmarks collection of the document + XNameAccess xNamedBookmarks = xBookmarksSupplier.getBookmarks(); + + // find the bookmark named "Subscription" + Object bookmark = xNamedBookmarks.getByName("Subscription"); + // we need its XTextRange which is available from getAnchor(), + // so query for XTextContent + XTextContent xBookmarkContent = UnoRuntime.queryInterface( + XTextContent.class, bookmark); + // get the anchor of the bookmark (its XTextRange) + XTextRange xBookmarkRange = xBookmarkContent.getAnchor(); + // set string at the bookmark position + xBookmarkRange.setString("subscription for the Manatee Journal"); + + } + + /** Sample for document changes, starting at the current view cursor position + * The sample changes the paragraph style and the character style at the + * current view cursor selection Open the sample file ViewCursorExampleFile, + * select some text and run the example. + * The current paragraph will be set to Quotations paragraph style. + * The selected text will be set to Quotation character style. + */ + private void viewCursorExample() throws java.lang.Exception { + // get the remote service manager + mxRemoteServiceManager = this.getRemoteServiceManager(); + // get the Desktop service + Object desktop = mxRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", mxRemoteContext); + // query its XDesktop interface, we need the current component + XDesktop xDesktop = UnoRuntime.queryInterface( + XDesktop.class, desktop); + // retrieve the current component and access the controller + XComponent xCurrentComponent = xDesktop.getCurrentComponent(); + XModel xModel = UnoRuntime.queryInterface(XModel.class, + xCurrentComponent); + XController xController = xModel.getCurrentController(); + // the controller gives us the TextViewCursor + XTextViewCursorSupplier xViewCursorSupplier = + UnoRuntime.queryInterface( + XTextViewCursorSupplier.class, xController); + XTextViewCursor xViewCursor = xViewCursorSupplier.getViewCursor(); + + // query its XPropertySet interface, we want to set character and paragraph + // properties + XPropertySet xCursorPropertySet = UnoRuntime.queryInterface( + XPropertySet.class, xViewCursor); + // set the appropriate properties for character and paragraph style + xCursorPropertySet.setPropertyValue("CharStyleName", "Quotation"); + xCursorPropertySet.setPropertyValue("ParaStyleName", "Quotations"); + // print the current page number + XPageCursor xPageCursor = UnoRuntime.queryInterface( + XPageCursor.class, xViewCursor); + System.out.println("The current page number is " + xPageCursor.getPage()); + // the model cursor is much more powerful, so + // we create a model cursor at the current view cursor position with the + // following steps: + // get the Text service from the TextViewCursor, it is an XTextRange: + XText xDocumentText = xViewCursor.getText(); + // create a model cursor from the viewcursor + XTextCursor xModelCursor = xDocumentText.createTextCursorByRange( + xViewCursor.getStart()); + // now we could query XWordCursor, XSentenceCursor and XParagraphCursor + // or XDocumentInsertable, XSortable or XContentEnumerationAccess + // and work with the properties of com.sun.star.text.TextCursor + // in this case we just go to the end of the paragraph and add some text. + XParagraphCursor xParagraphCursor = UnoRuntime.queryInterface(XParagraphCursor.class, xModelCursor); + // goto the end of the paragraph + xParagraphCursor.gotoEndOfParagraph(false); + xParagraphCursor.setString(" ***** Fin de semana! ******"); + } + + + /** Sample for the various editing facilities described in the + * developer's manual + */ + private void editingExample () throws java.lang.Exception { + // create empty swriter document + XComponent xEmptyWriterComponent = newDocComponent("swriter"); + // query its XTextDocument interface to get the text + mxDoc = UnoRuntime.queryInterface( + XTextDocument.class, xEmptyWriterComponent); + + // get a reference to the body text of the document + mxDocText = mxDoc.getText(); + + // Get a reference to the document's property set. This contains document + // information like the current word count + UnoRuntime.queryInterface(XPropertySet.class, mxDoc ); + + // Simple text insertion example + BodyTextExample (); + // Example using text ranges to insert strings at the beginning or end + // of a text range + TextRangeExample (); + // Create a document cursor and remember it, it will be used in most + // of the following examples + mxDocCursor = mxDocText.createTextCursor(); + // Demonstrate some of the different cursor types (word, sentence) + TextCursorExample (); + + // Access the text document's multi service factory, which we will need + // for most of the following examples + mxDocFactory = UnoRuntime.queryInterface( + XMultiServiceFactory.class, mxDoc ); + + // Examples of text fields, dependent text fields and field masters + TextFieldExample (); + + // Example of using an XEnumerationAccess to iterate over paragraphs and + // set properties of each paragraph as we do so + ParagraphExample (); + + // Example of creating and manipulating a text frame + TextFrameExample (); + + // Example of creating and manipulating a text table, text table rows + // and text table cells get a new random generator + maRandom = new Random(); + TextTableExample (); + + // Example of creating, inserting and manipulating text sections, as + // well as an example of how to refresh the document + TextSectionExample (); + + // Example of creating a text section over a block of text and formatting + // the text section into columns, as well as how to insert an empty + // paragraph using the XRelativeTextContentInsert + TextColumnsExample (); + + // Example of creating the NumberingRules service and adjusting + // NumberingTypes and NumberingLevels + NumberingExample (); + + // Example of how to use the XStyleFamiliesSupplier interface of the + // document and how to create, insert and apply styles + StylesExample (); + IndexExample (); + + // Example of how to create and manipulate reference marks and GetReference + // text fields + ReferenceExample (); + + // Example of how to create and insert Footnotes and how to use the + // XFootnotesSupplier interface of the document + FootnoteExample (); + + // This method demonstrates how to create shapes from the document factory + // and how to access the draw page of the document using the + // XDrawPageSupplier interface + DrawPageExample (); + + mxFactory = UnoRuntime.queryInterface( + XMultiServiceFactory.class, mxRemoteServiceManager); + // This example demonstrates the use of the AutoTextContainer, + // AutoTextGroup and AutoTextEntry services and shows how to create, + // insert and modify auto text blocks + AutoTextExample (); + } + + protected void storePrintExample() throws java.lang.Exception { + // get the remote service manager + mxRemoteServiceManager = this.getRemoteServiceManager(); + // retrieve the Desktop object, we need its XComponentLoader + Object desktop = mxRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", mxRemoteContext); + XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, desktop); + PropertyValue[] loadProps = new PropertyValue[0]; + + java.io.File sourceFile = new java.io.File("PrintDemo.odt"); + StringBuffer sLoadFileUrl = new StringBuffer("file:///"); + sLoadFileUrl.append(sourceFile.getCanonicalPath().replace('\\', '/')); + + XComponent xDoc = xComponentLoader.loadComponentFromURL( + sLoadFileUrl.toString(), "_blank", 0, loadProps); + + if ( xDoc != null ) { + sourceFile = new java.io.File(sOutputDir); + StringBuffer sStoreFileUrl = new StringBuffer(); + sStoreFileUrl.append(sourceFile.toURI().toURL().toString()); + sStoreFileUrl.append("somepopularfileformat.doc"); + + storeDocComponent(xDoc, sStoreFileUrl.toString() ); + printDocComponent(xDoc); + } + } + + private XMultiComponentFactory getRemoteServiceManager() + throws java.lang.Exception + { + if (mxRemoteContext == null && mxRemoteServiceManager == null) { + // get the remote office context. If necessary a new office + // process is started + mxRemoteContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + mxRemoteServiceManager = mxRemoteContext.getServiceManager(); + } + return mxRemoteServiceManager; + } + + protected XComponent newDocComponent(String docType) + throws java.lang.Exception + { + String loadUrl = "private:factory/" + docType; + mxRemoteServiceManager = this.getRemoteServiceManager(); + Object desktop = mxRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", mxRemoteContext); + XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, desktop); + PropertyValue[] loadProps = new PropertyValue[0]; + return xComponentLoader.loadComponentFromURL(loadUrl, "_blank", + 0, loadProps); + } + + /** Load a document as template + */ + protected XComponent newDocComponentFromTemplate(String loadUrl) + throws java.lang.Exception + { + // get the remote service manager + mxRemoteServiceManager = this.getRemoteServiceManager(); + // retrieve the Desktop object, we need its XComponentLoader + Object desktop = mxRemoteServiceManager.createInstanceWithContext( + "com.sun.star.frame.Desktop", mxRemoteContext); + XComponentLoader xComponentLoader = UnoRuntime.queryInterface(XComponentLoader.class, desktop); + + // define load properties according to com.sun.star.document.MediaDescriptor + // the boolean property AsTemplate tells the office to create a new document + // from the given file + PropertyValue[] loadProps = new PropertyValue[1]; + loadProps[0] = new PropertyValue(); + loadProps[0].Name = "AsTemplate"; + loadProps[0].Value = Boolean.TRUE; + // load + return xComponentLoader.loadComponentFromURL(loadUrl, "_blank", + 0, loadProps); + } + + /** Load a document with arguments (text purposes) + */ + protected void storeDocComponent(XComponent xDoc, String storeUrl) + throws java.lang.Exception + { + + XStorable xStorable = UnoRuntime.queryInterface( + XStorable.class, xDoc); + PropertyValue[] storeProps = new PropertyValue[1]; + storeProps[0] = new PropertyValue(); + storeProps[0].Name = "FilterName"; + storeProps[0].Value = "MS Word 97"; + + System.out.println("... store \"PrintDemo.odt\" to \"" + storeUrl + "\"."); + xStorable.storeAsURL(storeUrl, storeProps); + } + + protected void printDocComponent(XComponent xDoc) throws java.lang.Exception { + XPrintable xPrintable = UnoRuntime.queryInterface( + XPrintable.class, xDoc); + PropertyValue[] printerDesc = new PropertyValue[1]; + printerDesc[0] = new PropertyValue(); + printerDesc[0].Name = "Name"; + printerDesc[0].Value = aPrinterName; + + xPrintable.setPrinter(printerDesc); + + PropertyValue[] printOpts = new PropertyValue[1]; + printOpts[0] = new PropertyValue(); + printOpts[0].Name = "Pages"; + printOpts[0].Value = "1"; + + xPrintable.print(printOpts); + } + + // Setting the whole text of a document as one string + protected void BodyTextExample () + { + // Body Text and TextDocument example + try + { + // demonstrate simple text insertion + mxDocText.setString ( "This is the new body text of the document." + + "\n\nThis is on the second line.\n\n" ); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + + // Adding a string at the end or the beginning of text + protected void TextRangeExample () + { + try + { + // Get a text range referring to the beginning of the text document + XTextRange xStart = mxDocText.getStart(); + // use setString to insert text at the beginning + xStart.setString ( "This is text inserted at the beginning.\n\n" ); + // Get a text range referring to the end of the text document + XTextRange xEnd = mxDocText.getEnd(); + // use setString to insert text at the end + xEnd.setString ( "This is text inserted at the end.\n\n" ); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + + /** moving a text cursor, selecting text and overwriting it + */ + protected void TextCursorExample () + { + try + { + // First, get the XSentenceCursor interface of our text cursor + XSentenceCursor xSentenceCursor = UnoRuntime.queryInterface(XSentenceCursor.class, mxDocCursor ); + // Goto the next cursor, without selecting it + xSentenceCursor.gotoNextSentence( false ); + // Get the XWordCursor interface of our text cursor + XWordCursor xWordCursor = UnoRuntime.queryInterface( + XWordCursor.class, mxDocCursor ); + // Skip the first four words of this sentence and select the fifth + xWordCursor.gotoNextWord( false ); + xWordCursor.gotoNextWord( false ); + xWordCursor.gotoNextWord( false ); + xWordCursor.gotoNextWord( false ); + xWordCursor.gotoNextWord( true ); + // Use the XSimpleText interface to insert a word at the current cursor + // location, over-writing the current selection (the fifth word + // selected above) + mxDocText.insertString ( xWordCursor, "old ", true ); + + // Access the property set of the cursor, and set the currently + // selected text (which is the string we just inserted) to be bold + XPropertySet xCursorProps = UnoRuntime.queryInterface( + XPropertySet.class, mxDocCursor ); + xCursorProps.setPropertyValue ( "CharWeight", + new Float(com.sun.star.awt.FontWeight.BOLD) ); + + // replace the '.' at the end of the sentence with a new string + xSentenceCursor.gotoEndOfSentence( false ); + xWordCursor.gotoPreviousWord( true ); + mxDocText.insertString (xWordCursor, + ", which has been changed with text cursors!", + true); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + + /** This method inserts both a date field and a user field containing the + * number '42' + */ + protected void TextFieldExample () + { + try + { + // Use the text document's factory to create a DateTime text field, + // and access its XTextField interface + XTextField xDateField = UnoRuntime.queryInterface ( + XTextField.class, mxDocFactory.createInstance ( + "com.sun.star.text.TextField.DateTime" ) ); + + // Insert it at the end of the document + mxDocText.insertTextContent ( mxDocText.getEnd(), xDateField, false ); + + // Use the text document's factory to create a user text field, + // and access its XDependentTextField interface + XDependentTextField xUserField = + UnoRuntime.queryInterface ( + XDependentTextField.class, mxDocFactory.createInstance ( + "com.sun.star.text.TextField.User" ) ); + + // Create a fieldmaster for our newly created User Text field, and + // access its XPropertySet interface + XPropertySet xMasterPropSet = UnoRuntime.queryInterface( + XPropertySet.class, mxDocFactory.createInstance ( + "com.sun.star.text.fieldmaster.User" ) ); + + // Set the name and value of the FieldMaster + xMasterPropSet.setPropertyValue ( "Name", "UserEmperor" ); + xMasterPropSet.setPropertyValue ( "Value", Integer.valueOf( 42 ) ); + + // Attach the field master to the user field + xUserField.attachTextFieldMaster ( xMasterPropSet ); + + // Move the cursor to the end of the document + mxDocCursor.gotoEnd( false ); + // insert a paragraph break using the XSimpleText interface + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + + // Insert the user field at the end of the document + mxDocText.insertTextContent ( mxDocText.getEnd(), xUserField, false ); + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + + /** This method demonstrates how to iterate over paragraphs + */ + protected void ParagraphExample () + { + try + { + // The service 'com.sun.star.text.Text' supports the XEnumerationAccess + // interface to provide an enumeration of the paragraphs contained by + // the text the service refers to. + + // Here, we access this interface + XEnumerationAccess xParaAccess = UnoRuntime.queryInterface(XEnumerationAccess.class, mxDocText ); + // Call the XEnumerationAccess's only method to access the actual + // Enumeration + XEnumeration xParaEnum = xParaAccess.createEnumeration(); + + // While there are paragraphs, do things to them + while ( xParaEnum.hasMoreElements() ) + { + // Get a reference to the next paragraphs XServiceInfo interface. + // TextTables are also part of this enumeration access, so we ask + // the element if it is a TextTable, if it doesn't support the + // com.sun.star.text.TextTable service, then it is safe to assume + // that it really is a paragraph + XServiceInfo xInfo = UnoRuntime.queryInterface( + XServiceInfo.class, xParaEnum.nextElement() ); + if ( !xInfo.supportsService ( "com.sun.star.text.TextTable" ) ) + { + // Access the paragraph's property set...the properties in this + // property set are listed in: + // com.sun.star.style.ParagraphProperties + XPropertySet xSet = UnoRuntime.queryInterface( + XPropertySet.class, xInfo ); + // Set the justification to be center justified + xSet.setPropertyValue ( "ParaAdjust", + com.sun.star.style.ParagraphAdjust.CENTER ); + } + } + } + catch ( Exception e ) + { + e.printStackTrace(); + } + } + + /** This method returns a random double which isn't too high or too low + */ + protected double getRandomDouble () + { + return ( ( maRandom.nextInt() % 1000 ) * maRandom.nextDouble () ); + } + + /** This method sets the text colour of the cell referred to by sCellName to + white and inserts the string sText in it + */ + protected static void insertIntoCell(String sCellName, String sText, + XTextTable xTable) + { + // Access the XText interface of the cell referred to by sCellName + XText xCellText = UnoRuntime.queryInterface( + XText.class, xTable.getCellByName ( sCellName ) ); + + // create a text cursor from the cells XText interface + XTextCursor xCellCursor = xCellText.createTextCursor(); + // Get the property set of the cell's TextCursor + XPropertySet xCellCursorProps = UnoRuntime.queryInterface( + XPropertySet.class, xCellCursor ); + + try + { + // Set the colour of the text to white + xCellCursorProps.setPropertyValue( "CharColor", Integer.valueOf(16777215)); + } + catch ( Exception e) + { + e.printStackTrace(); + } + // Set the text in the cell to sText + xCellText.setString( sText ); + } + + /** This method shows how to create and insert a text table, as well as insert + text and formulae into the cells of the table + */ + protected void TextTableExample () + { + try + { + // Create a new table from the document's factory + XTextTable xTable = UnoRuntime.queryInterface( + XTextTable.class, mxDocFactory .createInstance( + "com.sun.star.text.TextTable" ) ); + + // Specify that we want the table to have 4 rows and 4 columns + xTable.initialize( 4, 4 ); + + // Insert the table into the document + mxDocText.insertTextContent( mxDocCursor, xTable, false); + // Get an XIndexAccess of the table rows + XIndexAccess xRows = xTable.getRows(); + + // Access the property set of the first row (properties listed in + // service description: com.sun.star.text.TextTableRow) + XPropertySet xRow = UnoRuntime.queryInterface( + XPropertySet.class, xRows.getByIndex ( 0 ) ); + // If BackTransparent is false, then the background color is visible + xRow.setPropertyValue( "BackTransparent", Boolean.FALSE); + // Specify the color of the background to be dark blue + xRow.setPropertyValue( "BackColor", Integer.valueOf(6710932)); + + // Access the property set of the whole table + XPropertySet xTableProps = UnoRuntime.queryInterface( + XPropertySet.class, xTable ); + // We want visible background colors + xTableProps.setPropertyValue( "BackTransparent", Boolean.FALSE); + // Set the background colour to light blue + xTableProps.setPropertyValue( "BackColor", Integer.valueOf(13421823)); + + // set the text (and text colour) of all the cells in the first row + // of the table + insertIntoCell( "A1", "First Column", xTable ); + insertIntoCell( "B1", "Second Column", xTable ); + insertIntoCell( "C1", "Third Column", xTable ); + insertIntoCell( "D1", "Results", xTable ); + + // Insert random numbers into the first this three cells of each + // remaining row + xTable.getCellByName( "A2" ).setValue( getRandomDouble() ); + xTable.getCellByName( "B2" ).setValue( getRandomDouble() ); + xTable.getCellByName( "C2" ).setValue( getRandomDouble() ); + + xTable.getCellByName( "A3" ).setValue( getRandomDouble() ); + xTable.getCellByName( "B3" ).setValue( getRandomDouble() ); + xTable.getCellByName( "C3" ).setValue( getRandomDouble() ); + + xTable.getCellByName( "A4" ).setValue( getRandomDouble() ); + xTable.getCellByName( "B4" ).setValue( getRandomDouble() ); + xTable.getCellByName( "C4" ).setValue( getRandomDouble() ); + + // Set the last cell in each row to be a formula that calculates + // the sum of the first three cells + xTable.getCellByName( "D2" ).setFormula( "sum " ); + xTable.getCellByName( "D3" ).setFormula( "sum " ); + xTable.getCellByName( "D4" ).setFormula( "sum " ); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + /** This method shows how to create and manipulate text frames + */ + protected void TextFrameExample () + { + try + { + // Use the document's factory to create a new text frame and + // immediately access its XTextFrame interface + XTextFrame xFrame = UnoRuntime.queryInterface ( + XTextFrame.class, mxDocFactory.createInstance ( + "com.sun.star.text.TextFrame" ) ); + + // Access the XShape interface of the TextFrame + XShape xShape = UnoRuntime.queryInterface(XShape.class, xFrame); + // Access the XPropertySet interface of the TextFrame + XPropertySet xFrameProps = UnoRuntime.queryInterface( + XPropertySet.class, xFrame ); + + // Set the size of the new Text Frame using the XShape's 'setSize' + // method + Size aSize = new Size(); + aSize.Height = 400; + aSize.Width = 15000; + xShape.setSize(aSize); + // Set the AnchorType to + // com.sun.star.text.TextContentAnchorType.AS_CHARACTER + xFrameProps.setPropertyValue( "AnchorType", + TextContentAnchorType.AS_CHARACTER ); + // Go to the end of the text document + mxDocCursor.gotoEnd( false ); + // Insert a new paragraph + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + // Then insert the new frame + mxDocText.insertTextContent(mxDocCursor, xFrame, false); + + // Access the XText interface of the text contained within the frame + XText xFrameText = xFrame.getText(); + // Create a TextCursor over the frame's contents + XTextCursor xFrameCursor = xFrameText.createTextCursor(); + // Insert some text into the frame + xFrameText.insertString( + xFrameCursor, "The first line in the newly created text frame.", + false ); + xFrameText.insertString( + xFrameCursor, "\nThe second line in the new text frame.", false ); + // Insert a paragraph break into the document (not the frame) + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** This example demonstrates the use of the AutoTextContainer, AutoTextGroup + and AutoTextEntry services and shows how to create, insert and modify + auto text blocks + */ + protected void AutoTextExample () + { + try + { + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + // Insert two paragraphs + mxDocText.insertControlCharacter ( mxDocCursor, + ControlCharacter.PARAGRAPH_BREAK, false ); + mxDocText.insertControlCharacter ( mxDocCursor, + ControlCharacter.PARAGRAPH_BREAK, false ); + // Position the cursor in the second paragraph + XParagraphCursor xParaCursor = UnoRuntime.queryInterface(XParagraphCursor.class, mxDocCursor ); + xParaCursor.gotoPreviousParagraph ( false ); + + // Get an XNameAccess interface to all auto text groups from the + // document factory + XNameAccess xContainer = UnoRuntime.queryInterface( + XNameAccess.class, mxFactory.createInstance ( + "com.sun.star.text.AutoTextContainer" ) ); + + // Create a new table at the document factory + XTextTable xTable = UnoRuntime.queryInterface( + XTextTable.class, mxDocFactory .createInstance( + "com.sun.star.text.TextTable" ) ); + + // Store the names of all auto text groups in an array of strings + String[] aGroupNames = xContainer.getElementNames(); + + // Make sure we have at least one group name + if ( aGroupNames.length > 0 ) + { + // initialise the table to have a row for every autotext group + // in a single column + one additional row for a header + xTable.initialize( aGroupNames.length+1,1); + + // Access the XPropertySet of the table + XPropertySet xTableProps = UnoRuntime.queryInterface( + XPropertySet.class, xTable ); + + // We want a visible background + xTableProps.setPropertyValue( "BackTransparent", + Boolean.FALSE); + + // We want the background to be light blue + xTableProps.setPropertyValue( "BackColor", Integer.valueOf(13421823)); + + // Inser the table into the document + mxDocText.insertTextContent( mxDocCursor, xTable, false); + + // Get an XIndexAccess to all table rows + XIndexAccess xRows = xTable.getRows(); + + // Get the first row in the table + XPropertySet xRow = UnoRuntime.queryInterface( + XPropertySet.class, xRows.getByIndex ( 0 ) ); + + // We want the background of the first row to be visible too + xRow.setPropertyValue( "BackTransparent", Boolean.FALSE); + + // And let's make it dark blue + xRow.setPropertyValue( "BackColor", Integer.valueOf(6710932)); + + // Put a description of the table contents into the first cell + insertIntoCell( "A1", "AutoText Groups", xTable); + + // Create a table cursor pointing at the second cell in the first + // column + XTextTableCursor xTableCursor = xTable.createCursorByCellName("A2"); + + // Loop over the group names + for ( int i = 0 ; i < aGroupNames.length ; i ++ ) + { + // Get the name of the current cell + String sCellName = xTableCursor.getRangeName (); + + // Get the XText interface of the current cell + XText xCellText = UnoRuntime.queryInterface ( + XText.class, xTable.getCellByName ( sCellName ) ); + + // Set the cell contents of the current cell to be + //the name of the of an autotext group + xCellText.setString ( aGroupNames[i] ); + + // Access the autotext group with this name + XAutoTextGroup xGroup = UnoRuntime.queryInterface (XAutoTextGroup.class, + xContainer.getByName(aGroupNames[i])); + + // Get the titles of each autotext block in this group + String [] aBlockNames = xGroup.getTitles(); + + // Make sure that the autotext group contains at least one block + if ( aBlockNames.length > 0 ) + { + // Split the current cell vertically into two separate cells + xTableCursor.splitRange ( (short) 1, false ); + + // Put the cursor in the newly created right hand cell + // and select it + xTableCursor.goRight ( (short) 1, false ); + + // Split this cell horizontally to make a separate cell + // for each Autotext block + if ( ( aBlockNames.length -1 ) > 0 ) + xTableCursor.splitRange ( + (short) (aBlockNames.length - 1), true ); + + // loop over the block names + for ( int j = 0 ; j < aBlockNames.length ; j ++ ) + { + // Get the XText interface of the current cell + xCellText = UnoRuntime.queryInterface ( + XText.class, xTable.getCellByName ( + xTableCursor.getRangeName() ) ); + + // Set the text contents of the current cell to the + // title of an Autotext block + xCellText.setString ( aBlockNames[j] ); + + // Move the cursor down one cell + xTableCursor.goDown( (short)1, false); + } + } + // Go back to the cell we originally split + xTableCursor.gotoCellByName ( sCellName, false ); + + // Go down one cell + xTableCursor.goDown( (short)1, false); + } + + XAutoTextGroup xGroup; + String [] aBlockNames; + + // Add a depth so that we only generate 200 numbers before giving up + // on finding a random autotext group that contains autotext blocks + int nDepth = 0; + do + { + // Generate a random, positive number which is lower than + // the number of autotext groups + int nRandom = Math.abs ( maRandom.nextInt() % + aGroupNames.length ); + + // Get the autotext group at this name + xGroup = UnoRuntime.queryInterface ( + XAutoTextGroup.class, xContainer.getByName ( + aGroupNames[ nRandom ] ) ); + + // Fill our string array with the names of all the blocks in + // this group + aBlockNames = xGroup.getElementNames(); + + // increment our depth counter + ++nDepth; + } + while ( nDepth < 200 && aBlockNames.length == 0 ); + // If we managed to find a group containing blocks... + if ( aBlockNames.length > 0 ) + { + // Pick a random block in this group and get its + // XAutoTextEntry interface + int nRandom = Math.abs ( maRandom.nextInt() + % aBlockNames.length ); + XAutoTextEntry xEntry = UnoRuntime.queryInterface ( + XAutoTextEntry.class, xGroup.getByName ( + aBlockNames[ nRandom ] ) ); + // insert the modified autotext block at the end of the document + xEntry.applyTo ( mxDocCursor ); + + // Get the titles of all text blocks in this AutoText group + String [] aBlockTitles = xGroup.getTitles(); + + // Get the XNamed interface of the autotext group + XNamed xGroupNamed = UnoRuntime.queryInterface ( + XNamed.class, xGroup ); + + // Output the short cut and title of the random block + //and the name of the group it's from + System.out.println ( "Inserted the Autotext '" + + aBlockTitles[nRandom] + + "', shortcut '" + aBlockNames[nRandom] + + "' from group '" + + xGroupNamed.getName()); + } + } + + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + // Insert new paragraph + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + + // Position cursor in new paragraph + xParaCursor.gotoPreviousParagraph ( false ); + + // Insert a string in the new paragraph + mxDocText.insertString ( mxDocCursor, + "Some text for a new autotext block", false ); + + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** This method demonstrates how to insert indexes and index marks + */ + protected void IndexExample () + { + try + { + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + // Insert a new paragraph and position the cursor in it + mxDocText.insertControlCharacter ( mxDocCursor, + ControlCharacter.PARAGRAPH_BREAK, false ); + XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor ); + xParaCursor.gotoPreviousParagraph ( false ); + + // Create a new ContentIndexMark and get its XPropertySet interface + XPropertySet xEntry = UnoRuntime.queryInterface( + XPropertySet.class, + mxDocFactory.createInstance("com.sun.star.text.ContentIndexMark")); + + // Set the text to be displayed in the index + xEntry.setPropertyValue( + "AlternativeText", "Big dogs! Falling on my head!"); + + // The Level property _must_ be set + xEntry.setPropertyValue ( "Level", Short.valueOf( (short) 1 ) ); + + // Create a ContentIndex and access its XPropertySet interface + XPropertySet xIndex = UnoRuntime.queryInterface( + XPropertySet.class, + mxDocFactory.createInstance ( "com.sun.star.text.ContentIndex" ) ); + + // Again, the Level property _must_ be set + xIndex.setPropertyValue ( "Level", Short.valueOf( (short) 10 ) ); + + // Access the XTextContent interfaces of both the Index and the + // IndexMark + XTextContent xIndexContent = UnoRuntime.queryInterface( + XTextContent.class, xIndex ); + XTextContent xEntryContent = UnoRuntime.queryInterface( + XTextContent.class, xEntry ); + + // Insert both in the document + mxDocText.insertTextContent ( mxDocCursor, xEntryContent, false ); + mxDocText.insertTextContent ( mxDocCursor, xIndexContent, false ); + + // Get the XDocumentIndex interface of the Index + XDocumentIndex xDocIndex = UnoRuntime.queryInterface( + XDocumentIndex.class, xIndex ); + + // And call its update method + xDocIndex.update(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** This method demonstrates how to create and insert reference marks, and + * GetReference Text Fields + */ + protected void ReferenceExample () + { + try + { + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + + // Insert a paragraph break + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + + // Get the Paragraph cursor + XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor ); + + // Move the cursor into the new paragraph + xParaCursor.gotoPreviousParagraph ( false ); + + // Create a new ReferenceMark and get its XNamed interface + XNamed xRefMark = UnoRuntime.queryInterface(XNamed.class, + mxDocFactory.createInstance ("com.sun.star.text.ReferenceMark")); + + // Set the name to TableHeader + xRefMark.setName ( "TableHeader" ); + + // Get the TextTablesSupplier interface of the document + XTextTablesSupplier xTableSupplier = UnoRuntime.queryInterface(XTextTablesSupplier.class, mxDoc); + + // Get an XIndexAccess of TextTables + XIndexAccess xTables = UnoRuntime.queryInterface( + XIndexAccess.class, xTableSupplier.getTextTables()); + + // We've only inserted one table, so get the first one from index zero + XTextTable xTable = UnoRuntime.queryInterface ( + XTextTable.class, xTables.getByIndex( 0 ) ); + + // Get the first cell from the table + XText xTableText = UnoRuntime.queryInterface( + XText.class, xTable.getCellByName ( "A1" ) ); + + // Get a text cursor for the first cell + XTextCursor xTableCursor = xTableText.createTextCursor(); + + // Get the XTextContent interface of the reference mark so we can + // insert it + XTextContent xContent = UnoRuntime.queryInterface ( + XTextContent.class, xRefMark ); + + // Insert the reference mark into the first cell of the table + xTableText.insertTextContent ( xTableCursor, xContent, false ); + + // Create a 'GetReference' text field to refer to the reference mark + // we just inserted, and get its XPropertySet interface + XPropertySet xFieldProps = UnoRuntime.queryInterface( + XPropertySet.class, mxDocFactory.createInstance ( + "com.sun.star.text.TextField.GetReference" ) ); + + // Get the XReferenceMarksSupplier interface of the document + XReferenceMarksSupplier xRefSupplier = UnoRuntime.queryInterface( XReferenceMarksSupplier.class, mxDoc ); + + // Get an XNameAccess which refers to all inserted reference marks + XNameAccess xMarks = UnoRuntime.queryInterface ( + XNameAccess.class, xRefSupplier.getReferenceMarks() ); + + // Put the names of each reference mark into an array of strings + String[] aNames = xMarks.getElementNames(); + + // Make sure that at least 1 reference mark actually exists + // (well, we just inserted one!) + if ( aNames.length > 0 ) + { + // Output the name of the first reference mark ('TableHeader') + System.out.println ( + "GetReference text field inserted for ReferenceMark : " + + aNames[0] ); + + // Set the SourceName of the GetReference text field to + // 'TableHeader' + xFieldProps.setPropertyValue ( "SourceName", aNames[0] ); + + // specify that the source is a reference mark (could also be a + // footnote, bookmark or sequence field ) + xFieldProps.setPropertyValue ( "ReferenceFieldSource", + Short.valueOf(ReferenceFieldSource.REFERENCE_MARK)); + + // We want the reference displayed as 'above' or 'below' + xFieldProps.setPropertyValue ( "ReferenceFieldPart", + Short.valueOf(ReferenceFieldPart.UP_DOWN)); + + + // Get the XTextContent interface of the GetReference text field + XTextContent xRefContent = UnoRuntime.queryInterface( + XTextContent.class, xFieldProps ); + + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + + // Make some text to precede the reference + mxDocText.insertString(mxDocText.getEnd(), "The table ", false); + + // Insert the text field + mxDocText.insertTextContent(mxDocText.getEnd(), xRefContent, false); + + // And some text after the reference... + mxDocText.insertString(mxDocText.getEnd(), + " contains the sum of some random numbers.", false ); + + // Refresh the document + XRefreshable xRefresh = UnoRuntime.queryInterface( + XRefreshable.class, mxDoc ); + xRefresh.refresh(); + } + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** This method demonstrates how to create and insert footnotes, and how to + access the XFootnotesSupplier interface of the document + */ + protected void FootnoteExample () + { + try + { + // Create a new footnote from the document factory and get its + // XFootnote interface + XFootnote xFootnote = UnoRuntime.queryInterface( + XFootnote.class, mxDocFactory.createInstance ( + "com.sun.star.text.Footnote" ) ); + + // Set the label to 'Numbers' + xFootnote.setLabel ( "Numbers" ); + + // Get the footnotes XTextContent interface so we can... + XTextContent xContent = UnoRuntime.queryInterface ( + XTextContent.class, xFootnote ); + + // ...insert it into the document + mxDocText.insertTextContent ( mxDocCursor, xContent, false ); + + // Get the XFootnotesSupplier interface of the document + XFootnotesSupplier xFootnoteSupplier = UnoRuntime.queryInterface(XFootnotesSupplier.class, mxDoc ); + + // Get an XIndexAccess interface to all footnotes + XIndexAccess xFootnotes = UnoRuntime.queryInterface ( + XIndexAccess.class, xFootnoteSupplier.getFootnotes() ); + + // Get the XFootnote interface to the first footnote inserted ('Numbers') + XFootnote xNumbers = UnoRuntime.queryInterface ( + XFootnote.class, xFootnotes.getByIndex( 0 ) ); + + // Get the XSimpleText interface to the Footnote + XSimpleText xSimple = UnoRuntime.queryInterface ( + XSimpleText.class, xNumbers ); + + // Create a text cursor for the foot note text + XTextRange xRange = UnoRuntime.queryInterface ( + XTextRange.class, xSimple.createTextCursor() ); + + // And insert the actual text of the footnote. + xSimple.insertString ( + xRange, " The numbers were generated by using java.util.Random", false ); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** This method demonstrates how to create and manipulate shapes, and how to + access the draw page of the document to insert shapes + */ + protected void DrawPageExample () + { + try + { + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + // Insert two new paragraphs + mxDocText.insertControlCharacter(mxDocCursor, + ControlCharacter.PARAGRAPH_BREAK, false); + mxDocText.insertControlCharacter(mxDocCursor, + ControlCharacter.PARAGRAPH_BREAK, false); + + // Get the XParagraphCursor interface of our document cursor + XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor ); + + // Position the cursor in the 2nd paragraph + xParaCursor.gotoPreviousParagraph ( false ); + + // Create a RectangleShape using the document factory + XShape xRect = UnoRuntime.queryInterface( + XShape.class, mxDocFactory.createInstance ( + "com.sun.star.drawing.RectangleShape" ) ); + + // Create an EllipseShape using the document factory + XShape xEllipse = UnoRuntime.queryInterface( + XShape.class, mxDocFactory.createInstance ( + "com.sun.star.drawing.EllipseShape" ) ); + + // Set the size of both the ellipse and the rectangle + Size aSize = new Size(); + aSize.Height = 4000; + aSize.Width = 10000; + xRect.setSize(aSize); + aSize.Height = 3000; + aSize.Width = 6000; + xEllipse.setSize ( aSize ); + + // Set the position of the Rectangle to the right of the ellipse + Point aPoint = new Point(); + aPoint.X = 6100; + aPoint.Y = 0; + xRect.setPosition ( aPoint ); + + // Get the XPropertySet interfaces of both shapes + XPropertySet xRectProps = UnoRuntime.queryInterface( + XPropertySet.class, xRect ); + XPropertySet xEllipseProps = UnoRuntime.queryInterface( + XPropertySet.class, xEllipse ); + + // And set the AnchorTypes of both shapes to 'AT_PARAGRAPH' + xRectProps.setPropertyValue ( "AnchorType", + TextContentAnchorType.AT_PARAGRAPH ); + xEllipseProps.setPropertyValue ( "AnchorType", + TextContentAnchorType.AT_PARAGRAPH ); + + // Access the XDrawPageSupplier interface of the document + XDrawPageSupplier xDrawPageSupplier = UnoRuntime.queryInterface (XDrawPageSupplier.class, mxDoc ); + + // Get the XShapes interface of the draw page + XShapes xShapes = UnoRuntime.queryInterface ( + XShapes.class, xDrawPageSupplier.getDrawPage () ); + + // Add both shapes + xShapes.add ( xEllipse ); + xShapes.add ( xRect ); + + /* + This doesn't work, I am assured that FME and AMA are fixing it. + + XShapes xGrouper = (XShapes) UnoRuntime.queryInterface( + XShapes.class, mxDocFactory.createInstance ( + "com.sun.star.drawing.GroupShape" ) ); + + XShape xGrouperShape = (XShape) UnoRuntime.queryInterface( + XShape.class, xGrouper ); + xShapes.add ( xGrouperShape ); + + xGrouper.add ( xRect ); + xGrouper.add ( xEllipse ); + + XShapeGrouper xShapeGrouper = (XShapeGrouper) + UnoRuntime.queryInterface(XShapeGrouper.class, xShapes); + xShapeGrouper.group ( xGrouper ); + */ + + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** This method demonstrates how to create, insert and apply styles + */ + protected void StylesExample () + { + try + { + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + + // Insert two paragraph breaks + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + + // Create a new style from the document's factory + XStyle xStyle = UnoRuntime.queryInterface( + XStyle.class, mxDocFactory.createInstance( + "com.sun.star.style.ParagraphStyle" ) ); + + // Access the XPropertySet interface of the new style + XPropertySet xStyleProps = UnoRuntime.queryInterface( + XPropertySet.class, xStyle ); + + // Give the new style a light blue background + xStyleProps.setPropertyValue ( "ParaBackColor", Integer.valueOf(13421823)); + + // Get the StyleFamiliesSupplier interface of the document + XStyleFamiliesSupplier xSupplier = UnoRuntime.queryInterface(XStyleFamiliesSupplier.class, mxDoc); + + // Use the StyleFamiliesSupplier interface to get the XNameAccess + // interface of the actual style families + XNameAccess xFamilies = UnoRuntime.queryInterface ( + XNameAccess.class, xSupplier.getStyleFamilies() ); + + // Access the 'ParagraphStyles' Family + XNameContainer xFamily = UnoRuntime.queryInterface ( + XNameContainer.class, + xFamilies.getByName ( "ParagraphStyles" ) ); + + // Insert the newly created style into the ParagraphStyles family + xFamily.insertByName ( "All-Singing All-Dancing Style", xStyle ); + + // Get the XParagraphCursor interface of the document cursor + XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor ); + + // Select the first paragraph inserted + xParaCursor.gotoPreviousParagraph ( false ); + xParaCursor.gotoPreviousParagraph ( true ); + + // Access the property set of the cursor selection + XPropertySet xCursorProps = UnoRuntime.queryInterface( + XPropertySet.class, mxDocCursor ); + + // Set the style of the cursor selection to our newly created style + xCursorProps.setPropertyValue ( "ParaStyleName", + "All-Singing All-Dancing Style" ); + + // Go back to the end + mxDocCursor.gotoEnd ( false ); + + // Select the last paragraph in the document + xParaCursor.gotoNextParagraph ( true ); + + // And reset its style to 'Standard' (the programmatic name for + // the default style) + xCursorProps.setPropertyValue ( "ParaStyleName", "Standard" ); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** This method demonstrates how to set numbering types and numbering levels + using the com.sun.star.text.NumberingRules service + */ + protected void NumberingExample () + { + try + { + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + // Get the RelativeTextContentInsert interface of the document + XRelativeTextContentInsert xRelative = + UnoRuntime.queryInterface ( + XRelativeTextContentInsert.class, mxDocText ); + + // Use the document's factory to create the NumberingRules service, + // and get its XIndexAccess interface + XIndexAccess xNum = UnoRuntime.queryInterface( + XIndexAccess.class, + mxDocFactory.createInstance( "com.sun.star.text.NumberingRules" ) ); + + // Also get the NumberingRule's XIndexReplace interface + XIndexReplace xReplace = UnoRuntime.queryInterface( + XIndexReplace.class, xNum ); + + // Create an array of XPropertySets, one for each of the three + // paragraphs we're about to create + XPropertySet xParas[] = new XPropertySet [ 3 ]; + for ( int i = 0 ; i < 3 ; ++ i ) + { + // Create a new paragraph + XTextContent xNewPara = UnoRuntime.queryInterface( + XTextContent.class, mxDocFactory.createInstance( + "com.sun.star.text.Paragraph" ) ); + + // Get the XPropertySet interface of the new paragraph and put + // it in our array + xParas[i] = UnoRuntime.queryInterface( + XPropertySet.class, xNewPara ); + + // Insert the new paragraph into the document after the fish + // section. As it is an insert relative to the fish section, the + // first paragraph inserted will be below the next two + xRelative.insertTextContentAfter ( xNewPara, mxFishSection ); + + // Separate from the above, but also needs to be done three times + + // Get the PropertyValue sequence for this numbering level + PropertyValue [] aProps = (PropertyValue [] ) xNum.getByIndex ( i ); + + // Iterate over the PropertyValue's for this numbering level, + // looking for the 'NumberingType' property + for ( int j = 0 ; j < aProps.length ; ++j ) + { + if ( aProps[j].Name.equals ( "NumberingType" ) ) + { + // Once we find it, set its value to a new type, + // dependent on which numbering level we're currently on + switch ( i ) + { + case 0 : aProps[j].Value = + Short.valueOf(NumberingType.ROMAN_UPPER); + break; + case 1 : aProps[j].Value = + Short.valueOf(NumberingType.CHARS_UPPER_LETTER); + break; + case 2 : aProps[j].Value = + Short.valueOf(NumberingType.ARABIC); + break; + } + // Put the updated PropertyValue sequence back into the + // NumberingRules service + xReplace.replaceByIndex ( i, aProps ); + break; + } + } + } + // Get the XParagraphCursor interface of our text cursor + XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor ); + // Go to the end of the document, then select the preceding paragraphs + mxDocCursor.gotoEnd ( false ); + xParaCursor.gotoPreviousParagraph ( false ); + xParaCursor.gotoPreviousParagraph ( true ); + xParaCursor.gotoPreviousParagraph ( true ); + + // Get the XPropertySet of the cursor's currently selected text + XPropertySet xCursorProps = UnoRuntime.queryInterface( + XPropertySet.class, mxDocCursor ); + + // Set the updated Numbering rules to the cursor's property set + xCursorProps.setPropertyValue ( "NumberingRules", xNum ); + mxDocCursor.gotoEnd( false ); + + // Set the first paragraph that was inserted to a numbering level of + // 2 (thus it will have Arabic style numbering) + xParas[0].setPropertyValue ( "NumberingLevel", Short.valueOf((short) 2)); + + // Set the second paragraph that was inserted to a numbering level of + // 1 (thus it will have 'Chars Upper Letter' style numbering) + xParas[1].setPropertyValue ( "NumberingLevel", Short.valueOf((short) 1)); + + // Set the third paragraph that was inserted to a numbering level of + // 0 (thus it will have 'Chars Upper Letter' style numbering) + xParas[2].setPropertyValue ( "NumberingLevel", Short.valueOf((short) 0)); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** This method demonstrates how to create linked and unlinked sections + */ + protected void TextSectionExample () + { + try + { + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + // Insert two paragraph breaks + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, true ); + + // Create a new TextSection from the document factory and access + // its XNamed interface + XNamed xChildNamed = UnoRuntime.queryInterface( + XNamed.class, mxDocFactory.createInstance( + "com.sun.star.text.TextSection" ) ); + // Set the new sections name to 'Child_Section' + xChildNamed.setName ( "Child_Section" ); + + // Access the Child_Section's XTextContent interface and insert it + // into the document + XTextContent xChildSection = UnoRuntime.queryInterface( + XTextContent.class, xChildNamed ); + mxDocText.insertTextContent ( mxDocCursor, xChildSection, false ); + + // Access the XParagraphCursor interface of our text cursor + XParagraphCursor xParaCursor = UnoRuntime.queryInterface(XParagraphCursor.class, mxDocCursor); + + // Go back one paragraph (into Child_Section) + xParaCursor.gotoPreviousParagraph ( false ); + + // Insert a string into the Child_Section + mxDocText.insertString ( mxDocCursor, "This is a test", false ); + + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + + // Go back two paragraphs + xParaCursor.gotoPreviousParagraph ( false ); + xParaCursor.gotoPreviousParagraph ( false ); + // Go to the end of the document, selecting the two paragraphs + mxDocCursor.gotoEnd ( true ); + + // Create another text section and access its XNamed interface + XNamed xParentNamed = UnoRuntime.queryInterface(XNamed.class, + mxDocFactory.createInstance("com.sun.star.text.TextSection")); + + // Set this text section's name to Parent_Section + xParentNamed.setName ( "Parent_Section" ); + + // Access the Parent_Section's XTextContent interface ... + XTextContent xParentSection = UnoRuntime.queryInterface( + XTextContent.class, xParentNamed ); + // ...and insert it into the document + mxDocText.insertTextContent ( mxDocCursor, xParentSection, false ); + + // Go to the end of the document + mxDocCursor.gotoEnd ( false ); + // Insert a new paragraph + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + // And select the new pargraph + xParaCursor.gotoPreviousParagraph ( true ); + + // Create a new Text Section and access its XNamed interface + XNamed xLinkNamed = UnoRuntime.queryInterface(XNamed.class, + mxDocFactory.createInstance("com.sun.star.text.TextSection")); + // Set the new text section's name to Linked_Section + xLinkNamed.setName ( "Linked_Section" ); + + // Access the Linked_Section's XTextContent interface + XTextContent xLinkedSection = UnoRuntime.queryInterface( + XTextContent.class, xLinkNamed ); + // And insert the Linked_Section into the document + mxDocText.insertTextContent ( mxDocCursor, xLinkedSection, false ); + + // Access the Linked_Section's XPropertySet interface + XPropertySet xLinkProps = UnoRuntime.queryInterface( + XPropertySet.class, xLinkNamed ); + // Set the linked section to be linked to the Child_Section + xLinkProps.setPropertyValue ( "LinkRegion", "Child_Section" ); + + // Access the XPropertySet interface of the Child_Section + XPropertySet xChildProps = UnoRuntime.queryInterface( + XPropertySet.class, xChildNamed ); + // Set the Child_Section's background colour to blue + xChildProps.setPropertyValue( "BackColor", Integer.valueOf(13421823)); + + // Refresh the document, so the linked section matches the Child_Section + XRefreshable xRefresh = UnoRuntime.queryInterface( + XRefreshable.class, mxDoc ); + xRefresh.refresh(); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** This method demonstrates the XTextColumns interface and how to insert a + blank paragraph using the XRelativeTextContentInsert interface + */ + protected void TextColumnsExample () + { + try + { + // Go to the end of the document + mxDocCursor.gotoEnd( false ); + // insert a new paragraph + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + + // insert the string 'I am a fish.' 100 times + for ( int i = 0 ; i < 100 ; ++i ) + { + mxDocText.insertString ( mxDocCursor, "I am a fish.", false ); + } + // insert a paragraph break after the text + mxDocText.insertControlCharacter ( + mxDocCursor, ControlCharacter.PARAGRAPH_BREAK, false ); + + // Get the XParagraphCursor interface of our text cursor + XParagraphCursor xParaCursor = UnoRuntime.queryInterface( XParagraphCursor.class, mxDocCursor ); + // Jump back before all the text we just inserted + xParaCursor.gotoPreviousParagraph ( false ); + xParaCursor.gotoPreviousParagraph ( false ); + + // Insert a string at the beginning of the block of text + mxDocText.insertString ( mxDocCursor, "Fish section begins:", false ); + + // Then select all of the text + xParaCursor.gotoNextParagraph ( true ); + xParaCursor.gotoNextParagraph ( true ); + + // Create a new text section and get its XNamed interface + XNamed xSectionNamed = UnoRuntime.queryInterface(XNamed.class, + mxDocFactory.createInstance("com.sun.star.text.TextSection")); + + // Set the name of our new section (appropriately) to 'Fish' + xSectionNamed.setName ( "Fish" ); + + // Create the TextColumns service and get its XTextColumns interface + XTextColumns xColumns = UnoRuntime.queryInterface( + XTextColumns.class, + mxDocFactory.createInstance ( "com.sun.star.text.TextColumns" ) ); + + // We want three columns + xColumns.setColumnCount ( (short) 3 ); + + // Get the TextColumns, and make the middle one narrow with a larger + // margin on the left than the right + TextColumn[] aSequence = xColumns.getColumns (); + aSequence[1].Width /= 2; + aSequence[1].LeftMargin = 350; + aSequence[1].RightMargin = 200; + // Set the updated TextColumns back to the XTextColumns + xColumns.setColumns ( aSequence ); + + // Get the property set interface of our 'Fish' section + XPropertySet xSectionProps = UnoRuntime.queryInterface( + XPropertySet.class, xSectionNamed ); + + // Set the columns to the Text Section + xSectionProps.setPropertyValue ( "TextColumns", xColumns ); + + // Get the XTextContent interface of our 'Fish' section + mxFishSection = UnoRuntime.queryInterface( + XTextContent.class, xSectionNamed ); + + // Insert the 'Fish' section over the currently selected text + mxDocText.insertTextContent ( mxDocCursor, mxFishSection, true ); + + // Get the wonderful XRelativeTextContentInsert interface + XRelativeTextContentInsert xRelative = UnoRuntime.queryInterface ( + XRelativeTextContentInsert.class, mxDocText ); + + // Create a new empty paragraph and get its XTextContent interface + XTextContent xNewPara = UnoRuntime.queryInterface( + XTextContent.class, + mxDocFactory.createInstance("com.sun.star.text.Paragraph")); + + // Insert the empty paragraph after the fish Text Section + xRelative.insertTextContentAfter ( xNewPara, mxFishSection ); + } + catch (Exception e) + { + e.printStackTrace(); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/Text/TextTemplateWithUserFields.odt b/odk/examples/DevelopersGuide/Text/TextTemplateWithUserFields.odt new file mode 100644 index 000000000..7c6814039 Binary files /dev/null and b/odk/examples/DevelopersGuide/Text/TextTemplateWithUserFields.odt differ diff --git a/odk/examples/DevelopersGuide/UCB/ChildrenRetriever.java b/odk/examples/DevelopersGuide/UCB/ChildrenRetriever.java new file mode 100644 index 000000000..102119dfc --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/ChildrenRetriever.java @@ -0,0 +1,338 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.ArrayList; +import java.util.StringTokenizer; + +import com.sun.star.beans.Property; +import com.sun.star.sdbc.XResultSet; +import com.sun.star.sdbc.XRow; +import com.sun.star.ucb.OpenCommandArgument2; +import com.sun.star.ucb.OpenMode; +import com.sun.star.ucb.XContent; +import com.sun.star.ucb.XContentAccess; +import com.sun.star.ucb.XDynamicResultSet; +import com.sun.star.uno.UnoRuntime; + +/** + * Retrieve the Children of a UCB Folder Content + */ +public class ChildrenRetriever { + + /** + * Member properties + */ + private Helper m_helper; + private XContent m_content; + private String m_contenturl = ""; + private ArrayList m_propnames = new ArrayList(); + + /** + * Constructor. Create a new connection with the specific args to a running office + * + *@param args This constructor requires the arguments: + * -url=... (optional) + * -propNames=... (optional) + * See Help (method printCmdLineUsage()). + * Without the arguments a new connection to a + * running office cannot created. + */ + public ChildrenRetriever( String args[] ) throws java.lang.Exception { + + // Parse arguments + parseArguments( args ); + + // Init + m_helper = new Helper( getContentURL() ); + + // Create UCB content + m_content = m_helper.createUCBContent(); + } + + /** + * Open a folder content, get properties values. + * This method requires the main and the optional arguments to be set in order to work. + * See Constructor. + * + *@return Returns children properties values if values successfully retrieved, + * null otherwise + */ + public ArrayList> getChildren() + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + ArrayList properties = getProperties(); + return getChildren ( properties ); + } + + /** + * Open a folder content, get properties values for the properties. + * + *@return Returns children properties values if values successfully retrieved, + * null otherwise + */ + public ArrayList> getChildren( ArrayList properties ) + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + + ArrayList> result = null; + if ( m_content != null ) { + int size = 0; + if ( properties != null && !properties.isEmpty()) { + size = properties.size(); + } + // Fill info for the properties wanted. + Property[] props = new Property[ size ]; + for ( int index = 0 ; index < size; index++ ) { + + // Define property sequence. + Property prop = new Property(); + prop.Name = properties.get( index ); + prop.Handle = -1; // n/a + props[ index ] = prop; + } + + // Fill argument structure... + OpenCommandArgument2 arg = new OpenCommandArgument2(); + arg.Mode = OpenMode.ALL; // FOLDER, DOCUMENTS -> simple filter + arg.Priority = 32768; // static final for 32768 + arg.Properties = props; + + XDynamicResultSet set; + + // Execute command "open". + set = UnoRuntime.queryInterface( + XDynamicResultSet.class, m_helper.executeCommand( m_content, "open", arg )); + XResultSet resultSet = set.getStaticResultSet(); + + result = new ArrayList>(); + + + // Iterate over children, access children and property values... + + + // Move to begin. + if ( resultSet.first() ) { + XContentAccess contentAccess = UnoRuntime.queryInterface( + XContentAccess.class, resultSet ); + XRow row = UnoRuntime.queryInterface( XRow.class, resultSet ); + + do { + ArrayList propsValues = new ArrayList(); + + // Obtain URL of child. + String id = contentAccess.queryContentIdentifierString(); + propsValues.add( id ); + for ( int i = 1; i <= size ; i++) { + Object propValue = row.getObject( i, null ); + if ( !row.wasNull() && !(propValue instanceof com.sun.star.uno.Any )) { + propsValues.add( propValue ); + } else { + propsValues.add( "[ Property not found ]" ); + } + } + result.add( propsValues ); + } while ( resultSet.next() ); // next child + } + } + return result; + } + + /** + * Get connect URL. + * + *@return String That contains the connect URL + */ + public String getContentURL() { + return m_contenturl; + } + + /** + * Get the properties. + * + *@return String That contains the properties + */ + public ArrayList getProperties() { + return m_propnames; + } + + /** + * Parse arguments + * + *@param args Arguments + */ + public void parseArguments( String[] args ) throws java.lang.Exception { + + for ( int i = 0; i < args.length; i++ ) { + if ( args[i].startsWith( "-url=" )) { + m_contenturl = args[i].substring( 5 ); + } else if ( args[i].startsWith( "-propNames=" )) { + StringTokenizer tok + = new StringTokenizer( args[i].substring( 11 ), ";" ); + + while ( tok.hasMoreTokens() ) + m_propnames.add( tok.nextToken() ); + + } else if ( args[i].startsWith( "-help" ) || + args[i].startsWith( "-?" )) { + printCmdLineUsage(); + System.exit( 0 ); + } + } + + if ( m_contenturl == null || m_contenturl.equals( "" )) { + m_contenturl = "file:///"; + } + + if ( m_propnames.size() == 0 ) { + m_propnames.add( "Title" ); + m_propnames.add( "IsDocument" ); + } + } + + /** + * Print the commands options + */ + public void printCmdLineUsage() { + System.out.println( + "Usage : ChildrenRetriever -url=... -propNames=..." ); + System.out.println( + "Defaults: -url=file:/// -propNames=Title,IsDocument" ); + System.out.println( + "\nExample : -url=file:///temp/ -propNames=Title;IsFolder;IsDocument" ); + } + + /** + * Print all properties out contained in vector . + */ + public void printLine( ArrayList props ) { + int limit; + while ( !props.isEmpty() ) { + String print = ""; + int size = props.size(); + for ( int i = 0; i < size; i++ ) { + limit = 15; + Object obj = props.get( i ); + if ( obj != null) { + String prop = obj.toString(); + int leng = prop.length(); + if ( leng < limit ) { + for ( int l = leng; l < limit; l++) { + prop += " "; + } + print+= prop + " "; + props.set( i, null ); + } else { + String temp1 = prop.substring( 0, limit ); + String temp2 = prop.substring( limit ); + print+= temp1 + " "; + props.set( i, temp2 ); + } + } else { + for ( int l = 0; l < limit; l++) { + print += " "; + } + print+= " "; + } + } + System.out.println( print ); + boolean isEmpty = true; + for ( int i = 0; i < size; i++ ) { + Object obj = props.get( i ); + if( obj != null ) + isEmpty = false; + } + if( isEmpty ) + props.clear(); + } + } + + /** + * Create a new connection with the specific args to a running office and + * access the children from a folder. + */ + public static void main ( String args[] ) { + + System.out.println( "\n" ); + System.out.println( + "-----------------------------------------------------------------" ); + System.out.println( + "ChildrenRetriever - obtains the children of a folder resource." ); + System.out.println( + "-----------------------------------------------------------------" ); + + try { + ChildrenRetriever access = new ChildrenRetriever( args ); + + // Get the properties Title and IsFolder for the children. + ArrayList> result = access.getChildren(); + + String tempPrint = "\nChildren of resource " + access.getContentURL(); + int size = tempPrint.length(); + System.out.println( tempPrint ); + tempPrint = ""; + for( int i = 0; i < size; i++ ) { + tempPrint += "-"; + } + System.out.println( tempPrint ); + + if ( result != null && !result.isEmpty() ) { + + ArrayList cont = new ArrayList(); + cont.add("URL:"); + ArrayList props = access.getProperties(); + size = props.size(); + for ( int i = 0; i < size; i++ ) { + Object obj = props.get( i ); + String prop = obj.toString(); + cont.add( prop + ":" ); + } + access.printLine(cont); + System.out.println( "\n" ); + for ( ArrayList propsV : result ) { + access.printLine( propsV ); + } + } + } catch ( com.sun.star.ucb.ResultSetException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.ucb.CommandAbortedException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.uno.Exception e ) { + System.out.println( "Error: " + e ); + } catch ( java.lang.Exception e ) { + System.out.println( "Error: " + e ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/DataStreamComposer.java b/odk/examples/DevelopersGuide/UCB/DataStreamComposer.java new file mode 100644 index 000000000..ce6edae31 --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/DataStreamComposer.java @@ -0,0 +1,246 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.ucb.InsertCommandArgument; +import com.sun.star.ucb.XContent; +import com.sun.star.io.XInputStream; + +/** + * Setting (Storing) the Content Data Stream of a UCB Document Content. + */ +public class DataStreamComposer { + + /** + * Member properties + */ + private Helper m_helper; + private XContent m_content; + private String m_contenturl = ""; + private String m_srcURL = ""; + + + /** + * Constructor. + * + *@param args This constructor requires the arguments: + * -url=... (optional) + * -srcURL=... (optional) + * -workdir=... (optional) + * See Help (method printCmdLineUsage()). + * Without the arguments a new connection to a + * running office cannot created. + */ + public DataStreamComposer( String args[] ) throws java.lang.Exception { + + // Parse arguments + parseArguments( args ); + + // Init + m_helper = new Helper( getContentURL() ); + + // Create UCB content + m_content = m_helper.createUCBContent(); + } + + /** + * Write the document data stream of a document content. + * This method requires the main and the optional arguments to be set in order to work. + * See Constructor. + * + *@return boolean Result + */ + public boolean setDataStream() + throws com.sun.star.ucb.CommandAbortedException, + com.sun.star.uno.Exception, + java.lang.Exception { + + String sourceURL = getSourceURL(); + return ( setDataStream( sourceURL )); + } + + /** + * Write the document data stream of a document content. + * + *@param sourceURL Source URL + *@return true if data stream successfully seted, false otherwise + */ + public boolean setDataStream( String sourceURL ) + throws com.sun.star.ucb.CommandAbortedException, + com.sun.star.uno.Exception, + java.lang.Exception { + + XInputStream stream; + if ( sourceURL == null || sourceURL.equals("") ) { + stream = new MyInputStream(); + } else { + String[] args = new String[ 1 ]; + args[ 0 ] = "-url=" + sourceURL; + DataStreamRetriever access = new DataStreamRetriever( args ); + stream = access.getDataStream(); + } + return ( setDataStream( stream )); + } + + /** + * Write the document data stream of a document content... + * + *@return boolean Returns true if data stream successfully seted, false otherwise + */ + public boolean setDataStream( XInputStream stream ) + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + + boolean result = false; + XInputStream data = stream; + if ( data != null && m_content != null ) { + + // Fill argument structure... + InsertCommandArgument arg = new InsertCommandArgument(); + arg.Data = data; + arg.ReplaceExisting = true; + + // Execute command "insert". + m_helper.executeCommand( m_content, "insert", arg ); + result = true; + } + return result; + } + + /** + * Get source URL. + * + *@return String That contains the source URL + */ + public String getSourceURL() { + return m_srcURL; + } + + /** + * Get connect URL. + * + *@return String That contains the connect URL + */ + public String getContentURL() { + return m_contenturl; + } + + /** + * Parse arguments + */ + public void parseArguments( String[] args ) throws java.lang.Exception { + + String workdir = ""; + + for ( int i = 0; i < args.length; i++ ) { + if ( args[i].startsWith( "-url=" )) { + m_contenturl = args[i].substring( 5 ); + } else if ( args[i].startsWith( "-srcURL=" )) { + m_srcURL = args[i].substring( 9 ); + } else if ( args[i].startsWith( "-workdir=" )) { + workdir = args[i].substring( 9 ); + } else if ( args[i].startsWith( "-help" ) || + args[i].startsWith( "-?" )) { + printCmdLineUsage(); + System.exit( 0 ); + } + } + + if ( m_contenturl == null || m_contenturl.equals( "" )) { + m_contenturl = Helper.createTargetDataFile( workdir ); + } + + if ( m_srcURL == null || m_srcURL.equals( "" )) { + m_srcURL = Helper.prependCurrentDirAsAbsoluteFileURL( "data/data.txt" ); + } + } + + /** + * Print the commands options + */ + public void printCmdLineUsage() { + System.out.println( + "Usage : DataStreamComposer -url=... -srcURL=... -workdir=..." ); + System.out.println( + "Defaults: -url=/resource- -srcURL=/data/data.txt -workdir=" ); + System.out.println( + "\nExample : -url=file:///temp/my.txt -srcURL=file:///temp/src.txt " ); + } + + + /** + * Create a new connection with the specific args to a running office and + * set the Content Data Stream of a UCB Document Content. + */ + public static void main ( String args[] ) { + System.out.println( "\n" ); + System.out.println( + "-----------------------------------------------------------------" ); + System.out.println( + "DataStreamComposer - sets the data stream of a document resource." ); + System.out.println( + " The data stream is obtained from another (the source) document " ); + System.out.println( + " resource before." ); + System.out.println( + "-----------------------------------------------------------------" ); + try { + + DataStreamComposer dataStream = new DataStreamComposer( args ); + String sourceURL = dataStream.getSourceURL(); + boolean result = dataStream.setDataStream( sourceURL ); + if ( result ) { + System.out.println( + "\nSetting data stream succeeded.\n Source URL: " + + dataStream.getSourceURL() + + "\n Target URL: " + + dataStream.getContentURL() ); + } else { + System.out.println( + "\nSetting data stream failed. \n Source URL: " + + dataStream.getSourceURL() + + "\n Target URL: " + + dataStream.getContentURL() ); + } + } catch ( com.sun.star.ucb.CommandAbortedException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.uno.Exception e ) { + System.out.println( "Error: " + e ); + } catch ( java.lang.Exception e ) { + System.out.println( "Error: " + e ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/DataStreamRetriever.java b/odk/examples/DevelopersGuide/UCB/DataStreamRetriever.java new file mode 100644 index 000000000..5644af0c2 --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/DataStreamRetriever.java @@ -0,0 +1,227 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.ucb.OpenCommandArgument2; +import com.sun.star.ucb.OpenMode; +import com.sun.star.ucb.XContent; +import com.sun.star.io.XActiveDataSink; +import com.sun.star.io.XInputStream; + +/** + * Accessing (Loading) the Content Data Stream of a UCB Document Content + */ +public class DataStreamRetriever { + + /** + * Member properties + */ + private Helper m_helper; + private XContent m_content; + private String m_contenturl = ""; + + /** + * Constructor. + * + *@param args This constructor requires the arguments: + * -url=... (optional) + * See Help (method printCmdLineUsage()). + * Without the arguments a new connection to a + * running office cannot created. + */ + public DataStreamRetriever( String args[] ) throws java.lang.Exception { + + // Parse arguments + parseArguments( args ); + + // Init + m_helper = new Helper( getContentURL() ); + + // Create UCB content + m_content = m_helper.createUCBContent(); + } + + /** + * Read the document data stream of a document content using a + * XActiveDataSink implementation as data sink... + * + *@return XInputStream Returns input stream if stream successfully retrieved, + * null otherwise + */ + public XInputStream getDataStream() + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + + XInputStream data = null; + if ( m_content != null ) { + + // Fill argument structure... + OpenCommandArgument2 arg = new OpenCommandArgument2(); + arg.Mode = OpenMode.DOCUMENT; + arg.Priority = 32768; // static final for 32768 + + // Create data sink implementation object. + XActiveDataSink dataSink = new MyActiveDataSink(); + arg.Sink = dataSink; + + // Execute command "open". The implementation of the command will + // supply an XInputStream implementation to the data sink. + m_helper.executeCommand( m_content, "open", arg ); + + // Get input stream supplied by the open command implementation. + data = dataSink.getInputStream(); + } + return data; + } + + /** + * Get connect URL. + * + *@return String That contains the connect URL + */ + public String getContentURL() { + return m_contenturl; + } + + /** + * Parse arguments + * + *@param args Arguments + */ + private void parseArguments( String[] args ) throws java.lang.Exception { + + for ( int i = 0; i < args.length; i++ ) { + if ( args[i].startsWith( "-url=" )) { + m_contenturl = args[i].substring( 5 ); + } else if ( args[i].startsWith( "-help" ) || + args[i].startsWith( "-?" )) { + printCmdLineUsage(); + System.exit( 0 ); + } + } + + if ( m_contenturl == null || m_contenturl.equals( "" )) { + m_contenturl = Helper.prependCurrentDirAsAbsoluteFileURL( "data/data.txt" ); + } + } + + /** + * Print the commands options + */ + private void printCmdLineUsage() { + System.out.println( + "Usage : DataStreamRetriever -url=..." ); + System.out.println( + "Defaults: -url=/data/data.txt" ); + System.out.println( + "\nExample : -url=file:///temp/my.txt" ); + } + + /** + * Print Stream content. + */ + private void printStream( XInputStream data ) + throws com.sun.star.uno.Exception { + + + // Read data from input stream...65536 + + + // Data buffer. Will be allocated by input stream implementation! + byte[][] buffer = new byte[ 1 ][ 65536 ]; + int read = data.readSomeBytes( buffer, 65536 ); + System.out.println( "Read bytes : " + read ); + System.out.println( "Read data (only first 64K displayed): "); + while ( read > 0 ) { + byte[] bytes = new byte[ read ]; + for( int i = 0; i < read; i++ ) { + bytes[ i ] = buffer[ 0 ][ i ]; + } + System.out.println( new String(bytes) ); + + // Process data contained in buffer. + read = data.readSomeBytes( buffer, 65536 ); + } + } + + /** + * Create a new connection with the specific args to a running office and + * access (Load) the content data stream of a UCB document content. + */ + public static void main ( String args[] ) { + System.out.println( "\n" ); + System.out.println( + "-----------------------------------------------------------------------" ); + System.out.println( + "DataStreamRetriever - obtains the data stream from a document resource." ); + System.out.println( + "-----------------------------------------------------------------------" ); + + try { + + DataStreamRetriever access = new DataStreamRetriever( args ); + XInputStream data = access.getDataStream(); + String url = access.getContentURL(); + if ( data != null ) { + String tempPrint = "\nGetting data stream for resource " + url + + " succeeded."; + int size = tempPrint.length(); + System.out.println( tempPrint ); + tempPrint = ""; + for( int i = 0; i < size; i++ ) { + tempPrint += "-"; + } + System.out.println( tempPrint ); + access.printStream( data ); + } else { + System.out.println( + "Getting data stream for resource " + url + " failed." ); + } + } catch ( com.sun.star.io.NotConnectedException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.io.BufferSizeExceededException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.io.IOException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.ucb.CommandAbortedException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.uno.Exception e ) { + System.out.println( "Error: " + e ); + } catch ( java.lang.Exception e ) { + System.out.println( "Error: " + e ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/Helper.java b/odk/examples/DevelopersGuide/UCB/Helper.java new file mode 100644 index 000000000..846f942dd --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/Helper.java @@ -0,0 +1,242 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.io.File; +import java.io.FileOutputStream; + +import com.sun.star.ucb.Command; +import com.sun.star.ucb.UniversalContentBroker; +import com.sun.star.ucb.XContent; +import com.sun.star.ucb.XContentProvider; +import com.sun.star.ucb.XContentIdentifier; +import com.sun.star.ucb.XContentIdentifierFactory; +import com.sun.star.ucb.XCommandProcessor; + +import com.sun.star.uno.XInterface; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + + +/** + * Helper for creating a new connection with the specific args to a running office. + */ +public class Helper { + + /** + * Member properties + */ + private XInterface m_ucb = null; + private String m_contenturl = null; + private static XComponentContext m_xContext = null; + + /** + * Constructor, create a new instance of the ucb. UNO is bootstrapped and + * the remote office service manager is used to create the ucb. If necessary + * a new office process is started. + */ + public Helper(String url) throws java.lang.Exception { + m_contenturl = url; + + if (null == m_xContext ) { + // get the remote office component context + m_xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + } + + m_ucb = UnoRuntime.queryInterface( + XInterface.class, UniversalContentBroker.create(m_xContext)); + } + + /** + * Returns created identifier object for given URL... + * + *@return XContent Created identifier object for given URL + */ + public XContent createUCBContent() throws java.lang.Exception { + return createUCBContent( getContentURL() ); + } + + /** + * Returned created identifier object for given URL. + * + *@param connectURL Connect URL. Example : -url=file:/// + *@return Created identifier object for given URL + */ + private XContent createUCBContent( String connectURL ) throws java.lang.Exception { + XContent content = null; + if ( connectURL != null && !connectURL.equals( "" )) { + + // Obtain required UCB interfaces... + XContentIdentifierFactory idFactory + = UnoRuntime.queryInterface( + XContentIdentifierFactory.class, m_ucb ); + XContentProvider provider + = UnoRuntime.queryInterface( + XContentProvider.class, m_ucb ); + + // Create identifier object for given URL. + XContentIdentifier id = idFactory.createContentIdentifier( connectURL ); + content = provider.queryContent( id ); + } + return content; + } + + /** + * Get ucb instance. + * + *@return XInterface That contains the ucb instance + */ + public XInterface getUCB() { + return m_ucb; + } + + /** + * Get connect URL. + * + *@return String That contains the connect URL + */ + public String getContentURL() { + return m_contenturl; + } + + /** + * Executes a command. + * + *param XInterface + *param String + *param Object + *@return Object The result according to the specification of the command. + *@exception com.sun.star.ucb.CommandAbortedException + *@exception com.sun.star.uno.Exception + */ + Object executeCommand( XInterface ifc, String commandName, Object argument ) + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + + + // Obtain command processor interface from given content. + + + XCommandProcessor cmdProcessor + = UnoRuntime.queryInterface( + XCommandProcessor.class, ifc ); + + + // Assemble command to execute. + + + Command command = new Command(); + command.Name = commandName; + command.Handle = -1; // not available + command.Argument = argument; + + // Note: throws CommandAbortedException, Exception + return cmdProcessor.execute( command, 0, null ); + } + + public static String getAbsoluteFileURLFromSystemPath( String systemPath ) + { + try + { + File file = new File( systemPath ); + String url = file.toURI().toURL().toString(); + if ( url.charAt( 6 ) != '/' ) { // file:/xxx vs. file:///xxxx + StringBuffer buf1 = new StringBuffer( "file:///" ); + buf1.append( url.substring( 6 ) ); + url = buf1.toString(); + } + return url; + } + catch ( java.net.MalformedURLException e ) + { + e.printStackTrace(); + } + return ""; + } + + public static String prependCurrentDirAsAbsoluteFileURL( String relativeURL ) + { + // get url of current dir. + String url = getAbsoluteFileURLFromSystemPath( "" ); + StringBuffer buf = new StringBuffer( url ); + if ( !url.endsWith( File.separator ) ) + buf.append( File.separator ); + buf.append( relativeURL ); + return buf.toString(); + } + + public static String createTargetDataFile( String workDir ) + { + try + { + StringBuffer buf = new StringBuffer(); + if ( workDir != null && workDir.length() > 0 ) { + buf.append( workDir ); + buf.append( File.separator ); + } + buf.append( "resource-" ); + buf.append( System.currentTimeMillis() ); + File file = new File( buf.toString() ); + String url = file.toURI().toURL().toString(); + if ( url.charAt( 6 ) != '/' ) { // file:/xxx vs. file:///xxxx + StringBuffer buf1 = new StringBuffer( "file:///" ); + buf1.append( url.substring( 6 ) ); + url = buf1.toString(); + } + + try + { + file.createNewFile(); + String content = "This is the content of a sample data file."; + FileOutputStream stream = new FileOutputStream( file ); + stream.write( content.getBytes() ); + stream.close(); + } + catch ( java.io.IOException e ) + { + e.printStackTrace(); + } + + return url; + } + catch ( java.net.MalformedURLException e ) + { + e.printStackTrace(); + } + + return ""; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/Makefile b/odk/examples/DevelopersGuide/UCB/Makefile new file mode 100644 index 000000000..22dd94bad --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/Makefile @@ -0,0 +1,155 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** +# Builds the UCB examples of the Developers Guide. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=UCBExamples +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) +OUT_APP_MISC = $(OUT_MISC)/$(EXAMPLE_NAME) + +APP1_NAME=ChildrenRetriever +APP1_JAR=$(OUT_APP_CLASS)/$(APP1_NAME).jar +APP2_NAME=DataStreamComposer +APP2_JAR=$(OUT_APP_CLASS)/$(APP2_NAME).jar +APP3_NAME=DataStreamRetriever +APP3_JAR=$(OUT_APP_CLASS)/$(APP3_NAME).jar +APP4_NAME=PropertiesComposer +APP4_JAR=$(OUT_APP_CLASS)/$(APP4_NAME).jar +APP5_NAME=PropertiesRetriever +APP5_JAR=$(OUT_APP_CLASS)/$(APP5_NAME).jar +APP6_NAME=ResourceCreator +APP6_JAR=$(OUT_APP_CLASS)/$(APP6_NAME).jar +APP7_NAME=ResourceManager +APP7_JAR=$(OUT_APP_CLASS)/$(APP7_NAME).jar +APP8_NAME=ResourceRemover +APP8_JAR=$(OUT_APP_CLASS)/$(APP8_NAME).jar + +APP_JAVAFILES = \ + Helper.java \ + MyActiveDataSink.java \ + MyInputStream.java + +APP_CLASSFILES = $(patsubst %.java,$(OUT_APP_CLASS)/%.class,$(APP_JAVAFILES)) +APP_CLASSNAMES = $(patsubst %.java,%.class,$(APP_JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +# Targets +.PHONY: ALL +ALL : \ + UCBExamples + +include $(SETTINGS)/stdtarget.mk + +$(APP_CLASSFILES) : $(APP_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $(APP_JAVAFILES) + +$(OUT_APP_CLASS)/%.class : %.java $(APP_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(OUT_APP_CLASS)/$(APP2_NAME).class : $(APP2_NAME).java $(OUT_APP_CLASS)/DataStreamRetriever.class $(APP_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(OUT_APP_CLASS)/$(APP6_NAME).class : $(APP6_NAME).java $(OUT_APP_CLASS)/DataStreamRetriever.class $(APP_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(OUT_APP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(OUT_APP_CLASS)/%.jar : $(OUT_APP_CLASS)/%.mf $(OUT_APP_CLASS)/%.class $(APP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class $(APP_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP2_JAR) : $(OUT_APP_CLASS)/$(APP2_NAME).mf $(OUT_APP_CLASS)/$(APP2_NAME).class $(OUT_APP_CLASS)/DataStreamRetriever.class $(APP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(basename $(@F)).class DataStreamRetriever.class $(APP_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP6_JAR) : $(OUT_APP_CLASS)/$(APP6_NAME).mf $(OUT_APP_CLASS)/$(APP6_NAME).class $(OUT_APP_CLASS)/DataStreamRetriever.class $(APP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(basename $(@F)).mf $(basename $(@F)).class DataStreamRetriever.class $(APP_CLASSNAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(OUT_APP_CLASS)/$(APP1_NAME).class +$(APP2_JAR) : $(OUT_APP_CLASS)/$(APP2_NAME).mf $(OUT_APP_CLASS)/$(APP2_NAME).class +$(APP3_JAR) : $(OUT_APP_CLASS)/$(APP3_NAME).mf $(OUT_APP_CLASS)/$(APP3_NAME).class +$(APP4_JAR) : $(OUT_APP_CLASS)/$(APP4_NAME).mf $(OUT_APP_CLASS)/$(APP4_NAME).class +$(APP5_JAR) : $(OUT_APP_CLASS)/$(APP5_NAME).mf $(OUT_APP_CLASS)/$(APP5_NAME).class +$(APP6_JAR) : $(OUT_APP_CLASS)/$(APP6_NAME).mf $(OUT_APP_CLASS)/$(APP6_NAME).class +$(APP7_JAR) : $(OUT_APP_CLASS)/$(APP7_NAME).mf $(OUT_APP_CLASS)/$(APP7_NAME).class +$(APP8_JAR) : $(OUT_APP_CLASS)/$(APP8_NAME).mf $(OUT_APP_CLASS)/$(APP8_NAME).class + +UCBExamples : $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) $(APP4_JAR) $(APP5_JAR) $(APP6_JAR) $(APP7_JAR) $(APP8_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP2_NAME).run + @echo $(MAKE) $(APP3_NAME).run + @echo $(MAKE) $(APP4_NAME).run + @echo $(MAKE) $(APP5_NAME).run + @echo $(MAKE) $(APP6_NAME).run + @echo $(MAKE) $(APP7_NAME).run + @echo $(MAKE) $(APP8_NAME).run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + -$(MKDIR) $(subst /,$(PS),$(OUT_APP_MISC)) + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< -workdir=$(OUT_APP_MISC) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/DevelopersGuide/UCB/MyActiveDataSink.java b/odk/examples/DevelopersGuide/UCB/MyActiveDataSink.java new file mode 100644 index 000000000..fcfadc7e4 --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/MyActiveDataSink.java @@ -0,0 +1,74 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.io.XActiveDataSink; +import com.sun.star.io.XInputStream; + +/** + * XActiveDataSink interface implementation. Makes it possible to read + * the corresponding object from an input stream. + */ +public class MyActiveDataSink implements XActiveDataSink { + + /** + * Member properties + */ + private XInputStream m_aStream = null; + + /** + * Constructor + */ + public MyActiveDataSink() { + super(); + } + + /** + * Plugs the input stream. + */ + public void setInputStream( XInputStream aStream ) { + m_aStream = aStream; + } + + /** + * Get the plugged stream. + * + *@return XInputStream The plugged stream + */ + public XInputStream getInputStream() { + return m_aStream; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/MyInputStream.java b/odk/examples/DevelopersGuide/UCB/MyInputStream.java new file mode 100644 index 000000000..048f2950c --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/MyInputStream.java @@ -0,0 +1,180 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.io.BufferSizeExceededException; +import com.sun.star.io.NotConnectedException; +import com.sun.star.io.XInputStream; +import com.sun.star.io.XSeekable; + +/** + * XInputStream interface implementation. + */ +public class MyInputStream implements XSeekable, XInputStream { + + /** + * Member properties + */ + private int offset = 0; + private int read = offset; + private byte[] bigbuffer; + + /** + * Constructor + */ + public MyInputStream() { + } + + // XSeekable. Makes it possible to seek to a certain position within a stream. + + /** + * Returns the length of the stream. + * + *@return long The length of the storage medium on which the stream works. + */ + public synchronized long getLength() + throws com.sun.star.io.IOException,com.sun.star.uno.RuntimeException { + if ( bigbuffer != null ) { + return bigbuffer.length - offset; + } else { + return 0; + } + } + + /** + * Returns the current offset of the stream. + * + *@return long The current offset in this stream. + */ + public synchronized long getPosition() + throws com.sun.star.io.IOException,com.sun.star.uno.RuntimeException { + return read - offset ; + } + + /** + * Changes the seek pointer to a new location relative to the beginning of the stream. + */ + public synchronized void seek(long p0) + throws IllegalArgumentException, com.sun.star.io.IOException, + com.sun.star.uno.RuntimeException { + if( bigbuffer != null ) { + p0 +=offset; + read = ( int ) p0; + if( read < offset || read > bigbuffer.length ) + throw new IllegalArgumentException(); + } + } + + // XInputStream. This is the basic interface to read data from a stream. + + /** + * States how many bytes can be read or skipped without blocking. + * + *@return int If not available, then returned 0 + */ + public synchronized int available() + throws NotConnectedException, com.sun.star.io.IOException, + com.sun.star.uno.RuntimeException { + if( bigbuffer != null ) + return ( bigbuffer.length - read ); + else + return 0; + } + + /** + * Closes the stream. . + */ + public void closeInput() + throws NotConnectedException,com.sun.star.io.IOException, + com.sun.star.uno.RuntimeException { + read = -1; + } + + /** + * Reads the specified number of bytes in the given sequence. + */ + public synchronized int readBytes(byte[][] p0, int p1) + throws NotConnectedException, BufferSizeExceededException, + com.sun.star.io.IOException, com.sun.star.uno.RuntimeException { + if( bigbuffer != null ) { + if( read == -1 ) + return 0; + int i = 0; + int available; + if ( p1 > bigbuffer.length - read ) + available = bigbuffer.length - read; + else + available = p1; + + p0[0] = new byte[p1]; + while( available != 0 ) { + p0[0][i++] = bigbuffer[read++]; + --available; + } + return i; + } else { + p0[0] = new byte[0]; + return 0; + } + } + + /** + * Reads the available number of bytes at maximum nMaxBytesToRead . + * This method blocks the thread until at least one byte is available. + */ + public synchronized int readSomeBytes(byte[][] p0, int p1) + throws NotConnectedException, + BufferSizeExceededException, + com.sun.star.io.IOException, + com.sun.star.uno.RuntimeException { + return readBytes( p0,p1 ); + } + + /** + * Skips the next nBytesToSkip bytes (must be positive). + * It is up to the implementation whether this method is blocking the thread or not. + */ + public synchronized void skipBytes(int p0) + throws NotConnectedException, BufferSizeExceededException, + com.sun.star.io.IOException, com.sun.star.uno.RuntimeException { + read += p0; + if( read > bigbuffer.length ) + read = bigbuffer.length; + + if( read < offset ) + read = offset; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/PropertiesComposer.java b/odk/examples/DevelopersGuide/UCB/PropertiesComposer.java new file mode 100644 index 000000000..1ebc9cbaa --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/PropertiesComposer.java @@ -0,0 +1,289 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.ArrayList; +import java.util.StringTokenizer; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.ucb.XContent; + +/** + * Setting Property Values of a UCB Content + */ +public class PropertiesComposer { + + /** + * Member properties + */ + private Helper m_helper; + private XContent m_content; + private String m_contenturl = ""; + private ArrayList m_propNames = new ArrayList(); + private ArrayList m_propValues = new ArrayList(); + + /** + * Constructor. + * + *@param args This constructor requires the arguments: + * -url=... (optional) + * -propNames=... (optional) + * -propValues=... (optional) + * -workdir=... (optional) + * See Help (method printCmdLineUsage()). + * Without the arguments a new connection to a + * running office cannot created. + */ + public PropertiesComposer( String args[] ) throws java.lang.Exception { + + // Parse arguments + parseArguments( args ); + + // Init + m_helper = new Helper( getContentURL() ); + + // Create UCB content + m_content = m_helper.createUCBContent(); + } + + /** + * Set values of the properties. + * This method requires the main and the optional arguments to be set in order to work. + * See Constructor. + * + *@return Object[] Returns null or instance object of com.sun.star.uno.Any + * if values successfully seted, properties otherwise + */ + public Object[] setProperties() + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + ArrayList properties = getProperties(); + ArrayList propertyValues = getPropertyValues(); + return setProperties( properties, propertyValues ); + } + + /** + * Set values of the properties. + * + *@return Object[] Returns null or instance object of com.sun.star.uno.Any + * if values successfully seted, properties otherwise + */ + public Object[] setProperties( ArrayList properties, ArrayList propertiesValues ) + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + + Object[] result = null; + if ( m_content != null && !properties.isEmpty() && + !propertiesValues.isEmpty() && + properties.size() == propertiesValues.size() ) { + + /* + **** This code is for unregistered properties. **** + + XPropertyContainer xPropContainer + = (XPropertyContainer)UnoRuntime.queryInterface( + XPropertyContainer.class, m_content ); + + XPropertySetInfo xPropSetInfo = ( XPropertySetInfo )UnoRuntime.queryInterface( + XPropertySetInfo.class, + m_helper.executeCommand( m_content, "getPropertySetInfo", null )); + */ + + int size = properties.size(); + PropertyValue[] props = new PropertyValue[ size ]; + for ( int index = 0 ; index < size; index++ ) { + String propName = properties.get( index ); + Object propValue = propertiesValues.get( index ); + + /* + **** This code is for unregistered properties. **** + + if ( !xPropSetInfo.hasPropertyByName( propName )) { + xPropContainer.addProperty( + propName, PropertyAttribute.MAYBEVOID, propValue ); + } + */ + + // Define property sequence. + PropertyValue prop = new PropertyValue(); + prop.Name = propName; + prop.Handle = -1; // n/a + prop.Value = propValue; + props[ index ] = prop; + } + + // Execute command "setPropertiesValues". + Object[] obj = + ( Object[] )m_helper.executeCommand( m_content, "setPropertyValues", props ); + if ( obj.length == size ) + result = obj; + } + return result; + } + + /** + * Get properties names. + * + *@return Vector That contains the properties names + */ + public ArrayList getProperties() { + return m_propNames; + } + + /** + * Get properties values. + * + *@return Vector That contains the properties values + */ + public ArrayList getPropertyValues() { + return m_propValues; + } + + /** + * Get connect URL. + * + *@return String That contains the connect URL + */ + public String getContentURL() { + return m_contenturl; + } + + /** + * Parse arguments + */ + public void parseArguments( String[] args ) throws java.lang.Exception { + + String workdir = ""; + + for ( int i = 0; i < args.length; i++ ) { + if ( args[i].startsWith( "-url=" )) { + m_contenturl = args[i].substring( 5 ); + } else if ( args[i].startsWith( "-propNames=" )) { + StringTokenizer tok + = new StringTokenizer( args[i].substring( 11 ), ";" ); + + while ( tok.hasMoreTokens() ) + m_propNames.add( tok.nextToken() ); + + } else if ( args[i].startsWith( "-propValues=" )) { + StringTokenizer tok + = new StringTokenizer( args[i].substring( 12 ), ";" ); + + while ( tok.hasMoreTokens() ) + m_propValues.add( tok.nextToken() ); + } else if ( args[i].startsWith( "-workdir=" )) { + workdir = args[i].substring( 9 ); + } else if ( args[i].startsWith( "-help" ) || + args[i].startsWith( "-?" )) { + printCmdLineUsage(); + System.exit( 0 ); + } + } + + if ( m_contenturl == null || m_contenturl.equals( "" )) { + m_contenturl = Helper.createTargetDataFile( workdir ); + } + + if ( m_propNames.size() == 0 ) { + m_propNames.add( "Title" ); + } + + if ( m_propValues.size() == 0 ) { + m_propValues.add( + "changed-" + m_contenturl.substring( + m_contenturl.lastIndexOf( "/" ) + 1 ) ); + } + } + + /** + * Print the commands options + */ + public void printCmdLineUsage() { + System.out.println( + "Usage : PropertiesComposer -url=... -propNames=... -propValues=... -workdir=..." ); + System.out.println( + "Defaults: -url=/resource- -propNames=Title -propValues=changed- -workdir=" ); + System.out.println( + "\nExample : -propNames=Title;Foo -propValues=MyRenamedFile.txt;bar" ); + } + + /** + * Create a new connection with the specific args to a running office and + * set properties of a resource. + */ + public static void main ( String args[] ) { + System.out.println( "\n" ); + System.out.println( + "--------------------------------------------------------" ); + System.out.println( + "PropertiesComposer - sets property values of a resource." ); + System.out.println( + "--------------------------------------------------------" ); + + try { + + PropertiesComposer setProp = new PropertiesComposer( args ); + ArrayList properties = setProp.getProperties(); + ArrayList propertiesValues = setProp.getPropertyValues(); + Object[] result = setProp.setProperties( properties, propertiesValues ); + + String tempPrint = "\nSetting properties of resource " + setProp.getContentURL(); + int size = tempPrint.length(); + System.out.println( tempPrint ); + tempPrint = ""; + for( int i = 0; i < size; i++ ) { + tempPrint += "-"; + } + System.out.println( tempPrint ); + if ( result != null ) { + for ( int index = 0; index < result.length; index++ ) { + Object obj = result[ index ]; + if( obj == null || obj instanceof com.sun.star.uno.Any ) + System.out.println( + "Setting property " + properties.get( index ) + " succeeded." ); + else + System.out.println( + "Setting property " + properties.get( index ) + " failed." ); + } + } + } catch ( com.sun.star.ucb.CommandAbortedException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.uno.Exception e ) { + System.out.println( "Error: " + e ); + } catch ( java.lang.Exception e ) { + System.out.println( "Error: " + e ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/PropertiesRetriever.java b/odk/examples/DevelopersGuide/UCB/PropertiesRetriever.java new file mode 100644 index 000000000..641b1de86 --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/PropertiesRetriever.java @@ -0,0 +1,245 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.ArrayList; +import java.util.StringTokenizer; + +import com.sun.star.beans.Property; +import com.sun.star.sdbc.XRow; +import com.sun.star.ucb.XContent; +import com.sun.star.uno.UnoRuntime; + + +/** + * Obtaining Property Values from a UCB Content + */ +public class PropertiesRetriever { + + /** + * Member properties + */ + private Helper m_helper; + private XContent m_content; + private String m_contenturl = ""; + private ArrayList m_propNames = new ArrayList(); + + /** + * Constructor. + * + *@param args This constructor requires the arguments: + * -url=... (optional) + * -propNames=... (optional) + * See Help (method printCmdLineUsage()). + * Without the arguments a new connection to a + * running office cannot created. + */ + public PropertiesRetriever( String args[] ) throws java.lang.Exception { + + // Parse arguments + parseArguments( args ); + + // Init + m_helper = new Helper( getContentURL() ); + + // Create UCB content + m_content = m_helper.createUCBContent(); + } + + /** + * Get values of the properties. + * This method requires the main and the optional arguments to be set in order to work. + * See Constructor. + * + *@return Properties values if values successfully retrieved, null otherwise + */ + public ArrayList getPropertyValues() + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + ArrayList properties = getProperties(); + return getPropertyValues ( properties ); + } + + /** + * Get values of the properties. + * + *@return Properties values if values successfully retrieved, null otherwise + */ + public ArrayList getPropertyValues( ArrayList properties ) + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + ArrayList m_propValues = null; + if ( m_content != null && properties != null && !properties.isEmpty() ) { + + int size = properties.size(); + + // Fill info for the properties wanted. + Property[] props = new Property[ size ]; + for ( int index = 0 ; index < size; index++ ) { + + // Define property sequence. + Property prop = new Property(); + prop.Name = properties.get( index ); + prop.Handle = -1; // n/a + props[ index ] = prop; + } + + // Execute command "getPropertyValues". + XRow values = + UnoRuntime.queryInterface( + XRow.class, m_helper.executeCommand( m_content,"getPropertyValues", props )); + + m_propValues = new ArrayList(); + + /* + Extract values from row object. Note that the + first column is 1, not 0. + Title: Obtain value of column 1 as string.*/ + for ( int index = 1 ; index <= size; index++ ) { + Object propertyValue = values.getObject( index, null ); + if ( !values.wasNull() && !(propertyValue instanceof com.sun.star.uno.Any )) + m_propValues.add( propertyValue ); + else + m_propValues.add( "[ Property not found ]" ); + } + } + return m_propValues; + } + + /** + * Get connect URL. + * + *@return String That contains the connect URL + */ + public String getContentURL() { + return m_contenturl; + } + + /** + * Get the properties. + * + *@return Vector That contains the properties + */ + public ArrayList getProperties() { + return m_propNames; + } + + /** + * Parse arguments + */ + public void parseArguments( String[] args ) throws java.lang.Exception { + + for ( int i = 0; i < args.length; i++ ) { + if ( args[i].startsWith( "-url=" )) { + m_contenturl = args[i].substring( 5 ); + } else if ( args[i].startsWith( "-propNames=" )) { + StringTokenizer tok + = new StringTokenizer( args[i].substring( 11 ), ";" ); + + while ( tok.hasMoreTokens() ) + m_propNames.add( tok.nextToken() ); + + } else if ( args[i].startsWith( "-help" ) || + args[i].startsWith( "-?" )) { + printCmdLineUsage(); + System.exit( 0 ); + } + } + + if ( m_contenturl == null || m_contenturl.equals( "" )) { + m_contenturl = Helper.prependCurrentDirAsAbsoluteFileURL( "data/data.txt" ); + } + + if ( m_propNames.size() == 0 ) { + m_propNames.add( "Title" ); + m_propNames.add( "IsDocument" ); + } + } + + /** + * Print the commands options + */ + public void printCmdLineUsage() { + System.out.println( + "Usage : PropertiesRetriever -url=... -propNames=..." ); + System.out.println( + "Defaults: -url=/data/data.txt -propNames=Title;IsDocument" ); + System.out.println( + "\nExample : -propNames=Title;IsFolder" ); + } + + /** + * Create a new connection with the specific args to a running office and + * get the properties values from a resource. + */ + public static void main ( String args[] ) { + System.out.println( "\n" ); + System.out.println( + "--------------------------------------------------------------" ); + System.out.println( + "PropertiesRetriever - obtains property values from a resource." ); + System.out.println( + "--------------------------------------------------------------" ); + try { + PropertiesRetriever obtProperty = new PropertiesRetriever( args ); + ArrayList properties = obtProperty.getProperties(); + ArrayList propertiesValues = obtProperty.getPropertyValues( properties ); + + String tempPrint = "\nProperties of resource " + obtProperty.getContentURL(); + int size = tempPrint.length(); + System.out.println( tempPrint ); + tempPrint = ""; + for( int i = 0; i < size; i++ ) { + tempPrint += "-"; + } + System.out.println( tempPrint ); + + if ( properties != null && propertiesValues != null ) { + size = properties.size(); + for (int index = 0; index < size ; index++ ) { + String property = properties.get( index ); + Object propValue = propertiesValues.get( index ); + System.out.println( property + " : " + propValue ); + } + } + } catch ( com.sun.star.ucb.CommandAbortedException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.uno.Exception e ) { + System.out.println( "Error: " + e ); + } catch ( java.lang.Exception e ) { + System.out.println( "Error: " + e ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/ResourceCreator.java b/odk/examples/DevelopersGuide/UCB/ResourceCreator.java new file mode 100644 index 000000000..0f7e2f200 --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/ResourceCreator.java @@ -0,0 +1,304 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.beans.PropertyValue; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.ucb.ContentInfo; +import com.sun.star.ucb.InsertCommandArgument; +import com.sun.star.ucb.XContent; +import com.sun.star.io.XInputStream; + + +/** + * Creating a New Resource + */ +public class ResourceCreator { + + /** + * Member properties + */ + private Helper m_helper; + private XContent m_content; + private String m_contenturl = ""; + private String m_name = ""; + private String m_srcURL = ""; + + /** + * Constructor. + * + *@param args This constructor requires the arguments: + * -url=... (optional) + * -name=... (optional) + * -srcURL=... (optional) + * -workdir=... (optional) + * See Help (method printCmdLineUsage()). + * Without the arguments a new connection to a + * running office cannot created. + */ + public ResourceCreator( String args[] ) throws java.lang.Exception { + + // Parse arguments + parseArguments( args ); + String url = getContentURL(); + + // Init + m_helper = new Helper( url ); + if ( url.startsWith( "file:///" )) { + + // Create UCB content + m_content = m_helper.createUCBContent(); + } else { + throw new Exception( + "Create new resource : parameter 'url' must contain a File URL " + + "pointing to the file system folder in which the new resource " + + "shall be created. (Example: file:///tmp/)" ); + } + } + + /** + * Create a new resource. + * This method requires the main and the optional arguments to be set in order to work. + * See Constructor. + * + *@return boolean Returns true if resource successfully created, false otherwise + */ + public boolean createNewResource() + throws com.sun.star.ucb.CommandAbortedException, + com.sun.star.uno.Exception, + java.lang.Exception { + + String sourceURL = getSourceURL(); + String name = getName(); + return createNewResource( sourceURL, name ); + } + + /** + * Create a new resource. + * + *@param sourceURL Source resource URL + *@param name New resource name + *@return true if resource successfully created, false otherwise + */ + public boolean createNewResource( String sourceURL, String name ) + throws com.sun.star.ucb.CommandAbortedException, + com.sun.star.uno.Exception, + java.lang.Exception { + + XInputStream stream = null; + if ( sourceURL == null || sourceURL.equals( "" )) { + stream = new MyInputStream(); + } else { + String[] args = new String[ 1 ]; + args[ 0 ] = "-url=" + sourceURL; + DataStreamRetriever access = new DataStreamRetriever( args ); + stream = access.getDataStream(); + } + return createNewResource( stream, name ); + } + + /** + * Create a new resource. + * + *@param stream Source resource stream + *@param name New resource name + *@return true if resource successfully created, false otherwise + */ + public boolean createNewResource( XInputStream stream, String name ) + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + + boolean result = false; + if ( stream != null && name != null && !name.equals( "" )) { + + // Note: The data for info may have been obtained from + // property CreatableContentsInfo. + ContentInfo info = new ContentInfo(); + info.Type = "application/vnd.sun.staroffice.fsys-file"; + info.Attributes = 0; + + // Create new, empty content (execute command "createNewContent"). + XContent newContent = UnoRuntime.queryInterface( + XContent.class, + m_helper.executeCommand( m_content, "createNewContent", info ) ); + + if ( newContent != null ) { + + + // Set mandatory properties... + + + // Define property value sequence. + PropertyValue[] props = new PropertyValue[ 1 ]; + PropertyValue prop = new PropertyValue(); + prop.Name = "Title"; + prop.Handle = -1; // n/a + prop.Value = name; + props[ 0 ] = prop; + + // Execute command "setPropertyValues". + m_helper.executeCommand( newContent, "setPropertyValues", props ); + + + // Write the new file to disk... + + + // Obtain document data for the new file. + XInputStream data = stream; + + // Fill argument structure... + InsertCommandArgument arg = new InsertCommandArgument(); + arg.Data = data; + arg.ReplaceExisting = false; + + // Execute command "insert". + m_helper.executeCommand( newContent, "insert", arg ); + result = true; + } + } + return result; + } + + /** + * Get new resource name. + * + *@return String That contains the name + */ + public String getName() { + return m_name; + } + + /** + * Get source URL. + * + *@return String That contains the source URL + */ + public String getSourceURL() { + return m_srcURL; + } + + /** + * Get connect URL. + * + *@return String That contains the connect URL + */ + public String getContentURL() { + return m_contenturl; + } + + /** + * Parse arguments + */ + public void parseArguments( String[] args ) throws java.lang.Exception { + + String workdir = ""; + + for ( int i = 0; i < args.length; i++ ) { + if ( args[i].startsWith( "-url=" )) { + m_contenturl = args[i].substring( 5 ); + } else if ( args[i].startsWith( "-name=" )) { + m_name = args[i].substring( 6 ); + } else if ( args[i].startsWith( "-srcURL=" )) { + m_srcURL = args[i].substring( 8 ); + } else if ( args[i].startsWith( "-workdir=" )) { + workdir = args[i].substring( 9 ); + } else if ( args[i].startsWith( "-help" ) || + args[i].startsWith( "-?" )) { + printCmdLineUsage(); + System.exit( 0 ); + } + } + + if ( m_contenturl == null || m_contenturl.equals( "" )) { + m_contenturl = Helper.getAbsoluteFileURLFromSystemPath( workdir ); + } + + if ( m_name == null || m_name.equals( "" )) { + m_name = "created-resource-" + System.currentTimeMillis(); + } + + if ( m_srcURL == null || m_srcURL.equals( "" )) { + m_srcURL = Helper.prependCurrentDirAsAbsoluteFileURL( "data/data.txt" ); + } + } + + /** + * Print the commands options + */ + public void printCmdLineUsage() { + System.out.println( + "Usage : ResourceCreator -url=... -name=... -srcURL=... -workdir=..." ); + System.out.println( + "Defaults: -url= -name=created-resource- -srcURL=/data/data.txt> -workdir=" ); + System.out.println( + "\nExample : -url=file:///home/kai/ -name=newfile.txt -srcURL=file:///home/kai/sourcefile.txt" ); + } + + /** + * Create a new connection with the specific args to a running office and + * create a new resource. + */ + public static void main ( String args[] ) { + System.out.println( "\n" ); + System.out.println( + "-----------------------------------------------------------------------" ); + System.out.println( + "ResourceCreator - creates a new file in an existing file system folder." ); + System.out.println( + " (Content for the new file can be retrieved from another file)." ); + System.out.println( + "-----------------------------------------------------------------------" ); + try { + ResourceCreator create = new ResourceCreator( args ); + boolean result = create.createNewResource(); + if ( result ) { + System.out.println( + "Creation of new resource " + create.getName() + " in folder: " + + create.getContentURL() + " succeeded." ); + } else { + System.out.println( + "Creation of new resource " + create.getName() + " in folder: " + + create.getContentURL() + " failed." ); + } + } catch ( com.sun.star.ucb.CommandAbortedException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.uno.Exception e ) { + System.out.println( "Error: " + e ); + } catch ( java.lang.Exception e ) { + System.out.println( "Error: " + e ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/ResourceManager.java b/odk/examples/DevelopersGuide/UCB/ResourceManager.java new file mode 100644 index 000000000..6eb10d87b --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/ResourceManager.java @@ -0,0 +1,280 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.ucb.NameClash; +import com.sun.star.ucb.TransferCommandOperation; +import com.sun.star.ucb.GlobalTransferCommandArgument; +import com.sun.star.uno.XInterface; + +/** + * Copying, Moving and Creating Links to a Resource + */ +public class ResourceManager { + + /** + * Member properties + */ + private Helper m_helper; + private XInterface m_ucb; + private String m_contenturl = ""; + private String m_targetFolderURL = ""; + private String m_newTitle = ""; + private String m_transOperation = ""; + + /** + * Constructor. + * + *@param args This constructor requires the arguments: + * -url=... (optional) + * -targetFolderURL=... (optional) + * -newTitle=... (optional) + * -transOper=... (optional) + * -workdir=... (optional) + * See Help (method printCmdLineUsage()). + * Without the arguments a new connection to a + * running office cannot created. + */ + public ResourceManager( String args[] ) throws java.lang.Exception { + + // Parse arguments + parseArguments( args ); + + // Init + m_helper = new Helper( getContentURL() ); + + // Get xUCB + m_ucb = m_helper.getUCB(); + } + + /** + * Copy, move or create a link for a resource. + * This method requires the main and the optional arguments to be set in order to work. + * See Constructor. + * + *@return true if resource successfully transferred, false otherwise + */ + public boolean transferResource() + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + String sourceURL = getContentURL(); // URL of the source object + String targetFolderURL = getTargetFolderURL(); // URL of the target folder + String newTitle = getNewTitle(); // New name for the resource + String transOperation = getTransOperation(); + return transferResource( sourceURL, targetFolderURL, newTitle, transOperation ); + } + + /** + * Copy, move or create a link for a resource. + * + *@param sourceURL Source URL + *@param targetFolderURL Target folder URL + *@param transOperation Transferring operation (copy, move, link) + *@return true if resource successfully transferred, false otherwise + */ + public boolean transferResource( + String sourceURL, String targetFolderURL, + String newTitle, String transOperation ) + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + + boolean result = false; + if ( m_ucb != null && sourceURL != null && !sourceURL.equals( "" ) && + targetFolderURL != null && !targetFolderURL.equals( "" ) && + newTitle != null && transOperation != null && !transOperation.equals( "" ) && + ( transOperation.equals( "copy" ) || transOperation.equals( "move" ) || + transOperation.equals( "link" ))) { + + + // Copy, move or create a link for a resource to another location... + + GlobalTransferCommandArgument arg = new GlobalTransferCommandArgument(); + if ( transOperation.equals( "copy" )) { + arg.Operation = TransferCommandOperation.COPY; + } else if ( transOperation.equals( "move" )) { + arg.Operation = TransferCommandOperation.MOVE; + } else if ( transOperation.equals( "link" )) { + arg.Operation = TransferCommandOperation.LINK; + } + arg.SourceURL = sourceURL; + arg.TargetURL = targetFolderURL; + + // object get a new unique name + arg.NewTitle = newTitle; + + // fail, if object with same name exists in target folder + arg.NameClash = NameClash.ERROR; + + // Let UCB execute the command "globalTransfer". + m_helper.executeCommand( m_ucb, "globalTransfer", arg ); + result = true; + } + return result; + } + + /** + * Get connect URL. + * + *@return String That contains the connect URL + */ + public String getContentURL() { + return m_contenturl; + } + + /** + * Get trasfering Operation. + * + *@return String That contains the trasfering Operation + */ + public String getTransOperation() { + return m_transOperation; + } + + /** + * Get target folder URL. + * + *@return String That contains the target folder URL + */ + public String getTargetFolderURL() { + return m_targetFolderURL; + } + + /** + * Get new title for the resource to be transferred. + * + *@return String That contains a new title for the transferred + * resource. Can be empty. In this case resource + * will keep the title it has in the source folder. + */ + public String getNewTitle() { + return m_newTitle; + } + + /** + * Parse arguments + */ + public void parseArguments( String[] args ) throws java.lang.Exception { + + String workdir = ""; + + for ( int i = 0; i < args.length; i++ ) { + if ( args[i].startsWith( "-url=" )) { + m_contenturl = args[i].substring( 5 ); + } else if ( args[i].startsWith( "-targetFolderURL=" )) { + m_targetFolderURL = args[i].substring( 17 ); + } else if ( args[i].startsWith( "-newTitle=" )) { + m_newTitle = args[i].substring( 10 ); + } else if ( args[i].startsWith( "-transOper=" )) { + m_transOperation = args[i].substring( 11 ); + } else if ( args[i].startsWith( "-workdir=" )) { + workdir = args[i].substring( 9 ); + } else if ( args[i].startsWith( "-help" ) || + args[i].startsWith( "-?" )) { + printCmdLineUsage(); + System.exit( 0 ); + } + } + + if ( m_contenturl == null || m_contenturl.equals( "" )) { + m_contenturl = Helper.prependCurrentDirAsAbsoluteFileURL( "data/data.txt" ); + } + + if ( m_targetFolderURL == null || m_targetFolderURL.equals( "" )) { + m_targetFolderURL = Helper.getAbsoluteFileURLFromSystemPath( workdir ); + } + + if ( m_newTitle == null || m_newTitle.equals( "" )) { + m_newTitle = "transferred-resource-" + System.currentTimeMillis(); + } + + if ( m_transOperation == null || m_transOperation.equals( "" )) { + m_transOperation = "copy"; + } + } + + /** + * Print the commands options + */ + public void printCmdLineUsage() { + System.out.println( + "Usage: ResourceManager -url=... -targetFolderURL=... -newTitle=... -transOper=... -workdir=..." ); + System.out.println( + "Defaults: -url=/data/data.txt> -targetFolderURL= -newTitle=transferred-resource- -transOper=copy -workdir="); + System.out.println( + "\nExample : -url=file:///temp/MyFile.txt -targetFolderURL=file:///test/ -newTitle=RenamedFile.txt -transOper=copy " ); + } + + /** + * Create a new connection with the specific args to a running office and + * copy, move or create links a resource. + */ + public static void main ( String args[] ) { + + System.out.println( "\n" ); + System.out.println( + "-----------------------------------------------------------------" ); + System.out.println( + "ResourceManager - copies/moves a resource." ); + System.out.println( + "-----------------------------------------------------------------" ); + + try { + ResourceManager transResource = new ResourceManager( args ); + String sourceURL = transResource.getContentURL(); + String targetFolderURL = transResource.getTargetFolderURL(); + String newTitle = transResource.getNewTitle(); + String transOperation = transResource.getTransOperation(); + boolean result = transResource.transferResource( + sourceURL, targetFolderURL, newTitle, transOperation ); + if ( result ) + System.out.println( "\nTransferring resource succeeded." ); + else + System.out.println( "Transferring resource failed." ); + + System.out.println( " Source URL : " + sourceURL ); + System.out.println( " Target Folder URL : " + targetFolderURL ); + System.out.println( " New name : " + newTitle ); + System.out.println( " Transfer Operation: " + transOperation ); + + + } catch ( com.sun.star.ucb.CommandAbortedException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.uno.Exception e ) { + System.out.println( "Error: " + e ); + } catch ( java.lang.Exception e ) { + System.out.println( "Error: " + e ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/ResourceRemover.java b/odk/examples/DevelopersGuide/UCB/ResourceRemover.java new file mode 100644 index 000000000..e6ac8fc1c --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/ResourceRemover.java @@ -0,0 +1,175 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +/** + * Deleting a resource + */ +public class ResourceRemover { + + /** + * Member properties + */ + private Helper m_helper; + private String m_contenturl = ""; + private com.sun.star.ucb.XContent m_content; + + /** + * Constructor. + * + *@param args This constructor requires the arguments: + * -url=... (optional) + * -workdir=... (optional) + * See Help (method printCmdLineUsage()). + * Without the arguments a new connection to a + * running office cannot created. + */ + public ResourceRemover( String args[] ) throws java.lang.Exception { + + // Parse arguments + parseArguments( args ); + + // Init + m_helper = new Helper( getContentURL() ); + + // Create UCB content + m_content = m_helper.createUCBContent(); + } + + /** + * Delete resource. + * + *@return true if resource successfully deleted, false otherwise + */ + public boolean deleteResource() + throws com.sun.star.ucb.CommandAbortedException, com.sun.star.uno.Exception { + + boolean result = false; + if ( m_content != null ) { + + + // Destroy a resource physically... + + + Boolean deletePhysically = Boolean.TRUE; + + // Execute command "delete". + m_helper.executeCommand( m_content, "delete", deletePhysically ); + result = true; + } + return result; + } + + /** + * Get connect URL. + * + *@return String That contains the connect URL + */ + public String getContentURL() { + return m_contenturl; + } + + /** + * Parse arguments + */ + public void parseArguments( String[] args ) throws java.lang.Exception { + + String workdir = ""; + + for ( int i = 0; i < args.length; i++ ) { + if ( args[i].startsWith( "-url=" )) { + m_contenturl = args[i].substring( 5 ); + } else if ( args[i].startsWith( "-workdir=" )) { + workdir = args[i].substring( 9 ); + } else if ( args[i].startsWith( "-help" ) || + args[i].startsWith( "-?" )) { + printCmdLineUsage(); + System.exit( 0 ); + } + } + + if ( m_contenturl == null || m_contenturl.equals( "" )) { + m_contenturl = Helper.createTargetDataFile( workdir ); + } + } + + /** + * Print the commands options + */ + public void printCmdLineUsage() { + System.out.println( + "Usage : ResourceRemover -url=... -workdir=..." ); + System.out.println( + "Defaults: -url=/resource- -workdir=" ); + System.out.println( + "\nExample : -url=file:///temp/MyFile.txt \n" ); + } + + /** + * Create a new connection with the specific args to a running office and + * delete a resource. + */ + public static void main ( String args[] ) { + + System.out.println( "\n" ); + System.out.println( + "-----------------------------------------------------------------" ); + System.out.println( + "ResourceRemover - destroys a resource." ); + System.out.println( + "-----------------------------------------------------------------" ); + + try { + ResourceRemover delete = new ResourceRemover( args ); + boolean result = delete.deleteResource(); + String url = delete.getContentURL(); + if ( result ) { + System.out.println( + "Delete of resource " + url + " succeeded." ); + } else { + System.out.println( + "Delete of resource " + url + " failed." ); + } + } catch ( com.sun.star.ucb.CommandAbortedException e ) { + System.out.println( "Error: " + e ); + } catch ( com.sun.star.uno.Exception e ) { + System.out.println( "Error: " + e ); + } catch ( java.lang.Exception e ) { + System.out.println( "Error: " + e ); + } + System.exit( 0 ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/DevelopersGuide/UCB/data/data.txt b/odk/examples/DevelopersGuide/UCB/data/data.txt new file mode 100644 index 000000000..dd47db97d --- /dev/null +++ b/odk/examples/DevelopersGuide/UCB/data/data.txt @@ -0,0 +1 @@ +sample sample sample sample sample sample sample sample EOF \ No newline at end of file diff --git a/odk/examples/DevelopersGuide/examples.html b/odk/examples/DevelopersGuide/examples.html new file mode 100644 index 000000000..252366025 --- /dev/null +++ b/odk/examples/DevelopersGuide/examples.html @@ -0,0 +1,2880 @@ + + + + + LibreOffice %PRODUCT_RELEASE% SDK - Developer's Guide Examples + + + + + +
+
+
+ +

+ Software Development Kit %PRODUCT_RELEASE% +

+
+
+
+
+
+

+ Developer's Guide Examples +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + +
+ + + + + + + + + +
+

The Developer's Guide +comes with a wide range of examples from all application areas which +shows the use of the API in the context of the different functional +areas. Furthermore the examples can be used as a first starting point +to modify an existing example to their own needs.

+

Some of the examples need a running office +instance listening on a port. If this is necessary you will get further +information in the makefiles.

+

All examples marked with a are executable and be started +using a run target in the makefile. The name of the binary (C++) can +differ compared to the source file, please see the run target in the +appropriate makefile. Some of the examples which create a component +have no run target. In these cases a document is provided which +instantiates and runs the component (see the makefile output). Also the +Basic examples provide documents which use and shows the implemented +functionality. The database and forms examples need a running database, +please see the description below. But note that is not described in +detail how to create a working data source (see the office help).

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
First StepsProfessional UNOWriting UNO components
Office DevelopmentText +DocumentsSpreadsheet Documents
Drawing and +Presentation DocumentsChartsLibreOffice %PRODUCT_RELEASE% Basic and +Dialogs
Database AccessFormsUniversal +Content Broker (UCB)
Configuration ManagementOffice Bean
Scripting FrameworkGraphical User Interfaces
+
+
+ + + + + + + + + +
+ + + + + + + +
FirstSteps +examples
+
+ + + + + + + + + + + + + + + + + + + +
Text Document ExamplesDescription
FirstUnoContactShows how to initialize UNO and +get a remote office service manager from a running LibreOffice %PRODUCT_RELEASE% in a +different process space.
FirstLoadComponentDemonstrates how to load a +component into LibreOffice %PRODUCT_RELEASE% by a Java application.
HelloTextTableShapePerforms some generic text and +shape operations on a text document, a spreadsheet document and a +drawing document.
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + +
Professional UNO examples1
+
+ + + + + + + + + + + + + + + +
Lifetime ExamplesDescription
MyUnoObjectShows that it depends on the +implementation of the Java VM whether finalize() will be called or not.
object_lifetime.cxx +(ProfUnoLifetime)Shows the UNO reference counting +mechanism in C++.
+
+ + + + + + + + + + + + + + + +
Interprocess Connection ExampleDescription
ConnectionAwareClientImplements a client which is aware +of losing connection to LibreOffice %PRODUCT_RELEASE%.
UrlResolverBuilds a connection to +LibreOffice %PRODUCT_RELEASE% using the URL given on the command line. This example +shows the usage of XUnoUrlResolver.
+
+ + + + + + + + + + + + + + + +
C++ Binding ExamplesDescription
office_connect.cxxBuilds a connection to +LibreOffice %PRODUCT_RELEASE% using C++.
string_samples.cxxDemonstrates usage of RTL string +classes OString, + OUString +and OUStringBuffer.
+
+ + + + + + + + + + + + + + + +
SimpleBootstrap Java ExampleDescription
SimpleBootstrap_java.javaShows the transparent use of +office UNO components from Java. The remote office component context is +obtained by using the com.sun.star.comp.helper.Bootstrap.bootstrap() +method, which bootstraps the component context from a UNO installation.
manifest.mfContains the additional manifest +file entries.
+
+ + + + + + + + + + + +
SimpleBootstrap C++ ExampleDescription
SimpleBootstrap_cpp.cxxShows the transparent use of +office UNO components from C++. The remote office component context is +obtained by using the ::cppu::bootstrap() function, which +bootstraps the component context from a UNO installation.
+
+ + + + + + + + + + + +
Deployment FeaturesDescription
description.xmlDemonstrates how license files can be embedded, so that they are shown to the user during installation.
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + +
Writing +UNO components examples
+
+ + + + + + + + + + + + + + + + + + + +
Jobs Addon ExampleDescription
AsyncJobAn java example showing how a job +can analyze the given arguments and how the environment can be +detected, in which the job is executed.
Jobs.xcuContains the example job +configuration.
Addons.xcuContains the configuration entries +for the Jobs addon where different entries are configured.
+
+ + + + + + + + + + + + + + + + + + + +
ProtocolHandler Addon JavaDescription
ProtocolHandlerAddonImplements a ProtocolHandler addon +component in Java.
ProtocolHandler.xcuContains the ProtocolHandler +configuration.
Addons.xcuContains the configuration entries +for the ProtocolHandler addon where different entries are configured.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
ProtocolHandler Addon C++Description
addon.cxxImplements a ProtocolHandler addon +component in C++.
addon.hxxContains the class definition of +the c++ ProtocolHandler example.
component.cxxImplements the administrative +component functions (component_writeInfo, component_getFactory, component_getImplementationEnvironment).
ProtocolHandler.xcuContains the ProtocolHandler +configuration.
Addons.xcuContains the configuration entries +for the ProtocolHandler addon where different entries are configured.
+
+ + + + + + + + + + + + + + + + + + + + + + + +
Java Component ExampleDescription
TestJavaComponentDemonstrates how to extend the +service provider with a new factory and instantiates the example +components.
TestComponentAShows a simple demo component +which implements XTypeProvider, + + XServiceInfo and an own interface XSomethingA.
TestComponentBShows a simple demo component +which implements + XTypeProvider, XServiceInfo +and an own interface XSomethingB.
TestServiceProviderImplements a factory (service +provider) which can create the two test components.
+
+ + + + + + + + + + + + + + + + + + + +
C++ Component ExampleDescription
TestCppComponent.cxxShows how to create new instances +of the demo services and calls some methods of the demo interface.
service1_impl.cxxImplements a simple UNO service +with an own interface in C++.
service2_impl.cxxImplements another simple UNO +service in C++.
+
+ + + + + + + + + + + + + + + +
Thumbs ExampleDescription
ImageShrinkContains a framework for a +component which scales images in a directory and stores them to another +directory. This code does not really do anything, it just contains the +framework.
ThumbsThis example registers a factory +for the image shrink component and instantiates it.
+
+ + + + + + + + + + + + + + + + + + + + + + + +
Dialog Component ExampleDescription
DialogComponent.javaImplements a component accessing a dialog created + with the LibreOffice %PRODUCT_RELEASE% Basic IDE. The component provides methods that + can be bound to dialog respectively control events .
XTestDialogHandler.idlInterface implementing a createDialog method showing the + dialog and some methods to be used as event handler for the dialog. +
TestDialogHandler.idl + Service definition for the component implementing + its own interface XTestDialogHandler. +
DialogComponent.odtDocument containing Basic code to + instantiate the Dialog Components and a Dialog containing + controls with events bound to methods supported by the + Dialog Component.
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + +
Office Development examples
+
+ + + + + + + + + + + + + + + + + + + +
Ascii Filter ExampleDescription
AsciiReplaceFilterImplements an example for an +import/export filter service.
FilterOptionsOffers some helper methods to +analyze and prepare the arguments of the filter method.
TypeDetection.xcuContains the necessary +configuration items for the AsciiReplaceFilter.
+
+ + + + + + + + + + + + + + + +
FlatXmlFilter C++ ExampleDescription
FlatXml.cxxImplements an import/export filter +storing the data in one xml stream instead of the normal three streams +in for example an .odt file. The example is implemented in C++.
FlatXmlFilter_cpp.xcuContains the necessary +configuration items for the C++ flat xml filter.
+
+ + + + + + + + + + + + + + + +
FlatXmlFilter Java ExampleDescription
FlatXmlImplements an import/export filter +storing the data in one xml stream instead of the normal three streams +in for example an .odt file. The example is implemented in Java.
FlatXmlFilter_java.xcuContains the necessary +configuration items for the Java flat xml filter.
+
+ + + + + + + + + + + + + + + + + + + + + + + +
FlatXml FilterDetection ExampleDescription
filterdetect.cxxImplements an example filter +detection for the flat xml filter. The example is implemented in C++.
filterdetect.hxxContains the class definition of +the filter detection example.
fdcomp.cxxImplements the administrative +component functions (component_writeInfo, component_getFactory, component_getImplementationEnvironment).
FlatXmlTypeDetection.xcuContains the necessary +configuration items for the C++ flat xml type detection.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Desktop Environment ExampleDescription
CustomizeViewOffers a view which allows hiding +and showing of the menubar, toolbar and objectbar of the related +document component.
DeskThis is the main part of a demo +application based on the framework APIs. It mainly shows the mechanisms +to load, store and convert documents, as well as dispatch and dispatch +interception. It integrates windows from LibreOffice %PRODUCT_RELEASE% via system +window handle. This is the same mechanism as used by the OOoBean, but +the OOoBean itself is not used here, just the JNI window handle access.
DocumentViewDeals with the application window +and it's actions.
FunctionHelperThis helper comprises all +LibreOffice %PRODUCT_RELEASE% API calls. Thus it is possible to learn about these +aspects separately from the rest of the application example.
IOnewayLinkThis is an interface to receive +asynchronous events from UNO oneway calls.
IShutdownListenerThis is a listener interface to +clean up on shutdown of LibreOffice %PRODUCT_RELEASE%.
InterceptorThis implements a dispatch +interceptor for a specific URL.
JavaWindowPeerFakeFakes an XWindowPeer +for the Java native window handle to create a child window for the +office frame.
NativeViewImplements native JNI methods to +get the window handle of the Java window.
OfficeConnectBuilds the remote bridge to +LibreOffice %PRODUCT_RELEASE% and exports its UNO service manager for the Java side of +the application.
OnewayExecutorImplements IOnewayLink +to decouple asynchronous oneway calls in the Java process.
StatusListenerImplements a listener for a + FeatureStateEvent.
StatusViewShows the current status for which +the application is registered as an event listener.
ViewContainerPerforms a clean up on the Java +side on LibreOffice %PRODUCT_RELEASE% shutdown.
+
+ + + + + + + + + + + + + + + + + + + + + + + +
Office Development ExamplesDescription
OfficeConnectBuilds the remote bridge to +LibreOffice %PRODUCT_RELEASE% and exports its UNO service manager to the Java side.
ContextMenuInterceptorThis example shows a context menu +interceptor that creates a new menu entry that has a sub menu. This sub +menu is in inserted into the context menu on the topmost position. It +provides some helper functions to the user that are reachable through +the menu Help.
MenuElementA helper class for the context +menu interceptor example. It determines the menu element type.
Number_FormatsDemonstrates the use of number +formats in a spreadsheet document.
+
+ + + + + + + + + + + + + + + +
Termination Test ExampleDescription
TerminationTestThis example uses the +TerminateListener and shows the use of them in a running program.
TerminateListenerAn example implementation of + XTerminateListener. It is called +when LibreOffice %PRODUCT_RELEASE% terminates.
+
+ + + + + + + + + + + + + + + + + + + + + + + +
Clipboard ExampleDescription
ClipboardDemonstrates the usage of the +clipboard service by registering a clipboard listener, getting a list +of formats from the current clipboard content and copying some data to +the clipboard.
ClipboardListenerImplements a clipboard listener +for the Clipboard example. In such a class, actions can be implemented +which happen whenever the clipboard content changes.
ClipboardOwnerImplements a clipboard owner for +the Clipboard example. This class is notified when it loses ownership +of the clipboard.
TextTransferableImplements a data object for the +Clipboard example. Such classes supply clients with data in a variety +of formats.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Linguistic ExampleDescription
LinguisticExamplesA short example that uses most of +the functionality from the LibreOffice %PRODUCT_RELEASE% linguistic API.
OneInstanceFactoryThis class is used to provide a +service factory for the linguistic services. It enforces that the +actual implementations are only instantiated once.
PropChgHelperThe base class for several +property change helpers which are used to keep track of the changes of +the service relevant linguistic properties. It is also used by the +thesaurus directly.
PropChgHelper_HyphThe property change helper that is +tracking the hyphenation relevant properties.
PropChgHelper_SpellThe property change helper that is +tracking the spell checking relevant properties.
SampleHyphenatorA simple implementation for a Hyphenator +service.
SampleSpellCheckerA simple implementation for a SpellChecker +service.
SampleThesaurusA simple implementation for a Thesaurus +service.
XHyphenatedWord_implAn object implementing the XHyphenatedWord +interface. An instance of this type may be returned by the hyphenator.
XMeaning_implAn object implementing the XMeaning +interface. An instance of this type may be returned by the thesaurus.
XPossibleHyphens_implAn object implementing the + XPossibleHyphens interface. An +instance of this type may be returned by the hyphenator.
XSpellAlternatives_implAn object implementing the + XSpellAlternatives interface. An +instance of this type may be returned by the spell checker.
+
+ + + + + + + + + + + +
Path Settings ExampleDescription
PathsettingsTestThis code example creates the +service + com.sun.star.util.PathSettings and +retrieves all path properties from it. It shows how a developer can +change the path properties using the XPropertySet +interface.
+
+ + + + + + + + + + + +
Path Substitution ExampleDescription
PathSubstitutionTestThis code example creates the path +substitution service + com.sun.star.util.PathSubstitution +and retrieves the pre-defined Office path variables. It shows the +variable values on the screen. The reSubstiuteVariables function is +used to show how the service exchanges parts of a path with a path +variable supporting platform independent path usage.
+
+ + + + + + + + + + + +
Disable Commands ExampleDescription
DisableCommandsTestImplements an example showing how +a developer can use the configuration API to disable/enable commands at +runtime.
+
+
+ + + + + + + + + +
+ + + + + + + +
Text +Documents examples
+
+ + + + + + + + + + + +
ExampleDescription
TextDocuments +

Demonstrates a wide variety of API functions in +text documents and text document views.

+
    +
  • use of templates
  • +
  • using the view cursor, including visible text +selections
  • +
  • changing the paragraph style
  • +
  • using various editing facilities like text +insertion
  • +
  • using various cursor interfaces
  • +
  • creating text contents, like tables, sections +and frames, well as text fields and columns
  • +
  • using stylesheets
  • +
  • applying numbering styles
  • +
  • using references, indexes, footnotes and +autotext
  • +
  • loading, storing and printing a text document
  • +
+

Adjust the strings at the beginning of the class +definition to match your installation!

+
+
+
+ + + + + + + + + +
+ + + + + + + +
Spreadsheet +Documents examples
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
ExampleAddInImplements a simple add-in +component for spreadsheet documents. This component needs to be +deployed before it can be used.
ExampleDataPilotSourceShows usage of a wide variety of +spreadsheet interfaces like + XCellRangeData, XCellSeries, + XArrayFormulaRange +and XMultipleOperations +as well as named ranges, label ranges and data pilot.
GeneralTableSampleExecutes some examples working on +generic tables.
SpreadsheetDocHelperDefines a helper class for the +other examples to access spreadsheet documents, sheets and cells.
SpreadsheetSampleExecutes some examples working on +a spreadsheet document.
ViewSampleShows how to manipulate view +settings like splitting sheeting sheets and selecting cells.
+
+
+ + + + + + + + + +
+ + + + + + + +
Drawing +and Presentation Documents examples
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
ChangeOrderDemoShows how to change the painting +order of shapes.
ControlAndSelectDemoDemonstrates the creation of a +control shape and selects it in the current view.
CustomShowDemoCreates two custom shows and +selects one of these.
DrawViewDemoPrints the view data properties +and the controller properties of a drawing view and shows an example of +setting such a property.
DrawingDemoCreates several shapes on several +slides. Nice pattern included!
FillAndLineStyleDemoDemonstrates usage of area fill +and line style properties.
GluePointDemoCreates two shapes with glue +points and connects them with two connectors.
GraphicExportDemoLoads a drawing document and +exports it to a GIF file. Run this program with source URL, target URL +and page index on the command line, where the URLs are fully qualified +URLs.
HelperContains a helper class for the +other examples to connect to LibreOffice %PRODUCT_RELEASE% and open or create a drawing +document.
LayerDemoCreates shapes in different layers +to show how to protect shapes from modifications.
ObjectTransformationDemoShows geometric transformations on +a shape using a homogeneous matrix.
OrganigramDemonstrates the creation of an +organigram consisting of shapes and connectors.
PageHelperContains a helper class for +accessing several kinds of draw pages in a presentation or drawing +document.
PresentationDemoCreates a presentation and runs it +with some user interaction.
ShapeHelperContains a helper class for +accessing and creating shapes for the other examples.
StyleDemoCreates a shape and applies a +predefined shape stylesheet.
TextDemoDemonstrates usage of text and +text styles in shapes.
+
+
+ + + + + + + + + +
+ + + + + + + +
Charts +examples
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
CalcHelperContains some helper methods for +charts in spreadsheet documents, like accessing sheets by name, +inserting a chart into a sheet, filling cell ranges with random numbers +etc.
ChartHelperContains some helper methods for +charts, like creating a chart as an embedded object.
ChartInCalcDemonstrates how to create an +embedded chart object with a random scatter chart within a spreadsheet.
ChartInDrawInserts a 3D-bar chart into a +drawing document.
ChartInWriterInserts an embedded chart object +with a random bar chart in a text document. This example does not +really work, because the API for embedding objects into text documents +is not implemented. To be more precise.
HelperShows how to connect to +LibreOffice %PRODUCT_RELEASE% and create text, drawing or spreadsheet document. This +class is used as a helper class for the other examples.
JavaSampleChartAddInGives an example of how to +implement chart add-ins to create new or specialized diagram types. The +resulting component has to be deployed before it can be used.
ListenAtCalcRangeInDrawThis helper class is used to build +connection between an embedded chart object in a drawing document and a +data range in a spreadsheet document.
SelectionChangeListenerShows how to register a handler +which is called when the selection within an embedded chart object +changes.
+
+
+ + + + + + + + + +
+ + + + + + + +
LibreOffice %PRODUCT_RELEASE% Basic and Dialogs examples
+
+ + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
FirstStepsBasic.odtThis StarBasic example shows how to +create an own dialog which inserts a graphics object into a text +document.
SampleDialogThis example builds a Java +component which creates a simple dialog.
CreatingDialogs.odtThis document contains a simple +Basic macro which loads the SampleDialog component. The macro will be +executed by pressing a Push button.
ToolkitControlsIn this directory you find a Basic +library which implements several examples using toolkit controls. You +can easy pack this Basic library as a UNO package and can install it +using the package manager (see the makefile output).
+After the installation you will find a new library "ToolkitControls" in +the Basic IDE containing 4 modules and the necessary dialogs.
+

Select one of the following modules and press the +Run button:

+
    +
  • FileDialog = simple dialog which ask for a +filename (nothing else)
  • +
  • MultiPage = a more complex dialog with several +tab pages
  • +
  • ProgressBar = a dialog which shows a progress +bar
  • +
  • ScrollBar = a dialog which shows a scroll bar
  • +
+
+
+
+ + + + + + + + + + + + +
+ + + + + + + + + + +
Database +Access examples
The Database examples use a SQL +database named "MYDB0" with write access. Make sure that you have a +data source operating on such a database in your office before you run +the example.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Database ExamplesDescription
CodeSamplesCreates the connection to +LibreOffice %PRODUCT_RELEASE% and executes the code SalesMan samples for database API.
OpenQueryDemonstrates the use of XResultSetUpdate +and + XRowUpdate.
RowSetDemonstrates the usage of a row +set.
RowSetEventListenerDemonstrates how to define +listener for the row set example.
SalesCreates a simple database table.
SalesManCreates a simple database table.
sdbcxDemonstrates the usage of the +SDBCX layer services.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Driver Skeleton ExampleDescription
OSubComponent.hxxHelper class to delegate special +dispose handling.
OTypeInfo.hxxContains the database types from +the DatabaseMetaData getTypes call.
SConnection.hxxThis file contains the declaration +of a class implementing the service com.sun.star.sdbc.Connection.
SConnection.cxxThis file contains the +implementation of the class declared in SConnection.hxx.
SDatabaseMetaData.hxxThis file contains the declaration +of a class implementing the interface com.sun.star.sdbc.XDatabaseMetaData.
SDatabaseMetaData.cxxThis file contains the +implementation of the class declared in SDatabaseMetaData.hxx.
SDriver.hxxThis file contains the declaration +of a class implementing the service com.sun.star.sdbc.Driver.
SDriver.cxxThis file contains the +implementation of the class declared in SDriver.hxx.
SPreparedStatement.hxxThis file contains the declaration +of a class implementing the service com.sun.star.sdbc.PreparedStatement. +
SPreparedStatement.cxxThis file contains the +implementation of the class declared in SPreparedStatement.hxx.
SResultSet.hxxThis file contains the declaration +of a class implementing the service com.sun.star.sdbc.ResultSet.
SResultSet.cxxThis file contains the +implementation of the class declared in SResultSet.hxx.
SResultSetMetaData.hxxThis file contains the declaration +of a class implementing the interface com.sun.star.sdbc.XResultSetMetaData.
SResultSetMetaData.cxxThis file contains the +implementation of the class declared in SResultSetMetaData.hxx.
SServices.cxxThis file contains a class +implementing the service needed to register the driver.
SStatement.hxxThis file contains the declaration +of a class implementing the service com.sun.star.sdbc.Statement.
SStatement.cxxThis file contains the +implementation of the class declared in SStatement.hxx.
propertyids.hxxDefines some common used strings +and declare a helper class for properties.
propertyids.cxxImplements the property helper +class.
+
+
+ + + + + + + + + +
+ + + + + + + +
Forms +examples
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
BooleanValidatorThe class BooleanOperator +implements an validator +for a form control, which can veto certain radio button or check box +states.
ButtonOperatorThe form created by the sample +program contains various buttons which are tied to certain +functionality. The class ButtonOperator, well, operates these buttons.
ComponentTreeTraversalHelper classes for traveling +through a tree of + FormComponent's.
ControlLockHelper class for implementing the +locking of control depending on the state of the underlying RowSet.
ControlValidationThis is the main class for the +control validation example. It creates a sample document, fills it with +controls, and attaches several validators to those controls
ControlValidatorBase class implementing the common +denominator for components validating +form controls.
DataAwarenessThis class implements the basic +example for a form working on a database. Two tables will be created +and a form (writer document) with a business example will fill its +fields from these tables.
DateValidatorThe class DateValidator +implements an validator +for a form control, which can check the content of a form date field.
DocumentBasedExampleThis class collects common +functionality of examples which require a document.
DocumentHelperHelper class for encapsulating +working with a document.
DocumentTypeA simple enumeration class for +classifying a document.
DocumentViewHelperHelper class for encapsulating +working with a view for a document.
FLToolsVarious small tools for the form +layer sample program.
FormLayerHelper class for accessing and +manipulating the form layer of a document.
GridFieldValidatorGridFieldValidator is +responsible for validating the input in a specific grid control column. +This is not to be mixed up with the control-based validation as +described in the validation +module. Instead, a GridFieldValidator assembles and uses +various other concepts.
InteractionRequestA simple implementation of a XInteractionRequest. +Not tied to the form layer example, but a general helper.
KeyGeneratorHelper class which is able to +generate (unique) keys for a (RowSet + ) column. An instance of this class can be tied +to a specific row set column. It then monitors the state of the +underlying row set, and upon inserting a new record into it (two +operation modi are possible here), it automatically inserts a newly +created (two modi, too) key into the column.
ListSelectionValidatorThe class ListSelectionValidator +implements an validator +for a form control, which can veto certain selections in a list box +control.
NumericValidatorThe class NumericValidator +implements an validator +for a form control, which can veto certain values in every control +which allows exchanging numerical values.
SingleControlValidationThough form documents feature +inbuilt mechanisms for visually indicating invalid control content (see + com.sun.star.form.validation + for discussions about validity), the ControlValidation +example extends this. The validity state of every control in this +example, as well as possible explanations for invalidity, are displayed +in dedicated texts. The SingleControlValidation class +ties together a validatable control and those status texts.
SpreadsheetDocumentA specialized DocumentHelper +which represents a spreadsheet document, and offers some form related +functionality. For instance, this class allows the creation of + CellValueBinding instances, which +can be used to couple the content of a form control with the content of +a spreadsheet cell.
SpreadsheetValueBindingThis example demonstrates how to +bind form controls to spreadsheet cells.
SpreadsheetViewA specialized DocumentViewHelper +which represents a view to a spreadsheet document.
TableCellTextBindingThis class allows binding the +control of a form control with a table cell in a text document. For +this, it uses the mechanisms of the + com.sun.star.form.binding module.
TextValidatorThe class TextValidator +implements an validator +for a form control, which can monitor a form text field.
TimeValidatorThe class TimeValidator +implements an validator +for a form control, which can monitor the content of a form time field. +
UNOA small UNO-syntax related helper +class.
ValueBindingAn example how to bind the content +of a form control to a table cell in a text document.
WaitForInputA pretty small helper for the +interactive examples, which notifies another instance when the user +pressed key on the console.
+
+
+ + + + + + + + + +
+ + + + + + + +
Universal Content Broker (UCB) +examples
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
ChildrenRetrieverShows child entries of a given +folder. Try -help or -? on the command line to view optional parameters.
DataStreamComposerDemonstrates usage of the data +stream by copying the data from one UCB node to another.
DataStreamRetrieverShows how to obtain the data +stream from a document resource.
HelperSome helper methods to access the +UCB which are used by the other examples.
MyActiveDataSinkA helper class for the DataStreamRetriever +example which implements a data sink.
PropertiesComposerShows how to set property values +of a UCB resource.
PropertiesRetrieverShows how to access property +values of a UCB resource.
ResourceCreatorCreates a new file in an existing +file system folder.
ResourceManagerDemonstrates how to copy and move +UCB resources.
ResourceRemoverDemonstrates how to remove UCB +resources.
+
+
+ + + + + + + + + +
+ + + + + + + +
Configuration +Management examples
+
+ + + + + + + + + + + +
ExampleDescription
ConfigExamplesThis example connects to a +LibreOffice %PRODUCT_RELEASE%, gets the configuration manager and accesses the +configuration in various ways.
+
+
+ + + + + + + + + +
+ + + + + + + +
Office +Bean example
+
+ + + + + + + + + + + +
ExampleDescription
OOoBeanViewerShows how to use the OOoBean +embedded in a Java AWT component. It shows how to load and store +documents as well as how to control toolbar visibility.
+
+
+ + + + + + + + + +
+ + + + + + + +
Scripting Framework Examples
+
+ + + + + + + + + + + + + + + +
ExampleDescription
SayHelloA Scripting Framework Java macro +that opens a new Writer document and inserts the word Hello in it.
ScriptSelectorA Scripting Framework Java macro +that opens a Java Swing dialog with a tree view of the macro hierarchy +for the Office application.
+
+
+ + + + + + + + + +
+ + + + + + + +
Graphical User Interfaces
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
+DialogDocumentA sample showing how to display an office document in a dialog window.
+MessageBoxA sample showing how to display a simple message box.
+UnoDialogSampleA sample showing how to create various controls in a dialog (fixed text field, currency field, progress bar, fixed line, group box, edit field, time field, date field, pattern field, numeric field, progressbar, check box, radio button, list box, combo box, formatted field, file control, button control, roadmap control)
+UnoDialogSample2A dialog sample showing how to use a roadmap control.
+UnoMenuA sample showing a top window with some menus.
+UnoMenu2A dialog sample showing how to use or work with a context menu.
+ImageControlSample2Dialog sample showing how to use an image control.
+
+
+
+ +
+
+
+ + diff --git a/odk/examples/OLE/activex/Makefile b/odk/examples/OLE/activex/Makefile new file mode 100644 index 000000000..15167bc93 --- /dev/null +++ b/odk/examples/OLE/activex/Makefile @@ -0,0 +1,121 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the OLE activex C++ component example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMPONENT_NAME=so_activex +COMPONENT_IMPL_NAME=$(SHAREDLIB_PRE)$(COMPONENT_NAME).$(SHAREDLIB_EXT) +COMPONENT_IMPL=$(SHAREDLIB_OUT)/$(SHAREDLIB_PRE)$(COMPONENT_NAME).$(SHAREDLIB_EXT) +OUT_COMP_INC = $(OUT_INC)/$(COMPONENT_NAME) +OUT_COMP_GEN = $(OUT_MISC)/$(COMPONENT_NAME) +OUT_COMP_SLO=$(OUT_SLO)/$(COMPONENT_NAME) + +MIDLFILES = so_activex.idl + +CXXFILES = SOActiveX.cpp \ + SOComWindowPeer.cpp \ + so_activex.cpp \ + StdAfx2.cpp + +SLOFILES = $(patsubst %.cpp,$(OUT_COMP_SLO)/%.$(OBJ_EXT),$(CXXFILES)) + +# Targets +.PHONY: ALL +ALL : \ + OleActvieXComponentExample + +include $(SETTINGS)/stdtarget.mk + +# Attention: so_activex.idl is no UNOIDL file! +$(OUT_COMP_INC)/so_activex.h : so_activex.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)) + midl.exe /tlb $(OUT_COMP_GEN)/so_activex.tlb /h $(OUT_COMP_INC)/so_activex.h \ + /iid $(OUT_COMP_INC)/so_activex_i.c /proxy $(OUT_COMP_INC)/so_activex_p.c \ + /dlldata $(OUT_COMP_INC)/dlldata.c /Oicf $< + +$(OUT_COMP_GEN)/so_activex.res : so_activex.rc $(OUT_COMP_INC)/so_activex.h + -$(MKDIR) $(subst /,$(PS),$(@D)) + rc $(CC_INCLUDES) /R /FO$@ so_activex.rc + +$(OUT_COMP_SLO)/%.$(OBJ_EXT) : %.cpp + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + + +# Note: If you don't use the MS Visual Studio .Net, please comment out the next line. +CL_NEW_LIB=atls.lib + +$(SHAREDLIB_OUT)/$(SHAREDLIB_PRE)%.$(SHAREDLIB_EXT) : $(SLOFILES) $(OUT_COMP_GEN)/so_activex.res so_activex.def + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_LIB)) + @echo . + @echo ----------------------------------------------------------------------------------- + @echo ATTENTION: If you have problems with linking the library and if you do not use the + @echo MS .Net compiler please check the makefile and comment out the variable CL_NEW_LIB. + @echo ----------------------------------------------------------------------------------- + @echo . + $(LINK) $(LIBRARY_LINK_FLAGS) /OUT:$@ /MAP:$(OUT_COMP_GEN)/$(subst $(SHAREDLIB_EXT),map,$(@F)) \ + /DEF:so_activex.def /IMPLIB:$(OUT_LIB)/iso_activex.lib $(SLOFILES) \ + $(LIBO_SDK_LDFLAGS_STDLIBS) user32.lib uuid.lib advapi32.lib ole32.lib oleaut32.lib gdi32.lib \ + urlmon.lib Shlwapi.lib oldnames.lib $(CL_NEW_LIB) $(OUT_COMP_GEN)/so_activex.res + $(LINK_MANIFEST) + +ifeq "$(OS)" "WIN" +OleActvieXComponentExample : $(COMPONENT_IMPL) + @echo -------------------------------------------------------------------------------- + @echo The activex control was created, please load the "$(QM)example.html$(QM)" file + @echo in your InternetExplorer to use the activex control. + @echo -------------------------------------------------------------------------------- +else +OleActvieXComponentExample : + @echo -------------------------------------------------------------------------------- + @echo This example works only under Windows! + @echo -------------------------------------------------------------------------------- +endif + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_SLO)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_LIB)/*$(COMPONENT_NAME).*)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SHAREDLIB_OUT)/$(SHAREDLIB_PRE)$(COMPONENT_NAME).*)) diff --git a/odk/examples/OLE/activex/README.txt b/odk/examples/OLE/activex/README.txt new file mode 100644 index 000000000..6528c528f --- /dev/null +++ b/odk/examples/OLE/activex/README.txt @@ -0,0 +1,40 @@ +* Compile. + +Warning: Before the control can be built user has to add path to MS ATL headers + into Makefile. + +If you use the build environment of the SDK you have to check which MS compiler +do you use. It you use the MS Visual Studio .NET compiler everything should work +fine with the SDK. If you use an older MS compiler please edit the Makefile and +uncomment or remove the line 'CL_NEW_LIB=atls.lib'. + +* Description. + +The LibreOffice ActiveX control shows an example of access to UNO through COM technology. +It requires a properly installed LibreOffice version 4.0 or later +This is a Lite ActiveX control so it can be used only in containers that +allows to use such controls. It can be activated with an tag from +a html-page to embed a document. Without any parameters a new writer document will be +opened for editing. Possible parameters are + src - full URL to the file that should be edited/viewed; + it can contain "private:factory/..." URLs to open new documents + for edit, for example "private:factory/swriter" + readonly - if it is set to "true" the document will be opened readonly, + otherwise the document will be opened for editing. + +The control can be extended easily, for example it can be changed +to allow scripting to load different documents. + +As any ActiveX control this one should be registered. +To let MSIE register it itself the "CODEBASE" parameter +for the "OBJECT" tag should be specified +with a URL to the library "so_activex.dll". + +Also it can be done using regsvr32 application. +To do it please write +\System32\regsvr32 so_activex.dll + +To unregister the control please use /u option: +\system32\regsvr32 so_activex.dll /u + + diff --git a/odk/examples/OLE/activex/SOActiveX.cpp b/odk/examples/OLE/activex/SOActiveX.cpp new file mode 100644 index 000000000..f98e2ddb1 --- /dev/null +++ b/odk/examples/OLE/activex/SOActiveX.cpp @@ -0,0 +1,645 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// SOActiveX.cpp : Implementation of CSOActiveX + +#include "stdafx2.h" +#include "so_activex.h" +#include "SOActiveX.h" +#include "SOComWindowPeer.h" + +#define STAROFFICE_WINDOWCLASS "SOParentWindow" + +#define BARS_NUMBER 3 +#define BARS_TO_SHOW 2 + +OLECHAR* pSlotUrl[BARS_NUMBER] = + {L"slot:5910" // SID_TOGGLEFUNCTIONBAR + ,L"slot:5920" // SID_TOGGLESTATUSBAR + ,L"slot:6661" // SID_TOGGLE_MENUBAR + }; + +OLECHAR* pSlotName[BARS_NUMBER] = + {L"FunctionBarVisible" // SID_TOGGLEFUNCTIONBAR + ,L"StatusBarVisible" // SID_TOGGLESTATUSBAR + ,L"MenuBarVisible" // SID_TOGGLE_MENUBAR + }; + + + + + +HRESULT ExecuteFunc( IDispatch* idispUnoObject, + OLECHAR* sFuncName, + CComVariant* params, + unsigned int count, + CComVariant* pResult ) +{ + if( !idispUnoObject ) + return E_FAIL; + + DISPID id; + HRESULT hr = idispUnoObject->GetIDsOfNames( IID_NULL, &sFuncName, 1, LOCALE_USER_DEFAULT, &id); + if( !SUCCEEDED( hr ) ) return hr; + + DISPPARAMS dispparams= { params, 0, count, 0}; + + // DEBUG + EXCEPINFO myInfo; + return idispUnoObject->Invoke( id, IID_NULL,LOCALE_USER_DEFAULT, DISPATCH_METHOD, + &dispparams, pResult, &myInfo, 0); +} + +HRESULT GetIDispByFunc( IDispatch* idispUnoObject, + OLECHAR* sFuncName, + CComVariant* params, + unsigned int count, + CComPtr& pdispResult ) +{ + if( !idispUnoObject ) + return E_FAIL; + + CComVariant result; + HRESULT hr = ExecuteFunc( idispUnoObject, sFuncName, params, count, &result ); + if( !SUCCEEDED( hr ) ) return hr; + + if( result.vt != VT_DISPATCH || result.pdispVal == NULL ) + return hr; + + pdispResult = CComPtr( result.pdispVal ); + + return S_OK; +} + +HRESULT PutPropertiesToIDisp( IDispatch* pdispObject, + OLECHAR** sMemberNames, + CComVariant* pVariant, + unsigned int count ) +{ + for( unsigned int ind = 0; ind < count; ind++ ) + { + DISPID id; + HRESULT hr = pdispObject->GetIDsOfNames( IID_NULL, &sMemberNames[ind], 1, LOCALE_USER_DEFAULT, &id ); + if( !SUCCEEDED( hr ) ) return hr; + + hr = CComDispatchDriver::PutProperty( pdispObject, id, &pVariant[ind] ); + if( !SUCCEEDED( hr ) ) return hr; + } + + return S_OK; +} + + +// CSOActiveX + +CSOActiveX::CSOActiveX() +: mCookie(0) +, mCurFileUrl( L"private:factory/swriter" ) +, mbLoad( FALSE ) +, mParentWin( NULL ) +, mOffWin( NULL ) +, mbViewOnly( FALSE ) +{ + CLSID clsFactory = {0x82154420,0x0FBF,0x11d4,{0x83, 0x13,0x00,0x50,0x04,0x52,0x6A,0xB4}}; + HRESULT hr = CoCreateInstance( clsFactory, NULL, CLSCTX_ALL, __uuidof(IDispatch), (void**)&mpDispFactory); + + mPWinClass.style = CS_HREDRAW|CS_VREDRAW; + mPWinClass.lpfnWndProc = ::DefWindowProc; + mPWinClass.cbClsExtra = 0; + mPWinClass.cbWndExtra = 0; + mPWinClass.hInstance = (HINSTANCE) GetModuleHandle(NULL); //myInstance; + mPWinClass.hIcon = NULL; + mPWinClass.hCursor = NULL; + mPWinClass.hbrBackground = (HBRUSH) COLOR_BACKGROUND; + mPWinClass.lpszMenuName = NULL; + mPWinClass.lpszClassName = STAROFFICE_WINDOWCLASS; + + RegisterClass(&mPWinClass); +} + +CSOActiveX::~CSOActiveX() +{ + Cleanup(); + +} + +HRESULT CSOActiveX::Cleanup() +{ + if( mpDispFrame && mbViewOnly ) + { + ShowSomeBars(); + mbViewOnly = FALSE; + } + + if( mpDispFrame ) + { + // mpDispFrame->dispose(); + CComVariant dummyResult; + ExecuteFunc( mpDispFrame, L"dispose", NULL, 0, &dummyResult ); + mpDispFrame = CComPtr< IDispatch >(); + } + + if( ::IsWindow( mOffWin ) ) + ::DestroyWindow( mOffWin ); + + return S_OK; +} + + +STDMETHODIMP CSOActiveX::InitNew () +{ + mbLoad = TRUE; + return S_OK; +} + +STDMETHODIMP CSOActiveX::Load ( LPSTREAM pStm ) +{ + mbLoad = TRUE; + + // may be later? + // for now just ignore + + return S_OK; +} + +STDMETHODIMP CSOActiveX::Load( LPPROPERTYBAG pPropBag, LPERRORLOG pErrorLog ) +{ + IPropertyBag2* pPropBag2; + HRESULT hr = pPropBag->QueryInterface( IID_IPropertyBag2, (void**)&pPropBag2 ); + ATLASSERT( hr >= 0 ); + + if( !SUCCEEDED( hr ) ) + return hr; + + unsigned long aNum; + hr = pPropBag2->CountProperties( &aNum ); + ATLASSERT( hr >= 0 ); + if( !SUCCEEDED( hr ) ) + return hr; + + PROPBAG2* aPropNames = new PROPBAG2[aNum]; + unsigned long aReaded; + + hr = pPropBag2->GetPropertyInfo( 0, + aNum, + aPropNames, + &aReaded ); + ATLASSERT( hr >= 0 ); + if( !SUCCEEDED( hr ) ) + { + delete[] aPropNames; + return hr; + } + + CComVariant* aVal = new CComVariant[aNum]; + HRESULT* hvs = new HRESULT[aNum]; + hr = pPropBag2->Read( aNum, + aPropNames, + NULL, + aVal, + hvs ); + ATLASSERT( hr >= 0 ); + if( !SUCCEEDED( hr ) ) + { + delete[] hvs; + delete[] aVal; + delete[] aPropNames; + return hr; + } + + USES_CONVERSION; + for( unsigned long ind = 0; ind < aNum; ind++ ) + { + // all information from the 'object' tag is in strings + if( aVal[ind].vt == VT_BSTR && !strcmp( OLE2T( aPropNames[ind].pstrName ), "src" ) ) + { + mCurFileUrl = wcsdup( aVal[ind].bstrVal ); + } + else if( aVal[ind].vt == VT_BSTR + && !strcmp( OLE2T( aPropNames[ind].pstrName ), "readonly" ) ) + { + if( !strcmp( OLE2T( aVal[ind].bstrVal ), "true" ) ) + { + mbViewOnly = TRUE; + } + else + { + // the default value + mbViewOnly = FALSE; + } + } + } + + delete[] hvs; + delete[] aVal; + delete[] aPropNames; + + if( !mpDispFactory ) + return hr; + + mbLoad = TRUE; + + Invalidate(); + UpdateWindow(); + + return hr; +} + +HRESULT CSOActiveX::GetUnoStruct( OLECHAR* sStructName, CComPtr& pdispResult ) +{ + return GetIDispByFunc( mpDispFactory, L"Bridge_GetStruct", &CComVariant( sStructName ), 1, pdispResult ); +} + +HRESULT CSOActiveX::GetUrlStruct( OLECHAR* sUrl, CComPtr& pdispUrl ) +{ + HRESULT hr = GetUnoStruct( L"com.sun.star.util.URL", pdispUrl ); + if( !SUCCEEDED( hr ) ) return hr; + + OLECHAR* sURLMemberName = L"Complete"; + DISPID nURLID; + hr = pdispUrl->GetIDsOfNames( IID_NULL, &sURLMemberName, 1, LOCALE_USER_DEFAULT, &nURLID ); + if( !SUCCEEDED( hr ) ) return hr; + hr = CComDispatchDriver::PutProperty( pdispUrl, nURLID, &CComVariant( sUrl ) ); + if( !SUCCEEDED( hr ) ) return hr; + + CComPtr pdispTransformer; + hr = GetIDispByFunc( mpDispFactory, + L"createInstance", + &CComVariant( L"com.sun.star.util.URLTransformer" ), + 1, + pdispTransformer ); + if( !SUCCEEDED( hr ) ) return hr; + + CComVariant dummyResult; + CComVariant aInOutParam; + aInOutParam.ppdispVal = &pdispUrl; + aInOutParam.vt = VT_DISPATCH | VT_BYREF; + hr = ExecuteFunc( pdispTransformer, L"parseStrict", &aInOutParam, 1, &dummyResult ); + if( !SUCCEEDED( hr ) || dummyResult.vt != VT_BOOL || !dummyResult.boolVal ) return hr; + + return S_OK; +} + + +HRESULT CSOActiveX::CreateFrameOldWay( HWND hwnd, int width, int height ) +{ + if( !mpDispFactory ) + return E_FAIL; + + // create window handle holder + CComPtr< CComObject< SOComWindowPeer > > pPeerToSend = new CComObject( hwnd ); + pPeerToSend->SetHWNDInternally( hwnd ); + CComQIPtr< IDispatch, &IID_IDispatch > pIDispToSend( pPeerToSend ); + + // create rectangle structure + CComPtr pdispRectangle; + HRESULT hr = GetUnoStruct( L"com.sun.star.awt.Rectangle", pdispRectangle ); + if( !SUCCEEDED( hr ) ) return hr; + + OLECHAR* sRectMemberNames[4] = { L"X", + L"Y", + L"Width", + L"Height" }; + CComVariant pRectVariant[4]; + pRectVariant[0] = pRectVariant[1] = pRectVariant[2] = pRectVariant[3] = CComVariant( 0 ); + + hr = PutPropertiesToIDisp( pdispRectangle, sRectMemberNames, pRectVariant, 4 ); + if( !SUCCEEDED( hr ) ) return hr; + + // create WindowDescriptor structure + CComPtr pdispWinDescr; + hr = GetUnoStruct( L"com.sun.star.awt.WindowDescriptor", pdispWinDescr ); + if( !SUCCEEDED( hr ) ) return hr; + + // fill in descriptor with info + OLECHAR* sDescriptorMemberNames[6] = { L"Type", + L"WindowServiceName", + L"ParentIndex", + L"Parent", + L"Bounds", + L"WindowAttributes" }; + CComVariant pDescriptorVar[6]; + pDescriptorVar[0] = CComVariant( 0 ); + pDescriptorVar[1] = CComVariant( L"workwindow" ); + pDescriptorVar[2] = CComVariant( 1 ); + pDescriptorVar[3] = CComVariant( pIDispToSend ); + pDescriptorVar[4] = CComVariant( pdispRectangle ); + pDescriptorVar[5] = CComVariant( 33 ); + hr = PutPropertiesToIDisp( pdispWinDescr, sDescriptorMemberNames, pDescriptorVar, 6 ); + if( !SUCCEEDED( hr ) ) return hr; + + // create XToolkit instance + CComPtr pdispToolkit; + hr = GetIDispByFunc( mpDispFactory, L"createInstance", &CComVariant( L"com.sun.star.awt.Toolkit" ), 1, pdispToolkit ); + if( !SUCCEEDED( hr ) ) return hr; + + // create window with toolkit + hr = GetIDispByFunc( pdispToolkit, L"createWindow", &CComVariant( pdispWinDescr ), 1, mpDispWin ); + if( !SUCCEEDED( hr ) ) return hr; + + // create frame + hr = GetIDispByFunc( mpDispFactory, L"createInstance", &CComVariant( L"com.sun.star.frame.Task" ), 1, mpDispFrame ); + if( !SUCCEEDED( hr ) || !mpDispFrame ) + { + // the interface com.sun.star.frame.Task is removed in 6.1 + // but the interface com.sun.star.frame.Frame has some bugs in 6.0 + hr = GetIDispByFunc( mpDispFactory, L"createInstance", &CComVariant( L"com.sun.star.frame.Frame" ), 1, mpDispFrame ); + if( !SUCCEEDED( hr ) ) return hr; + } + + // initialize frame + CComVariant dummyResult; + hr = ExecuteFunc( mpDispFrame, L"initialize", &CComVariant( mpDispWin ), 1, &dummyResult ); + if( !SUCCEEDED( hr ) ) return hr; + + // create desktop + CComPtr pdispDesktop; + hr = GetIDispByFunc( mpDispFactory, L"createInstance", &CComVariant( L"com.sun.star.frame.Desktop" ), 1, pdispDesktop ); + if( !SUCCEEDED( hr ) ) return hr; + + // create tree of frames + CComPtr pdispChildren; + hr = GetIDispByFunc( pdispDesktop, L"getFrames", NULL, 0, pdispChildren ); + if( !SUCCEEDED( hr ) ) return hr; + + // insert new frame into desktop hierarchy + hr = ExecuteFunc( pdispChildren, L"append", &CComVariant( mpDispFrame ), 1, &dummyResult ); + if( !SUCCEEDED( hr ) ) return hr; + + // initialize window + hr = ExecuteFunc( mpDispWin, L"setBackground", &CComVariant( (long)0xFFFFFFFF ), 1, &dummyResult ); + if( !SUCCEEDED( hr ) ) return hr; + + hr = ExecuteFunc( mpDispWin, L"setVisible", &CComVariant( TRUE ), 1, &dummyResult ); + if( !SUCCEEDED( hr ) ) return hr; + + CComVariant aPosArgs[5]; + aPosArgs[4] = CComVariant( 0 ); + aPosArgs[3] = CComVariant( 0 ); + aPosArgs[2] = CComVariant( width ); + aPosArgs[1] = CComVariant( height ); + aPosArgs[0] = CComVariant( 12 ); + hr = ExecuteFunc( mpDispWin, L"setPosSize", aPosArgs, 5, &dummyResult ); + if( !SUCCEEDED( hr ) ) return hr; + + + return S_OK; +} + +HRESULT CSOActiveX::CallDispatch1PBool( OLECHAR* sUrl, OLECHAR* sArgName, BOOL sArgVal ) +{ + CComPtr pdispURL; + HRESULT hr = GetUrlStruct( sUrl, pdispURL ); + if( !SUCCEEDED( hr ) ) return hr; + + CComPtr pdispXDispatch; + CComVariant aArgs[3]; + aArgs[2] = CComVariant( pdispURL ); + aArgs[1] = CComVariant( L"" ); + aArgs[0] = CComVariant( (int)0 ); + hr = GetIDispByFunc( mpDispFrame, + L"queryDispatch", + aArgs, + 3, + pdispXDispatch ); + if( !SUCCEEDED( hr ) ) return hr; + + SAFEARRAY FAR* pPropVals = SafeArrayCreateVector( VT_DISPATCH, 0, 1 ); + long ix = 0; + CComPtr pdispPropVal; + hr = GetUnoStruct( L"com.sun.star.beans.PropertyValue", pdispPropVal ); + if( !SUCCEEDED( hr ) ) return hr; + + OLECHAR* sPropMemberNames[2] = { L"Name", L"Value" }; + CComVariant pPropVar[2]; + pPropVar[0] = CComVariant( sArgName ); + pPropVar[1] = CComVariant(); pPropVar[1].vt = VT_BOOL; pPropVar[1].boolVal = sArgVal ? VARIANT_TRUE : VARIANT_FALSE ; + hr = PutPropertiesToIDisp( pdispPropVal, sPropMemberNames, pPropVar, 2 ); + if( !SUCCEEDED( hr ) ) return hr; + + SafeArrayPutElement( pPropVals, &ix, pdispPropVal ); + + CComVariant aDispArgs[2]; + aDispArgs[1] = CComVariant( pdispURL ); + // aDispArgs[0] = CComVariant( pPropVals ); such constructor is not defined ??! + aDispArgs[0] = CComVariant(); aDispArgs[0].vt = VT_ARRAY | VT_DISPATCH; aDispArgs[0].parray = pPropVals; + + CComVariant dummyResult; + hr = ExecuteFunc( pdispXDispatch, L"dispatch", aDispArgs, 2, &dummyResult ); + if( !SUCCEEDED( hr ) ) return hr; + + return S_OK; +} + +HRESULT CSOActiveX::ShowSomeBars() +{ + // show FunctionBar and StatusBar + for( int ind = 0; ind < BARS_TO_SHOW; ind ++ ) + { + HRESULT hr = CallDispatch1PBool( pSlotUrl[ind], pSlotName[ind], TRUE ); + if( !SUCCEEDED( hr ) ) return hr; + } + + return S_OK; +} + +HRESULT CSOActiveX::HideAllBars() +{ + for( int ind = 0; ind < BARS_NUMBER; ind ++ ) + { + HRESULT hr = CallDispatch1PBool( pSlotUrl[ind], pSlotName[ind], FALSE ); + if( !SUCCEEDED( hr ) ) return hr; + } + + return S_OK; +} + +HRESULT CSOActiveX::LoadURLToFrame( ) +{ + HRESULT hr = CallDispatch1PBool( mCurFileUrl, L"ReadOnly", mbViewOnly ); + if( !SUCCEEDED( hr ) ) return hr; + + if( mbViewOnly ) + HideAllBars(); + + return S_OK; +} + +HRESULT CSOActiveX::OnDrawAdvanced( ATL_DRAWINFO& di ) +{ + if( m_spInPlaceSite && mCurFileUrl ) + { + HWND hwnd; + HRESULT hr = m_spInPlaceSite->GetWindow( &hwnd ); + if( !SUCCEEDED( hr ) ) return hr; + + if( mParentWin != hwnd || !mOffWin ) + { + if( mpDispFrame ) + { + CComVariant dummyResult; + ExecuteFunc( mpDispFrame, L"dispose", NULL, 0, &dummyResult ); + mpDispFrame = CComPtr(); + } + + mParentWin = hwnd; + mOffWin = CreateWindow( + STAROFFICE_WINDOWCLASS, + "OfficeContainer", + WS_CHILD | WS_CLIPCHILDREN | WS_BORDER, + di.prcBounds->left, + di.prcBounds->top, + di.prcBounds->right - di.prcBounds->left, + di.prcBounds->bottom - di.prcBounds->top, + mParentWin, + NULL, + NULL, + NULL ); + + ::ShowWindow( mOffWin, SW_SHOW ); + } + else + { + RECT aRect; + ::GetWindowRect( mOffWin, &aRect ); + + if( aRect.left != di.prcBounds->left || aRect.top != di.prcBounds->top + || aRect.right != di.prcBounds->right || aRect.bottom != di.prcBounds->bottom ) + { + // on this state the office window should exist already + ::SetWindowPos( mOffWin, + HWND_TOP, + di.prcBounds->left, + di.prcBounds->top, + di.prcBounds->right - di.prcBounds->left, + di.prcBounds->bottom - di.prcBounds->top, + SWP_NOZORDER ); + + CComVariant aPosArgs[5]; + aPosArgs[4] = CComVariant( 0 ); + aPosArgs[3] = CComVariant( 0 ); + aPosArgs[2] = CComVariant( int(di.prcBounds->right - di.prcBounds->left) ); + aPosArgs[1] = CComVariant( int(di.prcBounds->bottom - di.prcBounds->top) ); + aPosArgs[0] = CComVariant( 12 ); + CComVariant dummyResult; + hr = ExecuteFunc( mpDispWin, L"setPosSize", aPosArgs, 5, &dummyResult ); + if( !SUCCEEDED( hr ) ) return hr; + } + } + + if( ! mpDispFrame ) + { + hr = CreateFrameOldWay( mOffWin, + di.prcBounds->right - di.prcBounds->left, + di.prcBounds->bottom - di.prcBounds->top ); + if( !SUCCEEDED( hr ) ) return hr; + } + + if( mbLoad ) + { + hr = LoadURLToFrame(); + if( !SUCCEEDED( hr ) ) return hr; + mbLoad = FALSE; + } + } + + return S_OK; +} + + +STDMETHODIMP CSOActiveX::SetClientSite( IOleClientSite* aClientSite ) +{ + HRESULT hr = IOleObjectImpl::SetClientSite( aClientSite ); + + if( !aClientSite ) + { + ATLASSERT( mWebBrowser2 ); + if( mWebBrowser2 ) + AtlUnadvise( mWebBrowser2, DIID_DWebBrowserEvents2, mCookie ); + return hr; + } + + CComPtr aContainer; + m_spClientSite->GetContainer( &aContainer ); + ATLASSERT( aContainer ); + + if( SUCCEEDED( hr ) && aContainer ) + { + CComQIPtr aServiceProvider( aContainer ); + ATLASSERT( aServiceProvider ); + + if( aServiceProvider ) + { + aServiceProvider->QueryService( SID_SInternetExplorer, + IID_IWebBrowser, + (void**)&mWebBrowser2 ); + ATLASSERT( mWebBrowser2 ); + if( mWebBrowser2 ) + AtlAdvise( mWebBrowser2, GetUnknown(), DIID_DWebBrowserEvents2, &mCookie ); + } + } + + return hr; +} + +STDMETHODIMP CSOActiveX::Invoke(DISPID dispidMember, + REFIID riid, + LCID lcid, + WORD wFlags, + DISPPARAMS* pDispParams, + VARIANT* pvarResult, + EXCEPINFO* pExcepInfo, + UINT* puArgErr) +{ + if (riid != IID_NULL) + return DISP_E_UNKNOWNINTERFACE; + + if (!pDispParams) + return DISP_E_PARAMNOTOPTIONAL; + + if ( dispidMember == DISPID_ONQUIT ) + Cleanup(); + + IDispatchImpl::Invoke( + dispidMember, riid, lcid, wFlags, pDispParams, + pvarResult, pExcepInfo, puArgErr); + + return S_OK; +} + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/OLE/activex/SOActiveX.h b/odk/examples/OLE/activex/SOActiveX.h new file mode 100644 index 000000000..2057e43f4 --- /dev/null +++ b/odk/examples/OLE/activex/SOActiveX.h @@ -0,0 +1,168 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// SOActiveX.h : Declaration of the CSOActiveX + +#ifndef INCLUDED_EXAMPLES_ACTIVEX_SOACTIVEX_H +#define INCLUDED_EXAMPLES_ACTIVEX_SOACTIVEX_H + +#include "resource.h" +#include +#include +#include +#include + +#include "so_activex.h" + + +// CSOActiveX +class ATL_NO_VTABLE CSOActiveX : + public CComObjectRootEx, + public IDispatchImpl, + public CComControl, + public IPersistStreamInitImpl, + public IOleControlImpl, + public IOleObjectImpl, + public IOleInPlaceActiveObjectImpl, + public IViewObjectExImpl, + public IOleInPlaceObjectWindowlessImpl, +// public IConnectionPointContainerImpl, + public CComCoClass, +// public CProxy_ItryPluginEvents< CSOActiveX >, + public IPersistPropertyBagImpl< CSOActiveX >, + public IProvideClassInfo2Impl< &CLSID_SOActiveX, + &DIID__ISOActiveXEvents, + &LIBID_SO_ACTIVEXLib >, + public IObjectSafetyImpl< CSOActiveX, + INTERFACESAFE_FOR_UNTRUSTED_DATA > +{ +protected: + CComPtr mWebBrowser2; + DWORD mCookie; + + CComPtr mpDispFactory; + CComPtr mpDispFrame; + CComPtr mpDispWin; + OLECHAR* mCurFileUrl; + BOOL mbLoad; + BOOL mbViewOnly; + WNDCLASS mPWinClass; + HWND mParentWin; + HWND mOffWin; +public: + CSOActiveX(); + ~CSOActiveX(); + +DECLARE_REGISTRY_RESOURCEID(IDR_SOACTIVEX) + +DECLARE_PROTECT_FINAL_CONSTRUCT() + +BEGIN_COM_MAP(CSOActiveX) + COM_INTERFACE_ENTRY(ISOActiveX) + COM_INTERFACE_ENTRY(IDispatch) + COM_INTERFACE_ENTRY(IViewObjectEx) + COM_INTERFACE_ENTRY(IViewObject2) + COM_INTERFACE_ENTRY(IViewObject) + COM_INTERFACE_ENTRY(IOleInPlaceObjectWindowless) + COM_INTERFACE_ENTRY(IOleInPlaceObject) + COM_INTERFACE_ENTRY2(IOleWindow, IOleInPlaceObjectWindowless) + COM_INTERFACE_ENTRY(IOleInPlaceActiveObject) + COM_INTERFACE_ENTRY(IOleControl) + COM_INTERFACE_ENTRY(IOleObject) + COM_INTERFACE_ENTRY(IPersistStreamInit) + COM_INTERFACE_ENTRY2(IPersist, IPersistStreamInit) +// COM_INTERFACE_ENTRY(IConnectionPointContainer) + COM_INTERFACE_ENTRY(IProvideClassInfo) + COM_INTERFACE_ENTRY(IProvideClassInfo2) + COM_INTERFACE_ENTRY(IPersistPropertyBag) + COM_INTERFACE_ENTRY(IObjectSafety) +END_COM_MAP() + +BEGIN_PROP_MAP(CSOActiveX) + PROP_DATA_ENTRY("_cx", m_sizeExtent.cx, VT_UI4) + PROP_DATA_ENTRY("_cy", m_sizeExtent.cy, VT_UI4) + // Example entries + // PROP_ENTRY("Property Description", dispid, clsid) + // PROP_PAGE(CLSID_StockColorPage) +END_PROP_MAP() + +BEGIN_CONNECTION_POINT_MAP(CSOActiveX) +END_CONNECTION_POINT_MAP() + +BEGIN_MSG_MAP(CSOActiveX) + CHAIN_MSG_MAP(CComControl) + DEFAULT_REFLECTION_HANDLER() +END_MSG_MAP() +// Handler prototypes: +// LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); +// LRESULT CommandHandler(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled); +// LRESULT NotifyHandler(int idCtrl, LPNMHDR pnmh, BOOL& bHandled); + + + +// IViewObjectEx + DECLARE_VIEW_STATUS(VIEWSTATUS_SOLIDBKGND | VIEWSTATUS_OPAQUE) + +// ISOActiveX +public: + + STDMETHOD(SetClientSite)( IOleClientSite* aClientSite ); + STDMETHOD(Invoke)( DISPID dispidMember, + REFIID riid, + LCID lcid, + WORD wFlags, + DISPPARAMS* pDispParams, + VARIANT* pvarResult, + EXCEPINFO* pExcepInfo, + UINT* puArgErr); + STDMETHOD(Load) ( LPPROPERTYBAG pPropBag, LPERRORLOG pErrorLog ); + STDMETHOD(Load) ( LPSTREAM pStm ); + STDMETHOD(InitNew) (); + HRESULT OnDrawAdvanced(ATL_DRAWINFO& di); + HRESULT OnDraw(ATL_DRAWINFO& di) { return S_OK; } + + HRESULT CreateFrameOldWay( HWND hwnd, int width, int height ); + HRESULT GetUnoStruct( OLECHAR* sStructName, CComPtr& pdispResult ); + HRESULT LoadURLToFrame(); + HRESULT ShowSomeBars(); + HRESULT HideAllBars(); + HRESULT CallDispatch1PBool( OLECHAR* sUrl, OLECHAR* sArgName, BOOL sArgVal ); + HRESULT GetUrlStruct( OLECHAR* sUrl, CComPtr& pdispUrl ); + HRESULT Cleanup(); +}; + +#endif // INCLUDED_EXAMPLES_ACTIVEX_SOACTIVEX_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/OLE/activex/SOActiveX.rgs b/odk/examples/OLE/activex/SOActiveX.rgs new file mode 100644 index 000000000..d3814df3b --- /dev/null +++ b/odk/examples/OLE/activex/SOActiveX.rgs @@ -0,0 +1,33 @@ +HKCR +{ + so_activex.SOActiveX.1 = s 'SOActiveX Class' + { + CLSID = s '{67F2A879-82D5-4A6D-8CC5-FFB3C114B69D}' + } + so_activex.SOActiveX = s 'SOActiveX Class' + { + CLSID = s '{67F2A879-82D5-4A6D-8CC5-FFB3C114B69D}' + CurVer = s 'so_activex.SOActiveX.1' + } + NoRemove CLSID + { + ForceRemove {67F2A879-82D5-4A6D-8CC5-FFB3C114B69D} = s 'SOActiveX Class' + { + ProgID = s 'so_activex.SOActiveX.1' + VersionIndependentProgID = s 'so_activex.SOActiveX' + ForceRemove 'Programmable' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'Apartment' + } + ForceRemove 'Control' + ForceRemove 'ToolboxBitmap32' = s '%MODULE%, 101' + 'MiscStatus' = s '0' + { + '1' = s '131473' + } + 'TypeLib' = s '{61FA3F13-8061-4796-B055-3697ED28CB38}' + 'Version' = s '1.0' + } + } +} diff --git a/odk/examples/OLE/activex/SOComWindowPeer.cpp b/odk/examples/OLE/activex/SOComWindowPeer.cpp new file mode 100644 index 000000000..0045014fe --- /dev/null +++ b/odk/examples/OLE/activex/SOComWindowPeer.cpp @@ -0,0 +1,61 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// SOComWindowPeer.cpp : Implementation of CHelpApp and DLL registration. + +#include "stdafx2.h" +#include "so_activex.h" +#include "SOComWindowPeer.h" +#include + + + + +STDMETHODIMP SOComWindowPeer::InterfaceSupportsErrorInfo(REFIID riid) +{ + static const IID* arr[] = + { + &IID_ISOComWindowPeer, + }; + + for (int i=0;i +#include +#include +#include + +#include "so_activex.h" + +class SOComWindowPeer : + public IDispatchImpl, + public ISupportErrorInfo, + public CComObjectRoot, + public CComCoClass +{ + HWND m_hwnd; +public: + SOComWindowPeer() : m_hwnd( NULL ) {} + +BEGIN_COM_MAP(SOComWindowPeer) + COM_INTERFACE_ENTRY(IDispatch) + COM_INTERFACE_ENTRY(ISOComWindowPeer) + COM_INTERFACE_ENTRY(ISupportErrorInfo) +END_COM_MAP() +DECLARE_NOT_AGGREGATABLE(SOComWindowPeer) +// Remove the comment from the line above if you don't want your object to +// support aggregation. + +DECLARE_REGISTRY_RESOURCEID(IDR_SOCOMWINDOWPEER) + +// ISupportsErrorInfo + STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); + +// ISOComWindowPeer + virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getWindowHandle( + /* [in] */ SAFEARRAY __RPC_FAR * procId, + /* [in] */ short s, + /* [retval][out] */ long __RPC_FAR *ret) + { + *ret = (long) m_hwnd; + return S_OK; + } + + virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getToolkit( + /* [retval][out] */ IDispatch __RPC_FAR *__RPC_FAR *retVal) + { + *retVal = NULL; + return S_OK; + } + + virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setPointer( + /* [in] */ IDispatch __RPC_FAR *xPointer) + { + return S_OK; + } + + virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setBackground( + /* [in] */ int nColor) + { + return S_OK; + } + + virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE invalidate( + /* [in] */ short __MIDL_0015) + { + return S_OK; + } + + virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE invalidateRect( + /* [in] */ IDispatch __RPC_FAR *aRect, + /* [in] */ short nFlags) + { + return S_OK; + } + + virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE dispose( void) + { + return S_OK; + } + + virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE addEventListener( + /* [in] */ IDispatch __RPC_FAR *xListener) + { + return S_OK; + } + + virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE removeEventListener( + /* [in] */ IDispatch __RPC_FAR *xListener) + { + return S_OK; + } + + virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Bridge_implementedInterfaces( + /* [retval][out] */ SAFEARRAY __RPC_FAR * __RPC_FAR *pVal) + { + *pVal = SafeArrayCreateVector( VT_BSTR, 0, 2 ); + + if( !*pVal ) + return E_FAIL; + + long ix = 0; + CComBSTR aInterface( OLESTR( "com.sun.star.awt.XSystemDependentWindowPeer" ) ); + SafeArrayPutElement( *pVal, &ix, aInterface ); + + ix = 1; + aInterface = CComBSTR( OLESTR( "com.sun.star.awt.XWindowPeer" ) ); + SafeArrayPutElement( *pVal, &ix, aInterface ); + + return S_OK; + } + + void SetHWNDInternally( HWND hwnd ) { m_hwnd = hwnd; } +}; + +#endif // INCLUDED_EXAMPLES_ACTIVEX_SOCOMWINDOWPEER_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/OLE/activex/SOComWindowPeer.rgs b/odk/examples/OLE/activex/SOComWindowPeer.rgs new file mode 100644 index 000000000..42e985a31 --- /dev/null +++ b/odk/examples/OLE/activex/SOComWindowPeer.rgs @@ -0,0 +1,23 @@ +HKCR +{ + so_activex.SOComWindowPeer.1 = s 'SOComWindowPeer Class' + { + CLSID = s '{EE51BD3E-8BB6-4FB8-B319-F65B1BE3B21D}' + } + so_activex.SOComWindowPeer = s 'SOComWindowPeer Class' + { + CLSID = s '{EE51BD3E-8BB6-4FB8-B319-F65B1BE3B21D}' + } + NoRemove CLSID + { + ForceRemove {EE51BD3E-8BB6-4FB8-B319-F65B1BE3B21D} = s 'SOComWindowPeer Class' + { + ProgID = s 'so_activex.SOComWindowPeer.1' + VersionIndependentProgID = s 'so_activex.SOComWindowPeer' + InprocServer32 = s '%MODULE%' + { + val ThreadingModel = s 'both' + } + } + } +} diff --git a/odk/examples/OLE/activex/StdAfx2.cpp b/odk/examples/OLE/activex/StdAfx2.cpp new file mode 100644 index 000000000..3911bcf24 --- /dev/null +++ b/odk/examples/OLE/activex/StdAfx2.cpp @@ -0,0 +1,49 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// stdafx1.cpp : source file that includes just the standard includes +// stdafx1.pch will be the pre-compiled header +// stdafx1.obj will contain the pre-compiled type information + +#include "stdafx2.h" + +#ifdef _ATL_STATIC_REGISTRY +#include +#include +#endif + +#include + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/OLE/activex/StdAfx2.h b/odk/examples/OLE/activex/StdAfx2.h new file mode 100644 index 000000000..df14ccf94 --- /dev/null +++ b/odk/examples/OLE/activex/StdAfx2.h @@ -0,0 +1,64 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// stdafx1.h : include file for standard system include files, +// or project specific include files that are used frequently, +// but are changed infrequently + +#ifndef INCLUDED_EXAMPLES_ACTIVEX_STDAFX2_H +#define INCLUDED_EXAMPLES_ACTIVEX_STDAFX2_H + +#define STRICT +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0502 +#endif +#define _ATL_APARTMENT_THREADED +#define _ATL_STATIC_REGISTRY + +#define min(a, b) (((a) < (b)) ? (a) : (b)) + +#include +//You may derive a class from CComModule and use it if you want to override +//something, but do not change the name of _Module +extern CComModule _Module; +#include +#include + +//{{AFX_INSERT_LOCATION}} +// Microsoft Visual C++ will insert additional declarations immediately before the previous line. + +#endif // INCLUDED_EXAMPLES_ACTIVEX_STDAFX2_H + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/OLE/activex/example.html b/odk/examples/OLE/activex/example.html new file mode 100644 index 000000000..f9843f0dd --- /dev/null +++ b/odk/examples/OLE/activex/example.html @@ -0,0 +1,44 @@ + + + + +Document Title + + + +
+First you should edit the example.html file!!! +
+
+ + + + + + + +
+ + + diff --git a/odk/examples/OLE/activex/resource.h b/odk/examples/OLE/activex/resource.h new file mode 100644 index 000000000..88480036f --- /dev/null +++ b/odk/examples/OLE/activex/resource.h @@ -0,0 +1,57 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by so_activex.rc + +#define IDS_PROJNAME 100 +#define IDB_SOACTIVEX 101 +#define IDR_SOACTIVEX 102 +#define IDB_SOCOMWINDOWPEER 103 +#define IDR_SOCOMWINDOWPEER 104 + +// Next default values for new objects + +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 201 +#define _APS_NEXT_COMMAND_VALUE 32768 +#define _APS_NEXT_CONTROL_VALUE 201 +#define _APS_NEXT_SYMED_VALUE 105 +#endif +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/OLE/activex/so_activex.cpp b/odk/examples/OLE/activex/so_activex.cpp new file mode 100644 index 000000000..e546aeff5 --- /dev/null +++ b/odk/examples/OLE/activex/so_activex.cpp @@ -0,0 +1,110 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// so_activex.cpp : Implementation of DLL Exports. + + +// Note: Proxy/Stub Information +// To build a separate proxy/stub DLL, +// run nmake -f so_activexps.mk in the project directory. + +#include "stdafx2.h" +#include "resource.h" +#include +#include "so_activex.h" + +#include "so_activex_i.c" +#include "SOActiveX.h" + + +CComModule _Module; + +BEGIN_OBJECT_MAP(ObjectMap) +OBJECT_ENTRY(CLSID_SOActiveX, CSOActiveX) +END_OBJECT_MAP() + + +// DLL Entry Point + +extern "C" +BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/) +{ + if (dwReason == DLL_PROCESS_ATTACH) + { + _Module.Init(ObjectMap, hInstance, &LIBID_SO_ACTIVEXLib); + DisableThreadLibraryCalls(hInstance); + } + else if (dwReason == DLL_PROCESS_DETACH) + _Module.Term(); + return TRUE; // ok +} + + +// Used to determine whether the DLL can be unloaded by OLE + +STDAPI DllCanUnloadNow(void) +{ + return (_Module.GetLockCount()==0) ? S_OK : S_FALSE; +} + + +// Returns a class factory to create an object of the requested type + +STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) +{ + return _Module.GetClassObject(rclsid, riid, ppv); +} + + +// DllRegisterServer - Adds entries to the system registry + +STDAPI DllRegisterServer(void) +{ + HRESULT aResult = _Module.RegisterServer(TRUE); + + return aResult; +} + + +// DllUnregisterServer - Removes entries from the system registry + +STDAPI DllUnregisterServer(void) +{ + HRESULT aResult = _Module.UnregisterServer(TRUE); + + return aResult; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/OLE/activex/so_activex.def b/odk/examples/OLE/activex/so_activex.def new file mode 100644 index 000000000..68939efa1 --- /dev/null +++ b/odk/examples/OLE/activex/so_activex.def @@ -0,0 +1,5 @@ +EXPORTS + DllCanUnloadNow PRIVATE + DllGetClassObject PRIVATE + DllRegisterServer PRIVATE + DllUnregisterServer PRIVATE diff --git a/odk/examples/OLE/activex/so_activex.idl b/odk/examples/OLE/activex/so_activex.idl new file mode 100644 index 000000000..6013b7e55 --- /dev/null +++ b/odk/examples/OLE/activex/so_activex.idl @@ -0,0 +1,140 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// so_activex.idl : IDL source for so_activex.dll + + +// This file will be processed by the MIDL tool to +// produce the type library (so_activex.tlb) and marshalling code. + +import "oaidl.idl"; +import "ocidl.idl"; +#include + + + [ + object, + uuid(DACF7E3F-626B-4BF9-964B-F4910C843711), + dual, + helpstring("ISOActiveX Interface"), + pointer_default(unique) + ] + interface ISOActiveX : IDispatch + { + }; + +[ + object, + uuid(BF5D10F3-8A10-4A0B-B150-2B6AA2D7E118), + dual, + helpstring("ISOComWindowPeer Interface"), + pointer_default(unique) +] +interface ISOComWindowPeer : IDispatch +{ + [id(1), helpstring("method getWindowHandle")] + HRESULT getWindowHandle( [in] SAFEARRAY(VARIANT) procId, + [in] short s, + [out,retval] long* ret); + + [id(2), helpstring("method getToolkit")] + HRESULT getToolkit( [out,retval] IDispatch** retVal ); + + [id(3), helpstring("method setPointer")] + HRESULT setPointer( [in] IDispatch* xPointer ); + + [id(4), helpstring("method setBackground")] + HRESULT setBackground( [in] int nColor ); + + [id(5), helpstring("method invalidate")] + HRESULT invalidate( [in] short ); + + [id(6), helpstring("method invalidateRect")] + HRESULT invalidateRect( [in] IDispatch* aRect, [in] short nFlags ); + + [id(7), helpstring("method dispose")] + HRESULT dispose(); + + [id(8), helpstring("method addEventListener")] + HRESULT addEventListener( [in] IDispatch* xListener ); + + [id(9), helpstring("method removeEventListener")] + HRESULT removeEventListener( [in] IDispatch* xListener ); + + [propget, id(10), helpstring("property_implementedInterfaces")] + HRESULT Bridge_implementedInterfaces([out, retval] SAFEARRAY(BSTR) *pVal); +}; + +[ + uuid(61FA3F13-8061-4796-B055-3697ED28CB38), + version(1.0), + helpstring("so_activex 1.0 Type Library") +] +library SO_ACTIVEXLib +{ + importlib("stdole32.tlb"); + importlib("stdole2.tlb"); + + [ + uuid(7F760565-5719-4F04-BA86-112C474B10EA), + helpstring("_ISOActiveXEvents Interface") + ] + dispinterface _ISOActiveXEvents + { + properties: + methods: + }; + + [ + uuid(67F2A879-82D5-4A6D-8CC5-FFB3C114B69D), + helpstring("SOActiveX Class") + ] + coclass SOActiveX + { + [default] interface ISOActiveX; + [default, source] dispinterface _ISOActiveXEvents; + }; + + [ + uuid(EE51BD3E-8BB6-4FB8-B319-F65B1BE3B21D), + helpstring("SOComWindowPeer Class") + ] + coclass SOComWindowPeer + { + [default] interface ISOComWindowPeer; + }; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/OLE/activex/so_activex.rc b/odk/examples/OLE/activex/so_activex.rc new file mode 100644 index 000000000..1141e1044 --- /dev/null +++ b/odk/examples/OLE/activex/so_activex.rc @@ -0,0 +1,136 @@ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +//Microsoft Developer Studio generated resource script. + +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS + + +// Generated from the TEXTINCLUDE 2 resource. + +#include "winres.h" + + +#undef APSTUDIO_READONLY_SYMBOLS + + +// Russian resources + +//#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_RUS) +//#ifdef _WIN32 +//LANGUAGE LANG_RUSSIAN, SUBLANG_DEFAULT +//#pragma code_page(1251) +//#endif //_WIN32 + + + +// Bitmap + + +//IDB_SOACTIVEX BITMAP DISCARDABLE "soacti.bmp" + + + + +// REGISTRY + + +IDR_SOACTIVEX REGISTRY DISCARDABLE "SOActiveX.rgs" +IDR_SOCOMWINDOWPEER REGISTRY DISCARDABLE "SOComWindowPeer.rgs" +//#endif // Russian resources + + + + +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED + + +// TEXTINCLUDE + + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "1 TYPELIB ""so_activex.tlb""\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + + +// String Table + + +STRINGTABLE DISCARDABLE +BEGIN + IDS_PROJNAME "so_activex" +END + +#endif // English (U.S.) resources + + + + +#ifndef APSTUDIO_INVOKED + + +// Generated from the TEXTINCLUDE 3 resource. + + +1 TYPELIB .\..\..\..\WINexample.out\misc\so_activex\so_activex.tlb + + +#endif // not APSTUDIO_INVOKED + diff --git a/odk/examples/OLE/delphi/InsertTables/Project1.dpr b/odk/examples/OLE/delphi/InsertTables/Project1.dpr new file mode 100644 index 000000000..9f2bd2fd5 --- /dev/null +++ b/odk/examples/OLE/delphi/InsertTables/Project1.dpr @@ -0,0 +1,14 @@ +program Project1; + +uses + Forms, + SampleUI in 'SampleUI.pas' {OKBottomDlg}, + SampleCode in 'SampleCode.pas'; + +{$R *.RES} + +begin + Application.Initialize; + Application.CreateForm(TOKBottomDlg, OKBottomDlg); + Application.Run; +end. diff --git a/odk/examples/OLE/delphi/InsertTables/Project1.res b/odk/examples/OLE/delphi/InsertTables/Project1.res new file mode 100644 index 000000000..e69de29bb diff --git a/odk/examples/OLE/delphi/InsertTables/SampleCode.pas b/odk/examples/OLE/delphi/InsertTables/SampleCode.pas new file mode 100644 index 000000000..f314f7ea6 --- /dev/null +++ b/odk/examples/OLE/delphi/InsertTables/SampleCode.pas @@ -0,0 +1,393 @@ +{*********************************************************************** + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************} +unit SampleCode; + +interface + +uses + Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, + StdCtrls, ComObj, Variants; + + type + TSampleCode = class + + function Connect() : boolean; + procedure Disconnect(); + + function CreateDocument(bReadOnly : boolean) : boolean; + + procedure InsertTable(sTableName : String; dbPointer : String); + + procedure InsertDatabaseTable( + oDoc : Variant; + sTableName : String; + oCursor : Variant; + iRows : Integer; + iColumns : Integer; + dbPointer : String ); + function CreateTextTable( + oDoc : Variant; + oCursor : Variant; + sName : String; + iRow : Integer; + iColumn : Integer) : Variant; + function getCellContent( + sBookmarkName : String ) : Variant; + function getDatabasePointer( + sTableName : String; + sCellname : String ) : String; + procedure InsertBookmark( + oDoc : Variant; + oTextCursor : Variant; + sBookmarkName : String ); + function CreateBookmarkName( + sTableName : String; + sCellName : String; + sDatabasepointer : String ) : String; + procedure ChangeCellContent( + oDoc : Variant; + sTableName : String; + sCellName : String; + dValue : Double ); + function GetBookmarkFromDBPointer( + oDoc : Variant; + sBookmarkName : String) : Variant; + function GetBookmarkFromAdress( + oDoc : Variant; + sTableName : String; + sCellAdress : String) : Variant; + function JumpToBookmark( + oBookmark : Variant) : Variant; + function CreateUniqueTablename(oDoc : Variant) : String; + + private + StarOffice : Variant; + Document : Variant; + + { Private-Deklarationen } + public + { Public-Deklarationen } + end; + +implementation + +{ Insert a table texttable and insert in each cell a Bookmark with the address + of the cell and database pointer +} + +function TSampleCode.Connect() : boolean; +begin + if VarIsEmpty(StarOffice) then + StarOffice := CreateOleObject('com.sun.star.ServiceManager'); + + Connect := not (VarIsEmpty(StarOffice) or VarIsNull(StarOffice)); +end; + +procedure TSampleCode.Disconnect(); +begin + StarOffice := Unassigned; +end; + +function TSampleCode.CreateDocument(bReadOnly : boolean) : boolean; +var + StarDesktop : Variant; + LoadParams : Variant; + CoreReflection : Variant; + PropertyValue : Variant; +begin + StarDesktop := StarOffice.createInstance('com.sun.star.frame.Desktop'); + + if (bReadOnly) then begin + LoadParams := VarArrayCreate([0, 0], varVariant); + CoreReflection := StarOffice.createInstance('com.sun.star.reflection.CoreReflection'); + + CoreReflection + .forName('com.sun.star.beans.PropertyValue') + .createObject(PropertyValue); + + PropertyValue.Name := 'ReadOnly'; + PropertyValue.Value := true; + + LoadParams[0] := PropertyValue; + end + else + LoadParams := VarArrayCreate([0, -1], varVariant); + + Document := StarDesktop.LoadComponentFromURL( 'private:factory/swriter', '_blank', 0, LoadParams); + + CreateDocument := not (VarIsEmpty(Document) or VarIsNull(Document)); +end; + + +function TSampleCode.getCellContent( + sBookmarkName : String ) : Variant; +var + oBookmark : Variant; + oTextCursor : Variant; +begin + oBookmark := GetBookmarkFromDBPointer( Document, sBookmarkName ); + oTextCursor := JumpToBookmark( oBookmark ); + + getCellContent := oTextCursor.Cell.Value; + +end; + + +function TSampleCode.getDatabasePointer( + sTableName : String; + sCellname : String ) : String; +var + oBookmark : Variant; + sBookmarkName : String; + iPos : Integer; +begin + oBookmark := GetBookmarkFromAdress( Document, sTableName, sCellName ); + + sBookmarkName := oBookmark.getName(); + + iPos := Pos('/%', sBookmarkName); + while Pos('/%', sBookmarkName) > 0 do + begin + iPos := Pos('/%', sBookmarkName); + sBookmarkName[iPos] := '%'; + end; + + Delete( sBookmarkName, 1, iPos+1); + getDatabasePointer := sBookmarkName; +end; + + +procedure TSampleCode.InsertTable(sTableName : String; dbPointer : String); +var + oCursor : Variant; +begin + { create a cursor object on the current position in the document } + oCursor := Document.Text.CreateTextCursor(); + + { Create for each table a unique database name } + if (sTableName = '') then + sTableName := createUniqueTablename(Document); + + InsertDatabaseTable( Document, sTableName, oCursor, 4, 2, dbPointer ); + + ChangeCellContent( Document, sTableName, 'B2', 1.12 ); +end; + +procedure TSampleCode.InsertDatabaseTable( + oDoc : Variant; + sTableName : String; + oCursor : Variant; + iRows : Integer; + iColumns : Integer; + dbPointer : String); +var + oTable : Variant; + sCellnames : Variant; + iCellcounter : Integer; + oCellCursor : Variant; + oTextCursor : Variant; + sCellName : String; +begin + oTable := CreateTextTable( oDoc, oCursor, sTableName, iRows, iColumns ); + sCellnames := oTable.getCellNames(); + + For iCellcounter := VarArrayLowBound( sCellnames, 1) to VarArrayHighBound(sCellnames, 1) do + begin + sCellName := sCellnames[iCellcounter]; + + oCellCursor := oTable.getCellByName(sCellName); + oCellCursor.Value := iCellcounter; + oTextCursor := oCellCursor.getEnd(); + InsertBookmark( + oDoc, + oTextCursor, + createBookmarkName(sTableName, sCellName, dbPointer)); + end; +end; + +{ + +' Change the content of a cell +} + +procedure TSampleCode.ChangeCellContent( + oDoc : Variant; + sTableName : String; + sCellName : String; + dValue : Double ); +var + oBookmark : Variant; + oTextCursor : Variant; + sBookmarkName : String; +begin + oBookmark := GetBookmarkFromAdress( oDoc, sTableName, sCellName ); + oTextCursor := JumpToBookmark( oBookmark ); + oTextCursor.Cell.Value := dValue; + + { create a new bookmark for the new number } + sBookmarkName := oBookmark.getName(); + oBookmark.dispose(); + InsertBookmark( oDoc, oTextCursor, sBookmarkName ); +end; + + +{ ' Jump to Bookmark and return for this position the cursor } + +function TSampleCode.JumpToBookmark( + oBookmark : Variant) : Variant; + +begin + JumpToBookmark := oBookmark.Anchor.Text.createTextCursorByRange( + oBookmark.Anchor ); +end; + + +{ ' Create a Texttable on a Textdocument } +function TSampleCode.CreateTextTable( + oDoc : Variant; + oCursor : Variant; + sName : String; + iRow : Integer; + iColumn : Integer) : Variant; +var + ret : Variant; +begin + ret := oDoc.createInstance( 'com.sun.star.text.TextTable' ); + + ret.setName( sName ); + ret.initialize( iRow, iColumn ); + oDoc.Text.InsertTextContent( oCursor, ret, False ); + + CreateTextTable := ret; +end; + + +{ 'create a unique name for the Texttables } +function TSampleCode.CreateUniqueTablename(oDoc : Variant) : String; +var + iHighestNumber : Integer; + sTableNames : Variant; + iTableCounter : Integer; + sTableName : String; + iTableNumber : Integer; + i : Integer; +begin + sTableNames := oDoc.getTextTables.getElementNames(); + iHighestNumber := 0; + For iTableCounter := VarArrayLowBound(sTableNames, 1) to VarArrayHighBound(sTableNames, 1) do + begin + sTableName := sTableNames[iTableCounter]; + i := Pos( '$$', sTableName ); + iTableNumber := strtoint( Copy(sTableName, i + 2, Length( sTableName ) - i - 1 ) ); + + If iTableNumber > iHighestNumber then + iHighestNumber := iTableNumber; + end; + createUniqueTablename := 'DBTable$$' + inttostr(iHighestNumber + 1); +end; + + +{' Insert a Bookmark on the cursor } +procedure TSampleCode.InsertBookmark( + oDoc : Variant; + oTextCursor : Variant; + sBookmarkName : String); +var + oBookmarkInst : Variant; +begin + oBookmarkInst := oDoc.createInstance('com.sun.star.text.Bookmark'); + + oBookmarkInst.Name := sBookmarkName; + oTextCursor.gotoStart( true ); + oTextCursor.text.InsertTextContent( oTextCursor, oBookmarkInst, true ); +end; + + +function TSampleCode.CreateBookmarkName( + sTableName : String; + sCellName : String; + sDatabasepointer : String ) : String; +begin + createBookmarkName := '//' + sTableName + '/%' + sCellName + '/%' + sDatabasePointer + ':' + sCellName; +end; + +{ ' Returns the Bookmark the Tablename and Cellname } +function TSampleCode.GetBookmarkFromAdress( + oDoc : Variant; + sTableName : String; + sCellAdress : String) : Variant; +var + sTableAddress : String; + iTableNameLength : Integer; + sBookNames : Variant; + iBookCounter : Integer; +begin + sTableAddress := '//' + sTableName + '/%' + sCellAdress; + iTableNameLength := Length( sTableAddress ); + + sBookNames := oDoc.Bookmarks.getElementNames; + + for iBookCounter := VarArrayLowBound(sBookNames, 1) to VarArrayHighBound(sBookNames, 1) do + begin + If sTableAddress = Copy( sBookNames[iBookCounter], 1, iTableNameLength) then + begin + GetBookmarkFromAdress := oDoc.Bookmarks.getByName(sBookNames[iBookCounter]); + exit; + end; + end; +end; + +{ ' Returns the Bookmark the Tablename and Cellname } +function TSampleCode.GetBookmarkFromDBPointer( + oDoc : Variant; + sBookmarkName : String) : Variant; +var + sBookNames : Variant; + iBookCounter : Integer; +begin + sBookNames := oDoc.Bookmarks.getElementNames; + + for iBookCounter := VarArrayLowBound(sBookNames, 1) to VarArrayHighBound(sBookNames, 1) do + begin + If Pos(sBookmarkName, sBookNames[iBookCounter]) = (1 + Length(sBookNames[iBookCounter]) - Length(sBookmarkName)) then + begin + GetBookmarkFromDBPointer := oDoc.Bookmarks.getByName(sBookNames[iBookCounter]); + exit; + end; + end; +end; + +end. + + diff --git a/odk/examples/OLE/delphi/InsertTables/SampleUI.dfm b/odk/examples/OLE/delphi/InsertTables/SampleUI.dfm new file mode 100644 index 000000000..082fce7b7 --- /dev/null +++ b/odk/examples/OLE/delphi/InsertTables/SampleUI.dfm @@ -0,0 +1,4 @@ +ÿ +ParentFont OldCreateOrder PositionpoScreenCenter PixelsPerInch` +TextHeight Table NameTable namedisconnectEnabledTabOrderOnClick OnDisconnectTStatusBar +StatusBar1LeftSimpleTextReady \ No newline at end of file diff --git a/odk/examples/OLE/delphi/InsertTables/SampleUI.pas b/odk/examples/OLE/delphi/InsertTables/SampleUI.pas new file mode 100644 index 000000000..fcd4f4301 --- /dev/null +++ b/odk/examples/OLE/delphi/InsertTables/SampleUI.pas @@ -0,0 +1,168 @@ +{*********************************************************************** + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************} +unit SampleUI; + +interface + +uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, + Buttons, ExtCtrls, SampleCode, ComCtrls; + +type + TOKBottomDlg = class(TForm) + Bevel1: TBevel; + Button1: TButton; + Button2: TButton; + Button3: TButton; + Button4: TButton; + Edit1: TEdit; + Label1: TLabel; + Edit2: TEdit; + Label2: TLabel; + Button5: TButton; + Button6: TButton; + Edit3: TEdit; + Label3: TLabel; + Label4: TLabel; + Label6: TLabel; + Edit6: TEdit; + Bevel2: TBevel; + Bevel3: TBevel; + Bevel4: TBevel; + StatusBar1: TStatusBar; + Edit4: TEdit; + Label7: TLabel; + procedure OnConnect(Sender: TObject); + procedure OnDisconnect(Sender: TObject); + procedure OnCreateDocument(Sender: TObject); + procedure OnInsertTable(Sender: TObject); + procedure OnGetDatabasePointer(Sender: TObject); + procedure OnGetCellContent(Sender: TObject); + private + { Private declarations } + public + { Public declarations } + end; + +var + OKBottomDlg: TOKBottomDlg; + Sample : TSampleCode; +implementation + +{$R *.DFM} + +procedure TOKBottomDlg.OnConnect(Sender: TObject); +begin + StatusBar1.SimpleText := 'Connection to StarOffice ...'; + Sample := TSampleCode.Create(); + if Sample.Connect() then + begin + Button1.Enabled := false; + Button2.Enabled := true; + Button3.Enabled := true; + Button4.Enabled := false; + Button5.Enabled := false; + Button6.Enabled := false; + end; + StatusBar1.SimpleText := 'Ready'; +end; + +procedure TOKBottomDlg.OnDisconnect(Sender: TObject); +begin + StatusBar1.SimpleText := 'Disconnection from StarOffice ...'; + Sample.Disconnect(); + Button1.Enabled := true; + Button2.Enabled := false; + Button3.Enabled := false; + Button4.Enabled := false; + Button5.Enabled := false; + Button6.Enabled := false; + StatusBar1.SimpleText := 'Ready'; +end; + +procedure TOKBottomDlg.OnCreateDocument(Sender: TObject); +begin + StatusBar1.SimpleText := 'Creating new text document ...'; + try + if Sample.CreateDocument(false) then + begin + Button4.Enabled := true; + Button5.Enabled := true; + Button6.Enabled := true; + end; + StatusBar1.SimpleText := 'Ready'; + except + StatusBar1.SimpleText := 'Error'; + end; +end; + +procedure TOKBottomDlg.OnInsertTable(Sender: TObject); +begin + try + StatusBar1.SimpleText := 'Inserting Table ...'; + Sample.InsertTable(Edit2.Text, Edit1.Text); + StatusBar1.SimpleText := 'Ready'; + except + StatusBar1.SimpleText := 'Error'; + end; +end; + +procedure TOKBottomDlg.OnGetDatabasePointer(Sender: TObject); +var + res : String; +begin + try + StatusBar1.SimpleText := 'Getting database pointer ...'; + res := Sample.getDatabasePointer(Edit4.Text, Edit3.Text); + Application.MessageBox(PChar('the pointer: ' + res), PChar('Result'), ID_OK); + StatusBar1.SimpleText := 'Ready'; + except + StatusBar1.SimpleText := 'Error'; + end; +end; + +procedure TOKBottomDlg.OnGetCellContent(Sender: TObject); +var + res : String; +begin + try + StatusBar1.SimpleText := 'Getting cell content ...'; + res := Sample.getCellContent(Edit6.Text); + Application.MessageBox(PChar('the content: ' + res), PChar('Result'), ID_OK); + StatusBar1.SimpleText := 'Ready'; + except + StatusBar1.SimpleText := 'Error'; + end; +end; + +end. diff --git a/odk/examples/OLE/delphi/StarOffice_Delphi.sxw b/odk/examples/OLE/delphi/StarOffice_Delphi.sxw new file mode 100644 index 000000000..77ccc4b77 Binary files /dev/null and b/odk/examples/OLE/delphi/StarOffice_Delphi.sxw differ diff --git a/odk/examples/OLE/delphi/StarOffice_and_Delphi.pdf b/odk/examples/OLE/delphi/StarOffice_and_Delphi.pdf new file mode 100644 index 000000000..92eee437f Binary files /dev/null and b/odk/examples/OLE/delphi/StarOffice_and_Delphi.pdf differ diff --git a/odk/examples/OLE/vbscript/WriterDemo.vbs b/odk/examples/OLE/vbscript/WriterDemo.vbs new file mode 100644 index 000000000..71d011e4f --- /dev/null +++ b/odk/examples/OLE/vbscript/WriterDemo.vbs @@ -0,0 +1,172 @@ +'*********************************************************************** +'* +'* The Contents of this file are made available subject to the terms of +'* the BSD license. +'* +'* Copyright 2000, 2010 Oracle and/or its affiliates. +'* All rights reserved. +'* +'* Redistribution and use in source and binary forms, with or without +'* modification, are permitted provided that the following conditions +'* are met: +'* 1. Redistributions of source code must retain the above copyright +'* notice, this list of conditions and the following disclaimer. +'* 2. Redistributions in binary form must reproduce the above copyright +'* notice, this list of conditions and the following disclaimer in the +'* documentation and/or other materials provided with the distribution. +'* 3. Neither the name of Sun Microsystems, Inc. nor the names of its +'* contributors may be used to endorse or promote products derived +'* from this software without specific prior written permission. +'* +'* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +'* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +'* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +'* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +'* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +'* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +'* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +'* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +'* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +'* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +'* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +'* +'************************************************************************* + +'The service manager is always the starting point +'If there is no office running then an office is started up +Set objServiceManager= WScript.CreateObject("com.sun.star.ServiceManager") + +'Create the CoreReflection service that is later used to create structs +Set objCoreReflection= objServiceManager.createInstance("com.sun.star.reflection.CoreReflection") + +'Create the Desktop +Set objDesktop= objServiceManager.createInstance("com.sun.star.frame.Desktop") + +'Open a new empty writer document +Dim args() +Set objDocument= objDesktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, args) + +'Create a text object +Set objText= objDocument.getText + +'Create a cursor object +Set objCursor= objText.createTextCursor + +'Inserting some Text +objText.insertString objCursor, "The first line in the newly created text document." & vbLf, false + +'Inserting a second line +objText.insertString objCursor, "Now we're in the second line", false + +'Create instance of a text table with 4 columns and 4 rows +Set objTable= objDocument.createInstance( "com.sun.star.text.TextTable") +objTable.initialize 4, 4 + +'Insert the table +objText.insertTextContent objCursor, objTable, false + +'Get first row +Set objRows= objTable.getRows +Set objRow= objRows.getByIndex( 0) + +'Set the table background color +objTable.setPropertyValue "BackTransparent", false +objTable.setPropertyValue "BackColor", 13421823 + +'Set a different background color for the first row +objRow.setPropertyValue "BackTransparent", false +objRow.setPropertyValue "BackColor", 6710932 + +'Fill the first table row +insertIntoCell "A1","FirstColumn", objTable +insertIntoCell "B1","SecondColumn", objTable +insertIntoCell "C1","ThirdColumn", objTable +insertIntoCell "D1","SUM", objTable + +objTable.getCellByName("A2").setValue 22.5 +objTable.getCellByName("B2").setValue 5615.3 +objTable.getCellByName("C2").setValue -2315.7 +objTable.getCellByName("D2").setFormula"sum " + +objTable.getCellByName("A3").setValue 21.5 +objTable.getCellByName("B3").setValue 615.3 +objTable.getCellByName("C3").setValue -315.7 +objTable.getCellByName("D3").setFormula "sum " + +objTable.getCellByName("A4").setValue 121.5 +objTable.getCellByName("B4").setValue -615.3 +objTable.getCellByName("C4").setValue 415.7 +objTable.getCellByName("D4").setFormula "sum " + +'Change the CharColor and add a Shadow +objCursor.setPropertyValue "CharColor", 255 +objCursor.setPropertyValue "CharShadowed", true + +'Create a paragraph break +'The second argument is a com::sun::star::text::ControlCharacter::PARAGRAPH_BREAK constant +objText.insertControlCharacter objCursor, 0 , false + +'Inserting colored Text. +objText.insertString objCursor, " This is a colored Text - blue with shadow" & vbLf, false + +'Create a paragraph break ( ControlCharacter::PARAGRAPH_BREAK). +objText.insertControlCharacter objCursor, 0, false + +'Create a TextFrame. +Set objTextFrame= objDocument.createInstance("com.sun.star.text.TextFrame") + +'Create a Size struct. +Set objSize= createStruct("com.sun.star.awt.Size") +objSize.Width= 15000 +objSize.Height= 400 +objTextFrame.setSize( objSize) + +' TextContentAnchorType.AS_CHARACTER = 1 +objTextFrame.setPropertyValue "AnchorType", 1 + +'insert the frame +objText.insertTextContent objCursor, objTextFrame, false + +'Get the text object of the frame +Set objFrameText= objTextFrame.getText + + +'Create a cursor object +Set objFrameTextCursor= objFrameText.createTextCursor + +'Inserting some Text +objFrameText.insertString objFrameTextCursor, "The first line in the newly created text frame.", _ + false +objFrameText.insertString objFrameTextCursor, _ + vbLf & "With this second line the height of the frame raises.", false + +'Create a paragraph break +'The second argument is a com::sun::star::text::ControlCharacter::PARAGRAPH_BREAK constant +objFrameText.insertControlCharacter objCursor, 0 , false + +'Change the CharColor and add a Shadow +objCursor.setPropertyValue "CharColor", 65536 +objCursor.setPropertyValue "CharShadowed", false + +'Insert another string +objText.insertString objCursor, " That's all for now !!", false + +On Error Resume Next +If Err Then + MsgBox "An error occurred" +End If + + +Sub insertIntoCell( strCellName, strText, objTable) + Set objCellText= objTable.getCellByName( strCellName) + Set objCellCursor= objCellText.createTextCursor + objCellCursor.setPropertyValue "CharColor",16777215 + objCellText.insertString objCellCursor, strText, false +End Sub + +Function createStruct( strTypeName) + Set classSize= objCoreReflection.forName( strTypeName) + Dim aStruct + classSize.createObject aStruct + Set createStruct= aStruct +End Function diff --git a/odk/examples/OLE/vbscript/readme.txt b/odk/examples/OLE/vbscript/readme.txt new file mode 100644 index 000000000..45a982a13 --- /dev/null +++ b/odk/examples/OLE/vbscript/readme.txt @@ -0,0 +1,4 @@ +Run the script in WriterDemo.vbs with Windows Script Host. +Command line: + +cscript WriterDemo.vbs diff --git a/odk/examples/basic/drawing/dirtree.txt b/odk/examples/basic/drawing/dirtree.txt new file mode 100644 index 000000000..9cb9afe6d --- /dev/null +++ b/odk/examples/basic/drawing/dirtree.txt @@ -0,0 +1,20 @@ +Explorer + Workspace + Bookmarks + Database + Macros + StarOffice Math + StarOffice API + ToDo + Translations + Chinese + German + English + French + Italian + Dutch + Portuguese + Swedish + Spanish + Examples + Databases \ No newline at end of file diff --git a/odk/examples/basic/drawing/importexportofasciifiles.odg b/odk/examples/basic/drawing/importexportofasciifiles.odg new file mode 100644 index 000000000..721f9e7b3 Binary files /dev/null and b/odk/examples/basic/drawing/importexportofasciifiles.odg differ diff --git a/odk/examples/basic/forms_and_controls/beef.wmf b/odk/examples/basic/forms_and_controls/beef.wmf new file mode 100644 index 000000000..0947521c0 Binary files /dev/null and b/odk/examples/basic/forms_and_controls/beef.wmf differ diff --git a/odk/examples/basic/forms_and_controls/burger.wmf b/odk/examples/basic/forms_and_controls/burger.wmf new file mode 100644 index 000000000..35b30c394 Binary files /dev/null and b/odk/examples/basic/forms_and_controls/burger.wmf differ diff --git a/odk/examples/basic/forms_and_controls/burger_factory.odt b/odk/examples/basic/forms_and_controls/burger_factory.odt new file mode 100644 index 000000000..8203ea0f0 Binary files /dev/null and b/odk/examples/basic/forms_and_controls/burger_factory.odt differ diff --git a/odk/examples/basic/forms_and_controls/chicken.wmf b/odk/examples/basic/forms_and_controls/chicken.wmf new file mode 100644 index 000000000..6be326d02 Binary files /dev/null and b/odk/examples/basic/forms_and_controls/chicken.wmf differ diff --git a/odk/examples/basic/forms_and_controls/fish.wmf b/odk/examples/basic/forms_and_controls/fish.wmf new file mode 100644 index 000000000..d7060f288 Binary files /dev/null and b/odk/examples/basic/forms_and_controls/fish.wmf differ diff --git a/odk/examples/basic/forms_and_controls/vegetable.wmf b/odk/examples/basic/forms_and_controls/vegetable.wmf new file mode 100644 index 000000000..364d122cf Binary files /dev/null and b/odk/examples/basic/forms_and_controls/vegetable.wmf differ diff --git a/odk/examples/basic/sheet/adapting_to_euroland.ods b/odk/examples/basic/sheet/adapting_to_euroland.ods new file mode 100644 index 000000000..6c1ced5af Binary files /dev/null and b/odk/examples/basic/sheet/adapting_to_euroland.ods differ diff --git a/odk/examples/basic/stock_quotes_updater/stock.ods b/odk/examples/basic/stock_quotes_updater/stock.ods new file mode 100644 index 000000000..5b530b5cd Binary files /dev/null and b/odk/examples/basic/stock_quotes_updater/stock.ods differ diff --git a/odk/examples/basic/text/creating_an_index/index.odt b/odk/examples/basic/text/creating_an_index/index.odt new file mode 100644 index 000000000..7af60ff29 Binary files /dev/null and b/odk/examples/basic/text/creating_an_index/index.odt differ diff --git a/odk/examples/basic/text/creating_an_index/indexlist.txt b/odk/examples/basic/text/creating_an_index/indexlist.txt new file mode 100644 index 000000000..43c548a7e --- /dev/null +++ b/odk/examples/basic/text/creating_an_index/indexlist.txt @@ -0,0 +1,9 @@ +Sun +StarOffice +Solaris +Java +Developer +technology +Administration +countries + diff --git a/odk/examples/basic/text/modifying_text_automatically/changing_appearance.odt b/odk/examples/basic/text/modifying_text_automatically/changing_appearance.odt new file mode 100644 index 000000000..ac718501c Binary files /dev/null and b/odk/examples/basic/text/modifying_text_automatically/changing_appearance.odt differ diff --git a/odk/examples/basic/text/modifying_text_automatically/inserting_bookmarks.odt b/odk/examples/basic/text/modifying_text_automatically/inserting_bookmarks.odt new file mode 100644 index 000000000..aea712f17 Binary files /dev/null and b/odk/examples/basic/text/modifying_text_automatically/inserting_bookmarks.odt differ diff --git a/odk/examples/basic/text/modifying_text_automatically/replacing_text.odt b/odk/examples/basic/text/modifying_text_automatically/replacing_text.odt new file mode 100644 index 000000000..14a3882cc Binary files /dev/null and b/odk/examples/basic/text/modifying_text_automatically/replacing_text.odt differ diff --git a/odk/examples/basic/text/modifying_text_automatically/using_regular_expressions.odt b/odk/examples/basic/text/modifying_text_automatically/using_regular_expressions.odt new file mode 100644 index 000000000..9374b6cb0 Binary files /dev/null and b/odk/examples/basic/text/modifying_text_automatically/using_regular_expressions.odt differ diff --git a/odk/examples/cpp/DocumentLoader/DocumentLoader.cxx b/odk/examples/cpp/DocumentLoader/DocumentLoader.cxx new file mode 100644 index 000000000..7e1f89cf3 --- /dev/null +++ b/odk/examples/cpp/DocumentLoader/DocumentLoader.cxx @@ -0,0 +1,150 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// Simple client application using the UnoUrlResolver service. +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; +using namespace com::sun::star::beans; +using namespace com::sun::star::bridge; +using namespace com::sun::star::frame; +using namespace com::sun::star::registry; + +using ::rtl::OUString; +using ::rtl::OUStringToOString; + + +SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv) +{ + OUString sConnectionString("uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager"); + + sal_Int32 nCount = (sal_Int32)rtl_getAppCommandArgCount(); + + if (nCount < 1) + { + printf("using: DocumentLoader -env:URE_MORE_TYPES= []\n\n" + "example: DocumentLoader -env:URE_MORE_TYPES=\"file:///.../program/offapi.rdb\" \"file:///e:/temp/test.odt\" \"uno:socket,host=localhost,port=2083;urp;StarOffice.ServiceManager\"\n"); + exit(1); + } + if (nCount == 2) + { + rtl_getAppCommandArg(1, &sConnectionString.pData); + } + + Reference< XComponentContext > xComponentContext(::cppu::defaultBootstrap_InitialComponentContext()); + + /* Gets the service manager instance to be used (or null). This method has + been added for convenience, because the service manager is an often used + object. + */ + Reference< XMultiComponentFactory > xMultiComponentFactoryClient( + xComponentContext->getServiceManager() ); + + /* Creates an instance of a component which supports the services specified + by the factory. + */ + Reference< XInterface > xInterface = + xMultiComponentFactoryClient->createInstanceWithContext( + "com.sun.star.bridge.UnoUrlResolver", + xComponentContext ); + + Reference< XUnoUrlResolver > resolver( xInterface, UNO_QUERY ); + + // Resolves the component context from the office, on the uno URL given by argv[1]. + try + { + xInterface = Reference< XInterface >( + resolver->resolve( sConnectionString ), UNO_QUERY ); + } + catch ( Exception& e ) + { + printf("Error: cannot establish a connection using '%s':\n %s\n", + OUStringToOString(sConnectionString, RTL_TEXTENCODING_ASCII_US).getStr(), + OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr()); + exit(1); + } + + // gets the server component context as property of the office component factory + Reference< XPropertySet > xPropSet( xInterface, UNO_QUERY ); + xPropSet->getPropertyValue("DefaultContext") >>= xComponentContext; + + // gets the service manager from the office + Reference< XMultiComponentFactory > xMultiComponentFactoryServer( + xComponentContext->getServiceManager() ); + + /* Creates an instance of a component which supports the services specified + by the factory. Important: using the office component context. + */ + Reference < XDesktop2 > xComponentLoader = Desktop::create(xComponentContext); + + /* Loads a component specified by a URL into the specified new or existing + frame. + */ + OUString sAbsoluteDocUrl, sWorkingDir, sDocPathUrl, sArgDocUrl; + rtl_getAppCommandArg(0, &sArgDocUrl.pData); + + osl_getProcessWorkingDir(&sWorkingDir.pData); + osl::FileBase::getFileURLFromSystemPath( sArgDocUrl, sDocPathUrl); + osl::FileBase::getAbsoluteFileURL( sWorkingDir, sDocPathUrl, sAbsoluteDocUrl); + + Reference< XComponent > xComponent = xComponentLoader->loadComponentFromURL( + sAbsoluteDocUrl, OUString( "_blank" ), 0, + Sequence < ::com::sun::star::beans::PropertyValue >() ); + + // dispose the local service manager + Reference< XComponent >::query( xMultiComponentFactoryClient )->dispose(); + + return 0; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/DocumentLoader/Makefile b/odk/examples/cpp/DocumentLoader/Makefile new file mode 100644 index 000000000..812d13332 --- /dev/null +++ b/odk/examples/cpp/DocumentLoader/Makefile @@ -0,0 +1,107 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the C++ DocumentLoader example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMPONENT_NAME=DocumentLoader + +OUT_COMP_INC = $(OUT_INC)/$(COMPONENT_NAME) +OUT_COMP_GEN = $(OUT_MISC)/$(COMPONENT_NAME) +OUT_COMP_OBJ=$(OUT_OBJ)/$(COMPONENT_NAME) + +CXXFILES = DocumentLoader.cxx + +OBJFILES = $(patsubst %.cxx,$(OUT_SLO_COMP)/%.$(OBJ_EXT),$(CXXFILES)) + +ENV_OFFICE_TYPES=-env:URE_MORE_TYPES=$(URLPREFIX)$(OFFICE_TYPES) + +# Targets +.PHONY: ALL +ALL : \ + CppDocumentLoaderExample + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_OBJ)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +$(OUT_BIN)/DocumentLoader$(EXE_EXT) : $(OUT_COMP_OBJ)/DocumentLoader.$(OBJ_EXT) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)) +ifeq "$(OS)" "WIN" + $(LINK) $(EXE_LINK_FLAGS) /OUT:$@ /MAP:$(OUT_COMP_GEN)/$(basename $(@F)).map \ + $< $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) +else + $(LINK) $(EXE_LINK_FLAGS) $(LINK_LIBS) -o $@ $< \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) $(STDC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS_BIN) $@ +endif +endif + +CppDocumentLoaderExample : $(OUT_BIN)/DocumentLoader$(EXE_EXT) + @echo -------------------------------------------------------------------------------- + @echo The example loads the "$(QM)test.odt$(QM)" document in the DocumentLoader example directory. + @echo If you want to load your own document, please use: + @echo $(SQM) $(SQM)DocumentLoader -env:URE_MORE_TYPES="$(QM)$(QM)" "$(QM)filename$(QM)" [connection_url] + @echo - + @echo Use the following command to execute the example! + @echo - + @echo $(MAKE) DocumentLoader.run + @echo - + @echo NOTE: This example does not use the new UNO bootstrap mechanism, it uses still a socket + @echo $(SQM) $(SQM)connection. The example use the defaultBootstrap_InitialComponentContext method and provides + @echo $(SQM) $(SQM)the additional office types via the UNO environment variable -env:URE_MORE_TYPES=... + @echo $(SQM) $(SQM)Before you can run this example you have to start your office in listening mode. + @echo - + @echo $(SQM) $(SQM)soffice "$(QM)--accept=socket,host=localhost,port=2083;urp;StarOffice.ServiceManager$(QM)" + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_BIN)/DocumentLoader$(EXE_EXT) + cd $(subst /,$(PS),$(OUT_BIN)) && $(basename $@) $(ENV_OFFICE_TYPES) $(subst \\,/,$(subst /,$(PS),"$(OO_SDK_HOME)/examples/cpp/DocumentLoader/test.odt")) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_OBJ)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_BIN)/DocumentLoader*)) diff --git a/odk/examples/cpp/DocumentLoader/test.odt b/odk/examples/cpp/DocumentLoader/test.odt new file mode 100644 index 000000000..dc4efecac Binary files /dev/null and b/odk/examples/cpp/DocumentLoader/test.odt differ diff --git a/odk/examples/cpp/complextoolbarcontrols/Addons.xcu b/odk/examples/cpp/complextoolbarcontrols/Addons.xcu new file mode 100644 index 000000000..786c3ad29 --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/Addons.xcu @@ -0,0 +1,187 @@ + + + + + + + + + vnd.demo.complextoolbarcontrols.demoaddon:ImageButtonCmd + + + Image Button + + + _self + + + com.sun.star.text.TextDocument,com.sun.star.sheet.SpreadsheetDocument + + + ImageButton + + + + + vnd.demo.complextoolbarcontrols.demoaddon:ComboboxCmd + + + ComboBox + + + _self + + + com.sun.star.text.TextDocument,com.sun.star.sheet.SpreadsheetDocument + + + Combobox + + + 200 + + + + + private:separator + + + + + vnd.demo.complextoolbarcontrols.demoaddon:SpinfieldCmd + + + Spinfield + + + _self + + + com.sun.star.text.TextDocument,com.sun.star.sheet.SpreadsheetDocument + + + Spinfield + + + 150 + + + + + private:separator + + + + + vnd.demo.complextoolbarcontrols.demoaddon:EditfieldCmd + + + Editfield + + + _self + + + com.sun.star.text.TextDocument,com.sun.star.sheet.SpreadsheetDocument + + + Editfield + + + 130 + + + + + private:separator + + + + + vnd.demo.complextoolbarcontrols.demoaddon:DropdownboxCmd + + + Dropdownbox + + + _self + + + com.sun.star.text.TextDocument,com.sun.star.sheet.SpreadsheetDocument + + + Dropdownbox + + + 80 + + + + + vnd.demo.complextoolbarcontrols.demoaddon:ToggleDropdownButtonCmd + + + Toggle Dropdown Button + + + _self + + + com.sun.star.text.TextDocument,com.sun.star.sheet.SpreadsheetDocument + + + ToggleDropdownButton + + + + + vnd.demo.complextoolbarcontrols.demoaddon:DropdownButtonCmd + + + Dropdown Button + + + _self + + + com.sun.star.text.TextDocument,com.sun.star.sheet.SpreadsheetDocument + + + DropdownButton + + + + + + + + vnd.demo.complextoolbarcontrols.demoaddon:ImageButtonCmd + + + + %origin%/logo_small.png + + + %origin%/logo_big.png + + + + + + diff --git a/odk/examples/cpp/complextoolbarcontrols/CalcListener.cxx b/odk/examples/cpp/complextoolbarcontrols/CalcListener.cxx new file mode 100644 index 000000000..e02a5d695 --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/CalcListener.cxx @@ -0,0 +1,32 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#include "MyListener.h" +#include + +void SAL_CALL CalcListener::notifyEvent( const ::com::sun::star::document::EventObject& aEvent ) throw (com::sun::star::uno::RuntimeException) +{ +} + +void SAL_CALL CalcListener::disposing( const com::sun::star::lang::EventObject& aSource ) throw( com::sun::star::uno::RuntimeException ) +{ +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/CalcWindowState.xcu b/odk/examples/cpp/complextoolbarcontrols/CalcWindowState.xcu new file mode 100644 index 000000000..4d9f71c29 --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/CalcWindowState.xcu @@ -0,0 +1,38 @@ + + + + + + + + false + + + Complex Toolbar Controls + + + true + + + false + + + + + \ No newline at end of file diff --git a/odk/examples/cpp/complextoolbarcontrols/Jobs.xcu b/odk/examples/cpp/complextoolbarcontrols/Jobs.xcu new file mode 100644 index 000000000..976e48434 --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/Jobs.xcu @@ -0,0 +1,39 @@ + + + + + + + vnd.demo.NewDocListener + + + + + + + + + + + + + + + + diff --git a/odk/examples/cpp/complextoolbarcontrols/ListenerHelper.cxx b/odk/examples/cpp/complextoolbarcontrols/ListenerHelper.cxx new file mode 100644 index 000000000..0ee09734a --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/ListenerHelper.cxx @@ -0,0 +1,138 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include + +#include "ListenerHelper.h" + +using com::sun::star::frame::XFrame; +using com::sun::star::frame::XDispatch; +using com::sun::star::frame::XStatusListener; +using com::sun::star::lang::EventObject; +using com::sun::star::uno::Reference; +using com::sun::star::uno::RuntimeException; +using com::sun::star::frame::FeatureStateEvent; + +static AllListeners aListeners; + +void ListenerHelper::AddListener( + const Reference < XFrame >& xFrame, + const Reference < XStatusListener > xControl, + const ::rtl::OUString& aCommand ) +{ + sal_uInt32 i=0; + sal_uInt32 nSize = aListeners.size(); + for ( i=0; i& xFrame, + const Reference < XStatusListener > xControl, + const ::rtl::OUString& aCommand ) +{ + sal_uInt32 nSize = aListeners.size(); + for ( sal_uInt32 i=0; i& xFrame, + const ::rtl::OUString& aCommand, + FeatureStateEvent& rEvent ) +{ + sal_uInt32 nSize = aListeners.size(); + for ( sal_uInt32 i=0; istatusChanged( rEvent ); + ++aIter; + } + } + } +} + +com::sun::star::uno::Reference < XDispatch > ListenerHelper::GetDispatch( + const Reference < XFrame >& xFrame, + const ::rtl::OUString& aCommand ) +{ + sal_uInt32 nSize = aListeners.size(); + for ( sal_uInt32 i=0; i(); +} + +void ListenerHelper::AddDispatch( + const Reference < XDispatch > xDispatch, + const Reference < XFrame >& xFrame, + const ::rtl::OUString& aCommand ) +{ + ListenerItem aItem; + aItem.xFrame = xFrame; + aItem.xDispatch = xDispatch; + aListeners.push_back( aItem ); + xFrame->addEventListener( new ListenerItemEventListener( xFrame ) ); +} + +void SAL_CALL ListenerItemEventListener::disposing( const EventObject& aEvent) throw (RuntimeException) +{ + AllListeners::iterator aIter = aListeners.begin(); + while ( aIter != aListeners.end() ) + { + if ( (*aIter).xFrame == mxFrame ) + { + aListeners.erase( aIter ); + break; + } + + ++aIter; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/ListenerHelper.h b/odk/examples/cpp/complextoolbarcontrols/ListenerHelper.h new file mode 100644 index 000000000..f24150df7 --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/ListenerHelper.h @@ -0,0 +1,85 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EXAMPLES_COMPLEXTOOLBARCONTROLS_LISTENERHELPER_H +#define INCLUDED_EXAMPLES_COMPLEXTOOLBARCONTROLS_LISTENERHELPER_H + +#include +#include + +#include +#include +#include + +#include +#include + +typedef std::vector < com::sun::star::uno::Reference < com::sun::star::frame::XStatusListener > > StatusListeners; + +typedef std::map < ::rtl::OUString, StatusListeners > ListenerMap; + +// For every frame there is *one* Dispatch object for all possible commands +// this struct contains an array of listeners for every supported command +// these arrays are accessed by a std::map (with the command string as index) +struct ListenerItem +{ + ListenerMap aContainer; + ::com::sun::star::uno::Reference< com::sun::star::frame::XDispatch > xDispatch; + ::com::sun::star::uno::Reference< com::sun::star::frame::XFrame > xFrame; +}; + +typedef std::vector < ListenerItem > AllListeners; + +class ListenerHelper +{ +public: + void AddListener( + const com::sun::star::uno::Reference < com::sun::star::frame::XFrame >& xFrame, + const com::sun::star::uno::Reference < com::sun::star::frame::XStatusListener > xControl, + const ::rtl::OUString& aCommand ); + void RemoveListener( + const com::sun::star::uno::Reference < com::sun::star::frame::XFrame >& xFrame, + const com::sun::star::uno::Reference < com::sun::star::frame::XStatusListener > xControl, + const ::rtl::OUString& aCommand ); + void Notify( + const com::sun::star::uno::Reference < com::sun::star::frame::XFrame >& xFrame, + const ::rtl::OUString& aCommand, + com::sun::star::frame::FeatureStateEvent& rEvent ); + com::sun::star::uno::Reference < com::sun::star::frame::XDispatch > GetDispatch( + const com::sun::star::uno::Reference < com::sun::star::frame::XFrame >& xFrame, + const ::rtl::OUString& aCommand ); + void AddDispatch( + const com::sun::star::uno::Reference < com::sun::star::frame::XDispatch > xDispatch, + const com::sun::star::uno::Reference < com::sun::star::frame::XFrame >& xFrame, + const ::rtl::OUString& aCommand ); +}; + +class ListenerItemEventListener : public cppu::WeakImplHelper1 < ::com::sun::star::lang::XEventListener > +{ + ::com::sun::star::uno::Reference< com::sun::star::frame::XFrame > mxFrame; +public: + ListenerItemEventListener( const com::sun::star::uno::Reference < com::sun::star::frame::XFrame >& xFrame) + : mxFrame(xFrame) + {} + virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& aEvent ) throw (com::sun::star::uno::RuntimeException); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/Makefile b/odk/examples/cpp/complextoolbarcontrols/Makefile new file mode 100644 index 000000000..ad75987cf --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/Makefile @@ -0,0 +1,182 @@ + #************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the complextoolbarcontrols C++ component example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk +include $(SETTINGS)/platform.mk + +# Define non-platform/compiler specific settings +COMP_NAME=complextoolbarcontrols +COMP_IMPL_NAME=$(COMP_NAME).uno.$(SHAREDLIB_EXT) +OUT_COMP_INC=$(OUT_INC)/$(COMP_NAME) +OUT_COMP_GEN=$(OUT_MISC)/$(COMP_NAME) +OUT_COMP_SLO=$(OUT_SLO)/$(COMP_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_UNOPKG_MANIFEST = $(OUT_COMP_GEN)/$(COMP_NAME)/META-INF/manifest.xml +COMP_UNOPKG_DESCRIPTION = $(OUT_COMP_GEN)/$(COMPONENT_NAME)/description.xml +COMP_COMPONENTS = $(OUT_COMP_GEN)/$(COMP_NAME).components +COMP_REGISTERFLAG = $(OUT_MISC)/cpp_$(COMP_NAME)_register_component.flag +COMP_TYPEFLAG = $(OUT_MISC)/cpp_$(COMP_NAME)_types.flag + +CXXFILES = \ + MyProtocolHandler.cxx \ + MyJob.cxx \ + MyListener.cxx \ + WriterListener.cxx \ + CalcListener.cxx \ + ListenerHelper.cxx \ + exports.cxx + +SLOFILES = $(patsubst %.cxx,$(OUT_COMP_SLO)/%.$(OBJ_EXT),$(CXXFILES)) + + +# Targets +.PHONY: ALL +ALL : \ + Example + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_SLO)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(STL_INCLUDES) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + + +ifeq "$(OS)" "WIN" +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)) + $(LINK) $(COMP_LINK_FLAGS) /OUT:$@ \ + /MAP:$(OUT_COMP_GEN)/$(subst $(SHAREDLIB_EXT),map,$(@F)) $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) msvcprt.lib $(LIBO_SDK_LDFLAGS_STDLIBS) + $(LINK_MANIFEST) +else +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(COMP_LINK_FLAGS) $(LINK_LIBS) -o $@ $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS) $@ +endif +endif + +# rule for extension description.xml +$(COMP_UNOPKG_DESCRIPTION) : description.xml + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_CAT) $< | $(SDK_SED) -e "s/#EXTENSION_PLATFORM#/$(EXTENSION_PLATFORM)/" > $@ + +# rule for component package manifest +$(OUT_COMP_GEN)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)Addons.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)WriterWindowState.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)CalcWindowState.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)ProtocolHandler.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components;platform=$(UNOPKG_PLATFORM)$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + +# @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-component;type=native;platform=$(UNOPKG_PLATFORM)$(QM)" >> $@ +# @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(OUT_COMP_GEN)/,,$(UNOPKG_PLATFORM)/$(@D))).uno.$(SHAREDLIB_EXT)$(QM)"/$(CSEP) >> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +$(COMP_COMPONENTS) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)components xmlns="$(QM)http://openoffice.org/2010/uno-components$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)component loader="$(QM)com.sun.star.loader.SharedLibrary$(QM)" uri="$(QM)$(UNOPKG_PLATFORM)/$(COMP_IMPL_NAME)$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)vnd.My.impl.NewDocListener$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)vnd.My.NewDocListener$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)vnd.demo.Impl.ProtocolHandler$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)vnd.demo.ProtocolHandler$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/component$(CSEP) >> $@ + @echo $(OSEP)/components$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(SHAREDLIB_OUT)/$(COMP_IMPL_NAME) Addons.xcu ProtocolHandler.xcu WriterWindowState.xcu CalcWindowState.xcu $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) $(COMP_UNOPKG_DESCRIPTION) + -$(MKDIR) $(subst /,$(PS),$(@D)) && $(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)/$(UNOPKG_PLATFORM)) + $(COPY) $(subst /,$(PS),$<) $(subst /,$(PS),$(OUT_COMP_GEN)/$(UNOPKG_PLATFORM)) + $(CD) $(subst /,$(PS),$(OUT_COMP_GEN)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_NAME).components description.xml + $(CD) $(subst /,$(PS),$(OUT_COMP_GEN)) && $(SDK_ZIP) -u ../../bin/$(@F) $(UNOPKG_PLATFORM)/$( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +Example : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The "$(QM)ProtocolHandler$(QM)" addon component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the example + @echo description. + @echo -------------------------------------------------------------------------------- + +run: $(COMP1_COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" --writer + + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_SLO)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_REGISTERFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_TYPEFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SHAREDLIB_OUT)/$(COMP_NAME).*)) diff --git a/odk/examples/cpp/complextoolbarcontrols/MyJob.cxx b/odk/examples/cpp/complextoolbarcontrols/MyJob.cxx new file mode 100644 index 000000000..656eb6942 --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/MyJob.cxx @@ -0,0 +1,97 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#include "MyJob.h" + +#include +#include +#include +#include + +using rtl::OUString; +using com::sun::star::uno::Sequence; +using com::sun::star::uno::Reference; +using com::sun::star::uno::Any; +using com::sun::star::uno::UNO_QUERY; +using com::sun::star::uno::XInterface; +using com::sun::star::uno::Exception; +using com::sun::star::uno::RuntimeException; +using com::sun::star::lang::IllegalArgumentException; +using com::sun::star::lang::XMultiServiceFactory; +using com::sun::star::beans::NamedValue; +using com::sun::star::document::XEventBroadcaster; + +Any SAL_CALL MyJob::execute( const Sequence< NamedValue >& aArguments ) + throw ( IllegalArgumentException, Exception, RuntimeException ) +{ + Reference < XEventBroadcaster > xBrd( mxMSF->createInstance( + "com.sun.star.frame.GlobalEventBroadcaster" ), UNO_QUERY ); + Reference < com::sun::star::document::XEventListener > xLstner( mxMSF->createInstance( + "com.sun.star.comp.Office.MyListener" ), UNO_QUERY ); + if ( xBrd.is() ) + xBrd->addEventListener( xLstner ); + return Any(); +} + +OUString MyJob_getImplementationName () + throw (RuntimeException) +{ + return OUString( "com.sun.star.comp.Office.MyJob" ); +} + +#define SERVICE_NAME "com.sun.star.task.Job" + +Sequence< OUString > SAL_CALL MyJob_getSupportedServiceNames( ) + throw (RuntimeException) +{ + Sequence < OUString > aRet(1); + OUString* pArray = aRet.getArray(); + pArray[0] = OUString( SERVICE_NAME ); + return aRet; +} + +#undef SERVICE_NAME + +Reference< XInterface > SAL_CALL MyJob_createInstance( const Reference< XMultiServiceFactory > & rSMgr) + throw( Exception ) +{ + return (cppu::OWeakObject*) new MyJob( rSMgr ); +} + +// XServiceInfo +OUString SAL_CALL MyJob::getImplementationName( ) + throw (RuntimeException) +{ + return MyJob_getImplementationName(); +} + +sal_Bool SAL_CALL MyJob::supportsService( const OUString& rServiceName ) + throw (RuntimeException) +{ + return cppu::supportsService(this, rServiceName); +} + +Sequence< OUString > SAL_CALL MyJob::getSupportedServiceNames( ) + throw (RuntimeException) +{ + return MyJob_getSupportedServiceNames(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/MyJob.h b/odk/examples/cpp/complextoolbarcontrols/MyJob.h new file mode 100644 index 000000000..0741e5eed --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/MyJob.h @@ -0,0 +1,91 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EXAMPLES_COMPLEXTOOLBARCONTROLS_MYJOB_H +#define INCLUDED_EXAMPLES_COMPLEXTOOLBARCONTROLS_MYJOB_H + +#include +#include +#include +#include +#include + +namespace com +{ + namespace sun + { + namespace star + { + namespace frame + { + class XModel; + class XFrame; + } + namespace beans + { + struct NamedValue; + } + } + } +} + +class MyJob : public cppu::WeakImplHelper2 +< + com::sun::star::task::XJob, + com::sun::star::lang::XServiceInfo +> +{ +private: + ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF; + +public: + MyJob( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > &rxMSF) + : mxMSF( rxMSF ) {} + virtual ~MyJob() {} + + // XJob + virtual ::com::sun::star::uno::Any SAL_CALL execute( + const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& Arguments ) + throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); + + // 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); +}; + +::rtl::OUString MyJob_getImplementationName() + throw ( ::com::sun::star::uno::RuntimeException ); + +sal_Bool SAL_CALL MyJob_supportsService( const ::rtl::OUString& ServiceName ) + throw ( ::com::sun::star::uno::RuntimeException ); + +::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL MyJob_getSupportedServiceNames( ) + throw ( ::com::sun::star::uno::RuntimeException ); + +::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > +SAL_CALL MyJob_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr) + throw ( ::com::sun::star::uno::Exception ); + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/MyListener.cxx b/odk/examples/cpp/complextoolbarcontrols/MyListener.cxx new file mode 100644 index 000000000..82f8d01a3 --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/MyListener.cxx @@ -0,0 +1,134 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#include "MyListener.h" +#include +#include +#include +#include +#include + +MyListener::MyListener(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR) + : m_xSMGR(xSMGR) +{} + +MyListener::~MyListener() +{} + +css::uno::Any SAL_CALL MyListener::execute(const css::uno::Sequence< css::beans::NamedValue >& lArguments) + throw (css::lang::IllegalArgumentException, + css::uno::Exception, + css::uno::RuntimeException) +{ + css::uno::Sequence< css::beans::NamedValue > lEnv; + + sal_Int32 i = 0; + sal_Int32 c = lArguments.getLength(); + const css::beans::NamedValue* p = lArguments.getConstArray(); + for (i=0; i>= lEnv; + break; + } + } + + css::uno::Reference< css::frame::XModel > xModel; + + c = lEnv.getLength(); + p = lEnv.getConstArray(); + for (i=0; i>= xModel; + break; + } + if ( p[i].Name == "Frame" ) + { + css::uno::Reference< css::frame::XController > xController; + css::uno::Reference< css::frame::XFrame > xFrame; + p[i].Value >>= xFrame; + if (xFrame.is()) + xController = xFrame->getController(); + if (xController.is()) + xModel = xController->getModel(); + break; + } + } + + if (!xModel.is()) + return css::uno::Any(); + + css::uno::Reference< css::lang::XServiceInfo > xInfo(xModel, css::uno::UNO_QUERY); + sal_Bool bCalc = xInfo->supportsService("com.sun.star.sheet.SpreadsheetDocument"); + sal_Bool bWriter = ( xInfo->supportsService("com.sun.star.text.TextDocument") && + !xInfo->supportsService("com.sun.star.text.WebDocument") && + !xInfo->supportsService("com.sun.star.text.GlobalDocument") ); + + // We are interested only in Writer and Calc. However, here we are + // notified of all newly opened Documents... + if (!bCalc && !bWriter) + return css::uno::Any(); + + void* pListener = 0; + if (bCalc) + pListener = (void*)(new CalcListener(m_xSMGR)); + else + if (bWriter) + pListener = (void*)(new WriterListener(m_xSMGR)); + + css::uno::Reference< css::document::XEventListener > xDocListener (static_cast< css::document::XEventListener* >(pListener), css::uno::UNO_QUERY); + css::uno::Reference< css::document::XEventBroadcaster > xDocBroadcaster (xModel , css::uno::UNO_QUERY); + + xDocBroadcaster->addEventListener(xDocListener); + + return css::uno::Any(); +} + +::rtl::OUString SAL_CALL MyListener::getImplementationName() + throw (css::uno::RuntimeException) +{ + return ::rtl::OUString( MYLISTENER_IMPLEMENTATIONNAME ); +} + +css::uno::Sequence< ::rtl::OUString > SAL_CALL MyListener::getSupportedServiceNames() + throw (css::uno::RuntimeException) +{ + css::uno::Sequence< ::rtl::OUString > lNames(1); + lNames[0] = ::rtl::OUString( MYLISTENER_SERVICENAME ); + return lNames; +} + +sal_Bool SAL_CALL MyListener::supportsService(const ::rtl::OUString& sServiceName) + throw (css::uno::RuntimeException) +{ + return cppu::supportsService(this, sServiceName); +} + +css::uno::Reference< css::uno::XInterface > MyListener::st_createInstance(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR) +{ + MyListener* pListener = new MyListener(xSMGR); + css::uno::Reference< css::uno::XInterface > xListener(static_cast< css::task::XJob* >(pListener), css::uno::UNO_QUERY); + return xListener; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/MyListener.h b/odk/examples/cpp/complextoolbarcontrols/MyListener.h new file mode 100644 index 000000000..428693dac --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/MyListener.h @@ -0,0 +1,116 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EXAMPLES_COMPLEXTOOLBARCONTROLS_MYLISTENER_H +#define INCLUDED_EXAMPLES_COMPLEXTOOLBARCONTROLS_MYLISTENER_H + +#include + +#include +#include +#include +#include +#include +#include +#include + +#define MYLISTENER_IMPLEMENTATIONNAME "vnd.My.impl.NewDocListener" +#define MYLISTENER_SERVICENAME "vnd.My.NewDocListener" + +/** + * Register in the Office configuration as job. + * This is called automatically for all new opened documents. You receive + * a reference of the opened document and then you can check if it's a + * supported format. (We are only interested in Writer/Calc documents.) + * + * @see CalcListener + * @see WriterListener + */ +class MyListener : public cppu::WeakImplHelper2< css::task::XJob , + css::lang::XServiceInfo > +{ + private: + css::uno::Reference< css::lang::XMultiServiceFactory > m_xSMGR; + public: + MyListener(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR); + virtual ~MyListener(); + + // XJob + virtual css::uno::Any SAL_CALL execute(const css::uno::Sequence< css::beans::NamedValue >& lArguments) + throw (css::lang::IllegalArgumentException, + css::uno::Exception, + css::uno::RuntimeException); + + // 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); + + public: + + static css::uno::Reference< css::uno::XInterface > st_createInstance(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR); +}; + +class CalcListener : public cppu::WeakImplHelper1< css::document::XEventListener > +{ + private: + ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mxMSF; + + + public: + CalcListener(const css::uno::Reference< css::lang::XMultiServiceFactory > &rxMSF) + : mxMSF( rxMSF ) + {} + + virtual ~CalcListener() + {} + + // document.XEventListener + virtual void SAL_CALL notifyEvent(const css::document::EventObject& aEvent) + throw (css::uno::RuntimeException); + virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent) + throw (css::uno::RuntimeException); +}; + +class WriterListener : public cppu::WeakImplHelper1< css::document::XEventListener > +{ + private: + css::uno::Reference< css::lang::XMultiServiceFactory > mxMSF; + + public: + WriterListener(const css::uno::Reference< css::lang::XMultiServiceFactory >& rxMSF); + + virtual ~WriterListener() + {} + + // document.XEventListener + virtual void SAL_CALL notifyEvent(const css::document::EventObject& aEvent) + throw (css::uno::RuntimeException); + virtual void SAL_CALL disposing(const css::lang::EventObject& aEvent) + throw (css::uno::RuntimeException); +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/MyProtocolHandler.cxx b/odk/examples/cpp/complextoolbarcontrols/MyProtocolHandler.cxx new file mode 100644 index 000000000..4020953b6 --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/MyProtocolHandler.cxx @@ -0,0 +1,501 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#include "ListenerHelper.h" +#include "MyProtocolHandler.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace com::sun::star::awt; +using namespace com::sun::star::frame; +using namespace com::sun::star::system; +using namespace com::sun::star::uno; + +using com::sun::star::beans::NamedValue; +using com::sun::star::beans::PropertyValue; +using com::sun::star::sheet::XSpreadsheetView; +using com::sun::star::text::XTextViewCursorSupplier; +using com::sun::star::util::URL; + +ListenerHelper aListenerHelper; + +void BaseDispatch::ShowMessageBox( const Reference< XFrame >& rFrame, const ::rtl::OUString& aTitle, const ::rtl::OUString& aMsgText ) +{ + if ( !mxToolkit.is() ) + mxToolkit = Toolkit::create(mxContext); + Reference< XMessageBoxFactory > xMsgBoxFactory( mxToolkit, UNO_QUERY ); + if ( rFrame.is() && xMsgBoxFactory.is() ) + { + Reference< XMessageBox > xMsgBox = xMsgBoxFactory->createMessageBox( + Reference< XWindowPeer >( rFrame->getContainerWindow(), UNO_QUERY ), + com::sun::star::awt::MessageBoxType_INFOBOX, + MessageBoxButtons::BUTTONS_OK, + aTitle, + aMsgText ); + + if ( xMsgBox.is() ) + xMsgBox->execute(); + } +} + +void BaseDispatch::SendCommand( const com::sun::star::util::URL& aURL, const ::rtl::OUString& rCommand, const Sequence< NamedValue >& rArgs, sal_Bool bEnabled ) +{ + Reference < XDispatch > xDispatch = + aListenerHelper.GetDispatch( mxFrame, aURL.Path ); + + FeatureStateEvent aEvent; + + aEvent.FeatureURL = aURL; + aEvent.Source = xDispatch; + aEvent.IsEnabled = bEnabled; + aEvent.Requery = sal_False; + + ControlCommand aCtrlCmd; + aCtrlCmd.Command = rCommand; + aCtrlCmd.Arguments = rArgs; + + aEvent.State <<= aCtrlCmd; + aListenerHelper.Notify( mxFrame, aEvent.FeatureURL.Path, aEvent ); +} + +void BaseDispatch::SendCommandTo( const Reference< XStatusListener >& xControl, const URL& aURL, const ::rtl::OUString& rCommand, const Sequence< NamedValue >& rArgs, sal_Bool bEnabled ) +{ + FeatureStateEvent aEvent; + + aEvent.FeatureURL = aURL; + aEvent.Source = (::com::sun::star::frame::XDispatch*) this; + aEvent.IsEnabled = bEnabled; + aEvent.Requery = sal_False; + + ControlCommand aCtrlCmd; + aCtrlCmd.Command = rCommand; + aCtrlCmd.Arguments = rArgs; + + aEvent.State <<= aCtrlCmd; + xControl->statusChanged( aEvent ); +} + +void SAL_CALL MyProtocolHandler::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException) +{ + Reference < XFrame > xFrame; + if ( aArguments.getLength() ) + { + // the first Argument is always the Frame, as a ProtocolHandler needs to have access + // to the context in which it is invoked. + aArguments[0] >>= xFrame; + mxFrame = xFrame; + } +} + +Reference< XDispatch > SAL_CALL MyProtocolHandler::queryDispatch( const URL& aURL, const ::rtl::OUString& sTargetFrameName, sal_Int32 nSearchFlags ) + throw( RuntimeException ) +{ + Reference < XDispatch > xRet; + if ( !mxFrame.is() ) + return 0; + + Reference < XController > xCtrl = mxFrame->getController(); + if ( xCtrl.is() && aURL.Protocol == "vnd.demo.complextoolbarcontrols.demoaddon:" ) + { + Reference < XTextViewCursorSupplier > xCursor( xCtrl, UNO_QUERY ); + Reference < XSpreadsheetView > xView( xCtrl, UNO_QUERY ); + if ( !xCursor.is() && !xView.is() ) + // without an appropriate corresponding document the handler doesn't function + return xRet; + + if ( aURL.Path == "ImageButtonCmd" || + aURL.Path == "ComboboxCmd" || + aURL.Path == "ToggleDropdownButtonCmd" || + aURL.Path == "DropdownButtonCmd" || + aURL.Path == "SpinfieldCmd" || + aURL.Path == "EditfieldCmd" || + aURL.Path == "DropdownboxCmd" ) + { + xRet = aListenerHelper.GetDispatch( mxFrame, aURL.Path ); + if ( !xRet.is() ) + { + xRet = xCursor.is() ? (BaseDispatch*) new WriterDispatch( mxContext, mxFrame ) : + (BaseDispatch*) new CalcDispatch( mxContext, mxFrame ); + aListenerHelper.AddDispatch( xRet, mxFrame, aURL.Path ); + } + } + } + + return xRet; +} + +Sequence < Reference< XDispatch > > SAL_CALL MyProtocolHandler::queryDispatches( const Sequence < DispatchDescriptor >& seqDescripts ) + throw( RuntimeException ) +{ + sal_Int32 nCount = seqDescripts.getLength(); + Sequence < Reference < XDispatch > > lDispatcher( nCount ); + + for( sal_Int32 i=0; i SAL_CALL MyProtocolHandler_getSupportedServiceNames( ) + throw (RuntimeException) +{ + Sequence < ::rtl::OUString > aRet(1); + aRet[0] = ::rtl::OUString( MYPROTOCOLHANDLER_SERVICENAME ); + return aRet; +} + +#undef SERVICE_NAME + +Reference< XInterface > SAL_CALL MyProtocolHandler_createInstance( const Reference< XComponentContext > & rSMgr) + throw( Exception ) +{ + return (cppu::OWeakObject*) new MyProtocolHandler( rSMgr ); +} + +// XServiceInfo +::rtl::OUString SAL_CALL MyProtocolHandler::getImplementationName( ) + throw (RuntimeException) +{ + return MyProtocolHandler_getImplementationName(); +} + +sal_Bool SAL_CALL MyProtocolHandler::supportsService( const ::rtl::OUString& rServiceName ) + throw (RuntimeException) +{ + return cppu::supportsService(this, rServiceName); +} + +Sequence< ::rtl::OUString > SAL_CALL MyProtocolHandler::getSupportedServiceNames( ) + throw (RuntimeException) +{ + return MyProtocolHandler_getSupportedServiceNames(); +} + +void SAL_CALL BaseDispatch::dispatch( const URL& aURL, const Sequence < PropertyValue >& lArgs ) throw (RuntimeException) +{ + /* It's necessary to hold this object alive, till this method finishes. + May the outside dispatch cache (implemented by the menu/toolbar!) + forget this instance during de-/activation of frames (focus!). + + E.g. An open db beamer in combination with the My-Dialog + can force such strange situation :-( + */ + Reference< XInterface > xSelfHold(static_cast< XDispatch* >(this), UNO_QUERY); + + if ( aURL.Protocol == "vnd.demo.complextoolbarcontrols.demoaddon:" ) + { + if ( aURL.Path == "ImageButtonCmd" ) + { + // open the LibreOffice web page + ::rtl::OUString sURL("http://www.libreoffice.org"); + Reference< XSystemShellExecute > xSystemShellExecute( + SystemShellExecute::create(mxContext) ); + try + { + xSystemShellExecute->execute( sURL, ::rtl::OUString(), SystemShellExecuteFlags::URIS_ONLY ); + } + catch( Exception& rEx ) + { + (void)rEx; + } + } + else if ( aURL.Path == "ComboboxCmd" ) + { + // remove the text if it's in our list + Sequence< NamedValue > aRemoveArgs( 1 ); + aRemoveArgs[0].Name = rtl::OUString( "Text" ); + aRemoveArgs[0].Value <<= maComboBoxText; + SendCommand( aURL, ::rtl::OUString( "RemoveEntryText" ), aRemoveArgs, sal_True ); + + // add the new text to the start of the list + Sequence< NamedValue > aInsertArgs( 2 ); + aInsertArgs[0].Name = rtl::OUString( "Pos" ); + aInsertArgs[0].Value <<= sal_Int32( 0 ); + aInsertArgs[1].Name = rtl::OUString( "Text" ); + aInsertArgs[1].Value <<= maComboBoxText; + SendCommand( aURL, ::rtl::OUString("InsertEntry"), aInsertArgs, sal_True ); + } + else if ( aURL.Path == "InsertEntry" ) + { + // Retrieve the text argument from the sequence property value + rtl::OUString aText; + for ( sal_Int32 i = 0; i < lArgs.getLength(); i++ ) + { + if ( lArgs[i].Name == "Text" ) + { + lArgs[i].Value >>= aText; + break; + } + } + + // create new URL to address the combox box + URL aCmdURL; + aCmdURL.Path = "ComboboxCmd"; + aCmdURL.Protocol = "vnd.demo.complextoolbarcontrols.demoaddon:"; + aCmdURL.Complete = aCmdURL.Path + aCmdURL.Protocol; + + // set the selected item as text into the combobox + Sequence< NamedValue > aArgs( 1 ); + aArgs[0].Name = "Text"; + aArgs[0].Value <<= aText; + SendCommand( aCmdURL, ::rtl::OUString( "SetText" ), aArgs, sal_True ); + } + else if ( aURL.Path == "DropdownButtonCmd" ) + { + // Retrieve the text argument from the sequence property value + rtl::OUString aText; + for ( sal_Int32 i = 0; i < lArgs.getLength(); i++ ) + { + if ( lArgs[i].Name == "Text" ) + { + lArgs[i].Value >>= aText; + break; + } + } + + // just enable this command + + // set enable flag according to selection + if ( aText == "Button Disabled" ) + mbButtonEnabled = sal_False; + else + mbButtonEnabled = sal_True; + + // create new URL to address the image button + URL aCmdURL; + aCmdURL.Path = "Command1"; + aCmdURL.Protocol = "vnd.demo.complextoolbarcontrols.demoaddon:"; + aCmdURL.Complete = aCmdURL.Path + aCmdURL.Protocol; + + // create and initialize FeatureStateEvent with IsEnabled + ::com::sun::star::frame::FeatureStateEvent aEvent; + aEvent.FeatureURL = aCmdURL; + aEvent.Source = (::com::sun::star::frame::XDispatch*) this; + aEvent.IsEnabled = mbButtonEnabled; + aEvent.Requery = sal_False; + aEvent.State = Any(); + + // Notify listener about new state + Reference < XDispatch > xDispatch = aListenerHelper.GetDispatch( mxFrame, aURL.Path ); + aListenerHelper.Notify( mxFrame, aEvent.FeatureURL.Path, aEvent ); + } + else if ( aURL.Path == "SpinfieldCmd" ) + { + } + else if ( aURL.Path == "DropdownboxCmd" ) + { + // Retrieve the text argument from the sequence property value + rtl::OUString aText; + for ( sal_Int32 i = 0; i < lArgs.getLength(); i++ ) + { + if ( lArgs[i].Name == "Text" ) + { + lArgs[i].Value >>= aText; + break; + } + } + } + } +} + +void SAL_CALL BaseDispatch::addStatusListener( const Reference< XStatusListener >& xControl, const URL& aURL ) throw (RuntimeException) +{ + if ( aURL.Protocol == "vnd.demo.complextoolbarcontrols.demoaddon:" ) + { + if ( aURL.Path == "ImageButtonCmd" ) + { + // just enable this command + ::com::sun::star::frame::FeatureStateEvent aEvent; + aEvent.FeatureURL = aURL; + aEvent.Source = (::com::sun::star::frame::XDispatch*) this; + aEvent.IsEnabled = mbButtonEnabled; + aEvent.Requery = sal_False; + aEvent.State = Any(); + xControl->statusChanged( aEvent ); + } + else if ( aURL.Path == "ComboboxCmd" ) + { + // just enable this command + ::com::sun::star::frame::FeatureStateEvent aEvent; + aEvent.FeatureURL = aURL; + aEvent.Source = (::com::sun::star::frame::XDispatch*) this; + aEvent.IsEnabled = sal_True; + aEvent.Requery = sal_False; + aEvent.State = Any(); + xControl->statusChanged( aEvent ); + } + else if ( aURL.Path == "ToggleDropdownButtonCmd" ) + { + // A toggle dropdown box is normally used for a group of commands + // where the user can select the last issued command easily. + // E.g. a typical command group would be "Insert shape" + Sequence< NamedValue > aArgs( 1 ); + + // send command to set context menu content + Sequence< rtl::OUString > aContextMenu( 3 ); + aContextMenu[0] = "Command 1"; + aContextMenu[1] = "Command 2"; + aContextMenu[2] = "Command 3"; + + aArgs[0].Name = "List"; + aArgs[0].Value <<= aContextMenu; + SendCommandTo( xControl, aURL, rtl::OUString( "SetList" ), aArgs, sal_True ); + + // send command to check item on pos=0 + aArgs[0].Name = rtl::OUString( "Pos" ); + aArgs[0].Value <<= sal_Int32( 0 ); + SendCommandTo( xControl, aURL, ::rtl::OUString( "CheckItemPos" ), aArgs, sal_True ); + } + else if ( aURL.Path == "DropdownButtonCmd" ) + { + // A dropdown box is normally used for a group of dependent modes, where + // the user can only select one. The modes cannot be combined. + // E.g. a typical group would be left,right,center,block. + Sequence< NamedValue > aArgs( 1 ); + + // send command to set context menu content + Sequence< rtl::OUString > aContextMenu( 2 ); + aContextMenu[0] = "Button Enabled"; + aContextMenu[1] = "Button Disabled"; + + aArgs[0].Name = "List"; + aArgs[0].Value <<= aContextMenu; + SendCommandTo( xControl, aURL, rtl::OUString( "SetList" ), aArgs, sal_True ); + + // set position according to enable/disable state of button + sal_Int32 nPos( mbButtonEnabled ? 0 : 1 ); + + // send command to check item on pos=0 + aArgs[0].Name = "Pos"; + aArgs[0].Value <<= nPos; + SendCommandTo( xControl, aURL, ::rtl::OUString( "CheckItemPos" ), aArgs, sal_True ); + } + else if ( aURL.Path == "SpinfieldCmd" ) + { + // A spin button + Sequence< NamedValue > aArgs( 5 ); + + // send command to initialize spin button + aArgs[0].Name = "Value"; + aArgs[0].Value <<= double( 0.0 ); + aArgs[1].Name = "UpperLimit"; + aArgs[1].Value <<= double( 10.0 ); + aArgs[2].Name = "LowerLimit"; + aArgs[2].Value <<= double( 0.0 ); + aArgs[3].Name = "Step"; + aArgs[3].Value <<= double( 0.1 ); + aArgs[4].Name = "OutputFormat"; + aArgs[4].Value <<= rtl::OUString("%.2f cm"); + + SendCommandTo( xControl, aURL, rtl::OUString( "SetValues" ), aArgs, sal_True ); + } + else if ( aURL.Path == "DropdownboxCmd" ) + { + // A dropdown box is normally used for a group of commands + // where the user can select one of a defined set. + Sequence< NamedValue > aArgs( 1 ); + + // send command to set context menu content + Sequence< rtl::OUString > aList( 10 ); + aList[0] = "White"; + aList[1] = "Black"; + aList[2] = "Red"; + aList[3] = "Blue"; + aList[4] = "Green"; + aList[5] = "Grey"; + aList[6] = "Yellow"; + aList[7] = "Orange"; + aList[8] = "Brown"; + aList[9] = "Pink"; + + aArgs[0].Name = "List"; + aArgs[0].Value <<= aList; + SendCommandTo( xControl, aURL, rtl::OUString( "SetList" ), aArgs, sal_True ); + } + + aListenerHelper.AddListener( mxFrame, xControl, aURL.Path ); + } +} + +void SAL_CALL BaseDispatch::removeStatusListener( const Reference< XStatusListener >& xControl, const URL& aURL ) throw (RuntimeException) +{ + aListenerHelper.RemoveListener( mxFrame, xControl, aURL.Path ); +} + +void SAL_CALL BaseDispatch::controlEvent( const ControlEvent& Event ) throw (RuntimeException) +{ + if ( Event.aURL.Protocol == "vnd.demo.complextoolbarcontrols.demoaddon:" ) + { + if ( Event.aURL.Path == "ComboboxCmd" ) + { + // We get notifications whenever the text inside the combobox has been changed. + // We store the new text into a member. + if ( Event.Event == "TextChanged" ) + { + rtl::OUString aNewText; + sal_Bool bHasText( sal_False ); + for ( sal_Int32 i = 0; i < Event.aInformation.getLength(); i++ ) + { + if ( Event.aInformation[i].Name == "Text" ) + { + bHasText = Event.aInformation[i].Value >>= aNewText; + break; + } + } + + if ( bHasText ) + maComboBoxText = aNewText; + } + } + } +} + +BaseDispatch::BaseDispatch( const Reference< XComponentContext > &rxContext, + const Reference< XFrame >& xFrame, + const ::rtl::OUString& rServiceName ) + : mxContext( rxContext ) + , mxFrame( xFrame ) + , msDocService( rServiceName ) + , mbButtonEnabled( sal_True ) +{ +} + +BaseDispatch::~BaseDispatch() +{ + mxFrame.clear(); + mxContext.clear(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/MyProtocolHandler.h b/odk/examples/cpp/complextoolbarcontrols/MyProtocolHandler.h new file mode 100644 index 000000000..4ee22a0fe --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/MyProtocolHandler.h @@ -0,0 +1,161 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EXAMPLES_COMPLEXTOOLBARCONTROLS_MYPROTOCOLHANDLER_H +#define INCLUDED_EXAMPLES_COMPLEXTOOLBARCONTROLS_MYPROTOCOLHANDLER_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#define MYPROTOCOLHANDLER_IMPLEMENTATIONNAME "vnd.demo.Impl.ProtocolHandler" +#define MYPROTOCOLHANDLER_SERVICENAME "vnd.demo.ProtocolHandler" + +namespace com +{ + namespace sun + { + namespace star + { + namespace frame + { + class XModel; + class XFrame; + } + namespace uno { class XComponentContext; } + } + } +} + + +class MyProtocolHandler : public cppu::WeakImplHelper3 +< + com::sun::star::frame::XDispatchProvider, + com::sun::star::lang::XInitialization, + com::sun::star::lang::XServiceInfo +> +{ +private: + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mxContext; + ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; + +public: + MyProtocolHandler( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > &rxContext) + : mxContext( rxContext ) {} + + // XDispatchProvider + virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > + SAL_CALL queryDispatch( const ::com::sun::star::util::URL& aURL, + const ::rtl::OUString& sTargetFrameName, sal_Int32 nSearchFlags ) + throw( ::com::sun::star::uno::RuntimeException ); + virtual ::com::sun::star::uno::Sequence < ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > + SAL_CALL queryDispatches( + const ::com::sun::star::uno::Sequence < ::com::sun::star::frame::DispatchDescriptor >& seqDescriptor ) + 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); + + // 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); +}; + +::rtl::OUString MyProtocolHandler_getImplementationName() + throw ( ::com::sun::star::uno::RuntimeException ); + +sal_Bool SAL_CALL MyProtocolHandler_supportsService( const ::rtl::OUString& ServiceName ) + throw ( ::com::sun::star::uno::RuntimeException ); + +::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL MyProtocolHandler_getSupportedServiceNames( ) + throw ( ::com::sun::star::uno::RuntimeException ); + +::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > +SAL_CALL MyProtocolHandler_createInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > & rContext) + throw ( ::com::sun::star::uno::Exception ); + +class BaseDispatch : public cppu::WeakImplHelper2 +< + ::com::sun::star::frame::XDispatch, + ::com::sun::star::frame::XControlNotificationListener +> +{ +protected: + ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > mxFrame; + ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mxContext; + ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit2 > mxToolkit; + ::rtl::OUString msDocService; + ::rtl::OUString maComboBoxText; + sal_Bool mbButtonEnabled; + +public: + BaseDispatch( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > &rxContext, + const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame, const ::rtl::OUString& rServiceName ); + + virtual ~BaseDispatch(); + + void ShowMessageBox( const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aTitle, const ::rtl::OUString& aMsgText ); + void SendCommand( const com::sun::star::util::URL& aURL, const ::rtl::OUString& rCommand, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rArgs, sal_Bool bEnabled ); + void SendCommandTo( const com::sun::star::uno::Reference< com::sun::star::frame::XStatusListener >& xControl, const com::sun::star::util::URL& aURL, const ::rtl::OUString& rCommand, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rArgs, sal_Bool bEnabled ); + + // XDispatch + virtual void SAL_CALL dispatch( const ::com::sun::star::util::URL& aURL, + const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lArgs ) + throw (::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL addStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, + const ::com::sun::star::util::URL& aURL ) throw (::com::sun::star::uno::RuntimeException); + virtual void SAL_CALL removeStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& xControl, + const ::com::sun::star::util::URL& aURL ) throw (::com::sun::star::uno::RuntimeException); + + // XControlNotificationListener + virtual void SAL_CALL controlEvent( const ::com::sun::star::frame::ControlEvent& Event ) + throw (::com::sun::star::uno::RuntimeException); +}; + +class WriterDispatch : public BaseDispatch +{ +public: + WriterDispatch( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > &rxContext, + const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame ) + : BaseDispatch( rxContext, xFrame, rtl::OUString( "com.sun.star.text.TextDocument" ) ) + {} +}; + +class CalcDispatch : public BaseDispatch +{ +public: + CalcDispatch( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > &rxContext, + const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame ) + : BaseDispatch( rxContext, xFrame, rtl::OUString( "com.sun.star.sheet.SpreadSheetDocument" ) ) + {} +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/ProtocolHandler.xcu b/odk/examples/cpp/complextoolbarcontrols/ProtocolHandler.xcu new file mode 100644 index 000000000..293e0185c --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/ProtocolHandler.xcu @@ -0,0 +1,27 @@ + + + + + + + vnd.demo.complextoolbarcontrols.demoaddon:* + + + + diff --git a/odk/examples/cpp/complextoolbarcontrols/WriterListener.cxx b/odk/examples/cpp/complextoolbarcontrols/WriterListener.cxx new file mode 100644 index 000000000..31be46c6a --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/WriterListener.cxx @@ -0,0 +1,40 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#include "MyListener.h" + + +#include + +void SAL_CALL WriterListener::notifyEvent( const ::com::sun::star::document::EventObject& aEvent ) throw (com::sun::star::uno::RuntimeException) +{ +} + +void SAL_CALL WriterListener::disposing( const com::sun::star::lang::EventObject& aSource ) throw( com::sun::star::uno::RuntimeException ) +{ +} + +WriterListener::WriterListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > &rxMSF) + : mxMSF( rxMSF ) +{ +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/WriterWindowState.xcu b/odk/examples/cpp/complextoolbarcontrols/WriterWindowState.xcu new file mode 100644 index 000000000..e590f6545 --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/WriterWindowState.xcu @@ -0,0 +1,38 @@ + + + + + + + + false + + + Complex Toolbar Controls + + + true + + + false + + + + + \ No newline at end of file diff --git a/odk/examples/cpp/complextoolbarcontrols/description.xml b/odk/examples/cpp/complextoolbarcontrols/description.xml new file mode 100644 index 000000000..40539382b --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/description.xml @@ -0,0 +1,26 @@ + + + + + + + + Complex Toolbar Controls Demo + + diff --git a/odk/examples/cpp/complextoolbarcontrols/exports.cxx b/odk/examples/cpp/complextoolbarcontrols/exports.cxx new file mode 100644 index 000000000..c88013b64 --- /dev/null +++ b/odk/examples/cpp/complextoolbarcontrols/exports.cxx @@ -0,0 +1,68 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include +#include + +#include "MyProtocolHandler.h" +#include "MyListener.h" + +extern "C" +{ + +SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory(const char* pImplName , + void* pServiceManager, + void* pRegistryKey ) +{ + if ( !pServiceManager || !pImplName ) + return 0; + + css::uno::Reference< css::uno::XInterface > xFactory ; + css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR (reinterpret_cast< css::lang::XMultiServiceFactory* >(pServiceManager), css::uno::UNO_QUERY); + ::rtl::OUString sImplName = ::rtl::OUString::createFromAscii(pImplName); + + if (sImplName == MYLISTENER_IMPLEMENTATIONNAME) + { + css::uno::Sequence< ::rtl::OUString > lNames(1); + lNames[0] = MYLISTENER_IMPLEMENTATIONNAME; + xFactory = ::cppu::createSingleFactory(xSMGR, sImplName, MyListener::st_createInstance, lNames); + } + else if (sImplName == MYPROTOCOLHANDLER_IMPLEMENTATIONNAME) + { + css::uno::Sequence< ::rtl::OUString > lNames(1); + lNames[0] = MYPROTOCOLHANDLER_SERVICENAME; + xFactory = ::cppu::createSingleComponentFactory(MyProtocolHandler_createInstance, sImplName, lNames); + } + + if (!xFactory.is()) + return 0; + + xFactory->acquire(); + return xFactory.get(); +} + +SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( + char const ** ppEnvTypeName, uno_Environment **) +{ + *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; +} + +} // extern C + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/complextoolbarcontrols/logo_big.png b/odk/examples/cpp/complextoolbarcontrols/logo_big.png new file mode 100644 index 000000000..23dd24109 Binary files /dev/null and b/odk/examples/cpp/complextoolbarcontrols/logo_big.png differ diff --git a/odk/examples/cpp/complextoolbarcontrols/logo_small.png b/odk/examples/cpp/complextoolbarcontrols/logo_small.png new file mode 100644 index 000000000..c24b4e275 Binary files /dev/null and b/odk/examples/cpp/complextoolbarcontrols/logo_small.png differ diff --git a/odk/examples/cpp/counter/Makefile b/odk/examples/cpp/counter/Makefile new file mode 100644 index 000000000..b848adb02 --- /dev/null +++ b/odk/examples/cpp/counter/Makefile @@ -0,0 +1,174 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the C++ counter example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=counter +COMP_IMPL_NAME=$(COMP_NAME).uno.$(SHAREDLIB_EXT) +COMP_IMPL=$(SHAREDLIB_OUT)/$(COMP_IMPL_NAME) +COMP_RDB_NAME = $(COMP_NAME).uno.rdb +COMP_RDB = $(OUT_BIN)/$(COMP_RDB_NAME) +OUT_COMP_INC = $(OUT_INC)/$(COMP_NAME) +OUT_COMP_GEN = $(OUT_MISC)/$(COMP_NAME) +OUT_COMP_OBJ = $(OUT_OBJ)/$(COMP_NAME) +OUT_COMP_SLO = $(OUT_SLO)/$(COMP_NAME) +COMP_SERVICES=$(SHAREDLIB_OUT)/counterservices.rdb + +ENV_EXAMPLE_TYPES=-env:URE_MORE_TYPES=$(URLPREFIX)$(COMP_RDB) +ENV_COMP_SERVICES=-env:URE_MORE_SERVICES=$(URLPREFIX)$(COMP_SERVICES) + +COMP_TYPEFLAG = $(OUT_MISC)/cpp_$(COMP_NAME)_types.flag + +IDLFILES = XCountable.idl + +COMPCXXFILES = counter.cxx + +CXXFILES = countermain.cxx + +SLOFILES = $(patsubst %.cxx,$(OUT_COMP_SLO)/%.$(OBJ_EXT),$(COMPCXXFILES)) +OBJFILES = $(patsubst %.cxx,$(OUT_COMP_SLO)/%.$(OBJ_EXT),$(CXXFILES)) + +GENURDFILES = $(patsubst %.idl,$(OUT_COMP_GEN)/%.urd,$(IDLFILES)) + +TYPESLIST = -Tfoo.XCountable + +# Targets +.PHONY: ALL +ALL : \ + CppCounterExample + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_GEN)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -I. -I$(IDL_DIR) -O$(OUT_COMP_GEN) $< + +# This example type library will be extended by the URE types +$(OUT_BIN)/%.rdb : $(GENURDFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + $(REGMERGE) $@ /UCR $(GENURDFILES) +# $(REGMERGE) $@ / $(URE_TYPES) + +$(COMP_TYPEFLAG) : $(COMP_RDB) $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_TYPEFLAG))) + $(CPPUMAKER) -Gc -O$(OUT_COMP_INC) $(TYPESLIST) $(COMP_RDB) -X $(URE_TYPES) + echo flagged > $@ + +$(OUT_COMP_OBJ)/%.$(OBJ_EXT) : %.cxx $(COMP_TYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(OUT_OBJ)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +$(OUT_COMP_SLO)/%.$(OBJ_EXT) : %.cxx $(COMP_TYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(OUT_SLO)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +ifeq "$(OS)" "WIN" +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)) + $(LINK) $(COMP_LINK_FLAGS) /OUT:$@ \ + /MAP:$(OUT_COMP_GEN)/$(subst $(SHAREDLIB_EXT),map,$(@F)) $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) msvcprt.lib $(LIBO_SDK_LDFLAGS_STDLIBS) + $(LINK_MANIFEST) +else +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(COMP_LINK_FLAGS) $(LINK_LIBS) -o $@ $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS) $@ +endif +endif + +$(OUT_BIN)/countermain$(EXE_EXT) : $(OUT_COMP_OBJ)/countermain.$(OBJ_EXT) $(SHAREDLIB_OUT)/counter.uno.$(SHAREDLIB_EXT) +ifeq "$(OS)" "WIN" + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(EXE_LINK_FLAGS) /OUT:$@ /MAP:$(OUT_COMP_GEN)/$(basename $(@F)).map \ + $< $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) +else + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(EXE_LINK_FLAGS) $(LINK_LIBS) -o $@ $< \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALHELPERLIB) $(SALLIB) $(STDC++LIB) +endif + +$(COMP_SERVICES) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)components xmlns="$(QM)http://openoffice.org/2010/uno-components$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)component loader="$(QM)com.sun.star.loader.SharedLibrary$(QM)" uri="$(QM)$(COMP_IMPL_NAME)$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)com.sun.star.comp.example.cpp.Counter$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)foo.Counter$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/component$(CSEP) >> $@ + @echo $(OSEP)/components$(CSEP) >> $@ + + +CppCounterExample : $(OUT_BIN)/countermain$(EXE_EXT) $(COMP_IMPL) $(COMP_SERVICES) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) countermain.run + @echo - + @echo NOTE: The example makes use of the URE and use the defaultBootstrap_InitialComponentContext method. + @echo $(SQM) $(SQM)The additional example IDL types are provided via the UNO environment variable -env:URE_MORE_TYPES=... + @echo $(SQM) $(SQM)and the example component is made available via -env:URE_MORE_SERVICES=... + @echo $(SQM) $(SQM)Please check the generated $(QM)$(COMP_SERVICES)$(QM) to see how you can specify your own components in such an environment + @echo $(SQM) $(SQM)and how to use the passive UNO registration. + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_BIN)/countermain$(EXE_EXT) $(COMP_IMPL) + cd $(subst /,$(PS),$(OUT_BIN)) && $(basename $@) $(ENV_EXAMPLE_TYPES) $(ENV_COMP_SERVICES) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_OBJ)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_SLO)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_TYPEFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_RDB))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SHAREDLIB_OUT)/$(COMP_NAME).*)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_BIN)/countermain*)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_SERVICES))) diff --git a/odk/examples/cpp/counter/XCountable.idl b/odk/examples/cpp/counter/XCountable.idl new file mode 100644 index 000000000..c7ed299fa --- /dev/null +++ b/odk/examples/cpp/counter/XCountable.idl @@ -0,0 +1,58 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include + +module foo +{ + /** + * Interface to count things. + */ + interface XCountable : com::sun::star::uno::XInterface + { + long getCount(); + void setCount( [in] long nCount ); + long increment(); + long decrement(); + }; + + service Counter + { + // exported interfaces: + interface XCountable; + }; +}; + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/counter/counter.cxx b/odk/examples/cpp/counter/counter.cxx new file mode 100644 index 000000000..7e16b6a10 --- /dev/null +++ b/odk/examples/cpp/counter/counter.cxx @@ -0,0 +1,183 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +/* + * service implementation: foo.Counter + * exported interfaces: foo.XCounter + * + * simple example component implementing a counter + */ + +#include +#include +#include +#include +#include +#include +// generated c++ interfaces +#include +#include +#include +#include +#include + +#define SERVICENAME "foo.Counter" +#define IMPLNAME "com.sun.star.comp.example.cpp.Counter" + +using namespace ::rtl; +using namespace ::osl; +using namespace ::cppu; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::registry; +using namespace ::foo; + +class MyCounterImpl + : public XCountable + , public XServiceInfo +{ + // to obtain other services if needed + Reference< XMultiServiceFactory > m_xServiceManager; + + sal_Int32 m_nRefCount; + sal_Int32 m_nCount; + +public: + MyCounterImpl( const Reference< XMultiServiceFactory > & xServiceManager ) + : m_xServiceManager( xServiceManager ), m_nRefCount( 0 ) + { printf( "< MyCounterImpl ctor called >\n" ); } + ~MyCounterImpl() + { printf( "< MyCounterImpl dtor called >\n" ); } + + // XInterface implementation + virtual void SAL_CALL acquire() throw () + { ++m_nRefCount; } + virtual void SAL_CALL release() throw () + { if (! --m_nRefCount) delete this; } + virtual Any SAL_CALL queryInterface( const Type & rType ) throw (RuntimeException) + { return cppu::queryInterface(rType, + static_cast< XInterface* >( static_cast< XServiceInfo* >( this ) ), + static_cast< XCountable* >( this ), + static_cast< XServiceInfo* >( this ) ); } + + // XServiceInfo implementation + virtual OUString SAL_CALL getImplementationName( ) throw(RuntimeException); + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw(RuntimeException); + virtual Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw(RuntimeException); + static Sequence< OUString > SAL_CALL getSupportedServiceNames_Static( ); + + // XCountable implementation + virtual sal_Int32 SAL_CALL getCount() throw (RuntimeException) + { return m_nCount; } + virtual void SAL_CALL setCount( sal_Int32 nCount ) throw (RuntimeException) + { m_nCount = nCount; } + virtual sal_Int32 SAL_CALL increment() throw (RuntimeException) + { return (++m_nCount); } + virtual sal_Int32 SAL_CALL decrement() throw (RuntimeException) + { return (--m_nCount); } +}; + +OUString SAL_CALL MyCounterImpl::getImplementationName( ) + throw(RuntimeException) +{ + return OUString( IMPLNAME ); +} + +sal_Bool SAL_CALL MyCounterImpl::supportsService( const OUString& ServiceName ) + throw(RuntimeException) +{ + return cppu::supportsService(this, ServiceName); +} + +Sequence SAL_CALL MyCounterImpl::getSupportedServiceNames( ) + throw(RuntimeException) +{ + return getSupportedServiceNames_Static(); +} + +Sequence SAL_CALL MyCounterImpl::getSupportedServiceNames_Static( ) +{ + OUString aName( SERVICENAME ); + return Sequence< OUString >( &aName, 1 ); +} + +/** + * Function to create a new component instance; is needed by factory helper implementation. + * @param xMgr service manager to if the components needs other component instances + */ +Reference< XInterface > SAL_CALL MyCounterImpl_create( + const Reference< XMultiServiceFactory > & xMgr ) +{ + return Reference(static_cast(new MyCounterImpl(xMgr))); +} + +/** + * 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 + */ +extern "C" SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory(const char * pImplName, void * pServiceManager, void * pRegistryKey) +{ + void * pRet = 0; + + if (rtl_str_compare( pImplName, IMPLNAME ) == 0) + { + Reference< XSingleServiceFactory > xFactory( createSingleFactory( + reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), + OUString( IMPLNAME ), + MyCounterImpl_create, + MyCounterImpl::getSupportedServiceNames_Static() ) ); + + if (xFactory.is()) + { + xFactory->acquire(); + pRet = xFactory.get(); + } + } + + return pRet; +} + +extern "C" SAL_DLLPUBLIC_EXPORT void SAL_CALL +component_getImplementationEnvironment( + char const ** ppEnvTypeName, uno_Environment **) +{ + *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/counter/countermain.cxx b/odk/examples/cpp/counter/countermain.cxx new file mode 100644 index 000000000..5a613f588 --- /dev/null +++ b/odk/examples/cpp/counter/countermain.cxx @@ -0,0 +1,98 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// simple client application registering and using the counter component. +#include "sal/config.h" + +#include +#include + +#include +#include + +#include + +#include + +// generated c++ interfaces +#include +#include +#include + + +using namespace foo; +using namespace cppu; +using namespace com::sun::star::uno; +using namespace com::sun::star::lang; + +using namespace ::rtl; + + +SAL_IMPLEMENT_MAIN() +{ + try { + + Reference< XComponentContext > xContext(::cppu::defaultBootstrap_InitialComponentContext()); + OSL_ENSURE( xContext.is(), "### bootstrap failed!" ); + + Reference< XMultiComponentFactory > xMgr = xContext->getServiceManager(); + OSL_ENSURE( xMgr.is(), "### cannot get initial service manager!" ); + + Reference< XInterface > xx = xMgr->createInstanceWithContext( "foo.Counter", xContext); + + OSL_ENSURE( xx.is(), "### cannot get service instance of \"foo.Counter\"!" ); + + Reference< XCountable > xCount( xx, UNO_QUERY ); + OSL_ENSURE( xCount.is(), "### cannot query XCountable interface of service instance \"foo.Counter\"!" ); + + if (xCount.is()) + { + xCount->setCount( 42 ); + fprintf( stdout , "%d," , (int)xCount->getCount() ); + fprintf( stdout , "%d," , (int)xCount->increment() ); + fprintf( stdout , "%d\n" , (int)xCount->decrement() ); + } + + Reference< XComponent >::query( xContext )->dispose(); + return EXIT_SUCCESS; + + } catch( Exception& e) { + printf("Error: caught exception:\n %s\n", + OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr()); + return EXIT_FAILURE; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/custompanel/CalcWindowState.xcu b/odk/examples/cpp/custompanel/CalcWindowState.xcu new file mode 100644 index 000000000..427734289 --- /dev/null +++ b/odk/examples/cpp/custompanel/CalcWindowState.xcu @@ -0,0 +1,39 @@ + + + + + + + + + Soylent Blue + + + false + + + vnd.sun.star.extension://org.apache.openoffice.custom-tool-panel/panel.png + + + vnd.sun.star.help://org.apache.openoffice.custom-tool-panel/colorpanel + + + + + diff --git a/odk/examples/cpp/custompanel/DrawWindowState.xcu b/odk/examples/cpp/custompanel/DrawWindowState.xcu new file mode 100644 index 000000000..ca7037a9c --- /dev/null +++ b/odk/examples/cpp/custompanel/DrawWindowState.xcu @@ -0,0 +1,39 @@ + + + + + + + + + Soylent Yellow + + + false + + + vnd.sun.star.extension://org.apache.openoffice.custom-tool-panel/panel.png + + + vnd.sun.star.help://org.apache.openoffice.custom-tool-panel/colorpanel + + + + + diff --git a/odk/examples/cpp/custompanel/Factories.xcu b/odk/examples/cpp/custompanel/Factories.xcu new file mode 100644 index 000000000..05ce990a4 --- /dev/null +++ b/odk/examples/cpp/custompanel/Factories.xcu @@ -0,0 +1,39 @@ + + + + + + + + + toolpanel + + + org.openoffice.example.colorpanel + + + + + + org.openoffice.example.colorpanel.ToolPanelFactory + + + + + diff --git a/odk/examples/cpp/custompanel/ImpressWindowState.xcu b/odk/examples/cpp/custompanel/ImpressWindowState.xcu new file mode 100644 index 000000000..372ac726e --- /dev/null +++ b/odk/examples/cpp/custompanel/ImpressWindowState.xcu @@ -0,0 +1,39 @@ + + + + + + + + + Soylent Orange + + + false + + + vnd.sun.star.extension://org.apache.openoffice.custom-tool-panel/panel.png + + + vnd.sun.star.help://org.apache.openoffice.custom-tool-panel/colorpanel + + + + + diff --git a/odk/examples/cpp/custompanel/Makefile b/odk/examples/cpp/custompanel/Makefile new file mode 100644 index 000000000..fcbcd20dc --- /dev/null +++ b/odk/examples/cpp/custompanel/Makefile @@ -0,0 +1,171 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +# Builds the custom-tool-panel C++ component example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk +include $(SETTINGS)/dk.mk + +# Define non-platform/compiler specific settings +COMP_NAME=custom-tool-panel +COMP_IMPL_NAME=$(COMP_NAME).uno.$(SHAREDLIB_EXT) +OUT_COMP_INC=$(OUT_INC)/$(COMP_NAME) +OUT_COMP_GEN=$(OUT_MISC)/$(COMP_NAME) +OUT_COMP_SLO=$(OUT_SLO)/$(COMP_NAME) +COMP_PACKAGE = $(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL = $(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_UNOPKG_MANIFEST = $(OUT_COMP_GEN)/$(COMP_NAME)/META-INF/manifest.xml +COMP_MAPFILE = $(OUT_COMP_GEN)/$(COMP_NAME).uno.map +COMP_COMPONENTS = $(OUT_COMP_GEN)/$(COMP_NAME).components +COMP_TYPEFLAG = $(OUT_MISC)/cpp_$(COMP_NAME)_types.flag + +# Allow deploying the extension when running it + +#this should be in odk/settings/std.mk +OUT_DEPLOY=$(OUT)/deploy + +OUT_COMP_DEPLOY=$(OUT_DEPLOY)/$(COMP_NAME) +OUT_DEPLOY_DIR=$(subst /,$(PS),$(OUT_COMP_DEPLOY)) +OUT_DEPLOY_URL=$(URLPREFIX)$(OUT_COMP_DEPLOY) +ENV_USER_INSTALL=-env:"UserInstallation=$(OUT_DEPLOY_URL)" +OFFICE_START_OPTIONS=-nologo -norestore -writer +OXT_DEPLOYEDFLAG=$(OUT_MISC)/cpp_$(COMP_NAME)_deployed_oxt.flag + +CXXFILES = \ + ctp_factory.cxx \ + ctp_panel.cxx \ + ctp_services.cxx + +SLOFILES = $(patsubst %.cxx,$(OUT_COMP_SLO)/%.$(OBJ_EXT),$(CXXFILES)) + +# Add OSL_DEBUG_LEVEL to compiler the flags (for OSL_TRACE et. al.) +ifeq "$(DEBUG)" "yes" +CC_FLAGS += -DOSL_DEBUG_LEVEL=2 +endif + +# Targets +.PHONY: ALL +ALL : \ + CustomToolPanelExample + +include $(SETTINGS)/stdtarget.mk + +$(OUT_COMP_SLO)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(STL_INCLUDES) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + + +#$(COMP_MAPFILE) : $(SLOFILES) +# -$(MKDIR) $(subst /,$(PS),$(@D)) +# cat $(PRJ)/settings/component.uno.map > $(COMP_MAPFILE) +#ifeq "$(OS)" "MACOSX" +# nm -gx $(SLOFILES) | $(ADDSYMBOLS) >> $(COMP_MAPFILE) +#endif + +ifeq "$(OS)" "WIN" +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)) + $(LINK) $(COMP_LINK_FLAGS) /OUT:$@ \ + /MAP:$(OUT_COMP_GEN)/$(subst $(SHAREDLIB_EXT),map,$(@F)) $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STLPORTLIB) msvcrt.lib kernel32.lib + $(LINK_MANIFEST) +else +#$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) $(COMP_MAPFILE) +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(COMP_LINK_FLAGS) $(LINK_LIBS) -o $@ $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STLPORTLIB) $(STC++LIB) $(CPPUHELPERDYLIB) $(CPPUDYLIB) $(SALDYLIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS) $@ +endif +endif + +# rule for component package manifest +$(OUT_COMP_GEN)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)CalcWindowState.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)DrawWindowState.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)ImpressWindowState.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)WriterWindowState.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)Factories.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components;platform=$(UNOPKG_PLATFORM)$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +$(COMP_COMPONENTS) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)components xmlns="$(QM)http://openoffice.org/2010/uno-components$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)component loader="$(QM)com.sun.star.loader.SharedLibrary$(QM)" uri="$(QM)$(UNOPKG_PLATFORM)/$(COMP_IMPL_NAME)$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)org.openoffice.comp.example.custompanel.ToolPanelFactory$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)org.openoffice.example.colorpanel.ToolPanelFactory$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/component$(CSEP) >> $@ + @echo $(OSEP)/components$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(SHAREDLIB_OUT)/$(COMP_IMPL_NAME) WriterWindowState.xcu CalcWindowState.xcu DrawWindowState.xcu ImpressWindowState.xcu Factories.xcu $(COMP_UNOPKG_MANIFEST) $(COMP_COMPONENTS) + -$(MKDIR) $(subst /,$(PS),$(@D)) && $(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)/$(UNOPKG_PLATFORM)) + $(COPY) $(subst /,$(PS),$<) $(subst /,$(PS),$(OUT_COMP_GEN)/$(UNOPKG_PLATFORM)) + cd $(subst /,$(PS),$(OUT_COMP_GEN)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_NAME).components + cd $(subst /,$(PS),$(OUT_COMP_GEN)) && $(SDK_ZIP) -u ../../bin/$(@F) $(UNOPKG_PLATFORM)/$( $(subst /,$(PS),$@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_SLO)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_DEPLOY_DIR)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_TYPEFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OXT_DEPLOYEDFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SHAREDLIB_OUT)/$(COMP_NAME).*)) diff --git a/odk/examples/cpp/custompanel/WriterWindowState.xcu b/odk/examples/cpp/custompanel/WriterWindowState.xcu new file mode 100644 index 000000000..c0ca084a6 --- /dev/null +++ b/odk/examples/cpp/custompanel/WriterWindowState.xcu @@ -0,0 +1,53 @@ + + + + + + + + + Soylent Green + + + false + + + vnd.sun.star.extension://org.apache.openoffice.custom-tool-panel/panel.png + + + vnd.sun.star.help://org.apache.openoffice.custom-tool-panel/colorpanel + + + + + Soylent Red + + + false + + + vnd.sun.star.extension://org.apache.openoffice.custom-tool-panel/panel.png + + + vnd.sun.star.help://org.apache.openoffice.custom-tool-panel/colorpanel + + + + + diff --git a/odk/examples/cpp/custompanel/ctp_factory.cxx b/odk/examples/cpp/custompanel/ctp_factory.cxx new file mode 100644 index 000000000..e2e29ee0d --- /dev/null +++ b/odk/examples/cpp/custompanel/ctp_factory.cxx @@ -0,0 +1,126 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#include "ctp_factory.hxx" +#include "ctp_panel.hxx" + +#include +#include + +namespace sd { namespace colortoolpanel +{ + using ::com::sun::star::uno::Reference; + using ::com::sun::star::uno::XInterface; + using ::com::sun::star::uno::UNO_QUERY; + using ::com::sun::star::uno::RuntimeException; + using ::com::sun::star::uno::Sequence; + using ::com::sun::star::uno::XComponentContext; + using ::com::sun::star::lang::IllegalArgumentException; + using ::com::sun::star::ui::XUIElement; + using ::com::sun::star::beans::PropertyValue; + using ::com::sun::star::container::NoSuchElementException; + using ::com::sun::star::awt::XWindow; + + ToolPanelFactory::ToolPanelFactory( const Reference< XComponentContext >& i_rContext ) + :m_xContext( i_rContext ) + { + } + + + ToolPanelFactory::~ToolPanelFactory() + { + } + + + Reference< XUIElement > SAL_CALL ToolPanelFactory::createUIElement( const OUString& i_rResourceURL, const Sequence< PropertyValue >& i_rArgs ) throw (NoSuchElementException, IllegalArgumentException, RuntimeException) + { + ::osl::MutexGuard aGuard( m_aMutex ); + + if ( !i_rResourceURL.startsWith( "private:resource/toolpanel/org.openoffice.example.colorpanel/" ) ) + throw NoSuchElementException( i_rResourceURL, *this ); + + const OUString sColor( i_rResourceURL.copy( i_rResourceURL.lastIndexOf( '/' ) + 1 ) ); + const sal_Int32 nPanelColor = static_cast< sal_Int32 >( sColor.toUInt32( 16 ) ); + + // retrieve the parent window + Reference< XWindow > xParentWindow; + const PropertyValue* pArg = i_rArgs.getConstArray(); + const PropertyValue* pArgEnd = i_rArgs.getConstArray() + i_rArgs.getLength(); + for ( ; pArg != pArgEnd; ++pArg ) + { + if ( pArg->Name == "ParentWindow" ) + { + xParentWindow.set( pArg->Value, UNO_QUERY ); + break; + } + } + if ( !xParentWindow.is() ) + { + OSL_FAIL( "ToolPanelFactory::createUIElement: no parent window in the args!" ); + throw IllegalArgumentException( + "No parent window provided in the creation arguments. Cannot create tool panel.", + *this, + 2 + ); + } + + /// create the panel + Reference< XUIElement > xUIElement( new PanelUIElement( m_xContext, xParentWindow, i_rResourceURL, nPanelColor ) ); + return xUIElement; + } + + OUString SAL_CALL ToolPanelFactory::getImplementationName( ) throw (RuntimeException) + { + return getImplementationName_static(); + } + + OUString SAL_CALL ToolPanelFactory::getImplementationName_static( ) throw (RuntimeException) + { + return OUString( "org.openoffice.comp.example.custompanel.ToolPanelFactory" ); + } + + sal_Bool SAL_CALL ToolPanelFactory::supportsService( const OUString& i_rServiceName ) throw (RuntimeException) + { + return cppu::supportsService(this, i_rServiceName); + } + + Sequence< OUString > SAL_CALL ToolPanelFactory::getSupportedServiceNames() throw (RuntimeException) + { + return getSupportedServiceNames_static(); + } + + Sequence< OUString > SAL_CALL ToolPanelFactory::getSupportedServiceNames_static() throw (RuntimeException) + { + Sequence< OUString > aServiceNames(1); + aServiceNames[0] = "org.openoffice.example.colorpanel.ToolPanelFactory"; + return aServiceNames; + } + + + Reference< XInterface > SAL_CALL ToolPanelFactory::Create( const Reference< XComponentContext >& i_rContext ) throw (RuntimeException) + { + return *( new ToolPanelFactory( i_rContext ) ); + } + + +} } // namespace sd::colortoolpanel + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/custompanel/ctp_factory.hxx b/odk/examples/cpp/custompanel/ctp_factory.hxx new file mode 100644 index 000000000..a3aa5ddd8 --- /dev/null +++ b/odk/examples/cpp/custompanel/ctp_factory.hxx @@ -0,0 +1,70 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EXAMPLES_CUSTOMPANEL_CTP_FACTORY_HXX +#define INCLUDED_EXAMPLES_CUSTOMPANEL_CTP_FACTORY_HXX + +#include +#include +#include + +#include +#include + + +namespace sd { namespace colortoolpanel +{ + + typedef ::cppu::WeakImplHelper2 < ::com::sun::star::ui::XUIElementFactory + , ::com::sun::star::lang::XServiceInfo + > ToolPanelFactory_Base; + class ToolPanelFactory :public ::cppu::BaseMutex + ,public ToolPanelFactory_Base + { + public: + ToolPanelFactory( + const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& i_rContext + ); + ~ToolPanelFactory(); + + // XUIElementFactory + virtual ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIElement > SAL_CALL createUIElement( const OUString& i_rResourceURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& i_rArgs ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); + + // XServiceInfo + virtual OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException); + virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException); + + // XServiceInfo - static versions + static OUString SAL_CALL getImplementationName_static( ) throw (::com::sun::star::uno::RuntimeException); + static ::com::sun::star::uno::Sequence< OUString > SAL_CALL getSupportedServiceNames_static( ) throw (::com::sun::star::uno::RuntimeException); + static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL Create( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& i_rContext ) throw (::com::sun::star::uno::RuntimeException); + + private: + const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > + m_xContext; + }; + + +} } // namespace sd::colortoolpanel + + +#endif // INCLUDED_EXAMPLES_CUSTOMPANEL_CTP_FACTORY_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/custompanel/ctp_panel.cxx b/odk/examples/cpp/custompanel/ctp_panel.cxx new file mode 100644 index 000000000..a6f03e247 --- /dev/null +++ b/odk/examples/cpp/custompanel/ctp_panel.cxx @@ -0,0 +1,243 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +#include "ctp_panel.hxx" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + + +namespace sd { namespace colortoolpanel +{ + + + using ::com::sun::star::uno::Reference; + using ::com::sun::star::uno::XInterface; + using ::com::sun::star::uno::UNO_QUERY; + using ::com::sun::star::uno::UNO_QUERY_THROW; + using ::com::sun::star::uno::UNO_SET_THROW; + using ::com::sun::star::uno::Exception; + using ::com::sun::star::uno::RuntimeException; + using ::com::sun::star::uno::Type; + using ::com::sun::star::uno::XComponentContext; + using ::com::sun::star::awt::XWindow; + using ::com::sun::star::lang::DisposedException; + using ::com::sun::star::awt::XWindowPeer; + using ::com::sun::star::lang::XMultiComponentFactory; + using ::com::sun::star::awt::WindowDescriptor; + using ::com::sun::star::awt::WindowClass_SIMPLE; + using ::com::sun::star::awt::Rectangle; + using ::com::sun::star::awt::PaintEvent; + using ::com::sun::star::lang::EventObject; + using ::com::sun::star::awt::XDevice; + using ::com::sun::star::awt::XGraphics; + using ::com::sun::star::accessibility::XAccessible; + using ::com::sun::star::frame::XFrame; + + namespace WindowAttribute = ::com::sun::star::awt::WindowAttribute; + namespace PosSize = ::com::sun::star::awt::PosSize; + namespace UIElementType = ::com::sun::star::ui::UIElementType; + + + //= helpers + + namespace + { + Reference< XWindow > lcl_createPlainWindow_nothrow( const Reference< XComponentContext >& i_rContext, + const Reference< XWindowPeer >& i_rParentWindow ) + { + try + { + OSL_ENSURE( i_rContext.is(), "illegal component context" ); + Reference< XMultiComponentFactory > xFactory( i_rContext->getServiceManager(), UNO_SET_THROW ); + Reference< XToolkit2 > xToolkit = Toolkit::create(i_rContext); + + WindowDescriptor aWindow; + aWindow.Type = WindowClass_SIMPLE; + aWindow.WindowServiceName = "window"; + aWindow.Parent = i_rParentWindow; + aWindow.WindowAttributes = WindowAttribute::BORDER; + + Reference< XWindowPeer > xWindow( xToolkit->createWindow( aWindow ), UNO_SET_THROW ); + return Reference< XWindow >( xWindow, UNO_QUERY_THROW ); + } + catch( const Exception& ) + { + } + return NULL; + } + } + + SingleColorPanel::SingleColorPanel( const Reference< XComponentContext >& i_rContext, const Reference< XWindow >& i_rParentWindow, const ::sal_Int32 i_nPanelColor ) + :SingleColorPanel_Base( m_aMutex ) + ,m_xWindow() + ,m_nPanelColor( i_nPanelColor ) + { + // retrieve the parent window for our to-be-created pane window + Reference< XWindowPeer > xParentPeer( i_rParentWindow, UNO_QUERY ); + + osl_atomic_increment( &m_refCount ); + if ( xParentPeer.is() ) + { + m_xWindow = lcl_createPlainWindow_nothrow( i_rContext, xParentPeer ); + m_xWindow->addPaintListener( this ); + if ( m_xWindow.is() ) + { + const Rectangle aPanelAnchorSize( i_rParentWindow->getPosSize() ); + m_xWindow->setPosSize( 0, 0, aPanelAnchorSize.Width, aPanelAnchorSize.Height, PosSize::POSSIZE ); + m_xWindow->setVisible( sal_True ); + } + } + osl_atomic_decrement( &m_refCount ); + } + + + SingleColorPanel::~SingleColorPanel() + { + } + + + Reference< XWindow > SAL_CALL SingleColorPanel::getWindow() throw (RuntimeException) + { + ::osl::MutexGuard aGuard( m_aMutex ); + if ( !m_xWindow.is() ) + throw DisposedException( OUString(), *this ); + return m_xWindow; + } + + + Reference< XAccessible > SAL_CALL SingleColorPanel::createAccessible( const Reference< XAccessible >& i_rParentAccessible ) throw (RuntimeException) + { + ::osl::MutexGuard aGuard( m_aMutex ); + if ( !m_xWindow.is() ) + throw DisposedException( OUString(), *this ); + + // TODO: the following is wrong, since it doesn't respect i_rParentAccessible. In a real extension, you should + // implement this correctly :) + (void)i_rParentAccessible; + return Reference< XAccessible >( getWindow(), UNO_QUERY ); + } + + + void SAL_CALL SingleColorPanel::windowPaint( const PaintEvent& i_rEvent ) throw (RuntimeException) + { + try + { + const Reference< XDevice > xDevice( i_rEvent.Source, UNO_QUERY_THROW ); + const Reference< XGraphics > xGraphics( xDevice->createGraphics(), UNO_SET_THROW ); + xGraphics->setFillColor( m_nPanelColor ); + xGraphics->setLineColor( 0x00FFFFFF ); + + const Reference< XWindow > xWindow( i_rEvent.Source, UNO_QUERY_THROW ); + const Rectangle aWindowRect( xWindow->getPosSize() ); + xGraphics->drawRect( 0, 0, aWindowRect.Width - 1, aWindowRect.Height - 1 ); + } + catch( const Exception& ) + { + } + } + + + void SAL_CALL SingleColorPanel::disposing( const EventObject& i_rSource ) throw (RuntimeException) + { + (void)i_rSource; + } + + + void SAL_CALL SingleColorPanel::disposing() + { + ::osl::MutexGuard aGuard( m_aMutex ); + if ( !m_xWindow.is() ) + // already disposed + return; + m_xWindow->removePaintListener( this ); + try + { + Reference< XComponent > xWindowComp( m_xWindow, UNO_QUERY_THROW ); + xWindowComp->dispose(); + } + catch( const Exception& ) + { + } + m_xWindow.clear(); + } + + PanelUIElement::PanelUIElement( const Reference< XComponentContext >& i_rContext, const Reference< XWindow >& i_rParentWindow, + const OUString& i_rResourceURL, const ::sal_Int32 i_nPanelColor ) + :PanelUIElement_Base( m_aMutex ) + ,m_sResourceURL( i_rResourceURL ) + ,m_xToolPanel( new SingleColorPanel( i_rContext, i_rParentWindow, i_nPanelColor ) ) + { + } + + + PanelUIElement::~PanelUIElement() + { + } + + + Reference< XFrame > SAL_CALL PanelUIElement::getFrame() throw (RuntimeException) + { + // TODO + return NULL; + } + + + OUString SAL_CALL PanelUIElement::getResourceURL() throw (RuntimeException) + { + return m_sResourceURL; + } + + + ::sal_Int16 SAL_CALL PanelUIElement::getType() throw (RuntimeException) + { + return UIElementType::TOOLPANEL; + } + + + Reference< XInterface > SAL_CALL PanelUIElement::getRealInterface( ) throw (RuntimeException) + { + ::osl::MutexGuard aGuard( m_aMutex ); + if ( !m_xToolPanel.is() ) + throw DisposedException(); + return m_xToolPanel; + } + + + void SAL_CALL PanelUIElement::disposing() + { + Reference< XComponent > xPanelComponent( m_xToolPanel, UNO_QUERY_THROW ); + m_xToolPanel.clear(); + xPanelComponent->dispose(); + } + + +} } // namespace sd::colortoolpanel + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/custompanel/ctp_panel.hxx b/odk/examples/cpp/custompanel/ctp_panel.hxx new file mode 100644 index 000000000..c811f24e6 --- /dev/null +++ b/odk/examples/cpp/custompanel/ctp_panel.hxx @@ -0,0 +1,108 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#ifndef INCLUDED_EXAMPLES_CUSTOMPANEL_CTP_PANEL_HXX +#define INCLUDED_EXAMPLES_CUSTOMPANEL_CTP_PANEL_HXX + +#include +#include +#include +#include +#include + +#include +#include +#include + + +namespace sd { namespace colortoolpanel +{ + + typedef ::cppu::WeakComponentImplHelper2 < ::com::sun::star::ui::XToolPanel + , ::com::sun::star::awt::XPaintListener + > SingleColorPanel_Base; + class SingleColorPanel :public ::cppu::BaseMutex + ,public SingleColorPanel_Base + { + public: + SingleColorPanel( + const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& i_rContext, + const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& i_rParentWindow, + const ::sal_Int32 i_nPanelColor + ); + + // XToolPanel + virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > SAL_CALL getWindow() throw (::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL createAccessible( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& i_rParentAccessible ) throw (::com::sun::star::uno::RuntimeException); + + // XPaintListener + virtual void SAL_CALL windowPaint( const ::com::sun::star::awt::PaintEvent& e ) throw (::com::sun::star::uno::RuntimeException); + + // XEventListener + virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException); + + // XComponent equivalents + virtual void SAL_CALL disposing(); + + protected: + ~SingleColorPanel(); + + private: + ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > m_xWindow; + const sal_Int32 m_nPanelColor; + }; + + typedef ::cppu::WeakComponentImplHelper1 < ::com::sun::star::ui::XUIElement + > PanelUIElement_Base; + class PanelUIElement :public ::cppu::BaseMutex + ,public PanelUIElement_Base + { + public: + PanelUIElement( + const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& i_rContext, + const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >& i_rParentWindow, + const OUString& i_rResourceURL, + const ::sal_Int32 i_nPanelColor + ); + + // XUIElement + virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > SAL_CALL getFrame() throw (::com::sun::star::uno::RuntimeException); + virtual OUString SAL_CALL getResourceURL() throw (::com::sun::star::uno::RuntimeException); + virtual ::sal_Int16 SAL_CALL getType() throw (::com::sun::star::uno::RuntimeException); + virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getRealInterface( ) throw (::com::sun::star::uno::RuntimeException); + + // OComponentHelper + virtual void SAL_CALL disposing(); + + protected: + ~PanelUIElement(); + + private: + const OUString m_sResourceURL; + ::com::sun::star::uno::Reference< ::com::sun::star::ui::XToolPanel > + m_xToolPanel; + }; + + +} } // namespace sd::colortoolpanel + + +#endif // INCLUDED_EXAMPLES_CUSTOMPANEL_CTP_PANEL_HXX + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/custompanel/ctp_services.cxx b/odk/examples/cpp/custompanel/ctp_services.cxx new file mode 100644 index 000000000..5c795f695 --- /dev/null +++ b/odk/examples/cpp/custompanel/ctp_services.cxx @@ -0,0 +1,63 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +#include "ctp_factory.hxx" + +#include +#include + + +namespace sd { namespace colortoolpanel +{ + + + //= descriptors for the services implemented in this component + + static struct ::cppu::ImplementationEntry s_aServiceEntries[] = + { + { + ToolPanelFactory::Create, + ToolPanelFactory::getImplementationName_static, + ToolPanelFactory::getSupportedServiceNames_static, + ::cppu::createSingleComponentFactory, NULL, 0 + }, + { 0, 0, 0, 0, 0, 0 } + }; + + +} } // namespace sd::colortoolpanel + + +extern "C" +{ + + SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey ) + { + return ::cppu::component_getFactoryHelper( pImplName, pServiceManager, pRegistryKey , ::sd::colortoolpanel::s_aServiceEntries ); + } + +SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( + char const ** ppEnvTypeName, uno_Environment **) +{ + *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/cpp/custompanel/description.xml b/odk/examples/cpp/custompanel/description.xml new file mode 100644 index 000000000..431305fd5 --- /dev/null +++ b/odk/examples/cpp/custompanel/description.xml @@ -0,0 +1,33 @@ + + + + + + + + + Custom Tool Panel Example + + + + + diff --git a/odk/examples/cpp/custompanel/manifest.xml b/odk/examples/cpp/custompanel/manifest.xml new file mode 100644 index 000000000..fbb9fdcde --- /dev/null +++ b/odk/examples/cpp/custompanel/manifest.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + diff --git a/odk/examples/cpp/custompanel/panel.png b/odk/examples/cpp/custompanel/panel.png new file mode 100644 index 000000000..2438714af Binary files /dev/null and b/odk/examples/cpp/custompanel/panel.png differ diff --git a/odk/examples/cpp/remoteclient/Makefile b/odk/examples/cpp/remoteclient/Makefile new file mode 100644 index 000000000..238ec3ca2 --- /dev/null +++ b/odk/examples/cpp/remoteclient/Makefile @@ -0,0 +1,154 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the C++ remoteclient example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=remoteclientsample +COMP_IMPL_NAME=$(COMP_NAME).uno.$(SHAREDLIB_EXT) +COMP_IMPL=$(SHAREDLIB_OUT)/$(COMP_IMPL_NAME) +COMP_RDB_NAME = $(COMP_NAME).uno.rdb +COMP_RDB = $(OUT_BIN)/$(COMP_RDB_NAME) +COMP_SERVICES=$(SHAREDLIB_OUT)/remoteclientsample.rdb + +ENV_COMP_SERVICES=-env:URE_MORE_SERVICES=$(URLPREFIX)$(COMP_SERVICES) + +OUT_COMP_INC=$(OUT_INC)/$(COMP_NAME) +OUT_COMP_GEN=$(OUT_MISC)/$(COMP_NAME) +OUT_COMP_SLO=$(OUT_SLO)/$(COMP_NAME) + +COMP_TYPEFLAG = $(OUT_MISC)/cpp_$(COMP_NAME)_types.flag + +CXXFILES = remoteclient.cxx + +SLOFILES = $(patsubst %.cxx,$(OUT_COMP_SLO)/%.$(OBJ_EXT),$(CXXFILES)) + +# Targets +.PHONY: ALL +ALL : \ + CppClientExample + +include $(SETTINGS)/stdtarget.mk + +# This example type library will be extended by the URE types +$(OUT_BIN)/%.rdb : + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + $(REGMERGE) $@ / $(URE_TYPES) + +$(OUT_COMP_SLO)/%.$(OBJ_EXT) : %.cxx $(SDKTYPEFLAG) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(CC) $(CC_FLAGS) $(CC_INCLUDES) -I$(OUT_COMP_INC) $(CC_DEFINES) $(CC_OUTPUT_SWITCH)$(subst /,$(PS),$@) $< + +ifeq "$(OS)" "WIN" +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + -$(MKDIR) $(subst /,$(PS),$(OUT_COMP_GEN)) + $(LINK) $(COMP_LINK_FLAGS) /OUT:$@ \ + /MAP:$(OUT_COMP_GEN)/$(subst $(SHAREDLIB_EXT),map,$(@F)) $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) msvcprt.lib $(LIBO_SDK_LDFLAGS_STDLIBS) + $(LINK_MANIFEST) +else +$(SHAREDLIB_OUT)/%.$(SHAREDLIB_EXT) : $(SLOFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(LINK) $(COMP_LINK_FLAGS) $(LINK_LIBS) -o $@ $(SLOFILES) \ + $(CPPUHELPERLIB) $(CPPULIB) $(SALLIB) $(STC++LIB) +ifeq "$(OS)" "MACOSX" + $(INSTALL_NAME_URELIBS) $@ +endif +endif + +$(COMP_SERVICES) : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)components xmlns="$(QM)http://openoffice.org/2010/uno-components$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)component loader="$(QM)com.sun.star.loader.SharedLibrary$(QM)" uri="$(QM)$(COMP_IMPL_NAME)$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)implementation name="$(QM)com.sun.star.comp.product.example.RemoteClientSample$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)service name="$(QM)com.sun.star.bridge.example.RemoteClientSample$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/implementation$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)/component$(CSEP) >> $@ + @echo $(OSEP)/components$(CSEP) >> $@ + + +#CppClientExample : $(COMP_IMPL) $(COMP_ENV_FLAG) +CppClientExample : $(COMP_IMPL) $(COMP_SERVICES) + @echo -------------------------------------------------------------------------------- + @echo The remoteclient C++ component can be used by using the uno binary. Use the + @echo the following command to start the example. The run target starts a remote + @echo server and connect with the client to this server. + @echo - + @echo $(MAKE) remoteclient.run + @echo - + @echo NOTE: The example uses the $(QM)uno$(QM) tool to prepare a working UNO environment. + @echo $(SQM) $(SQM)The example component is made available via -env:URE_MORE_SERVICES=... + @echo $(SQM) $(SQM)Please check the generated $(QM)$(COMP_SERVICES)$(QM) to see how you can specify your own components in such an environment + @echo $(SQM) $(SQM)and how to use the passive UNO registration. + @echo -------------------------------------------------------------------------------- + +%.run: $(COMP_IMPL) + @echo Start the remote server process ... + @echo - +ifeq "$(OS)" "WIN" + start uno $(ENV_COMP_SERVICES) --singleaccept -s com.sun.star.io.Pipe \ + -u "uno:socket,host=localhost,port=2083;urp;MyPipe" +else + uno $(ENV_COMP_SERVICES) --singleaccept -s com.sun.star.io.Pipe \ + -u "uno:socket,host=localhost,port=2083;urp;MyPipe" & + @echo waiting on the server process ... + sleep 5 +endif + @echo - + @echo ... remote server process runs ... + @echo - + @echo Start remote client process ... + @echo - + uno $(ENV_COMP_SERVICES) -s com.sun.star.bridge.example.RemoteClientSample \ + -- "uno:socket,host=localhost,port=2083;urp;MyPipe" + @echo - + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_INC)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_SLO)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_TYPEFLAG))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_SERVICES))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(SHAREDLIB_OUT)/$(COMP_NAME).*)) +# -$(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_BIN)/remoteserver.rdb)) diff --git a/odk/examples/cpp/remoteclient/remoteclient.cxx b/odk/examples/cpp/remoteclient/remoteclient.cxx new file mode 100644 index 000000000..7c70f5dfe --- /dev/null +++ b/odk/examples/cpp/remoteclient/remoteclient.cxx @@ -0,0 +1,260 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#include +#include +#include +#include + +#include + +#include + +#include + +#include +#include +#include +#include + +#include +#include + +#include + +using namespace ::rtl; +using namespace ::cppu; +using namespace ::osl; +using namespace ::com::sun::star::uno; +using namespace ::com::sun::star::lang; +using namespace ::com::sun::star::connection; +using namespace ::com::sun::star::bridge; +using namespace ::com::sun::star::io; + + +namespace remotebridges_officeclient { + +class PipeClientMain : public WeakImplHelper1< XMain > +{ +public: + PipeClientMain( const Reference< XMultiServiceFactory > &r ) : + m_xSMgr( r ) + {} +public: // Methods + + + virtual sal_Int32 SAL_CALL run( const Sequence< OUString >& aArguments ) + throw(RuntimeException); + + +private: // helper methods + void testPipe( const Reference < XInterface > & rComponent ); + Reference< XMultiServiceFactory > m_xSMgr; +}; + +void PipeClientMain::testPipe( const Reference< XInterface > & rxInterface ) +{ + // ask for the input stream + Reference< XInputStream > rInputStream( rxInterface, UNO_QUERY ); + + // ask for the output stream + Reference< XOutputStream > rOutputStream( rxInterface, UNO_QUERY ); + + if( rInputStream.is() && rOutputStream.is() ) + { + printf( "got inputstream and outputstream from remote process\n" ); + + sal_Int8 a[] = { 5,4,3,2,1,0 }; + Sequence< sal_Int8 > seq( a , 6 ); + rOutputStream->writeBytes( seq ); + rOutputStream->closeOutput(); + + Sequence< sal_Int8> seqRead; + if( rInputStream->readBytes( seqRead ,3 ) != 3 ) + { + printf( "error : Couldn't read the expected number of bytes\n" ); + return; + } + + if( seqRead.getConstArray()[0] != 5 || + seqRead.getConstArray()[1] != 4 || + seqRead.getConstArray()[2] != 3 ) + { + printf( "error : The array doesn't contain the expected values\n" ); + return; + } + + // try to read more bytes than written + if( rInputStream->readBytes( seqRead , 4 ) != 3 ) + { + printf( "error : Got an unexpected number of bytes\n" ); + return; + } + + if( seqRead.getConstArray()[0] != 2 || + seqRead.getConstArray()[1] != 1 || + seqRead.getConstArray()[2] != 0 ) + { + printf( "error : The array doesn't contain the expected values\n" ); + return; + } + + printf( "pipe test worked perfect\n" ); + } + else + { + printf( "Couldn't get inputstream and outputstream\n" ); + } +} + + +sal_Int32 PipeClientMain::run( const Sequence< OUString > & aArguments ) throw ( RuntimeException ) +{ + printf( "Connecting...\n" ); + + if( aArguments.getLength() == 1 ) + { + try { + Reference < XInterface > r = + m_xSMgr->createInstance("com.sun.star.bridge.UnoUrlResolver"); + Reference < XUnoUrlResolver > rResolver( r , UNO_QUERY ); + + // connect to the remote process and retrieve the initial object + r = rResolver->resolve( aArguments.getConstArray()[0] ); + + if( r.is() ) + { + printf( "got the remote initial object\n" ); + testPipe( r ); + } + else + { + printf( "error : didn't get the initial object\n" ); + } + } + catch( ConnectionSetupException &e ) + { + OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ); + printf( "%s\n", o.pData->buffer ); + printf( "couldn't access local resource (possible security reasons)\n" ); + } + catch( NoConnectException &e ) + { + OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ); + printf( "%s\n", o.pData->buffer ); + printf( "no server listening on the resource\n" ); + } + catch( IllegalArgumentException &e ) + { + OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ); + printf( "%s\n", o.pData->buffer ); + printf( "uno url invalid\n" ); + } + catch( RuntimeException & e ) + { + OString o = OUStringToOString( e.Message, RTL_TEXTENCODING_ASCII_US ); + printf( "%s\n", o.pData->buffer ); + printf( "a remote call was aborted\n" ); + } + } + else + { + printf( "usage: (uno remoteclient-component --) uno-url\n" + "e.g.: uno:socket,host=localhost,port=2083;urp;MyPipe\n" ); + return 1; + } + return 0; +} + +Reference< XInterface > SAL_CALL CreateInstance( const Reference< XMultiServiceFactory > &r) +{ + return Reference< XInterface > ( ( OWeakObject * ) new PipeClientMain(r) ); +} + +Sequence< OUString > getSupportedServiceNames() +{ + static Sequence < OUString > *pNames = 0; + if( ! pNames ) + { + MutexGuard guard( Mutex::getGlobalMutex() ); + if( !pNames ) + { + static Sequence< OUString > seqNames(1); + seqNames[0] = "com.sun.star.bridge.example.RemoteClientSample"; + pNames = &seqNames; + } + } + return *pNames; +} + +} + +using namespace remotebridges_officeclient; +#define IMPLEMENTATION_NAME "com.sun.star.comp.product.example.RemoteClientSample" + + +extern "C" +{ +SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory( + const char * pImplName, void * pServiceManager, void * pRegistryKey ) +{ + void * pRet = 0; + + if (pServiceManager && rtl_str_compare( pImplName, IMPLEMENTATION_NAME ) == 0) + { + Reference< XSingleServiceFactory > xFactory( createSingleFactory( + reinterpret_cast< XMultiServiceFactory * >( pServiceManager ), + OUString::createFromAscii( pImplName ), + CreateInstance, getSupportedServiceNames() ) ); + + if (xFactory.is()) + { + xFactory->acquire(); + pRet = xFactory.get(); + } + } + + return pRet; +} + +SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( + char const ** ppEnvTypeName, uno_Environment **) +{ + *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; +} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/examples.html b/odk/examples/examples.html new file mode 100644 index 000000000..25d5efe40 --- /dev/null +++ b/odk/examples/examples.html @@ -0,0 +1,834 @@ + + + + + LibreOffice %PRODUCT_RELEASE% SDK - Examples + + + + + +
+
+
+ +

+ Software Development Kit %PRODUCT_RELEASE% +

+
+
+
+
+
+

+ Examples +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
+ + + + + + + +
+

The SDK provides a rich set of examples in different programming + languages (Java, Python, C++, LibreOffice %PRODUCT_RELEASE% Basic, OLE) to illustrate the use + of the API and demonstrate how to benefit from the included word + processor, spreadsheet, presentation software, graphics program and + database of LibreOffice %PRODUCT_RELEASE%.
+ Some of the examples need a running office instance listening on a + port. If this is necessary you will get further information in the + makefiles.

+

Every makefile contains at least one run target to execute an + running example, please see the makefile output in the different + example directories. Some of the examples which create a component have + no run target. In these cases a document is provided which instantiates + and runs the component (see the makefile output). Also the Basic + examples provide documents which use and shows the implemented + functionality.

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Developer's Guide examplesThe Developer's Guide comes + with a rich set of examples which demonstrate the use of the API in + the different application areas.
Java examplesSet of simple and more complex examples which + shows the use of the API from Java.
Python examplesSmall set of examples which shows the use of the API from Python.
C++ examplesSmall set of examples which shows the use of + the API from C++.
LibreOffice %PRODUCT_RELEASE% Basic examplesSmall set of examples which shows the use of + the API from LibreOffice %PRODUCT_RELEASE% Basic.
Object Linking and Embedding (OLE) examplesExamples which show the use of the API from OLE.
Common Language Infrastructure (CLI) examplesExamples which show the use of the API from the CLI.
+
+ + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +
Java examples + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Text Document ExamplesDescription
BookmarkInsertionThis application connects to the office server and + gets the multi component factory. An empty text document will be opened + and an example text will be entered. Afterwards, some bookmarks will be + inserted.
HardFormattingThis program connects to the office server and gets + the multi component factory. Furthermore, an empty text document will be + opened, an example text will be entered, some text attributes will be + inspected, and the PropertyState will be checked from the selection.
SWriterThe program connects to the office server and gets the + multi component factory. An empty text document will be created, some + text will be entered, and a text table, a colored text, and text frame + will be inserted.
StyleCreationThe example connects to the office server and gets the + multi component factory. An empty text document will be opened, a new + paragraph style will be created, and applied.
StyleInitializationThe program connects to the office server and gets the + multi component factory. Thereafter, an empty text document will be + opened and an example text will be entered. The paragraph collection will + be used, in order to apply a different paragraph style on the + paragraphs.
TextDocumentStructureThe application connects to the office server and gets + the multi component factory. An empty text document will be opened, an + enumeration of all paragraphs and an enumeration of all text portions + will be created.
TextReplaceThe example connects to the office server and gets the + multi component factory. An empty text document will be created, an + example text will be inserted, and some English spelled words will be + replaced with US spelled words.
GraphicsInserterThe GraphicsInserter creates a graphics object on an + empty text document by setting its position, width, height, and URL.
WriterSelectorThis class gives you information on the selected + objects (text range, text frame, or graphics) at a LibreOffice + Server.
+
+ + + + + + + + + + + + + + + + + + + + + + + +
Spreadsheet Document ExamplesDescription
CalcAddinsThis component adds new functions to the spreadsheet + application. After registering the component, the inserted functions can + be found with help of the functions autopilot. The new functions are + assigned to the category Add-in.
ChartTypeChangeThis class loads a LibreOffice %PRODUCT_RELEASE% Calc document and + changes the type of the embedded chart.
EuroAdaptionThe application connects to the office server and gets + the multi component factory, opens an empty Calc document, enters an + example text, sets the number format to DM, changes the number format to + EUR (Euro), and uses the DM/EUR factor on each cell with content.
SCalcThe program connects to the office server and gets the + multi component factory. Then an empty calc document will be opened, + cell styles will be created, some data will be inserted into the sheets, + and the created cell styles will be applied. Finally, a 3D chart will be + inserted.
+
+ + + + + + + + + + + +
Drawing Document ExamplesDescription
SDrawThis program connects to the office server and gets + the multi component factory. Afterwards, an empty text document will + be created and some shapes will be inserted on the draw page.
+
+ + + + + + + + + + + + + + + + + + + + + + + +
Document Handling ExamplesDescription
DocumentConverterThe program offers a service that converts arbitrary + documents to a favored document type.
DocumentLoaderThe DocumentLoader can open a new or an + existing document.
DocumentPrinterThe DocumentPrinter allows you to print the + favored pages of a specified document on your favored printer.
DocumentSaverThe DocumentSaver shows how to save a document and + how you can change the type of your document.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
UNO Component ExamplesDescription
Object InspectorThe Object Inspector is primarily an auxiliary tool + for the developer, which can present information about an object of the + LibreOffice %PRODUCT_RELEASE% API at run-time. Depending on the object to be inspected, + appropriate methods, interfaces, services, and attributes can be displayed + to the developer. The methods, interfaces, services and attributes are + represented in a predictable tree. If the attributes contained in an + object are to be examined, the appropriate nodes in the tree can be + expanded with the help of the mouse. For each non primitive object, five + categories are offered to the user, as long as those are available with + that object. The Object Inspector is currently available as a NetBeans project + only because of major code changes. Please see the project page for further details.
MinimalComponentThis class provides a minimal UNO component. You can + take this class as a base for your own components. By extensions of this + class it is possible to also extend the function range of the Office.
PropTestContains a component that provides property set + interfaces by means of inheriting com.sun.star.lib.uno.helper.ProperterSet.
ToDoFor every to-do listed in a spreadsheet document, this + component calculates the start date, day of week of the start date, the + end date, and the day of week of the end date. All calculations are + dependent upon the values of "Needed Days", "Due Date" + and "Status". The columns "Needed Days" and + "Status" are mandatory. The first to-do should be placed in + row nine. The date to start the calculation should be placed in cell C6. + The private holidays should be placed in cell K4/K5 and below.
+ All rows will be calculated up to the first empty cell in the first + column. If a cell in the column "Due Date" is colored red, + you should take a look at your entries.
EmbeddedObjectContains a component that provides an example of embedded object implementation.
+
+ + + + +
+

Additional information:

+

+ How to write a UNO component in Java
+ Java UNO Language Binding
+ Debugging Java components
+

+
+
+
+ + + + + + + + + + +
+ + + + + + + + +
Python examples + + +
+
+ + + + + + + + + + + +
ExampleDescription
ToolPanelPocThis proof of concept extension illustrates how to create a ToolPanel in Calc.
+
+ + + + +
+

No Additional information

+
+
+
+ + + + + + + + + + +
+ + + + + + + + +
C++ examples + + +
+ The DocumentLoader example needs a running office server, before + running this program you should invoke the office with the following + command: +
+ soffice "--accept=socket,host=localhost,port=2083;urp;StarOffice.ServiceManager" +
+ You can also customize the mentioned host and port to your needs. +
+
+ + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
DocumentLoaderThis component works the same as the appropriate Java + example, but is implemented in C++.
CounterThis demo shows how to implement a very simple UNO + component and how to access the UNO component from an executable.
Remote clientThe 'uno' program is used to export an arbitrary + service to other processes. In this example the com.sun.star.uno.Pipe + service (which is built in io-module) is exported. The client component + implements the + com.sun.star.lang.XMain interface. In the run method, it connects to + the servers process and retrieves an instance and does some calls on the + instance.
complextoolbarcontrolsThis example shows how to create a toolbar add-on with complex toolbar controls. + It shows how to use an Image Button, a Combo Box, a Spin Field, an Edit Field, a Dropdown Box, a Toggle Dropdown Button and a normal Dropdown Button
+
+ + + + +
+

Additional information:

+

+ How to write a UNO component in C++
+ C++ UNO Language Binding
+ C++ reference +

+
+
+
+ + + + + + + + + + +
+ + + + + + + + +
LibreOffice %PRODUCT_RELEASE% Basic examples + + +
+

The example programs are embedded in LibreOffice %PRODUCT_RELEASE% documents in the + samples directory. To view or edit the LibreOffice %PRODUCT_RELEASE% Basic source, + select the appropriate document and then select Tools->Macro.

+

Most of the examples are stand-alone, but two of them (Creating an + Index and Import/Export of ASCII Files) have an associated data file + identified by a .txt file name suffix).

+

Some of the examples are also available in Java, you can find them in + the + Java section.

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
Changing Appearance To change the style used for certain words, you can + start with the following example. This code searches for the regular + expression the[a-z], which stands for the text portion the + followed by exactly one lowercase letter. All occurrences of these four + letters are then changed to bold characters. The same happens in the next + part of the program, this time changing the appearance of + all[a-z] to italic. In order for this example to work, you + must execute it from an open text document.
Replacing TextIf you regularly receive documents from other people + for editing, you might want to make sure that certain words are always + written the same. The next example illustrates this by forcing certain + words to be spelled in American English.
+ In order for this example to work, you must execute it from an open text + document. For a real world application, it is a good idea to read the + words from an external file.
Using Regular ExpressionsAnother application of automatic text modification is + related to stylistic questions. Suppose your company’s policy is to + avoid the use of certain words. You want to replace these words, but you + cannot do that automatically because you have to find the appropriate + replacement, which depends on the context. So instead of deleting or + replacing the offending words automatically, you change their color to + make them stand out during a subsequent manual review process.
+ The following example handles two kinds of unwanted wordings: those + which are absolutely forbidden and must be replaced by something else, + and those which are considered bad style. A subroutine is responsible + for the changes. It can be used to make all words in a list appear in a + certain color in the text document. To keep the lists short, we use + regular expressions which provide for the variants of the words + (plural, adjective etc.).
Inserting Bookmarks +

The next example does something very similar. This time, however, we + do not change the color of the words but insert a bookmark at each of + them. You can thus use the StarOffice navigator to jump directly from + word to word. Bookmarks must first be created using + createInstance(). They are then inserted with + insertTextContent() at the current text range.

+

The main difference to the preceding example is the For loop in + markList(). Instead of changing the color of the current + word, it creates a new bookmark, oBookmark, whose name is the current + word with an integer appended. It then inserts this bookmark at the + word.

Creating an IndexIndices for text documents can be created manually in + LibreOffice %PRODUCT_RELEASE% Writer by clicking on the words that should appear in the + index. If the document is large, or if you have to generate indices for + several documents, this task should be automated.
Adapting to EurolandMost of the members of the European Union will abandon + their old currency in favor of the new Euro in 2001. This requires + modifications to all programs using the old currencies. Since the exchange + rates for the old currencies have been fixed at the end of 1999, one can + already convert old data. The following program does this for all values + in a table that are formatted with the currency string DM.
Import/Export of ASCII FilesYou can use the drawing facilities of StarOffice API + to generate a picture from ASCII input. One application would be a + hierarchical representation of a directory listing, based on textual + data.
Stock Quotes UpdaterIf you want to display stock charts for certain + companies, you can open up your browser every day, go to a search engine, + look up the quote and copy it by hand into a table. Or you can use a + program that does all this automatically. The following example relies on + the sheet module. It uses URLs to obtain the current stock quotes. The + quotes are displayed in sheets, one for each company. We show a line + diagram and the numerical values for this company on every sheet. The + functionality is hidden in the three subroutines GetValue(), + UpdateValue(), and UpdateChart().
Forms and ControlsThe example document Burger Factory offers some forms + and controls, which you can use to order your desired burger type, + beverage, topping, and sauce. By hitting the button + "Order now!", your order will be placed.
+
+ + + + +
+ Additional information: OpenOffice.org %PRODUCT_RELEASE% Basic language binding +
+
+
+ + + + + + + + + + +
+ + + + + +
Object Linking and Embedding (OLE) examples + + +
+
+ + + + + + + + + + + + + + + +
ExampleDescription
ActiveX ControlThe ActiveX control shows an example of access to UNO + through COM technology. It requires a properly installed StarOffice + version 6.0 or OpenOffice 1.0 or newer. This is a Lite ActiveX control + so it can be used only in containers that allow the use of such controls. + It can be activated with an <OBJECT> tag from a html-page to embed + a document. Without any parameters a new writer document will be opened + for editing. For more details please see the README.
+ Note: This example works only under windows and if you don't use the MS + .Net C++ compiler please check the makefile and take notice of the + comments.
WriterDemoThis Visual Basic Script creates an empty text + document and inserts text, a table, and a text frame.
+
+ + + + +
+ Additional information: Automation Language Binding +
+
+
+ + + + + + + + + + +
+ + + + + +
Common Language Infrastructure (CLI) examples + + +
+
+ + + + + + + + + + + + + + + +
ExampleDescription
Spreadsheet ExampleThis example is written in C# and shows how Spreadsheet + documents are created and filled with content. This example actually + consists of three separate executables, SpreadsheetSample.exe, + GeneralTableSample.exe, ViewSample.exe.
WriterDemoThis example is written in VB.NET. It creates a text + document and inserts text, a table, and a text frame.
+
+ + + + +
+ Additional information: CLI-UNO Language Binding +
+
+
+
+ +
+
+
+ + diff --git a/odk/examples/java/ConverterServlet/ConverterServlet.html b/odk/examples/java/ConverterServlet/ConverterServlet.html new file mode 100644 index 000000000..7ef0a0db3 --- /dev/null +++ b/odk/examples/java/ConverterServlet/ConverterServlet.html @@ -0,0 +1,64 @@ + + +Document Converter + +

Document Converter

+

Converting documents with a remote running OpenOffice.org.

+
+ + + + + + + + + + + + + +
Local document + +
Target document type + +
Extension + +
+

The converted document will be returned by the server. If you selected the + target document type "swriter: HTML (StarWriter)" or "scalc: + HTML (StarCalc)", the document will be shown in the browser. If have an application + registered in your browser for the selected document type (mime type) the application will be started. + Otherwise, a dialog will be opened, which allows you to open or save the converted document.

+

+ +

+
+ diff --git a/odk/examples/java/ConverterServlet/ConverterServlet.java b/odk/examples/java/ConverterServlet/ConverterServlet.java new file mode 100644 index 000000000..91380ab86 --- /dev/null +++ b/odk/examples/java/ConverterServlet/ConverterServlet.java @@ -0,0 +1,325 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +// JDK API +import java.io.IOException; +import java.io.PrintWriter; +import java.io.File; +import java.util.Enumeration; + +// Servlet API +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +// Helper API +import com.oreilly.servlet.MultipartRequest; +import com.oreilly.servlet.MultipartResponse; +import com.oreilly.servlet.ServletUtils; + +// UNO API +import com.sun.star.bridge.XUnoUrlResolver; +import com.sun.star.uno.XComponentContext; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XStorable; +import com.sun.star.util.XCloseable; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; + + +/** This class implements a http servlet in order to convert an incoming document + * with help of a running OpenOffice.org and to push the converted file back + * to the client. + */ +public class ConverterServlet extends HttpServlet { + /** Specifies the temporary directory on the web server. + */ + private String stringWorkingDirectory = System.getProperty( "java.io.tmpdir" ).replace( '\\', '/' ); + + /** Specifies the host for the office server. + */ + private static final String stringHost = "localhost"; + + /** Specifies the port for the office server. + */ + private static final String stringPort = "2083"; + + /** Called by the server (via the service method) to allow a servlet to handle + * a POST request. The file from the client will be uploaded to the web server + * and converted on the web server and after all pushed to the client. + * @param request Object that contains the request the client has made of the servlet. + * @param response Object that contains the response the servlet sends to the client. + * @throws ServletException If the request for the POST could not be handled. + * @throws IOException If an input or output error is detected when the servlet handles the request. + */ + @Override + protected void doPost( HttpServletRequest request, + HttpServletResponse response) throws ServletException, java.io.IOException { + try { + // If necessary, add a slash to the end of the string. + if ( !stringWorkingDirectory.endsWith( "/" ) ) { + stringWorkingDirectory += "/"; + } + + // Construct a MultipartRequest to help read the information. + // Pass in the request, a directory to save files to, and the + // maximum POST size we should attempt to handle. + MultipartRequest multipartrequest = + new MultipartRequest( request, stringWorkingDirectory, 5 * 1024 * 1024 ); + + // Getting all file names from the request + Enumeration files = multipartrequest.getFileNames(); + + // Every received file will be converted to the specified type + while (files.hasMoreElements()) { + // Getting the name from the element + String stringName = (String)files.nextElement(); + + // Getting the filename from the request + String stringFilename = + multipartrequest.getFilesystemName( stringName ); + + // Converting the given file on the server to the specified type and + // append a special extension + File cleanupFile = null; + String stringSourceFile = stringWorkingDirectory + stringFilename; + + try { + String stringConvertedFile = convertDocument(stringSourceFile, + multipartrequest.getParameter( "converttype" ), + multipartrequest.getParameter( "extension" )); + + String shortFileName = stringConvertedFile.substring( + stringConvertedFile.lastIndexOf('/') + 1); + + // Set the response header + // Set the filename, is used when the file will be saved (problem with mozilla) + response.addHeader( "Content-Disposition", + "attachment; filename=" + shortFileName); + + // Constructing the multi part response to the client + MultipartResponse multipartresponse = new MultipartResponse(response); + + // Is the convert type HTML? + if ( ( multipartrequest.getParameter( "converttype" ).equals( + "swriter: HTML (StarWriter)" ) ) + || ( multipartrequest.getParameter( "converttype" ).equals( + "scalc: HTML (StarCalc)" ) ) ) { + // Setting the content type of the response being sent to the client + // to text + multipartresponse.startResponse( "text/html" ); + } else { + // Setting the content type of the response being sent to the client + // to application/octet-stream so that file will open a dialog box + // at the client in order to save the converted file + multipartresponse.startResponse( "application/octet-stream" ); + } + + // Pushing the converted file to the client + ServletUtils.returnFile( stringConvertedFile, + response.getOutputStream() ); + + // Finishing the multi part response + multipartresponse.finish(); + + // clean up the working directory + cleanupFile = new File(stringConvertedFile); + if ( cleanupFile.exists() ) + cleanupFile.delete(); + + } catch (Exception exc) { + response.setContentType( "text/html;charset=8859-1" ); + PrintWriter out = response.getWriter(); + + exc.printStackTrace(); + + out.println( "" ); + out.println( " " + "SDK Converter Servlet" + "" ); + out.println( "" ); + out.println( "

"); + out.println( "Sorry, the conversion failed!

"); + out.println( "

Error Message:
" + exc.getMessage() + "
"); + exc.printStackTrace(out); + out.println( "

"); + } + + // clean up the working directory + cleanupFile = new File(stringSourceFile); + if ( cleanupFile.exists() ) + cleanupFile.delete(); + } + } + catch (Exception exception) { + System.err.println( exception.toString() ); + } + } + + /** This method converts a document to a given type by using a running + * OpenOffice.org and saves the converted document to the specified + * working directory. + * @param stringDocumentName The full path name of the file on the server to be converted. + * @param stringConvertType Type to convert to. + * @param stringExtension This string will be appended to the file name of the converted file. + * @return The full path name of the converted file will be returned. + * @see stringWorkingDirectory + */ + private String convertDocument( String stringDocumentName, + String stringConvertType, + String stringExtension) + throws Exception + { + String stringConvertedFile = ""; + + // Converting the document to the favoured type +// try { + // Composing the URL + String stringUrl = "file:///" + stringDocumentName; + + /* Bootstraps a component context with the jurt base components + registered. Component context to be granted to a component for running. + Arbitrary values can be retrieved from the context. */ + XComponentContext xcomponentcontext = + com.sun.star.comp.helper.Bootstrap.createInitialComponentContext( null ); + + /* Gets the service manager instance to be used (or null). This method has + been added for convenience, because the service manager is an often used + object. */ + XMultiComponentFactory xmulticomponentfactory = + xcomponentcontext.getServiceManager(); + + /* Creates an instance of the component UnoUrlResolver which + supports the services specified by the factory. */ + Object objectUrlResolver = + xmulticomponentfactory.createInstanceWithContext( + "com.sun.star.bridge.UnoUrlResolver", xcomponentcontext ); + + // Create a new url resolver + XUnoUrlResolver xurlresolver = UnoRuntime.queryInterface( XUnoUrlResolver.class, + objectUrlResolver ); + + // Resolves an object that is specified as follow: + // uno:;; + Object objectInitial = xurlresolver.resolve( + "uno:socket,host=" + stringHost + ",port=" + stringPort + + ";urp;StarOffice.ServiceManager" ); + + // Create a service manager from the initial object + xmulticomponentfactory = UnoRuntime.queryInterface( XMultiComponentFactory.class, objectInitial ); + + // Query for the XPropertySet interface. + XPropertySet xpropertysetMultiComponentFactory = UnoRuntime.queryInterface( XPropertySet.class, xmulticomponentfactory ); + + // Get the default context from the office server. + Object objectDefaultContext = + xpropertysetMultiComponentFactory.getPropertyValue( "DefaultContext" ); + + // Query for the interface XComponentContext. + xcomponentcontext = UnoRuntime.queryInterface( + XComponentContext.class, objectDefaultContext ); + + /* A desktop environment contains tasks with one or more + frames in which components can be loaded. Desktop is the + environment for components which can instantiate within + frames. */ + XComponentLoader xcomponentloader = UnoRuntime.queryInterface( XComponentLoader.class, + xmulticomponentfactory.createInstanceWithContext( + "com.sun.star.frame.Desktop", xcomponentcontext ) ); + + // Preparing properties for loading the document + PropertyValue propertyvalue[] = new PropertyValue[ 1 ]; + // Setting the flag to hide the open document + propertyvalue[ 0 ] = new PropertyValue(); + propertyvalue[ 0 ].Name = "Hidden"; + propertyvalue[ 0 ].Value = Boolean.TRUE; + + // Loading the wanted document + Object objectDocumentToStore = + xcomponentloader.loadComponentFromURL( + stringUrl, "_blank", 0, propertyvalue ); + + // Getting an object that will offer a simple way to store a document to a URL. + XStorable xstorable = + UnoRuntime.queryInterface( XStorable.class, + objectDocumentToStore ); + + // Preparing properties for converting the document + propertyvalue = new PropertyValue[ 2 ]; + // Setting the flag for overwriting + propertyvalue[ 0 ] = new PropertyValue(); + propertyvalue[ 0 ].Name = "Overwrite"; + propertyvalue[ 0 ].Value = Boolean.TRUE; + // Setting the filter name + propertyvalue[ 1 ] = new PropertyValue(); + propertyvalue[ 1 ].Name = "FilterName"; + propertyvalue[ 1 ].Value = stringConvertType; + + // Appending the favoured extension to the origin document name + int index = stringUrl.lastIndexOf('.'); + if ( index >= 0 ) { + stringConvertedFile = stringUrl.substring(0, index) + "." + stringExtension; + } else { + stringConvertedFile = stringUrl + "." + stringExtension; + } + + // Storing and converting the document + xstorable.storeAsURL( stringConvertedFile, propertyvalue ); + + XCloseable xcloseable = UnoRuntime.queryInterface( XCloseable.class,xstorable ); + + // Closing the converted document + if ( xcloseable != null ) + xcloseable.close(false); + else { + // If Xcloseable is not supported (older versions, + // use dispose() for closing the document + XComponent xComponent = UnoRuntime.queryInterface( + XComponent.class, xstorable ); + xComponent.dispose(); + } + + if ( stringConvertedFile.startsWith( "file:///" ) ) { + // Truncating the beginning of the file name + stringConvertedFile = stringConvertedFile.substring( 8 ); + } + + // Returning the name of the converted file + return stringConvertedFile; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/ConverterServlet/Makefile b/odk/examples/java/ConverterServlet/Makefile new file mode 100644 index 000000000..2dff683c3 --- /dev/null +++ b/odk/examples/java/ConverterServlet/Makefile @@ -0,0 +1,93 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java ConverterServlet example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMPONENT_NAME=ConverterServletExample +OUT_COMP_CLASS=$(OUT_CLASS)/$(COMPONENT_NAME) + +JAVAFILES = \ + ConverterServlet.java + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OFFICE_CLASSES_DIR)/cos.jar\ + $(PATH_SEPARATOR)$(OFFICE_CLASSES_DIR)/servlet.jar\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + +# Targets +.PHONY: ALL +ALL : \ + ConverterServletExample + +include $(SETTINGS)/stdtarget.mk + +$(OFFICE_CLASSES_DIR)/cos.jar : + @echo -------------------------------------------------------------------------------- + @echo You need the servlet support Java archive "$(QM)cos.jar$(QM)" for this example. + @echo You can download it from "$(QM)http://www.servlets.com/cos/index.html$(QM)" + @echo and then please copy it into your "$(QM)$(OFFICE_CLASSES_DIR)$(QM)" directory. + @echo -------------------------------------------------------------------------------- + +$(OFFICE_CLASSES_DIR)/servlet.jar : + @echo -------------------------------------------------------------------------------- + @echo You need the servlet API "$(QM)servlet.jar$(QM)" for this example. + @echo You can download it from "$(QM)http://java.sun.com/products/servlet/index.html$(QM)" + @echo and then please copy it into your "$(QM)$(OFFICE_CLASSES_DIR)$(QM)" directory. + @echo -------------------------------------------------------------------------------- + +$(CLASSFILES) : $(JAVAFILES) $(OFFICE_CLASSES_DIR)/cos.jar $(OFFICE_CLASSES_DIR)/servlet.jar + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(JAVAFILES) + +ConverterServletExample : $(CLASSFILES) + @echo -------------------------------------------------------------------------------- + @echo Please see the README file for more information how to use the converter + @echo servlet. + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.class + $(JAVA) -classpath "$(SDK_CLASSPATH)" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) diff --git a/odk/examples/java/ConverterServlet/README b/odk/examples/java/ConverterServlet/README new file mode 100644 index 000000000..ea59b80b4 --- /dev/null +++ b/odk/examples/java/ConverterServlet/README @@ -0,0 +1,38 @@ +Servlet for converting documents +================================ + +Build preparation: +================== +In the file "ConverterServlet.html", search for the following line: +
+Replace the existing IP address (localhost) with your intended IP address. + +Installation instructions: +========================== +1. If no web server is available you should install your favourite web server. + The example was tested with a Tomcat 4.1 server (http://jakarta.apache.org/tomcat/) +2. Download the servlet support Java archive (cos.jar) from + http://www.servlets.com/cos/index.html and copy the file to the directory + /program/classes. If you don't use the created WAR (WAR = simple web archive file, it + is similar to a normal Jar file) file, please make these classes also known to your web server. +3. You need also the Servlet API (servlet.jar). The Tomcat server comes with this Servlet API. Please + copy the file "servlet.jar" to the directory /program/classes. + If you don't use the Tomcat server, make sure that the Servlet API is in the classpath of your web + server. You can download the Servlet API from http://java.sun.com/products/servlet/index.html . +4. Use your GNU make (http://www.gnu.org) to build the servlet class. +5. Make the servlet class known to your web server. + The example creates also a WAR file which can be easy deployed in a Tomcat server. + 5.1 Browse the 'Tomcat Web Application Manager' + 5.2 Navigate into the section 'Upload a WAR file to install' + 5.3 Browse to your generated WAR file and select it + 5.4 install it + + +Converting documents with the servlet: +====================================== +1. Browse your web server "http:///conversion/ConverterServlet.html" or + open the file "ConverterServlet.html" in your web browser and select a file. +2. Select a type to convert the file to, and the extension for the converted file. +3. Press the button. The document will be uploaded to the server, converted and + pushed back to the client. Your browser will open a dialog for saving the + converted document. diff --git a/odk/examples/java/ConverterServlet/web.xml b/odk/examples/java/ConverterServlet/web.xml new file mode 100644 index 000000000..10dfde5ec --- /dev/null +++ b/odk/examples/java/ConverterServlet/web.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/odk/examples/java/DocumentHandling/DocumentConverter.java b/odk/examples/java/DocumentHandling/DocumentConverter.java new file mode 100644 index 000000000..386af9f1f --- /dev/null +++ b/odk/examples/java/DocumentHandling/DocumentConverter.java @@ -0,0 +1,226 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; + +import java.io.File; + + +/** The class DocumentConverter allows you to convert all documents + * in a given directory and in its subdirectories to a given type. A converted + * document will be created in the same directory as the origin document. + * + */ +public class DocumentConverter { + /** Containing the loaded documents + */ + static com.sun.star.frame.XComponentLoader xCompLoader = null; + /** Containing the given type to convert to + */ + static String sConvertType = ""; + /** Containing the given extension + */ + static String sExtension = ""; + /** Containing the current file or directory + */ + static String sIndent = ""; + /** Containing the directory where the converted files are saved + */ + static String sOutputDir = ""; + + /** Traversing the given directory recursively and converting their files to + * the favoured type if possible + * @param fileDirectory Containing the directory + */ + static void traverse( File fileDirectory ) { + // Testing, if the file is a directory, and if so, it throws an exception + if ( !fileDirectory.isDirectory() ) { + throw new IllegalArgumentException( + "not a directory: " + fileDirectory.getName() + ); + } + + // Prepare Url for the output directory + File outdir = new File(DocumentConverter.sOutputDir); + String sOutUrl = "file:///" + outdir.getAbsolutePath().replace( '\\', '/' ); + + System.out.println("\nThe converted documents will stored in \"" + + outdir.getPath() + "!"); + + System.out.println(sIndent + "[" + fileDirectory.getName() + "]"); + sIndent += " "; + + // Getting all files and directories in the current directory + File[] entries = fileDirectory.listFiles(); + + + // Iterating for each file and directory + for ( int i = 0; i < entries.length; ++i ) { + // Testing, if the entry in the list is a directory + if ( entries[ i ].isDirectory() ) { + // Recursive call for the new directory + traverse( entries[ i ] ); + } else { + // Converting the document to the favoured type + try { + // Composing the URL by replacing all backslashes + String sUrl = "file:///" + + entries[ i ].getAbsolutePath().replace( '\\', '/' ); + + // Loading the wanted document + com.sun.star.beans.PropertyValue propertyValues[] = + new com.sun.star.beans.PropertyValue[1]; + propertyValues[0] = new com.sun.star.beans.PropertyValue(); + propertyValues[0].Name = "Hidden"; + propertyValues[0].Value = Boolean.TRUE; + + Object oDocToStore = + DocumentConverter.xCompLoader.loadComponentFromURL( + sUrl, "_blank", 0, propertyValues); + + // Getting an object that will offer a simple way to store + // a document to a URL. + com.sun.star.frame.XStorable xStorable = + UnoRuntime.queryInterface( + com.sun.star.frame.XStorable.class, oDocToStore ); + + // Preparing properties for converting the document + propertyValues = new com.sun.star.beans.PropertyValue[2]; + // Setting the flag for overwriting + propertyValues[0] = new com.sun.star.beans.PropertyValue(); + propertyValues[0].Name = "Overwrite"; + propertyValues[0].Value = Boolean.TRUE; + // Setting the filter name + propertyValues[1] = new com.sun.star.beans.PropertyValue(); + propertyValues[1].Name = "FilterName"; + propertyValues[1].Value = DocumentConverter.sConvertType; + + // Appending the favoured extension to the origin document name + int index1 = sUrl.lastIndexOf('/'); + int index2 = sUrl.lastIndexOf('.'); + String sStoreUrl = sOutUrl + sUrl.substring(index1, index2 + 1) + + DocumentConverter.sExtension; + + // Storing and converting the document + xStorable.storeAsURL(sStoreUrl, propertyValues); + + // Closing the converted document. Use XCloseable.close if the + // interface is supported, otherwise use XComponent.dispose + com.sun.star.util.XCloseable xCloseable = + UnoRuntime.queryInterface( + com.sun.star.util.XCloseable.class, xStorable); + + if ( xCloseable != null ) { + xCloseable.close(false); + } else { + com.sun.star.lang.XComponent xComp = + UnoRuntime.queryInterface( + com.sun.star.lang.XComponent.class, xStorable); + + xComp.dispose(); + } + } + catch( Exception e ) { + e.printStackTrace(System.err); + } + + System.out.println(sIndent + entries[ i ].getName()); + } + } + + sIndent = sIndent.substring(2); + } + + /** Bootstrap UNO, getting the remote component context, getting a new instance + * of the desktop (used interface XComponentLoader) and calling the + * static method traverse + * @param args The array of the type String contains the directory, in which + * all files should be converted, the favoured converting type + * and the wanted extension + */ + public static void main( String args[] ) { + if ( args.length < 3 ) { + System.out.println("usage: java -jar DocumentConverter.jar " + + "\"\" \"\" " + + "\"\" \"\""); + System.out.println("\ne.g.:"); + System.out.println("usage: java -jar DocumentConverter.jar " + + "\"c:/myoffice\" \"swriter: MS Word 97\" \"doc\""); + System.exit(1); + } + + com.sun.star.uno.XComponentContext xContext = null; + + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + // get the remote office service manager + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + + xCompLoader = UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class, + oDesktop); + + // Getting the given starting directory + File file = new File(args[0]); + + // Getting the given type to convert to + sConvertType = args[1]; + + // Getting the given extension that should be appended to the + // origin document + sExtension = args[2]; + + // Getting the given type to convert to + sOutputDir = args[3]; + + // Starting the conversion of documents in the given directory + // and subdirectories + traverse(file); + + System.exit(0); + } catch( Exception e ) { + e.printStackTrace(System.err); + System.exit(1); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/DocumentHandling/DocumentLoader.java b/odk/examples/java/DocumentHandling/DocumentLoader.java new file mode 100644 index 000000000..63d8dc66e --- /dev/null +++ b/odk/examples/java/DocumentHandling/DocumentLoader.java @@ -0,0 +1,94 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; + + +/** This class opens a new or an existing office document. + */ +public class DocumentLoader { + public static void main(String args[]) { + if ( args.length < 1 ) { + System.out.println( + "usage: java -jar DocumentLoader.jar \"\"" ); + System.out.println( "\ne.g.:" ); + System.out.println( + "java -jar DocumentLoader.jar \"private:factory/swriter\"" ); + System.exit(1); + } + + com.sun.star.uno.XComponentContext xContext = null; + + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + // get the remote office service manager + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + + com.sun.star.frame.XComponentLoader xCompLoader = + UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, oDesktop); + + String sUrl = args[0]; + if ( sUrl.indexOf("private:") != 0) { + java.io.File sourceFile = new java.io.File(args[0]); + StringBuffer sbTmp = new StringBuffer("file:///"); + sbTmp.append(sourceFile.getCanonicalPath().replace('\\', '/')); + sUrl = sbTmp.toString(); + } + + // Load a Writer document, which will be automatically displayed + com.sun.star.lang.XComponent xComp = xCompLoader.loadComponentFromURL( + sUrl, "_blank", 0, new com.sun.star.beans.PropertyValue[0]); + + if ( xComp != null ) + System.exit(0); + else + System.exit(1); + } + catch( Exception e ) { + e.printStackTrace(System.err); + System.exit(1); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/DocumentHandling/DocumentPrinter.java b/odk/examples/java/DocumentHandling/DocumentPrinter.java new file mode 100644 index 000000000..dfa35aedd --- /dev/null +++ b/odk/examples/java/DocumentHandling/DocumentPrinter.java @@ -0,0 +1,111 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; + + +public class DocumentPrinter { + public static void main(String args[]) { + if ( args.length < 3 ) { + System.out.println("usage: java -jar DocumentLoader.jar " + + "\"\" \"\" \"\""); + System.out.println( "\ne.g.:" ); + System.out.println("java -jar DocumentLoader.jar \"amadeus\" " + + "\"file:///f:/TestPrint.odt\" \"1-3;7;9\""); + System.exit(1); + } + + com.sun.star.uno.XComponentContext xContext = null; + + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + // get the remote office service manager + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + + com.sun.star.frame.XComponentLoader xCompLoader = + UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, oDesktop); + + java.io.File sourceFile = new java.io.File(args[1]); + StringBuffer sUrl = new StringBuffer("file:///"); + sUrl.append(sourceFile.getCanonicalPath().replace('\\', '/')); + + // Load a Writer document, which will be automatically displayed + com.sun.star.lang.XComponent xComp = xCompLoader.loadComponentFromURL( + sUrl.toString(), "_blank", 0, + new com.sun.star.beans.PropertyValue[0] ); + + // Querying for the interface XPrintable on the loaded document + com.sun.star.view.XPrintable xPrintable = + UnoRuntime.queryInterface( + com.sun.star.view.XPrintable.class, xComp); + + // Setting the property "Name" for the favoured printer (name of + // IP address) + com.sun.star.beans.PropertyValue propertyValue[] = + new com.sun.star.beans.PropertyValue[1]; + propertyValue[0] = new com.sun.star.beans.PropertyValue(); + propertyValue[0].Name = "Name"; + propertyValue[0].Value = args[ 0 ]; + + // Setting the name of the printer + xPrintable.setPrinter( propertyValue ); + + // Setting the property "Pages" so that only the desired pages + // will be printed. + propertyValue[0] = new com.sun.star.beans.PropertyValue(); + propertyValue[0].Name = "Pages"; + propertyValue[0].Value = args[ 2 ]; + + // Printing the loaded document + xPrintable.print( propertyValue ); + + System.exit(0); + } + catch( Exception e ) { + e.printStackTrace(System.err); + System.exit(1); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/DocumentHandling/DocumentSaver.java b/odk/examples/java/DocumentHandling/DocumentSaver.java new file mode 100644 index 000000000..ec1ce9242 --- /dev/null +++ b/odk/examples/java/DocumentHandling/DocumentSaver.java @@ -0,0 +1,131 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; + + +/** The purpose of this class is to open a specified text document and save this + * file to a specified URL. The type of the saved file is + * "swriter: StarOffice XML (Writer)". + */ +public class DocumentSaver { + /** The main method of the application. + * @param args The program needs two arguments: + * - full file name to open, + * - full file name to save. + */ + public static void main(String args[]) { + if ( args.length < 2 ) { + System.out.println("usage: java -jar DocumentSaver.jar" + + "\"\" \"\""); + System.out.println("\ne.g.:"); + System.out.println("java -jar DocumentSaver " + + "\"file:///f:/TestPrint.doc\"" + + "\"file:///f:/TestPrint.odt\""); + System.exit(1); + } + + com.sun.star.uno.XComponentContext xContext = null; + + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + // get the remote office service manager + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + + com.sun.star.frame.XComponentLoader xCompLoader = + UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, oDesktop); + + java.io.File sourceFile = new java.io.File(args[0]); + StringBuffer sLoadUrl = new StringBuffer("file:///"); + sLoadUrl.append(sourceFile.getCanonicalPath().replace('\\', '/')); + + sourceFile = new java.io.File(args[1]); + StringBuffer sSaveUrl = new StringBuffer("file:///"); + sSaveUrl.append(sourceFile.getCanonicalPath().replace('\\', '/')); + + com.sun.star.beans.PropertyValue[] propertyValue = + new com.sun.star.beans.PropertyValue[1]; + propertyValue[0] = new com.sun.star.beans.PropertyValue(); + propertyValue[0].Name = "Hidden"; + propertyValue[0].Value = Boolean.TRUE; + + Object oDocToStore = xCompLoader.loadComponentFromURL( + sLoadUrl.toString(), "_blank", 0, propertyValue ); + com.sun.star.frame.XStorable xStorable = + UnoRuntime.queryInterface( + com.sun.star.frame.XStorable.class, oDocToStore ); + + propertyValue = new com.sun.star.beans.PropertyValue[ 2 ]; + propertyValue[0] = new com.sun.star.beans.PropertyValue(); + propertyValue[0].Name = "Overwrite"; + propertyValue[0].Value = Boolean.TRUE; + propertyValue[1] = new com.sun.star.beans.PropertyValue(); + propertyValue[1].Name = "FilterName"; + propertyValue[1].Value = "StarOffice XML (Writer)"; + xStorable.storeAsURL( sSaveUrl.toString(), propertyValue ); + + System.out.println("\nDocument \"" + sLoadUrl + "\" saved under \"" + + sSaveUrl + "\"\n"); + + com.sun.star.util.XCloseable xCloseable = UnoRuntime.queryInterface(com.sun.star.util.XCloseable.class, + oDocToStore ); + + if (xCloseable != null ) { + xCloseable.close(false); + } else + { + com.sun.star.lang.XComponent xComp = UnoRuntime.queryInterface( + com.sun.star.lang.XComponent.class, oDocToStore ); + xComp.dispose(); + } + System.out.println("document closed!"); + System.exit(0); + } + catch( Exception e ) { + e.printStackTrace(System.err); + System.exit(1); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/DocumentHandling/Makefile b/odk/examples/java/DocumentHandling/Makefile new file mode 100644 index 000000000..d8eff760d --- /dev/null +++ b/odk/examples/java/DocumentHandling/Makefile @@ -0,0 +1,144 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java DocumentHandling examples of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +SAMPLE_NAME=JavaDocumentHandlingExamples +SAMPLE_CLASS_OUT = $(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT = $(OUT_MISC)/$(SAMPLE_NAME) + +DIRFLAG=$(OUT_MISC)/$(SAMPLE_NAME)_directory.flag + +APP1_NAME=DocumentConverter +APP1_JAR=$(SAMPLE_CLASS_OUT)/$(APP1_NAME).jar +APP2_NAME=DocumentLoader +APP2_JAR=$(SAMPLE_CLASS_OUT)/$(APP2_NAME).jar +APP3_NAME=DocumentPrinter +APP3_JAR=$(SAMPLE_CLASS_OUT)/$(APP3_NAME).jar +APP4_NAME=DocumentSaver +APP4_JAR=$(SAMPLE_CLASS_OUT)/$(APP4_NAME).jar + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : \ + $(SAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(SAMPLE_CLASS_OUT)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(SAMPLE_CLASS_OUT) $< + +$(SAMPLE_CLASS_OUT)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(SAMPLE_CLASS_OUT)/%.jar : $(SAMPLE_CLASS_OUT)/%.mf $(SAMPLE_CLASS_OUT)/%.class + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP1_JAR) : $(SAMPLE_CLASS_OUT)/$(APP1_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP1_NAME).class +$(APP2_JAR) : $(SAMPLE_CLASS_OUT)/$(APP2_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP2_NAME).class +$(APP3_JAR) : $(SAMPLE_CLASS_OUT)/$(APP3_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP3_NAME).class +$(APP4_JAR) : $(SAMPLE_CLASS_OUT)/$(APP4_NAME).mf $(SAMPLE_CLASS_OUT)/$(APP4_NAME).class + +$(SAMPLE_NAME) : $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) $(APP4_JAR) + @echo -------------------------------------------------------------------------------- + @echo The $(APP1_NAME) search the "$(QM)./test$(QM)" directory for documents, convert + @echo them using the "$(QM)MS Word 97$(QM)" filter and the extension "$(QM).doc$(QM)". + @echo The converted files are store in "$(QM)$(SAMPLE_GEN_OUT)/converted_files$(QM)". + @echo The list of possible filter names can change. Normally an updated list can be found + @echo on "$(QM)http://www.openoffice.org/files/documents/25/111/filter_description.html$(QM)". + @echo - + @echo The $(APP2_NAME) loads the document "$(QM)./test/test1.odt$(QM)". + @echo - + @echo The $(APP3_NAME) prints the document "$(QM)./test/test1.odt$(QM)" using the + @echo the specified printer. If the printer is unknown, the default printer is used. + @echo - + @echo The $(APP5_NAME) loads the document "$(QM)./test/test1.odt$(QM)" and saves it + @echo under "$(QM)$(SAMPLE_GEN_OUT)/savetest/testsave.odt$(QM)". + @echo - + @echo Please use one of the following commands to execute the examples! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo $(MAKE) $(APP2_NAME).run + @echo $(MAKE) $(APP3_NAME).run + @echo $(MAKE) $(APP4_NAME).run + @echo -------- + @echo The examples need parameters. Please use one the following commands to + @echo start the demo if you do not want the default parameters specified in the + @echo this makefile. Starting without parameters print a command line help: + @echo --- $(APP1_NAME) --- + @echo java -jar $(APP1_NAME).jar "$(QM)directory$(QM)" "$(QM)filter name$(QM)" "$(QM)extension$(QM)" "$(QM)output_directory$(QM)" + @echo --- $(APP2_NAME) --- + @echo java -jar $(APP2_NAME).jar "$(QM)Url|path$(QM)" + @echo --- $(APP3_NAME) --- + @echo java -jar $(APP3_NAME).jar "$(QM)printername$(QM)" "$(QM)filename$(QM)" "$(QM)pages$(QM)" + @echo --- $(APP4_NAME) --- + @echo java -jar $(APP4_NAME).jar "$(QM)load Url|path$(QM)" "$(QM)save Url|path$(QM)" + @echo -------------------------------------------------------------------------------- + +$(APP1_NAME).run: $(APP1_JAR) + -$(MKDIR) $(subst /,$(PS),$(SAMPLE_GEN_OUT)/converted_files) + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< "./test" "MS Word 97" "doc" "$(SAMPLE_GEN_OUT)/converted_files" + +$(APP2_NAME).run: $(APP2_JAR) + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< "./test/test1.odt" + +$(APP3_NAME).run: $(APP3_JAR) + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< "my_printer" "./test/test1.odt" 1 + +$(APP4_NAME).run: $(APP4_JAR) + -$(MKDIR) $(subst /,$(PS),$(SAMPLE_GEN_OUT)/savetest) + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< "./test/test1.odt" "$(SAMPLE_GEN_OUT)/savetest/testsave.odt" + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) diff --git a/odk/examples/java/DocumentHandling/test/test1.odt b/odk/examples/java/DocumentHandling/test/test1.odt new file mode 100644 index 000000000..6a3c769ee Binary files /dev/null and b/odk/examples/java/DocumentHandling/test/test1.odt differ diff --git a/odk/examples/java/Drawing/Makefile b/odk/examples/java/Drawing/Makefile new file mode 100644 index 000000000..861ab96ff --- /dev/null +++ b/odk/examples/java/Drawing/Makefile @@ -0,0 +1,91 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java Drawing example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=JavaDrawingExample +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +APP1_NAME=SDraw +APP1_JAR=$(OUT_APP_CLASS)/$(APP1_NAME).jar + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + +# Targets +.PHONY: ALL +ALL : \ + $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_APP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(OUT_APP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(OUT_APP_CLASS)/%.jar : $(OUT_APP_CLASS)/%.mf $(OUT_APP_CLASS)/%.class + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(OUT_APP_CLASS)/$(APP1_NAME).class + +$(EXAMPLE_NAME) : $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) SDraw.run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/java/Drawing/SDraw.java b/odk/examples/java/Drawing/SDraw.java new file mode 100644 index 000000000..5d2f9a52e --- /dev/null +++ b/odk/examples/java/Drawing/SDraw.java @@ -0,0 +1,266 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +// comment: Step 1: bootstrap UNO and get the remote component context +// Step 2: open an empty text document +// Step 3: get the drawpage an insert some shapes + + + +import com.sun.star.uno.UnoRuntime; + +public class SDraw { + + + public static void main(String args[]) { + + //oooooooooooooooooooooooooooStep 1oooooooooooooooooooooooooooooooooooooooo + // bootstrap UNO and get the remote component context. The context can + // be used to get the service manager + + com.sun.star.uno.XComponentContext xContext = null; + + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + com.sun.star.lang.XComponent xDrawDoc = null; + com.sun.star.drawing.XDrawPage xDrawPage = null; + + //oooooooooooooooooooooooooooStep 2oooooooooooooooooooooooooooooooooooooooo + // open an empty document. In this case it's a draw document. + // For this purpose an instance of com.sun.star.frame.Desktop + // is created. It's interface XDesktop provides the XComponentLoader, + // which is used to open the document via loadComponentFromURL + + + //Open document + //Draw + System.out.println("Opening an empty Draw document ..."); + xDrawDoc = openDraw(xContext); + + //oooooooooooooooooooooooooooStep 3oooooooooooooooooooooooooooooooooooooooo + // get the drawpage an insert some shapes. + // the documents DrawPageSupplier supplies the DrawPage vi IndexAccess + // To add a shape get the MultiServiceFaktory of the document, create an + // instance of the ShapeType and add it to the Shapes-container + // provided by the drawpage + + + + // get the drawpage of drawing here + try { + System.out.println( "getting Drawpage" ); + com.sun.star.drawing.XDrawPagesSupplier xDPS = + UnoRuntime.queryInterface( + com.sun.star.drawing.XDrawPagesSupplier.class, xDrawDoc); + com.sun.star.drawing.XDrawPages xDPn = xDPS.getDrawPages(); + com.sun.star.container.XIndexAccess xDPi = + UnoRuntime.queryInterface( + com.sun.star.container.XIndexAccess.class, xDPn); + xDrawPage = UnoRuntime.queryInterface( + com.sun.star.drawing.XDrawPage.class, xDPi.getByIndex(0)); + } catch ( Exception e ) { + System.err.println( "Couldn't create document"+ e ); + e.printStackTrace(System.err); + } + + createSequence(xDrawDoc, xDrawPage); + + //put something on the drawpage + System.out.println( "inserting some Shapes" ); + com.sun.star.drawing.XShapes xShapes = UnoRuntime.queryInterface( + com.sun.star.drawing.XShapes.class, xDrawPage); + xShapes.add(createShape(xDrawDoc,2000,1500,1000,1000,"Line",0)); + xShapes.add(createShape(xDrawDoc,3000,4500,15000,1000,"Ellipse",16711680)); + xShapes.add(createShape(xDrawDoc,5000,3500,7500,5000,"Rectangle",6710932)); + + + System.out.println("done"); + System.exit(0); + } + + public static com.sun.star.lang.XComponent openDraw( + com.sun.star.uno.XComponentContext xContext) + { + com.sun.star.frame.XComponentLoader xCLoader; + com.sun.star.lang.XComponent xComp = null; + + try { + // get the remote office service manager + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + + xCLoader = UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class, + oDesktop); + com.sun.star.beans.PropertyValue szEmptyArgs[] = + new com.sun.star.beans.PropertyValue[0]; + String strDoc = "private:factory/sdraw"; + xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs); + + } catch(Exception e){ + System.err.println(" Exception " + e); + e.printStackTrace(System.err); + } + + return xComp; + } + + public static com.sun.star.drawing.XShape createShape( + com.sun.star.lang.XComponent xDocComp, int height, int width, int x, + int y, String kind, int col) + { + //possible values for kind are 'Ellipse', 'Line' and 'Rectangle' + com.sun.star.awt.Size size = new com.sun.star.awt.Size(); + com.sun.star.awt.Point position = new com.sun.star.awt.Point(); + com.sun.star.drawing.XShape xShape = null; + + //get MSF + com.sun.star.lang.XMultiServiceFactory xDocMSF = + UnoRuntime.queryInterface( + com.sun.star.lang.XMultiServiceFactory.class, xDocComp ); + + try { + Object oInt = xDocMSF.createInstance("com.sun.star.drawing." + +kind + "Shape"); + xShape = UnoRuntime.queryInterface( + com.sun.star.drawing.XShape.class, oInt); + size.Height = height; + size.Width = width; + position.X = x; + position.Y = y; + xShape.setSize(size); + xShape.setPosition(position); + + } catch ( Exception e ) { + System.err.println( "Couldn't create instance "+ e ); + e.printStackTrace(System.err); + } + + com.sun.star.beans.XPropertySet xSPS = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xShape); + + try { + xSPS.setPropertyValue("FillColor", Integer.valueOf(col)); + } catch (Exception e) { + System.err.println("Can't change colors " + e); + e.printStackTrace(System.err); + } + + return xShape; + } + + public static com.sun.star.drawing.XShape createSequence( + com.sun.star.lang.XComponent xDocComp, com.sun.star.drawing.XDrawPage xDP) + { + com.sun.star.awt.Size size = new com.sun.star.awt.Size(); + com.sun.star.awt.Point position = new com.sun.star.awt.Point(); + com.sun.star.drawing.XShape xShape = null; + com.sun.star.drawing.XShapes xShapes = UnoRuntime.queryInterface(com.sun.star.drawing.XShapes.class, xDP); + int height = 3000; + int width = 3500; + int x = 1900; + int y = 20000; + Object oInt = null; + int r = 40; + int g = 0; + int b = 80; + + //get MSF + com.sun.star.lang.XMultiServiceFactory xDocMSF = + UnoRuntime.queryInterface( + com.sun.star.lang.XMultiServiceFactory.class, xDocComp ); + + for (int i=0; i<370; i=i+25) { + try{ + oInt = xDocMSF.createInstance("com.sun.star.drawing.EllipseShape"); + xShape = UnoRuntime.queryInterface( + com.sun.star.drawing.XShape.class, oInt); + size.Height = height; + size.Width = width; + position.X = (x+(i*40)); + position.Y = + (new Float(y+(Math.sin((i*Math.PI)/180))*5000)).intValue(); + xShape.setSize(size); + xShape.setPosition(position); + + } catch ( Exception e ) { + // Some exception occurs.FAILED + System.err.println( "Couldn't get Shape "+ e ); + e.printStackTrace(System.err); + } + + b=b+8; + + com.sun.star.beans.XPropertySet xSPS = UnoRuntime.queryInterface(com.sun.star.beans.XPropertySet.class, + xShape); + + try { + xSPS.setPropertyValue("FillColor", Integer.valueOf(getCol(r,g,b))); + xSPS.setPropertyValue("Shadow", Boolean.TRUE); + } catch (Exception e) { + System.err.println("Can't change colors " + e); + e.printStackTrace(System.err); + } + xShapes.add(xShape); + } + + com.sun.star.drawing.XShapeGrouper xSGrouper = + UnoRuntime.queryInterface( + com.sun.star.drawing.XShapeGrouper.class, xDP); + + xShape = xSGrouper.group(xShapes); + + return xShape; + } + + public static int getCol(int r, int g, int b) { + return r*65536+g*256+b; + } +} + + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/EmbedDocument/Container1/EmbedContApp.java b/odk/examples/java/EmbedDocument/Container1/EmbedContApp.java new file mode 100644 index 000000000..a275c27ea --- /dev/null +++ b/odk/examples/java/EmbedDocument/Container1/EmbedContApp.java @@ -0,0 +1,1044 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import java.awt.*; +import java.applet.*; +import java.awt.event.*; +import java.net.*; +import java.io.*; + +import javax.swing.JOptionPane; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; + +import com.sun.star.lang.XComponent; + +import com.sun.star.beans.PropertyValue; + +import com.sun.star.datatransfer.DataFlavor; +import com.sun.star.datatransfer.XTransferable; + +import com.sun.star.container.XNameAccess; + +import com.sun.star.io.XStream; +import com.sun.star.io.XInputStream; +import com.sun.star.io.XOutputStream; +import com.sun.star.io.XTruncate; + +import com.sun.star.util.XCloseable; + +import com.sun.star.embed.*; + +public class EmbedContApp extends Applet implements MouseListener, XEmbeddedClient +{ + private XMultiServiceFactory m_xServiceFactory; + + private XEmbeddedObject m_xEmbedObj; + private XStorage m_xStorage; + + private Frame m_aFrame; + private Menu m_aFileMenu; + private Menu m_aObjectMenu; + private Toolkit m_aToolkit; + private Image m_aImage; + + private boolean m_bOwnFile = false; + + private boolean m_bLinkObj = false; + private String m_aLinkURI; + + public EmbedContApp( Frame aFrame, XMultiServiceFactory xServiceFactory ) + { + m_aFrame = aFrame; + m_xServiceFactory = xServiceFactory; + } + + public void init() + { + resize( 640, 480 ); + setBackground( Color.gray ); + + m_aToolkit = Toolkit.getDefaultToolkit(); + + // Get a menu bar. + MenuBar aMenuBar = m_aFrame.getMenuBar(); + if( aMenuBar == null ) + { + aMenuBar = new MenuBar(); + m_aFrame.setMenuBar( aMenuBar ); + } + + // Create menus for the menu bar. + + // File menu + m_aFileMenu = new Menu( "File", true ); + aMenuBar.add( m_aFileMenu ); + + MenuItem aItem = new NewMenuItem(); + m_aFileMenu.add( aItem ); + + aItem = new OpenFileMenuItem(); + m_aFileMenu.add( aItem ); + + aItem = new SaveMenuItem(); + m_aFileMenu.add( aItem ); + + aItem = new SaveAsMenuItem(); + m_aFileMenu.add( aItem ); + + // Object menu + m_aObjectMenu = new Menu( "Object", true ); + aMenuBar.add( m_aObjectMenu ); + + aItem = new NewObjectMenuItem(); + m_aObjectMenu.add( aItem ); + + aItem = new LoadObjectMenuItem(); + m_aObjectMenu.add( aItem ); + + aItem = new LinkObjectMenuItem(); + m_aObjectMenu.add( aItem ); + + aItem = new ConvertLinkToEmbedMenuItem(); + m_aObjectMenu.add( aItem ); + + // Handle mouse clicks in our window. + addMouseListener( this ); + } + + public void update( Graphics g ) + { + paint( g ); + } + + public void paint( Graphics g ) + { + super.paint( g ); + + if ( m_xEmbedObj != null ) + { + synchronized( this ) + { + if ( m_aImage != null ) + g.drawImage( m_aImage, 0, 0, EmbedContApp.this ); + } + } + } + + public void generateNewImage() + { + if ( m_xEmbedObj != null ) + { + try { + int nOldState = m_xEmbedObj.getCurrentState(); + int nState = nOldState; + if ( nOldState == EmbedStates.LOADED ) + { + m_xEmbedObj.changeState( EmbedStates.RUNNING ); + nState = EmbedStates.RUNNING; + } + + if ( nState == EmbedStates.ACTIVE || nState == EmbedStates.RUNNING ) + { + XComponentSupplier xCompProv = (XComponentSupplier)UnoRuntime.queryInterface( + XComponentSupplier.class, + m_xEmbedObj ); + if ( xCompProv != null ) + { + XCloseable xComp = xCompProv.getComponent(); + XTransferable xTransfer = (XTransferable)UnoRuntime.queryInterface( + XTransferable.class, + xComp ); + if ( xTransfer != null ) + { + DataFlavor aFlavor = new DataFlavor(); + aFlavor.MimeType = "image/png"; + aFlavor.HumanPresentableName = "Portable Network Graphics"; + aFlavor.DataType = new Type( byte[].class ); + + byte[] aPNGData = (byte[])AnyConverter.toArray( xTransfer.getTransferData( aFlavor ) ); + if ( aPNGData != null && aPNGData.length != 0 ) + { + synchronized( this ) + { + m_aImage = m_aToolkit.createImage( aPNGData ); + } + } + } + else + System.out.println( "paint() : can not get XTransferable for the component!\n" ); + } + else + System.out.println( "paint() : XComponentSupplier is not implemented!\n" ); + } + } + catch( com.sun.star.uno.Exception e ) + { + // dialogs should not be used in paint() + System.out.println( "Exception in paint(): " + e ); + } + } + } + + public void mouseClicked( MouseEvent e ) + { + if( e.getModifiers() == InputEvent.BUTTON1_MASK ) + { + // activate object if exists and not active + if ( m_xEmbedObj != null ) + { + try { + m_xEmbedObj.changeState( EmbedStates.ACTIVE ); + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( m_aFrame, ex, "Exception on mouse click", JOptionPane.ERROR_MESSAGE ); + } + } + } + } + + public void mousePressed( MouseEvent e ){}; + public void mouseEntered( MouseEvent e ){}; + public void mouseExited( MouseEvent e ){}; + public void mouseReleased( MouseEvent e ){}; + + // XEmbeddedClient + public void saveObject() + throws com.sun.star.uno.Exception + { + if ( m_xEmbedObj != null ) + { + try { + XEmbedPersist xPersist = (XEmbedPersist)UnoRuntime.queryInterface( XEmbedPersist.class, m_xEmbedObj ); + if ( xPersist != null ) + { + xPersist.storeOwn(); + generateNewImage(); + } + else + JOptionPane.showMessageDialog( m_aFrame, "No XEmbedPersist!", "Error:", JOptionPane.ERROR_MESSAGE ); + } + catch( Exception e ) + { + JOptionPane.showMessageDialog( m_aFrame, e, "Exception in saveObject:", JOptionPane.ERROR_MESSAGE ); + } + } + + generateNewImage(); + repaint(); + } + + public void onShowWindow( boolean bVisible ) + { + // for now nothing to do + } + + class NewMenuItem extends MenuItem implements ActionListener // Menu New + { + public NewMenuItem() + { + super( "New", new MenuShortcut( KeyEvent.VK_A )); + addActionListener( this ); + } + + public void actionPerformed( ActionEvent e ) + { + // clear everything + clearObjectAndStorage(); + + repaint(); + } + } + + class SaveAsMenuItem extends MenuItem implements ActionListener // Menu SaveAs... + { + public SaveAsMenuItem() + { + super( "SaveAs..." ); + addActionListener( this ); + } + + public void actionPerformed( ActionEvent e ) + { + // open SaveAs dialog and store + + if ( m_xStorage != null && m_xEmbedObj != null ) + { + FileDialog aFileDialog = new FileDialog( m_aFrame, "SaveAs", FileDialog.SAVE ); + aFileDialog.show(); + if ( aFileDialog.getFile() != null ) + { + String aFileName = aFileDialog.getDirectory() + aFileDialog.getFile(); + File aFile = new File( aFileName ); + if ( aFile != null ) + { + // create object from specified file + String aFileURI = aFile.toURI().toASCIIString(); + try { + saveObject(); + + if ( m_bLinkObj ) + storeLinkToStorage(); + + saveStorageAsFileURI( aFileURI ); + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( m_aFrame, + ex, + "Exception in SaveAsMenuItem:", + JOptionPane.ERROR_MESSAGE ); + } + } + } + } + else + JOptionPane.showMessageDialog( m_aFrame, "No document is embedded!", "Error:", JOptionPane.ERROR_MESSAGE ); + } + } + + class OpenFileMenuItem extends MenuItem implements ActionListener // Menu Open + { + public OpenFileMenuItem() + { + super( "Open", new MenuShortcut( KeyEvent.VK_C )); + addActionListener( this ); + } + + public void actionPerformed( ActionEvent e ) + { + // clear everything + clearObjectAndStorage(); + + // open OpenFile dialog and load doc + FileDialog aFileDialog = new FileDialog( m_aFrame, "Open" ); + aFileDialog.show(); + if ( aFileDialog.getFile() != null ) + { + String aFileName = aFileDialog.getDirectory() + aFileDialog.getFile(); + File aFile = new File( aFileName ); + if ( aFile != null ) + { + // create object from specified file + String aFileURI = aFile.toURI().toASCIIString(); + + // load from specified file + loadFileURI( aFileURI ); + + if ( m_xEmbedObj != null ) + { + try { + m_xEmbedObj.setClientSite( EmbedContApp.this ); + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( m_aFrame, + ex, + "Exception in OpenFileMenuItem:", + JOptionPane.ERROR_MESSAGE ); + } + } + } + } + + generateNewImage(); + repaint(); + } + } + + class SaveMenuItem extends MenuItem implements ActionListener // Menu Save + { + public SaveMenuItem() + { + super( "Save", new MenuShortcut( KeyEvent.VK_D )); + addActionListener( this ); + } + + public void actionPerformed( ActionEvent e ) + { + // if has persistence store there + // if not open SaveAs dialog and store + if ( m_xStorage != null && m_xEmbedObj != null ) + { + if ( m_bOwnFile ) + { + if ( m_xStorage == null ) + { + JOptionPane.showMessageDialog( m_aFrame, + "No storage for owned file!", + "Error:", + JOptionPane.ERROR_MESSAGE ); + return; + } + + try { + saveObject(); + + if ( m_bLinkObj ) + storeLinkToStorage(); + + XTransactedObject xTransact = (XTransactedObject)UnoRuntime.queryInterface( XTransactedObject.class, + m_xStorage ); + if ( xTransact != null ) + xTransact.commit(); + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( m_aFrame, + ex, + "Exception during save operation in SaveMenuItem:", + JOptionPane.ERROR_MESSAGE ); + } + } + else + { + FileDialog aFileDialog = new FileDialog( m_aFrame, "SaveAs", FileDialog.SAVE ); + aFileDialog.show(); + if ( aFileDialog.getFile() != null ) + { + String aFileName = aFileDialog.getDirectory() + aFileDialog.getFile(); + File aFile = new File( aFileName ); + if ( aFile != null ) + { + // create object from specified file + String aFileURI = aFile.toURI().toASCIIString(); + try { + saveObject(); + + if ( m_bLinkObj ) + storeLinkToStorage(); + + saveStorageAsFileURI( aFileURI ); + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( m_aFrame, + ex, + "Exception during 'save as' operation in SaveMenuItem:", + JOptionPane.ERROR_MESSAGE ); + } + } + } + } + } + else + JOptionPane.showMessageDialog( m_aFrame, "No document is embedded!", "Error:", JOptionPane.ERROR_MESSAGE ); + } + } + + class NewObjectMenuItem extends MenuItem implements ActionListener // Menu NewObject + { + public NewObjectMenuItem() + { + super( "Create", new MenuShortcut( KeyEvent.VK_N )); + addActionListener( this ); + } + + public void actionPerformed( ActionEvent e ) + { + // remove current object an init a new one + clearObjectAndStorage(); + + Object[] possibleValues = { "com.sun.star.comp.Writer.TextDocument", + "com.sun.star.comp.Writer.GlobalDocument", + "com.sun.star.comp.Writer.WebDocument", + "com.sun.star.comp.Calc.SpreadsheetDocument", + "com.sun.star.comp.Draw.PresentationDocument", + "com.sun.star.comp.Draw.DrawingDocument", + "com.sun.star.comp.Math.FormulaDocument" }; + + String selectedValue = (String)JOptionPane.showInputDialog( null, "DocumentType", "Select", + JOptionPane.INFORMATION_MESSAGE, null, + possibleValues, possibleValues[0] ); + + if ( selectedValue != null ) + { + m_xStorage = createTempStorage(); + + if ( m_xStorage != null ) + m_xEmbedObj = createEmbedObject( selectedValue ); + else + JOptionPane.showMessageDialog( m_aFrame, + "Can't create temporary storage!", + "Error:", + JOptionPane.ERROR_MESSAGE ); + + + if ( m_xEmbedObj != null ) + { + try { + m_xEmbedObj.setClientSite( EmbedContApp.this ); + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( m_aFrame, + ex, + "Exception in NewObjectMenuItem:", + JOptionPane.ERROR_MESSAGE ); + } + } + } + + generateNewImage(); + repaint(); + } + } + + class LoadObjectMenuItem extends MenuItem implements ActionListener // Menu LoadObject + { + public LoadObjectMenuItem() + { + super( "Load from file", new MenuShortcut( KeyEvent.VK_L )); + addActionListener( this ); + } + + public void actionPerformed( ActionEvent e ) + { + // first remove current object + clearObjectAndStorage(); + + // open OpenFile dialog and load doc + FileDialog aFileDialog = new FileDialog( m_aFrame, "Select sources to use for object init" ); + aFileDialog.show(); + if ( aFileDialog.getFile() != null ) + { + String aFileName = aFileDialog.getDirectory() + aFileDialog.getFile(); + File aFile = new File( aFileName ); + if ( aFile != null ) + { + // create object from specified file + String aFileURI = aFile.toURI().toASCIIString(); + m_xStorage = createTempStorage(); + + if ( m_xStorage != null ) + m_xEmbedObj = loadEmbedObject( aFileURI ); + + if ( m_xEmbedObj != null ) + { + try { + m_xEmbedObj.setClientSite( EmbedContApp.this ); + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( m_aFrame, + ex, + "Exception in LoadObjectMenuItem:", + JOptionPane.ERROR_MESSAGE ); + } + } + } + } + + generateNewImage(); + repaint(); + } + } + + class LinkObjectMenuItem extends MenuItem implements ActionListener // Menu LinkObject + { + public LinkObjectMenuItem() + { + super( "Create link", new MenuShortcut( KeyEvent.VK_M )); + addActionListener( this ); + } + + public void actionPerformed( ActionEvent e ) + { + // first remove current object + clearObjectAndStorage(); + + // open OpenFile dialog and load doc + FileDialog aFileDialog = new FileDialog( m_aFrame, "Select sources to use for object init" ); + aFileDialog.show(); + if ( aFileDialog.getFile() != null ) + { + m_xStorage = createTempStorage(); + + String aFileName = aFileDialog.getDirectory() + aFileDialog.getFile(); + File aFile = new File( aFileName ); + if ( aFile != null ) + { + // create object from specified file + String aFileURI = aFile.toURI().toASCIIString(); + + m_xEmbedObj = createLinkObject( aFileURI ); + + if ( m_xEmbedObj != null ) + { + m_aLinkURI = aFileURI; + m_bLinkObj = true; + + try { + m_xEmbedObj.setClientSite( EmbedContApp.this ); + } + catch( Exception ex ) + { + JOptionPane.showMessageDialog( m_aFrame, + ex, + "Exception in LinkObjectMenuItem:", + JOptionPane.ERROR_MESSAGE ); + } + } + } + } + + generateNewImage(); + repaint(); + } + } + + class ConvertLinkToEmbedMenuItem extends MenuItem implements ActionListener // Menu LinkObject + { + public ConvertLinkToEmbedMenuItem() + { + super( "Convert link to embed", new MenuShortcut( KeyEvent.VK_M )); + addActionListener( this ); + } + + public void actionPerformed( ActionEvent e ) + { + if ( !m_bLinkObj ) + { + JOptionPane.showMessageDialog( m_aFrame, "The object is not a link!", "Error:", JOptionPane.ERROR_MESSAGE ); + return; + } + + if ( m_xEmbedObj != null ) + { + if ( m_xStorage != null ) + { + try { + XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface( XNameAccess.class, + m_xStorage ); + if ( xNameAccess != null && xNameAccess.hasByName( "LinkName" ) ) + m_xStorage.removeElement( "LinkName" ); + + XEmbedPersist xPersist = (XEmbedPersist)UnoRuntime.queryInterface( XEmbedPersist.class, + m_xEmbedObj ); + if ( xPersist != null ) + { + PropertyValue[] pEmp = new PropertyValue[0]; + xPersist.setPersistentEntry( m_xStorage, "EmbedSub", EntryInitModes.NO_INIT, pEmp ); + m_bLinkObj = false; + m_aLinkURI = null; + } + else + JOptionPane.showMessageDialog( m_aFrame, + "No XEmbedPersist in ConvertLink... !", + "Error:", + JOptionPane.ERROR_MESSAGE ); + } + catch( Exception e1 ) + { + JOptionPane.showMessageDialog( m_aFrame, + e1, + "Exception in ConvertLinkToEmbed:try 1 :", + JOptionPane.ERROR_MESSAGE ); + } + } + } + } + } + + // Helper methods + public XEmbeddedObject createEmbedObject( String aServiceName ) + { + XEmbeddedObject xEmbObj = null; + byte[] pClassID = new byte[16]; + + if ( aServiceName.equals( "com.sun.star.comp.Writer.TextDocument" ) ) + { + int[] pTempClassID = { 0x8B, 0xC6, 0xB1, 0x65, 0xB1, 0xB2, 0x4E, 0xDD, + 0xAA, 0x47, 0xDA, 0xE2, 0xEE, 0x68, 0x9D, 0xD6 }; + for ( int ind = 0; ind < 16; ind++ ) + pClassID[ind] = (byte)pTempClassID[ind]; + } + else if ( aServiceName.equals( "com.sun.star.comp.Writer.GlobalDocument" ) ) + { + int[] pTempClassID = { 0xB2, 0x1A, 0x0A, 0x7C, 0xE4, 0x03, 0x41, 0xFE, + 0x95, 0x62, 0xBD, 0x13, 0xEA, 0x6F, 0x15, 0xA0 }; + for ( int ind = 0; ind < 16; ind++ ) + pClassID[ind] = (byte)pTempClassID[ind]; + } + else if ( aServiceName.equals( "com.sun.star.comp.Writer.WebDocument" ) ) + { + int[] pTempClassID = { 0xA8, 0xBB, 0xA6, 0x0C, 0x7C, 0x60, 0x45, 0x50, + 0x91, 0xCE, 0x39, 0xC3, 0x90, 0x3F, 0xAC, 0x5E }; + for ( int ind = 0; ind < 16; ind++ ) + pClassID[ind] = (byte)pTempClassID[ind]; + } + else if ( aServiceName.equals( "com.sun.star.comp.Calc.SpreadsheetDocument" ) ) + { + int[] pTempClassID = { 0x47, 0xBB, 0xB4, 0xCB, 0xCE, 0x4C, 0x4E, 0x80, + 0xA5, 0x91, 0x42, 0xD9, 0xAE, 0x74, 0x95, 0x0F }; + for ( int ind = 0; ind < 16; ind++ ) + pClassID[ind] = (byte)pTempClassID[ind]; + } + else if ( aServiceName.equals( "com.sun.star.comp.Draw.PresentationDocument" ) ) + { + int[] pTempClassID = { 0x91, 0x76, 0xE4, 0x8A, 0x63, 0x7A, 0x4D, 0x1F, + 0x80, 0x3B, 0x99, 0xD9, 0xBF, 0xAC, 0x10, 0x47 }; + for ( int ind = 0; ind < 16; ind++ ) + pClassID[ind] = (byte)pTempClassID[ind]; + } + else if ( aServiceName.equals( "com.sun.star.comp.Draw.DrawingDocument" ) ) + { + int[] pTempClassID = { 0x4B, 0xAB, 0x89, 0x70, 0x8A, 0x3B, 0x45, 0xB3, + 0x99, 0x1C, 0xCB, 0xEE, 0xAC, 0x6B, 0xD5, 0xE3 }; + for ( int ind = 0; ind < 16; ind++ ) + pClassID[ind] = (byte)pTempClassID[ind]; + } + else if ( aServiceName.equals( "com.sun.star.comp.Math.FormulaDocument" ) ) + { + int[] pTempClassID = { 0x07, 0x8B, 0x7A, 0xBA, 0x54, 0xFC, 0x45, 0x7F, + 0x85, 0x51, 0x61, 0x47, 0xE7, 0x76, 0xA9, 0x97 }; + for ( int ind = 0; ind < 16; ind++ ) + pClassID[ind] = (byte)pTempClassID[ind]; + } + + if ( pClassID != null ) + { + // create embedded object based on the class ID + try { + Object oEmbedFactory = m_xServiceFactory.createInstance( "com.sun.star.embed.EmbeddedObjectFactory" ); + XEmbedObjectFactory xEmbedFactory = (XEmbedObjectFactory)UnoRuntime.queryInterface( + XEmbedObjectFactory.class, + oEmbedFactory ); + if ( xEmbedFactory != null ) + { + Object oEmbObj = xEmbedFactory.createInstanceInitNew( pClassID, + "Dummy name", + m_xStorage, + "EmbedSub" ); + xEmbObj = (XEmbeddedObject)UnoRuntime.queryInterface( XEmbeddedObject.class, oEmbObj ); + } + else + JOptionPane.showMessageDialog( m_aFrame, + "Can't create EmbedFactory!", + "Error:", + JOptionPane.ERROR_MESSAGE ); + } + catch( Exception e ) + { + JOptionPane.showMessageDialog( m_aFrame, e, "Exception in createInstanceInitNew():", JOptionPane.ERROR_MESSAGE ); + } + } + else + JOptionPane.showMessageDialog( m_aFrame, "Can't retrieve class ID!", "Error:", JOptionPane.ERROR_MESSAGE ); + + return xEmbObj; + } + + public XEmbeddedObject createLinkObject( String aLinkURL ) + { + XEmbeddedObject xEmbObj = null; + + try { + Object oEmbedFactory = m_xServiceFactory.createInstance( "com.sun.star.embed.EmbeddedObjectFactory" ); + XEmbedObjectFactory xEmbedFactory = (XEmbedObjectFactory)UnoRuntime.queryInterface( + XEmbedObjectFactory.class, + oEmbedFactory ); + if ( xEmbedFactory != null ) + { + Object oEmbObj = xEmbedFactory.createInstanceLink( aLinkURL ); + xEmbObj = (XEmbeddedObject)UnoRuntime.queryInterface( XEmbeddedObject.class, oEmbObj ); + } + else + JOptionPane.showMessageDialog( m_aFrame, + "Can't create EmbedFactory!", + "Error:", + JOptionPane.ERROR_MESSAGE ); + } + catch( Exception e ) + { + JOptionPane.showMessageDialog( m_aFrame, e, "Exception in createLinkObject():", JOptionPane.ERROR_MESSAGE ); + } + + + return xEmbObj; + } + + + public XEmbeddedObject loadEmbedObject( String aFileURI ) + { + XEmbeddedObject xEmbObj = null; + try { + Object oEmbedFactory = m_xServiceFactory.createInstance( "com.sun.star.embed.EmbeddedObjectFactory" ); + XEmbedObjectFactory xEmbedFactory = (XEmbedObjectFactory)UnoRuntime.queryInterface( + XEmbedObjectFactory.class, + oEmbedFactory ); + if ( xEmbedFactory != null ) + { + PropertyValue[] aMedDescr = { new PropertyValue(), new PropertyValue() }; + aMedDescr[0].Name = "URL"; + aMedDescr[0].Value = (Object) aFileURI; + aMedDescr[1].Name = "ReadOnly"; + aMedDescr[1].Value = (Object) Boolean.FALSE; + Object oEmbObj = xEmbedFactory.createInstanceInitFromMediaDescriptor( m_xStorage, + "EmbedSub", + aMedDescr ); + xEmbObj = (XEmbeddedObject)UnoRuntime.queryInterface( XEmbeddedObject.class, oEmbObj ); + } + else + JOptionPane.showMessageDialog( m_aFrame, + "Can't create EmbedFactory!", + "Error:", + JOptionPane.ERROR_MESSAGE ); + } + catch( Exception e ) + { + JOptionPane.showMessageDialog( m_aFrame, e, "Exception in loadEmbedObject():", JOptionPane.ERROR_MESSAGE ); + } + + return xEmbObj; + } + + public void clearObjectAndStorage() + { + synchronized( this ) + { + m_aImage = null; + } + + m_bOwnFile = false; + + m_aLinkURI = null; + m_bLinkObj = false; + + if ( m_xEmbedObj != null ) + { + try { + XComponent xComponent = (XComponent)UnoRuntime.queryInterface( XComponent.class, m_xEmbedObj ); + if ( xComponent != null ) + xComponent.dispose(); + } + catch ( Exception ex ) + {} + m_xEmbedObj = null; + } + + if ( m_xStorage != null ) + { + try { + XComponent xComponent = (XComponent)UnoRuntime.queryInterface( XComponent.class, m_xStorage ); + if ( xComponent != null ) + xComponent.dispose(); + } + catch ( Exception ex ) + {} + m_xStorage = null; + } + } + + public XStorage createTempStorage() + { + XStorage xTempStorage = null; + + try { + Object oStorageFactory = m_xServiceFactory.createInstance( "com.sun.star.embed.StorageFactory" ); + XSingleServiceFactory xStorageFactory = (XSingleServiceFactory)UnoRuntime.queryInterface( + XSingleServiceFactory.class, + oStorageFactory ); + if ( xStorageFactory != null ) + { + Object oStorage = xStorageFactory.createInstance(); + xTempStorage = (XStorage)UnoRuntime.queryInterface( XStorage.class, oStorage ); + } + else + JOptionPane.showMessageDialog( m_aFrame, + "Can't create StorageFactory!", + "Error:", + JOptionPane.ERROR_MESSAGE ); + } + catch( Exception e ) + { + JOptionPane.showMessageDialog( m_aFrame, e, "Exception in createTempStorage():", JOptionPane.ERROR_MESSAGE ); + } + + return xTempStorage; + } + + public void saveStorageAsFileURI( String aFileURI ) + { + try { + Object oStorageFactory = m_xServiceFactory.createInstance( "com.sun.star.embed.StorageFactory" ); + XSingleServiceFactory xStorageFactory = (XSingleServiceFactory)UnoRuntime.queryInterface( + XSingleServiceFactory.class, + oStorageFactory ); + if ( xStorageFactory != null ) + { + Object aArgs[] = new Object[2]; + aArgs[0] = aFileURI; + aArgs[1] = Integer.valueOf( ElementModes.READWRITE ); + + Object oStorage = xStorageFactory.createInstanceWithArguments( aArgs ); + XStorage xTargetStorage = (XStorage)UnoRuntime.queryInterface( XStorage.class, oStorage ); + m_xStorage.copyToStorage( xTargetStorage ); + + XComponent xComponent = (XComponent)UnoRuntime.queryInterface( XComponent.class, m_xStorage ); + xComponent.dispose(); + + m_xStorage = xTargetStorage; + m_bOwnFile = true; + } + else + JOptionPane.showMessageDialog( m_aFrame, + "Can't create StorageFactory!", + "Error:", + JOptionPane.ERROR_MESSAGE ); + } + catch( Exception e ) + { + JOptionPane.showMessageDialog( m_aFrame, e, "Exception in saveStorageToFileURI():", JOptionPane.ERROR_MESSAGE ); + } + + } + + public void loadFileURI( String aFileURI ) + { + try + { + Object oStorageFactory = m_xServiceFactory.createInstance( "com.sun.star.embed.StorageFactory" ); + XSingleServiceFactory xStorageFactory = (XSingleServiceFactory)UnoRuntime.queryInterface( + XSingleServiceFactory.class, + oStorageFactory ); + Object aArgs[] = new Object[2]; + aArgs[0] = aFileURI; + aArgs[1] = Integer.valueOf( ElementModes.READWRITE ); + + Object oStorage = xStorageFactory.createInstanceWithArguments( aArgs ); + XStorage xTargetStorage = (XStorage)UnoRuntime.queryInterface( XStorage.class, oStorage ); + + Object oEmbedFactory = m_xServiceFactory.createInstance( "com.sun.star.embed.EmbeddedObjectFactory" ); + XEmbedObjectFactory xEmbedFactory = (XEmbedObjectFactory)UnoRuntime.queryInterface( + XEmbedObjectFactory.class, + oEmbedFactory ); + + XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface( XNameAccess.class, + xTargetStorage ); + if ( xNameAccess == null ) + { + JOptionPane.showMessageDialog( m_aFrame, "No XNameAccess!", "Error:", JOptionPane.ERROR_MESSAGE ); + return; + } + + Object oEmbObj = null; + if ( xNameAccess.hasByName( "LinkName" ) && xTargetStorage.isStreamElement( "LinkName" ) ) + { + XStream xLinkStream = xTargetStorage.openStreamElement( "LinkName", ElementModes.READ ); + if ( xLinkStream != null ) + { + XInputStream xInStream = xLinkStream.getInputStream(); + if ( xInStream != null ) + { + byte[][] pBuff = new byte[1][0]; + int nRead = xInStream.readBytes( pBuff, 1000 ); + m_aLinkURI = new String( pBuff[0] ); + xInStream.closeInput(); + oEmbObj = xEmbedFactory.createInstanceLink( m_aLinkURI ); + m_bLinkObj = true; + } + } + } + else + oEmbObj = xEmbedFactory.createInstanceInitFromEntry( xTargetStorage, + "EmbedSub", + false ); + + m_xEmbedObj = (XEmbeddedObject)UnoRuntime.queryInterface( XEmbeddedObject.class, oEmbObj ); + + if ( m_xEmbedObj != null ) + { + m_xStorage = xTargetStorage; + m_bOwnFile = true; + } + else + JOptionPane.showMessageDialog( m_aFrame, + "Can't create EmbedObject from storage!", + "Error:", + JOptionPane.ERROR_MESSAGE ); + } + catch( Exception e ) + { + JOptionPane.showMessageDialog( m_aFrame, e, "Exception in loadFileURI():", JOptionPane.ERROR_MESSAGE ); + } + } + + public void storeLinkToStorage() + { + if ( m_xStorage != null && m_bLinkObj ) + { + try { + XStream xLinkStream = m_xStorage.openStreamElement( "LinkName", ElementModes.WRITE ); + + if ( xLinkStream != null ) + { + XOutputStream xLinkOutStream = xLinkStream.getOutputStream(); + XTruncate xTruncate = (XTruncate) UnoRuntime.queryInterface( XTruncate.class, + xLinkOutStream ); + if ( xLinkOutStream != null && xTruncate != null ) + { + xTruncate.truncate(); + + char[] aLinkChar = m_aLinkURI.toCharArray(); + byte[] aLinkBytes = new byte[ aLinkChar.length ]; + for ( int ind = 0; ind < aLinkChar.length; ind++ ) + aLinkBytes[ind] = (byte)aLinkChar[ind]; + + xLinkOutStream.writeBytes( aLinkBytes ); + xLinkOutStream.closeOutput(); + + XComponent xComponent = (XComponent) UnoRuntime.queryInterface( XComponent.class, + xLinkStream ); + if ( xComponent != null ) + xComponent.dispose(); + } + else + JOptionPane.showMessageDialog( m_aFrame, + "The substream can not be truncated or written!", + "Error:", + JOptionPane.ERROR_MESSAGE ); + + } + else + JOptionPane.showMessageDialog( m_aFrame, + "Can't create/open substream!", + "Error:", + JOptionPane.ERROR_MESSAGE ); + } + catch( Exception e ) + { + JOptionPane.showMessageDialog( m_aFrame, + e, + "Exception in storeLinkToStorage:", + JOptionPane.ERROR_MESSAGE ); + + } + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/EmbedDocument/Container1/EmbedContFrame.java b/odk/examples/java/EmbedDocument/Container1/EmbedContFrame.java new file mode 100644 index 000000000..afc3496e2 --- /dev/null +++ b/odk/examples/java/EmbedDocument/Container1/EmbedContFrame.java @@ -0,0 +1,128 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import java.awt.*; +import java.awt.event.*; + +import com.sun.star.comp.servicemanager.ServiceManager; + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.connection.XConnector; +import com.sun.star.connection.XConnection; + +import com.sun.star.bridge.XUnoUrlResolver; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.XNamingService; +import com.sun.star.uno.XComponentContext; + +import com.sun.star.container.*; +import com.sun.star.beans.*; +import com.sun.star.lang.*; + + +public class EmbedContFrame extends Frame +{ + WindowListener m_aCloser = new WindowAdapter() + { + public void windowClosing( WindowEvent e ) + { + dispose(); + System.exit( 0 ); + } + }; + + public EmbedContFrame( String sName ) + { + super( sName ); + addWindowListener( m_aCloser ); + } + + public static void start() + { + EmbedContFrame aFrame = new EmbedContFrame( "Testing container." ); + + // connect to the office + XMultiServiceFactory aServiceFactory = null; + try { + aServiceFactory = connectOfficeGetServiceFactory(); + } + catch( Exception e ) + {} + + if ( aServiceFactory == null ) + { + System.out.println( "Can't get service manager!\n" ); + System.exit( 1 ); + } + + EmbedContApp aApp = new EmbedContApp( aFrame, aServiceFactory ); + aApp.init(); + aApp.start(); + + Dimension aSize = aApp.getSize(); + + aFrame.add( "Center", aApp ); + aFrame.pack(); + aFrame.setSize( aSize ); + + aFrame.setVisible( true ); + } + + public static void main( String args[] ) + { + EmbedContFrame.start(); + } + + public static XMultiServiceFactory connectOfficeGetServiceFactory() + throws com.sun.star.uno.Exception, + com.sun.star.uno.RuntimeException, + Exception + { + String sConnectionString = "uno:socket,host=localhost,port=8100;urp;StarOffice.NamingService"; + + // Get component context + XComponentContext xComponentContext = + com.sun.star.comp.helper.Bootstrap.createInitialComponentContext( null ); + + // initial serviceManager + XMultiComponentFactory xLocalServiceManager = xComponentContext.getServiceManager(); + + // create a connector, so that it can contact the office + Object oUrlResolver = xLocalServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", + xComponentContext ); + XUnoUrlResolver xUrlResolver = (XUnoUrlResolver)UnoRuntime.queryInterface( XUnoUrlResolver.class, oUrlResolver ); + + Object oInitialObject = xUrlResolver.resolve( sConnectionString ); + XNamingService xName = (XNamingService)UnoRuntime.queryInterface( XNamingService.class, oInitialObject ); + + XMultiServiceFactory xMSF = null; + if( xName != null ) { + Object oMSF = xName.getRegisteredObject( "StarOffice.ServiceManager" ); + xMSF = (XMultiServiceFactory)UnoRuntime.queryInterface( XMultiServiceFactory.class, oMSF ); + } + else + System.out.println( "Error: Can't get XNamingService interface from url resolver!" ); + + return xMSF; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/EmbedDocument/Container1/Makefile b/odk/examples/java/EmbedDocument/Container1/Makefile new file mode 100644 index 000000000..88279bbe5 --- /dev/null +++ b/odk/examples/java/EmbedDocument/Container1/Makefile @@ -0,0 +1,65 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +# Builds the Java Storage test example of the SDK. + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMPONENT_NAME=EmbedDocument.Container1 +OUT_COMP_CLASS = $(OUT_CLASS)/$(COMPONENT_NAME) + +JAVAFILES = \ + EmbedContApp.java\ + EmbedContFrame.java + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : \ + JavaStorageTestExample + +include $(SETTINGS)/stdtarget.mk + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(JAVAFILES) + +JavaStorageTestExample : $(CLASSFILES) + @echo -------------------------------------------------------------------------------- + @echo Please use following command to execute the example! + @echo ------ + @echo $(MAKE) EmbedContFrame.run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.class + $(SDK_JAVA) -classpath "$(SDK_CLASSPATH)" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + diff --git a/odk/examples/java/EmbedDocument/EmbeddedObject/EditorFrame.java b/odk/examples/java/EmbedDocument/EmbeddedObject/EditorFrame.java new file mode 100644 index 000000000..fb15106b7 --- /dev/null +++ b/odk/examples/java/EmbedDocument/EmbeddedObject/EditorFrame.java @@ -0,0 +1,134 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import java.awt.*; +import java.awt.event.*; +import java.awt.image.*; +import javax.swing.JTextArea; +import javax.swing.JFrame; +import java.io.*; +import javax.imageio.ImageIO; + +public class EditorFrame extends JFrame +{ + private final OwnEmbeddedObject m_aEmbObj; + private final JTextArea m_aTextArea; + private BufferedImage m_aBufImage; + + private final WindowListener m_aCloser = new WindowAdapter() + { + @Override + public void windowClosing( WindowEvent e ) + { + m_aBufImage = new BufferedImage( m_aTextArea.getWidth(), m_aTextArea.getHeight(), BufferedImage.TYPE_INT_RGB ); + Graphics2D aGr = m_aBufImage.createGraphics(); + m_aTextArea.paintAll( aGr ); + aGr.dispose(); + + hide(); + m_aEmbObj.CloseFrameRequest(); + } + }; + + public EditorFrame( String sName, OwnEmbeddedObject aEmbObj, int nWidth, int nHeight ) + { + super( sName ); + m_aEmbObj = aEmbObj; + addWindowListener( m_aCloser ); + m_aTextArea = new JTextArea( "", nWidth, nHeight ); + + add( "Center", m_aTextArea ); + pack(); + } + + public String getText() + { + return m_aTextArea.getText(); + } + + public void setText( String aText ) + { + m_aTextArea.setText( aText ); + } + + public Dimension getAppSize() + { + return m_aTextArea.getSize(); + } + + public void setAppSize( Dimension aSize ) + { + Dimension aOwnSize = getSize(); + Dimension aAppSize = m_aTextArea.getSize(); + Dimension aToSet = + new Dimension( (int)( aSize.getWidth() + aOwnSize.getWidth() - aAppSize.getWidth() ), + (int)(aSize.getHeight() + aOwnSize.getHeight() - aAppSize.getHeight() ) ); + + setSize( aToSet ); + validate(); + } + + public byte[] getReplacementImage() + { + Dimension aDim = m_aTextArea.getSize(); + BufferedImage aBufImage = null; + + if ( m_aBufImage != null ) + aBufImage = m_aBufImage; + else + { + try + { + int nWidth = (int)aDim.getWidth(); + int nHeight = (int)aDim.getHeight(); + aBufImage = new BufferedImage( nWidth, nHeight, BufferedImage.TYPE_INT_RGB ); + Graphics2D aGr = aBufImage.createGraphics(); + aGr.setBackground( Color.WHITE ); + aGr.clearRect( 0, 0, nWidth, nHeight ); + aGr.dispose(); + } + catch ( java.lang.Exception e ) + {} + } + + if ( aBufImage != null ) + { + try + { + File aTmpFile = File.createTempFile( "temp", ".png" ); + ImageIO.write( aBufImage, "png", aTmpFile ); + + int nLen = (int)aTmpFile.length(); + byte[] aResult = new byte[nLen]; + FileInputStream aTmpStream = new FileInputStream( aTmpFile ); + aTmpStream.read( aResult ); + aTmpStream.close(); + aTmpFile.delete(); + + return aResult; + } + catch ( java.lang.Exception e ) + {} + } + + return new byte[0]; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/EmbedDocument/EmbeddedObject/EmbeddedObject.odt b/odk/examples/java/EmbedDocument/EmbeddedObject/EmbeddedObject.odt new file mode 100644 index 000000000..dde408bd3 Binary files /dev/null and b/odk/examples/java/EmbedDocument/EmbeddedObject/EmbeddedObject.odt differ diff --git a/odk/examples/java/EmbedDocument/EmbeddedObject/EmbeddedObject.xcu b/odk/examples/java/EmbedDocument/EmbeddedObject/EmbeddedObject.xcu new file mode 100644 index 000000000..ce7f3785b --- /dev/null +++ b/odk/examples/java/EmbedDocument/EmbeddedObject/EmbeddedObject.xcu @@ -0,0 +1,45 @@ + + + + + + + org.openoffice.examples.embedding.Factory69474366FD6F480683748EDD1B6E771D + + + PRIMARY SHOW OPEN HIDE + + + + + 69474366-FD6F-4806-8374-8EDD1B6E771D + + + + + + Example of a simple outplace text object + + + 69474366-FD6F-4806-8374-8EDD1B6E771D + + + + + diff --git a/odk/examples/java/EmbedDocument/EmbeddedObject/Makefile b/odk/examples/java/EmbedDocument/EmbeddedObject/Makefile new file mode 100644 index 000000000..b568c39c2 --- /dev/null +++ b/odk/examples/java/EmbedDocument/EmbeddedObject/Makefile @@ -0,0 +1,148 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +PRJ=../../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings + +# we use the sample directory name for separating this example +# from others in the output directory +SAMPLE_NAME=EmbeddedObject +SAMPLE_CLASS_OUT=$(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT=$(OUT_MISC)/$(SAMPLE_NAME) + +COMP_NAME=OwnEmbeddedObject +COMP_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(COMP_NAME) +COMP_GEN_OUT=$(SAMPLE_GEN_OUT)/$(COMP_NAME) +COMP_PACKAGE=$(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL=$(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME=$(COMP_NAME).uno.jar +COMP_JAR=$(SAMPLE_CLASS_OUT)/$(COMP_JAR_NAME) +COMP_JAR_MANIFEST=$(COMP_GEN_OUT)/$(COMP_NAME).Manifest +COMP_UNOPKG_MANIFEST = $(COMP_GEN_OUT)/META-INF/manifest.xml +COMP_REGISTERFLAG=$(COMP_GEN_OUT)$(PS)java_$(COMP_NAME)_register_component.flag +COMP_COMPONENTS=$(COMP_NAME).components + +PACKAGE = + +COMP_JAVAFILES =\ + OwnEmbeddedObject.java\ + OwnEmbeddedObjectFactory.java\ + EditorFrame.java + +COMP_CLASSFILES = $(patsubst %.java,$(COMP_CLASS_OUT)/%.class,$(COMP_JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)\ + $(PATH_SEPARATOR)$(COMP_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : $(COMP_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(COMP_GEN_OUT)/%.Manifest : + -$(MKDIR) $(subst \\,\,$(subst /,$(PS),$(@D))) + @echo RegistrationClassName: $(subst /,.,$(PACKAGE)).$(COMP_NAME)Factory> $@ + +# component as well as application are dependent from the generated types +# rule for component class files +$(COMP_CLASS_OUT)/%.class : $(COMP_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(COMP_CLASS_OUT) $(COMP_JAVAFILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_JAR_MANIFEST) $(COMP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(COMP_CLASS_OUT) . + +# rule for component package manifest +$(COMP_GEN_OUT)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(SAMPLE_NAME).xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_JAR) $(COMP_UNOPKG_MANIFEST) $(COMP_NAME).components + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ $(SAMPLE_NAME).xcu + $(SDK_ZIP) $@ -u $(COMP_NAME).components + cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_ZIP) -u $@ $(COMP_JAR_NAME) + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u $@ META-INF/manifest.xml + +$(COMP_REGISTERFLAG) : $(COMP_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst \\,\,$(subst /,$(PS),$(@D))) + $(DEPLOYTOOL) $(COMP_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(COMP_NAME) : $(COMP_REGISTERFLAG) + @echo ------ + @echo The $(COMP_NAME) component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo Load the "$(QM)$(SAMPLE_NAME).odt$(QM)" document to see how this component works. + @echo You can use this component inside your office installation, see the example + @echo description. + @echo - + @echo $(MAKE) $(SAMPLE_NAME).odt.load + @echo -------------------------------------------------------------------------------- + +$(SAMPLE_NAME).odt.load : $(COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObject.components b/odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObject.components new file mode 100644 index 000000000..a77b099e0 --- /dev/null +++ b/odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObject.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObject.java b/odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObject.java new file mode 100644 index 000000000..f2377dcbc --- /dev/null +++ b/odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObject.java @@ -0,0 +1,1123 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import java.awt.Dimension; +import java.util.ArrayList; + +import com.sun.star.beans.XPropertySet; +import com.sun.star.configuration.theDefaultProvider; +import com.sun.star.container.XNameAccess; +import com.sun.star.embed.VisualRepresentation; +import com.sun.star.embed.XStorage; +import com.sun.star.embed.XTransactedObject; +import com.sun.star.io.XInputStream; +import com.sun.star.io.XOutputStream; +import com.sun.star.io.XStream; +import com.sun.star.io.XTruncate; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + +public final class OwnEmbeddedObject extends WeakBase + implements com.sun.star.embed.XEmbedPersist, + com.sun.star.embed.XEmbeddedObject +{ + private final XComponentContext m_xContext; + private final byte[] m_aClassID; + + private boolean m_bDisposed = false; + private int m_nObjectState = -1; + + private com.sun.star.embed.XStorage m_xParentStorage; + private com.sun.star.embed.XStorage m_xOwnStorage; + private String m_aEntryName; + + private com.sun.star.embed.XStorage m_xNewParentStorage; + private com.sun.star.embed.XStorage m_xNewOwnStorage; + private String m_aNewEntryName; + private boolean m_bWaitSaveCompleted = false; + + private EditorFrame m_aEditorFrame; + + private ArrayList m_aListeners; + + private com.sun.star.embed.VerbDescriptor[] m_pOwnVerbs; + + private com.sun.star.embed.XEmbeddedClient m_xClient; + + private Dimension m_aObjSize; + + + private ArrayList GetListeners() + { + if ( m_aListeners == null ) + m_aListeners = new ArrayList(10); + + return m_aListeners; + } + + + private Dimension UpdateSizeAndGetFromActive() + { + if ( m_nObjectState == com.sun.star.embed.EmbedStates.ACTIVE ) + m_aObjSize = m_aEditorFrame.getAppSize(); + + if ( m_aObjSize != null ) + return m_aObjSize; + else + return new Dimension(); + } + + + private void SwitchOwnPersistence( XStorage xParentStorage, XStorage xOwnStorage, String aEntryName ) + { + if ( xOwnStorage != m_xOwnStorage ) + { + if ( m_xOwnStorage != null ) + m_xOwnStorage.dispose(); + m_xParentStorage = xParentStorage; + m_xOwnStorage = xOwnStorage; + m_aEntryName = aEntryName; + } + } + + + private void SwitchOwnPersistence( XStorage xParentStorage, String aEntryName ) throws com.sun.star.io.IOException + { + if ( xParentStorage != m_xParentStorage || !aEntryName.equals( m_aEntryName ) ) + { + try + { + XStorage xOwnStorage = xParentStorage.openStorageElement( aEntryName, com.sun.star.embed.ElementModes.READWRITE ); + SwitchOwnPersistence( xParentStorage, xOwnStorage, aEntryName ); + } + catch( com.sun.star.io.IOException e ) + { + throw e; + } + catch( com.sun.star.uno.Exception e ) + { + com.sun.star.io.IOException e2 = new com.sun.star.io.IOException( "Error while switching object storage!" ); + e2.initCause(e); + throw e2; + } + } + } + + + private static void SaveDataToStorage( XStorage xStorage, String aString, Dimension aDimension ) throws com.sun.star.io.IOException + { + try + { + // save the text + XStream xStream = xStorage.openStreamElement( "content.txt", com.sun.star.embed.ElementModes.READWRITE ); + XComponent xStreamComp = UnoRuntime.queryInterface( XComponent.class, xStream ); + if ( xStreamComp == null ) + throw new com.sun.star.uno.RuntimeException(); + + XOutputStream xOutStream = xStream.getOutputStream(); + XTruncate xTruncate = UnoRuntime.queryInterface( XTruncate.class, xOutStream ); + if ( xTruncate == null ) + throw new com.sun.star.io.IOException(); + + xTruncate.truncate(); + xOutStream.writeBytes( aString.getBytes() ); + + // save the size + xStream = xStorage.openStreamElement( "properties.txt", com.sun.star.embed.ElementModes.READWRITE ); + xStreamComp = UnoRuntime.queryInterface( XComponent.class, xStream ); + if ( xStreamComp == null ) + throw new com.sun.star.uno.RuntimeException(); + + xOutStream = xStream.getOutputStream(); + xTruncate = UnoRuntime.queryInterface( XTruncate.class, xOutStream ); + if ( xTruncate == null ) + throw new com.sun.star.io.IOException(); + + xTruncate.truncate(); + String aProps = Integer.toString( (int)aDimension.getWidth() ) + "|" + Integer.toString( (int)aDimension.getHeight() ); + xOutStream.writeBytes( aProps.getBytes() ); + + // set the media type + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xStorage ); + if ( xPropSet == null ) + throw new com.sun.star.uno.RuntimeException(); + xPropSet.setPropertyValue( "MediaType", "application/x-openoffice-embedded-69474366-FD6F-4806-8374-8EDD1B6E771D" ); + + XTransactedObject xTransact = UnoRuntime.queryInterface( XTransactedObject.class, xStorage ); + if ( xTransact != null ) + xTransact.commit(); + + xStreamComp.dispose(); + } + catch( com.sun.star.io.IOException e ) + { + throw e; + } + catch( com.sun.star.uno.Exception e ) + { + com.sun.star.io.IOException e2 = new com.sun.star.io.IOException( "Error while switching object storage!" ); + e2.initCause(e); + throw e2; + } + } + + + private void PostEvent( String aEvEntryName ) + { + if ( m_aListeners != null ) + { + com.sun.star.document.EventObject aEventObject = new com.sun.star.document.EventObject( this, aEvEntryName ); + for ( int nInd = 0; nInd < m_aListeners.size(); nInd++ ) + { + try + { + com.sun.star.document.XEventListener xListener = UnoRuntime.queryInterface( com.sun.star.document.XEventListener.class, m_aListeners.get( nInd ) ); + + if ( xListener != null ) + xListener.notifyEvent( aEventObject ); + } + catch( java.lang.Exception e ) + { + m_aListeners.remove( nInd ); + } + } + } + } + + + private void StateChangeNotification( boolean bBeforeChange, int nOldState, int nNewState ) + { + if ( m_aListeners != null ) + { + com.sun.star.lang.EventObject aEventObject = new com.sun.star.lang.EventObject( this ); + for ( int nInd = 0; nInd < m_aListeners.size(); nInd++ ) + { + try + { + com.sun.star.embed.XStateChangeListener xListener = UnoRuntime.queryInterface( com.sun.star.embed.XStateChangeListener.class, m_aListeners.get( nInd ) ); + + if ( xListener != null ) + { + if ( bBeforeChange ) + xListener.changingState( aEventObject, nOldState, nNewState ); + else + xListener.stateChanged( aEventObject, nOldState, nNewState ); + } + } + catch( java.lang.Exception e ) + { + m_aListeners.remove( nInd ); + } + } + } + } + + + private String ReadStringFromStream( XStorage xStorage, String aStreamName ) throws com.sun.star.io.IOException + { + if ( xStorage == null ) + throw new com.sun.star.uno.RuntimeException(); + + try + { + XStream xStream = xStorage.openStreamElement( aStreamName, com.sun.star.embed.ElementModes.READWRITE ); + XComponent xStreamComp = UnoRuntime.queryInterface( XComponent.class, xStream ); + if ( xStreamComp == null ) + throw new com.sun.star.uno.RuntimeException(); + + XInputStream xInStream = xStream.getInputStream(); + byte[][] aData = new byte[1][]; + aData[0] = new byte[0]; + String aResult = ""; + + int nLen = 0; + do + { + nLen = xInStream.readBytes( aData, 10 ); + if ( aData.length == 0 || aData[0] == null ) + throw new com.sun.star.io.IOException(); + aResult += new String( aData[0] ); + } while( nLen > 0 ); + + xStreamComp.dispose(); + + return aResult; + } + catch( com.sun.star.io.IOException e ) + { + throw e; + } + catch( com.sun.star.uno.Exception e ) + { + com.sun.star.io.IOException e2 = new com.sun.star.io.IOException( "Error while reading one of object streams!" ); + e2.initCause(e); + throw e2; + } + } + + + private void ReadSizeFromOwnStorage() throws com.sun.star.io.IOException + { + String aSize = ReadStringFromStream( m_xOwnStorage, "properties.txt" ); + + int nSeparator = aSize.indexOf( '|' ); + if ( nSeparator > 0 && nSeparator < aSize.length() - 1 ) + { + int nWidth = Integer.parseInt( aSize.substring( 0, nSeparator ) ); + int nHeight = Integer.parseInt( aSize.substring( nSeparator + 1, aSize.length() ) ); + m_aObjSize = new Dimension( nWidth, nHeight ); + } + } + + + public OwnEmbeddedObject( XComponentContext context, byte[] aClassID ) + { + m_xContext = context; + m_aClassID = aClassID; + } + + + public void CloseFrameRequest() + { + com.sun.star.embed.XEmbeddedClient xClient = m_xClient; + if ( xClient == null ) + return; + + UpdateSizeAndGetFromActive(); + StateChangeNotification( true, com.sun.star.embed.EmbedStates.ACTIVE, com.sun.star.embed.EmbedStates.RUNNING ); + + try{ + xClient.visibilityChanged( false ); + } catch( com.sun.star.uno.Exception e ){} + + try{ + xClient.saveObject(); + } catch( com.sun.star.uno.Exception e ){} + + m_nObjectState = com.sun.star.embed.EmbedStates.RUNNING; + StateChangeNotification( false, com.sun.star.embed.EmbedStates.ACTIVE, m_nObjectState ); + + PostEvent( "OnVisAreaChanged" ); + } + + // com.sun.star.embed.XCommonEmbedPersist: + + public void storeOwn() throws com.sun.star.embed.WrongStateException, com.sun.star.io.IOException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 || m_bWaitSaveCompleted ) + throw new com.sun.star.embed.WrongStateException(); + + // nothing to do, if the object is in loaded state + if ( m_nObjectState == com.sun.star.embed.EmbedStates.LOADED ) + return; + + if ( m_xOwnStorage == null ) + throw new com.sun.star.io.IOException(); + + PostEvent( "OnSave" ); + + if ( m_aEditorFrame == null ) + throw new com.sun.star.uno.RuntimeException(); + + SaveDataToStorage( m_xOwnStorage, m_aEditorFrame.getText(), UpdateSizeAndGetFromActive() ); + + PostEvent( "OnSaveDone" ); + } + + + public boolean isReadonly() throws com.sun.star.embed.WrongStateException + { + return false; + } + + + public void reload(com.sun.star.beans.PropertyValue[] aMediaArgs, com.sun.star.beans.PropertyValue[] aObjectArgs) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.embed.WrongStateException, com.sun.star.io.IOException, com.sun.star.uno.Exception + { + // not implemented currently + } + + // com.sun.star.embed.XEmbedPersist: + + public void setPersistentEntry(com.sun.star.embed.XStorage xStorage, String aEntryName, int nEntryConnectionMode, com.sun.star.beans.PropertyValue[] aMediaArgs, com.sun.star.beans.PropertyValue[] aObjectArgs) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.embed.WrongStateException, com.sun.star.io.IOException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( xStorage == null || aEntryName.length() == 0 ) + throw new com.sun.star.lang.IllegalArgumentException(); + + if ( ( m_nObjectState != -1 || nEntryConnectionMode == com.sun.star.embed.EntryInitModes.NO_INIT ) + && ( m_nObjectState == -1 || nEntryConnectionMode != com.sun.star.embed.EntryInitModes.NO_INIT ) ) + { + // if the object is not loaded + // it can not get persistent representation without initialization + + // if the object is loaded + // it can switch persistent representation only without initialization + + throw new com.sun.star.embed.WrongStateException(); + } + + if ( m_bWaitSaveCompleted ) + { + if ( nEntryConnectionMode == com.sun.star.embed.EntryInitModes.NO_INIT ) + { + if ( m_xParentStorage == xStorage && m_aEntryName.equals( aEntryName ) ) + saveCompleted( false ); + else if ( m_xNewParentStorage == xStorage && m_aNewEntryName.equals( aEntryName ) ) + saveCompleted( true ); + else + throw new com.sun.star.embed.WrongStateException(); + } + else + throw new com.sun.star.embed.WrongStateException(); + + return; + } + + boolean bElExists = xStorage.hasByName( aEntryName ); + + if ( nEntryConnectionMode == com.sun.star.embed.EntryInitModes.DEFAULT_INIT ) + { + SwitchOwnPersistence( xStorage, aEntryName ); + if ( bElExists ) + { + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, m_xOwnStorage ); + if ( xPropSet == null ) + throw new com.sun.star.uno.RuntimeException(); + + String aMediaType = AnyConverter.toString( xPropSet.getPropertyValue( "MediaType" ) ); + if ( !aMediaType.equals( "application/x-openoffice-embedded-69474366-FD6F-4806-8374-8EDD1B6E771D" ) ) + throw new com.sun.star.lang.IllegalArgumentException(); + + m_nObjectState = com.sun.star.embed.EmbedStates.LOADED; + } + else + { + m_aEditorFrame = new EditorFrame( m_aEntryName, this, 5, 20 ); + m_nObjectState = com.sun.star.embed.EmbedStates.RUNNING; + m_aObjSize = m_aEditorFrame.getAppSize(); + } + } + else if ( nEntryConnectionMode == com.sun.star.embed.EntryInitModes.TRUNCATE_INIT ) + { + SwitchOwnPersistence( xStorage, aEntryName ); + m_aEditorFrame = new EditorFrame( m_aEntryName, this, 5, 20 ); + m_nObjectState = com.sun.star.embed.EmbedStates.RUNNING; + m_aObjSize = m_aEditorFrame.getAppSize(); + } + else + throw new com.sun.star.lang.IllegalArgumentException(); + } + + + public void storeToEntry(com.sun.star.embed.XStorage xStorage, String aEntryName, com.sun.star.beans.PropertyValue[] aMediaArgs, com.sun.star.beans.PropertyValue[] aObjectArgs) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.embed.WrongStateException, com.sun.star.io.IOException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 || m_bWaitSaveCompleted ) + throw new com.sun.star.embed.WrongStateException(); + + if ( m_nObjectState == com.sun.star.embed.EmbedStates.LOADED ) + { + m_xParentStorage.copyElementTo( m_aEntryName, xStorage, aEntryName ); + } + else + { + com.sun.star.embed.XStorage xSubStorage = + xStorage.openStorageElement( aEntryName, + com.sun.star.embed.ElementModes.READWRITE | com.sun.star.embed.ElementModes.TRUNCATE ); + + SaveDataToStorage( xSubStorage, m_aEditorFrame.getText(), UpdateSizeAndGetFromActive() ); + } + } + + + public void storeAsEntry(com.sun.star.embed.XStorage xStorage, String aEntryName, com.sun.star.beans.PropertyValue[] aMediaArgs, com.sun.star.beans.PropertyValue[] aObjectArgs) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.embed.WrongStateException, com.sun.star.io.IOException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 || m_bWaitSaveCompleted ) + throw new com.sun.star.embed.WrongStateException(); + + com.sun.star.embed.XStorage xSubStorage = null; + + if ( m_nObjectState == com.sun.star.embed.EmbedStates.LOADED ) + { + xSubStorage = + xStorage.openStorageElement( aEntryName, + com.sun.star.embed.ElementModes.READWRITE | com.sun.star.embed.ElementModes.NOCREATE ); + + m_xOwnStorage.copyToStorage( xSubStorage ); + } + else + { + xSubStorage = + xStorage.openStorageElement( aEntryName, + com.sun.star.embed.ElementModes.READWRITE | com.sun.star.embed.ElementModes.TRUNCATE ); + + SaveDataToStorage( xSubStorage, m_aEditorFrame.getText(), UpdateSizeAndGetFromActive() ); + } + + m_bWaitSaveCompleted = true; + m_xNewOwnStorage = xSubStorage; + m_xNewParentStorage = xStorage; + m_aNewEntryName = aEntryName; + + } + + + public void saveCompleted(boolean bUseNew) throws com.sun.star.embed.WrongStateException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + // it is allowed to call saveCompleted( false ) for nonstored objects + if ( !m_bWaitSaveCompleted && !bUseNew ) + return; + + if ( !m_bWaitSaveCompleted ) + throw new com.sun.star.io.IOException(); + + if ( bUseNew ) + { + SwitchOwnPersistence( m_xNewParentStorage, m_xNewOwnStorage, m_aNewEntryName ); + PostEvent( "OnSaveAsDone" ); + } + else + { + try + { + m_xNewOwnStorage.dispose(); + } + catch( com.sun.star.uno.RuntimeException e ) + {} + } + + m_xNewOwnStorage = null; + m_xNewParentStorage = null; + m_aNewEntryName = null; + m_bWaitSaveCompleted = false; + } + + + public boolean hasEntry() throws com.sun.star.embed.WrongStateException + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_bWaitSaveCompleted ) + throw new com.sun.star.embed.WrongStateException(); + + if ( m_xOwnStorage != null ) + return true; + + return false; + } + + + public String getEntryName() throws com.sun.star.embed.WrongStateException + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 || m_bWaitSaveCompleted ) + throw new com.sun.star.embed.WrongStateException(); + + return m_aEntryName; + } + + // com.sun.star.embed.XVisualObject: + + public void setVisualAreaSize(long nAspect, com.sun.star.awt.Size aSize) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.embed.WrongStateException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + if ( nAspect == com.sun.star.embed.Aspects.MSOLE_ICON ) + // the ICON aspect should be handled by the container + throw new com.sun.star.embed.WrongStateException(); + + if ( m_nObjectState == com.sun.star.embed.EmbedStates.LOADED ) + changeState( com.sun.star.embed.EmbedStates.RUNNING ); + + if ( m_aEditorFrame == null ) + throw new com.sun.star.uno.RuntimeException(); + + m_aObjSize.setSize( aSize.Width, aSize.Height ); + m_aEditorFrame.setAppSize( m_aObjSize ); + } + + + public com.sun.star.awt.Size getVisualAreaSize(long nAspect) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.embed.WrongStateException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + if ( nAspect == com.sun.star.embed.Aspects.MSOLE_ICON ) + // the ICON aspect should be handled by the container + throw new com.sun.star.embed.WrongStateException(); + + if ( m_nObjectState == com.sun.star.embed.EmbedStates.LOADED ) + changeState( com.sun.star.embed.EmbedStates.RUNNING ); + + UpdateSizeAndGetFromActive(); + + return new com.sun.star.awt.Size( (int)m_aObjSize.getWidth(), (int)m_aObjSize.getHeight() ); + } + + + public VisualRepresentation getPreferredVisualRepresentation(long nAspect) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.embed.WrongStateException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + if ( nAspect == com.sun.star.embed.Aspects.MSOLE_ICON ) + // the ICON aspect should be handled by the container + throw new com.sun.star.embed.WrongStateException(); + + if ( m_nObjectState == com.sun.star.embed.EmbedStates.LOADED ) + changeState( com.sun.star.embed.EmbedStates.RUNNING ); + + byte[] aData = m_aEditorFrame.getReplacementImage(); + VisualRepresentation aVisRep = new VisualRepresentation(); + aVisRep.Data = aData; + aVisRep.Flavor = new com.sun.star.datatransfer.DataFlavor( "image/png", "png", new com.sun.star.uno.Type( byte[].class ) ); + return aVisRep; + } + + + public int getMapUnit(long nAspect) throws com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + if ( nAspect == com.sun.star.embed.Aspects.MSOLE_ICON ) + // the ICON aspect should be handled by the container + throw new com.sun.star.embed.WrongStateException(); + + return com.sun.star.embed.EmbedMapUnits.PIXEL; + } + + // com.sun.star.embed.XClassifiedObject: + + public byte[] getClassID() + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + return m_aClassID; + } + + + public String getClassName() + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + return ""; + } + + + public void setClassInfo(byte[] aClassID, String sClassName) throws com.sun.star.lang.NoSupportException + { + throw new com.sun.star.lang.NoSupportException(); + } + + // com.sun.star.embed.XComponentSupplier: + + public com.sun.star.util.XCloseable getComponent() + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + // allows no access to the component, this simple example just has no + return null; + } + + // com.sun.star.embed.XStateChangeBroadcaster: + + public void addStateChangeListener(com.sun.star.embed.XStateChangeListener xListener) + { + if ( m_bDisposed ) + return; + + GetListeners().add( xListener ); + } + + + public void removeStateChangeListener(com.sun.star.embed.XStateChangeListener xListener) + { + if ( m_bDisposed ) + return; + + if ( m_aListeners != null ) + m_aListeners.remove( xListener ); + } + + // com.sun.star.document.XEventBroadcaster: + + public void addEventListener(com.sun.star.document.XEventListener xListener) + { + if ( m_bDisposed ) + return; + + GetListeners().add( xListener ); + } + + + public void removeEventListener(com.sun.star.document.XEventListener xListener) + { + if ( m_bDisposed ) + return; + + if ( m_aListeners != null ) + m_aListeners.remove( xListener ); + } + + // com.sun.star.util.XCloseBroadcaster: + + public void addCloseListener(com.sun.star.util.XCloseListener xListener) + { + if ( m_bDisposed ) + return; + + GetListeners().add( xListener ); + } + + + public void removeCloseListener(com.sun.star.util.XCloseListener xListener) + { + if ( m_bDisposed ) + return; + + if ( m_aListeners != null ) + m_aListeners.remove( xListener ); + } + + // com.sun.star.util.XCloseable: + + public void close(boolean bDeliverOwnership) throws com.sun.star.util.CloseVetoException + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + com.sun.star.lang.EventObject aEventObject = new com.sun.star.lang.EventObject( this ); + + if ( m_aListeners != null ) + { + for ( int nInd = 0; nInd < m_aListeners.size(); nInd++ ) + { + try + { + com.sun.star.util.XCloseListener xListener = ( com.sun.star.util.XCloseListener ) + UnoRuntime.queryInterface( com.sun.star.document.XEventListener.class, m_aListeners.get( nInd ) ); + + if ( xListener != null ) + xListener.queryClosing( aEventObject, bDeliverOwnership ); + } + catch( com.sun.star.util.CloseVetoException e ) + { + throw e; + } + catch( java.lang.Exception e ) + { + m_aListeners.remove( nInd ); + } + } + + m_bDisposed = true; + + for ( int nInd = 0; nInd < m_aListeners.size(); nInd++ ) + { + try + { + com.sun.star.util.XCloseListener xListener = ( com.sun.star.util.XCloseListener ) + UnoRuntime.queryInterface( com.sun.star.document.XEventListener.class, m_aListeners.get( nInd ) ); + + if ( xListener != null ) + xListener.notifyClosing( aEventObject ); + } + catch( java.lang.Exception e ) + { + m_aListeners.remove( nInd ); + } + } + + m_aListeners.clear(); + } + + m_bDisposed = true; + + if ( m_aEditorFrame != null ) + { + m_aEditorFrame.dispose(); + m_aEditorFrame = null; + } + + if ( m_xOwnStorage != null ) + { + try { + m_xOwnStorage.dispose(); + } catch( java.lang.Exception e ) {} + m_xOwnStorage = null; + } + } + + // com.sun.star.embed.XEmbeddedObject: + + public void changeState(int nNewState) throws com.sun.star.embed.UnreachableStateException, com.sun.star.embed.WrongStateException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + int nOldState = m_nObjectState; + + if ( nOldState == nNewState ) + { + if ( nOldState == com.sun.star.embed.EmbedStates.ACTIVE ) + { + if ( m_aEditorFrame == null ) + throw new com.sun.star.uno.RuntimeException(); + m_aEditorFrame.toFront(); + } + + return; + } + + if ( nNewState != com.sun.star.embed.EmbedStates.LOADED + && nNewState != com.sun.star.embed.EmbedStates.RUNNING + && nNewState != com.sun.star.embed.EmbedStates.ACTIVE ) + throw new com.sun.star.embed.UnreachableStateException(); + + StateChangeNotification( true, nOldState, nNewState ); + + try + { + if ( nOldState == com.sun.star.embed.EmbedStates.LOADED ) + { + // switch to the RUNNING state first + String aText = ReadStringFromStream( m_xOwnStorage, "content.txt" ); + + EditorFrame aEditorFrame = new EditorFrame( m_aEntryName, this, 5, 20 ); + aEditorFrame.setText( aText ); + + ReadSizeFromOwnStorage(); + + m_aEditorFrame = aEditorFrame; + m_nObjectState = com.sun.star.embed.EmbedStates.RUNNING; + + if ( nNewState == com.sun.star.embed.EmbedStates.ACTIVE ) + { + if ( m_xClient == null ) + throw new com.sun.star.embed.WrongStateException(); + + m_aEditorFrame.show(); + m_aEditorFrame.toFront(); + + if ( m_aObjSize != null ) + aEditorFrame.setAppSize( m_aObjSize ); + + m_xClient.visibilityChanged( true ); + m_nObjectState = com.sun.star.embed.EmbedStates.ACTIVE; + } + } + else if ( nOldState == com.sun.star.embed.EmbedStates.RUNNING ) + { + if ( nNewState == com.sun.star.embed.EmbedStates.LOADED ) + { + EditorFrame aFrame = m_aEditorFrame; + m_aEditorFrame = null; + aFrame.dispose(); + m_nObjectState = nNewState; + } + else // nNewState == ACTIVE + { + if ( m_aEditorFrame == null ) + throw new com.sun.star.uno.RuntimeException(); + + if ( m_xClient == null ) + throw new com.sun.star.embed.WrongStateException(); + + m_aEditorFrame.show(); + m_aEditorFrame.toFront(); + + if ( m_aObjSize != null ) + m_aEditorFrame.setAppSize( m_aObjSize ); + + m_xClient.visibilityChanged( true ); + + m_nObjectState = nNewState; + } + } + else // nOldState == ACTIVE + { + UpdateSizeAndGetFromActive(); + if ( nNewState == com.sun.star.embed.EmbedStates.RUNNING ) + { + m_aEditorFrame.hide(); + m_nObjectState = nNewState; + } + else // nNewState == LOADED + { + EditorFrame aFrame = m_aEditorFrame; + m_aEditorFrame = null; + aFrame.dispose(); + m_nObjectState = nNewState; + } + } + } + catch( com.sun.star.uno.Exception e ) + { + if ( nOldState != m_nObjectState ) + StateChangeNotification( false, nOldState, m_nObjectState ); + throw e; + } + + StateChangeNotification( true, nOldState, nNewState ); + } + + + public int[] getReachableStates() throws com.sun.star.embed.NeedsRunningStateException, com.sun.star.embed.WrongStateException + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + int[] pStates = new int[3]; + pStates[0] = com.sun.star.embed.EmbedStates.LOADED; + pStates[1] = com.sun.star.embed.EmbedStates.RUNNING; + pStates[2] = com.sun.star.embed.EmbedStates.ACTIVE; + + return pStates; + } + + + public int getCurrentState() throws com.sun.star.embed.WrongStateException + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + return m_nObjectState; + } + + + public void doVerb(int nVerbID) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.embed.WrongStateException, com.sun.star.embed.UnreachableStateException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + if ( nVerbID == com.sun.star.embed.EmbedVerbs.MS_OLEVERB_PRIMARY + || nVerbID == com.sun.star.embed.EmbedVerbs.MS_OLEVERB_SHOW + || nVerbID == com.sun.star.embed.EmbedVerbs.MS_OLEVERB_OPEN ) + changeState( com.sun.star.embed.EmbedStates.ACTIVE ); + else if ( nVerbID == com.sun.star.embed.EmbedVerbs.MS_OLEVERB_HIDE ) + changeState( com.sun.star.embed.EmbedStates.RUNNING ); + } + + + public com.sun.star.embed.VerbDescriptor[] getSupportedVerbs() throws com.sun.star.embed.NeedsRunningStateException, com.sun.star.embed.WrongStateException + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + if ( m_pOwnVerbs == null ) + { + try + { + XMultiServiceFactory xConfProvider = theDefaultProvider.get(m_xContext); + if ( xConfProvider == null ) + throw new com.sun.star.uno.RuntimeException(); + + Object[] aArgs = new Object[1]; + aArgs[0] = "/org.openoffice.Office.Embedding/Objects"; + Object oSettings = xConfProvider.createInstanceWithArguments( "com.sun.star.configuration.ConfigurationAccess", aArgs ); + XNameAccess xObjConfNA = UnoRuntime.queryInterface( XNameAccess.class, oSettings ); + if ( xObjConfNA == null ) + throw new com.sun.star.uno.RuntimeException(); + + Object oEmbObj = xObjConfNA.getByName( "69474366-FD6F-4806-8374-8EDD1B6E771D" ); + XNameAccess xEmbObjNA = UnoRuntime.queryInterface( XNameAccess.class, oEmbObj ); + if ( xEmbObjNA == null ) + throw new com.sun.star.uno.RuntimeException(); + + String[] pVerbShortcuts = (String[]) AnyConverter.toArray( xEmbObjNA.getByName( "ObjectVerbs" ) ); + if ( pVerbShortcuts != null && pVerbShortcuts.length != 0 ) + { + com.sun.star.embed.VerbDescriptor[] pVerbs = new com.sun.star.embed.VerbDescriptor[pVerbShortcuts.length]; + aArgs[0] = "/org.openoffice.Office.Embedding/Verbs"; + Object oVerbs = xConfProvider.createInstanceWithArguments( "com.sun.star.configuration.ConfigurationAccess", aArgs ); + XNameAccess xVerbsConfNA = UnoRuntime.queryInterface( XNameAccess.class, oVerbs ); + if ( xVerbsConfNA == null ) + throw new com.sun.star.uno.RuntimeException(); + + for ( int nInd = 0; nInd < pVerbShortcuts.length; nInd++ ) + { + try + { + XNameAccess xVerbNA = UnoRuntime.queryInterface( + XNameAccess.class, + xVerbsConfNA.getByName( pVerbShortcuts[nInd] ) ); + if ( xVerbNA != null ) + { + com.sun.star.embed.VerbDescriptor aVerb = new com.sun.star.embed.VerbDescriptor(); + aVerb.VerbID = AnyConverter.toInt( xVerbNA.getByName( "VerbID" ) ); + aVerb.VerbName = AnyConverter.toString( xVerbNA.getByName( "VerbUIName" ) ); + aVerb.VerbFlags = AnyConverter.toInt( xVerbNA.getByName( "VerbFlags" ) ); + aVerb.VerbAttributes = AnyConverter.toInt( xVerbNA.getByName( "VerbAttributes" ) ); + pVerbs[nInd] = aVerb; + } + } + catch( java.lang.Exception e ) + { + } + + if ( pVerbs[nInd] == null ) + { + // let the error be visible + pVerbs[nInd] = new com.sun.star.embed.VerbDescriptor(); + pVerbs[nInd].VerbID = com.sun.star.embed.EmbedVerbs.MS_OLEVERB_PRIMARY; + pVerbs[nInd].VerbName = "ERROR!"; + pVerbs[nInd].VerbFlags = 0; + pVerbs[nInd].VerbAttributes = com.sun.star.embed.VerbAttributes.MS_VERBATTR_ONCONTAINERMENU; + } + } + + m_pOwnVerbs = pVerbs; + } + } + catch( com.sun.star.uno.Exception e ) + {} + } + + if ( m_pOwnVerbs != null ) + return m_pOwnVerbs; + + return new com.sun.star.embed.VerbDescriptor[0]; + } + + + public void setClientSite(com.sun.star.embed.XEmbeddedClient xClient) throws com.sun.star.embed.WrongStateException + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + m_xClient = xClient; + } + + + public com.sun.star.embed.XEmbeddedClient getClientSite() throws com.sun.star.embed.WrongStateException + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + return m_xClient; + } + + + public void update() throws com.sun.star.embed.WrongStateException, com.sun.star.uno.Exception + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + // not implemented + } + + + public void setUpdateMode(int nMode) throws com.sun.star.embed.WrongStateException + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + // not implemented + } + + + public long getStatus(long nAspect) throws com.sun.star.embed.WrongStateException + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + if ( m_nObjectState == -1 ) + throw new com.sun.star.embed.WrongStateException(); + + return 0; + } + + + public void setContainerName(String sName) + { + if ( m_bDisposed ) + throw new com.sun.star.lang.DisposedException(); + + // not implemented + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObjectFactory.java b/odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObjectFactory.java new file mode 100644 index 000000000..a4333a8fd --- /dev/null +++ b/odk/examples/java/EmbedDocument/EmbeddedObject/OwnEmbeddedObjectFactory.java @@ -0,0 +1,106 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.uno.XComponentContext; +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.lib.uno.helper.WeakBase; + +public final class OwnEmbeddedObjectFactory extends WeakBase + implements com.sun.star.lang.XServiceInfo, + com.sun.star.embed.XEmbedObjectFactory +{ + private final XComponentContext m_xContext; + private static final String m_implementationName = OwnEmbeddedObjectFactory.class.getName(); + private static final String[] m_serviceNames = { + "org.openoffice.examples.embedding.Factory69474366FD6F480683748EDD1B6E771D" }; + private static final byte[] m_classID = { 0x69, 0x47, 0x43, 0x66, (byte)0xFD, 0x6F, 0x48, 0x06, (byte)0x83, 0x74, (byte)0x8E, (byte)0xDD, 0x1B, 0x6E, 0x77, 0x1D }; + + + public OwnEmbeddedObjectFactory( XComponentContext context ) + { + m_xContext = context; + } + + public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) { + XSingleComponentFactory xFactory = null; + + if ( sImplementationName.equals( m_implementationName ) ) + xFactory = Factory.createComponentFactory(OwnEmbeddedObjectFactory.class, m_serviceNames); + return xFactory; + } + + // com.sun.star.lang.XServiceInfo: + public String getImplementationName() { + return m_implementationName; + } + + public boolean supportsService( String sService ) { + int len = m_serviceNames.length; + + for( int i=0; i < len; i++) { + if (sService.equals(m_serviceNames[i])) + return true; + } + return false; + } + + public String[] getSupportedServiceNames() { + return m_serviceNames; + } + + // com.sun.star.embed.XEmbedObjectFactory: + public Object createInstanceUserInit(byte[] aClassID, String sClassName, com.sun.star.embed.XStorage xStorage, String sEntName, int nEntryConnectionMode, com.sun.star.beans.PropertyValue[] aArgs, com.sun.star.beans.PropertyValue[] aObjectArgs) throws com.sun.star.lang.IllegalArgumentException, com.sun.star.io.IOException, com.sun.star.uno.Exception + { + if ( xStorage == null || sEntName == null || sEntName.length() == 0 ) + throw new com.sun.star.lang.IllegalArgumentException(); + + if ( nEntryConnectionMode == com.sun.star.embed.EntryInitModes.DEFAULT_INIT ) + { + if ( aClassID != null && aClassID.length != 0 ) + { + if ( aClassID.length != m_classID.length ) + throw new com.sun.star.lang.IllegalArgumentException(); + + for ( int i = 0; i < aClassID.length; i++ ) + if ( aClassID[i] != m_classID[i] ) + throw new com.sun.star.lang.IllegalArgumentException(); + } + else if ( !xStorage.hasByName( sEntName ) ) + throw new com.sun.star.lang.IllegalArgumentException(); + } + else if ( nEntryConnectionMode == com.sun.star.embed.EntryInitModes.TRUNCATE_INIT ) + { + if ( aClassID.length != m_classID.length ) + throw new com.sun.star.lang.IllegalArgumentException(); + + for ( int i = 0; i < m_classID.length; i++ ) + if ( aClassID[i] != m_classID[i] ) + throw new com.sun.star.lang.IllegalArgumentException(); + } + + OwnEmbeddedObject aObject = new OwnEmbeddedObject( m_xContext, m_classID ); + aObject.setPersistentEntry( xStorage, sEntName, nEntryConnectionMode, aArgs, aObjectArgs ); + + return aObject; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/Addons.xcu b/odk/examples/java/Inspector/Addons.xcu new file mode 100644 index 000000000..2ea6abdef --- /dev/null +++ b/odk/examples/java/Inspector/Addons.xcu @@ -0,0 +1,40 @@ + + + + + + + + + org.openoffice.Office.addon.Inspector:inspect + + + Object Inspector + + + _self + + + + + + + + + diff --git a/odk/examples/java/Inspector/HideableMutableTreeNode.java b/odk/examples/java/Inspector/HideableMutableTreeNode.java new file mode 100644 index 000000000..c601d075e --- /dev/null +++ b/odk/examples/java/Inspector/HideableMutableTreeNode.java @@ -0,0 +1,106 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import javax.swing.tree.*; + +/** + * HideableMutableTreeNode is a DefaultMutableTreeNode + * implementation that works with HideableTreeModel. + */ +public class HideableMutableTreeNode extends DefaultMutableTreeNode { + /** + * The node is visible flag. + */ + private boolean bIsvisible = true; + private static final String SDUMMY = "Dummy"; + + + /** + * Creates a tree node that has no parent and no children, but which + * allows children. + */ + public HideableMutableTreeNode() { + super(); + } + + /** + * Creates a tree node with no parent, no children, but which allows + * children, and initializes it with the specified user object. + * + * @param _userObject - an Object provided by the user that + * constitutes the node's data + */ + public HideableMutableTreeNode(Object _userObject) { + super(_userObject); + } + + /** + * Creates a tree node with no parent, no children, initialized with the + * specified user object, and that allows children only if specified. + * + * @param _userObject - an Object provided by the user that describes the node's data + * @param _ballowsChildren - if true, the node is allowed to have childnodes -- otherwise, it is always a leaf node + */ + public HideableMutableTreeNode(Object _userObject, boolean _ballowsChildren) { + super(_userObject, _ballowsChildren); + } + + /** + * Checks if the node is visible. + * + * @return true if the node is visible, else false + */ + public boolean isVisible() { + return this.bIsvisible; + } + + /** + * Sets if the node is visible. + * + * @param _bIsVisible true if the node is visible, else false + */ + public void setVisible(boolean _bIsVisible) { + this.bIsvisible = _bIsVisible; + } + + + public void addDummyNode(){ + removeDummyNode(); + DefaultMutableTreeNode oDefaultMutableTreeNode = new DefaultMutableTreeNode(SDUMMY); + add(oDefaultMutableTreeNode); + + } + + + public boolean removeDummyNode(){ + boolean breturn = false; + if (getChildCount() == 1){ + DefaultMutableTreeNode oDefaultMutableTreeNode = (DefaultMutableTreeNode) getChildAt(0); + if (oDefaultMutableTreeNode != null){ + if (oDefaultMutableTreeNode.getUserObject().equals(SDUMMY)){ + remove(0); + breturn = true; + } + } + } + return breturn; + } + +} +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/HideableTreeModel.java b/odk/examples/java/Inspector/HideableTreeModel.java new file mode 100644 index 000000000..b70d63046 --- /dev/null +++ b/odk/examples/java/Inspector/HideableTreeModel.java @@ -0,0 +1,258 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import java.util.ArrayList; +import javax.swing.event.TreeModelEvent; +import javax.swing.event.TreeModelListener; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreeNode; +import javax.swing.tree.TreePath; + + +public class HideableTreeModel implements TreeModel { + + private ArrayList modelListeners = new ArrayList(); + private Object root = null; + + + public HideableTreeModel(TreeNode _root) { + super(); + setRoot(_root); + } + + + public Object getRoot() { + return this.root; + } + + + private void setRoot(Object r) { + this.root = r; + } + + + private Object[] getPathToRoot(Object node) { + return getPathToRoot(node, 0); + } + + + private Object[] getPathToRoot(Object node, int i) { + Object anode[]; + if(node == null) { + if(i == 0) { + return null; + } + anode = new Object[i]; + } else { + i++; + if(node == getRoot()) { + anode = new Object[i]; + } else { + anode = getPathToRoot(getParent(node), i); + } + anode[anode.length - i] = node; + } + return anode; + } + + + public void addTreeModelListener(TreeModelListener l) { + modelListeners.add(l); + } + + + public void removeTreeModelListener(TreeModelListener l) { + modelListeners.remove(l); + } + + + + + + public void valueForPathChanged(TreePath path, Object newValue) { + nodeChanged(path.getLastPathComponent()); + } + + + + + public void nodeInserted(Object node, Object child, int index) { + if(index < 0) { + index = getIndexOfChild(node, child); + } + if(node != null && child != null && index >= 0) { + TreePath tp = new TreePath(getPathToRoot(node)); + int[] ai = { index }; + Object[] ac = { child }; + fireTreeNodesInserted(new TreeModelEvent(this, tp, ai, ac)); + } + } + + + private void nodeRemoved(Object node, Object child, int index) { + if(node != null && child != null && index >= 0) { + TreePath tp = new TreePath(getPathToRoot(node)); + int[] ai = { index }; + Object[] ac = { child }; + fireTreeNodesRemoved(new TreeModelEvent(this, tp, ai, ac)); + } + } + + + public void nodeChanged(Object node) { + if(node != null) { + TreePath tp = new TreePath(getPathToRoot(node)); + fireTreeNodesChanged(new TreeModelEvent(this, tp, null, null)); + } + } + + + private void fireTreeNodesChanged(TreeModelEvent event) { + for(TreeModelListener l : modelListeners) { + l.treeNodesChanged(event); + } + } + + + private void fireTreeNodesInserted(TreeModelEvent event) { + for(TreeModelListener l : modelListeners) { + l.treeNodesInserted(event); + } + } + + + private void fireTreeNodesRemoved(TreeModelEvent event) { + for(TreeModelListener l : modelListeners) { + l.treeNodesRemoved(event); + } + } + + public boolean isLeaf(Object _oNode) { + if(_oNode instanceof TreeNode) { + return ((TreeNode) _oNode).isLeaf(); + } + return true; + } + + + + private Object getParent(Object node) { + if(node != getRoot() && (node instanceof TreeNode)) { + return ((TreeNode)node).getParent(); + } + return null; + } + + + private boolean isNodeVisible(Object node) { + if(node != getRoot()) { + if(node instanceof HideableMutableTreeNode) { + return ((HideableMutableTreeNode)node).isVisible(); + } + } + return true; + } + + + public boolean setNodeVisible(Object node, boolean v) { + // can't hide root + if(node != getRoot()) { + if(node instanceof HideableMutableTreeNode) { + HideableMutableTreeNode n = (HideableMutableTreeNode)node; + if(v != n.isVisible()) { + TreeNode parent = n.getParent(); + if(v) { + // need to get index after showing... + n.setVisible(v); + int index = getIndexOfChild(parent, n); + nodeInserted(parent, n, index); + } else { + // need to get index before hiding... + int index = getIndexOfChild(parent, n); + n.setVisible(v); + nodeRemoved(parent, n, index); + } + } + return true; + } + } + return false; + } + + + + + + + + + public Object getChild(Object parent, int index) { + if(parent instanceof TreeNode) { + TreeNode p = (TreeNode) parent; + for(int i = 0, j = -1; i < p.getChildCount(); i++) { + TreeNode pc = p.getChildAt(i); + if(isNodeVisible(pc)) { + j++; + } + if(j == index) { + return pc; + } + } + } + return null; + } + + + public int getChildCount(Object parent) { + int count = 0; + if(parent instanceof TreeNode) { + TreeNode p = (TreeNode) parent; + for(int i = 0; i < p.getChildCount(); i++) { + TreeNode pc = p.getChildAt(i); + if(isNodeVisible(pc)) { + count++; + } + } + } + return count; + } + + + public int getIndexOfChild(Object parent, Object child) { + int index = -1; + if(parent instanceof TreeNode && child instanceof TreeNode) { + TreeNode p = (TreeNode)parent; + TreeNode c = (TreeNode)child; + if(isNodeVisible(c)) { + index = 0; + for(int i = 0; i < p.getChildCount(); i++) { + TreeNode pc = p.getChildAt(i); + if(pc.equals(c)) { + return index; + } + if(isNodeVisible(pc)) { + index++; + } + } + } + } + return index; + } +} +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/Inspector.java b/odk/examples/java/Inspector/Inspector.java new file mode 100644 index 000000000..18d8d909a --- /dev/null +++ b/odk/examples/java/Inspector/Inspector.java @@ -0,0 +1,459 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Set; + +import org.openoffice.XInstanceInspector; + +import com.sun.star.awt.XMessageBox; +import com.sun.star.awt.XMessageBoxFactory; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.beans.NamedValue; +import com.sun.star.beans.XPropertySet; +import com.sun.star.configuration.theDefaultProvider; +import com.sun.star.container.XNameAccess; +import com.sun.star.frame.XModel; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.registry.XRegistryKey; +import com.sun.star.ui.dialogs.XExecutableDialog; +import com.sun.star.ui.dialogs.XFolderPicker2; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.util.CloseVetoException; +import com.sun.star.util.XChangesBatch; +import com.sun.star.util.XCloseable; + + +/** The purpose of this class is to provide a factory for creating the service + * (__getServiceFactory) and writes the information into the given + * registry key (__writeRegistryServiceInfo). + */ +public class Inspector{ + public static final String sIDLDOCUMENTSUBFOLDER = "docs/idl/ref/"; + + + /** This class implements the method of the interface XInstanceInspector. + * Also the class implements the interfaces XServiceInfo, and XTypeProvider. + */ + public static class _Inspector extends WeakBase implements XInstanceInspector, XServiceInfo{ + + private static final String __serviceName = "org.openoffice.InstanceInspector"; + private HashMap aApplicationHashMap = new HashMap(); + private String sTitle = "Object Inspector"; + private ArrayList aHiddenDocuments = new ArrayList(); + private XComponentContext m_xComponentContext; + private HashMap aInspectorPanes = new HashMap(); + private XDialogProvider m_oSwingDialogProvider; + private TDocSupplier oTDocSupplier; + private Introspector m_oIntrospector = null; + // TODO: improve these strings: + private static final String sWRONGINSTALLATIONPATH = "Your selected path does not refer to an SDK-Installation!"; + /** Creates a new instance of Dialog */ + public _Inspector(XComponentContext _xComponentContext) { + m_xComponentContext = _xComponentContext; + m_oIntrospector = Introspector.getIntrospector(m_xComponentContext); + aApplicationHashMap.put("private:factory/swriter", "Text Document"); + aApplicationHashMap.put("private:factory/scalc", "Spreadsheet"); + aApplicationHashMap.put("private:factory/simpress", "Presentation"); + aApplicationHashMap.put("private:factory/sdraw", "Drawing"); + aApplicationHashMap.put("private:factory/smath", "Formula"); + m_oSwingDialogProvider = new SwingDialogProvider(this, sTitle); + } + + + public XComponentContext getXComponentContext(){ + return m_xComponentContext; + } + + + public HashMap getInspectorPages(){ + return aInspectorPanes; + } + + + private String getSDKPath(){ + String sRetPath = ""; + try{ + XNameAccess xNameAccess = getConfigurationAccess("org.openoffice.inspector.ObjectInspector", true); + XPropertySet xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, xNameAccess); + sRetPath = (String) xPropertySet.getPropertyValue("SDKPath"); + }catch( Exception exception ) { + exception.printStackTrace(System.err); + } + return sRetPath; + } + + + public String getIDLPath(){ + String sRetPath = getSDKPath(); + if (m_oIntrospector.isValidSDKInstallationPath(sRetPath)){ + sRetPath = Introspector.addToPath(sRetPath, sIDLDOCUMENTSUBFOLDER); + } + else{ + sRetPath = ""; + } + return sRetPath; + } + + + public void openIdlFileforSelectedNode(){ + InspectorPane oInspectorPane = m_oSwingDialogProvider.getSelectedInspectorPage(); + if (oInspectorPane != null){ + XUnoNode oUnoNode = oInspectorPane.getSelectedNode(); + if (oUnoNode != null){ + String sPath = getIDLPath(); + oUnoNode.openIdlDescription(sPath); + } + } + } + + + public void assignSDKPath() { + try { + String sInstallationFolder = ""; + Object oFolderPicker = m_xComponentContext.getServiceManager().createInstanceWithContext("com.sun.star.ui.dialogs.FolderPicker", m_xComponentContext); + XFolderPicker2 xFolderPicker = UnoRuntime.queryInterface(XFolderPicker2.class, oFolderPicker); + XExecutableDialog xExecutable = UnoRuntime.queryInterface(XExecutableDialog.class, oFolderPicker); + XComponent xComponent = UnoRuntime.queryInterface(XComponent.class, oFolderPicker); + String sPath = getSDKPath(); + if (!sPath.equals("")){ + xFolderPicker.setDisplayDirectory(sPath); + } + xFolderPicker.setTitle("Add the Path to your SDK installation"); + short nResult = xExecutable.execute(); + if (nResult == com.sun.star.ui.dialogs.ExecutableDialogResults.OK){ + sInstallationFolder = xFolderPicker.getDirectory(); + if (m_oIntrospector.isValidSDKInstallationPath(sInstallationFolder)){ + XNameAccess xNameAccess = getConfigurationAccess(true); + XPropertySet xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, xNameAccess); + xPropertySet.setPropertyValue("SDKPath", sInstallationFolder); + XChangesBatch xBatch = UnoRuntime.queryInterface(XChangesBatch.class, xNameAccess); + xBatch.commitChanges(); + } + else{ + XPropertySet xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, xFolderPicker); + Object oWindow = xPropertySet.getPropertyValue("Window"); + XWindowPeer xWindowPeer = UnoRuntime.queryInterface(XWindowPeer.class, oWindow); + showErrorMessageBox(xWindowPeer, sTitle, sWRONGINSTALLATIONPATH); + assignSDKPath(); + } + } + xComponent.dispose(); + }catch( Exception exception ) { + exception.printStackTrace(System.err); + }} + + + private void showErrorMessageBox(XWindowPeer _xWindowPeer, String _sTitle, String _sMessage){ + try { + Object oToolkit = m_xComponentContext.getServiceManager().createInstanceWithContext("com.sun.star.awt.Toolkit", m_xComponentContext); + XMessageBoxFactory xMessageBoxFactory = UnoRuntime.queryInterface(XMessageBoxFactory.class, oToolkit); + XMessageBox xMessageBox = xMessageBoxFactory.createMessageBox(_xWindowPeer, com.sun.star.awt.MessageBoxType.ERRORBOX, com.sun.star.awt.MessageBoxButtons.BUTTONS_OK, _sTitle, _sMessage); + XComponent xComponent = UnoRuntime.queryInterface(XComponent.class, xMessageBox); + if (xMessageBox != null){ + xMessageBox.execute(); + xComponent.dispose(); + } + } catch (com.sun.star.uno.Exception ex) { + ex.printStackTrace(System.err); + }} + + + public void inspect(java.lang.Object _oUserDefinedObject, String _sTitle) throws com.sun.star.uno.RuntimeException { + try { + int nPageIndex = m_oSwingDialogProvider.getInspectorPageCount(); + SwingTreeControlProvider oSwingTreeControlProvider = new SwingTreeControlProvider(m_oSwingDialogProvider); + InspectorPane oInspectorPane = new InspectorPane(getXComponentContext(), m_oSwingDialogProvider, oSwingTreeControlProvider, getSourceCodeLanguage()); + oInspectorPane.inspect(_oUserDefinedObject, _sTitle); + getInspectorPages().put(_sTitle, oInspectorPane); + m_oSwingDialogProvider.show(nPageIndex); + }catch( Exception exception ) { + exception.printStackTrace(System.err); + }} + + + public void inspectOpenEmptyDocument(String _sApplicationDocUrl){ + XComponent xComponent = getTDocSupplier().openEmptyDocument(_sApplicationDocUrl); + String sRootTitle = aApplicationHashMap.get(_sApplicationDocUrl); + inspect(xComponent, sRootTitle); + aHiddenDocuments.add(xComponent); + } + + + public void inspectOpenDocument(String _sTDocUrl){ + String sTreeNodeName = getTDocSupplier().getTitleByTDocUrl(_sTDocUrl); + XModel xTDocModel = getTDocSupplier().getXModelByTDocUrl(_sTDocUrl); + inspect(xTDocModel, sTreeNodeName); + } + + + public void inspectSelectedNode(){ + InspectorPane oInspectorPane = m_oSwingDialogProvider.getSelectedInspectorPage(); + if (oInspectorPane != null){ + XUnoNode oUnoNode = oInspectorPane.getSelectedNode(); + Object oUnoObject = oUnoNode.getUnoObject(); + if (oUnoObject != null){ + String sNodeDescription = UnoNode.getNodeDescription(oUnoObject); + inspect(oUnoObject, sNodeDescription); + } + } + } + + + public void addSourceCodeOfSelectedNode(){ + InspectorPane oInspectorPane = m_oSwingDialogProvider.getSelectedInspectorPage(); + if (oInspectorPane != null){ + oInspectorPane.addSourceCodeOfSelectedNode(); + } + } + + + public void invokeSelectedMethod(){ + InspectorPane oInspectorPane = m_oSwingDialogProvider.getSelectedInspectorPage(); + if (oInspectorPane != null){ + oInspectorPane.invokeSelectedMethodNode(); + } + } + + + public void setSourceCodeLanguage(final int _nLanguage){ + try{ + String sLanguage = "Java"; + XNameAccess xNameAccess = getConfigurationAccess("org.openoffice.inspector.ObjectInspector", true); + XPropertySet xPropertySet = UnoRuntime.queryInterface(XPropertySet.class, xNameAccess); + switch (_nLanguage){ + case XLanguageSourceCodeGenerator.nJAVA: + sLanguage = "Java"; + break; + case XLanguageSourceCodeGenerator.nCPLUSPLUS: + sLanguage = "CPlusPlus"; + break; + case XLanguageSourceCodeGenerator.nBASIC: + sLanguage = "Basic"; + break; + default: + System.out.println("Warning: Sourcecode language is not defined!"); + } + xPropertySet.setPropertyValue("Language", sLanguage); + XChangesBatch xBatch = UnoRuntime.queryInterface(XChangesBatch.class, xNameAccess); + xBatch.commitChanges(); + for (int i = 0; i < m_oSwingDialogProvider.getInspectorPageCount(); i++){ + m_oSwingDialogProvider.getInspectorPage(i).convertCompleteSourceCode(_nLanguage); + } + }catch( Exception exception ) { + exception.printStackTrace(System.err); + }} + + + private TDocSupplier getTDocSupplier(){ + if (oTDocSupplier == null){ + oTDocSupplier = new TDocSupplier(m_xComponentContext); + } + return oTDocSupplier; + } + + public String[] getTDocUrls(){ + return getTDocSupplier().getTDocUrls(); + } + + + public String[] getTDocTitles(String[] _sTDocUrls){ + return getTDocSupplier().getTDocTitles(_sTDocUrls); + } + + + public String[][] getApplicationUrls(){ + Set aSet = aApplicationHashMap.keySet(); + String[][] sReturnList = new String[aSet.size()][]; + int n= 0; + for ( Iterator i = aSet.iterator(); i.hasNext(); ){ + String[] sSingleApplication = new String[2]; + sSingleApplication[0] = i.next(); + // assign the title in the second index + sSingleApplication[1] = aApplicationHashMap.get(sSingleApplication[0]); + sReturnList[n++] = sSingleApplication; + } + return sReturnList; + } + + + public void disposeHiddenDocuments(){ + int nHiddenCount = aHiddenDocuments.size(); + if (nHiddenCount > 0){ + for (int i = nHiddenCount - 1; i >= 0; i--){ + XComponent xComponent = aHiddenDocuments.get(i); + if (xComponent != null){ + try { + XCloseable xCloseable = UnoRuntime.queryInterface(XCloseable.class, xComponent); + xCloseable.close(true); + aHiddenDocuments.remove(i); + } catch (CloseVetoException ex) { + ex.printStackTrace(); + } + } + } + } + } + + + private static String[] getServiceNames() { + String[] sSupportedServiceNames = { __serviceName }; + return sSupportedServiceNames; + } + + // Implement the interface XServiceInfo + /** Get all supported service names. + * @return Supported service names. + */ + public String[] getSupportedServiceNames() { + return getServiceNames(); + } + + // Implement the interface XServiceInfo + /** Test, if the given service will be supported. + * @return Return true, if the service will be supported. + */ + public boolean supportsService( String sServiceName ) { + return sServiceName.equals( __serviceName ); + } + + // Implement the interface XServiceInfo + /** Get the implementation name of the component. + * @return Implementation name of the component. + */ + public String getImplementationName() { + return _Inspector.class.getName(); + } + + + private int getSourceCodeLanguage(){ + int nLanguage = XLanguageSourceCodeGenerator.nJAVA; + try{ + XNameAccess xNameAccess = getConfigurationAccess("org.openoffice.inspector.ObjectInspector", false); + String sLanguage = (String) xNameAccess.getByName("Language"); + if (sLanguage.toUpperCase().equals("JAVA")){ + nLanguage = XLanguageSourceCodeGenerator.nJAVA; + } + else if (sLanguage.toUpperCase().equals("BASIC")){ + nLanguage = XLanguageSourceCodeGenerator.nBASIC; + } + else if (sLanguage.toUpperCase().equals("CPLUSPLUS")){ + nLanguage = XLanguageSourceCodeGenerator.nCPLUSPLUS; + } + else{ + System.out.println("Warning: Sourcecode language " + sLanguage + " is not defined!"); + } + m_oSwingDialogProvider.selectSourceCodeLanguage(nLanguage); + }catch( Exception exception ) { + exception.printStackTrace(System.err); + } + return nLanguage; + } + + + private XNameAccess getConfigurationAccess(boolean _bUpdate){ + return getConfigurationAccess("org.openoffice.inspector.ObjectInspector", _bUpdate); + } + + + private XNameAccess getConfigurationAccess(String _sNodePath, boolean update) { + XNameAccess xNameAccess = null; + try { + String sAccess = ""; + if (update) { + sAccess = "com.sun.star.configuration.ConfigurationUpdateAccess"; + } + else{ + sAccess = "com.sun.star.configuration.ConfigurationAccess"; + } + XMultiComponentFactory xMCF = m_xComponentContext.getServiceManager(); + XMultiServiceFactory xMSFCfg = theDefaultProvider.get(this.getXComponentContext()); + Object oAccess = xMSFCfg.createInstanceWithArguments(sAccess, new Object[]{new NamedValue("nodepath", _sNodePath)}); + xNameAccess = UnoRuntime.queryInterface(XNameAccess.class, oAccess); + } catch (com.sun.star.uno.Exception e) { + } + return xNameAccess; + } + + + } + +// end of inner class + + + /** + * Gives a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XSingleComponentFactory for creating + * the component + * @param sImplName the name of the implementation for which a + * service is desired + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleComponentFactory __getComponentFactory( String sImplName ) + { + XSingleComponentFactory xFactory = null; + if ( sImplName.equals( _Inspector.class.getName() ) ) + xFactory = Factory.createComponentFactory(_Inspector.class, _Inspector.getServiceNames()); + if ( xFactory == null ) + xFactory = InspectorAddon.__getComponentFactory(sImplName); + return xFactory; + } + + /** + * Writes the service information into the given registry key. + * This method is called by the JavaLoader + *

+ * @return returns true if the operation succeeded + * @param regKey the registryKey + * @see com.sun.star.comp.loader.JavaLoader + */ + public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) { + return (Factory.writeRegistryServiceInfo(_Inspector.class.getName(), _Inspector.getServiceNames(), regKey) + && InspectorAddon.__writeRegistryServiceInfo(regKey)); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/InspectorAddon.java b/odk/examples/java/Inspector/InspectorAddon.java new file mode 100644 index 000000000..b001d17b5 --- /dev/null +++ b/odk/examples/java/Inspector/InspectorAddon.java @@ -0,0 +1,224 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.beans.XPropertySet; +import com.sun.star.frame.DispatchDescriptor; +import com.sun.star.frame.XController; +import com.sun.star.frame.XDispatch; +import com.sun.star.frame.XDispatchProvider; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.XModel; +import com.sun.star.frame.XStatusListener; +import com.sun.star.lang.XInitialization; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XSingleComponentFactory; +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.XComponentContext; +import com.sun.star.lib.uno.helper.Factory; + + +public class InspectorAddon { + /** This class implements the component. At least the interfaces XServiceInfo, + * XTypeProvider, and XInitialization should be provided by the service. + */ + public static class InspectorAddonImpl extends WeakBase implements XDispatchProvider, XInitialization, XServiceInfo { + private org.openoffice.XInstanceInspector xInstInspector = null; +// Dispatcher oDispatcher = null; + private XFrame m_xFrame = null; + + private static final String[] m_serviceNames = { + "org.openoffice.InstanceInspectorAddon", + "com.sun.star.frame.ProtocolHandler" }; + + private XComponentContext m_xContext = null; + + /** Creates a new instance of InspectorAddon */ + public InspectorAddonImpl(XComponentContext _xContext) { + m_xContext = _xContext; + } + + public XDispatch queryDispatch( /*IN*/com.sun.star.util.URL aURL, /*IN*/String sTargetFrameName, /*IN*/int iSearchFlags ) { + XDispatch xRet = null; + if ( aURL.Protocol.equals("org.openoffice.Office.addon.Inspector:") ) { + if ( aURL.Path.equals( "inspect" ) ){ + // Todo: Check if the frame is already administered (use hashtable) + xRet = new Dispatcher(m_xFrame); + } + } + return xRet; + } + + + public XDispatch[] queryDispatches( /*IN*/DispatchDescriptor[] seqDescripts ) { + int nCount = seqDescripts.length; + XDispatch[] lDispatcher = new XDispatch[nCount]; + for( int i=0; i 0 ){ + m_xFrame = UnoRuntime.queryInterface(XFrame.class, object[ 0 ] ); + } + } + + private class Dispatcher implements XDispatch{ + private XFrame m_xFrame = null; + private XModel xModel = null; + + private Dispatcher(XFrame _xFrame){ + m_xFrame = _xFrame; + if (m_xFrame != null){ + XController xController = m_xFrame.getController(); + if (xController != null){ + xModel = xController.getModel(); + } + } + } + + // XDispatch + public void dispatch( /*IN*/com.sun.star.util.URL _aURL, /*IN*/com.sun.star.beans.PropertyValue[] aArguments ) { + try{ + if ( _aURL.Protocol.equals("org.openoffice.Office.addon.Inspector:") ){ + if ( _aURL.Path.equals("inspect")){ + Object oUnoInspectObject = xModel; + com.sun.star.lang.XMultiComponentFactory xMCF = m_xContext.getServiceManager(); + if (xInstInspector == null){ + Object obj= xMCF.createInstanceWithContext("org.openoffice.InstanceInspector", m_xContext); + xInstInspector = UnoRuntime.queryInterface(org.openoffice.XInstanceInspector.class, obj); + } + if ((m_xFrame == null) || (xModel == null)){ + Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", m_xContext); + m_xFrame = UnoRuntime.queryInterface(XFrame.class, oDesktop); + oUnoInspectObject = m_xFrame; + } + XPropertySet xFramePropertySet = UnoRuntime.queryInterface(XPropertySet.class, m_xFrame); + String sTitle = (String) xFramePropertySet.getPropertyValue("Title"); + String[] sTitleList = sTitle.split(" - "); + if (sTitleList.length > 0){ + sTitle = sTitleList[0]; + } + xInstInspector.inspect(oUnoInspectObject, sTitle); + } + } + } catch( Exception e ) { + System.err.println( e + e.getMessage()); + e.printStackTrace(System.err); + }} + + public void addStatusListener( /*IN*/XStatusListener xControl, /*IN*/com.sun.star.util.URL aURL ) { + } + + public void removeStatusListener( /*IN*/XStatusListener xControl, /*IN*/com.sun.star.util.URL aURL ) { + } + + + } + + + private static String[] getServiceNames() { + return m_serviceNames; + } + + // Implement the interface XServiceInfo + /** Get all supported service names. + * @return Supported service names. + */ + public String[] getSupportedServiceNames() { + return getServiceNames(); + } + + // Implement the interface XServiceInfo + /** Test, if the given service will be supported. + * @return Return true, if the service will be supported. + */ + public boolean supportsService( String sServiceName ) { + int len = m_serviceNames.length; + + for( int i=0; i < len; i++) { + if ( sServiceName.equals( m_serviceNames[i] ) ) + return true; + } + + return false; + } + + // Implement the interface XServiceInfo + /** Get the implementation name of the component. + * @return Implementation name of the component. + */ + public String getImplementationName() { + return InspectorAddonImpl.class.getName(); + } + + } + + + /** + * Gives a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XSingleComponentFactory for creating + * the component + * @param sImplName the name of the implementation for which a + * service is desired + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleComponentFactory __getComponentFactory( String sImplName ) + { + XSingleComponentFactory xFactory = null; + if ( sImplName.equals( InspectorAddonImpl.class.getName() ) ) + xFactory = Factory.createComponentFactory(InspectorAddonImpl.class, InspectorAddonImpl.getServiceNames()); + return xFactory; + } + + /** + * Writes the service information into the given registry key. + * This method is called by the JavaLoader + *

+ * @return returns true if the operation succeeded + * @param regKey the registryKey + * @see com.sun.star.comp.loader.JavaLoader + */ + public static boolean __writeRegistryServiceInfo(XRegistryKey regKey) { + return Factory.writeRegistryServiceInfo(InspectorAddonImpl.class.getName(), InspectorAddonImpl.getServiceNames(), regKey); + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/InspectorPane.java b/odk/examples/java/Inspector/InspectorPane.java new file mode 100644 index 000000000..6483958b7 --- /dev/null +++ b/odk/examples/java/Inspector/InspectorPane.java @@ -0,0 +1,577 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +import org.openoffice.XInstanceInspector; + +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XIntrospectionAccess; +import com.sun.star.beans.XPropertySet; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.reflection.XIdlMethod; +import com.sun.star.uno.Any; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; +import com.sun.star.uno.TypeClass; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + + public class InspectorPane extends WeakBase implements XInstanceInspector{ //, XServiceInfo + private XComponentContext m_xComponentContext; + private XDialogProvider m_xDialogProvider; + private Introspector m_oIntrospector = null; + private SourceCodeGenerator m_oSourceCodeGenerator; + private XTreeControlProvider m_xTreeControlProvider; + private String sTitle = ""; + + + /** The constructor of the inner class has a XMultiServiceFactory parameter. + */ + public InspectorPane(XComponentContext _xComponentContext, XDialogProvider _xDialogProvider, XTreeControlProvider _xTreeControlProvider, int _nLanguage) { + m_xComponentContext = _xComponentContext; + m_xTreeControlProvider = _xTreeControlProvider; + m_xDialogProvider = _xDialogProvider; + m_oIntrospector = Introspector.getIntrospector(m_xComponentContext); + m_oSourceCodeGenerator = new SourceCodeGenerator(_nLanguage); + _xTreeControlProvider.addInspectorPane(this); + } + + /** Inspect the given object for methods, properties, interfaces, and + * services. + * @param _oUserDefinedObject The object to inspect + * @throws RuntimeException If + */ + public void inspect(java.lang.Object _oUserDefinedObject, String _sTitle) throws com.sun.star.uno.RuntimeException { + try { + Object oContainer = m_xTreeControlProvider.inspect(_oUserDefinedObject, _sTitle); + m_xDialogProvider.addInspectorPage(getTitle(), oContainer); + } + catch( Exception exception ) { + exception.printStackTrace(System.err); + }} + + + public void setTitle(String _sTitle){ + if (_sTitle != null){ + if (_sTitle.length() > 0){ + sTitle = _sTitle; + } + } + } + + + public String getTitle(){ + return sTitle; + } + + + + private Type[] getTypes(Object _oUnoObject){ + Type[] aTypes = null; + if (AnyConverter.isArray(_oUnoObject)){ + aTypes = (Type[])_oUnoObject; + } + else{ + aTypes = m_oIntrospector.getInterfaces(_oUnoObject); + } + return aTypes; + } + + + private Object invoke(XUnoMethodNode _oUnoMethodNode){ + try{ + String sParamValueDescription = ""; + Object oUnoReturnObject = _oUnoMethodNode.invoke(); + boolean bHasParameters = _oUnoMethodNode.hasParameters(); + boolean bIsPrimitive = _oUnoMethodNode.isPrimitive(); + if (bHasParameters){ + sParamValueDescription = " (" + m_oSourceCodeGenerator.getMethodParameterValueDescription(_oUnoMethodNode, _oUnoMethodNode.getLastParameterObjects(), true) + ")"; + } + if (oUnoReturnObject != null ){ + String sNodeDescription = ""; + XUnoNode oUnoNode = null; + if (_oUnoMethodNode.getXIdlMethod().getReturnType().getTypeClass().getValue() == TypeClass.VOID_value){ + sNodeDescription += _oUnoMethodNode.getXIdlMethod().getReturnType().getName() + " " + _oUnoMethodNode.getXIdlMethod().getName() + sParamValueDescription; + _oUnoMethodNode.setLabel(sNodeDescription); + m_xTreeControlProvider.nodeChanged(_oUnoMethodNode); + } + else if (bHasParameters || !bIsPrimitive){ + if (bIsPrimitive){ + sNodeDescription += m_oSourceCodeGenerator.getStringValueOfObject(oUnoReturnObject, _oUnoMethodNode.getTypeClass()); + } + else{ + Any aReturnObject = Any.complete(oUnoReturnObject); + String sShortClassName = Introspector.getShortClassName(aReturnObject.getType().getTypeName()); + sNodeDescription += m_oSourceCodeGenerator.getVariableNameforUnoObject(sShortClassName); + } + if (Introspector.isArray(oUnoReturnObject)){ + if (Introspector.isUnoTypeObject(oUnoReturnObject)){ + oUnoNode = addUnoFacetteNode(_oUnoMethodNode, XUnoFacetteNode.SINTERFACEDESCRIPTION, _oUnoMethodNode.getUnoObject()); + } + else if(Introspector.isUnoPropertyTypeObject(oUnoReturnObject)){ + oUnoNode = addUnoFacetteNode(_oUnoMethodNode, XUnoFacetteNode.SPROPERTYINFODESCRIPTION, oUnoReturnObject); + } + else if(Introspector.isUnoPropertyValueTypeObject(oUnoReturnObject)){ + oUnoNode = addUnoFacetteNode(_oUnoMethodNode, XUnoFacetteNode.SPROPERTYVALUEDESCRIPTION, oUnoReturnObject); + } + } + if (oUnoNode == null){ + if (bHasParameters){ + sNodeDescription += sParamValueDescription; + } + oUnoNode = addUnoNode(null, oUnoReturnObject, sNodeDescription); + if (bHasParameters){ + oUnoNode.setParameterObjects(_oUnoMethodNode.getLastParameterObjects()); + } + } + if (oUnoNode != null){ + oUnoNode.setFoldable(!bIsPrimitive); + _oUnoMethodNode.setFoldable(false); + _oUnoMethodNode.addChildNode(oUnoNode); + m_xTreeControlProvider.nodeInserted(_oUnoMethodNode, oUnoNode, _oUnoMethodNode.getChildCount()-1); + } + } + else{ + if (bIsPrimitive){ + sNodeDescription = _oUnoMethodNode.getStandardMethodDescription() + "=" + UnoMethodNode.getDisplayValueOfPrimitiveType(oUnoReturnObject); + _oUnoMethodNode.setLabel(sNodeDescription); + m_xTreeControlProvider.nodeChanged(_oUnoMethodNode); + } + } + } + // ReturnObject of method node == null... + else{ + if (!bHasParameters){ + _oUnoMethodNode.setLabel(_oUnoMethodNode.getLabel() + " = null"); + } + else{ + _oUnoMethodNode.setLabel(_oUnoMethodNode.getXIdlMethod().getName() + sParamValueDescription + " = null"); + } + m_xTreeControlProvider.nodeChanged(_oUnoMethodNode); + } + return oUnoReturnObject; + }catch(Exception exception ) { + return null; + }} + + + public void invokeSelectedMethodNode(){ + XTreePathProvider xTreePathProvider = m_xTreeControlProvider.getSelectedPath(); + XUnoNode oUnoNode = xTreePathProvider.getLastPathComponent(); + if (oUnoNode instanceof XUnoMethodNode){ + invoke((XUnoMethodNode) oUnoNode); + m_xTreeControlProvider.expandPath(xTreePathProvider); + } + } + + + public void addSourceCodeOfSelectedNode(){ + XTreePathProvider oTreePathProvider = m_xTreeControlProvider.getSelectedPath(); + XUnoNode oUnoNode = oTreePathProvider.getLastPathComponent(); + if (oUnoNode instanceof XUnoMethodNode){ + XUnoMethodNode oUnoMethodNode = (XUnoMethodNode) oUnoNode; + if (!oUnoMethodNode.isInvoked() && oUnoMethodNode.isInvokable()){ + invoke(oUnoMethodNode); + } + } + String sSourceCode = m_oSourceCodeGenerator.addSourceCodeOfUnoObject(oTreePathProvider, true, true); + m_xTreeControlProvider.setSourceCode(sSourceCode); + } + + + public void convertCompleteSourceCode(int _nLanguage){ + String sSourceCode = m_oSourceCodeGenerator.convertAllUnoObjects(_nLanguage); + m_xTreeControlProvider.setSourceCode(sSourceCode); + } + + protected XUnoNode getSelectedNode(){ + return m_xTreeControlProvider.getSelectedNode(); + } + + + // add the object to the hashtable for a possible access in the tree + private XUnoFacetteNode addUnoFacetteNode(XUnoNode _oParentNode, String _sNodeDescription, Object _oUnoObject){ + return m_xTreeControlProvider.addUnoFacetteNode( _oParentNode, _sNodeDescription, _oUnoObject); + } + + + private XUnoMethodNode addMethodNode(Object _objectElement, XIdlMethod _xIdlMethod){ + return m_xTreeControlProvider.addMethodNode(_objectElement, _xIdlMethod); + } + + + + private void addMethodsToTreeNode(XUnoNode _oGrandParentNode, Object _oUnoParentObject, XIdlMethod[] _xIdlMethods){ + if (Introspector.isValid(_xIdlMethods)){ + for ( int n = 0; n < _xIdlMethods.length; n++ ) { + XIdlMethod xIdlMethod = _xIdlMethods[n]; + if (!xIdlMethod.getDeclaringClass().getName().equals("com.sun.star.uno.XInterface")){ + XUnoMethodNode oChildNode = addMethodNode(_oUnoParentObject, xIdlMethod); + if (oChildNode != null){ + _oGrandParentNode.addChildNode(oChildNode); + } + } + } + } + } + + + private void addFacetteNodesToTreeNode(XUnoNode _oParentNode, Object _oUnoObject){ + if (m_oIntrospector.hasMethods(_oUnoObject)){ + addUnoFacetteNode(_oParentNode, XUnoFacetteNode.SMETHODDESCRIPTION, _oUnoObject); + } + if (m_oIntrospector.hasProperties(_oUnoObject)){ + addUnoFacetteNode(_oParentNode, XUnoFacetteNode.SPROPERTYDESCRIPTION, _oUnoObject); + } + if (m_oIntrospector.hasInterfaces(_oUnoObject)){ + addUnoFacetteNode(_oParentNode, XUnoFacetteNode.SINTERFACEDESCRIPTION, _oUnoObject); + } + if (m_oIntrospector.isContainer(_oUnoObject)){ + addUnoFacetteNode(_oParentNode, XUnoFacetteNode.SCONTAINERDESCRIPTION, _oUnoObject); + } + if (m_oIntrospector.hasSupportedServices(_oUnoObject)){ + addUnoFacetteNode(_oParentNode, XUnoFacetteNode.SSERVICEDESCRIPTION, _oUnoObject); + } + } + + + private void addInterfacesToTreeNode(XUnoNode _oGrandParentNode, Object _oUnoParentObject, Type[] _aTypes) { + try { + if (_oUnoParentObject != null){ + for ( int m = 0; m < _aTypes.length; m++ ) { + addUnoNode(_oGrandParentNode, _oUnoParentObject, _aTypes[m]); + } + } + } + catch( Exception exception ) { + exception.printStackTrace(System.err); + }} + + + // add all services for the given object to the tree under the node parent + private void addServicesToTreeNode(XUnoNode _oGrandParentNode, Object _oUnoObject) { + try{ + XServiceInfo xServiceInfo = UnoRuntime.queryInterface( XServiceInfo.class, _oUnoObject ); + if ( xServiceInfo != null ){ + String[] sSupportedServiceNames = xServiceInfo.getSupportedServiceNames(); + for ( int m = 0; m < sSupportedServiceNames.length; m++ ) { + String sServiceName = sSupportedServiceNames[m]; + if (sServiceName.length() > 0){ + XUnoNode oUnoNode = addUnoNode(_oGrandParentNode, _oUnoObject, sSupportedServiceNames[m]); + oUnoNode.setNodeType(XUnoNode.nSERVICE); + } + } + } + } + catch(Exception exception) { + exception.printStackTrace(System.err); + }} + + + private void addPropertiesAndInterfacesOfService(XUnoNode _oUnoServiceNode){ + String sServiceName = _oUnoServiceNode.getClassName(); + Object oUnoObject = _oUnoServiceNode.getUnoObject(); + addInterfacesToTreeNode(_oUnoServiceNode, oUnoObject, m_oIntrospector.getInterfaces(oUnoObject, sServiceName)); + addPropertiesToTreeNode(_oUnoServiceNode, oUnoObject, m_oIntrospector.getProperties(oUnoObject, sServiceName)); + } + + + private void addPropertiesToTreeNode(XUnoNode _oParentNode, Object _oUnoParentObject, Property[] _aProperties) { + try { + if (_aProperties.length > 0){ + for ( int n = 0; n < _aProperties.length; n++ ){ + Property aProperty = _aProperties[n]; + XIntrospectionAccess xIntrospectionAccess = m_oIntrospector.getXIntrospectionAccess(_oUnoParentObject); + XPropertySet xPropertySet = UnoRuntime.queryInterface( XPropertySet.class, xIntrospectionAccess.queryAdapter(new Type( XPropertySet.class))); + if (xPropertySet != null) { + if (xPropertySet.getPropertySetInfo().hasPropertyByName(aProperty.Name)){ + Object objectElement = xPropertySet.getPropertyValue(aProperty.Name); + if (objectElement != null) { + XUnoNode oChildNode = m_xTreeControlProvider.addUnoPropertyNode(_oUnoParentObject, aProperty, objectElement); + if (oChildNode != null){ + _oParentNode.addChildNode(oChildNode); + } + } + } + } + } + } + } + catch(Exception exception) { + exception.printStackTrace(System.err); + }} + + + private void addContainerElementsToTreeNode(XUnoNode _oParentNode, Object _oUnoParentObject){ + Object[] oUnoContainerElements = m_oIntrospector.getUnoObjectsOfContainer(_oUnoParentObject); + if (Introspector.isValid(oUnoContainerElements)){ + if (oUnoContainerElements.length > 0){ + for (int i=0; i< oUnoContainerElements.length; i++){ + XUnoNode oChildNode = addUnoNode(_oParentNode, oUnoContainerElements[i], UnoNode.getNodeDescription(oUnoContainerElements[i])); + m_xTreeControlProvider.nodeInserted(_oParentNode, oChildNode, _oParentNode.getChildCount()-1); + } + } + } + } + + + private XUnoNode addUnoNode(XUnoNode _oParentNode, Object _oUnoObject, String _sLabel ){ + XUnoNode oUnoNode = this.m_xTreeControlProvider.addUnoNode(_oUnoObject); + oUnoNode.setLabel(_sLabel); + if (_oParentNode != null){ + _oParentNode.addChildNode(oUnoNode); + } + setNodeFoldable(oUnoNode, _oUnoObject); + return oUnoNode; + } + + + private void setNodeFoldable(XUnoNode _oUnoNode, Object _oUnoObject){ + if (_oUnoObject != null){ + if (!Introspector.isObjectPrimitive(_oUnoObject)){ + _oUnoNode.setFoldable(true); + } + } + } + + + private XUnoNode addUnoNode(XUnoNode _oParentNode, Object _oUnoObject, Type _aType){ + XUnoNode oUnoNode = this.m_xTreeControlProvider.addUnoNode(_oUnoObject, _aType); + if (_oParentNode != null){ + _oParentNode.addChildNode(oUnoNode); + } + setNodeFoldable(oUnoNode, _oUnoObject); + return oUnoNode; + } + + + private void addPropertySetInfoNodesToTreeNode(XUnoFacetteNode _oUnoFacetteNode, Object _oUnoObject){ + if (_oUnoObject.getClass().isArray()){ + Object[] object = ( Object[] ) _oUnoObject; + for ( int i = 0; i < object.length; i++ ) { + Property aProperty = (Property) object[i]; + XUnoPropertyNode oUnoPropertyNode = m_xTreeControlProvider.addUnoPropertyNode(_oUnoObject, aProperty); + oUnoPropertyNode.setLabel(XUnoFacetteNode.SPROPERTYINFODESCRIPTION + " (" + aProperty.Name + ")"); + oUnoPropertyNode.setFoldable(true); + _oUnoFacetteNode.addChildNode(oUnoPropertyNode); + } + } + } + + private void addPrimitiveValuesToTreeNode(XUnoNode _oUnoNode, Object _oUnoObject){ + if (_oUnoObject.getClass().isArray()){ + if (!_oUnoObject.getClass().getComponentType().isPrimitive()){ + Object[] object = ( Object[] ) _oUnoObject; + for ( int i = 0; i < object.length; i++ ) { + if (Introspector.isObjectPrimitive(object[i])){ + addUnoNode(_oUnoNode, null, UnoNode.getNodeDescription(object[i])); + } + } + } + else{ + String[] sDisplayValues = UnoNode.getDisplayValuesofPrimitiveArray(_oUnoObject); + for ( int i = 0; i < sDisplayValues.length; i++ ) { + addUnoNode(_oUnoNode, null, sDisplayValues[i]); + } + } + } + } + + + private void addPropertySetInfoSubNodes(XUnoPropertyNode _oUnoPropertyNode){ + Property aProperty = _oUnoPropertyNode.getProperty(); + _oUnoPropertyNode.addChildNode(m_xTreeControlProvider.addUnoPropertyNodeWithName(aProperty)); + _oUnoPropertyNode.addChildNode(m_xTreeControlProvider.addUnoPropertyNodeWithType(aProperty)); + _oUnoPropertyNode.addChildNode(m_xTreeControlProvider.addUnoPropertyNodeWithHandle(aProperty)); + _oUnoPropertyNode.addChildNode(m_xTreeControlProvider.addUnoPropertyNodeWithAttributesDescription(aProperty)); + } + + + private void addPropertyValueSubNodes(XUnoFacetteNode _oUnoFacetteNode, Object _oUnoObject){ + if (Introspector.isUnoPropertyValueTypeObject(_oUnoObject)){ + Object[] object = ( Object[] ) _oUnoObject; + for ( int i = 0; i < object.length; i++ ) { + String sObjectClassName = object[i].getClass().getName(); + if (sObjectClassName.equals("com.sun.star.beans.PropertyValue")){ + XUnoNode oChildNode = null; + PropertyValue aPropertyValue = (PropertyValue) object[i]; + if (! Introspector.isObjectPrimitive(aPropertyValue.Value)){ + oChildNode = m_xTreeControlProvider.addUnoPropertyNode(_oUnoObject, aPropertyValue, _oUnoObject); + } + else{ + oChildNode = addUnoNode(null, aPropertyValue.Value, UnoPropertyNode.getStandardPropertyValueDescription(aPropertyValue)); + } + if (oChildNode != null){ + _oUnoFacetteNode.addChildNode(oChildNode); + } + } + } + } + } + + + public boolean expandNode(XUnoNode _oUnoNode){ + if ( _oUnoNode != null ) { + _oUnoNode.setFoldable(false); + if (m_xTreeControlProvider.isMethodNode(_oUnoNode)){ + XUnoMethodNode oUnoMethodNode = (XUnoMethodNode) _oUnoNode; + if (!oUnoMethodNode.isInvoked()){ + Object oUnoReturnObject = invoke((XUnoMethodNode) _oUnoNode); + if (oUnoReturnObject == null){ + _oUnoNode.setFoldable(true); + return false; + } + } + } + else if (m_xTreeControlProvider.isPropertyNode(_oUnoNode)){ + XUnoPropertyNode oUnoPropertyNode = (XUnoPropertyNode) _oUnoNode; + Object oUnoObject = oUnoPropertyNode.getUnoReturnObject(); + if (oUnoPropertyNode.getPropertyNodeType() == XUnoPropertyNode.nPROPERTYSETINFOTYPE){ + addPropertySetInfoSubNodes(oUnoPropertyNode); + } + else{ + //TODO: this code is redundant!!! + if ( oUnoObject.getClass().isArray()){ + // TODO: probably we should provide a possibility to insert also non-primitive nodes + addPrimitiveValuesToTreeNode(oUnoPropertyNode, oUnoObject); + } + else{ + addFacetteNodesToTreeNode(oUnoPropertyNode, oUnoObject); + } + } + } + else if (m_xTreeControlProvider.isFacetteNode(_oUnoNode)){ + XUnoFacetteNode oUnoFacetteNode = (XUnoFacetteNode) _oUnoNode; + Object oUnoObject = _oUnoNode.getUnoObject(); + if (oUnoFacetteNode.isMethodNode()){ + addMethodsToTreeNode(oUnoFacetteNode, oUnoObject, m_oIntrospector.getMethods(oUnoObject)); + } + if (oUnoFacetteNode.isPropertyNode()){ + String sNodeDescription = oUnoFacetteNode.getLabel(); + // TODO: it's very dangerous to distinguish the different UnoFacetteNodes only by the node description + if (sNodeDescription.startsWith(XUnoFacetteNode.SPROPERTYINFODESCRIPTION)){ + addPropertySetInfoNodesToTreeNode(oUnoFacetteNode, oUnoObject); + } + else if (sNodeDescription.startsWith(XUnoFacetteNode.SPROPERTYVALUEDESCRIPTION)){ + addPropertyValueSubNodes(oUnoFacetteNode, oUnoObject); + } + else{ + addPropertiesToTreeNode(oUnoFacetteNode, oUnoObject, m_oIntrospector.getProperties(oUnoObject)); + } + } + if (oUnoFacetteNode.isServiceNode()){ + addServicesToTreeNode(oUnoFacetteNode, oUnoObject); + } + if (oUnoFacetteNode.isInterfaceNode()){ + addInterfacesToTreeNode(oUnoFacetteNode, oUnoObject, getTypes(oUnoObject)); + } + if (oUnoFacetteNode.isContainerNode()){ + addContainerElementsToTreeNode(oUnoFacetteNode, oUnoObject); + } + } + else if (_oUnoNode.getNodeType() == XUnoNode.nSERVICE){ + addPropertiesAndInterfacesOfService(_oUnoNode); + } + else if (_oUnoNode.getNodeType() == XUnoNode.nINTERFACE){ + Type aType = _oUnoNode.getUnoType(); + if (aType != null){ + addMethodsToTreeNode(_oUnoNode, _oUnoNode.getUnoObject(), m_oIntrospector.getMethodsOfInterface(aType)); + } + } + else if (_oUnoNode.getNodeType() == XUnoNode.nOTHERS){ + Object oUnoObject = _oUnoNode.getUnoObject(); + if ( oUnoObject.getClass().isArray()){ + // TODO: probably we should provide a possibility to insert also non-primitive nodes + addPrimitiveValuesToTreeNode(_oUnoNode, oUnoObject); + } + else{ + addFacetteNodesToTreeNode(_oUnoNode, oUnoObject); + } + } + } + return true; + } + + + + public void applyFilter(XUnoFacetteNode _oUnoFacetteNode, String _sFilter){ + for (int i = 0; i < _oUnoFacetteNode.getChildCount(); i++){ + XUnoNode oUnoNode = _oUnoFacetteNode.getChild(i); + boolean bIsVisible = oUnoNode.isFilterApplicable(_sFilter); + m_xTreeControlProvider.setNodeVisible(oUnoNode, bIsVisible); + } + _oUnoFacetteNode.setFilter(_sFilter); + } + + + public String getFilter(XUnoNode _oUnoNode){ + String sFilter = ""; + if (_oUnoNode != null){ + XUnoNode oUnoNode = _oUnoNode; + boolean bleaveLoop = false; + do{ + if (m_xTreeControlProvider.isFacetteNode(oUnoNode)){ + sFilter = ((XUnoFacetteNode) oUnoNode).getFilter(); + bleaveLoop = true; + } + else{ + if (oUnoNode.getParentNode() != null){ + oUnoNode = oUnoNode.getParentNode(); + } + else{ + bleaveLoop = true; + } + } + } while(!bleaveLoop); + } + return sFilter; + } + + + public void showPopUpMenu(Object _invoker, int x, int y) throws ClassCastException{ + XUnoNode oUnoNode = getSelectedNode(); + boolean bdoEnableInvoke = oUnoNode instanceof XUnoMethodNode; + if (bdoEnableInvoke){ + XUnoMethodNode oUnoMethodNode = (XUnoMethodNode) oUnoNode; + bdoEnableInvoke = oUnoMethodNode.isInvokable(); + } + m_xDialogProvider.enablePopupMenuItem(XDialogProvider.SINVOKE, bdoEnableInvoke); + m_xDialogProvider.showPopUpMenu(_invoker, x, y); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/InstanceInspector.idl b/odk/examples/java/Inspector/InstanceInspector.idl new file mode 100644 index 000000000..81b396170 --- /dev/null +++ b/odk/examples/java/Inspector/InstanceInspector.idl @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_ORG_OPENOFFICE_INSTANCEINSPECTOR_IDL +#define INCLUDED_ORG_OPENOFFICE_INSTANCEINSPECTOR_IDL + +#include + + +module org { module openoffice { + + /** + * This service describes an instance inspector which can inspect + * UNO objects and provides information about the implemented + * interfaces, the supported services and properties of this object. + */ + service InstanceInspector: XInstanceInspector; + +}; }; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/InstanceInspectorTest.odt b/odk/examples/java/Inspector/InstanceInspectorTest.odt new file mode 100644 index 000000000..74cde4e68 Binary files /dev/null and b/odk/examples/java/Inspector/InstanceInspectorTest.odt differ diff --git a/odk/examples/java/Inspector/Introspector.java b/odk/examples/java/Inspector/Introspector.java new file mode 100644 index 000000000..b8d3be3c0 --- /dev/null +++ b/odk/examples/java/Inspector/Introspector.java @@ -0,0 +1,643 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.ArrayList; +import java.util.List; + +import com.sun.star.beans.IllegalTypeException; +import com.sun.star.beans.MethodConcept; +import com.sun.star.beans.Property; +import com.sun.star.beans.XIntrospection; +import com.sun.star.beans.XIntrospectionAccess; +import com.sun.star.container.XEnumeration; +import com.sun.star.container.XEnumerationAccess; +import com.sun.star.container.XHierarchicalNameAccess; +import com.sun.star.container.XIndexAccess; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XTypeProvider; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.reflection.TypeDescriptionSearchDepth; +import com.sun.star.reflection.XConstantTypeDescription; +import com.sun.star.reflection.XConstantsTypeDescription; +import com.sun.star.reflection.XIdlClass; +import com.sun.star.reflection.XIdlMethod; +import com.sun.star.reflection.XIdlReflection; +import com.sun.star.reflection.XIndirectTypeDescription; +import com.sun.star.reflection.XInterfaceTypeDescription; +import com.sun.star.reflection.XPropertyTypeDescription; +import com.sun.star.reflection.XServiceTypeDescription; +import com.sun.star.reflection.XTypeDescription; +import com.sun.star.reflection.XTypeDescriptionEnumeration; +import com.sun.star.reflection.XTypeDescriptionEnumerationAccess; +import com.sun.star.ucb.XSimpleFileAccess; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; +import com.sun.star.uno.TypeClass; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; + +public class Introspector extends WeakBase{ + + private XIntrospection m_xIntrospection; + private XMultiComponentFactory m_xMultiComponentFactory; + private XComponentContext m_xComponentContext; + private XTypeDescriptionEnumerationAccess m_xTDEnumerationAccess; + private XIdlReflection mxIdlReflection; + private static Introspector m_oIntrospector = null; + private XSimpleFileAccess xSimpleFileAccess = null; + + + + public static Introspector getIntrospector(){ + if (m_oIntrospector == null){ + throw new NullPointerException(); + } + else{ + return m_oIntrospector; + } + } + + public static Introspector getIntrospector(XComponentContext _xComponentContext){ + if (m_oIntrospector == null){ + m_oIntrospector = new Introspector(_xComponentContext); + } + return m_oIntrospector; + } + + + /** Creates a new instance of Introspection */ + private Introspector(XComponentContext _xComponentContext) { + try{ + m_xComponentContext = _xComponentContext; + m_xMultiComponentFactory = m_xComponentContext.getServiceManager(); + Object o = m_xMultiComponentFactory.createInstanceWithContext("com.sun.star.beans.Introspection", m_xComponentContext); + m_xIntrospection = UnoRuntime.queryInterface(XIntrospection.class, o ); + Object oCoreReflection = getXMultiComponentFactory().createInstanceWithContext("com.sun.star.reflection.CoreReflection", getXComponentContext()); + mxIdlReflection = UnoRuntime.queryInterface(XIdlReflection.class, oCoreReflection); + initTypeDescriptionManager(); + } + catch( Exception exception ) { + System.err.println( exception ); + }} + + + protected XComponentContext getXComponentContext(){ + return m_xComponentContext; + } + + + private XMultiComponentFactory getXMultiComponentFactory(){ + return m_xMultiComponentFactory; + } + + + protected XIntrospectionAccess getXIntrospectionAccess(Object _oUnoComponent){ + return m_xIntrospection.inspect(_oUnoComponent); + } + + + public boolean isContainer(Object _oUnoObject){ + boolean bIsContainer = false; + try { + XIntrospectionAccess xIntrospectionAccessObject = getXIntrospectionAccess(_oUnoObject); + if (xIntrospectionAccessObject != null){ + XEnumerationAccess xEnumerationAccess = UnoRuntime.queryInterface(XEnumerationAccess.class, xIntrospectionAccessObject.queryAdapter( new Type( XEnumerationAccess.class ) ) ); + if (xEnumerationAccess != null){ + XEnumeration xEnumeration = xEnumerationAccess.createEnumeration(); + bIsContainer = xEnumeration.hasMoreElements(); + } + if (!bIsContainer){ + XIndexAccess xIndexAccess = UnoRuntime.queryInterface( XIndexAccess.class, xIntrospectionAccessObject.queryAdapter(new Type( XIndexAccess.class ))); + if (xIndexAccess != null){ + bIsContainer = (xIndexAccess.getCount() > 0); + } + } + } + } catch (IllegalTypeException ex) { + ex.printStackTrace(System.err); + } + return bIsContainer; + } + + + // add all containers for the given object to the tree under the node + // parent + public Object[] getUnoObjectsOfContainer(Object _oUnoParentObject) { + Object[] oRetComponents = null; + try { + ArrayList oRetComponentsVector = new ArrayList(); + XIntrospectionAccess xIntrospectionAccessObject = getXIntrospectionAccess(_oUnoParentObject); + if ( xIntrospectionAccessObject != null ) { + XEnumerationAccess xEnumerationAccess = UnoRuntime.queryInterface(XEnumerationAccess.class, xIntrospectionAccessObject.queryAdapter( new Type( XEnumerationAccess.class ) ) ); + if ( xEnumerationAccess != null ) { + XEnumeration xEnumeration = xEnumerationAccess.createEnumeration(); + while ( xEnumeration.hasMoreElements() ) { + oRetComponentsVector.add(xEnumeration.nextElement()); + } + } + XIndexAccess xIndexAccess = UnoRuntime.queryInterface( XIndexAccess.class, xIntrospectionAccessObject.queryAdapter(new Type( XIndexAccess.class ))); + if ( xIndexAccess != null ) { + XIdlMethod mMethod = xIntrospectionAccessObject.getMethod("getByIndex", com.sun.star.beans.MethodConcept.INDEXCONTAINER); + for ( int i = 0; i < xIndexAccess.getCount(); i++ ) { + Object[][] aParamInfo = new Object[1][1]; + aParamInfo[0] = new Integer[] { Integer.valueOf(i) }; + oRetComponentsVector.add(mMethod.invoke(_oUnoParentObject, aParamInfo)); + } + } + } + if (oRetComponentsVector != null){ + oRetComponents = new Object[oRetComponentsVector.size()]; + oRetComponentsVector.toArray(oRetComponents); + } + } + catch( Exception exception ) { + System.err.println( exception ); + } + return oRetComponents; + } + + + protected XIdlMethod[] getMethodsOfInterface(Type _aType){ + try{ + XIdlClass xIdlClass = mxIdlReflection.forName(_aType.getTypeName()); + return xIdlClass.getMethods(); + } + catch( Exception e ) { + System.err.println( e ); + return null; + }} + + + + + + public boolean hasMethods(Object _oUnoObject){ + boolean bHasMethods = (getMethods(_oUnoObject).length > 0); + return bHasMethods; + } + + + // add all methods for the given object to the tree under the node parent + public XIdlMethod[] getMethods(Object _oUnoParentObject) { + try { + XIntrospectionAccess xIntrospectionAccess = getXIntrospectionAccess(_oUnoParentObject); + if (xIntrospectionAccess != null){ + XIdlMethod[] xIdlMethods = xIntrospectionAccess.getMethods(MethodConcept.ALL - MethodConcept.DANGEROUS); + return xIdlMethods; + } + } + catch( Exception e ) { + System.err.println( e ); + } + return null; + } + + + public boolean hasProperties(Object _oUnoObject){ + boolean bHasProperties = (getProperties(_oUnoObject).length > 0); + return bHasProperties; + } + + + protected Property[] getProperties( Object _oUnoParentObject){ + try { + XIntrospectionAccess xIntrospectionAccess = getXIntrospectionAccess(_oUnoParentObject); + if (xIntrospectionAccess != null){ + Property[] aProperties = xIntrospectionAccess.getProperties(com.sun.star.beans.PropertyConcept.ATTRIBUTES + com.sun.star.beans.PropertyConcept.PROPERTYSET); + return aProperties; + } + } + catch( Exception e ) { + System.err.println( e ); + } + return null; + } + + + protected Property[] getProperties(Object _oUnoObject, String _sServiceName){ + Property[] aProperties = getProperties(_oUnoObject); + List aListOfProperties = java.util.Arrays.asList(aProperties); + ArrayList aPropertiesVector = new ArrayList(aListOfProperties); + if (aProperties != null){ + XPropertyTypeDescription[] xPropertyTypeDescriptions = getPropertyDescriptionsOfService(_sServiceName); + for (int i = aProperties.length - 1; i >= 0; i--){ + if (!hasByName(xPropertyTypeDescriptions, _sServiceName + "." + aProperties[i].Name)){ + aPropertiesVector.remove(i); + } + } + } + Property[] aRetProperties = new Property[aPropertiesVector.size()]; + aPropertiesVector.toArray(aRetProperties); + return aRetProperties; + } + + + protected Type[] getInterfaces(Object _oUnoObject, String _sServiceName){ + Type[] aTypes = getInterfaces(_oUnoObject); + List aListOfTypes = java.util.Arrays.asList(aTypes); + ArrayList aTypesVector = new ArrayList(aListOfTypes); + if (aTypes != null){ + XInterfaceTypeDescription[] xInterfaceTypeDescriptions = getInterfaceDescriptionsOfService(_sServiceName); + for (int i = aTypes.length - 1; i >= 0; i--){ + if (!hasByName(xInterfaceTypeDescriptions, aTypes[i].getTypeName())){ + aTypesVector.remove(i); + } + } + } + Type[] aRetTypes = new Type[aTypesVector.size()]; + aTypesVector.toArray(aRetTypes); + return aRetTypes; + } + + + public boolean hasInterfaces(Object _oUnoObject){ + return (getInterfaces(_oUnoObject).length > 0); + } + + + protected Type[] getInterfaces(Object _oUnoParentObject){ + Type[] aTypes = new Type[]{}; + XTypeProvider xTypeProvider = UnoRuntime.queryInterface( XTypeProvider.class, _oUnoParentObject); + if ( xTypeProvider != null ) { + aTypes = xTypeProvider.getTypes(); + } + return aTypes; + } + + + + public static boolean isObjectSequence(Object _oUnoObject){ + Type aType = AnyConverter.getType(_oUnoObject); + return aType.getTypeClass().getValue() == TypeClass.SEQUENCE_value; + } + + + public static boolean isObjectPrimitive(Object _oUnoObject){ + boolean breturn = false; + if (_oUnoObject != null){ + Type aType = AnyConverter.getType(_oUnoObject); + breturn = isObjectPrimitive(_oUnoObject.getClass(), aType.getTypeClass()); + } + return breturn; + } + + + public static boolean isPrimitive(TypeClass _typeClass){ + return (( _typeClass == TypeClass.BOOLEAN ) + || ( _typeClass == TypeClass.BYTE ) + || ( _typeClass == TypeClass.CHAR ) + || ( _typeClass == TypeClass.DOUBLE ) + || ( _typeClass == TypeClass.ENUM ) + || ( _typeClass == TypeClass.FLOAT ) + || ( _typeClass == TypeClass.HYPER ) + || ( _typeClass == TypeClass.LONG ) + || ( _typeClass == TypeClass.SHORT ) + || ( _typeClass == TypeClass.STRING ) + || ( _typeClass == TypeClass.UNSIGNED_HYPER ) + || ( _typeClass == TypeClass.UNSIGNED_LONG ) + || ( _typeClass == TypeClass.UNSIGNED_SHORT )); + } + + public static boolean isObjectPrimitive(Class _oUnoClass, TypeClass _typeClass){ + return !( ( !_oUnoClass.isPrimitive() ) && ( _typeClass != TypeClass.ARRAY ) + && ( _typeClass != TypeClass.BOOLEAN ) + && ( _typeClass != TypeClass.BYTE ) + && ( _typeClass != TypeClass.CHAR ) + && ( _typeClass != TypeClass.DOUBLE ) + && ( _typeClass != TypeClass.ENUM ) + && ( _typeClass != TypeClass.FLOAT ) + && ( _typeClass != TypeClass.HYPER ) + && ( _typeClass != TypeClass.LONG ) + && ( _typeClass != TypeClass.SHORT ) + && ( _typeClass != TypeClass.STRING ) + && ( _typeClass != TypeClass.UNSIGNED_HYPER ) + && ( _typeClass != TypeClass.UNSIGNED_LONG ) + && ( _typeClass != TypeClass.UNSIGNED_SHORT )); + } + + + private void initTypeDescriptionManager() { + try { + Object oTypeDescriptionManager = getXComponentContext().getValueByName("/singletons/com.sun.star.reflection.theTypeDescriptionManager"); + m_xTDEnumerationAccess = UnoRuntime.queryInterface(XTypeDescriptionEnumerationAccess.class, oTypeDescriptionManager); + } catch ( java.lang.Exception e) { + System.out.println(System.out); + }} + + + private XTypeDescriptionEnumerationAccess getXTypeDescriptionEnumerationAccess(){ + return m_xTDEnumerationAccess; + } + + + protected XConstantTypeDescription[] getFieldsOfConstantGroup(String _sTypeClass){ + XConstantTypeDescription[] xConstantTypeDescriptions = null; + try { + TypeClass[] eTypeClasses = new com.sun.star.uno.TypeClass[1]; + eTypeClasses[0] = com.sun.star.uno.TypeClass.CONSTANTS; + XTypeDescriptionEnumeration xTDEnumeration = m_xTDEnumerationAccess.createTypeDescriptionEnumeration(getModuleName(_sTypeClass), eTypeClasses, TypeDescriptionSearchDepth.INFINITE); + while (xTDEnumeration.hasMoreElements()) { + XTypeDescription xTD = xTDEnumeration.nextTypeDescription(); + if (xTD.getName().equals(_sTypeClass)){ + XConstantsTypeDescription xConstantsTypeDescription = UnoRuntime.queryInterface(XConstantsTypeDescription.class, xTD); + xConstantTypeDescriptions = xConstantsTypeDescription.getConstants(); + } + String sName = xTD.getName(); + } + return xConstantTypeDescriptions; + } catch ( java.lang.Exception e) { + System.out.println(System.out); + } + return null; + } + + private XServiceTypeDescription getServiceTypeDescription(String _sServiceName, TypeClass _eTypeClass){ + try{ + if (_sServiceName.length() > 0){ + TypeClass[] eTypeClasses = new com.sun.star.uno.TypeClass[2]; + eTypeClasses[0] = com.sun.star.uno.TypeClass.SERVICE; + eTypeClasses[1] = _eTypeClass; + XTypeDescriptionEnumeration xTDEnumeration = getXTypeDescriptionEnumerationAccess().createTypeDescriptionEnumeration(Introspector.getModuleName(_sServiceName), eTypeClasses, TypeDescriptionSearchDepth.INFINITE); + while (xTDEnumeration.hasMoreElements()) { + XTypeDescription xTD = xTDEnumeration.nextTypeDescription(); + if (xTD.getName().equals(_sServiceName)){ + XServiceTypeDescription xServiceTypeDescription = UnoRuntime.queryInterface(XServiceTypeDescription.class, xTD); + return xServiceTypeDescription; + } + } + } + return null; + } catch (Exception ex) { + ex.printStackTrace(System.err); + return null; + }} + + + public XPropertyTypeDescription[] getPropertyDescriptionsOfService(String _sServiceName){ + try { + XServiceTypeDescription xServiceTypeDescription = getServiceTypeDescription(_sServiceName, com.sun.star.uno.TypeClass.PROPERTY); + if (xServiceTypeDescription != null){ + XPropertyTypeDescription[] xPropertyTypeDescriptions = xServiceTypeDescription.getProperties(); + return xPropertyTypeDescriptions; + } + } catch ( java.lang.Exception e) { + System.out.println(System.out); + } + return new XPropertyTypeDescription[]{}; + } + + + public XTypeDescription getReferencedType(String _sTypeName){ + XTypeDescription xTypeDescription = null; + try{ + XHierarchicalNameAccess xHierarchicalNameAccess = UnoRuntime.queryInterface(XHierarchicalNameAccess.class, m_xTDEnumerationAccess); + if (xHierarchicalNameAccess != null){ + if (xHierarchicalNameAccess.hasByHierarchicalName(_sTypeName)){ + XIndirectTypeDescription xIndirectTypeDescription = UnoRuntime.queryInterface(XIndirectTypeDescription.class, xHierarchicalNameAccess.getByHierarchicalName(_sTypeName)); + if (xIndirectTypeDescription != null){ + xTypeDescription = xIndirectTypeDescription.getReferencedType(); + } + } + } + } catch (Exception ex) { + ex.printStackTrace(System.err); + } + return xTypeDescription; + } + + + private XInterfaceTypeDescription[] getInterfaceDescriptionsOfService(String _sServiceName){ + try { + XServiceTypeDescription xServiceTypeDescription = getServiceTypeDescription(_sServiceName, com.sun.star.uno.TypeClass.INTERFACE); + if (xServiceTypeDescription != null){ + XInterfaceTypeDescription[] xInterfaceTypeDescriptions = xServiceTypeDescription.getMandatoryInterfaces(); + return xInterfaceTypeDescriptions; + } + } catch ( java.lang.Exception e) { + System.out.println(System.out); + } + return new XInterfaceTypeDescription[]{}; + } + + + private static boolean hasByName(XTypeDescription[] _xTypeDescriptions, String _sTypeName){ + for (int i = 0; i < _xTypeDescriptions.length; i++){ + if (_xTypeDescriptions[i].getName().equals(_sTypeName)){ + return true; + } + } + return false; + } + + + public static String getModuleName(String _sTypeClass){ + int nlastindex = _sTypeClass.lastIndexOf("."); + if (nlastindex > -1){ + return _sTypeClass.substring(0, nlastindex); + } + else{ + return ""; + } + } + + + public static String getShortClassName(String _sClassName){ + String sShortClassName = _sClassName; + int nindex = _sClassName.lastIndexOf("."); + if ((nindex < _sClassName.length()) && nindex > -1){ + sShortClassName = _sClassName.substring(nindex + 1); + } + return sShortClassName; + } + + + + public static boolean isUnoTypeObject(Object _oUnoObject){ + return isOfUnoType(_oUnoObject, "com.sun.star.uno.Type"); + } + + + public static boolean isUnoPropertyTypeObject(Object _oUnoObject){ + return isOfUnoType(_oUnoObject, "com.sun.star.beans.Property"); + } + + + public static boolean isUnoPropertyValueTypeObject(Object _oUnoObject){ + return isOfUnoType(_oUnoObject, "com.sun.star.beans.PropertyValue"); + } + + + private static boolean isOfUnoType(Object _oUnoObject, String _sTypeName){ + boolean bIsUnoObject = false; + if (_oUnoObject != null){ + if (_oUnoObject.getClass().isArray()){ + if (!_oUnoObject.getClass().getComponentType().isPrimitive()){ + Object[] oUnoArray = (Object[]) _oUnoObject; + if (oUnoArray.length > 0){ + bIsUnoObject = ( oUnoArray[0].getClass().getName().equals(_sTypeName)); + } + } + } + } + else{ + bIsUnoObject = (_oUnoObject.getClass().getName().equals(_sTypeName)); + } + return bIsUnoObject; + } + + + public String getConstantDisplayString(int _nValue, XConstantTypeDescription[] _xConstantTypeDescription, String _sDisplayString){ + String sPrefix = ""; + int[] nbits = new int[_xConstantTypeDescription.length]; + for (int i = 0; i < _xConstantTypeDescription.length; i++){ + short nConstantValue = ((Short) _xConstantTypeDescription[i].getConstantValue()).shortValue(); + nbits[i] = _nValue & nConstantValue; + if (nbits[i] > 0){ + _sDisplayString += sPrefix + _xConstantTypeDescription[i].getName(); + sPrefix = " + "; + } + } + return _sDisplayString; + } + + + public static boolean isValid(Object[] _oObject){ + if (_oObject != null){ + if (_oObject.length > 0){ + return true; + } + } + return false; + } + + + + + + public static boolean isArray(Object _oObject){ + return _oObject.getClass().isArray(); + } + + + public boolean hasSupportedServices(Object _oUnoObject){ + boolean bHasSupportedServices = false; + XServiceInfo xServiceInfo = UnoRuntime.queryInterface( XServiceInfo.class, _oUnoObject); + if ( xServiceInfo != null ){ + String[] sSupportedServiceNames = xServiceInfo.getSupportedServiceNames(); + bHasSupportedServices = sSupportedServiceNames.length > 0; + } + return bHasSupportedServices; + } + + + public Object getValueOfText(TypeClass aTypeClass, String sText){ + Object oReturn = null; + switch (aTypeClass.getValue()){ + case TypeClass.CHAR_value: + break; + case TypeClass.DOUBLE_value: + oReturn = Double.valueOf(sText); + break; + case TypeClass.ENUM_value: + break; + case TypeClass.FLOAT_value: + oReturn = Float.valueOf(sText); + break; + case TypeClass.HYPER_value: + oReturn = Long.valueOf(sText); + break; + case TypeClass.LONG_value: + oReturn = Integer.valueOf(sText); + break; + case TypeClass.SHORT_value: + oReturn = Byte.valueOf(sText); + break; + case TypeClass.STRING_value: + oReturn = sText; + break; + case TypeClass.UNSIGNED_HYPER_value: + oReturn = Long.valueOf(sText); + break; + case TypeClass.UNSIGNED_LONG_value: + oReturn = Integer.valueOf(sText); + break; + case TypeClass.UNSIGNED_SHORT_value: + oReturn = Byte.valueOf(sText); + break; + default: + } + return oReturn; + } + + + public XSimpleFileAccess getXSimpleFileAccess(){ + try { + if (xSimpleFileAccess == null){ + Object oSimpleFileAccess = m_xComponentContext.getServiceManager().createInstanceWithContext("com.sun.star.ucb.SimpleFileAccess", m_xComponentContext); + xSimpleFileAccess = com.sun.star.uno.UnoRuntime.queryInterface(XSimpleFileAccess.class, oSimpleFileAccess); + } + return xSimpleFileAccess; + } catch (com.sun.star.uno.Exception ex) { + ex.printStackTrace(System.err); + return null; + }} + + + public boolean isValidSDKInstallationPath(String _sSDKInstallationPath){ + boolean bIsValid = false; + try { + String sIDLFolder = Introspector.addToPath(_sSDKInstallationPath, Inspector.sIDLDOCUMENTSUBFOLDER); + String sIndexFile = Introspector.addToPath(_sSDKInstallationPath, "index.html"); + if (getXSimpleFileAccess() != null){ + bIsValid = (getXSimpleFileAccess().exists(sIDLFolder) && getXSimpleFileAccess().exists(sIndexFile)); + } + } catch (com.sun.star.uno.Exception ex) { + ex.printStackTrace(System.err); + } + return bIsValid; + } + + + public static String addToPath(String _sPath, String _sSubPath){ + if (!_sPath.endsWith("/")){ + _sPath += "/"; + } + return _sPath + _sSubPath; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/Makefile b/odk/examples/java/Inspector/Makefile new file mode 100644 index 000000000..a0d80bf6d --- /dev/null +++ b/odk/examples/java/Inspector/Makefile @@ -0,0 +1,194 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java InstanceInspector component example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings + +# we use the sample directory name for separating this example +# from others in the output directory +SAMPLE_NAME=InstanceInspector +SAMPLE_CLASS_OUT=$(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT=$(OUT_MISC)/$(SAMPLE_NAME) + +# some special macro names for separating the component jar stuff +COMP_NAME=Inspector +COMP_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(COMP_NAME) +COMP_GEN_OUT=$(SAMPLE_GEN_OUT)/$(COMP_NAME) +COMP_RDB_NAME=$(COMP_NAME).uno.rdb +COMP_RDB=$(COMP_GEN_OUT)/$(COMP_RDB_NAME) +COMP_PACKAGE=$(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL=$(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME=$(COMP_NAME).uno.jar +COMP_JAR=$(SAMPLE_CLASS_OUT)/$(COMP_JAR_NAME) +COMP_JAR_MANIFEST=$(COMP_GEN_OUT)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(COMP_GEN_OUT)/META-INF/manifest.xml +COMP_REGISTERFLAG=$(COMP_GEN_OUT)$(PS)java_$(COMP_NAME)_register_component.flag + +IDLFILES = InstanceInspector.idl \ + XInstanceInspector.idl + +# normally the idl file should be stored in a directory tree fitting the +# module structure, for the example we know the module structure +PACKAGE = org/openoffice + +COMP_JAVAFILES = XDialogProvider.java XTreeControlProvider.java XTreePathProvider.java MethodParametersDialog.java HideableMutableTreeNode.java HideableTreeModel.java Introspector.java XUnoNode.java SwingUnoNode.java UnoNode.java XUnoMethodNode.java SwingUnoMethodNode.java UnoMethodNode.java XUnoPropertyNode.java SwingUnoPropertyNode.java UnoPropertyNode.java XUnoFacetteNode.java SwingUnoFacetteNode.java TDocSupplier.java UnoTreeRenderer.java InspectorAddon.java XLanguageSourceCodeGenerator.java SourceCodeGenerator.java InspectorPane.java SwingDialogProvider.java SwingTreeControlProvider.java SwingTreePathProvider.java Inspector.java +COMP_CLASSFILES = $(patsubst %.java,$(COMP_CLASS_OUT)/%.class,$(COMP_JAVAFILES)) + +GEN_CLASSFILES = $(patsubst %.idl,$(SAMPLE_CLASS_OUT)/$(PACKAGE)/%.class,$(IDLFILES)) +GEN_TYPELIST = $(subst /,.,$(patsubst %.idl,-T$(PACKAGE)/% ,$(IDLFILES))) +GEN_URDFILES = $(patsubst %.idl,$(SAMPLE_GEN_OUT)/%.urd,$(IDLFILES)) + +# the generated types are necessary for the component jar +GEN_CLASSFILENAMES = $(subst $(SAMPLE_CLASS_OUT)/,,$(GEN_CLASSFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)\ + $(PATH_SEPARATOR)$(COMP_CLASS_OUT)) + +COMP_IMAGE_FILES= images/containers_16.png \ + images/content_16.png \ + images/interfaces_16.png \ + images/methods_16.png \ + images/properties_16.png \ + images/services_16.png + +# Targets +.PHONY: ALL +ALL : JavaInspectorExample + +include $(SETTINGS)/stdtarget.mk + +# rule for component manifest file +$(COMP_GEN_OUT)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo RegistrationClassName: $(basename $(basename $(@F)))> $@ + +# rule for compiling the IDL files +$(SAMPLE_GEN_OUT)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -C -I. -I$(IDL_DIR) -O$(SAMPLE_GEN_OUT) $< + +# rule for creating the component rdb file +$(COMP_GEN_OUT)/%.rdb : $(GEN_URDFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(REGMERGE) $@ /UCR $(GEN_URDFILES) + +# rule for creating IDL dependent class files +$(GEN_CLASSFILES) : $(COMP_RDB) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(JAVAMAKER) -nD $(GEN_TYPELIST) -O$(SAMPLE_CLASS_OUT) $(COMP_RDB) -X$(URE_TYPES) -X$(OFFICE_TYPES) + +# component as well as application are dependent from the generated types +# rule for component class files +$(COMP_CLASS_OUT)/%.class : %.java $(GEN_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -sourcepath . -d $(COMP_CLASS_OUT) $< + +# rule for component jar file +$(COMP_JAR) : $(COMP_JAR_MANIFEST) $(COMP_CLASSFILES) $(COMP_IMAGE_FILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(COMP_CLASS_OUT) . + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) uvf $(@F) $(GEN_CLASSFILENAMES) + +$(SDK_JAR) uvf $@ $(COMP_IMAGE_FILES) + +# rule for component package manifest +$(COMP_GEN_OUT)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)Addons.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)ProtocolHandler.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-schema$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)ObjectInspector.xcs$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.configuration-data$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)ObjectInspector.xcu$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-typelibrary;type=RDB$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(SAMPLE_GEN_OUT)/,,$(@D))).uno.rdb$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-component;type=Java$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(SAMPLE_GEN_OUT)/,,$(@D))).uno.jar$(QM)"/$(CSEP) >> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_RDB) $(COMP_JAR) Addons.xcu ProtocolHandler.xcu ObjectInspector.xcu ObjectInspector.xcs $(COMP_UNOPKG_MANIFEST) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) ../../../bin/$(@F) $(COMP_RDB_NAME) + + cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_JAR_NAME) + $(SDK_ZIP) -u $@ Addons.xcu ProtocolHandler.xcu ObjectInspector.xcu ObjectInspector.xcs + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u ../../../bin/$(@F) META-INF/manifest.xml + +$(COMP_REGISTERFLAG) : $(COMP_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(COMP_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +JavaInspectorExample : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The InstanceInspector component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the example + @echo document. + @echo - + @echo $(MAKE) InstanceInspectorTest.odt.load + @echo -------------------------------------------------------------------------------- + +InstanceInspectorTest.odt.load : $(COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/java/Inspector/MethodParametersDialog.java b/odk/examples/java/Inspector/MethodParametersDialog.java new file mode 100644 index 000000000..621e6228b --- /dev/null +++ b/odk/examples/java/Inspector/MethodParametersDialog.java @@ -0,0 +1,351 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.util.ArrayList; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; + +import com.sun.star.reflection.ParamInfo; +import com.sun.star.reflection.XIdlMethod; +import com.sun.star.uno.TypeClass; + +public class MethodParametersDialog extends JDialog{ + private javax.swing.JPanel jPnlParamContainer; + private ParameterPanel[] m_aParameterPanels; + private ParamInfo[] m_aParamInfo; + private XIdlMethod m_xIdlMethod; + private ActionListener oActionListener; + private JButton jHelpButton = new JButton("Help"); + private JButton jOKButton = new JButton("Ok"); + private JButton jInvokeButton = new JButton("Invoke"); + private Object m_oUnoObject = null; + private Object m_oUnoReturnObject = null; + private JLabel jLblResult; + private JPanel jResultPanel = null; + private boolean bisdiposed = false; + private XUnoMethodNode m_xUnoMethodNode; + + + public MethodParametersDialog(XUnoMethodNode _xUnoMethodNode){ + m_xUnoMethodNode = _xUnoMethodNode; + m_xIdlMethod = _xUnoMethodNode.getXIdlMethod(); + m_aParamInfo = m_xIdlMethod.getParameterInfos(); + m_oUnoObject = m_xUnoMethodNode.getUnoObject(); + } + + + public ArrayList getMethodObjects() { + super.setModal(true); + addBorderPanel(getContentPane(), BorderLayout.NORTH); + addBorderPanel(getContentPane(), BorderLayout.WEST); + addBorderPanel(getContentPane(), BorderLayout.EAST); + jPnlParamContainer = new JPanel(); + jPnlParamContainer.setLayout(new javax.swing.BoxLayout(jPnlParamContainer, javax.swing.BoxLayout.Y_AXIS)); + JPanel jHeaderPanel = new JPanel(new BorderLayout()); + JLabel jLblHeader = new JLabel(); + jLblHeader.setText("Please insert the values for the given Parameters of the method '" + m_xIdlMethod.getName() + "'"); + jHeaderPanel.add(jLblHeader,BorderLayout.WEST); + jPnlParamContainer.add(jHeaderPanel); + + m_aParameterPanels = new ParameterPanel[m_aParamInfo.length]; + for (int i = 0; i < m_aParameterPanels.length; i++){ + m_aParameterPanels[i] = new ParameterPanel(m_aParamInfo[i]); + jPnlParamContainer.add(m_aParameterPanels[i]); + } + jPnlParamContainer.add(new ButtonPanel(), java.awt.BorderLayout.SOUTH); + getContentPane().add(jPnlParamContainer, java.awt.BorderLayout.CENTER); + pack(); + setLocation(350, 350); + setTitle("Object Inspector - Parameter Values of '" + m_xIdlMethod.getName() + "'"); + super.setFocusable(true); + super.setFocusableWindowState(true); + super.requestFocus(); + m_aParameterPanels[0].getInputComponent().requestFocusInWindow(); + setVisible(true); + if (!bisdiposed){ + ArrayList aMethodObjects = new ArrayList(); + for (int i = 0; i < m_aParameterPanels.length; i++){ + aMethodObjects.add(m_aParameterPanels[i].getValue()); + } + aMethodObjects.add(m_oUnoReturnObject); + return aMethodObjects; + } + else{ + return null; + } + } + + + private void insertResultPanel(Exception _oInvocationException){ + boolean bAddPanel = false; + if (jResultPanel == null){ + jResultPanel = new JPanel(new BorderLayout()); + bAddPanel = true; + } + else{ + jResultPanel.removeAll(); + } + jLblResult = new JLabel(); + jLblResult.setMaximumSize(new java.awt.Dimension(getSize().width - 20, 57)); + if (_oInvocationException != null){ + jLblResult.setText("Invoking the method cause an exception:
" + _oInvocationException.toString() + ""); + } + else{ + jLblResult.setText("The invocation of the method did not produce any error"); + } + jResultPanel.add(jLblResult,BorderLayout.WEST); + if (bAddPanel){ + int nPos = jPnlParamContainer.getComponentCount() - 1; + jPnlParamContainer.add(jResultPanel, nPos); + } + super.pack(); + super.validate(); + } + + + private Object[] getParameterValues(){ + Object[] oParameterValues = new Object[m_aParameterPanels.length]; + for (int i = 0; i < m_aParameterPanels.length; i++){ + oParameterValues[i] = m_aParameterPanels[i].getValue(); + } + return oParameterValues; + } + + + private boolean isCompleted(){ + boolean bIsCompleted = true; + for (int i = 0; i < m_aParameterPanels.length; i++){ + bIsCompleted = m_aParameterPanels[i].isCompleted(); + if (!bIsCompleted){ + break; + } + } + return bIsCompleted; + } + + + private void addBorderPanel(java.awt.Container _jContainer, String _sLayout){ + JPanel jPnlBorder = new JPanel(); + jPnlBorder.setPreferredSize(new java.awt.Dimension(10, 10)); + _jContainer.add(jPnlBorder, _sLayout); + } + + private void addGapPanel(java.awt.Container _jContainer){ + JPanel jPnlBorder = new JPanel(); + jPnlBorder.setPreferredSize(new java.awt.Dimension(10, 10)); + jPnlBorder.setMaximumSize(new java.awt.Dimension(10, 10)); + _jContainer.add(jPnlBorder); + } + + + private class ParameterPanel extends JPanel{ + private JComponent m_jComponent; + private TypeClass m_aTypeClass = null; + + public ParameterPanel(ParamInfo _aParamInfo){ + JTextField jTextField = new JTextField(); + JComboBox jComboBox = new JComboBox(); + m_aTypeClass = _aParamInfo.aType.getTypeClass(); + setLayout(new java.awt.BorderLayout()); + addBorderPanel(this, BorderLayout.NORTH); + addBorderPanel(this, BorderLayout.SOUTH); + JPanel jPnlCenter1 = new javax.swing.JPanel(); + jPnlCenter1.setLayout(new javax.swing.BoxLayout(jPnlCenter1, javax.swing.BoxLayout.X_AXIS)); + JLabel jLabel1 = new JLabel(); + jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); + String sParamText = _aParamInfo.aName + " (" + _aParamInfo.aType.getName() +")"; + jLabel1.setText(sParamText); + jPnlCenter1.add(jLabel1); + addGapPanel(jPnlCenter1); + switch (m_aTypeClass.getValue()){ + case TypeClass.BOOLEAN_value: + jComboBox.setBackground(new java.awt.Color(255, 255, 255)); + jComboBox.setPreferredSize(new java.awt.Dimension(50, 19)); + jComboBox.addItem("True"); + jComboBox.addItem("False"); + jComboBox.addKeyListener(new UpdateUIAdapter()); + jPnlCenter1.add(jComboBox); + m_jComponent = jComboBox; + break; + case TypeClass.BYTE_value: + case TypeClass.CHAR_value: + case TypeClass.DOUBLE_value: + case TypeClass.ENUM_value: + case TypeClass.FLOAT_value: + case TypeClass.HYPER_value: + case TypeClass.LONG_value: + case TypeClass.SHORT_value: + case TypeClass.STRING_value: + case TypeClass.UNSIGNED_HYPER_value: + case TypeClass.UNSIGNED_LONG_value: + case TypeClass.UNSIGNED_SHORT_value: + jTextField.setPreferredSize(new java.awt.Dimension(50, 19)); + jTextField.addKeyListener(new UpdateUIAdapter()); + jPnlCenter1.add(jTextField); + m_jComponent = jTextField; + break; + default: + System.out.println("Type " + m_aTypeClass.getValue() + " not yet defined in 'ParameterPanel()'"); + } + add(jPnlCenter1, java.awt.BorderLayout.CENTER); + JPanel jPnlEast = new JPanel(); + add(jPnlEast, BorderLayout.EAST); + } + + private JComponent getInputComponent(){ + return m_jComponent; + } + + public Object getValue(){ + Object oReturn = null; + if (m_jComponent instanceof JTextField){ + String sText = ((JTextField) m_jComponent).getText(); + oReturn = Introspector.getIntrospector().getValueOfText(m_aTypeClass, sText); + } + else{ + JComboBox jComboBox = ((JComboBox) m_jComponent); + oReturn = Boolean.valueOf(jComboBox.getSelectedIndex() == 0); + } + return oReturn; + } + + + public boolean isCompleted(){ + if (m_jComponent instanceof JTextField){ + return !((JTextField) m_jComponent).getText().equals(""); + } + else{ + return true; + } + } + } + + + private class UpdateUIAdapter extends KeyAdapter{ + @Override + public void keyReleased(KeyEvent e){ + boolean bIsCompleted = isCompleted(); + jOKButton.setEnabled(bIsCompleted); + jInvokeButton.setEnabled(bIsCompleted); + if (jLblResult != null){ + jLblResult.setEnabled(false); + jLblResult.invalidate(); + } + } + } + + + + private class ButtonPanel extends JPanel{ + public ButtonPanel(){ + super(); + setLayout(new BorderLayout()); + addBorderPanel(this, BorderLayout.NORTH); + addBorderPanel(this, BorderLayout.SOUTH); + JPanel jPnlBottomCenter = new JPanel(); + jPnlBottomCenter.setLayout(new javax.swing.BoxLayout(jPnlBottomCenter, javax.swing.BoxLayout.X_AXIS)); + jHelpButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + oActionListener.actionPerformed(e); + } + }); + jHelpButton.setEnabled(oActionListener != null); + jPnlBottomCenter.add(jHelpButton); + addGapPanel(jPnlBottomCenter); + jOKButton.setEnabled(false); + jOKButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + invokeParameterMethod(); + dispose(); + } + }); + jOKButton.setEnabled(isCompleted()); + jInvokeButton.setEnabled(isCompleted()); + jInvokeButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e) { + invokeParameterMethod(); + } + }); + + jPnlBottomCenter.add(jOKButton); + addGapPanel(jPnlBottomCenter); + jPnlBottomCenter.add(jInvokeButton); + addGapPanel(jPnlBottomCenter); + JButton jCancelButton = new JButton("Cancel"); + jCancelButton.setFocusCycleRoot(true); + jCancelButton.setFocusPainted(true); + jCancelButton.addActionListener(new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + bisdiposed = true; + dispose(); + } + }); + + jPnlBottomCenter.add(jCancelButton); + add(jPnlBottomCenter); + } + } + + + public void addActionListener(ActionListener _oActionListener){ + oActionListener = _oActionListener; + jHelpButton.setEnabled(oActionListener != null); + } + + + private void invokeParameterMethod(){ + try{ + Object[] oParameters = getParameterValues(); + m_oUnoReturnObject = m_xUnoMethodNode.invoke(m_oUnoObject, oParameters); + insertResultPanel(null); + } catch (Exception ex) { + insertResultPanel(ex); + m_oUnoReturnObject = null; + }} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/ObjectInspector.xcs b/odk/examples/java/Inspector/ObjectInspector.xcs new file mode 100644 index 000000000..552e72ef8 --- /dev/null +++ b/odk/examples/java/Inspector/ObjectInspector.xcs @@ -0,0 +1,34 @@ + + + + + Configuration parameters for the Object Inspector. + + + + + + + diff --git a/odk/examples/java/Inspector/ObjectInspector.xcu b/odk/examples/java/Inspector/ObjectInspector.xcu new file mode 100644 index 000000000..b76960866 --- /dev/null +++ b/odk/examples/java/Inspector/ObjectInspector.xcu @@ -0,0 +1,35 @@ + + + + +]> + + + Java + + + + + + + diff --git a/odk/examples/java/Inspector/ProtocolHandler.xcu b/odk/examples/java/Inspector/ProtocolHandler.xcu new file mode 100644 index 000000000..30f3b6b44 --- /dev/null +++ b/odk/examples/java/Inspector/ProtocolHandler.xcu @@ -0,0 +1,28 @@ + + + + + + + org.openoffice.Office.addon.Inspector:* + + + + + diff --git a/odk/examples/java/Inspector/ProtocolHandlerAddon.java b/odk/examples/java/Inspector/ProtocolHandlerAddon.java new file mode 100644 index 000000000..51158c392 --- /dev/null +++ b/odk/examples/java/Inspector/ProtocolHandlerAddon.java @@ -0,0 +1,273 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.XComponentContext; +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.registry.XRegistryKey; +import com.sun.star.lang.XInitialization; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.frame.XStatusListener; +import com.sun.star.frame.XDispatchProvider; +import com.sun.star.frame.XDispatch; +import com.sun.star.frame.XFrame; +import com.sun.star.frame.DispatchDescriptor; +import com.sun.star.awt.XToolkit; +import com.sun.star.awt.XWindowPeer; +import com.sun.star.awt.XMessageBox; +import com.sun.star.awt.WindowAttribute; +import com.sun.star.awt.WindowClass; +import com.sun.star.awt.WindowDescriptor; +import com.sun.star.awt.Rectangle; + +public class ProtocolHandlerAddon { + /** This class implements the component. At least the interfaces XServiceInfo, + * XTypeProvider, and XInitialization should be provided by the service. + */ + public static class ProtocolHandlerAddonImpl extends WeakBase implements + XDispatchProvider, + XDispatch, + XInitialization, + XServiceInfo { + + /** The service name, that must be used to get an instance of this service. + */ + private static final String[] m_serviceNames = { "com.sun.star.frame.ProtocolHandler" }; + + /** The component context, that gives access to the service manager and all registered services. + */ + private XComponentContext m_xCmpCtx; + + /** The toolkit, that we can create UNO dialogs. + */ + private XToolkit m_xToolkit; + + /** The frame where the addon depends on. + */ + private XFrame m_xFrame; + + + /** The constructor of the inner class has a XMultiServiceFactory parameter. + * @param xComponentContext A special service factory + * could be introduced while initializing. + */ + public ProtocolHandlerAddonImpl( XComponentContext xComponentContext ) { + m_xCmpCtx = xComponentContext; + } + + /** This method is a member of the interface for initializing an object + * directly after its creation. + * @param object This array of arbitrary objects will be passed to the + * component after its creation. + * @throws com.sun.star.uno.Exception Every exception will not be handled, but will be + * passed to the caller. + */ + public void initialize( Object[] object ) + throws com.sun.star.uno.Exception { + + if ( object.length > 0 ) + { + m_xFrame = UnoRuntime.queryInterface( + XFrame.class, object[ 0 ] ); + } + + // Create the toolkit to have access to it later + m_xToolkit = UnoRuntime.queryInterface( + XToolkit.class, + m_xCmpCtx.getServiceManager().createInstanceWithContext("com.sun.star.awt.Toolkit", + m_xCmpCtx)); + } + + /** This method returns an array of all supported service names. + * @return Array of supported service names. + */ + public String[] getSupportedServiceNames() { + return getServiceNames(); + } + + private static String[] getServiceNames() { + return m_serviceNames; + } + + /** This method returns true, if the given service will be + * supported by the component. + * @param sService Service name. + * @return True, if the given service name will be supported. + */ + public boolean supportsService( String sService ) { + int len = m_serviceNames.length; + + for( int i=0; i < len; i++) { + if ( sService.equals( m_serviceNames[i] ) ) + return true; + } + + return false; + } + + /** Return the class name of the component. + * @return Class name of the component. + */ + public String getImplementationName() { + return ProtocolHandlerAddonImpl.class.getName(); + } + + // XDispatchProvider + public XDispatch queryDispatch( /*IN*/com.sun.star.util.URL aURL, + /*IN*/String sTargetFrameName, + /*IN*/int iSearchFlags ) { + XDispatch xRet = null; + if ( aURL.Protocol.equals("org.openoffice.Office.addon.example:") ) { + if ( aURL.Path.equals( "Function1" ) ) + xRet = this; + if ( aURL.Path.equals( "Function2" ) ) + xRet = this; + if ( aURL.Path.equals( "Help" ) ) + xRet = this; + } + return xRet; + } + + public XDispatch[] queryDispatches( /*IN*/DispatchDescriptor[] seqDescripts ) { + int nCount = seqDescripts.length; + XDispatch[] lDispatcher = new XDispatch[nCount]; + + for( int i=0; iJavaLoader + *

+ * @return Returns a XSingleServiceFactory for creating the + * component. + * @see com.sun.star.comp.loader.JavaLoader + * @param sImplementationName The implementation name of the component. + */ + public static XSingleComponentFactory __getComponentFactory( String sImplementationName ) { + XSingleComponentFactory xFactory = null; + + if ( sImplementationName.equals( ProtocolHandlerAddonImpl.class.getName() ) ) + xFactory = Factory.createComponentFactory(ProtocolHandlerAddonImpl.class, + ProtocolHandlerAddonImpl.getServiceNames()); + + return xFactory; + } + + /** Writes the service information into the given registry key. + * This method is called by the JavaLoader. + * @return returns true if the operation succeeded + * @see com.sun.star.comp.loader.JavaLoader + * @see com.sun.star.lib.uno.helper.Factory + * @param xRegistryKey Makes structural information (except regarding tree + * structures) of a single + * registry key accessible. + */ + public static boolean __writeRegistryServiceInfo( + XRegistryKey xRegistryKey ) { + return Factory.writeRegistryServiceInfo( + ProtocolHandlerAddonImpl.class.getName(), + ProtocolHandlerAddonImpl.getServiceNames(), + xRegistryKey ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/SourceCodeGenerator.java b/odk/examples/java/Inspector/SourceCodeGenerator.java new file mode 100644 index 000000000..9ff6ad793 --- /dev/null +++ b/odk/examples/java/Inspector/SourceCodeGenerator.java @@ -0,0 +1,1635 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.ArrayList; +import java.util.HashMap; + +import com.sun.star.reflection.ParamInfo; +import com.sun.star.reflection.XIdlClass; +import com.sun.star.reflection.XIdlMethod; +import com.sun.star.reflection.XTypeDescription; +import com.sun.star.uno.Any; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.TypeClass; + + + +public class SourceCodeGenerator { + private ArrayList sExceptions = new ArrayList(); + private ArrayList sHeaderStatements = new HeaderStatements(); + private XLanguageSourceCodeGenerator m_xLanguageSourceCodeGenerator; + private String sStatementCode = ""; + private String sMainMethodSignature = ""; + + private HashMap aVariables = new HashMap(); + private final String SSUFFIXSEPARATOR = "_"; + private final String SVARIABLENAME = "VariableName"; + private Introspector m_oIntrospector; + private ArrayList aTreepathProviders = new ArrayList(); + private boolean baddExceptionHandling = false; + private boolean bXPropertySetExceptionsAreAdded = false; + private XUnoNode oInitialUnoNode = null; + private final String sINITIALVARIABLENAME = "_oUnoEntryObject"; + + + /** Creates a new instance of SourceCodeGenerator */ + public SourceCodeGenerator(int _nLanguage) { + this.setLanguage(_nLanguage); + m_oIntrospector = Introspector.getIntrospector(); + } + + + public String addSourceCodeOfUnoObject(XTreePathProvider _xTreepathProvider, boolean _brememberPath, boolean _baddHeader){ + String sVariableName = ""; + if (_xTreepathProvider != null) { + for (int i = 0; i < _xTreepathProvider.getPathCount(); i++){ + XUnoNode oUnoNode = _xTreepathProvider.getPathComponent(i); + if (i == 0){ + sVariableName = sINITIALVARIABLENAME; + oInitialUnoNode = oUnoNode; + } + else{ + if (oUnoNode instanceof XUnoMethodNode){ + XUnoMethodNode oUnoMethodNode = (XUnoMethodNode) oUnoNode; + if (oUnoMethodNode.isInvoked()){ + UnoObjectDefinition oUnoReturnObjectDefinition = getUnoObjectDefinition(_xTreepathProvider, oUnoMethodNode, i); + if (!isVariableDeclared(oUnoReturnObjectDefinition, this.generateVariableNameFromMethod(oUnoMethodNode.getXIdlMethod()))){ + sStatementCode += "\n" + getMethodStatementSourceCode(oUnoMethodNode, sVariableName, oUnoReturnObjectDefinition); + } + sVariableName = oUnoReturnObjectDefinition.getVariableName(); + } + } + else if (oUnoNode instanceof XUnoPropertyNode){ + XUnoPropertyNode oUnoPropertyNode = (XUnoPropertyNode) oUnoNode; + Any oReturnObject = com.sun.star.uno.Any.complete(oUnoPropertyNode.getUnoReturnObject()); + UnoObjectDefinition oUnoReturnObjectDefinition = new UnoObjectDefinition(oReturnObject); + if (!isVariableDeclared(oUnoReturnObjectDefinition, oUnoPropertyNode.getProperty().Name)){ + sStatementCode += "\n" + getPropertyStatementSourceCode(oUnoPropertyNode, sVariableName, oUnoReturnObjectDefinition); + } + sVariableName = oUnoReturnObjectDefinition.getVariableName(); + } + } + } + } + String sCompleteCode = combineCompleteSourceCode(_baddHeader); + if (_brememberPath){ + aTreepathProviders.add(_xTreepathProvider); + } + return sCompleteCode; + } + + + private void setLanguage(int _nLanguage){ + XLanguageSourceCodeGenerator xLanguageSourceCodeGenerator = null; + switch(_nLanguage){ + case XLanguageSourceCodeGenerator.nJAVA: + xLanguageSourceCodeGenerator = new JavaCodeGenerator(); + break; + case XLanguageSourceCodeGenerator.nCPLUSPLUS: + xLanguageSourceCodeGenerator = new CPlusPlusCodeGenerator(); + break; + case XLanguageSourceCodeGenerator.nBASIC: + xLanguageSourceCodeGenerator = new BasicCodeGenerator(); + break; + default: + System.out.println("Unknown Sourcecode Language. Check Menus!"); + } + if (xLanguageSourceCodeGenerator != null){ + m_xLanguageSourceCodeGenerator = xLanguageSourceCodeGenerator; + } + } + + private void resetSourceCodeGeneration(int _nLanguage){ + aVariables.clear(); + this.sHeaderStatements.clear(); + setLanguage(_nLanguage); + sStatementCode = ""; + } + + private String generateVariableNameFromMethod(String _sMethodName, String _sPrefix, boolean _bConsiderAll){ + String sReturn = ""; + if (_sMethodName.startsWith(_sPrefix)){ + int nPrefixLength = _sPrefix.length(); + if (_sMethodName.length() > nPrefixLength){ + String sChar = _sMethodName.substring(nPrefixLength, nPrefixLength + 1); + String sUpperChar = sChar.toUpperCase(); + if (sUpperChar.equals(sChar)){ + if (_bConsiderAll){ + sReturn = _sMethodName; + } + else{ + sReturn = _sMethodName.substring(nPrefixLength, _sMethodName.length()); + } + } + } + } + return sReturn; + } + + + private String generateVariableNameFromMethod(XIdlMethod _xIdlMethod){ + // todo: refactor this!!! + String sMethodName = _xIdlMethod.getName(); + String sReturn = ""; + sReturn = generateVariableNameFromMethod(sMethodName, "getBy", false); + if (sReturn.equals("")){ + sReturn = generateVariableNameFromMethod(sMethodName, "get", false); + } + if (sReturn.equals("")){ + sReturn = generateVariableNameFromMethod(sMethodName, "attach", false); + } + if (sReturn.equals("")){ + sReturn = generateVariableNameFromMethod(sMethodName, "assign", false); + } + if (sReturn.equals("")){ + sReturn = generateVariableNameFromMethod(sMethodName, "attach", false); + } + if (sReturn.equals("")){ + sReturn = generateVariableNameFromMethod(sMethodName, "create", false); + } + if (sReturn.equals("")){ + sReturn = generateVariableNameFromMethod(sMethodName, "is", true); + } + if (sReturn.equals("")){ + sReturn = generateVariableNameFromMethod(sMethodName, "has", true); + } + if (sReturn.equals("")){ + sReturn = sMethodName; + } + return sReturn; + } + + + public String convertAllUnoObjects(int _nLanguage){ + String sSourceCode = ""; + resetSourceCodeGeneration(_nLanguage); + int ncount = aTreepathProviders.size(); + for (int i=0; i< ncount; i++){ + sSourceCode = addSourceCodeOfUnoObject(aTreepathProviders.get(i), false, (i == (ncount-1))); + } + return sSourceCode; + } + + private UnoObjectDefinition getUnoObjectDefinition(XTreePathProvider _xTreePathProvider, XUnoMethodNode _oUnoMethodNode, int _nindex){ + XUnoNode oUnoNode = null; + Object oUnoReturnObject = null; + Object[] oParamObjects = null; + XIdlClass xIdlClass = _oUnoMethodNode.getXIdlMethod().getReturnType(); + String sTypeName = xIdlClass.getName(); + TypeClass aTypeClass = xIdlClass.getTypeClass(); + if (aTypeClass.getValue() != TypeClass.VOID_value){ + if (_xTreePathProvider.getPathCount() > _nindex + 1){ + oUnoNode = _xTreePathProvider.getPathComponent(_nindex + 1); + oUnoReturnObject = oUnoNode.getUnoObject(); + } + } + if (oUnoReturnObject == null){ + oUnoReturnObject = _oUnoMethodNode.getLastUnoReturnObject(); + } + UnoObjectDefinition oUnoObjectDefinition = new UnoObjectDefinition(oUnoReturnObject, sTypeName, aTypeClass); + if (_oUnoMethodNode.hasParameters()){ + if (oUnoNode != null){ + oParamObjects = oUnoNode.getParameterObjects(); + } + else{ + oParamObjects = _oUnoMethodNode.getLastParameterObjects(); + } + } + if (oParamObjects != null){ + oUnoObjectDefinition.addParameterObjects(oParamObjects); + } + return oUnoObjectDefinition; + } + + + private String combineCompleteSourceCode(boolean _bAddHeader){ + String sCompleteCode = ""; + if (_bAddHeader){ + sMainMethodSignature = m_xLanguageSourceCodeGenerator.getMainMethodSignatureSourceCode(oInitialUnoNode, sINITIALVARIABLENAME); + m_xLanguageSourceCodeGenerator.assignqueryInterfaceHeaderSourceCode(); + sCompleteCode += getHeaderSourceCode(); + } + sCompleteCode += sMainMethodSignature; + sCompleteCode += sStatementCode; + if (_bAddHeader){ + sCompleteCode += m_xLanguageSourceCodeGenerator.getMethodTerminationSourceCode(); + sCompleteCode += "\n" + m_xLanguageSourceCodeGenerator.getCommentSign() + "..."; + } + return sCompleteCode; + } + + + private String getPropertyStatementSourceCode(XUnoPropertyNode _oUnoPropertyNode, String _sVariableName, UnoObjectDefinition _oUnoReturnObjectDefinition){ + String sReturnObjectVariableDefinition = ""; + String sStatement = ""; + String sPropertyName = _oUnoPropertyNode.getProperty().Name; + UnoObjectDefinition oUnoObjectDefinition = new UnoObjectDefinition(_oUnoPropertyNode.getUnoObject(), "com.sun.star.beans.XPropertySet"); + if (!m_xLanguageSourceCodeGenerator.needsqueryInterface() || (oUnoObjectDefinition.getTypeClass().getValue() == TypeClass.STRUCT_value)){ + oUnoObjectDefinition.setVariableName(_sVariableName); + if (oUnoObjectDefinition.getTypeClass().getValue() == TypeClass.STRUCT_value){ + sReturnObjectVariableDefinition = getVariableInitialization(_oUnoReturnObjectDefinition, false); + sStatement += m_xLanguageSourceCodeGenerator.getStructSourceCode(sReturnObjectVariableDefinition, oUnoObjectDefinition.getVariableName(), sPropertyName); + return sStatement; + } + } + sStatement += addQueryInterfaceSourceCode(oUnoObjectDefinition, _sVariableName, "com.sun.star.beans.XPropertySet"); + if (_oUnoReturnObjectDefinition.getTypeClass().getValue() != TypeClass.VOID_value){ + sReturnObjectVariableDefinition = getVariableInitialization(_oUnoReturnObjectDefinition, true); + } + sStatement += m_xLanguageSourceCodeGenerator.getPropertyValueGetterSourceCode(sPropertyName, sReturnObjectVariableDefinition, oUnoObjectDefinition.getVariableName(), _oUnoReturnObjectDefinition.getTypeClass(), _oUnoReturnObjectDefinition.getTypeName()); + addXPropertySetRelatedExceptions(); + return sStatement; + } + + + private String getMethodStatementSourceCode(XUnoMethodNode _oUnoMethodNode, String _sVariableName, UnoObjectDefinition _oUnoReturnObjectDefinition){ + String sReturnObjectVariableDefinition = ""; + String sStatement = ""; + XIdlMethod xIdlMethod = _oUnoMethodNode.getXIdlMethod(); + TypeClass aReturnTypeClass = xIdlMethod.getReturnType().getTypeClass(); + UnoObjectDefinition oUnoObjectDefinition = new UnoObjectDefinition(_oUnoMethodNode.getUnoObject(), _oUnoMethodNode.getClassName()); + String sVariableStemName = this.generateVariableNameFromMethod(xIdlMethod); + sStatement += addQueryInterfaceSourceCode(oUnoObjectDefinition, _sVariableName, oUnoObjectDefinition.getTypeName()); + if (_oUnoReturnObjectDefinition.getTypeClass().getValue() != TypeClass.VOID_value){ + sReturnObjectVariableDefinition = getVariableInitialization(_oUnoReturnObjectDefinition, false) + " = "; + } + Object[] oParamObjects = _oUnoReturnObjectDefinition.getParameterObjects(); + String sParameterCode = getMethodParameterValueDescription(_oUnoMethodNode, oParamObjects, false); + String sSeparator = m_xLanguageSourceCodeGenerator.getMethodSeparator(); + sStatement += "\t" + sReturnObjectVariableDefinition + oUnoObjectDefinition.getVariableName() + sSeparator + xIdlMethod.getName() + "(" + sParameterCode + ")"; + sStatement += m_xLanguageSourceCodeGenerator.getStatementTerminationCharacter(); + addExceptions(xIdlMethod); + return sStatement; + } + + + private String addQueryInterfaceSourceCode(UnoObjectDefinition _oUnoObjectDefinition, String _sVariableName, String _sTypeName){ + String sLocStatement = ""; + if (m_xLanguageSourceCodeGenerator.needsqueryInterface()){ + if (!isVariableDeclared(_oUnoObjectDefinition, "")){ + String sObjectVariableDefinition = getVariableDeclaration(_oUnoObjectDefinition, false, ""); + sLocStatement += m_xLanguageSourceCodeGenerator.getqueryInterfaceSourceCode(_sTypeName, sObjectVariableDefinition, _sVariableName); + } + } + else{ + _oUnoObjectDefinition.setVariableName(_sVariableName); + } + return sLocStatement; + } + + + private void addXPropertySetRelatedExceptions(){ + if (!bXPropertySetExceptionsAreAdded){ + sExceptions.add("com.sun.star.beans.UnknownPropertyException"); + sExceptions.add("com.sun.star.lang.WrappedTargetException"); + sExceptions.add("com.sun.star.lang.IllegalArgumentException"); + bXPropertySetExceptionsAreAdded = true; + baddExceptionHandling = true; + } + } + + + private void addExceptions(XIdlMethod _xIdlMethod){ + XIdlClass[] xIdlClasses = _xIdlMethod.getExceptionTypes(); + for (int i = 0; i > xIdlClasses.length; i++){ + sExceptions.add(xIdlClasses[0].getName()); + baddExceptionHandling = true; + } + } + + private String getHeaderSourceCode(){ + for(UnoObjectDefinition oUnoObjectDefinition : aVariables.values()){ + String sCurHeaderStatement = m_xLanguageSourceCodeGenerator.getHeaderSourceCode(oUnoObjectDefinition.getUnoObject(), oUnoObjectDefinition.getTypeName(), oUnoObjectDefinition.getTypeClass()); + sHeaderStatements.add(sCurHeaderStatement); + } + String sHeaderSourcecode = ""; + String[] sHeaderStatementArray = new String[sHeaderStatements.size()]; + sHeaderStatements.toArray(sHeaderStatementArray); + java.util.Arrays.sort(sHeaderStatementArray); + for (int i = 0; i < sHeaderStatementArray.length; i++){ + sHeaderSourcecode += sHeaderStatementArray[i]; + } + sHeaderSourcecode += m_xLanguageSourceCodeGenerator.getFinalHeaderStatements(); + return sHeaderSourcecode +"\n" + m_xLanguageSourceCodeGenerator.getCommentSign() + "...\n"; + } + + + private class HeaderStatements extends ArrayList { + + public boolean contains(String _oElement){ + String sCompName = _oElement; + for (int i = 0; i < this.size(); i++){ + String sElement = this.get(i); + if (sElement.equals(sCompName)){ + return true; + } + } + return false; + } + + + @Override + public boolean add(String _oElement){ + if (!contains(_oElement)){ + super.add(_oElement); + return true; + } + return false; + } + } + + + private boolean isVariableDeclared(UnoObjectDefinition _oUnoObjectDefinition, String _sDefaultStemName){ + boolean bisDeclared = false; + if (!_sDefaultStemName.equals("")){ + _oUnoObjectDefinition.setCentralVariableStemName(_sDefaultStemName); + } + String sVariableStemName = _oUnoObjectDefinition.getVariableStemName(); + bisDeclared = aVariables.containsKey(sVariableStemName); + if (bisDeclared){ + Object oUnoObject = _oUnoObjectDefinition.getUnoObject(); + if (Introspector.isObjectPrimitive(oUnoObject)){ + bisDeclared = false; + } + else if (Introspector.isObjectSequence(oUnoObject)){ + bisDeclared = false; + } + else{ + String sCompVariableName = sVariableStemName; + String sUnoObjectIdentity = oUnoObject.toString(); + boolean bleaveloop = false; + int a = 2; + while (!bleaveloop){ + if (aVariables.containsKey(sCompVariableName)){ + Object oUnoCompObject = aVariables.get(sCompVariableName).getUnoObject(); + String sUnoCompObjectIdentity = oUnoCompObject.toString(); + bleaveloop = sUnoCompObjectIdentity.equals(sUnoObjectIdentity); + bisDeclared = bleaveloop; + if (!bleaveloop){ + sCompVariableName = sVariableStemName + SSUFFIXSEPARATOR + a++; + } + } + else{ + bleaveloop = true; + bisDeclared = false; + } + } + } + } + return bisDeclared; + } + + + private String addUniqueVariableName(String _sStemVariableName, UnoObjectDefinition _oUnoObjectDefinition){ + boolean bElementexists = true; + int a = 2; + String sCompName = _sStemVariableName; + while (bElementexists){ + if (! aVariables.containsKey(sCompName)){ + aVariables.put(sCompName, _oUnoObjectDefinition); + break; + } + sCompName = _sStemVariableName + SSUFFIXSEPARATOR + a++; + } + return sCompName; + } + + + + private String getTypeString(String _sTypeName, TypeClass _aTypeClass, boolean _bAsHeaderSourceCode){ + String sTypeString = ""; + switch (_aTypeClass.getValue()){ + case TypeClass.BOOLEAN_value: + sTypeString = m_xLanguageSourceCodeGenerator.getbooleanTypeDescription(); + break; + case TypeClass.BYTE_value: + sTypeString = m_xLanguageSourceCodeGenerator.getbyteTypeDescription(); + break; + case TypeClass.CHAR_value: + sTypeString = m_xLanguageSourceCodeGenerator.getcharTypeDescription(); + break; + case TypeClass.DOUBLE_value: + sTypeString = m_xLanguageSourceCodeGenerator.getdoubleTypeDescription(); + break; + case TypeClass.FLOAT_value: + sTypeString = m_xLanguageSourceCodeGenerator.getfloatTypeDescription(); + break; + case TypeClass.HYPER_value: + sTypeString = m_xLanguageSourceCodeGenerator.gethyperTypeDescription(); + break; + case TypeClass.LONG_value: + sTypeString = m_xLanguageSourceCodeGenerator.getlongTypeDescription(); + break; + case TypeClass.SHORT_value: + sTypeString = m_xLanguageSourceCodeGenerator.getshortTypeDescription(); + break; + case TypeClass.STRING_value: + sTypeString = m_xLanguageSourceCodeGenerator.getstringTypeDescription(_bAsHeaderSourceCode); + break; + case TypeClass.UNSIGNED_HYPER_value: + sTypeString = m_xLanguageSourceCodeGenerator.getunsignedhyperTypeDescription(); + break; + case TypeClass.UNSIGNED_LONG_value: + sTypeString = m_xLanguageSourceCodeGenerator.getunsignedlongTypeDescription(); + break; + case TypeClass.UNSIGNED_SHORT_value: + sTypeString = m_xLanguageSourceCodeGenerator.getdoubleTypeDescription(); + break; + case TypeClass.SEQUENCE_value: + //TODO consider mulitdimensional Arrays + XTypeDescription xTypeDescription = Introspector.getIntrospector().getReferencedType(_sTypeName); + if (xTypeDescription != null){ + sTypeString = getTypeString(xTypeDescription.getName(), xTypeDescription.getTypeClass(), _bAsHeaderSourceCode); + } + break; + case TypeClass.ANY_value: + sTypeString = m_xLanguageSourceCodeGenerator.getanyTypeDescription(_bAsHeaderSourceCode); + break; + case TypeClass.TYPE_value: + sTypeString = m_xLanguageSourceCodeGenerator.getObjectTypeDescription("com.sun.star.uno.Type", _bAsHeaderSourceCode); + break; + case TypeClass.ENUM_value: + case TypeClass.STRUCT_value: + case TypeClass.INTERFACE_ATTRIBUTE_value: + case TypeClass.INTERFACE_METHOD_value: + case TypeClass.INTERFACE_value: + case TypeClass.PROPERTY_value: + sTypeString = m_xLanguageSourceCodeGenerator.getObjectTypeDescription(_sTypeName, _bAsHeaderSourceCode); + break; + default: + } + return sTypeString; + } + + + private String getVariableDeclaration(UnoObjectDefinition _oUnoObjectDefinition, boolean _bInitialize, String _sVariableDefaultName){ + TypeClass aTypeClass = _oUnoObjectDefinition.getTypeClass(); + TypeClass aLocTypeClass = aTypeClass; + boolean bIsArray = false; + if (_oUnoObjectDefinition.getUnoObject() != null){ + bIsArray = Introspector.isObjectSequence(_oUnoObjectDefinition.getUnoObject()); + } + else{ + bIsArray = _oUnoObjectDefinition.getTypeClass().getValue() == TypeClass.SEQUENCE_value; + } + String sVariableName = _oUnoObjectDefinition.getVariableName(_sVariableDefaultName); + String sTypeName = _oUnoObjectDefinition.getTypeName(); + String sTypeString = getTypeString(sTypeName, aLocTypeClass, false); + if (bIsArray){ + XTypeDescription xTypeDescription = Introspector.getIntrospector().getReferencedType(sTypeName); + if (xTypeDescription != null){ + aLocTypeClass = xTypeDescription.getTypeClass(); + } + } + String sVariableDeclaration = m_xLanguageSourceCodeGenerator.getVariableDeclaration(sTypeString, sVariableName, bIsArray, aLocTypeClass, _bInitialize); + addUniqueVariableName(sVariableName, _oUnoObjectDefinition); + return sVariableDeclaration; + } + + + private String getVariableInitialization(UnoObjectDefinition _oUnoObjectDefinition, boolean _bInitialize){ + String sObjectVariableDeclaration = ""; + String sVariableName = _oUnoObjectDefinition.getVariableName(); + if (isVariableDeclared(_oUnoObjectDefinition, "")){ + sObjectVariableDeclaration = sVariableName; + } + else{ + sObjectVariableDeclaration = getVariableDeclaration(_oUnoObjectDefinition, _bInitialize, ""); + } + return sObjectVariableDeclaration; + } + + + + public String getVariableNameforUnoObject(String _sShortClassName){ + if (_sShortClassName.startsWith("X")){ + return "x" + _sShortClassName.substring(1); + } + else{ + return _sShortClassName; + } + } + + +private class UnoObjectDefinition{ + private Object m_oUnoObject = null; + + private String sVariableStemName = ""; + private String m_sCentralVariableStemName = ""; + private String sVariableName = ""; + private String m_sTypeName = ""; + private TypeClass m_aTypeClass = null; + private Object[] m_oParameterObjects = null; + + + private UnoObjectDefinition(Any _oUnoObject){ + m_sTypeName = _oUnoObject.getType().getTypeName(); + m_aTypeClass = _oUnoObject.getType().getTypeClass(); + m_oUnoObject = _oUnoObject; + m_sCentralVariableStemName = getCentralVariableStemName(m_aTypeClass); + } + + + private UnoObjectDefinition(Object _oUnoObject, String _sTypeName, TypeClass _aTypeClass){ + m_oUnoObject = _oUnoObject; + m_sTypeName = _sTypeName; + m_aTypeClass = _aTypeClass; + m_sCentralVariableStemName = getCentralVariableStemName(m_aTypeClass); + } + + + private UnoObjectDefinition(Object _oUnoObject, String _sTypeName){ + m_oUnoObject = _oUnoObject; + m_sTypeName = _sTypeName; + m_aTypeClass = AnyConverter.getType(_oUnoObject).getTypeClass(); + m_sCentralVariableStemName = getCentralVariableStemName(m_aTypeClass); + } + + + private String getCentralVariableStemName(TypeClass _aTypeClass){ + String sCentralVariableStemName = ""; + int nTypeClass = _aTypeClass.getValue(); + switch(nTypeClass){ + case TypeClass.SEQUENCE_value: + //TODO consider mulitdimensional Arrays + XTypeDescription xTypeDescription = Introspector.getIntrospector().getReferencedType(getTypeName()); + if (xTypeDescription != null){ + sCentralVariableStemName = getCentralVariableStemName(xTypeDescription.getTypeClass()); + } + break; + case TypeClass.TYPE_value: + sCentralVariableStemName = SVARIABLENAME; + break; + case TypeClass.STRUCT_value: + sCentralVariableStemName = Introspector.getShortClassName(getTypeName()); + break; + case TypeClass.INTERFACE_ATTRIBUTE_value: + case TypeClass.INTERFACE_METHOD_value: + case TypeClass.INTERFACE_value: + case TypeClass.PROPERTY_value: + String sShortClassName = Introspector.getShortClassName(getTypeName()); + sCentralVariableStemName = getVariableNameforUnoObject(sShortClassName); + default: + sCentralVariableStemName = SVARIABLENAME; + } + return sCentralVariableStemName; + } + + /** may return null + */ + public Object getUnoObject(){ + return m_oUnoObject; + } + + + public TypeClass getTypeClass(){ + return m_aTypeClass; + } + + + public String getTypeName(){ + return m_sTypeName; + } + + + public void setCentralVariableStemName(String _sCentralVariableStemName){ + m_sCentralVariableStemName = _sCentralVariableStemName; + } + + + public String getVariableStemName(){ + if (sVariableStemName.equals("")){ + sVariableStemName = getVariableStemName(m_aTypeClass); + } + return sVariableStemName; + } + + + private void addParameterObjects(Object[] _oParameterObjects){ + m_oParameterObjects = _oParameterObjects; + } + + + public Object[] getParameterObjects(){ + return m_oParameterObjects; + } + + + + + + private String getVariableStemName(TypeClass _aTypeClass){ + int nTypeClass = _aTypeClass.getValue(); + switch(nTypeClass){ + case TypeClass.BOOLEAN_value: + sVariableStemName = "b" + m_sCentralVariableStemName; + break; + case TypeClass.DOUBLE_value: + case TypeClass.FLOAT_value: + sVariableStemName = "f" + m_sCentralVariableStemName; + break; + case TypeClass.BYTE_value: + case TypeClass.HYPER_value: + case TypeClass.LONG_value: + case TypeClass.UNSIGNED_HYPER_value: + case TypeClass.UNSIGNED_LONG_value: + case TypeClass.UNSIGNED_SHORT_value: + case TypeClass.SHORT_value: + sVariableStemName = "n" + m_sCentralVariableStemName; + break; + case TypeClass.CHAR_value: + case TypeClass.STRING_value: + sVariableStemName = "s" + m_sCentralVariableStemName; + break; + case TypeClass.SEQUENCE_value: + //TODO consider mulitdimensional Arrays + XTypeDescription xTypeDescription = Introspector.getIntrospector().getReferencedType(getTypeName()); + if (xTypeDescription != null){ + sVariableStemName = getVariableStemName(xTypeDescription.getTypeClass()); + } + break; + case TypeClass.TYPE_value: + sVariableStemName = "a" + m_sCentralVariableStemName; + break; + case TypeClass.ANY_value: + sVariableStemName = "o" + m_sCentralVariableStemName; + break; + case TypeClass.STRUCT_value: + case TypeClass.ENUM_value: + sVariableStemName = "a" + m_sCentralVariableStemName; + break; + case TypeClass.INTERFACE_ATTRIBUTE_value: + case TypeClass.INTERFACE_METHOD_value: + case TypeClass.INTERFACE_value: + case TypeClass.PROPERTY_value: + String sShortClassName = Introspector.getShortClassName(getTypeName()); + sVariableStemName = getVariableNameforUnoObject(sShortClassName); + default: + } + return sVariableStemName; + } + + + private void setVariableName(String _sVariableName){ + sVariableName = _sVariableName; + } + + + private String getVariableName(String _sCentralVariableStemName){ + if (!_sCentralVariableStemName.equals("")){ + this.m_sCentralVariableStemName = _sCentralVariableStemName; + } + return getVariableName(); + } + + + private String getVariableName() throws NullPointerException{ + if (sVariableName.equals("")){ + int a = 2; + sVariableName = getVariableStemName(); + boolean bleaveloop = false; + while (!bleaveloop){ + if (aVariables.containsKey(sVariableName)){ + String sUnoObjectIdentity = aVariables.get(sVariableName).getUnoObject().toString(); + if (m_oUnoObject != null){ + if ((sUnoObjectIdentity.equals(m_oUnoObject.toString()) && (!Introspector.isPrimitive(this.getTypeClass())) && + (! Introspector.isObjectSequence(m_oUnoObject)))){ + bleaveloop = true; + } + else{ + sVariableName = getVariableStemName() + SSUFFIXSEPARATOR + a++; + } + } + else{ + bleaveloop = true; + } + } + else{ + bleaveloop = true; + } + } + } + return sVariableName; + } + } + + + public String getStringValueOfObject(Object _oUnoObject, TypeClass _aTypeClass){ + String sReturn = ""; + switch (_aTypeClass.getValue()){ + case TypeClass.BOOLEAN_value: + boolean bbooleanValue = ((Boolean) _oUnoObject).booleanValue(); + sReturn += Boolean.toString(bbooleanValue); + case TypeClass.CHAR_value: + break; + case TypeClass.DOUBLE_value: + double fdoubleValue = ((Double) _oUnoObject).doubleValue(); + sReturn += Double.toString(fdoubleValue); + break; + case TypeClass.ENUM_value: + break; + case TypeClass.FLOAT_value: + float floatValue = ((Float) _oUnoObject).floatValue(); + sReturn += Float.toString(floatValue); + break; + case TypeClass.HYPER_value: + long nlongValue = ((Long) _oUnoObject).longValue(); + sReturn += Long.toString(nlongValue); + break; + case TypeClass.LONG_value: + int nintValue = ((Integer) _oUnoObject).intValue(); + sReturn += Integer.toString(nintValue); + break; + case TypeClass.SHORT_value: + short nshortValue = ((Short) _oUnoObject).shortValue(); + sReturn += Short.toString(nshortValue); + break; + case TypeClass.STRING_value: + sReturn += (String) _oUnoObject; + break; + case TypeClass.UNSIGNED_HYPER_value: + nlongValue = ((Long) _oUnoObject).longValue(); + sReturn += Long.toString(nlongValue); + break; + case TypeClass.UNSIGNED_LONG_value: + nintValue = ((Integer) _oUnoObject).intValue(); + sReturn += Integer.toString(nintValue); + break; + case TypeClass.UNSIGNED_SHORT_value: + nshortValue = ((Short) _oUnoObject).shortValue(); + sReturn += Short.toString(nshortValue); + break; + default: + System.out.println("Type " + _aTypeClass.getValue() + " not yet defined in 'getStringValueOfObject()'"); + } + return sReturn; + } + + + public String getMethodParameterValueDescription(XUnoMethodNode _oUnoMethodNode, Object[] _oParamObjects, boolean _bIncludeParameterNames){ + String sParamSourceCode = ""; + ParamInfo[] aParamInfos = _oUnoMethodNode.getXIdlMethod().getParameterInfos(); + if (_oParamObjects != null){ + for (int i = 0; i < _oParamObjects.length; i++){ + TypeClass aTypeClass = aParamInfos[i].aType.getTypeClass(); + if (_bIncludeParameterNames){ + sParamSourceCode += aParamInfos[i].aName + "="; + } + String sParamDescription = getStringValueOfObject(_oParamObjects[i], aTypeClass); + sParamDescription = this.m_xLanguageSourceCodeGenerator.castLiteral(sParamDescription, aTypeClass); + sParamSourceCode += sParamDescription; + + if (i < _oParamObjects.length - 1){ + sParamSourceCode += ", "; + } + } + } + return sParamSourceCode; + } + + + private class JavaCodeGenerator implements XLanguageSourceCodeGenerator{ + + private boolean bAddAnyConverter = false; + private boolean bIsPropertyUnoObjectDefined = false; + + public JavaCodeGenerator(){ + } + + + public String getStatementTerminationCharacter(){ + return ";"; + } + + + public String getHeaderSourceCode(Object _oUnoObject, String _sClassName, TypeClass _aTypeClass){ + String sClassName = _sClassName; + String sHeaderStatement = ""; + if (_oUnoObject != null){ + if (!Introspector.isObjectPrimitive(_oUnoObject)){ + if (Introspector.isObjectSequence(_oUnoObject)){ + XTypeDescription xTypeDescription = m_oIntrospector.getReferencedType(sClassName); + if (xTypeDescription != null){ + if (!Introspector.isPrimitive(xTypeDescription.getTypeClass())){ + sClassName = getTypeString(xTypeDescription.getName(), xTypeDescription.getTypeClass(), true); + } + // primitive Types are not supposed to turn up in the import section... + else{ + sClassName = ""; + } + } + } + else{ + sClassName = getTypeString(_sClassName, _aTypeClass, true); + } + } + else if (_aTypeClass.getValue() == TypeClass.ENUM_value){ + sClassName = _sClassName; + } + else{ + sClassName = ""; + } + if (!sClassName.equals("")){ + sHeaderStatement = "import " + sClassName + ";\n"; + } + } + return sHeaderStatement; + } + + + public String getFinalHeaderStatements(){ + return ""; + } + + + public void assignqueryInterfaceHeaderSourceCode(){ + sHeaderStatements.add("import com.sun.star.uno.UnoRuntime;\n"); + sHeaderStatements.add("import com.sun.star.uno.XInterface;\n"); + if (bAddAnyConverter){ + sHeaderStatements.add("import com.sun.star.uno.AnyConverter;\n"); + } + } + + + + public String getConvertedSourceCodeValueOfObject(String _sReturnVariableName, String _sObjectDescription, TypeClass _aTypeClass, String _sTypeName){ + boolean bLocAddAnyConverter = true; + String sReturn = ""; + switch (_aTypeClass.getValue()){ + case TypeClass.BOOLEAN_value: + sReturn = _sReturnVariableName + " = AnyConverter.toBoolean(" + _sObjectDescription + ")"; + break; + case TypeClass.CHAR_value: + sReturn = _sReturnVariableName + " = AnyConverter.toChar(" + _sObjectDescription + ")"; + break; + case TypeClass.BYTE_value: + sReturn = _sReturnVariableName + " = AnyConverter.toByte(" + _sObjectDescription + ")"; + break; + case TypeClass.DOUBLE_value: + sReturn = _sReturnVariableName + " = AnyConverter.toDouble(" + _sObjectDescription + ")"; + break; + case TypeClass.FLOAT_value: + sReturn = _sReturnVariableName + " = AnyConverter.toFloat(" + _sObjectDescription + ")"; + break; + case TypeClass.UNSIGNED_HYPER_value: + sReturn = _sReturnVariableName + " = AnyConverter.toUnsignedLong(" + _sObjectDescription + ")"; + break; + case TypeClass.HYPER_value: + sReturn = _sReturnVariableName + " = AnyConverter.toLong(" + _sObjectDescription + ")"; + break; + case TypeClass.UNSIGNED_LONG_value: + sReturn = _sReturnVariableName + " = AnyConverter.toUnsignedInt(" + _sObjectDescription + ")"; + break; + case TypeClass.LONG_value: + sReturn = _sReturnVariableName + " = AnyConverter.toInt(" + _sObjectDescription + ")"; + break; + case TypeClass.SHORT_value: + sReturn = _sReturnVariableName + " = AnyConverter.toShort(" + _sObjectDescription + ")"; + break; + case TypeClass.UNSIGNED_SHORT_value: + sReturn = _sReturnVariableName + " = AnyConverter.toUnsignedShort(" + _sObjectDescription + ")"; + break; + case TypeClass.STRING_value: + sReturn = _sReturnVariableName + " = AnyConverter.toString(" + _sObjectDescription + ")"; + break; + default: + String sShortTypeName = Introspector.getShortClassName(_sTypeName); + if (bIsPropertyUnoObjectDefined){ + sReturn = "oUnoObject = " + _sObjectDescription + ";\n\t"; + } + else{ + sReturn = "Object oUnoObject = " + _sObjectDescription + ";\n\t"; + bIsPropertyUnoObjectDefined = true; + } + sReturn += _sReturnVariableName + " = (" + sShortTypeName + ") AnyConverter.toObject(" + sShortTypeName + ".class, oUnoObject);"; + break; + } + if (!bAddAnyConverter){ + bAddAnyConverter = bLocAddAnyConverter; + } + return sReturn; + } + + + public String getStructSourceCode(String _sReturnVariableDescription, String _sObjectDescription, String _sMember){ + return "\t" + _sReturnVariableDescription + " = " + _sObjectDescription + "." + _sMember + ";"; + } + + public String getMainMethodSignatureSourceCode(XUnoNode _oUnoNode, String _soReturnObjectDescription){ + //TODO try to use + _oUnoNode.getClassName() instead of the hack + String sReturn = "public void codesnippet(XInterface " + _soReturnObjectDescription + "){"; + if (baddExceptionHandling){ + sReturn += "\ntry{"; + } + return sReturn; + } + + public String getMethodSeparator(){ + return "."; + } + + public boolean needsqueryInterface(){ + return true; + } + + public String getqueryInterfaceSourceCode(String _sClassName, String _sReturnVariableName, String _sIncomingObjectName){ + String sShortClassName = Introspector.getShortClassName(_sClassName); + return "\t" + _sReturnVariableName + " = (" + sShortClassName + ") UnoRuntime.queryInterface(" + sShortClassName + ".class, " + _sIncomingObjectName + ");\n"; + } + + + public String getPropertyValueGetterSourceCode(String _sPropertyName, String _sReturnVariableName, String _sIncomingObjectName, TypeClass _aTypeClass, String _sTypeName){ + String sObjectDescription = _sIncomingObjectName + ".getPropertyValue(\"" + _sPropertyName + "\")"; + String sReturn = getConvertedSourceCodeValueOfObject(_sReturnVariableName, sObjectDescription, _aTypeClass, _sTypeName); + sReturn += ";"; + sReturn = "\t" + sReturn; + return sReturn; + } + + + public String getObjectTypeDescription(String _sClassName, boolean _bAsHeader){ + String sReturn = ""; + if (_bAsHeader){ + sReturn = _sClassName; + } + else{ + sReturn = Introspector.getShortClassName(_sClassName); + } + return sReturn; + } + + + public String getMethodTerminationSourceCode(){ + String sReturn = ""; + int nIndex = 1; + String sExceptionName = "e"; + if (baddExceptionHandling){ + for (int i = 0; i < sExceptions.size(); i++){ + String sCurException = sExceptions.get(i); + if (sReturn.indexOf(sCurException) == -1){ + if (nIndex > 1){ + sExceptionName = "e"+ nIndex; + } + else{ + sReturn +="\n}"; + } + sReturn += "catch (" + sCurException + " " + sExceptionName + "){\n"; + sReturn += "\t" + sExceptionName + ".printStackTrace(System.err);\n"; + sReturn += "\t" + getCommentSign() + "Enter your Code here...\n}"; + nIndex++; + } + } + } + sReturn += "\n}"; + return sReturn; + } + + public String castLiteral(String _sExpression, TypeClass _aTypeClass){ + String sReturn = ""; + switch (_aTypeClass.getValue()){ + case TypeClass.BOOLEAN_value: + sReturn = _sExpression; + break; + case TypeClass.BYTE_value: + sReturn = "(byte) " + _sExpression; + break; + case TypeClass.CHAR_value: + sReturn = "'" + _sExpression + "'"; + break; + case TypeClass.DOUBLE_value: + sReturn = "(double) " + _sExpression; + break; + case TypeClass.FLOAT_value: + sReturn = "(float) " + _sExpression; + break; + case TypeClass.UNSIGNED_SHORT_value: + case TypeClass.SHORT_value: + sReturn = "(short) " + _sExpression; + break; + case TypeClass.STRING_value: + sReturn = "\"" + _sExpression + "\""; + break; + case TypeClass.HYPER_value: + case TypeClass.UNSIGNED_HYPER_value: + sReturn = "(long) " + _sExpression; + break; + case TypeClass.LONG_value: + sReturn = _sExpression; + break; + case TypeClass.ENUM_value: + default: + sReturn = _sExpression; + System.out.println("Type " + _aTypeClass.getValue() + " not yet defined in 'castliteral()'"); + } + return sReturn; + } + + + public String getbooleanTypeDescription(){ + return "boolean"; + } + + public String getbyteTypeDescription(){ + return "byte"; + } + + public String getshortTypeDescription(){ + return "short"; + } + + public String getlongTypeDescription(){ + return "int"; + } + + public String getunsignedlongTypeDescription(){ + return "int"; + } + + public String gethyperTypeDescription(){ + return "long"; + } + + public String getunsignedhyperTypeDescription(){ + return "long"; + } + + public String getfloatTypeDescription(){ + return "float"; + } + + public String getdoubleTypeDescription(){ + return "double"; + } + + public String getcharTypeDescription(){ + return "char"; + } + + public String getstringTypeDescription(boolean _bAsHeaderSourceCode){ + if (_bAsHeaderSourceCode){ + return ""; + } + else{ + return "String"; + } + } + + public String getanyTypeDescription(boolean _bAsHeaderSourceCode){ + if (_bAsHeaderSourceCode){ + return ""; + } + else{ + return "Object"; + } + } + + + public String getStringValue(String _sValue){ + return _sValue; + } + + + public String getVariableDeclaration(String _sTypeString, String _sVariableName, boolean _bIsArray, TypeClass _aTypeClass, boolean _bInitialize){ + String sReturn = ""; + if (_bIsArray){ + sReturn = _sTypeString + "[] " + _sVariableName; + } + else{ + sReturn = _sTypeString + " " + _sVariableName; + } + return sReturn; + } + + + public String getCommentSign(){ + return "//"; + } + } + + + private class BasicCodeGenerator implements XLanguageSourceCodeGenerator{ + + + public BasicCodeGenerator(){ + } + + public String getHeaderSourceCode(Object _oUnoObject, String _sClassName, TypeClass _aTypeClass){ + String sHeaderStatement = ""; + return sHeaderStatement; + } + + public String getFinalHeaderStatements(){ + return ""; + } + + public String getMainMethodSignatureSourceCode(XUnoNode _oUnoNode, String _soReturnObjectDescription){ + //TODO try to use + _oUnoNode.getClassName() instead of the hack + return "Sub Main(" + _soReturnObjectDescription + " as " + getanyTypeDescription(false) + ")"; + } + + public boolean needsqueryInterface(){ + return false; + } + + public void assignqueryInterfaceHeaderSourceCode(){ + } + + public String getMethodSeparator(){ + return "."; + } + + + public String getqueryInterfaceSourceCode(String _sClassName, String _sReturnVariableName, String _sIncomingObjectName){ + return _sIncomingObjectName; + } + + + public String getPropertyValueGetterSourceCode(String _sPropertyName, String _sReturnVariableName, String _sIncomingObjectName, TypeClass _aTypeClass, String _sTypeName){ + return "\t" + _sReturnVariableName + " = " + _sIncomingObjectName + "." + _sPropertyName; + } + + + public String getStructSourceCode(String _sReturnVariableDescription, String _sObjectDescription, String _sMember){ + return getPropertyValueGetterSourceCode(_sMember, _sReturnVariableDescription, _sObjectDescription, null, "" ); + } + + public String getConvertedSourceCodeValueOfObject(String _sReturnVariableName, String _sObjectDescription, TypeClass _aTypeClass, String _sTypeName){ + return _sReturnVariableName + " = " + _sObjectDescription; + } + + + public String getObjectTypeDescription(String _sClassName, boolean _bAsHeader){ + return "Object"; + } + + + public String getMethodTerminationSourceCode(){ + return "\nEnd Sub\n"; + } + + + public String castLiteral(String _sExpression, TypeClass _aTypeClass){ + String sReturn = ""; + switch (_aTypeClass.getValue()){ + case TypeClass.BOOLEAN_value: + case TypeClass.BYTE_value: + case TypeClass.DOUBLE_value: + case TypeClass.FLOAT_value: + case TypeClass.UNSIGNED_SHORT_value: + case TypeClass.SHORT_value: + case TypeClass.LONG_value: + case TypeClass.UNSIGNED_LONG_value: + case TypeClass.HYPER_value: + case TypeClass.UNSIGNED_HYPER_value: + sReturn = _sExpression; + break; + case TypeClass.CHAR_value: + case TypeClass.STRING_value: + sReturn = "\"" +_sExpression + "\""; + break; + case TypeClass.ENUM_value: + default: + sReturn = _sExpression; + System.out.println("Type " + _aTypeClass.getValue() + " not yet defined in 'castliteral()'"); + } + return sReturn; + } + + + + public String getbooleanTypeDescription(){ + return "Boolean"; + } + + public String getbyteTypeDescription(){ + return "Integer"; + } + + public String getshortTypeDescription(){ + return "Integer"; + } + + public String getlongTypeDescription(){ + return "Integer"; + } + + public String getunsignedlongTypeDescription(){ + return "Long"; + } + + public String gethyperTypeDescription(){ + return "Long"; + } + + public String getunsignedhyperTypeDescription(){ + return "Long"; + } + + public String getfloatTypeDescription(){ + return "Double"; + } + + public String getdoubleTypeDescription(){ + return "Double"; + } + + public String getcharTypeDescription(){ + return "String"; + } + + public String getstringTypeDescription(boolean _bAsHeaderSourceCode){ + if (_bAsHeaderSourceCode){ + return ""; + } + else{ + return "String"; + } + } + + public String getanyTypeDescription(boolean _bAsHeaderSourceCode){ + if (_bAsHeaderSourceCode){ + return ""; + } + else{ + return "Object"; + } + } + + public String getStatementTerminationCharacter(){ + return ""; + } + + + public String getVariableDeclaration(String _sTypeString, String _sVariableName, boolean bIsArray, TypeClass _aTypeClass, boolean _bInitialize){ + String sReturn = ""; + if (bIsArray){ + sReturn = "Dim " + _sVariableName + "() as " + _sTypeString + "\n\t" + _sVariableName; + } + else{ + sReturn = "Dim " + _sVariableName + " as " + _sTypeString + "\n\t" + _sVariableName; + } + return sReturn; + } + + + public String getStringValue(String _sValue){ + return _sValue; + } + + + public String getCommentSign(){ + return "'"; + } + + } + + private class CPlusPlusCodeGenerator implements XLanguageSourceCodeGenerator{ + + private boolean bIncludeStringHeader = false; + private boolean bIncludeAny = false; + private boolean bIncludeSequenceHeader = false; + + public CPlusPlusCodeGenerator(){ + } + + private String getCSSNameSpaceString(){ + return "css"; + } + + public String getStatementTerminationCharacter(){ + return ";"; + } + + + public String getHeaderSourceCode(Object _oUnoObject, String _sClassName, TypeClass _aTypeClass){ + String sClassName = _sClassName; + String sHeaderStatement = ""; + if (_oUnoObject != null){ + if (!Introspector.isObjectPrimitive(_oUnoObject)){ + if (Introspector.isObjectSequence(_oUnoObject)){ + XTypeDescription xTypeDescription = m_oIntrospector.getReferencedType(sClassName); + if (xTypeDescription != null){ + if (!Introspector.isPrimitive(xTypeDescription.getTypeClass())){ + sClassName = getTypeString(xTypeDescription.getName(), xTypeDescription.getTypeClass(), true); + } + // primitive Types are not supposed to turn up in the import section... + else{ + sClassName = ""; + } + } + } + else{ + sClassName = getTypeString(_sClassName, _aTypeClass, true); + } + if (!sClassName.equals("")){ + sHeaderStatement = getHeaderOfClass(sClassName); + } + } + } + return sHeaderStatement; + } + + + + public String getFinalHeaderStatements(){ + String sReturn = ""; + sReturn += "\nnamespace " + getCSSNameSpaceString() + " = com::sun::star;\n"; + sReturn += "using ::rtl::OUString;\n"; + return sReturn; + } + + + private String getHeaderOfClass(String _sClassName){ + return "#include \"" + _sClassName.replace('.', '/') + ".hpp\"\n"; + } + + + + public void assignqueryInterfaceHeaderSourceCode(){ + sHeaderStatements.add("#include \"sal/config.h\"\n"); + sHeaderStatements.add("#include \"sal/types.h\"\n"); + if (bIncludeStringHeader){ + sHeaderStatements.add("#include \"rtl/ustring.hxx\"\n"); + } + sHeaderStatements.add("#include \"com/sun/star/uno/Reference.hxx\"\n"); + if (bIncludeSequenceHeader){ + sHeaderStatements.add("#include \"com/sun/star/uno/Sequence.hxx\"\n"); + } + sHeaderStatements.add(getHeaderOfClass("com.sun.star.uno.XInterface")); + if (bIncludeAny){ + sHeaderStatements.add(getHeaderOfClass("com.sun.star.uno.Any")); + } + } + + + public String getMainMethodSignatureSourceCode(XUnoNode _oUnoNode, String _soReturnObjectDescription){ + String sReturn = ""; + sReturn = "void codesnippet(const " + getCSSNameSpaceString() + "::uno::Reference<" + getCSSNameSpaceString() + "::uno::XInterface>& " + _soReturnObjectDescription + " ){"; + int a = 0; + if (!sExceptions.contains("com.sun.star.uno.RuntimeException")){ + sExceptions.add("com.sun.star.uno.RuntimeException"); + } + if (baddExceptionHandling){ + sReturn += "\n//throw "; + for (int i = 0; i < sExceptions.size(); i++){ + String sCurException = sExceptions.get(i); + if (sReturn.indexOf(sCurException) == -1){ + if (a++ > 0){ + sReturn += ", "; + } + sReturn += getObjectTypeDescription(sCurException, false); + + } + } + + } + sReturn += "{"; + return sReturn; + } + + + public boolean needsqueryInterface(){ + return true; + } + + + public String getqueryInterfaceSourceCode(String _sClassName, String _sReturnVariableName, String _sIncomingObjectName){ + return "\t" + _sReturnVariableName + "( " + _sIncomingObjectName + ", " + getCSSNameSpaceString() + "::uno::UNO_QUERY_THROW);\n"; + } + + + public String getPropertyValueGetterSourceCode(String _sPropertyName, String _sReturnVariableName, String _sIncomingObjectName, TypeClass _aTypeClass, String _sTypeName){ + String sFirstLine = "\t"; + String sReturnVariableName = _sReturnVariableName; + // e.g. uno::Any a = xPropSet->getPropertyValue( rtl::OUString( "DefaultContext" ) ); + String[] sVarDefinition = _sReturnVariableName.split("="); + if (sVarDefinition.length > 0){ + String sVariable = sVarDefinition[0]; + String[] sVarDeclaration = sVariable.split(" "); + if (sVarDeclaration.length > 0){ + sFirstLine += sReturnVariableName + ";\n"; + sReturnVariableName = sVarDeclaration[sVarDeclaration.length-1]; + } + } + String sObjectDescription = _sIncomingObjectName + "->getPropertyValue(" + getStringValue(_sPropertyName) + ")"; + String sSecondLine = "\t" + getConvertedSourceCodeValueOfObject(sReturnVariableName, sObjectDescription, _aTypeClass, _sTypeName) + ";"; + return sFirstLine + sSecondLine; + } + + + public String getStructSourceCode(String _sReturnVariableDescription, String _sObjectDescription, String _sMember){ + return "\t" + _sReturnVariableDescription + " = " + _sObjectDescription + "->" + _sMember + ";"; + } + + + public String getConvertedSourceCodeValueOfObject(String _sReturnVariableName, String _sObjectDescription, TypeClass _aTypeClass, String _sTypeName){ + return _sObjectDescription + " >>= " + _sReturnVariableName; + } + + + public String getStringValue(String _sValue){ + bIncludeStringHeader = true; + return "OUString(\"" + _sValue + "\")"; + } + + + public String getObjectTypeDescription(String _sClassName, boolean _bAsHeader){ + String sReturn = ""; + if (_bAsHeader){ + sReturn = _sClassName.replace('.', '/'); + } + else{ + String sModuleName = Introspector.getModuleName(_sClassName); + sModuleName = Introspector.getShortClassName(sModuleName); + sReturn = getCSSNameSpaceString() + "::" + sModuleName + "::" + Introspector.getShortClassName(_sClassName); + } + return sReturn; + } + + + public String getMethodTerminationSourceCode(){ + return "\n}"; + } + + public String getMethodSeparator(){ + return "->"; + } + + + public String castLiteral(String _sExpression, TypeClass _aTypeClass){ + String sReturn = ""; + switch (_aTypeClass.getValue()){ + case TypeClass.BOOLEAN_value: + case TypeClass.BYTE_value: + case TypeClass.DOUBLE_value: + case TypeClass.FLOAT_value: + case TypeClass.UNSIGNED_SHORT_value: + case TypeClass.SHORT_value: + case TypeClass.LONG_value: + case TypeClass.UNSIGNED_LONG_value: + case TypeClass.HYPER_value: + case TypeClass.UNSIGNED_HYPER_value: + sReturn = _sExpression; + break; + case TypeClass.CHAR_value: + sReturn = "'" + _sExpression + "'"; + break; + case TypeClass.STRING_value: + sReturn = getStringValue(_sExpression); + break; + case TypeClass.ENUM_value: + default: + sReturn = _sExpression; + System.out.println("Type " + _aTypeClass.getValue() + " not yet defined in 'castliteral()'"); + } + return sReturn; + } + + public String getbooleanTypeDescription(){ + return "sal_Bool"; + } + + public String getbyteTypeDescription(){ + return "sal_Int8"; + } + + public String getshortTypeDescription(){ + return "sal_Int16"; + } + + public String getlongTypeDescription(){ + return "sal_Int32"; + } + + public String getunsignedlongTypeDescription(){ + return "sal_uInt32"; + } + + public String gethyperTypeDescription(){ + return "sal_Int64"; + } + + public String getunsignedhyperTypeDescription(){ + return "sal_uInt64"; + } + + public String getfloatTypeDescription(){ + return "float"; + } + + public String getdoubleTypeDescription(){ + return "double"; + } + + public String getcharTypeDescription(){ + return "sal_Unicode"; + } + + public String getstringTypeDescription(boolean _bAsHeaderSourceCode){ + bIncludeStringHeader = true; + if (_bAsHeaderSourceCode){ + return ""; + } + else{ + return "OUString"; + } + } + + public String getanyTypeDescription(boolean _bAsHeaderSourceCode){ + if (_bAsHeaderSourceCode){ + return "com/sun/star/uno/XInterface"; + } + else{ + return "XInterface"; + } + } + + + public String getVariableDeclaration(String _sTypeString, String _sVariableName, boolean bIsArray, TypeClass _aTypeClass, boolean _bInitialize){ + boolean bIsPrimitive = Introspector.isPrimitive(_aTypeClass); + + String sReturn = ""; + if (bIsArray){ + bIncludeSequenceHeader = true; + sReturn = getCSSNameSpaceString() + "::uno::Sequence<" + _sTypeString + "> " + _sVariableName; + } + else{ + if (bIsPrimitive){ + sReturn = _sTypeString + " " + _sVariableName; + if (_bInitialize){ + switch (_aTypeClass.getValue()){ + case TypeClass.BOOLEAN_value: + sReturn = sReturn + " = false"; + break; + case TypeClass.BYTE_value: + case TypeClass.UNSIGNED_SHORT_value: + case TypeClass.SHORT_value: + case TypeClass.LONG_value: + case TypeClass.UNSIGNED_LONG_value: + case TypeClass.HYPER_value: + case TypeClass.UNSIGNED_HYPER_value: + sReturn = sReturn + " = 0"; + break; + case TypeClass.DOUBLE_value: + case TypeClass.FLOAT_value: + sReturn = sReturn + " = 0.0"; + break; + case TypeClass.CHAR_value: + sReturn = sReturn + "'0'"; + break; + case TypeClass.STRING_value: + sReturn = _sTypeString + " " + _sVariableName; + break; + default: + sReturn = _sTypeString + " " + _sVariableName; + System.out.println("Type " + _aTypeClass.getValue() + " not yet defined in 'getVariableDeclaration()'"); + } + } + } + else{ + sReturn = getCSSNameSpaceString() + "::uno::Reference<" + _sTypeString + "> " +_sVariableName; + } + } + return sReturn; + } + + public String getCommentSign(){ + return "//"; + } + + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/SwingDialogProvider.java b/odk/examples/java/Inspector/SwingDialogProvider.java new file mode 100644 index 000000000..e66bedce8 --- /dev/null +++ b/odk/examples/java/Inspector/SwingDialogProvider.java @@ -0,0 +1,444 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.XComponentContext; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.event.ActionListener; +import java.awt.event.ComponentAdapter; +import java.awt.event.ComponentEvent; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import javax.swing.ButtonGroup; +import javax.swing.JDialog; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.JRadioButtonMenuItem; +import javax.swing.JTabbedPane; +import javax.swing.KeyStroke; + + + +public class SwingDialogProvider implements XDialogProvider{ + + private JPopupMenu m_jPopupMenu = new JPopupMenu(); + private XComponentContext m_xComponentContext; + private Inspector._Inspector m_oInspector; + private JDialog m_jInspectorDialog = new JDialog(); + private JTabbedPane m_jTabbedPane1 = new JTabbedPane(); + private Container cp; + + private JMenu jMnuOptions = new JMenu("Options"); + private JRadioButtonMenuItem jJavaMenuItem = null; + private JRadioButtonMenuItem jCPlusPlusMenuItem = null; + private JRadioButtonMenuItem jBasicMenuItem = null; + + /** Creates a new instance of SwingPopupMentuProvider */ + public SwingDialogProvider(Inspector._Inspector _oInspector, String _sTitle) { + m_oInspector = _oInspector; + m_xComponentContext = _oInspector.getXComponentContext(); + insertMenus(); + initializePopupMenu(); + cp = m_jInspectorDialog.getContentPane(); + cp.setLayout(new java.awt.BorderLayout(0, 10)); + m_jTabbedPane1.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); + m_jInspectorDialog.addWindowListener(new InspectorWindowAdapter()); + m_jInspectorDialog.addComponentListener(new InspectorComponentAdapter()); + m_jInspectorDialog.setTitle(_sTitle); + m_jInspectorDialog.setLocation(100, 50); + m_jInspectorDialog.getContentPane().add(m_jTabbedPane1); + } + + + + public JDialog getDialog(){ + return m_jInspectorDialog; + } + + + private void addMenuBar(JMenuBar _jMenuBar){ + getDialog().setJMenuBar(_jMenuBar); + } + + + private void removeTabPaneByIndex(int _nIndex){ + if (_nIndex > -1){ + String sSelInspectorPanelTitle = m_jTabbedPane1.getTitleAt(_nIndex); + m_jTabbedPane1.remove(_nIndex); + m_oInspector.getInspectorPages().remove(sSelInspectorPanelTitle); + } + } + + + public void selectInspectorPageByIndex(int nTabIndex){ + m_jTabbedPane1.setSelectedIndex(nTabIndex); + } + + + public int getInspectorPageCount(){ + return m_jTabbedPane1.getTabCount(); + } + + + public JTabbedPane getTabbedPane(){ + return m_jTabbedPane1; + } + + + public InspectorPane getSelectedInspectorPage(){ + int nIndex = m_jTabbedPane1.getSelectedIndex(); + return getInspectorPage(nIndex); + } + + + public InspectorPane getInspectorPage(int _nIndex){ + InspectorPane oInspectorPane = null; + if (_nIndex > -1){ + String sInspectorPanelTitle = m_jTabbedPane1.getTitleAt(_nIndex); + oInspectorPane = m_oInspector.getInspectorPages().get(sInspectorPanelTitle); + } + return oInspectorPane; + } + + + private void removeTabPanes(){ + int nCount = m_jTabbedPane1.getTabCount(); + if (nCount > 0){ + for (int i = nCount-1; i >= 0; i--){ + removeTabPaneByIndex(i); + } + } + } + + private void removeSelectedTabPane(){ + int nIndex = getTabbedPane().getSelectedIndex(); + removeTabPaneByIndex(nIndex); + } + + + private class InspectorComponentAdapter extends ComponentAdapter{ + @Override + public void componentHidden(ComponentEvent e){ + m_jInspectorDialog.pack(); + m_jInspectorDialog.invalidate(); + + } + + @Override + public void componentShown(ComponentEvent e){ + m_jInspectorDialog.pack(); + m_jInspectorDialog.invalidate(); + } + } + + private class InspectorWindowAdapter extends WindowAdapter{ + @Override + public void windowClosed(WindowEvent e){ + removeTabPanes(); + m_oInspector.disposeHiddenDocuments(); + } + + @Override + public void windowClosing(WindowEvent e){ + removeTabPanes(); + m_oInspector.disposeHiddenDocuments(); + } + } + + + + private void initializePopupMenu(){ + m_jPopupMenu.add(getInspectMenuItem("Inspect")); + m_jPopupMenu.add(getSourceCodeMenuItem(SADDTOSOURCECODE)); + m_jPopupMenu.add(getInvokeMenuItem(SINVOKE)); + m_jPopupMenu.addSeparator(); + m_jPopupMenu.add(getHelpMenuItem("Help")); + } + + + private void addOpenDocumentMenu(JMenu _jMnuRoot){ + ActionListener oActionListener = new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + String sTDocUrl = evt.getActionCommand(); + m_oInspector.inspectOpenDocument(sTDocUrl); + } + }; + String[] sTDocUrls = m_oInspector.getTDocUrls(); + String[] sTDocTitles = m_oInspector.getTDocTitles(sTDocUrls); + for (int i = 0; i < sTDocUrls.length; i++){ + addSingleMenuItem(_jMnuRoot, sTDocTitles[i], sTDocUrls[i], oActionListener); + } + } + + + private void addApplicationDocumentMenu(JMenu _jMnuRoot){ + ActionListener oActionListener = new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + String sApplicationDocUrl = evt.getActionCommand(); + m_oInspector.inspectOpenEmptyDocument(sApplicationDocUrl); + } + }; + String[][] sApplUrls = m_oInspector.getApplicationUrls(); + for (int i = 0; i < sApplUrls.length; i++){ + addSingleMenuItem(_jMnuRoot, sApplUrls[i][1], sApplUrls[i][0], oActionListener); + } + } + + + private void addSingleMenuItem(JMenu _jMnuOpenDocs, String _sTitle, String _sActionCommand, ActionListener _oActionListener){ + javax.swing.JMenuItem jMnuItemOpenDoc = new javax.swing.JMenuItem(_sTitle); + jMnuItemOpenDoc.setActionCommand(_sActionCommand); + jMnuItemOpenDoc.addActionListener(_oActionListener); + _jMnuOpenDocs.add(jMnuItemOpenDoc); + } + + + private void addHelpMenu(JMenuBar _jInspectMenuBar){ + JMenu jMnuHelp = new JMenu("Help"); + jMnuHelp.add(getHelpMenuItem("Idl-Help")); + _jInspectMenuBar.add(jMnuHelp); + } + + + private JMenuItem getHelpMenuItem(String _sMenuTitle){ + JMenuItem jMnuHelpItem = new JMenuItem(_sMenuTitle); + jMnuHelpItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0)); + jMnuHelpItem.setMnemonic('H'); + jMnuHelpItem.addActionListener(new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + m_oInspector.openIdlFileforSelectedNode(); + } + }); + return jMnuHelpItem; + } + + private void addFileMenu(JMenuBar _jInspectMenuBar){ + JMenu jMnuFile = new JMenu("File"); + JMenuItem jMnuItemRemoveInspector = new JMenuItem("Remove"); + jMnuItemRemoveInspector.addActionListener(new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + removeSelectedTabPane(); + } + }); + jMnuFile.add(jMnuItemRemoveInspector); + JMenuItem jMnuItemExit = new JMenuItem("Exit"); + jMnuItemExit.addActionListener(new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + getDialog().dispose(); + } + }); + jMnuFile.add(jMnuItemExit); + _jInspectMenuBar.add(jMnuFile); + } + + private JMenuItem getInspectMenuItem(String _sLabel){ + JMenuItem jMnuSelectedObject = new JMenuItem(_sLabel); + jMnuSelectedObject.addActionListener(new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + m_oInspector.inspectSelectedNode(); + } + }); + return jMnuSelectedObject; + } + + + private JMenuItem getSourceCodeMenuItem(String _sLabel){ + JMenuItem jMnuSelectedObject = new JMenuItem(_sLabel); + jMnuSelectedObject.addActionListener(new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + m_oInspector.addSourceCodeOfSelectedNode(); + } + }); + return jMnuSelectedObject; + } + + private JMenuItem getInvokeMenuItem(String _sLabel){ + JMenuItem jMnuSelectedObject = new JMenuItem(_sLabel); + jMnuSelectedObject.addActionListener(new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + m_oInspector.invokeSelectedMethod(); + } + }); + return jMnuSelectedObject; + } + + + private void addInspectMenu(JMenuBar _jInspectMenuBar){ + JMenu jMnuInspect = new JMenu("Inspect"); + addApplicationDocumentMenu(jMnuInspect); + jMnuInspect.addSeparator(); + addGlobalServiceManagerMenu(jMnuInspect); + jMnuInspect.addSeparator(); + jMnuInspect.add(getInspectMenuItem("Selected Object")); + jMnuInspect.addSeparator(); + addOpenDocumentMenu(jMnuInspect); + _jInspectMenuBar.add(jMnuInspect); + } + + public int getLanguage(){ + return XLanguageSourceCodeGenerator.nJAVA; + } + + + public void selectSourceCodeLanguage(int _nLanguage){ + switch (_nLanguage){ + case XLanguageSourceCodeGenerator.nJAVA: + jJavaMenuItem.setSelected(true); + break; + case XLanguageSourceCodeGenerator.nCPLUSPLUS: + jCPlusPlusMenuItem.setSelected(true); + break; + case XLanguageSourceCodeGenerator.nBASIC: + jBasicMenuItem.setSelected(true); + break; + default: + System.out.println("Warning: Sourcecode language is not defined!"); + } + } + + private JRadioButtonMenuItem addLanguageMenuItem(ButtonGroup _group, String _sLanguageTitle, boolean _bSelect, char _sMnemonic, final int _nLanguage){ + JRadioButtonMenuItem jMenuItem = new JRadioButtonMenuItem(_sLanguageTitle, _bSelect); + jMenuItem.setMnemonic(_sMnemonic); + _group.add(jMenuItem); + jMenuItem.addActionListener(new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + m_oInspector.setSourceCodeLanguage(_nLanguage); + } + }); + return jMenuItem; + } + + + public String getIDLPath(){ + return this.m_oInspector.getIDLPath(); + } + + private void addOptionsMenu(JMenuBar _jInspectMenuBar){ + ButtonGroup oButtonGroup = new ButtonGroup(); + jJavaMenuItem = addLanguageMenuItem(oButtonGroup, "Generate Java Sourcecode", true, 'J', XLanguageSourceCodeGenerator.nJAVA); + jMnuOptions.add(jJavaMenuItem); + jCPlusPlusMenuItem = addLanguageMenuItem(oButtonGroup, "Generate C++ Sourcecode", false, 'C', XLanguageSourceCodeGenerator.nCPLUSPLUS); + jMnuOptions.add(jCPlusPlusMenuItem); + jBasicMenuItem = addLanguageMenuItem(oButtonGroup, "Generate OpenOffice.org Basic Sourcecode", false, 'B', XLanguageSourceCodeGenerator.nBASIC); + jMnuOptions.add(jBasicMenuItem); + jMnuOptions.addSeparator(); + JMenuItem jMenuItem = new JMenuItem("Path to SDK-Installation"); + jMenuItem.setMnemonic('I'); + jMenuItem.addActionListener(new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + m_oInspector.assignSDKPath(); + } + }); + + jMnuOptions.add(jMenuItem); + _jInspectMenuBar.add(jMnuOptions); + } + + + private void insertMenus(){ + JMenuBar jMenuBar1 = new javax.swing.JMenuBar(); + addFileMenu(jMenuBar1); + addInspectMenu(jMenuBar1); + JMenu jMnuEdit = new JMenu("Edit"); + JMenu jMnuView = new JMenu("View"); + addOptionsMenu(jMenuBar1); + jMenuBar1.setFont(new java.awt.Font("Dialog", 0, 12)); + jMenuBar1.add(jMnuEdit); + jMenuBar1.add(jMnuView); + addHelpMenu(jMenuBar1); + addMenuBar(jMenuBar1); + } + + private void addGlobalServiceManagerMenu(JMenu _jMnuRoot){ + JMenuItem jMnuGlobalServiceManager = new JMenuItem("Global Service Manager"); + jMnuGlobalServiceManager.addActionListener(new ActionListener(){ + public void actionPerformed(java.awt.event.ActionEvent evt) { + m_oInspector.inspect(m_xComponentContext.getServiceManager(), "Global ServiceManager"); + } + }); + _jMnuRoot.add(jMnuGlobalServiceManager); + } + + + + public void enablePopupMenuItem(String _sMenuTitle, boolean _bdoEnable){ + Component[] oComponents = m_jPopupMenu.getComponents(); + for (int i = 0; i < oComponents.length; i++){ + if (oComponents[i] instanceof JMenuItem){ + JMenuItem jMenuItem = (JMenuItem) oComponents[i]; + if (jMenuItem.getText().equals(_sMenuTitle)){ + jMenuItem.setEnabled(_bdoEnable); + } + } + } + } + + + public void showPopUpMenu(Object _invoker, int x, int y) throws ClassCastException{ + if (_invoker instanceof Component){ + m_jPopupMenu.show((Component) _invoker, x, y); + } + } + + + public void show(int _nPageIndex){ + Dimension aDimension = m_jInspectorDialog.getSize(); + selectInspectorPageByIndex(_nPageIndex); + if (_nPageIndex > 0){ + m_jInspectorDialog.setSize(aDimension); + } + else{ + m_jInspectorDialog.pack(); + } + m_jInspectorDialog.setVisible(true); + } + + public void paint(){ + m_jTabbedPane1.paintImmediately(m_jTabbedPane1.getBounds()); + } + + + public void addInspectorPage(String _sTitle, Object _oContainer) throws ClassCastException{ + if (_oContainer instanceof Component){ + m_jTabbedPane1.addTab(_sTitle, (Component) _oContainer); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/SwingTreeControlProvider.java b/odk/examples/java/Inspector/SwingTreeControlProvider.java new file mode 100644 index 000000000..c8cbb4dcb --- /dev/null +++ b/odk/examples/java/Inspector/SwingTreeControlProvider.java @@ -0,0 +1,423 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; +import com.sun.star.lang.NullPointerException; +import com.sun.star.reflection.XConstantTypeDescription; +import com.sun.star.reflection.XIdlMethod; +import com.sun.star.uno.Type; +import java.awt.BorderLayout; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.swing.JPanel; +import javax.swing.JScrollBar; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.event.TreeWillExpandListener; +import javax.swing.tree.DefaultTreeSelectionModel; +import javax.swing.tree.ExpandVetoException; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; + + + +public class SwingTreeControlProvider implements XTreeControlProvider{ + private JTextArea jtxtGeneratedSourceCode = new JTextArea(); + private JTextField jtxtFilter = new JTextField(); + private javax.swing.JLabel jlblFilter = new javax.swing.JLabel("Set a filter"); + private JTree jTree = new javax.swing.JTree(); + private XDialogProvider m_xDialogProvider; + private HideableTreeModel treeModel; + private InspectorPane m_oInspectorPane; + private Object oUserDefinedObject = null; + private boolean bIsUserDefined = false; + private SwingUnoNode oRootNode; + + private final int nDIALOGWIDTH = 800; + + + + public SwingTreeControlProvider(XDialogProvider _xDialogProvider){ + m_xDialogProvider = _xDialogProvider; + } + + + public void addInspectorPane(InspectorPane _oInspectorPane){ + m_oInspectorPane = _oInspectorPane; + } + + public InspectorPane getInspectorPane() throws NullPointerException{ + if (m_oInspectorPane == null){ + throw new NullPointerException("InspectorPage has not been added to TreeControl"); + } + else{ + return m_oInspectorPane; + } + } + + private void ComponentSelector(Object _oRootObject, String _sRootTreeNodeName) { + oRootNode = new SwingUnoNode(_oRootObject); + oRootNode.setLabel(_sRootTreeNodeName); + treeModel = new HideableTreeModel(oRootNode); + jTree.setModel(treeModel); + jTree.setRootVisible(true); + jTree.setVisible(true); + oRootNode.setFoldable(true); + enableFilterElements(null); + } + + + + private void insertTopPanel(JPanel _jPnlCenter){ + javax.swing.JPanel jPnlTop = new javax.swing.JPanel(new BorderLayout(10, 10)); + jPnlTop.setPreferredSize(new java.awt.Dimension(nDIALOGWIDTH, 20)); + jlblFilter.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); + jlblFilter.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); + jPnlTop.add(jlblFilter, java.awt.BorderLayout.WEST); + jtxtFilter.setHorizontalAlignment(javax.swing.JTextField.LEFT); + jtxtFilter.setPreferredSize(new java.awt.Dimension(200, 10)); + jtxtFilter.addKeyListener(new InspectorKeyFilterAdapter()); + jPnlTop.add(jtxtFilter, java.awt.BorderLayout.CENTER); + _jPnlCenter.add(jPnlTop, java.awt.BorderLayout.NORTH); + } + + + private void insertBottomPanel(JSplitPane _jSplitPane){ //JPanel _jPnlCenter){ + jtxtGeneratedSourceCode.setTabSize(4); + jtxtGeneratedSourceCode.getAccessibleContext().setAccessibleName("generated SourceCode"); + JScrollPane jScrollPane = new JScrollPane(jtxtGeneratedSourceCode); + jScrollPane.setPreferredSize(new Dimension(nDIALOGWIDTH,205)); + jtxtGeneratedSourceCode.setEditable(false); + _jSplitPane.setBottomComponent(jScrollPane); + } + + private void insertBorderPanes(Container _cp){ + JPanel jPnlEast = new JPanel(new BorderLayout()); + JPanel jPnlNorth = new JPanel(new BorderLayout()); + JPanel jPnlSouth = new JPanel(new BorderLayout()); + JPanel jPnlWest = new JPanel(new BorderLayout()); + _cp.add(jPnlNorth, java.awt.BorderLayout.NORTH); + jPnlWest.setPreferredSize(new java.awt.Dimension(10, 10)); + _cp.add(jPnlWest, java.awt.BorderLayout.WEST); + jPnlEast.setPreferredSize(new java.awt.Dimension(10, 10)); + _cp.add(jPnlEast, java.awt.BorderLayout.EAST); + jPnlSouth.setPreferredSize(new java.awt.Dimension(10, 10)); + _cp.add(jPnlSouth, java.awt.BorderLayout.SOUTH); + } + + + public String enableFilterElements(XUnoNode _oUnoNode){ + String sFilter =""; + boolean bIsFacetteNode = isFacetteNode(_oUnoNode); + this.jtxtFilter.setEnabled(bIsFacetteNode); + this.jlblFilter.setEnabled(bIsFacetteNode); + sFilter = m_oInspectorPane.getFilter(_oUnoNode); + jtxtFilter.setText(sFilter); + return sFilter; + } + + + private class InspectorKeyFilterAdapter extends KeyAdapter{ + @Override + public void keyReleased(KeyEvent e){ + String sFilter = jtxtFilter.getText(); + SwingTreePathProvider oSwingTreePathProvider = new SwingTreePathProvider(jTree.getSelectionPath()); + XUnoNode oUnoNode = oSwingTreePathProvider.getLastPathComponent(); + if (oUnoNode instanceof XUnoFacetteNode){ + m_oInspectorPane.applyFilter((XUnoFacetteNode) oUnoNode, sFilter); + } + } + } + + + + /** Inspect the given object for methods, properties, interfaces, and + * services. + * @param _oUserDefinedObject The object to inspect + * @throws RuntimeException If + */ + public Object inspect(java.lang.Object _oUserDefinedObject, String _sTitle) throws com.sun.star.uno.RuntimeException { + JPanel jPnlContainer = new javax.swing.JPanel(new BorderLayout(10, 10)); + try { + javax.swing.JPanel jPnlCenter = new javax.swing.JPanel(); + bIsUserDefined = (_oUserDefinedObject != null); + if (bIsUserDefined){ + oUserDefinedObject = _oUserDefinedObject; + m_oInspectorPane.setTitle(_sTitle); + } + javax.swing.JScrollPane jScrollPane1 = new javax.swing.JScrollPane(); + TreeSelectionModel tsm = new DefaultTreeSelectionModel(); + tsm.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + jTree.setSelectionModel(tsm); + jTree.setVisible(false); + jPnlCenter.setLayout(new java.awt.BorderLayout(10, 10)); + jPnlCenter.getAccessibleContext().setAccessibleName("inspection tab view"); + insertTopPanel(jPnlCenter); + jScrollPane1.setViewportView(jTree); + jScrollPane1.setPreferredSize(new java.awt.Dimension(600, 600)); + jScrollPane1.getAccessibleContext().setAccessibleName("API view scroll pane"); + + JScrollBar jHScrollBar = jScrollPane1.createHorizontalScrollBar(); + jHScrollBar.getAccessibleContext().setAccessibleName("API view horizontal scroll bar"); + jScrollPane1.setHorizontalScrollBar(jHScrollBar); + + JScrollBar jVScrollBar = jScrollPane1.createVerticalScrollBar(); + jVScrollBar.getAccessibleContext().setAccessibleName("API view vertical scroll bar"); + jScrollPane1.setVerticalScrollBar(jVScrollBar); + + JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); + jSplitPane.setTopComponent(jScrollPane1); + jPnlCenter.add(jSplitPane, java.awt.BorderLayout.CENTER); + jSplitPane.setDividerLocation(500); + insertBottomPanel(jSplitPane); + UnoTreeRenderer oUnoTreeRenderer = new UnoTreeRenderer(); + jTree.setCellRenderer(oUnoTreeRenderer); + jTree.addTreeSelectionListener( + new TreeSelectionListener() { + public void valueChanged(TreeSelectionEvent event) { + TreePath tp = event.getNewLeadSelectionPath(); + if (tp != null){ + XUnoNode oUnoNode = getSelectedNode(); + String sFilter = enableFilterElements(oUnoNode); + } + } + } + ); + // Add KeyListener for help + jTree.addKeyListener( new java.awt.event.KeyAdapter() { + @Override + public void keyReleased(java.awt.event.KeyEvent event) { + if ( event.getKeyCode() == KeyEvent.VK_F1 ) { + // function key F1 pressed + TreePath aTreePath = jTree.getSelectionPath(); + SwingUnoNode oUnoNode = (SwingUnoNode) aTreePath.getLastPathComponent(); + oUnoNode.openIdlDescription(m_xDialogProvider.getIDLPath()); + } + } + }); + jTree.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed (MouseEvent e) { + if (e.isPopupTrigger()){ + m_oInspectorPane.showPopUpMenu(e.getComponent(), e.getX(), e.getY()); + } + //unfortunately under Windows the method "isPopupTrigger" always returns false + else if ((e.getModifiersEx() & MouseEvent.BUTTON3_DOWN_MASK) == MouseEvent.BUTTON3_DOWN_MASK){ + m_oInspectorPane.showPopUpMenu(e.getComponent(), e.getX(), e.getY()); + } + } + }); + jPnlContainer.add(jPnlCenter, java.awt.BorderLayout.CENTER); + insertBorderPanes(jPnlContainer); + if (this.bIsUserDefined){ + ComponentSelector(oUserDefinedObject, m_oInspectorPane.getTitle()); + } + m_xDialogProvider.addInspectorPage(m_oInspectorPane.getTitle(), jPnlContainer); + addTreeExpandListener(); + } + catch( Exception exception ) { + exception.printStackTrace(System.err); + } + return jPnlContainer; + } + + public HideableTreeModel getModel(){ + return treeModel; + } + + + public void addTreeExpandListener(){ + jTree.addTreeWillExpandListener( + new TreeWillExpandListener() { + public void treeWillExpand(javax.swing.event.TreeExpansionEvent event) throws javax.swing.tree.ExpandVetoException { + SwingTreePathProvider oSwingTreePathProvider = new SwingTreePathProvider(event.getPath()); + XUnoNode oUnoNode = oSwingTreePathProvider.getLastPathComponent(); + if (!m_oInspectorPane.expandNode(oUnoNode)){ + throw new ExpandVetoException(event); + } + } + + public void treeWillCollapse( javax.swing.event.TreeExpansionEvent evt) throws javax.swing.tree.ExpandVetoException { + } + }); + } + + + public void setSourceCode(String _sSourceCode){ + jtxtGeneratedSourceCode.setText(_sSourceCode); + } + + + public XTreePathProvider getSelectedPath(){ + return new SwingTreePathProvider(jTree.getSelectionPath()); + } + + + public void expandPath(XTreePathProvider _xTreePathProvider) throws ClassCastException{ + SwingTreePathProvider oSwingTreePathProvider = (SwingTreePathProvider) _xTreePathProvider; + jTree.expandPath(oSwingTreePathProvider.getSwingTreePath()); + } + + + public XUnoNode getSelectedNode(){ + XUnoNode oUnoNode = null; + TreePath aTreePath = jTree.getSelectionPath(); + Object oNode = aTreePath.getLastPathComponent(); + if (oNode instanceof XUnoNode){ + oUnoNode = (XUnoNode) oNode; + } + return oUnoNode; + } + + + public void nodeInserted(XUnoNode _oParentNode, XUnoNode _oChildNode, int index) { + getModel().nodeInserted(_oParentNode, _oChildNode, _oParentNode.getChildCount()-1); + } + + + public void nodeChanged(XUnoNode _oNode) { + getModel().nodeChanged(_oNode); + } + + + public boolean setNodeVisible(Object node, boolean v) { + return getModel().setNodeVisible(node, v); + } + + + public boolean isPropertyNode(XUnoNode _oUnoNode){ + return (_oUnoNode instanceof SwingUnoPropertyNode); + } + + + public boolean isMethodNode(XUnoNode _oUnoNode){ + return (_oUnoNode instanceof SwingUnoMethodNode); + } + + + public boolean isFacetteNode(XUnoNode _oUnoNode){ + return (_oUnoNode instanceof SwingUnoFacetteNode); + } + + + public XUnoNode addUnoNode(Object _oUnoObject){ + return new SwingUnoNode(_oUnoObject); + } + + + public XUnoNode addUnoNode(Object _oUnoObject, Type _aType){ + return new SwingUnoNode(_oUnoObject, _aType); + } + + + public XUnoFacetteNode addUnoFacetteNode(XUnoNode _oParentNode, String _sNodeDescription, Object _oUnoObject){ + SwingUnoFacetteNode oSwingUnoFacetteNode = new SwingUnoFacetteNode(_oUnoObject); + oSwingUnoFacetteNode.setLabel(_sNodeDescription); + if (_oParentNode != null){ + ((SwingUnoNode) _oParentNode).addChildNode(oSwingUnoFacetteNode); + } + return oSwingUnoFacetteNode; + } + + + public XUnoMethodNode addMethodNode(Object _objectElement, XIdlMethod _xIdlMethod){ + SwingUnoMethodNode oSwingUnoMethodNode = new SwingUnoMethodNode(_xIdlMethod, _objectElement, m_xDialogProvider); + return oSwingUnoMethodNode; + } + + + public XUnoPropertyNode addUnoPropertyNodeWithName(Property _aProperty){ + SwingUnoPropertyNode oUnoPropertyNode = new SwingUnoPropertyNode(_aProperty); + oUnoPropertyNode.setLabel("Name: " + _aProperty.Name); + return oUnoPropertyNode; + } + + + public XUnoPropertyNode addUnoPropertyNodeWithHandle(Property _aProperty){ + SwingUnoPropertyNode oUnoPropertyNode = new SwingUnoPropertyNode(_aProperty); + oUnoPropertyNode.setLabel("Handle: " + _aProperty.Handle); + return oUnoPropertyNode; + } + + + public XUnoPropertyNode addUnoPropertyNodeWithType(Property _aProperty){ + SwingUnoPropertyNode oUnoPropertyNode = new SwingUnoPropertyNode(_aProperty); + oUnoPropertyNode.setLabel("Type: " + _aProperty.Type.getTypeName()); + return oUnoPropertyNode; + } + + + public XUnoPropertyNode addUnoPropertyNodeWithAttributesDescription(Property _aProperty){ + SwingUnoPropertyNode oUnoPropertyNode = new SwingUnoPropertyNode(_aProperty); + XConstantTypeDescription[] xPropertyAttributesTypeDescriptions = Introspector.getIntrospector().getFieldsOfConstantGroup("com.sun.star.beans.PropertyAttribute"); + String sDisplay = Introspector.getIntrospector().getConstantDisplayString(_aProperty.Attributes, xPropertyAttributesTypeDescriptions, "Attributes: "); + oUnoPropertyNode.setLabel(sDisplay); + return oUnoPropertyNode; + } + + + public XUnoPropertyNode addUnoPropertyNode(Object _oUnoObject, Property _aProperty){ + SwingUnoPropertyNode oUnoPropertyNode = new SwingUnoPropertyNode(_aProperty, _oUnoObject, null); + oUnoPropertyNode.setPropertyNodeType(XUnoPropertyNode.nPROPERTYSETINFOTYPE); + oUnoPropertyNode.setLabel(UnoPropertyNode.getStandardPropertyDescription(_aProperty, null)); + return oUnoPropertyNode; + } + + + public XUnoPropertyNode addUnoPropertyNode(Object _oUnoObject, Property _aProperty, Object _oUnoReturnObject){ + SwingUnoPropertyNode oUnoPropertyNode = new SwingUnoPropertyNode(_aProperty, _oUnoObject, _oUnoReturnObject); + oUnoPropertyNode.setLabel(UnoPropertyNode.getStandardPropertyDescription(_aProperty, _oUnoReturnObject)); + return oUnoPropertyNode; + } + + + public XUnoPropertyNode addUnoPropertyNode(Object _oUnoObject, PropertyValue _aPropertyValue, Object _oReturnObject){ + SwingUnoPropertyNode oUnoPropertyNode = new SwingUnoPropertyNode(_aPropertyValue, _oUnoObject, _oReturnObject); + oUnoPropertyNode.setLabel(UnoPropertyNode.getStandardPropertyValueDescription(_aPropertyValue)); + return oUnoPropertyNode; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/SwingTreePathProvider.java b/odk/examples/java/Inspector/SwingTreePathProvider.java new file mode 100644 index 000000000..c0f6703ca --- /dev/null +++ b/odk/examples/java/Inspector/SwingTreePathProvider.java @@ -0,0 +1,60 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import javax.swing.tree.TreePath; + +public class SwingTreePathProvider implements XTreePathProvider { + private TreePath m_aTreePath; + + /** Creates a new instance of TreePathProvider */ + public SwingTreePathProvider(TreePath _aTreePath) { + m_aTreePath = _aTreePath; + } + + + public XUnoNode getLastPathComponent(){ + return (XUnoNode) m_aTreePath.getLastPathComponent(); + } + + + public XUnoNode getPathComponent(int i){ + return (XUnoNode) m_aTreePath.getPathComponent(i); + } + + public int getPathCount(){ + return m_aTreePath.getPathCount(); + } + + + public XTreePathProvider getParentPath(){ + return new SwingTreePathProvider(m_aTreePath.getParentPath()); + } + + + public XTreePathProvider pathByAddingChild(XUnoNode _oUnoNode){ + TreePath aTreePath = m_aTreePath.pathByAddingChild(_oUnoNode); + return new SwingTreePathProvider(aTreePath); + } + + public TreePath getSwingTreePath(){ + return m_aTreePath; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/SwingUnoFacetteNode.java b/odk/examples/java/Inspector/SwingUnoFacetteNode.java new file mode 100644 index 000000000..31a80ffd9 --- /dev/null +++ b/odk/examples/java/Inspector/SwingUnoFacetteNode.java @@ -0,0 +1,84 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + + +public class SwingUnoFacetteNode extends SwingUnoNode implements XUnoFacetteNode{ + private String m_sFilter = ""; + + /** Creates a new instance of UnoMethodNode */ + public SwingUnoFacetteNode(Object _oUnoObject){ + super(_oUnoObject); + setFoldable(true); + } + + + public String getFilter(){ + return m_sFilter; + } + + public void setFilter(String _sFilter){ + m_sFilter = _sFilter; + } + + @Override + public String getName(){ + return toString(); + } + +// TODO The implementation of the following methods is not really robust and should be changed!!! + public boolean isMethodNode(){ + return ((String) getUserObject()).equals(SMETHODDESCRIPTION); + } + + public boolean isPropertyNode(){ + String sNodeDescription = (String) getUserObject(); + return ((sNodeDescription.equals(SPROPERTYDESCRIPTION)) || (sNodeDescription.equals(SPROPERTYINFODESCRIPTION)) || (sNodeDescription.equals(SPROPERTYVALUEDESCRIPTION))); + } + + public boolean isContainerNode(){ + return ((String) getUserObject()).equals(SCONTAINERDESCRIPTION); + } + + public boolean isServiceNode(){ + return ((String) getUserObject()).equals(SSERVICEDESCRIPTION); + } + + public boolean isInterfaceNode(){ + return ((String) getUserObject()).equals(SINTERFACEDESCRIPTION); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/SwingUnoMethodNode.java b/odk/examples/java/Inspector/SwingUnoMethodNode.java new file mode 100644 index 000000000..f06f2161c --- /dev/null +++ b/odk/examples/java/Inspector/SwingUnoMethodNode.java @@ -0,0 +1,144 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; + +import com.sun.star.reflection.XIdlMethod; +import com.sun.star.uno.TypeClass; + + + +public class SwingUnoMethodNode extends SwingUnoNode implements ActionListener, XUnoMethodNode{ + + private UnoMethodNode m_oUnoMethodNode; + private XDialogProvider m_xDialogProvider = null; + + public SwingUnoMethodNode(XIdlMethod _xIdlMethod, Object _oUnoObject, XDialogProvider _xDialogProvider) { + super(_oUnoObject); + m_oUnoMethodNode = new UnoMethodNode(_xIdlMethod, _oUnoObject, this); + m_xDialogProvider = _xDialogProvider; + setUserObject(m_oUnoMethodNode.getNodeDescription()); + if (m_oUnoMethodNode.isFoldable()){ + setFoldable(true); + } + } + + public boolean isFoldable(){ + return m_oUnoMethodNode.isFoldable(); + } + + @Override + public String getName(){ + return m_oUnoMethodNode.getName(); + } + + @Override + public String getClassName(){ + String sClassName = ""; + sClassName = getXIdlMethod().getDeclaringClass().getName(); + if (sClassName.equals("")){ + sClassName = super.getClassName(); + } + return sClassName; + } + + @Override + public String getAnchor(){ + return m_oUnoMethodNode.getAnchor(); + } + + public Object invoke(Object _oUnoObject, Object[] _oParameters) throws com.sun.star.uno.Exception{ + return m_oUnoMethodNode.invoke(_oUnoObject, _oParameters); + } + + + public Object[] getLastParameterObjects(){ + return m_oUnoMethodNode.getLastParameterObjects(); + } + + public Object getLastUnoReturnObject(){ + return m_oUnoMethodNode.getLastUnoReturnObject(); + } + + public TypeClass getTypeClass() { + return m_oUnoMethodNode.getTypeClass(); + } + + public XIdlMethod getXIdlMethod() { + return m_oUnoMethodNode.getXIdlMethod(); + } + + public boolean hasParameters() { + return m_oUnoMethodNode.hasParameters(); + } + + public Object invoke() throws com.sun.star.uno.Exception{ + return m_oUnoMethodNode.invoke(); + } + + public boolean isInvoked() { + return m_oUnoMethodNode.isInvoked(); + } + + public boolean isInvokable(){ + return m_oUnoMethodNode.isInvokable(); + } + + public boolean isPrimitive() { + return m_oUnoMethodNode.isPrimitive(); + } + + public void actionPerformed(ActionEvent e){ + openIdlDescription(m_xDialogProvider.getIDLPath()); + } + + public ArrayList getMethodObjects(){ + MethodParametersDialog oMethodParametersDialog = new MethodParametersDialog(this); + oMethodParametersDialog.addActionListener(this); + return oMethodParametersDialog.getMethodObjects(); + } + + + public String getParameterDescription(){ + return m_oUnoMethodNode.getParameterDescription(); + } + + + public String getStandardMethodDescription(){ + return m_oUnoMethodNode.getStandardMethodDescription(); + } +} +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/SwingUnoNode.java b/odk/examples/java/Inspector/SwingUnoNode.java new file mode 100644 index 000000000..c1d84d85e --- /dev/null +++ b/odk/examples/java/Inspector/SwingUnoNode.java @@ -0,0 +1,160 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.uno.Type; +import javax.swing.tree.TreeNode; + + +public class SwingUnoNode extends HideableMutableTreeNode implements XUnoNode{ + private UnoNode m_oUnoNode; + + /** Creates a new instance of SwingUnoNode */ + public SwingUnoNode(Object _oUnoObject) { + super(); + m_oUnoNode = new UnoNode(_oUnoObject); + } + + + public SwingUnoNode(Object _oUnoObject, Type _aType) { + super(); + m_oUnoNode = new UnoNode(_oUnoObject, _aType); + if (_aType != null){ + this.setLabel(_aType.getTypeName()); + } + } + + + public Object getUnoObject(){ + return m_oUnoNode.getUnoObject(); + } + + public void setVisible(String _sFilter){ + boolean bisVisible = isFilterApplicable(_sFilter); + super.setVisible(bisVisible); + } + + public boolean isFilterApplicable(String _sFilter) { + return m_oUnoNode.isFilterApplicable(_sFilter, getName()); + } + + public void setParameterObjects(Object[] _oParamObjects) { + m_oUnoNode.setParameterObjects(_oParamObjects); + } + + public void openIdlDescription(String _SDKPath) { + m_oUnoNode.openIdlDescription(_SDKPath, getClassName()); + } + + public Object[] getParameterObjects() { + return m_oUnoNode.getParameterObjects(); + } + + public String getClassName(){ + String sClassName = m_oUnoNode.getClassName(); + if (sClassName.equals("")){ + TreeNode oTreeNode = getParent(); + if (oTreeNode != null){ + if (oTreeNode instanceof XUnoNode){ + SwingUnoNode oUnoNode = (SwingUnoNode) oTreeNode; + sClassName = oUnoNode.getClassName(); + } + } + } + return sClassName; + } + + public String getAnchor() { + return m_oUnoNode.getAnchor(); + } + + + public void setFoldable(boolean _bIsFoldable){ + if (_bIsFoldable){ + addDummyNode(); + } + else{ + removeDummyNode(); + } + } + + + public XUnoNode getParentNode(){ + return (SwingUnoNode) super.getParent(); + } + + + public void addChildNode(XUnoNode _xUnoNode) { + super.add((SwingUnoNode) _xUnoNode); + } + + public void setLabel(String _sLabel){ + super.setUserObject(_sLabel); + this.m_oUnoNode.setLabel(_sLabel); + } + + public String getLabel(){ + return (String) super.getUserObject(); + } + + + @Override + public int getChildCount(){ + return super.getChildCount(); + } + + + public XUnoNode getChild(int _i){ + return (SwingUnoNode) super.getChildAt(_i); + } + + public int getNodeType(){ + return m_oUnoNode.getNodeType(); + } + + public void setNodeType(int _nNodeType){ + m_oUnoNode.setNodeType(_nNodeType); + } + + + public String getName(){ + return getClassName(); + } + + + public Type getUnoType(){ + return m_oUnoNode.getUnoType(); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/SwingUnoPropertyNode.java b/odk/examples/java/Inspector/SwingUnoPropertyNode.java new file mode 100644 index 000000000..0e65a0361 --- /dev/null +++ b/odk/examples/java/Inspector/SwingUnoPropertyNode.java @@ -0,0 +1,102 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; + +public class SwingUnoPropertyNode extends SwingUnoNode implements XUnoPropertyNode{ + + private UnoPropertyNode m_oUnoPropertyNode = null; + + + public SwingUnoPropertyNode(Property _aProperty, Object _oUnoObject, Object _oUnoReturnObject) { + super(_oUnoObject); + m_oUnoPropertyNode = new UnoPropertyNode(_aProperty, _oUnoObject, _oUnoReturnObject); + super.setUserObject(m_oUnoPropertyNode.getLabel()); + setFoldable(m_oUnoPropertyNode.isFoldable()); + } + + + public SwingUnoPropertyNode(Property _aProperty){ + super(null); + m_oUnoPropertyNode = new UnoPropertyNode(_aProperty); + } + + + public SwingUnoPropertyNode(PropertyValue _aPropertyValue, Object _oUnoObject, Object _oUnoReturnObject) { + super(_oUnoObject); + m_oUnoPropertyNode = new UnoPropertyNode(_aPropertyValue, _oUnoObject, _oUnoReturnObject); + } + + @Override + public String getName(){ + return m_oUnoPropertyNode.getName(); + } + + + public Object getUnoReturnObject(){ + return m_oUnoPropertyNode.getUnoReturnObject(); + } + + + @Override + public String getClassName(){ + String sClassName = m_oUnoPropertyNode.getClassName(); + if (sClassName.equals("")){ + sClassName = super.getClassName(); + } + return sClassName; + } + + @Override + public String getAnchor(){ + return m_oUnoPropertyNode.getAnchor(); + } + + public int getPropertyNodeType(){ + return m_oUnoPropertyNode.getPropertyNodeType(); + } + + + public void setPropertyNodeType(int _nPropertyType){ + m_oUnoPropertyNode.setPropertyNodeType(_nPropertyType); + } + + public Property getProperty(){ + return m_oUnoPropertyNode.getProperty(); + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/TDocSupplier.java b/odk/examples/java/Inspector/TDocSupplier.java new file mode 100644 index 000000000..593c8a852 --- /dev/null +++ b/odk/examples/java/Inspector/TDocSupplier.java @@ -0,0 +1,166 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.frame.XModel; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.sdbc.XRow; +import com.sun.star.ucb.Command; +import com.sun.star.ucb.UniversalContentBroker; +import com.sun.star.ucb.XCommandProcessor; +import com.sun.star.ucb.XContent; +import com.sun.star.ucb.XContentIdentifier; +import com.sun.star.ucb.XSimpleFileAccess; +import com.sun.star.ucb.XUniversalContentBroker; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import javax.swing.JOptionPane; + + +public class TDocSupplier { + private XMultiComponentFactory m_xMultiComponentFactory; + private XComponentContext m_xComponentContext; + + + /** Creates a new instance of TDocSupplier */ + public TDocSupplier(XComponentContext _xComponentContext) { + m_xComponentContext = _xComponentContext; + m_xMultiComponentFactory = m_xComponentContext.getServiceManager(); + } + + + private XComponentContext getXComponentContext(){ + return m_xComponentContext; + } + + + private XMultiComponentFactory getXMultiComponentFactory(){ + return m_xMultiComponentFactory; + } + + public XModel getXModelByTDocUrl(String _sTDocUrl){ + try{ + XRow xRow = getXRowOfTDocUrl(_sTDocUrl, "DocumentModel"); + if (xRow != null){ + Object oModel = xRow.getObject(1, null); + XModel xModel = UnoRuntime.queryInterface(XModel.class, oModel); + return xModel; + } + }catch(Exception exception){ + exception.printStackTrace(System.err); + } + JOptionPane.showMessageDialog(new javax.swing.JFrame(), "The selected Document could not be opened!", "Object Inspector", JOptionPane.ERROR_MESSAGE); + return null; + } + + + public String getTitleByTDocUrl(String _sTDocUrl){ + try{ + XRow xRow = this.getXRowOfTDocUrl(_sTDocUrl, "Title"); + if (xRow != null){ + return xRow.getString(1); + } + }catch(Exception exception){ + exception.printStackTrace(System.err); + } + JOptionPane.showMessageDialog(new javax.swing.JFrame(), "The selected Document could not be opened!", "Object Inspector", JOptionPane.ERROR_MESSAGE); + return ""; + } + + + private XRow getXRowOfTDocUrl(String _sTDocUrl, String _sPropertyName){ + try{ + XUniversalContentBroker xUCB = UniversalContentBroker.create( getXComponentContext() ); + XContentIdentifier xId = xUCB.createContentIdentifier(_sTDocUrl); + XContent xContent = xUCB.queryContent(xId); + XCommandProcessor xCmdProcessor = UnoRuntime.queryInterface(XCommandProcessor.class, xContent); + Property aProperty = new Property(); + aProperty.Name = _sPropertyName; // "DocumentModel"; //DocumentModel + Command aCommand = new Command(); + aCommand.Name = "getPropertyValues"; + aCommand.Handle = -1; // not available + aCommand.Argument = new Property[]{aProperty}; + Object oAny = xCmdProcessor.execute(aCommand, 0, null); + XRow xRow = UnoRuntime.queryInterface(XRow.class, oAny); + return xRow; + }catch(Exception exception){ + exception.printStackTrace(System.err); + return null; + }} + + + protected String[] getTDocTitles(String[] _sTDocUrls){ + String[] sTitles = new String[_sTDocUrls.length]; + for (int i = 0; i < _sTDocUrls.length; i++){ + sTitles[i] = getTitleByTDocUrl(_sTDocUrls[i]); + } + return sTitles; + } + + + protected String[] getTDocUrls(){ + try{ + Object oSimpleFileAccess = getXMultiComponentFactory().createInstanceWithContext("com.sun.star.ucb.SimpleFileAccess", getXComponentContext()); + XSimpleFileAccess xSimpleFileAccess = UnoRuntime.queryInterface(XSimpleFileAccess.class, oSimpleFileAccess); + String[] sContent = xSimpleFileAccess.getFolderContents("vnd.sun.star.tdoc:/", false); + return sContent; + } catch( Exception e ) { + System.err.println( e ); + return new String[]{}; + }} + + + public XComponent openEmptyDocument(String _sUrl){ + try{ + PropertyValue[] aPropertyValues = new PropertyValue[1]; + aPropertyValues[0] = new PropertyValue(); + aPropertyValues[0].Name = "Hidden"; + aPropertyValues[0].Value = Boolean.TRUE; + Object oDesktop = getXMultiComponentFactory().createInstanceWithContext("com.sun.star.frame.Desktop", getXComponentContext()); + XComponentLoader xCL = UnoRuntime.queryInterface(XComponentLoader.class, oDesktop); + return xCL.loadComponentFromURL(_sUrl, "_default", 0, aPropertyValues); + } + catch( Exception exception ) { + System.err.println( exception ); + return null; + }} + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/TestInspector.java b/odk/examples/java/Inspector/TestInspector.java new file mode 100644 index 000000000..208acf25b --- /dev/null +++ b/odk/examples/java/Inspector/TestInspector.java @@ -0,0 +1,88 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.uno.UnoRuntime; + +public class TestInspector { + + public static void main(String args[]) { + com.sun.star.uno.XComponentContext xContext = null; + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if( xContext != null ) + System.out.println("Connected to a running office ..."); + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + try { + com.sun.star.lang.XMultiComponentFactory xMCF = xContext.getServiceManager(); + // Creating an instance of the instance inspector with arguments + + XSingleComponentFactory xFactory = Inspector.__getComponentFactory(Inspector._Inspector.class.getName()); + Object obj= null; + if (xFactory != null) { + obj = xFactory.createInstanceWithContext(xContext); + } + org.openoffice.XInstanceInspector xInstInspector = null; + if (obj != null) { + xInstInspector = UnoRuntime.queryInterface(org.openoffice.XInstanceInspector.class, obj); + } + + /* A desktop environment contains tasks with one or more + frames in which components can be loaded. Desktop is the + environment for components which can instantiate within + frames. */ + com.sun.star.frame.XComponentLoader xCmpLoader = UnoRuntime.queryInterface( com.sun.star.frame.XComponentLoader.class, + xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext)); + + // Load a new spreadsheet document, which will be automatically + // displayed and is used for inspection + com.sun.star.lang.XComponent xComp = xCmpLoader.loadComponentFromURL("private:factory/scalc", "_blank", 0, new com.sun.star.beans.PropertyValue[0] ); + xInstInspector.inspect(xCmpLoader, ""); + System.out.println("You can now inspect the new spreadsheet " + "document ...\n"); + } + catch( Exception e ) { + System.err.println( e + e.getMessage()); + e.printStackTrace(); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/UnoMethodNode.java b/odk/examples/java/Inspector/UnoMethodNode.java new file mode 100644 index 000000000..a620fc81a --- /dev/null +++ b/odk/examples/java/Inspector/UnoMethodNode.java @@ -0,0 +1,228 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.reflection.ParamInfo; +import com.sun.star.reflection.ParamMode; +import com.sun.star.reflection.XIdlClass; +import com.sun.star.reflection.XIdlMethod; +import com.sun.star.uno.TypeClass; + +public class UnoMethodNode extends UnoNode{ + private XIdlMethod m_xIdlMethod = null; + private Object[] m_oParamObjects = null; + private Object m_oUnoReturnObject = null; + private boolean m_bisInvoked = false; + private XUnoMethodNode m_xUnoMethodNode = null; + + + /** Creates a new instance of UnoMethodNode */ + public UnoMethodNode(XIdlMethod _xIdlMethod, Object _oUnoObject, XUnoMethodNode _xUnoMethodNode) { + super(_oUnoObject); + m_xIdlMethod = _xIdlMethod; + m_oParamObjects = new Object[m_xIdlMethod.getParameterInfos().length]; + m_xUnoMethodNode = _xUnoMethodNode; + } + + protected boolean isFoldable(){ + return ((!this.isPrimitive()) && (getTypeClass().getValue() != TypeClass.VOID_value)); + } + + protected boolean isInvokable(){ + boolean bisFoldable = true; + XIdlClass[] xIdlClasses = m_xIdlMethod.getParameterTypes(); + for (int i = 0; i < xIdlClasses.length; i++){ + bisFoldable = Introspector.isPrimitive(xIdlClasses[i].getTypeClass()); + if (!bisFoldable){ + return false; + } + } + return bisFoldable; + } + + public XIdlMethod getXIdlMethod(){ + return m_xIdlMethod; + } + + + @Override + public String getAnchor(){ + return getXIdlMethod().getName(); + } + + + public String getName(){ + return getXIdlMethod().getName(); + } + + + public Object invoke(){ + Object oUnoReturnObject = null; + if (!hasParameters()){ + oUnoReturnObject = invokeParameterlessMethod(); + m_bisInvoked = true; + } + else{ + java.util.List oUnoMethodObjects = m_xUnoMethodNode.getMethodObjects(); + if (oUnoMethodObjects != null){ + for (int i = 0; i < getXIdlMethod().getParameterInfos().length; i++){ + this.m_oParamObjects[i] = oUnoMethodObjects.get(i); + } + if (oUnoMethodObjects.size() == m_oParamObjects.length + 1){ + oUnoReturnObject = oUnoMethodObjects.get(oUnoMethodObjects.size()-1); + } + m_bisInvoked = (oUnoReturnObject != null); + } + } + m_oUnoReturnObject = oUnoReturnObject; + return oUnoReturnObject; + } + + + public boolean isInvoked(){ + return m_bisInvoked; + } + + + protected String getNodeDescription(){ + String sNodeDescription = ""; + String sParameters = getParameterDescription(); + if (m_xIdlMethod.getParameterInfos().length > 0){ + sNodeDescription = getStandardMethodDescription(); + } + else{ + TypeClass typeClass = getTypeClass(); + if (typeClass != TypeClass.VOID){ + sNodeDescription = getStandardMethodDescription(); + } + else{ + sNodeDescription = getStandardMethodDescription(); + } + } + return sNodeDescription; + } + + + public String getStandardMethodDescription(){ + String sNodeDescription = m_xIdlMethod.getReturnType().getName() + " " + m_xIdlMethod.getName() + " (" + getParameterDescription() + " )"; + if (isPrimitive()){ + sNodeDescription += ""; + } + return sNodeDescription; + } + + + public boolean hasParameters(){ + return (m_xIdlMethod.getParameterInfos().length > 0); + } + + + public Object[] getLastParameterObjects(){ + return m_oParamObjects; + } + + + public Object getLastUnoReturnObject(){ + return m_oUnoReturnObject; + } + + + public String getParameterDescription(){ + ParamInfo[] paramInfo = m_xIdlMethod.getParameterInfos(); + String sParameters = ""; + if (Introspector.isValid(paramInfo)) { + // get all parameters with type and mode + for ( int i = 0; i < paramInfo.length; i++ ) { + XIdlClass xIdlClass = paramInfo[ i ].aType; + if ( i == 0 ) { + // the first parameter has no leading comma + sParameters += "[" + getParamMode(paramInfo[ i ].aMode ) + "] " + xIdlClass.getName(); + } + else { + // all other parameters are separated with comma + sParameters += ", [" + getParamMode(paramInfo[ i ].aMode ) + "] " + xIdlClass.getName(); + } + } + } + return sParameters; + } + + + // return the parameter mode (IN, OUT, INOUT) + private static String getParamMode(ParamMode paramMode) { + String toReturn = ""; + if ( paramMode == ParamMode.IN ) { + toReturn = "IN"; + } + if ( paramMode == ParamMode.OUT ) { + toReturn = "OUT"; + } + if ( paramMode == ParamMode.INOUT ) { + toReturn = "INOUT"; + } + return toReturn; + } + + public TypeClass getTypeClass(){ + XIdlClass xIdlClass = m_xIdlMethod.getReturnType(); + return xIdlClass.getTypeClass(); + } + + + private Object invokeParameterlessMethod(){ + try { + Object[][] aParamInfo = new Object[1][]; + aParamInfo[0] = new Object[] {}; + return getXIdlMethod().invoke(getUnoObject(), aParamInfo); + } catch (Exception ex) { + ex.printStackTrace(System.err); + return null; + }} + + + public boolean isPrimitive(){ + return Introspector.isObjectPrimitive(m_xIdlMethod.getClass(), getTypeClass()); + } + + + protected Object invoke(Object _oUnoObject, Object[] oParameters) throws com.sun.star.uno.Exception{ + Object[][] aParams = new Object[1][oParameters.length]; + for ( int i = 0; i < oParameters.length; i++ ) { + aParams[0][i] = oParameters[i]; + } + return m_xIdlMethod.invoke(_oUnoObject, aParams); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/UnoNode.java b/odk/examples/java/Inspector/UnoNode.java new file mode 100644 index 000000000..0e72d1efd --- /dev/null +++ b/odk/examples/java/Inspector/UnoNode.java @@ -0,0 +1,351 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.beans.PropertyValue; +import com.sun.star.frame.FrameSearchFlag; +import com.sun.star.frame.XDesktop; +import com.sun.star.frame.XDispatch; +import com.sun.star.frame.XDispatchProvider; +import com.sun.star.frame.XFrame; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.Type; +import com.sun.star.uno.TypeClass; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import com.sun.star.util.URL; +import com.sun.star.util.XURLTransformer; + +public class UnoNode{ + + + Object m_oUnoObject; + private XMultiComponentFactory m_xMultiComponentFactory; + private XComponentContext m_xComponentContext; + private Object[] m_oParamObjects = null; + private int m_nNodeType = XUnoNode.nOTHERS; + private Type aType = null; + private String sLabel = ""; + + + + /** Creates a new instance of UnoNode */ + public UnoNode(Object _oUnoObject) { + m_xComponentContext = Introspector.getIntrospector().getXComponentContext(); + m_xMultiComponentFactory = m_xComponentContext.getServiceManager(); + m_oUnoObject = _oUnoObject; + } + + public UnoNode(Object _oUnoObject, Type _aType) { + this(_oUnoObject); + aType = _aType; + m_nNodeType = XUnoNode.nINTERFACE; + } + + public Object getUnoObject(){ + return m_oUnoObject; + } + + + private XComponentContext getXComponentContext(){ + return m_xComponentContext; + } + + + private XMultiComponentFactory getXMultiComponentFactory(){ + return m_xMultiComponentFactory; + } + + + public String getAnchor(){ + return ""; + } + + public int getNodeType(){ + return m_nNodeType; + } + + public void setNodeType(int _nNodeType){ + m_nNodeType = _nNodeType; + } + + public String getClassName(){ + String sClassName = ""; + if (m_nNodeType == XUnoNode.nINTERFACE){ + sClassName = aType.getTypeName(); + } + else if(m_nNodeType == XUnoNode.nSERVICE){ + sClassName = sLabel; + } + return sClassName; + } + + + public Type getUnoType(){ + return aType; + } + + protected void setLabel(String _sLabel){ + sLabel = _sLabel; + } + + public void openIdlDescription(String _sIDLUrl, String _sClassName){ + try{ + String sIDLUrl = _sIDLUrl; + String sAnchor = ""; // TODO find out how the Anchor may be set at the html file; //_sAnchor; + boolean bExists = Introspector.getIntrospector().getXSimpleFileAccess().exists(sIDLUrl); + if (sIDLUrl.equals("") || (!bExists)){ + sIDLUrl = "https://api.libreoffice.org/" + Inspector.sIDLDOCUMENTSUBFOLDER; + } + if (!sIDLUrl.endsWith("/")){ + sIDLUrl += "/"; + } + if (_sClassName.equals("")){ + sIDLUrl += "index"; + sAnchor = ""; + } + else{ + sIDLUrl += _sClassName.replace(".", "_1_1"); + } + sIDLUrl += ".html"; + if (sAnchor != null){ + if (!sAnchor.equals("")){ + sIDLUrl += "#" + sAnchor; + } + } + URL openHyperlink = getDispatchURL(".uno:OpenHyperlink"); + PropertyValue pv = new PropertyValue(); + pv.Name = "URL"; + pv.Value = sIDLUrl; + getXDispatcher(openHyperlink).dispatch(openHyperlink, new PropertyValue[] {pv}); + } catch(Exception exception) { + exception.printStackTrace(System.err); + }} + + + private com.sun.star.util.URL getDispatchURL(String _sURL){ + try { + Object oTransformer = getXMultiComponentFactory().createInstanceWithContext("com.sun.star.util.URLTransformer", getXComponentContext()); + XURLTransformer xTransformer = UnoRuntime.queryInterface(XURLTransformer.class, oTransformer); + com.sun.star.util.URL[] oURL = new com.sun.star.util.URL[1]; + oURL[0] = new com.sun.star.util.URL(); + oURL[0].Complete = _sURL; + xTransformer.parseStrict(oURL); + return oURL[0]; + } catch (Exception e) { + e.printStackTrace(System.err); + } + return null; + } + + + private XFrame getCurrentFrame(){ + try{ + Object oDesktop = getXMultiComponentFactory().createInstanceWithContext("com.sun.star.frame.Desktop", getXComponentContext()); + XDesktop xDesktop = UnoRuntime.queryInterface(XDesktop.class, oDesktop); + return xDesktop.getCurrentFrame(); + } catch (Exception e) { + e.printStackTrace(System.err); + return null; + }} + + + private XDispatch getXDispatcher(com.sun.star.util.URL oURL) { + try { + com.sun.star.util.URL[] oURLArray = new com.sun.star.util.URL[1]; + oURLArray[0] = oURL; + XDispatchProvider xDispatchProvider = UnoRuntime.queryInterface(XDispatchProvider.class, getCurrentFrame()); + XDispatch xDispatch = xDispatchProvider.queryDispatch(oURLArray[0], "_top", FrameSearchFlag.ALL); // "_self" + return xDispatch; + } catch (Exception e) { + e.printStackTrace(System.err); + return null; + }} + + + public boolean isFilterApplicable(String _sFilter, String _sName){ + boolean bFilterDoesApply = true; + if (_sFilter.length() > 0){ + if (_sName.indexOf(_sFilter) == -1){ + bFilterDoesApply = false; + } + } + return bFilterDoesApply; + } + + + public static String getDisplayValueOfPrimitiveType(Object _objectElement){ + String sValue =""; + try{ + if (AnyConverter.isString(_objectElement)){ + sValue = AnyConverter.toString(_objectElement); + } + else if (AnyConverter.isBoolean(_objectElement)){ + sValue += AnyConverter.toBoolean(_objectElement); + } + else if (AnyConverter.isByte(_objectElement)){ + sValue += AnyConverter.toByte(_objectElement); + } + else if (AnyConverter.isChar(_objectElement)){ + sValue += AnyConverter.toChar(_objectElement); + } + else if (AnyConverter.isDouble(_objectElement)){ + sValue += AnyConverter.toDouble(_objectElement); + } + else if (AnyConverter.isFloat(_objectElement)){ + sValue += AnyConverter.toFloat(_objectElement); + } + else if (AnyConverter.isInt(_objectElement)){ + sValue += AnyConverter.toInt(_objectElement); + } + else if (AnyConverter.isLong(_objectElement)){ + sValue += AnyConverter.toLong(_objectElement); + } + else if (AnyConverter.isShort(_objectElement)){ + sValue += AnyConverter.toShort(_objectElement); + } + } + catch( Exception e ) { + System.err.println( e ); + } + return sValue; + } + + protected static String[] getDisplayValuesofPrimitiveArray(Object _oUnoObject){ + String[] sDisplayValues = null; + try{ + Type aType = AnyConverter.getType(_oUnoObject); + TypeClass aTypeClass = aType.getTypeClass(); + int nTypeValue = aTypeClass.getValue(); + if (nTypeValue == TypeClass.SEQUENCE_value){ + nTypeValue = (sequenceComponentType(aType)).getTypeClass().getValue(); + } + switch (nTypeValue){ + case TypeClass.BOOLEAN_value: + boolean[] bBooleans = (boolean[]) AnyConverter.toArray(_oUnoObject); + sDisplayValues = new String[bBooleans.length]; + for (int i = 0; i < bBooleans.length; i++){ + sDisplayValues[i] = Boolean.toString(bBooleans[i]); + } + break; + case TypeClass.BYTE_value: + byte[] bBytes = (byte[]) AnyConverter.toArray(_oUnoObject); + sDisplayValues = new String[bBytes.length]; + for (int i = 0; i < bBytes.length; i++){ + sDisplayValues[i] = "" + bBytes[i]; + } + break; + case TypeClass.DOUBLE_value: + double[] fdoubles = (double[]) AnyConverter.toArray(_oUnoObject); + sDisplayValues = new String[fdoubles.length]; + for (int i = 0; i < fdoubles.length; i++){ + sDisplayValues[i] = String.valueOf(fdoubles[i]); + } + break; + case TypeClass.FLOAT_value: + float[] ffloats = (float[]) AnyConverter.toArray(_oUnoObject); + sDisplayValues = new String[ffloats.length]; + for (int i = 0; i < ffloats.length; i++){ + sDisplayValues[i] = String.valueOf(ffloats[i]); + } + break; + case TypeClass.LONG_value: + int[] nints = (int[]) AnyConverter.toArray(_oUnoObject); + sDisplayValues = new String[nints.length]; + for (int i = 0; i < nints.length; i++){ + sDisplayValues[i] = String.valueOf(nints[i]); + } + break; + case TypeClass.HYPER_value: + long[] nlongs = (long[]) AnyConverter.toArray(_oUnoObject); + sDisplayValues = new String[nlongs.length]; + for (int i = 0; i < nlongs.length; i++){ + sDisplayValues[i] = String.valueOf(nlongs[i]); + } + break; + case TypeClass.SHORT_value: + short[] nShorts = (short[]) AnyConverter.toArray(_oUnoObject); + sDisplayValues = new String[nShorts.length]; + for (int i = 0; i < nShorts.length; i++){ + sDisplayValues[i] = "" + nShorts[i]; + } + break; + case TypeClass.CHAR_value: + break; + default: + System.out.println("Value could not be retrieved: " + aType.getTypeClass().getClass().getName()); + } + return sDisplayValues; + } + catch( Exception e ) { + System.err.println( e ); + return null; + }} + + + private static Type sequenceComponentType(Type sequenceType) { + String n = sequenceType.getTypeName(); + final String PREFIX = "[]"; + return new Type(n.substring(PREFIX.length())); + } + + + + + + public static String getNodeDescription(Object _oUnoObject){ + XServiceInfo xServiceInfo = UnoRuntime.queryInterface( XServiceInfo.class, _oUnoObject ); + if ( xServiceInfo != null ) { + return xServiceInfo.getImplementationName(); + } + if (Introspector.isObjectPrimitive(_oUnoObject)){ //super.isO{sObjectClassName.equals("String"))issClassName.equals("String")) + return _oUnoObject.toString(); + } + else{ + return _oUnoObject.getClass().getName(); + } + } + + public void setParameterObjects(Object[] _oParamObjects){ + m_oParamObjects = _oParamObjects; + } + + public Object[] getParameterObjects(){ + return m_oParamObjects; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/UnoPropertyNode.java b/odk/examples/java/Inspector/UnoPropertyNode.java new file mode 100644 index 000000000..51b6569b2 --- /dev/null +++ b/odk/examples/java/Inspector/UnoPropertyNode.java @@ -0,0 +1,218 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.reflection.XPropertyTypeDescription; +import com.sun.star.uno.UnoRuntime; + +public class UnoPropertyNode extends UnoNode{ + + private Property aProperty; + private PropertyValue aPropertyValue; + private String m_sPropertyName; + private Object m_oUnoReturnObject; + private int m_nPropertyType = XUnoPropertyNode.nDEFAULT; + private String sLabel = ""; + + + /** Creates a new instance of UnoMethodNode */ + public UnoPropertyNode(Property _aProperty, Object _oUnoObject, Object _oUnoReturnObject) { + super(_oUnoObject); + aProperty = _aProperty; + m_sPropertyName = aProperty.Name; + m_oUnoReturnObject = _oUnoReturnObject; + } + + + public UnoPropertyNode(Property _aProperty){ + super(null); + aProperty = _aProperty; + m_sPropertyName = aProperty.Name; + m_oUnoReturnObject = null; + } + + public UnoPropertyNode(PropertyValue _aPropertyValue, Object _oUnoObject, Object _oUnoReturnObject) { + super(_oUnoObject); + m_oUnoReturnObject = _oUnoReturnObject; + aPropertyValue = _aPropertyValue; + m_sPropertyName = aPropertyValue.Name; + } + + + public int getPropertyNodeType(){ + return m_nPropertyType; + } + + + public void setPropertyNodeType(int _nPropertyType){ + m_nPropertyType = _nPropertyType; + } + + + public String getPropertyName(){ + return m_sPropertyName; + } + + public String getName(){ + return this.m_sPropertyName; + } + + + @Override + public String getClassName(){ + String sClassName = ""; + if (m_oUnoObject != null){ + XServiceInfo xServiceInfo = UnoRuntime.queryInterface(XServiceInfo.class, m_oUnoObject); + if (xServiceInfo != null){ + String[] sServiceNames = xServiceInfo.getSupportedServiceNames(); + for (int i = 0; i < sServiceNames.length; i++){ + if (doesServiceSupportProperty(sServiceNames[i], m_sPropertyName)){ + sClassName = sServiceNames[i]; + break; + } + } + } + } + else{ + sClassName = "com.sun.star.beans.Property"; + } + return sClassName; + } + + + @Override + public String getAnchor(){ + return m_sPropertyName; + } + + + + private boolean doesServiceSupportProperty(String _sServiceName, String _sPropertyName){ + try { + XPropertyTypeDescription[] xPropertyTypeDescriptions = Introspector.getIntrospector().getPropertyDescriptionsOfService(_sServiceName); + for (int i = 0; i < xPropertyTypeDescriptions.length; i++){ + if (xPropertyTypeDescriptions[i].getName().equals(_sServiceName + "." + _sPropertyName)){ + return true; + } + } + } catch ( java.lang.Exception e) { + System.out.println(System.out); + } + return false; + } + + + public Object getUnoReturnObject(){ + return m_oUnoReturnObject; + } + + + private boolean isPrimitive(){ + boolean bIsPrimitive = true; + if (getUnoReturnObject() != null){ + if (getProperty() != null){ + bIsPrimitive = Introspector.isObjectPrimitive(getUnoReturnObject().getClass(), getProperty().Type.getTypeClass()); + } + else{ + bIsPrimitive = Introspector.isObjectPrimitive(getUnoReturnObject().getClass()); + } + } + else{ + bIsPrimitive = Introspector.isObjectPrimitive(aProperty.Type.getTypeClass()); + } + return bIsPrimitive; + } + + + protected boolean isFoldable(){ + boolean bIsFoldable = false; + if (! isPrimitive()){ + String sTypeName = getUnoReturnObject().getClass().getName(); + bIsFoldable = (!sTypeName.equals("com.sun.star.uno.Type")); + } + return bIsFoldable; + } + + + protected String getLabel(){ + if (!sLabel.equals("")){ + if (! isPrimitive()){ + if (isFoldable()){ + sLabel = getPropertyTypeDescription(aProperty, getUnoReturnObject()); + } + else{ + sLabel = getStandardPropertyDescription(aProperty, getUnoReturnObject()); + } + } + else { + sLabel = getStandardPropertyDescription(aProperty, getUnoReturnObject()); + } + } + return sLabel; + } + + public Property getProperty(){ + return aProperty; + } + + private static String getPropertyTypeDescription(Property _aProperty, Object _oUnoObject){ + return _aProperty.Type.getTypeName() + " " + _aProperty.Name + " = " + _oUnoObject.toString(); + } + + + protected static String getStandardPropertyDescription(Property _aProperty, Object _objectElement){ + if (!Introspector.isObjectPrimitive(_objectElement)){ + return _aProperty.Name + " = (" + _aProperty.Type.getTypeName() + ") "; + } + else{ + return _aProperty.Name + " (" + _aProperty.Type.getTypeName() + ") = " + getDisplayValueOfPrimitiveType(_objectElement); + } + } + + + protected static String getStandardPropertyValueDescription(PropertyValue _aPropertyValue){ + if (!Introspector.isObjectPrimitive(_aPropertyValue.Value)){ + return _aPropertyValue.Name; + } + else{ + return _aPropertyValue.Name + " : " + UnoNode.getDisplayValueOfPrimitiveType(_aPropertyValue.Value); + } + } +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/UnoTreeRenderer.java b/odk/examples/java/Inspector/UnoTreeRenderer.java new file mode 100644 index 000000000..81e62a6d1 --- /dev/null +++ b/odk/examples/java/Inspector/UnoTreeRenderer.java @@ -0,0 +1,122 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import java.awt.Component; +import java.awt.Graphics; +import javax.swing.Icon; +import javax.swing.ImageIcon; +import javax.swing.JTree; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeCellRenderer; + + + +public class UnoTreeRenderer extends DefaultTreeCellRenderer{ + private Icon m_oMethodIcon; + private Icon m_oPropertyIcon; + private Icon m_oContainerIcon; + private Icon m_oContentIcon; + private Icon m_oServiceIcon; + private Icon m_oInterfaceIcon; + private Icon m_oPropertyValueIcon; + private boolean bSelected; + private int nWidth = 0; + + + /** Creates a new instance of UnoTreeRenderer */ + public UnoTreeRenderer(){ + super(); + try { + + final ClassLoader loader = ClassLoader.getSystemClassLoader(); + m_oMethodIcon = new ImageIcon(loader.getResource("images/methods_16.png")); + m_oPropertyIcon = new ImageIcon("images/properties_16.png"); + m_oPropertyValueIcon = new ImageIcon("images/properties_16.png"); + m_oContainerIcon = new ImageIcon("images/containers_16.png"); + m_oServiceIcon = new ImageIcon("images/services_16.png"); + m_oInterfaceIcon = new ImageIcon("images/interfaces_16.png"); + m_oContentIcon = new ImageIcon("images/content_16.png"); + } catch (RuntimeException e) { + System.out.println("Sorry, could not locate resources, treecell icons will not be displayed."); + } + } + + + @Override + public synchronized Component getTreeCellRendererComponent(JTree tree,Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus){ + try{ + bSelected = sel; + DefaultMutableTreeNode node = (DefaultMutableTreeNode) value; + Component rc = super.getTreeCellRendererComponent( tree, value, sel,expanded, leaf, row,hasFocus); + String sLabelText = (String)node.getUserObject(); + if (sLabelText != null){ + if (sLabelText.equals(XUnoFacetteNode.SCONTAINERDESCRIPTION)){ + } else if (sLabelText.equals(XUnoFacetteNode.SCONTENTDESCRIPTION)){ + } else if (sLabelText.equals(XUnoFacetteNode.SINTERFACEDESCRIPTION)){ + } else if (sLabelText.equals(XUnoFacetteNode.SMETHODDESCRIPTION)){ + } else if (sLabelText.equals(XUnoFacetteNode.SPROPERTYDESCRIPTION)){ + } else if (sLabelText.startsWith(XUnoFacetteNode.SPROPERTYINFODESCRIPTION)){ + } else if (sLabelText.equals(XUnoFacetteNode.SPROPERTYVALUEDESCRIPTION)){ + } else if (sLabelText.equals(XUnoFacetteNode.SSERVICEDESCRIPTION)){ + } else{ + setText(sLabelText); + rc.validate(); + } + setSize(getPreferredSize()); + rc.validate(); + doLayout(); + } + } catch (RuntimeException e) { + System.out.println("Sorry, icon for treecell could not be displayed."); + } + return this; + } + + + + @Override + public void paintComponent(Graphics g) { + int x; + if(getIcon() == null) { + x = 0; + } else { + x = getIcon().getIconWidth() + getIconTextGap(); + } + g.setColor(getForeground()); + super.paintComponent(g); + } +} + + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/XDialogProvider.java b/odk/examples/java/Inspector/XDialogProvider.java new file mode 100644 index 000000000..78b0c792e --- /dev/null +++ b/odk/examples/java/Inspector/XDialogProvider.java @@ -0,0 +1,68 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +public interface XDialogProvider { + + public static String SINVOKE = "Invoke"; + + public static String SADDTOSOURCECODE = "Add to Sourcecode"; + + public void enablePopupMenuItem(String _sMenuTitle, boolean _bdoEnable); + + public void showPopUpMenu(Object invoker, int x, int y) throws java.lang.ClassCastException; + + public InspectorPane getSelectedInspectorPage(); + + public void addInspectorPage(String _sTitle, Object _oContainer); + + public InspectorPane getInspectorPage(int _nIndex); + + public int getInspectorPageCount(); + + public void selectInspectorPageByIndex(int nTabIndex); + + public void show(int _nPageIndex) throws java.lang.ClassCastException; + + public void selectSourceCodeLanguage(int _nLanguage); + + + + // returns one of the constants defined in XLanguageSourceCodeGenerator + public int getLanguage(); + + public String getIDLPath(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/XInstanceInspector.idl b/odk/examples/java/Inspector/XInstanceInspector.idl new file mode 100644 index 000000000..ca96a27e1 --- /dev/null +++ b/odk/examples/java/Inspector/XInstanceInspector.idl @@ -0,0 +1,59 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_ORG_OPENOFFICE_XINSTANCEINSPECTOR_IDL +#define INCLUDED_ORG_OPENOFFICE_XINSTANCEINSPECTOR_IDL + +#include + +module org { module openoffice { + + interface XInstanceInspector { + /** + * For a given instance this method displays all services, interfaces, + * methods, attributes, and contents in a tree. All dependent + * instances are also inspected and displayed, so the user could browse + * the tree. If you press the key "F1", the API-documentation from + * www.openoffice.org for the current instance will be displayed in a + * new window. + */ + void inspect( [in] any aInstance, [in] string sTitle ); + }; + +}; }; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/XLanguageSourceCodeGenerator.java b/odk/examples/java/Inspector/XLanguageSourceCodeGenerator.java new file mode 100644 index 000000000..8729471e2 --- /dev/null +++ b/odk/examples/java/Inspector/XLanguageSourceCodeGenerator.java @@ -0,0 +1,108 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.uno.TypeClass; + +public interface XLanguageSourceCodeGenerator { + + public static final int nJAVA = 0; + public static final int nCPLUSPLUS = 1; + public static final int nBASIC = 2; + + public String getHeaderSourceCode(Object _oUnoObject, String _sClassName, TypeClass _aTypeClass); + + public String getFinalHeaderStatements(); + + public void assignqueryInterfaceHeaderSourceCode(); + + public String getMainMethodSignatureSourceCode(XUnoNode _oUnoNode, String _soReturnObjectDescription); + + public String getMethodTerminationSourceCode(); + + public String getStatementTerminationCharacter(); + + public boolean needsqueryInterface(); + + public String getqueryInterfaceSourceCode(String _sReturnValueDescription, String _sClassName, String _sObjectDescription); + + public String getPropertyValueGetterSourceCode(String _sPropertyName, String _sReturnVariableName, String _sIncomingObjectName, TypeClass _aTypeClass, String _sTypeName); + + public String getStructSourceCode(String _sReturnVariableDescription, String _sObjectDescription, String _sMember); + + public String getObjectTypeDescription(String _sClassName, boolean _bAsHeader); + + public String getbooleanTypeDescription(); + + public String getbyteTypeDescription(); + + public String getshortTypeDescription(); + + + + public String getlongTypeDescription(); + + public String getunsignedlongTypeDescription(); + + public String gethyperTypeDescription(); + + public String getunsignedhyperTypeDescription(); + + public String getfloatTypeDescription(); + + public String getdoubleTypeDescription(); + + public String getcharTypeDescription(); + + public String getstringTypeDescription(boolean _bAsHeaderSourceCode); + + + + public String getanyTypeDescription(boolean _bAsHeaderSourceCode); + + + + public String getVariableDeclaration(String _sTypeString, String _sVariableName, boolean _bIsArray, TypeClass aTypeClass, boolean _bInitialize); + + public String getMethodSeparator(); + + public String getStringValue(String _sValue); + + public String getConvertedSourceCodeValueOfObject(String _sReturnVariableName, String _sObjectDescription, TypeClass _aTypeClass, String _sTypeName); + + public String castLiteral(String _sExpression, TypeClass _aTypeClass); + + public String getCommentSign(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/XTreeControlProvider.java b/odk/examples/java/Inspector/XTreeControlProvider.java new file mode 100644 index 000000000..1cb69c972 --- /dev/null +++ b/odk/examples/java/Inspector/XTreeControlProvider.java @@ -0,0 +1,96 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.beans.Property; +import com.sun.star.beans.PropertyValue; +import com.sun.star.reflection.XIdlMethod; +import com.sun.star.uno.Type; + +public interface XTreeControlProvider { + + + + public String enableFilterElements(XUnoNode _oUnoNode); + + public void setSourceCode(String _sSourceCode); + + public Object inspect(java.lang.Object _oUserDefinedObject, String _sTitle) throws com.sun.star.uno.RuntimeException; + + public void nodeInserted(XUnoNode _oParentNode, XUnoNode _oChildNode, int index); + + public void nodeChanged(XUnoNode _oNode); + + public boolean setNodeVisible(Object node, boolean v); + + public XUnoNode getSelectedNode(); + + public XTreePathProvider getSelectedPath(); + + public void expandPath(XTreePathProvider xTreePathProvider) throws java.lang.ClassCastException; + + public void addTreeExpandListener(); + + public void addInspectorPane(InspectorPane _oInspectorPane); + + public boolean isPropertyNode(XUnoNode _oUnoNode); + + public boolean isMethodNode(XUnoNode _oUnoNode); + + public boolean isFacetteNode(XUnoNode _oUnoNode); + + public XUnoNode addUnoNode(Object _oUnoObject); + + public XUnoNode addUnoNode(Object _oUnoObject, Type _aType); + + public XUnoFacetteNode addUnoFacetteNode(XUnoNode _oParentNode, String _sNodeDescription, Object _oUnoObject); + + public XUnoMethodNode addMethodNode(Object _objectElement, XIdlMethod _xIdlMethod); + + public XUnoPropertyNode addUnoPropertyNodeWithName(Property _aProperty); + + public XUnoPropertyNode addUnoPropertyNodeWithHandle(Property _aProperty); + + public XUnoPropertyNode addUnoPropertyNodeWithType(Property _aProperty); + + public XUnoPropertyNode addUnoPropertyNodeWithAttributesDescription(Property _aProperty); + + public XUnoPropertyNode addUnoPropertyNode(Object _oUnoObject, Property _aProperty); + + public XUnoPropertyNode addUnoPropertyNode(Object _oUnoObject, PropertyValue _aPropertyValue, Object _oReturnObject); + + public XUnoPropertyNode addUnoPropertyNode(Object _oUnoObject, Property _aProperty, Object _oUnoReturnObject); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/XTreePathProvider.java b/odk/examples/java/Inspector/XTreePathProvider.java new file mode 100644 index 000000000..ecbf52dd4 --- /dev/null +++ b/odk/examples/java/Inspector/XTreePathProvider.java @@ -0,0 +1,33 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +public interface XTreePathProvider { + + public XUnoNode getLastPathComponent(); + + public XUnoNode getPathComponent(int i); + + public int getPathCount(); + + public XTreePathProvider getParentPath(); + + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/XUnoFacetteNode.java b/odk/examples/java/Inspector/XUnoFacetteNode.java new file mode 100644 index 000000000..ad1e114c1 --- /dev/null +++ b/odk/examples/java/Inspector/XUnoFacetteNode.java @@ -0,0 +1,66 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + + +public interface XUnoFacetteNode extends XUnoNode { + + public static String SMETHODDESCRIPTION = "Methods"; + public static String SPROPERTYDESCRIPTION = "Properties"; + public static String SPROPERTYINFODESCRIPTION = "PropertyInfo"; + public static String SCONTAINERDESCRIPTION = "Container"; + public static String SSERVICEDESCRIPTION = "Services"; + public static String SINTERFACEDESCRIPTION = "Interfaces"; + public static String SCONTENTDESCRIPTION = "Content"; + public static String SPROPERTYVALUEDESCRIPTION = "PropertyValues"; + + + public boolean isMethodNode(); + + public boolean isPropertyNode(); + + public boolean isContainerNode(); + + public boolean isServiceNode(); + + public boolean isInterfaceNode(); + + public String getFilter(); + + public void setFilter(String _sFilter); + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/XUnoMethodNode.java b/odk/examples/java/Inspector/XUnoMethodNode.java new file mode 100644 index 000000000..4749c92a0 --- /dev/null +++ b/odk/examples/java/Inspector/XUnoMethodNode.java @@ -0,0 +1,70 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.reflection.XIdlMethod; +import com.sun.star.uno.TypeClass; + + +public interface XUnoMethodNode extends XUnoNode { + + public XIdlMethod getXIdlMethod(); + + public boolean isInvoked(); + + public Object invoke() throws com.sun.star.uno.Exception; + + public Object invoke(Object _oUnoObject, Object[] _oParameters) throws com.sun.star.uno.Exception; + + public boolean isInvokable(); + + public boolean hasParameters(); + + public Object[] getLastParameterObjects(); + + public Object getLastUnoReturnObject(); + + public TypeClass getTypeClass(); + + public boolean isPrimitive(); + + public java.util.List getMethodObjects(); + + public boolean isFoldable(); + + public String getStandardMethodDescription(); + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/XUnoNode.java b/odk/examples/java/Inspector/XUnoNode.java new file mode 100644 index 000000000..11eba35da --- /dev/null +++ b/odk/examples/java/Inspector/XUnoNode.java @@ -0,0 +1,87 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +import com.sun.star.uno.Type; +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +public interface XUnoNode { + + public static final int nINTERFACE = 1; + public static final int nSERVICE = 2; + public static final int nOTHERS = 3; + + public String getAnchor(); + + public String getClassName(); + + public void openIdlDescription(String _sIDLUrl); + + public boolean isFilterApplicable(String _sFilter); + + public void setVisible(String _sFilter); + + public void setParameterObjects(Object[] _oParamObjects); + + public Object[] getParameterObjects(); + + public String getName(); + + public void setFoldable(boolean _bIsFoldable); + + public Object getUnoObject(); + + public XUnoNode getParentNode(); + + public void addChildNode(XUnoNode _xUnoNode); + + public void setLabel(String _sLabel); + + public String getLabel(); + + public int getChildCount(); + + public XUnoNode getChild(int _index); + + public int getNodeType(); + + // possible values are nINTERFACE, nSERVICE, nOTHERS + public void setNodeType(int _nNodeType); + + /** delivers only the Uno-Type when the NodeType is set to nINTERFACE + * otherwise (when the NodeType has not been set returns null + */ + public Type getUnoType(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/XUnoPropertyNode.java b/odk/examples/java/Inspector/XUnoPropertyNode.java new file mode 100644 index 000000000..1902a5db2 --- /dev/null +++ b/odk/examples/java/Inspector/XUnoPropertyNode.java @@ -0,0 +1,54 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.beans.Property; + + +public interface XUnoPropertyNode extends XUnoNode { + + public static int nDEFAULT = 0; + public static int nPROPERTYSETINFOTYPE = 1; + + + public Object getUnoReturnObject(); + + public int getPropertyNodeType(); + + public void setPropertyNodeType(int _nPropertyType); + + public Property getProperty(); + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Inspector/images/containers_16.png b/odk/examples/java/Inspector/images/containers_16.png new file mode 100644 index 000000000..0b4c62f11 Binary files /dev/null and b/odk/examples/java/Inspector/images/containers_16.png differ diff --git a/odk/examples/java/Inspector/images/content_16.png b/odk/examples/java/Inspector/images/content_16.png new file mode 100644 index 000000000..758169260 Binary files /dev/null and b/odk/examples/java/Inspector/images/content_16.png differ diff --git a/odk/examples/java/Inspector/images/interfaces_16.png b/odk/examples/java/Inspector/images/interfaces_16.png new file mode 100644 index 000000000..cf633ac9c Binary files /dev/null and b/odk/examples/java/Inspector/images/interfaces_16.png differ diff --git a/odk/examples/java/Inspector/images/methods_16.png b/odk/examples/java/Inspector/images/methods_16.png new file mode 100644 index 000000000..25cd8b45c Binary files /dev/null and b/odk/examples/java/Inspector/images/methods_16.png differ diff --git a/odk/examples/java/Inspector/images/properties_16.png b/odk/examples/java/Inspector/images/properties_16.png new file mode 100644 index 000000000..4e22dd1d5 Binary files /dev/null and b/odk/examples/java/Inspector/images/properties_16.png differ diff --git a/odk/examples/java/Inspector/images/services_16.png b/odk/examples/java/Inspector/images/services_16.png new file mode 100644 index 000000000..024a16ed6 Binary files /dev/null and b/odk/examples/java/Inspector/images/services_16.png differ diff --git a/odk/examples/java/Inspector/manifest.mf b/odk/examples/java/Inspector/manifest.mf new file mode 100644 index 000000000..328e8e5bc --- /dev/null +++ b/odk/examples/java/Inspector/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/odk/examples/java/MinimalComponent/BuildMinimalComponent.xml b/odk/examples/java/MinimalComponent/BuildMinimalComponent.xml new file mode 100644 index 000000000..10dfde5ec --- /dev/null +++ b/odk/examples/java/MinimalComponent/BuildMinimalComponent.xml @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/odk/examples/java/MinimalComponent/Makefile b/odk/examples/java/MinimalComponent/Makefile new file mode 100644 index 000000000..0639b1cac --- /dev/null +++ b/odk/examples/java/MinimalComponent/Makefile @@ -0,0 +1,204 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java Minimal component example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings + +# we use the sample directory name for separating this example +# from others in the output directory +SAMPLE_NAME=MinimalComponent +SAMPLE_CLASS_OUT=$(OUT_CLASS)/$(SAMPLE_NAME) +SAMPLE_GEN_OUT=$(OUT_MISC)/$(SAMPLE_NAME) + +COMP_NAME=MinimalComponent +COMP_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(COMP_NAME) +COMP_GEN_OUT=$(SAMPLE_GEN_OUT)/$(COMP_NAME) +COMP_RDB_NAME=$(COMP_NAME).uno.rdb +COMP_RDB=$(COMP_GEN_OUT)/$(COMP_RDB_NAME) +COMP_PACKAGE=$(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL=$(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME=$(COMP_NAME).uno.jar +COMP_JAR=$(SAMPLE_CLASS_OUT)/$(COMP_JAR_NAME) +COMP_JAR_MANIFEST=$(COMP_GEN_OUT)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(COMP_GEN_OUT)/META-INF/manifest.xml +COMP_REGISTERFLAG=$(COMP_GEN_OUT)$(PS)java_$(COMP_NAME)_register_component.flag +COMP_COMPONENTS=$(COMP_NAME).components + +APP1_NAME=TestMinimalComponent +APP1_CLASS_OUT=$(SAMPLE_CLASS_OUT)/$(APP1_NAME) +APP1_GEN_OUT=$(SAMPLE_GEN_OUT)/$(APP1_NAME) +APP1_JAR=$(SAMPLE_CLASS_OUT)/$(APP1_NAME).jar +APP1_JAR_MANIFEST=$(APP1_GEN_OUT)/$(APP1_NAME).mf + +IDLFILES = MinimalComponent.idl + +# normally the idl file should be stored in a directory tree fitting the module structure, +# for the example we know the module structure +PACKAGE = org/openoffice + +COMP_JAVAFILES = MinimalComponent.java +COMP_CLASSFILES = $(patsubst %.java,$(COMP_CLASS_OUT)/%.class,$(COMP_JAVAFILES)) + +GEN_CLASSFILES = $(patsubst %.idl,$(SAMPLE_CLASS_OUT)/$(PACKAGE)/%.class,$(IDLFILES)) +GEN_TYPELIST = $(subst /,.,$(patsubst %.idl,-T$(PACKAGE)/% ,$(IDLFILES))) +GEN_URDFILES = $(patsubst %.idl,$(SAMPLE_GEN_OUT)/%.urd,$(IDLFILES)) + +# the generated types are necessary for the component and the application jar +GEN_CLASSFILENAMES = $(subst $(SAMPLE_CLASS_OUT)/,,$(GEN_CLASSFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(SAMPLE_CLASS_OUT)\ + $(PATH_SEPARATOR)$(COMP_CLASS_OUT)\ + $(PATH_SEPARATOR)$(APP1_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : JavaMinimalComponentExample + +include $(SETTINGS)/stdtarget.mk + +$(COMP_GEN_OUT)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo UNO-Type-Path: $(basename $*).uno.jar> $@ + @echo RegistrationClassName: $(basename $*)>> $@ + +$(SAMPLE_GEN_OUT)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -C -I. -I$(IDL_DIR) -O$(SAMPLE_GEN_OUT) $< + +$(COMP_GEN_OUT)/%.rdb : $(GEN_URDFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(REGMERGE) $@ /UCR $(GEN_URDFILES) + +$(GEN_CLASSFILES) : $(COMP_RDB) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(JAVAMAKER) -nD $(GEN_TYPELIST) -O$(SAMPLE_CLASS_OUT) $(COMP_RDB) -X$(URE_TYPES) -X$(OFFICE_TYPES) + +# component as well as application are dependent from the generated types +# rule for component class files +$(COMP_CLASS_OUT)/%.class : %.java $(GEN_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(COMP_CLASS_OUT) $< + +# rule for example application class files +$(APP1_CLASS_OUT)/%.class : %.java $(GEN_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(APP1_CLASS_OUT) $< + +# rule for client/example application manifest file +$(APP1_GEN_OUT)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +# rule for client/example application jar file +$(APP1_JAR) : $(APP1_JAR_MANIFEST) $(APP1_CLASS_OUT)/$(APP1_NAME).class $(GEN_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(APP1_CLASS_OUT) . + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) uvf $(@F) $(GEN_CLASSFILENAMES) + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_JAR_MANIFEST) $(COMP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAR) cvfm $@ $< -C $(COMP_CLASS_OUT) . + +cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_JAR) uvf $(@F) $(GEN_CLASSFILENAMES) + +# rule for component package manifest +$(COMP_GEN_OUT)/%/manifest.xml : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo $(OSEP)?xml version="$(QM)1.0$(QM)" encoding="$(QM)UTF-8$(QM)"?$(CSEP) > $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP)>> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP)>> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-typelibrary;type=RDB$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(SAMPLE_GEN_OUT)/,,$(@D))).uno.rdb$(QM)"/$(CSEP)>> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_RDB) $(COMP_JAR) $(COMP_UNOPKG_MANIFEST) $(COMP_NAME).components + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ $(COMP_NAME).components + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u ../../../bin/$(@F) $(COMP_RDB_NAME) + cd $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_JAR_NAME) + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u ../../../bin/$(@F) META-INF/manifest.xml + +$(COMP_REGISTERFLAG) : $(COMP_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(COMP_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +JavaMinimalComponentExample : $(COMP_REGISTERFLAG) $(APP1_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) $(APP1_NAME).run + @echo ------ + @echo The $(COMP_NAME) component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the example + @echo description. + @echo -------------------------------------------------------------------------------- + +%.run: $(SAMPLE_CLASS_OUT)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(SAMPLE_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/java/MinimalComponent/MinimalComponent.components b/odk/examples/java/MinimalComponent/MinimalComponent.components new file mode 100644 index 000000000..9e413f2b6 --- /dev/null +++ b/odk/examples/java/MinimalComponent/MinimalComponent.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/java/MinimalComponent/MinimalComponent.idl b/odk/examples/java/MinimalComponent/MinimalComponent.idl new file mode 100644 index 000000000..1b63b7705 --- /dev/null +++ b/odk/examples/java/MinimalComponent/MinimalComponent.idl @@ -0,0 +1,55 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef _org_openoffice_MinimalComponent_idl_ +#define _org_openoffice_MinimalComponent_idl_ + +#include + +// org +module org { + // openoffice + module openoffice { + // example service, XServiceInfo is implemented here for demonstration + // issues. XServiceInfo must be implemented by all components. But + // here it is used to show the new code generation feature for services. + // See the TestMinimalComponent.java how it can be used! + service MinimalComponent: ::com::sun::star::lang::XServiceInfo; + }; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/MinimalComponent/MinimalComponent.java b/odk/examples/java/MinimalComponent/MinimalComponent.java new file mode 100644 index 000000000..b8efbafcc --- /dev/null +++ b/odk/examples/java/MinimalComponent/MinimalComponent.java @@ -0,0 +1,156 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.uno.XComponentContext; +import com.sun.star.lang.XInitialization; +import com.sun.star.lang.XServiceInfo; + +/** This class capsulates the class, that implements the minimal component, a + * factory for creating the service (__getComponentFactory) and a + * method, that writes the information into the given registry key + * (__writeRegistryServiceInfo). + */ +public class MinimalComponent { + /** This class implements the component. At least the interfaces XServiceInfo, + * XTypeProvider, and XInitialization should be provided by the service. + */ + public static class _MinimalComponent extends WeakBase + implements XInitialization, XServiceInfo { + /** The service name, that must be used to get an instance of this service. + */ + private static final String __serviceName = + "org.openoffice.MinimalComponent"; + + /** The initial component contextr, that gives access to + * the service manager, supported singletons, ... + * It's often later used + */ + private XComponentContext m_cmpCtx; + + /** The service manager, that gives access to all registered services. + * It's often later used + */ + private XMultiComponentFactory m_xMCF; + + /** The constructor of the inner class has a XMultiServiceFactory parameter. + * @param xCompContext A special service factory + * could be introduced while initializing. + */ + public _MinimalComponent(XComponentContext xCompContext) { + try { + m_cmpCtx = xCompContext; + m_xMCF = m_cmpCtx.getServiceManager(); + } + catch( Exception e ) { + e.printStackTrace(); + } + } + + /** This method is a member of the interface for initializing an object + * directly after its creation. + * @param object This array of arbitrary objects will be passed to the + * component after its creation. + * @throws com.sun.star.uno.Exception Every exception will not be handled, but will be + * passed to the caller. + */ + public void initialize( Object[] object ) + throws com.sun.star.uno.Exception { + /* The component describes what arguments are expected and in which + * order! At this point you can read the objects and initialize + * your component using these objects. + */ + } + + /** This method returns an array of all supported service names. + * @return Array of supported service names. + */ + public String[] getSupportedServiceNames() { + return getServiceNames(); + } + + /** This method is a simple helper function to used in the + * static component initialisation functions as well as in + * getSupportedServiceNames. + */ + private static String[] getServiceNames() { + String[] sSupportedServiceNames = { __serviceName }; + return sSupportedServiceNames; + } + + /** This method returns true, if the given service will be + * supported by the component. + * @param sServiceName Service name. + * @return True, if the given service name will be supported. + */ + public boolean supportsService( String sServiceName ) { + return sServiceName.equals( __serviceName ); + } + + /** Return the class name of the component. + * @return Class name of the component. + */ + public String getImplementationName() { + return _MinimalComponent.class.getName(); + } + } + + + /** + * Gives a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XSingleComponentFactory for creating + * the component + * @param sImplName the name of the implementation for which a + * service is desired + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleComponentFactory __getComponentFactory(String sImplName) + { + XSingleComponentFactory xFactory = null; + + if ( sImplName.equals( _MinimalComponent.class.getName() ) ) + xFactory = Factory.createComponentFactory(_MinimalComponent.class, + _MinimalComponent.getServiceNames()); + + return xFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/MinimalComponent/TestMinimalComponent.java b/odk/examples/java/MinimalComponent/TestMinimalComponent.java new file mode 100644 index 000000000..604e16163 --- /dev/null +++ b/odk/examples/java/MinimalComponent/TestMinimalComponent.java @@ -0,0 +1,67 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.lang.XServiceInfo; + +public class TestMinimalComponent { + public static void main(String args[]) { + com.sun.star.uno.XComponentContext xContext = null; + + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if( xContext != null ) + System.out.println("Connected to a running office ..."); + + XServiceInfo xSIMinimalComponent = + org.openoffice.MinimalComponent.create(xContext); + + System.out.println("\nXServiceInfo is used to get the implementation" + + " name: " + + xSIMinimalComponent.getImplementationName() + + "\nOk\n"); + xContext = null; + + System.exit(0); + } + catch( Exception e ) { + System.err.println( e ); + e.printStackTrace(); + System.exit(1); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/NotesAccess/Makefile b/odk/examples/java/NotesAccess/Makefile new file mode 100644 index 000000000..47d024db8 --- /dev/null +++ b/odk/examples/java/NotesAccess/Makefile @@ -0,0 +1,112 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java NotesAccess example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=NotesAccessExample +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +APP_NAME=NotesAccess +APP_JAR=$(OUT_APP_CLASS)/$(APP_NAME).jar + +JAVAFILES = \ + NotesAccess.java + +CLASSFILES = $(patsubst %.java,$(OUT_APP_CLASS)/%.class,$(JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : \ + JavaNotesAccessExample + +include $(SETTINGS)/stdtarget.mk + +NotesAPIs : + @echo -------------------------------------------------------------------------------- + @echo This example uses external APIs from Lotus Notes/Domino. You can download a + @echo trial version from "$(QM)http://www.lotus.com/downloads$(QM)". After installation + @echo please do the following: + @echo 1. Add the install path to the PATH or LD_LIBRARY_PATH of this shell. + @echo e.g "$(QM)PATH=C:\Program Files\lotus\notes;...$(QM)" + @echo 2. Add the "$(QM)Notes.jar$(QM)" to your CLASSPATH + @echo e.g. "$(QM)CLASSPATH=C:\Program Files\lotus\notes\Notes.jar;$(QM)" + @echo -------------------------------------------------------------------------------- + + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $(JAVAFILES) + +$(OUT_APP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Class-Path: Notes.jar> $@ + @echo Main-Class: com.sun.star.lib.loader.Loader>> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(APP_JAR) : $(OUT_APP_CLASS)/$(APP_NAME).mf $(OUT_APP_CLASS)/$(APP_NAME).class + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $(APP_NAME).mf $(APP_NAME).class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +JavaNotesAccessExample : NotesAPIs $(APP_JAR) + @echo -------------------------------------------------------------------------------- + @echo NOTE: Before you run this example make sure that the external "$(QM)Notes.jar$(QM)" can + @echo be found besides "$(QM)$(APP_JAR)"$(QM) + @echo and that the PATH variable includes the Notes installation directory. + @echo - + @echo Please use the following command to execute the example! + @echo - + @echo $(MAKE) NotesAccess.run + @echo -------------------------------------------------------------------------------- + +%.run: $(APP_JAR) + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< "$(QM)$(QM)" "$(QM)$(QM)" "$(QM)$(QM)" Stocks.nsf + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst \\,\,$(subst /,$(PS),$(OUT_APP_CLASS))) diff --git a/odk/examples/java/NotesAccess/NotesAccess.java b/odk/examples/java/NotesAccess/NotesAccess.java new file mode 100644 index 000000000..0d0a0bb5e --- /dev/null +++ b/odk/examples/java/NotesAccess/NotesAccess.java @@ -0,0 +1,282 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// Lotus Notes Domino API +import lotus.domino.NotesThread; +import lotus.domino.Session; +import lotus.domino.Database; +import lotus.domino.DocumentCollection; +import lotus.domino.Document; +import lotus.domino.NotesFactory; + +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.uno.XComponentContext; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.frame.XComponentLoader; +import com.sun.star.beans.PropertyValue; +import com.sun.star.sheet.XSpreadsheetDocument; +import com.sun.star.sheet.XSpreadsheets; +import com.sun.star.sheet.XSpreadsheet; +import com.sun.star.container.XIndexAccess; +import com.sun.star.table.XCell; + +/** This class creates an OpenOffice.org Calc spreadsheet document and fills it + * with existing values of documents from a Lotus Notes database. + */ +public class NotesAccess implements Runnable { + + /** Host server of the Domino Directory. + */ + static String stringHost = ""; + + /** User in the host's Domino Directory. + */ + static String stringUser = ""; + + /** Password for the user in the host's Domino Directory. + */ + static String stringPassword = ""; + + /** Database with documents to get data from. + */ + static String stringDatabase = ""; + + /** Reading the arguments and constructing the thread. + * @param args Holding values for the host, user, and the password of the user. + */ + public static void main( String args[] ) { + Thread thread; + + if ( args.length < 4 ) { + System.out.println( + "usage: java -jar NotesAccess.jar \"\" \"\" " + + "\"\" \"\"" ); + System.out.println( "\ne.g.:" ); + System.out.println( + "java -jar NotesAccess.jar \"\" \"\" \"\" \"Stocks.nsf\"" ); + System.exit( 1 ); + } + + if ( !args[ 0 ].trim().equals( "" ) ) { + stringHost = args[ 0 ].trim(); + } + if ( !args[ 1 ].trim().equals( "" ) ) { + stringUser = args[ 1 ].trim(); + } + stringPassword = args[ 2 ].trim(); + + try { + java.io.File sourceFile = new java.io.File(args[ 3 ].trim()); + stringDatabase = sourceFile.getCanonicalPath(); + } catch (java.io.IOException e) { + System.out.println("Error: Please check the name or path to your database file."); + e.printStackTrace(); + System.exit( 1 ); + } + + if ( stringHost.equals( "" ) ) { + // Initializing. + NotesAccess notesaccess = new NotesAccess(); + + // Allowing only local calls to the Domino classes. + thread = new NotesThread( notesaccess ); + } + else { + // Extracting the host, user, and password. + NotesAccess notesaccess = new NotesAccess(); + + // Allowing remote calls to the Domino classes. + thread = new Thread( notesaccess ); + } + + // Starting the thread. + thread.start(); + } + + /** Reading all documents from the given database and writing the data to + * an OpenOffice.org Calc spreadsheet document. + */ + public void run() { + try { + // get the remote office component context + XComponentContext xContext = + com.sun.star.comp.helper.Bootstrap.bootstrap(); + + System.out.println("Connected to a running office ..."); + + XMultiComponentFactory xMCF = xContext.getServiceManager(); + + /* A desktop environment contains tasks with one or more + frames in which components can be loaded. Desktop is the + environment for components which can instantiate within + frames. */ + XComponentLoader xLoader = UnoRuntime.queryInterface(XComponentLoader.class, + xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext)); + + // Load a Writer document, which will be automatically displayed + XComponent xComponent = xLoader.loadComponentFromURL( + "private:factory/scalc", "_blank", 0, + new PropertyValue[0] ); + + // Querying for the interface XSpreadsheetDocument + XSpreadsheetDocument xSpreadsheetDoc = + UnoRuntime.queryInterface( + XSpreadsheetDocument.class, xComponent); + + // Getting all sheets from the spreadsheet document. + XSpreadsheets xSpreadsheets = xSpreadsheetDoc.getSheets() ; + + // Querying for the interface XIndexAccess. + XIndexAccess xIndexAccess = UnoRuntime.queryInterface( + XIndexAccess.class, xSpreadsheets); + + // Getting the first spreadsheet. + XSpreadsheet xSpreadsheet = UnoRuntime.queryInterface( + XSpreadsheet.class, xIndexAccess.getByIndex(0)); + + Session session; + if ( !stringHost.equals( "" ) ) { + // Creating a Notes session for remote calls to the Domino classes. + session = NotesFactory.createSession(stringHost, stringUser, + stringPassword); + } + else { + // Creating a Notes session for only local calls to the + // Domino classes. + session = NotesFactory.createSession(); + } + + // Getting the specified Notes database. + Database database = session.getDatabase( "", stringDatabase ); + + // Getting a collection of all documents from the database. + DocumentCollection documentCollection = database.getAllDocuments(); + + // Getting the first document from the database + Document document = documentCollection.getFirstDocument(); + + // Start to write to cells at this row. + int intRowToStart = 0; + + // The current row. + int intRow = intRowToStart; + + // The current column. + int intColumn = 0; + + // Process all documents + while ( document != null ) { + // Getting the name of the stock. + String stringName = document.getItemValueString("Name"); + + // Inserting the name to a specified cell. + insertIntoCell(intColumn, intRow, stringName, xSpreadsheet, ""); + + // Getting the number of stocks. + double intNumber = document.getItemValueInteger( "Number" ); + + // Inserting the number of stocks to a specified cell. + insertIntoCell( intColumn + 1, intRow, String.valueOf(intNumber), + xSpreadsheet, "V" ); + + // Getting current share price. + double doubleSharePrice = document.getItemValueDouble("SharePrice"); + + // Inserting the current share price to a specified cell. + insertIntoCell(intColumn + 2, intRow, + String.valueOf(doubleSharePrice), + xSpreadsheet, "V"); + + // Inserting the total value. + insertIntoCell(intColumn + 3, intRow, "=B" + + ( intRow + 1 ) + + "*C" + (intRow + 1), + xSpreadsheet, ""); + + // Increasing the current row. + intRow++; + + // Getting the next document from the collection. + document = documentCollection.getNextDocument(); + } + + // Summing all specific amounts. + insertIntoCell(intColumn + 3, intRow, "=sum(D" + + ( intRowToStart + 1 ) + ":D" + + intRow, + xSpreadsheet, ""); + + xContext = null; + + // Leaving the program. + System.exit(0); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + /** Inserting a value or formula to a cell defined by the row and column. + * @param intCellX Row. + * @param intCellY Column. + * @param stringValue This value will be written to the cell. + * @param xSpreadsheet Write the value to the cells of this spreadsheet. + * @param stringFlag If this string contains "V", the value will be written, + * otherwise the formula. + */ + public static void insertIntoCell(int intCellX, int intCellY, + String stringValue, + XSpreadsheet xSpreadsheet, + String stringFlag) + { + XCell xCell = null; + + try { + xCell = xSpreadsheet.getCellByPosition( intCellX, intCellY ); + } catch ( com.sun.star.lang.IndexOutOfBoundsException exception ) { + System.out.println( "Could not get Cell" ); + } + if ( stringFlag.equals( "V" )) { + xCell.setValue((new Float(stringValue)).floatValue()); + } + else { + xCell.setFormula(stringValue); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/NotesAccess/Stocks.nsf b/odk/examples/java/NotesAccess/Stocks.nsf new file mode 100644 index 000000000..10ed138ed Binary files /dev/null and b/odk/examples/java/NotesAccess/Stocks.nsf differ diff --git a/odk/examples/java/PropertySet/Makefile b/odk/examples/java/PropertySet/Makefile new file mode 100644 index 000000000..2ab04e13e --- /dev/null +++ b/odk/examples/java/PropertySet/Makefile @@ -0,0 +1,135 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java PropertySet component example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=PropTest +COMP_CLASS_OUT=$(OUT_CLASS)/$(COMP_NAME) +COMP_GEN_OUT=$(OUT_MISC)/$(COMP_NAME) +COMP_PACKAGE=$(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL=$(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME=$(COMP_NAME).uno.jar +COMP_JAR=$(COMP_CLASS_OUT)/$(COMP_JAR_NAME) +COMP_JAR_MANIFEST=$(COMP_CLASS_OUT)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(COMP_GEN_OUT)/META-INF/manifest.xml +COMP_REGISTERFLAG=$(COMP_GEN_OUT)$(PS)java_$(COMP_NAME)_register_component.flag +COMP_COMPONENTS=$(COMP_NAME).components + +COMP_JAVAFILES = PropTest.java + +COMP_CLASSFILES = $(patsubst %.java,$(COMP_CLASS_OUT)/%.class,$(COMP_JAVAFILES)) + +$(COMP_NAME)_CLASSFILES = $(COMP_NAME).class + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(COMP_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : JavaPropertySetExample + +include $(SETTINGS)/stdtarget.mk + +$(COMP_CLASS_OUT)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo RegistrationClassName: $(basename $(basename $(@F)))> $@ + +$(COMP_CLASSFILES) : $(COMP_JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(COMP_CLASS_OUT) $(COMP_JAVAFILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_JAR_MANIFEST) $(COMP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + cd $(subst /,$(PS),$(COMP_CLASS_OUT)) && $(SDK_JAR) cvfm $(@F) $( $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_JAR) $(COMP_UNOPKG_MANIFEST) $(COMP_NAME).components + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ $(COMP_NAME).components + cd $(subst /,$(PS),$(COMP_CLASS_OUT)) && $(SDK_ZIP) -u ../../bin/$(@F) $( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +JavaPropertySetExample : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The PropTest was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo Load the "$(QM)PropertySet.odt$(QM)" document to see how this component works. You can + @echo use this component inside your office installation, see the example description. + @echo - + @echo $(MAKE) PropertySet.odt.load + @echo -------------------------------------------------------------------------------- + +PropertySet.odt.load : $(COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(COMP_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(COMP_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/java/PropertySet/PropTest.components b/odk/examples/java/PropertySet/PropTest.components new file mode 100644 index 000000000..320e3511c --- /dev/null +++ b/odk/examples/java/PropertySet/PropTest.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/java/PropertySet/PropTest.java b/odk/examples/java/PropertySet/PropTest.java new file mode 100644 index 000000000..c77a905e8 --- /dev/null +++ b/odk/examples/java/PropertySet/PropTest.java @@ -0,0 +1,262 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +/* +This example shows a UNO component that inherits com.sun.star.lib.uno.helper.PropertySet in +order to provide implementations of these interfaces: + + com.sun.star.beans.XPropertySet + com.sun.star.beans.XMultiPropertySet + com.sun.star.beans.XFastPropertySet + com.sun.star.lang.XComponent + com.sun.star.uno.XWeak + com.sun.star.lang.XTypeProvider +*/ +import com.sun.star.lib.uno.helper.PropertySet; +import com.sun.star.comp.loader.FactoryHelper; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; +import com.sun.star.registry.XRegistryKey; +import com.sun.star.uno.Any; +import com.sun.star.uno.Type; +import com.sun.star.uno.XInterface; +import com.sun.star.lang.XTypeProvider; +import com.sun.star.beans.PropertyAttribute; + +/** + This component contains the following properties: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * +
Property Name Type Name PropertyAttribute
boolABOOLEAN - + *
charACHAR -
byteABYTE -
shortASHORT -
intALONG -
longAHYPER -
floatAFLOAT -
doubleADOUBLE -
stringASTRING -
objectAANY -
anyAANY -
typeATYPE -
xinterfaceAINTERFACE -
xtypeproviderAINTERFACE -
arBoolA[]boolean -
arCharA[]char -
arByteA[]byte -
arShortA[]short -
arIntA[]long -
arLongA[]hyper -
arFloatA[]float -
arDoubleA[]double -
arStringA[]string -
arObjectA[]any -
arXinterfaceA[]com.sun.star.uno.XInterface -
ar2BoolA[][]boolean -
boolClassAboolean -
charClassAchar -
byteClassAbyte -
shortClassAshort -
intClassAlong -
longClassAhyper -
floatClassAfloat -
doubleClassAdouble -
roIntAlongREADONLY
roIntClassAlongREADONLY
roObjectAanyREADONLY
roAnyAanyREADONLY
bcBoolAbooleanBOUND,CONSTRAINED
bcBoolClassAbooleanBOUND,CONSTRAINED
bcObjectAanyBOUND,CONSTRAINED
bcAnyAanyBOUND,CONSTRAINED
mvIntAlongMAYBEVOID
mvObjectAanyMAYBEVOID
mvAnyAanyMAYBEVOID
mvXinterfaceAanyMAYBEVOID
+*/ + +public class PropTest extends PropertySet implements XServiceInfo +{ + + public boolean boolA; + public char charA; + public byte byteA; + public short shortA; + public int intA; + public long longA; + public float floatA; + public double doubleA; + public String stringA; // MAYBEVOID + public Object objectA; // MAYBEVOID + public Any anyA; // MAYBEVOID + public Type typeA;// MAYBEVOID + public XInterface xinterfaceA;// MAYBEVOID + public XTypeProvider xtypeproviderA;// MAYBEVOID + public boolean[] arBoolA; // MAYBEVOID + public char[] arCharA; // MAYBEVOID + public byte[] arByteA; // MAYBEVOID + public short[] arShortA; // MAYBEVOID + public int[] arIntA; // MAYBEVOID + public long[] arLongA; // MAYBEVOID + public float[] arFloatA; // MAYBEVOID + public double[] arDoubleA; // MAYBEVOID + public String[] arStringA; // MAYBEVOID + public Object[] arObjectA; // MAYBEVOID + public Any[] arAnyA; // MAYBEVOID + public XInterface[] arXinterfaceA; // MAYBEVOID + public boolean[][] ar2BoolA; // MAYBEVOID + public Boolean boolClassA; // MAYBEVOID + public Character charClassA; // MAYBEVOID + public Byte byteClassA; // MAYBEVOID + public Short shortClassA; // MAYBEVOID + public Integer intClassA; // MAYBEVOID + public Long longClassA; // MAYBEVOID + public Float floatClassA; // MAYBEVOID + public Double doubleClassA; // MAYBEVOID + + // readonly + public int roIntA= 100; + public Integer roIntClassA= Integer.valueOf(100); + public Object roObjectA= Integer.valueOf(101); + public Any roAnyA= new Any( new Type(int.class), Integer.valueOf(102)); + + // BOUND & CONSTRAINED + public boolean bcBoolA; + public Boolean bcBoolClassA; // MAYBEVOID + public Object bcObjectA; // MAYBEVOID + public Any bcAnyA; // MAYBEVOID + + // MAYBEVOID + public Integer mvIntA; + public Object mvObjectA; + public Any mvAnyA; + public XInterface mvXinterfaceA; + + public static final String __serviceName="PropTest"; + + public PropTest() { + registerProperty("boolA", (short) 0); + registerProperty("charA", (short) 0); + registerProperty("byteA", (short) 0); + registerProperty("shortA", (short) 0); + registerProperty("intA", (short) 0); + registerProperty("longA", (short) 0); + registerProperty("floatA", (short) 0); + registerProperty("doubleA", (short) 0); + registerProperty("stringA", PropertyAttribute.MAYBEVOID); + registerProperty("objectA", PropertyAttribute.MAYBEVOID); + registerProperty("anyA", PropertyAttribute.MAYBEVOID); + registerProperty("typeA", PropertyAttribute.MAYBEVOID); + registerProperty("xinterfaceA", PropertyAttribute.MAYBEVOID); + registerProperty("xtypeproviderA", PropertyAttribute.MAYBEVOID); + registerProperty("arBoolA", PropertyAttribute.MAYBEVOID); + registerProperty("arCharA", PropertyAttribute.MAYBEVOID); + registerProperty("arByteA", PropertyAttribute.MAYBEVOID); + registerProperty("arShortA", PropertyAttribute.MAYBEVOID); + registerProperty("arIntA", PropertyAttribute.MAYBEVOID); + registerProperty("arLongA", PropertyAttribute.MAYBEVOID); + registerProperty("arFloatA", PropertyAttribute.MAYBEVOID); + registerProperty("arDoubleA", PropertyAttribute.MAYBEVOID); + registerProperty("arStringA", PropertyAttribute.MAYBEVOID); + registerProperty("arObjectA", PropertyAttribute.MAYBEVOID); + registerProperty("arAnyA", PropertyAttribute.MAYBEVOID); + registerProperty("arXinterfaceA", PropertyAttribute.MAYBEVOID); + registerProperty("ar2BoolA", PropertyAttribute.MAYBEVOID); + registerProperty("boolClassA", PropertyAttribute.MAYBEVOID); + registerProperty("charClassA", PropertyAttribute.MAYBEVOID); + registerProperty("byteClassA", PropertyAttribute.MAYBEVOID); + registerProperty("shortClassA", PropertyAttribute.MAYBEVOID); + registerProperty("intClassA", PropertyAttribute.MAYBEVOID); + registerProperty("longClassA", PropertyAttribute.MAYBEVOID); + registerProperty("floatClassA", PropertyAttribute.MAYBEVOID); + registerProperty("doubleClassA", PropertyAttribute.MAYBEVOID); + registerProperty("roIntA", PropertyAttribute.READONLY); + registerProperty("roIntClassA", PropertyAttribute.READONLY); + registerProperty("roObjectA", PropertyAttribute.READONLY); + registerProperty("roAnyA", PropertyAttribute.READONLY); + registerProperty("bcBoolA",(short) ( PropertyAttribute.BOUND | PropertyAttribute.CONSTRAINED)); + registerProperty("bcBoolClassA", (short) (PropertyAttribute.BOUND | PropertyAttribute.CONSTRAINED | PropertyAttribute.MAYBEVOID)); + registerProperty("bcObjectA", (short) (PropertyAttribute.BOUND | PropertyAttribute.CONSTRAINED | PropertyAttribute.MAYBEVOID)); + registerProperty("bcAnyA", (short) (PropertyAttribute.BOUND | PropertyAttribute.CONSTRAINED |PropertyAttribute.MAYBEVOID)); + registerProperty("mvIntA", PropertyAttribute.MAYBEVOID); + registerProperty("mvObjectA", PropertyAttribute.MAYBEVOID); + registerProperty("mvAnyA", PropertyAttribute.MAYBEVOID); + registerProperty("mvXinterfaceA", PropertyAttribute.MAYBEVOID); + } + + + // XServiceName + public String getImplementationName( ) + { + return getClass().getName(); + } + + // XServiceName + public boolean supportsService( /*IN*/String name ) + { + if (name.equals(__serviceName)) + return true; + return false; + } + + //XServiceName + public String[] getSupportedServiceNames( ) + { + String[] retValue= new String[]{__serviceName}; + return retValue; + } + + public static XSingleServiceFactory __getServiceFactory(String implName, + XMultiServiceFactory multiFactory, + XRegistryKey regKey) + { + XSingleServiceFactory xSingleServiceFactory = null; + + if (implName.equals( PropTest.class.getName()) ) + xSingleServiceFactory = FactoryHelper.getServiceFactory( PropTest.class, + PropTest.__serviceName, + multiFactory, + regKey); + + return xSingleServiceFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/PropertySet/PropertySet.odt b/odk/examples/java/PropertySet/PropertySet.odt new file mode 100644 index 000000000..31d326e41 Binary files /dev/null and b/odk/examples/java/PropertySet/PropertySet.odt differ diff --git a/odk/examples/java/Spreadsheet/CalcAddins.components b/odk/examples/java/Spreadsheet/CalcAddins.components new file mode 100644 index 000000000..c16c4a3a9 --- /dev/null +++ b/odk/examples/java/Spreadsheet/CalcAddins.components @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/odk/examples/java/Spreadsheet/CalcAddins.java b/odk/examples/java/Spreadsheet/CalcAddins.java new file mode 100644 index 000000000..37785056e --- /dev/null +++ b/odk/examples/java/Spreadsheet/CalcAddins.java @@ -0,0 +1,283 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +// Template for an Office Calc add-in Java implementation file. + +/** You can find more + * information on the following web page: + * https://api.libreoffice.org/ + */ +import com.sun.star.comp.loader.FactoryHelper; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; +import com.sun.star.registry.XRegistryKey; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XServiceName; +import com.sun.star.sheet.XAddIn; +import com.sun.star.lang.Locale; +import org.openoffice.sheet.addin.XCalcAddins; + +/** This outer class provides an inner class to implement the service + * description, a method to instantiate the + * component on demand (__getServiceFactory()), and a method to give + * information about the component (__writeRegistryServiceInfo()). + */ +public class CalcAddins { + +/** This inner class provides the component as a concrete implementation + * of the service description. It implements the needed interfaces. + * @implements XCalcAddins, XAddIn, XServiceName, XServiceInfo, XTypeProvider + */ + public static class _CalcAddins extends WeakBase implements + XCalcAddins, + XAddIn, + XServiceName, + XServiceInfo + { + +/** The component will be registered under this name. + */ + private static final String __serviceName = "org.openoffice.sheet.addin.CalcAddins"; + + private static final String ADDIN_SERVICE = "com.sun.star.sheet.AddIn"; + + private Locale aFuncLoc; + + private static final String[] stringFunctionName = { +/** TO DO: + * You should replace these method names by the method names of your interface. + */ + "getMyFirstValue", + "getMySecondValue" + }; + +/** TO DO: + * For each of your methods you should make up a new constant with a different value. + */ + private static final short shortGETMYFIRSTVALUE = 0; + private static final short shortGETMYSECONDVALUE = 1; + +/** TO DO: + * This is where you implement all methods of your interface. The parameters have to + * be the same as in your IDL file and their types have to be the correct + * IDL-to-Java mappings of their types in the IDL file. + */ + public int getMyFirstValue( + com.sun.star.beans.XPropertySet xOptions + ) { + return 1; + } + + public int getMySecondValue( + com.sun.star.beans.XPropertySet xOptions, + int intDummy + ) { + return 2 + intDummy; + } + + // Implement method from interface XServiceName + public String getServiceName() { + return __serviceName; + } + + // Implement methods from interface XServiceInfo + public boolean supportsService(String stringServiceName) { + return( stringServiceName.equals( ADDIN_SERVICE ) || + stringServiceName.equals( __serviceName ) ); + } + + public String getImplementationName() { + return _CalcAddins.class.getName(); + } + + public String[] getSupportedServiceNames() { + String[] stringSupportedServiceNames = { ADDIN_SERVICE, __serviceName }; + return stringSupportedServiceNames; + } + + // Implement methods from interface XAddIn + public String getDisplayArgumentName(String stringProgrammaticFunctionName,int intArgument) { + String stringReturn = ""; + + switch( this.getFunctionID( stringProgrammaticFunctionName ) ) { +/** TO DO: + * You should list all argument names for each of your methods, here. + */ + case shortGETMYFIRSTVALUE: + switch( intArgument ) { + case 0: + stringReturn = "(internal)"; + break; + } + break; + case shortGETMYSECONDVALUE: + switch( intArgument ) { + case 0: + stringReturn = "(internal)"; + break; + case 1: + stringReturn = "intDummy"; + break; + } + break; + } + return stringReturn; + } + + public String getDisplayFunctionName(String stringProgrammaticName) { + String stringReturn = ""; + + switch( this.getFunctionID( stringProgrammaticName ) ) { +/** TO DO: + * Assign the name of each of your methods. + */ + case shortGETMYFIRSTVALUE: + stringReturn = "getMyFirstValue"; + break; + case shortGETMYSECONDVALUE: + stringReturn = "getMySecondValue"; + break; + } + + return stringReturn; + } + + public String getProgrammaticCategoryName(String p1) { + return "Add-In"; + } + + public String getDisplayCategoryName(String p1) { + return "Add-In"; + } + + public String getFunctionDescription(String stringProgrammaticName) { + String stringReturn = ""; + + switch( this.getFunctionID( stringProgrammaticName ) ) { +/** TO DO: + * Enter a description for each of your methods that office users will understand. + */ + case shortGETMYFIRSTVALUE: + stringReturn = "This is your first method."; + break; + case shortGETMYSECONDVALUE: + stringReturn = "This is your second method."; + break; + } + + return stringReturn; + } + + public String getArgumentDescription(String stringProgrammaticFunctionName,int intArgument) { + String stringReturn = ""; + + switch( this.getFunctionID( stringProgrammaticFunctionName ) ) { +/** TO DO: + * Enter a description for every argument of every method. Make them so that office users will understand. + */ + case shortGETMYFIRSTVALUE: + switch( intArgument ) { + case 0: + stringReturn = "(internal)"; + break; + } + break; + case shortGETMYSECONDVALUE: + switch( intArgument ) { + case 0: + stringReturn = "(internal)"; + break; + case 1: + stringReturn = "You can add this value."; + break; + } + break; + } + return stringReturn; + } + + public String getProgrammaticFuntionName(String p1) { + return ""; + } + + // Implement methods from interface XLocalizable + public Locale getLocale() { + return aFuncLoc; + } + + public void setLocale(Locale p1) { + aFuncLoc = p1; + } + + // Auxiliary functions + private short getFunctionID( String stringProgrammaticName ) { + for ( int i = 0; i < stringFunctionName.length; i++ ) { + if ( stringProgrammaticName.equals( stringFunctionName[ i ] ) ) { + return ( short ) i; + } + } + + return -1; + } + } + + /** + * Returns a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XSingleServiceFactory for creating the component + * @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 + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleServiceFactory __getServiceFactory(String implName, + XMultiServiceFactory multiFactory, + XRegistryKey regKey) { + XSingleServiceFactory xSingleServiceFactory = null; + + if (implName.equals(_CalcAddins.class.getName()) ) + xSingleServiceFactory = FactoryHelper.getServiceFactory(_CalcAddins.class, + _CalcAddins.__serviceName, + multiFactory, + regKey); + + return xSingleServiceFactory; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Spreadsheet/CalcAddins.ods b/odk/examples/java/Spreadsheet/CalcAddins.ods new file mode 100644 index 000000000..133539d5a Binary files /dev/null and b/odk/examples/java/Spreadsheet/CalcAddins.ods differ diff --git a/odk/examples/java/Spreadsheet/ChartTypeChange.java b/odk/examples/java/Spreadsheet/ChartTypeChange.java new file mode 100644 index 000000000..d436b3889 --- /dev/null +++ b/odk/examples/java/Spreadsheet/ChartTypeChange.java @@ -0,0 +1,347 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +import com.sun.star.awt.Rectangle; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.chart.XDiagram; +import com.sun.star.chart.XChartDocument; + +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XIndexAccess; + +import com.sun.star.document.XEmbeddedObjectSupplier; + +import com.sun.star.frame.XComponentLoader; + +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XMultiComponentFactory; + +import com.sun.star.sheet.XSpreadsheets; +import com.sun.star.sheet.XSpreadsheet; +import com.sun.star.sheet.XSpreadsheetDocument; +import com.sun.star.sheet.XCellRangeAddressable; + +import com.sun.star.table.XTableChart; +import com.sun.star.table.XTableCharts; +import com.sun.star.table.XCell; +import com.sun.star.table.XCellRange; +import com.sun.star.table.XTableChartsSupplier; +import com.sun.star.table.CellRangeAddress; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.XComponentContext; + + + +/** This class loads an OpenOffice.org Calc document and changes the type of the + * embedded chart. + */ +public class ChartTypeChange { + + /** Table chart, which type will be changed. + */ + private XTableChart xtablechart = null; + + /** Service factory + */ + private final XMultiComponentFactory xMCF; + + /** Component context + */ + private final XComponentContext xCompContext; + + /** Beginning of the program. + * @param args No arguments will be passed to the class. + */ + public static void main(String args[]) { + try { + ChartTypeChange charttypechange = new ChartTypeChange(); + + // Double array holding all values the chart should be based on. + String[][] stringValues = { + { "", "Jan", "Feb", "Mar", "Apr", "Mai" }, + { "Profit", "12.3", "43.2", "5.1", "76", "56.8" }, + { "Rival in business", "12.2", "12.6", "17.7", "20.4", "100" }, + }; + + // Create the chart with + charttypechange.getChart( stringValues ); + + String[] stringChartType = { + "com.sun.star.chart.LineDiagram", + "com.sun.star.chart.BarDiagram", + "com.sun.star.chart.PieDiagram", + "com.sun.star.chart.NetDiagram", + "com.sun.star.chart.XYDiagram", + "com.sun.star.chart.StockDiagram", + "com.sun.star.chart.AreaDiagram" + }; + + for ( int intCounter = 0; intCounter < stringChartType.length; + intCounter++ ) { + charttypechange.changeChartType( stringChartType[ intCounter ], + false ); + Thread.sleep( 3000 ); + } + + System.exit(0); + } + catch( Exception exception ) { + System.err.println( exception ); + } + } + + /** The constructor connects to the OpenOffice.org. + * @throws Exception All exceptions are thrown from this method. + */ + public ChartTypeChange() + throws Exception { + + /* Bootstraps a component context. Component context to be granted + to a component for running. Arbitrary values can be retrieved + from the context. */ + xCompContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + + /* Gets the service manager instance to be used (or null). This method has + been added for convenience, because the service manager is an often used + object. */ + xMCF = xCompContext.getServiceManager(); + } + + /** This method will change the type of a specified chart. + * @param stringType The chart will be converted to this type. + * @param booleanIs3D If the chart should be displayed in 3D this parameter should be set to true. + * @throws Exception All exceptions are thrown from this method. + */ + public void changeChartType( String stringType, boolean booleanIs3D ) + throws Exception { + XEmbeddedObjectSupplier xEmbeddedObjSupplier = UnoRuntime.queryInterface(XEmbeddedObjectSupplier.class, xtablechart); + XInterface xInterface = xEmbeddedObjSupplier.getEmbeddedObject(); + + XChartDocument xChartDoc = UnoRuntime.queryInterface( + XChartDocument.class, xInterface); + XDiagram xDiagram = xChartDoc.getDiagram(); + XMultiServiceFactory xMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, xChartDoc ); + Object object = xMSF.createInstance( stringType ); + xDiagram = UnoRuntime.queryInterface(XDiagram.class, object); + + XPropertySet xPropSet = UnoRuntime.queryInterface( + XPropertySet.class, xDiagram ); + xPropSet.setPropertyValue( "Dim3D", Boolean.valueOf( booleanIs3D ) ); + + xChartDoc.setDiagram(xDiagram); + } + + /** Loading an OpenOffice.org Calc document and getting a chart by name. + * @param stringFileName Name of the OpenOffice.org Calc document which should + * be loaded. + * @param stringChartName Name of the chart which should get a new chart type. + */ + public void getChart( String stringFileName, String stringChartName ) { + try { + /* A desktop environment contains tasks with one or more + frames in which components can be loaded. Desktop is the + environment for components which can instantiate within + frames. */ + XComponentLoader xComponentloader = UnoRuntime.queryInterface( XComponentLoader.class, + xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", + xCompContext ) ); + + // Load a Writer document, which will be automatically displayed + XComponent xComponent = xComponentloader.loadComponentFromURL( + "file:///" + stringFileName, "_blank", 0, + new PropertyValue[0] ); + + // Query for the interface XSpreadsheetDocument + XSpreadsheetDocument xSpreadSheetDocument = UnoRuntime.queryInterface( XSpreadsheetDocument.class, xComponent ); + + XSpreadsheets xSpreadsheets = xSpreadSheetDocument.getSheets() ; + + XIndexAccess xIndexAccess = UnoRuntime.queryInterface(XIndexAccess.class, xSpreadsheets ); + + XSpreadsheet xSpreadsheet = UnoRuntime.queryInterface( + XSpreadsheet.class, xIndexAccess.getByIndex(0)); + + XTableChartsSupplier xTableChartsSupplier = UnoRuntime.queryInterface( XTableChartsSupplier.class, xSpreadsheet ); + + xIndexAccess = UnoRuntime.queryInterface( + XIndexAccess.class, xTableChartsSupplier.getCharts() ); + + this.xtablechart = UnoRuntime.queryInterface( + XTableChart.class, xIndexAccess.getByIndex( 0 ) ); + } + catch( Exception exception ) { + System.err.println( exception ); + } + } + + /** Creating an empty OpenOffice.org Calc document, inserting data, and getting a + * chart by name. + * @param stringValues Double array with the values for the chart. + */ + public void getChart( String[][] stringValues ) { + try { + /* A desktop environment contains tasks with one or more + frames in which components can be loaded. Desktop is the + environment for components which can instantiate within + frames. */ + XComponentLoader xcomponentloader = UnoRuntime.queryInterface( XComponentLoader.class, + xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", + xCompContext ) ); + + // Create an empty calc document, which will be automatically displayed + XComponent xComponent = xcomponentloader.loadComponentFromURL( + "private:factory/scalc", "_blank", 0, + new PropertyValue[0] ); + + // Query for the interface XSpreadsheetDocument + XSpreadsheetDocument xspreadsheetdocument = UnoRuntime.queryInterface( XSpreadsheetDocument.class, xComponent ); + + // Get all sheets of the spreadsheet document. + XSpreadsheets xspreadsheets = xspreadsheetdocument.getSheets() ; + + // Get the index of the spreadsheet document. + XIndexAccess xindexaccess = UnoRuntime.queryInterface( + XIndexAccess.class, xspreadsheets ); + + // Get the first spreadsheet. + XSpreadsheet xspreadsheet = UnoRuntime.queryInterface( + XSpreadsheet.class, xindexaccess.getByIndex(0)); + + // The double array will written to the spreadsheet + for ( int intY = 0; intY < stringValues.length; intY++ ) { + for ( int intX = 0; intX < stringValues[ intY ].length; + intX++ ) { + // Insert the value to the cell, specified by intY and intX. + ChartTypeChange.insertIntoCell( intY, intX, + stringValues[ intY ][ intX ], xspreadsheet, "" ); + } + } + + // Create a rectangle, which holds the size of the chart. + Rectangle rectangle = new Rectangle(); + rectangle.X = 500; + rectangle.Y = 3000; + rectangle.Width = 25000; + rectangle.Height = 11000; + + // Get the cell range of the spreadsheet. + XCellRange xcellrange = UnoRuntime.queryInterface( + XCellRange.class, xspreadsheet ); + + // Create the Unicode of the character for the column name. + char charRectangle = ( char ) ( 65 + stringValues.length - 1 ); + + // Get maximum length all rows in the double array. + int intMaximumWidthRow = 0; + for ( int intRow = 0; intRow < stringValues.length; intRow++ ) { + if ( stringValues[ intRow ].length > intMaximumWidthRow ) { + intMaximumWidthRow = stringValues[ intRow ].length; + } + } + + // Get the cell range of the written values. + XCellRange xcellrangeChart = xcellrange.getCellRangeByName( "A1:" + + charRectangle + intMaximumWidthRow ); + + // Get the addressable cell range. + XCellRangeAddressable xcellrangeaddressable = + UnoRuntime.queryInterface( + XCellRangeAddressable.class, xcellrangeChart ); + + // Get the cell range address. + CellRangeAddress cellrangeaddress = xcellrangeaddressable.getRangeAddress(); + + // Create the cell range address for the chart. + CellRangeAddress[] cellrangeaddressChart = + new CellRangeAddress[ 1 ]; + cellrangeaddressChart[ 0 ] = cellrangeaddress; + + // Get the table charts supplier of the spreadsheet. + XTableChartsSupplier xtablechartssupplier = UnoRuntime.queryInterface( XTableChartsSupplier.class, xspreadsheet ); + + // Get all table charts of the spreadsheet. + XTableCharts xtablecharts = xtablechartssupplier.getCharts(); + + // Create a table chart with all written values. + xtablecharts.addNewByName( "Example", rectangle, + cellrangeaddressChart, true, true ); + + // Get the created table chart. + this.xtablechart = UnoRuntime.queryInterface( + XTableChart.class, UnoRuntime.queryInterface( + XNameAccess.class, xtablecharts ).getByName( "Example" )); + } + catch( Exception exception ) { + System.err.println( exception ); + } + } + + /** Inserting a given value to a cell, that is specified by the parameters intX + * and intY. + * @param intX Column on the spreadsheet. + * @param intY Row on the spreadsheet. + * @param stringValue Value to be inserted to a cell. + * @param xspreadsheet Spreadsheet of the cell, which will be changed. + * @param stringFlag If the value of stringFlag is "V", the stringValue + * will be converted to the + * float type. Otherwise the stringValue will be written as a formula. + */ + public static void insertIntoCell( int intX, int intY, String stringValue, + XSpreadsheet xspreadsheet, String stringFlag ) + { + XCell xcell = null; + + try { + xcell = xspreadsheet.getCellByPosition( intX, intY ); + } + catch ( com.sun.star.lang.IndexOutOfBoundsException exception ) { + System.out.println( "Could not get cell." ); + } + if ( stringFlag.equals( "V" ) ) { + xcell.setValue( ( new Float( stringValue ) ).floatValue() ); + } + else { + xcell.setFormula( stringValue ); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Spreadsheet/EuroAdaption.java b/odk/examples/java/Spreadsheet/EuroAdaption.java new file mode 100644 index 000000000..c6906f45b --- /dev/null +++ b/odk/examples/java/Spreadsheet/EuroAdaption.java @@ -0,0 +1,383 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +// comment: Step 1: get the Desktop object from the office +// Step 2: open an empty Calc document +// Step 3: enter an example text, set the numberformat to DM +// Step 4: change the numberformat to EUR (Euro) +// Step 5: use the DM/EUR factor on each cell with a content + + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.container.XEnumeration; +import com.sun.star.container.XIndexAccess; +import com.sun.star.container.XEnumerationAccess; + +import com.sun.star.document.XActionLockable; + +import com.sun.star.frame.XDesktop; +import com.sun.star.frame.XComponentLoader; + +import com.sun.star.lang.Locale; +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiComponentFactory; + +import com.sun.star.table.XCell; +import com.sun.star.table.XCellRange; + +import com.sun.star.sheet.XSpreadsheet; +import com.sun.star.sheet.XSpreadsheets; +import com.sun.star.sheet.XSheetCellRanges; +import com.sun.star.sheet.XCellRangesQuery; +import com.sun.star.sheet.XCellFormatRangesSupplier; +import com.sun.star.sheet.XSpreadsheetDocument; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.AnyConverter; +import com.sun.star.uno.XComponentContext; + +import com.sun.star.util.XNumberFormats; +import com.sun.star.util.XNumberFormatsSupplier; + + +public class EuroAdaption { + + public static void main(String args[]) { + // You need the desktop to create a document + // The getDesktop method does the UNO bootstrapping, gets the + // remote service manager and the desktop object. + com.sun.star.frame.XDesktop xDesktop = null; + xDesktop = getDesktop(); + + // create a sheet document + XSpreadsheetDocument xSheetdocument = null; + xSheetdocument = createSheetdocument( xDesktop ); + System.out.println( "Create a new Spreadsheet" ); + + // get the collection of all sheets from the document + XSpreadsheets xSheets = null; + xSheets = xSheetdocument.getSheets(); + + // the Action Interface provides methods to hide actions, + // like inserting data, on a sheet, that increase the performance + XActionLockable xActionInterface = null; + xActionInterface = UnoRuntime.queryInterface( + XActionLockable.class, xSheetdocument ); + + // lock all actions + xActionInterface.addActionLock(); + + com.sun.star.sheet.XSpreadsheet xSheet = null; + try { + // get via the index access the first sheet + XIndexAccess xElements = UnoRuntime.queryInterface( + XIndexAccess.class, xSheets ); + + // specify the first sheet from the spreadsheet + xSheet = UnoRuntime.queryInterface( + XSpreadsheet.class, xElements.getByIndex( 0 )); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + // get the interface to apply and create new numberformats + XNumberFormatsSupplier xNumberFormatSupplier = null; + xNumberFormatSupplier = UnoRuntime.queryInterface( + XNumberFormatsSupplier.class, xSheetdocument ); + XNumberFormats xNumberFormats = null; + xNumberFormats = xNumberFormatSupplier.getNumberFormats(); + + // insert some example data in a sheet + createExampleData( xSheet, xNumberFormats ); + System.out.println( "Insert example data and use the number format with the currency 'DM'" ); + + // Change the currency from the cells from DM to Euro + Convert( xSheet, xNumberFormats, "DM", "EUR", 1.95583f ); + System.out.println( "Change the number format to EUR and divide the values with the factor 1.95583" ); + + // remove all locks, the user see all changes + xActionInterface.removeActionLock(); + + System.out.println("done"); + System.exit(0); + } + + + public static void Convert( XSpreadsheet xSheet, XNumberFormats xNumberFormats, + String sOldSymbol, String sNewSymbol, + float fFactor ) { + try { + Locale xLanguage = new Locale(); + xLanguage.Country = "de"; // Germany -> DM + xLanguage.Language = "de"; // German + + // Numberformat string with sNewSymbol + String sSimple = "0 [$" + sNewSymbol + "]"; + // create a number format key with the sNewSymbol + int iSimpleKey = NumberFormat( xNumberFormats, sSimple, xLanguage ); + + // you have to use the FormatSupplier interface to get the + // CellFormat enumeration + XCellFormatRangesSupplier xCellFormatSupplier = + UnoRuntime.queryInterface( + XCellFormatRangesSupplier.class, xSheet ); + + // getCellFormatRanges() has the interfaces for the enumeration + XEnumerationAccess xEnumerationAccess = + UnoRuntime.queryInterface( + XEnumerationAccess.class, + xCellFormatSupplier.getCellFormatRanges() ); + + XEnumeration xRanges = xEnumerationAccess.createEnumeration(); + + while( xRanges.hasMoreElements() ) { + // the enumeration returns a cellrange + XCellRange xCellRange = UnoRuntime.queryInterface( + XCellRange.class, xRanges.nextElement()); + + // the PropertySet the get and set the properties from the cellrange + XPropertySet xCellProp = UnoRuntime.queryInterface( + XPropertySet.class, xCellRange ); + + // getPropertyValue returns an Object, you have to cast it to + // type that you need + Object oNumberObject = xCellProp.getPropertyValue( "NumberFormat" ); + int iNumberFormat = AnyConverter.toInt(oNumberObject); + + // get the properties from the cellrange numberformat + XPropertySet xFormat = xNumberFormats.getByKey(iNumberFormat ); + + short fType = AnyConverter.toShort(xFormat.getPropertyValue("Type")); + String sCurrencySymbol = AnyConverter.toString( + xFormat.getPropertyValue("CurrencySymbol")); + + // change the numberformat only on cellranges with a + // currency numberformat + if( ( (fType & com.sun.star.util.NumberFormat.CURRENCY) > 0) && + ( sCurrencySymbol.equals( sOldSymbol ) ) ) { + boolean bThousandSep = AnyConverter.toBoolean( + xFormat.getPropertyValue("ThousandsSeparator")); + boolean bNegativeRed = AnyConverter.toBoolean( + xFormat.getPropertyValue("NegativeRed")); + short fDecimals = AnyConverter.toShort( + xFormat.getPropertyValue("Decimals")); + short fLeadingZeros = AnyConverter.toShort( + xFormat.getPropertyValue("LeadingZeros")); + Locale oLocale = (Locale) AnyConverter.toObject( + new com.sun.star.uno.Type(Locale.class), + xFormat.getPropertyValue("Locale")); + + // create a new numberformat string + String sNew = xNumberFormats.generateFormat( iSimpleKey, + oLocale, bThousandSep, bNegativeRed, + fDecimals, fLeadingZeros ); + + // get the NumberKey from the numberformat + int iNewNumberFormat = NumberFormat( xNumberFormats, + sNew, oLocale ); + + // set the new numberformat to the cellrange DM->EUR + xCellProp.setPropertyValue( "NumberFormat", + Integer.valueOf( iNewNumberFormat ) ); + + // iterate over all cells from the cellrange with an + // content and use the DM/EUR factor + XCellRangesQuery xCellRangesQuery = UnoRuntime.queryInterface( + XCellRangesQuery.class, xCellRange ); + + XSheetCellRanges xSheetCellRanges = + xCellRangesQuery.queryContentCells( + (short) com.sun.star.sheet.CellFlags.VALUE ); + + if( xSheetCellRanges.getCount() > 0 ) { + XEnumerationAccess xCellEnumerationAccess = + xSheetCellRanges.getCells(); + XEnumeration xCellEnumeration = + xCellEnumerationAccess.createEnumeration(); + + while( xCellEnumeration.hasMoreElements() ) { + XCell xCell = UnoRuntime.queryInterface( + XCell.class, xCellEnumeration.nextElement()); + xCell.setValue( xCell.getValue() / fFactor ); + } + } + } + } + } + catch( Exception e) { + e.printStackTrace(System.err); + } + } + + + public static int NumberFormat( XNumberFormats xNumberFormat, String sFormat, + com.sun.star.lang.Locale xLanguage ) { + int nRetKey = 0; + + try { + // exists the numberformat + nRetKey = xNumberFormat.queryKey( sFormat, xLanguage, true ); + + // if not, create a new one + if( nRetKey == -1 ) { + nRetKey = xNumberFormat.addNew( sFormat, xLanguage ); + if( nRetKey == -1 ) + nRetKey = 0; + } + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return nRetKey; + } + + + public static void createExampleData( XSpreadsheet xSheet, + XNumberFormats xNumberFormat ) { + + // enter in a cellrange numbers and change the numberformat to DM + XCell xCell = null; + XCellRange xCellRange = null; + + try { + Locale xLanguage = new Locale(); + xLanguage.Country = "de"; // Germany -> DM + xLanguage.Language = "de"; // German + + // Numberformat string from DM + String sSimple = "0 [$DM]"; + + // get the numberformat key + int iNumberFormatKey = NumberFormat(xNumberFormat, sSimple, xLanguage); + + for( int iCounter=1; iCounter < 10; iCounter++ ) { + // get one cell and insert a number + xCell = xSheet.getCellByPosition( 2, 1 + iCounter ); + xCell.setValue( (double) iCounter * 2 ); + xCellRange = xSheet.getCellRangeByPosition( 2, 1 + iCounter, + 2, 1 + iCounter ); + + // get the PropertySet from the cell, to change the numberformat + XPropertySet xCellProp = UnoRuntime.queryInterface( + XPropertySet.class, xCellRange ); + xCellProp.setPropertyValue( "NumberFormat", + Integer.valueOf(iNumberFormatKey) ); + } + } + catch( Exception e) { + e.printStackTrace(System.err); + } + } + + public static XDesktop getDesktop() { + XDesktop xDesktop = null; + XMultiComponentFactory xMCF = null; + + try { + XComponentContext xContext = null; + + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + + // get the remote office service manager + xMCF = xContext.getServiceManager(); + if( xMCF != null ) { + System.out.println("Connected to a running office ..."); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + xDesktop = UnoRuntime.queryInterface( + XDesktop.class, oDesktop); + } + else + System.out.println( "Can't create a desktop. No connection, no remote servicemanager available!" ); + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + + return xDesktop; + } + + + public static XSpreadsheetDocument createSheetdocument( XDesktop xDesktop ) { + XSpreadsheetDocument aSheetDocument = null; + + try { + XComponent xComponent = null; + xComponent = CreateNewDocument( xDesktop, "scalc" ); + + aSheetDocument = UnoRuntime.queryInterface( + XSpreadsheetDocument.class, xComponent); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return aSheetDocument; + } + + protected static XComponent CreateNewDocument( XDesktop xDesktop, + String sDocumentType ) { + String sURL = "private:factory/" + sDocumentType; + + XComponent xComponent = null; + XComponentLoader xComponentLoader = null; + PropertyValue xEmptyArgs[] = new PropertyValue[0]; + + try { + xComponentLoader = UnoRuntime.queryInterface( + XComponentLoader.class, xDesktop ); + + xComponent = xComponentLoader.loadComponentFromURL( + sURL, "_blank", 0, xEmptyArgs); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return xComponent ; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Spreadsheet/Makefile b/odk/examples/java/Spreadsheet/Makefile new file mode 100644 index 000000000..e24662849 --- /dev/null +++ b/odk/examples/java/Spreadsheet/Makefile @@ -0,0 +1,214 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java Spreadsheet examples of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=JavaSpreadsheetExamples +OUT_COMP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) +OUT_COMP_GEN = $(OUT_MISC)/$(EXAMPLE_NAME) + +APP1_NAME=EuroAdaption +APP1_JAR=$(OUT_COMP_CLASS)/$(APP1_NAME).jar +APP2_NAME=SCalc +APP2_JAR=$(OUT_COMP_CLASS)/$(APP2_NAME).jar +APP3_NAME=ChartTypeChange +APP3_JAR=$(OUT_COMP_CLASS)/$(APP3_NAME).jar + +COMP_NAME=CalcAddins +COMP_RDB_NAME=$(COMP_NAME).uno.rdb +COMP_RDB=$(OUT_COMP_GEN)/$(COMP_RDB_NAME) +COMP_PACKAGE=$(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL=$(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME=$(COMP_NAME).uno.jar +COMP_JAR=$(OUT_COMP_CLASS)/$(COMP_JAR_NAME) +COMP_MANIFESTFILE=$(OUT_COMP_CLASS)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(OUT_COMP_CLASS)/$(COMP_NAME)/META-INF/manifest.xml +COMP_REGISTERFLAG=$(OUT_MISC)$(PS)java_$(COMP_NAME)_register_component.flag +COMP_COMPONENTS=$(COMP_NAME).components + +IDLFILES = XCalcAddins.idl + +# normally the idl file should be stored in a directory tree fitting the module structure, +# for the example we know the module structure +PACKAGE = org/openoffice/sheet/addin + +COMPJAVAFILES = CalcAddins.java + +#GENJAVAFILES = $(patsubst %.idl,$(OUT_COMP_GEN)/$(PACKAGE)/%.java,$(IDLFILES)) +GENCLASSFILES = $(patsubst %.idl,$(OUT_COMP_CLASS)/$(PACKAGE)/%.class,$(IDLFILES)) +GENTYPELIST = $(subst /,.,$(patsubst %.idl,-T$(PACKAGE)/% ,$(IDLFILES))) +GENURDFILES = $(patsubst %.idl,$(OUT_COMP_GEN)/%.urd,$(IDLFILES)) + +COMPCLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(COMPJAVAFILES)) +#COMPCLASSFILES += $(subst $(OUT_COMP_GEN),$(OUT_COMP_CLASS),$(GENJAVAFILES:.java=.class)) + +$(COMP_NAME)_CLASSFILES = $(COMP_NAME).class \ + $(COMP_NAME)$(QUOTE)$$_$(COMP_NAME).class + +#$(COMP_NAME)_CLASSFILES += $(subst $(OUT_COMP_GEN)/,,$(GENJAVAFILES:.java=.class)) +$(COMP_NAME)_CLASSFILES += $(subst $(OUT_COMP_CLASS)/,,$(GENCLASSFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + +# Targets +.PHONY: ALL +ALL : $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +# rule for a component manifest file +$(OUT_COMP_CLASS)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo UNO-Type-Path: $(basename $*).uno.jar> $@ + @echo RegistrationClassName: $(basename $*)>> $@ + +$(OUT_COMP_GEN)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -C -I. -I$(IDL_DIR) -O$(OUT_COMP_GEN) $< + +$(OUT_COMP_GEN)/%.rdb : $(GENURDFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(REGMERGE) $@ /UCR $(GENURDFILES) + +#$(OUT_COMP_GEN)/%.java : $(COMP_RDB) +$(GENCLASSFILES) : $(COMP_RDB) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(JAVAMAKER) -nD $(GENTYPELIST) -O$(OUT_COMP_CLASS) $(COMP_RDB) -X$(URE_TYPES) -X$(OFFICE_TYPES) + +$(OUT_COMP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $< + +# only the component depends on the generated types +$(COMPCLASSFILES) : $(JAVAFILES) $(GENCLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(COMPJAVAFILES) + +# rule for client/example application manifest file +$(OUT_COMP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +# rule for client/example application jar file +$(OUT_COMP_CLASS)/%.jar : $(OUT_COMP_CLASS)/%.mf $(OUT_COMP_CLASS)/%.class + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_MANIFESTFILE) $(COMPCLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_JAR) cvfm $(@F) $( $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-typelibrary;type=RDB$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(OUT_COMP_CLASS)/,,$(@D))).uno.rdb$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_RDB) $(COMP_JAR) $(COMP_UNOPKG_MANIFEST) $(COMP_NAME).components + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(COPY) $(subst /,$(PS),$<) $(subst /,$(PS),$(OUT_COMP_CLASS)) + $(SDK_ZIP) $@ -u $(COMP_NAME).components + cd $(subst /,$(PS),$(OUT_COMP_CLASS)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_RDB_NAME) $(COMP_JAR_NAME) + cd $(subst /,$(PS),$(OUT_COMP_CLASS)/$(subst .$(UNOOXT_EXT),,$(@F))) && $(SDK_ZIP) -u ../../../bin/$(@F) META-INF/manifest.xml + $(DEL) $(subst \\,\,$(subst /,$(PS),$(OUT_COMP_CLASS)/$( $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +$(APP1_JAR) : $(OUT_COMP_CLASS)/$(APP1_NAME).mf $(OUT_COMP_CLASS)/$(APP1_NAME).class +$(APP2_JAR) : $(OUT_COMP_CLASS)/$(APP2_NAME).mf $(OUT_COMP_CLASS)/$(APP2_NAME).class +$(APP3_JAR) : $(OUT_COMP_CLASS)/$(APP3_NAME).mf $(OUT_COMP_CLASS)/$(APP3_NAME).class + +$(EXAMPLE_NAME) : $(COMP_REGISTERFLAG) $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) + @echo -------------------------------------------------------------------------------- + @echo Please use the following command to execute the examples! + @echo - + @echo $(MAKE) EuroAdaption.run + @echo $(MAKE) SCalc.run + @echo $(MAKE) ChartTypeChange.run + @echo -------------------------------------------------------------------------------- + @echo The Calc add-in component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo You can use this component inside your office installation, see the example + @echo description. You can also load the "$(QM)CalcAddins.ods$(QM)" document to see + @echo how the add-in functions works. + @echo - + @echo $(MAKE) CalcAddins.ods.load + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +CalcAddins.ods.load : $(COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_GEN)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_REGISTERFLAG))) diff --git a/odk/examples/java/Spreadsheet/SCalc.java b/odk/examples/java/Spreadsheet/SCalc.java new file mode 100644 index 000000000..90c5ce00f --- /dev/null +++ b/odk/examples/java/Spreadsheet/SCalc.java @@ -0,0 +1,408 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +// comment: Step 1: get the remote component context from the office +// Step 2: open an empty calc document +// Step 3: create cell styles +// Step 4: get the sheet an insert some data +// Step 5: apply the created cell styles +// Step 6: insert a 3D Chart + + +import com.sun.star.awt.Rectangle; + +import com.sun.star.beans.PropertyValue; +import com.sun.star.beans.XPropertySet; + +import com.sun.star.chart.XDiagram; +import com.sun.star.chart.XChartDocument; + +import com.sun.star.container.XIndexAccess; +import com.sun.star.container.XNameAccess; +import com.sun.star.container.XNameContainer; + +import com.sun.star.document.XEmbeddedObjectSupplier; + +import com.sun.star.frame.XComponentLoader; + +import com.sun.star.lang.XComponent; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XMultiComponentFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XInterface; +import com.sun.star.uno.XComponentContext; + +import com.sun.star.sheet.XCellRangeAddressable; +import com.sun.star.sheet.XSpreadsheet; +import com.sun.star.sheet.XSpreadsheets; +import com.sun.star.sheet.XSpreadsheetDocument; + +import com.sun.star.style.XStyleFamiliesSupplier; + +import com.sun.star.table.CellRangeAddress; +import com.sun.star.table.XCell; +import com.sun.star.table.XCellRange; +import com.sun.star.table.XTableChart; +import com.sun.star.table.XTableCharts; +import com.sun.star.table.XTableChartsSupplier; + + +public class SCalc { + + public static void main(String args[]) { + + //oooooooooooooooooooooooooooStep 1oooooooooooooooooooooooooooooooooooooooooo + // call UNO bootstrap method and get the remote component context form + // the a running office (office will be started if necessary) + + XComponentContext xContext = null; + + // get the remote office component context + try { + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + } catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + //oooooooooooooooooooooooooooStep 2oooooooooooooooooooooooooooooooooooooooooo + // open an empty document. In this case it's a calc document. + // For this purpose an instance of com.sun.star.frame.Desktop + // is created. The desktop provides the XComponentLoader interface, + // which is used to open the document via loadComponentFromURL + + + //Open document + + //Calc + XSpreadsheetDocument myDoc = null; +// XCell oCell = null; + + System.out.println("Opening an empty Calc document"); + myDoc = openCalc(xContext); + + + + + //oooooooooooooooooooooooooooStep 3oooooooooooooooooooooooooooooooooooooooooo + // create cell styles. + // For this purpose get the StyleFamiliesSupplier and the family + // CellStyle. Create an instance of com.sun.star.style.CellStyle and + // add it to the family. Now change some properties + + + try { + XStyleFamiliesSupplier xSFS = UnoRuntime.queryInterface(XStyleFamiliesSupplier.class, myDoc); + XNameAccess xSF = xSFS.getStyleFamilies(); + XNameAccess xCS = UnoRuntime.queryInterface( + XNameAccess.class, xSF.getByName("CellStyles")); + XMultiServiceFactory oDocMSF = UnoRuntime.queryInterface(XMultiServiceFactory.class, myDoc ); + XNameContainer oStyleFamilyNameContainer = UnoRuntime.queryInterface( + XNameContainer.class, xCS); + XInterface oInt1 = (XInterface) oDocMSF.createInstance( + "com.sun.star.style.CellStyle"); + oStyleFamilyNameContainer.insertByName("My Style", oInt1); + XPropertySet oCPS1 = UnoRuntime.queryInterface( + XPropertySet.class, oInt1 ); + oCPS1.setPropertyValue("IsCellBackgroundTransparent", Boolean.FALSE); + oCPS1.setPropertyValue("CellBackColor",Integer.valueOf(6710932)); + oCPS1.setPropertyValue("CharColor",Integer.valueOf(16777215)); + XInterface oInt2 = (XInterface) oDocMSF.createInstance( + "com.sun.star.style.CellStyle"); + oStyleFamilyNameContainer.insertByName("My Style2", oInt2); + XPropertySet oCPS2 = UnoRuntime.queryInterface( + XPropertySet.class, oInt2 ); + oCPS2.setPropertyValue("IsCellBackgroundTransparent", Boolean.FALSE); + oCPS2.setPropertyValue("CellBackColor",Integer.valueOf(13421823)); + } catch (Exception e) { + e.printStackTrace(System.err); + } + + + + //oooooooooooooooooooooooooooStep 4oooooooooooooooooooooooooooooooooooooooooo + // get the sheet an insert some data. + // Get the sheets from the document and then the first from this container. + // Now some data can be inserted. For this purpose get a Cell via + // getCellByPosition and insert into this cell via setValue() (for floats) + // or setFormula() for formulas and Strings + + + + XSpreadsheet xSheet=null; + + try { + System.out.println("Getting spreadsheet") ; + XSpreadsheets xSheets = myDoc.getSheets() ; + XIndexAccess oIndexSheets = UnoRuntime.queryInterface( + XIndexAccess.class, xSheets); + xSheet = UnoRuntime.queryInterface( + XSpreadsheet.class, oIndexSheets.getByIndex(0)); + + } catch (Exception e) { + System.out.println("Couldn't get Sheet " +e); + e.printStackTrace(System.err); + } + + + + System.out.println("Creating the Header") ; + + insertIntoCell(1,0,"JAN",xSheet,""); + insertIntoCell(2,0,"FEB",xSheet,""); + insertIntoCell(3,0,"MAR",xSheet,""); + insertIntoCell(4,0,"APR",xSheet,""); + insertIntoCell(5,0,"MAI",xSheet,""); + insertIntoCell(6,0,"JUN",xSheet,""); + insertIntoCell(7,0,"JUL",xSheet,""); + insertIntoCell(8,0,"AUG",xSheet,""); + insertIntoCell(9,0,"SEP",xSheet,""); + insertIntoCell(10,0,"OCT",xSheet,""); + insertIntoCell(11,0,"NOV",xSheet,""); + insertIntoCell(12,0,"DEC",xSheet,""); + insertIntoCell(13,0,"SUM",xSheet,""); + + + System.out.println("Fill the lines"); + + insertIntoCell(0,1,"Smith",xSheet,""); + insertIntoCell(1,1,"42",xSheet,"V"); + insertIntoCell(2,1,"58.9",xSheet,"V"); + insertIntoCell(3,1,"-66.5",xSheet,"V"); + insertIntoCell(4,1,"43.4",xSheet,"V"); + insertIntoCell(5,1,"44.5",xSheet,"V"); + insertIntoCell(6,1,"45.3",xSheet,"V"); + insertIntoCell(7,1,"-67.3",xSheet,"V"); + insertIntoCell(8,1,"30.5",xSheet,"V"); + insertIntoCell(9,1,"23.2",xSheet,"V"); + insertIntoCell(10,1,"-97.3",xSheet,"V"); + insertIntoCell(11,1,"22.4",xSheet,"V"); + insertIntoCell(12,1,"23.5",xSheet,"V"); + insertIntoCell(13,1,"=SUM(B2:M2)",xSheet,""); + + + insertIntoCell(0,2,"Jones",xSheet,""); + insertIntoCell(1,2,"21",xSheet,"V"); + insertIntoCell(2,2,"40.9",xSheet,"V"); + insertIntoCell(3,2,"-57.5",xSheet,"V"); + insertIntoCell(4,2,"-23.4",xSheet,"V"); + insertIntoCell(5,2,"34.5",xSheet,"V"); + insertIntoCell(6,2,"59.3",xSheet,"V"); + insertIntoCell(7,2,"27.3",xSheet,"V"); + insertIntoCell(8,2,"-38.5",xSheet,"V"); + insertIntoCell(9,2,"43.2",xSheet,"V"); + insertIntoCell(10,2,"57.3",xSheet,"V"); + insertIntoCell(11,2,"25.4",xSheet,"V"); + insertIntoCell(12,2,"28.5",xSheet,"V"); + insertIntoCell(13,2,"=SUM(B3:M3)",xSheet,""); + + insertIntoCell(0,3,"Brown",xSheet,""); + insertIntoCell(1,3,"31.45",xSheet,"V"); + insertIntoCell(2,3,"-20.9",xSheet,"V"); + insertIntoCell(3,3,"-117.5",xSheet,"V"); + insertIntoCell(4,3,"23.4",xSheet,"V"); + insertIntoCell(5,3,"-114.5",xSheet,"V"); + insertIntoCell(6,3,"115.3",xSheet,"V"); + insertIntoCell(7,3,"-171.3",xSheet,"V"); + insertIntoCell(8,3,"89.5",xSheet,"V"); + insertIntoCell(9,3,"41.2",xSheet,"V"); + insertIntoCell(10,3,"71.3",xSheet,"V"); + insertIntoCell(11,3,"25.4",xSheet,"V"); + insertIntoCell(12,3,"38.5",xSheet,"V"); + insertIntoCell(13,3,"=SUM(A4:L4)",xSheet,""); + + + + //oooooooooooooooooooooooooooStep 5oooooooooooooooooooooooooooooooooooooooooo + // apply the created cell style. + // For this purpose get the PropertySet of the Cell and change the + // property CellStyle to the appropriate value. + + + // change backcolor + chgbColor( 1 , 0, 13, 0, "My Style", xSheet ); + chgbColor( 0 , 1, 0, 3, "My Style", xSheet ); + chgbColor( 1 , 1, 13, 3, "My Style2", xSheet ); + + + + //oooooooooooooooooooooooooooStep 6oooooooooooooooooooooooooooooooooooooooooo + // insert a 3D chart. + // get the CellRange which holds the data for the chart and its RangeAddress + // get the TableChartSupplier from the sheet and then the TableCharts from it. + // add a new chart based on the data to the TableCharts. + // get the ChartDocument, which provide the Diagram. Change the properties + // Dim3D (3 dimension) and String (the title) of the diagram. + + + // insert a chart + + Rectangle oRect = new Rectangle(); + oRect.X = 500; + oRect.Y = 3000; + oRect.Width = 25000; + oRect.Height = 11000; + + XCellRange oRange = UnoRuntime.queryInterface( + XCellRange.class, xSheet); + XCellRange myRange = oRange.getCellRangeByName("A1:N4"); + XCellRangeAddressable oRangeAddr = UnoRuntime.queryInterface(XCellRangeAddressable.class, myRange); + CellRangeAddress myAddr = oRangeAddr.getRangeAddress(); + + CellRangeAddress[] oAddr = new CellRangeAddress[1]; + oAddr[0] = myAddr; + XTableChartsSupplier oSupp = UnoRuntime.queryInterface( + XTableChartsSupplier.class, xSheet); + + XTableChart oChart = null; + + System.out.println("Insert Chart"); + + XTableCharts oCharts = oSupp.getCharts(); + oCharts.addNewByName("Example", oRect, oAddr, true, true); + + // get the diagram and change some of the properties + + try { + oChart = (UnoRuntime.queryInterface( + XTableChart.class, UnoRuntime.queryInterface( + XNameAccess.class, oCharts).getByName("Example"))); + XEmbeddedObjectSupplier oEOS = UnoRuntime.queryInterface(XEmbeddedObjectSupplier.class, oChart); + XInterface oInt = oEOS.getEmbeddedObject(); + XChartDocument xChart = UnoRuntime.queryInterface( + XChartDocument.class,oInt); + XDiagram oDiag = xChart.getDiagram(); + System.out.println("Change Diagram to 3D"); + XPropertySet oCPS = UnoRuntime.queryInterface( + XPropertySet.class, oDiag ); + oCPS.setPropertyValue("Dim3D", Boolean.TRUE); + System.out.println("Change the title"); + Thread.sleep(200); + XPropertySet oTPS = UnoRuntime.queryInterface( + XPropertySet.class, xChart.getTitle() ); + oTPS.setPropertyValue("String","The new title"); + } catch (Exception e){ + System.err.println("Changing Properties failed "+e); + e.printStackTrace(System.err); + } + + System.out.println("done"); + System.exit(0); + } + + public static XSpreadsheetDocument openCalc(XComponentContext xContext) + { + //define variables + XMultiComponentFactory xMCF = null; + XComponentLoader xCLoader; + XSpreadsheetDocument xSpreadSheetDoc = null; + XComponent xComp = null; + + try { + // get the service manager from the office + xMCF = xContext.getServiceManager(); + + // create a new instance of the desktop + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext ); + + // query the desktop object for the XComponentLoader + xCLoader = UnoRuntime.queryInterface( + XComponentLoader.class, oDesktop ); + + PropertyValue [] szEmptyArgs = new PropertyValue [0]; + String strDoc = "private:factory/scalc"; + + xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs ); + xSpreadSheetDoc = UnoRuntime.queryInterface( + XSpreadsheetDocument.class, xComp); + + } catch(Exception e){ + System.err.println(" Exception " + e); + e.printStackTrace(System.err); + } + + return xSpreadSheetDoc; + } + + + public static void insertIntoCell(int CellX, int CellY, String theValue, + XSpreadsheet TT1, String flag) + { + XCell xCell = null; + + try { + xCell = TT1.getCellByPosition(CellX, CellY); + } catch (com.sun.star.lang.IndexOutOfBoundsException ex) { + System.err.println("Could not get Cell"); + ex.printStackTrace(System.err); + } + + if (flag.equals("V")) { + xCell.setValue((new Float(theValue)).floatValue()); + } else { + xCell.setFormula(theValue); + } + + } + + public static void chgbColor( int x1, int y1, int x2, int y2, + String template, XSpreadsheet TT ) + { + XCellRange xCR = null; + try { + xCR = TT.getCellRangeByPosition(x1,y1,x2,y2); + } catch (com.sun.star.lang.IndexOutOfBoundsException ex) { + System.err.println("Could not get CellRange"); + ex.printStackTrace(System.err); + } + + XPropertySet xCPS = UnoRuntime.queryInterface( + XPropertySet.class, xCR ); + + try { + xCPS.setPropertyValue("CellStyle", template); + } catch (Exception e) { + System.err.println("Can't change colors chgbColor" + e); + e.printStackTrace(System.err); + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Spreadsheet/XCalcAddins.idl b/odk/examples/java/Spreadsheet/XCalcAddins.idl new file mode 100644 index 000000000..79767b12c --- /dev/null +++ b/odk/examples/java/Spreadsheet/XCalcAddins.idl @@ -0,0 +1,103 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ +#ifndef INCLUDED_ORG_OPENOFFICE_SHEET_ADDIN_XCALCADDIN_IDL +#define INCLUDED_ORG_OPENOFFICE_SHEET_ADDIN_XCALCADDIN_IDL + +#include +#include + + +module org { + module openoffice { + module sheet { + module addin { + /** Interface with your additional methods. + + You may declare several methods. Each method may have + any number of arguments after xOptions. + Furthermore, you could replace the name of the service and + the interface, but only if you want to replace this name in all + your project files. This example will work with the necessary default + names. + Interface names should start with an X prefix. + */ + interface XCalcAddins + { + /** Declare your methods: + This is where you could add the declarations of your methods. + If you want to learn more about + the IDL syntax including the base types, you could + visit the following web page: + http://www.openoffice.org/project/udk/common/man/idl_syntax.html . + */ + long getMyFirstValue( + /** Parameters: + You could insert further arguments after the + parameter xOptions. + */ + [in] com::sun::star::beans::XPropertySet xOptions + ); + + long getMySecondValue( + /** Parameters: + You could insert further arguments after the + parameter xOptions. + */ + [in] com::sun::star::beans::XPropertySet xOptions, + [in] long intDummy + ); + }; + + service CalcAddins + { + /** Exported interfaces: + This is where you put all interfaces that this service exports. The service + supports its main interface only. + */ + interface XCalcAddins; + + /** Necessary base service. + All add-ins must implement this service + */ + service com::sun::star::sheet::AddIn; + }; + }; + }; + }; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/Makefile b/odk/examples/java/Storage/Makefile new file mode 100644 index 000000000..3bf990b5d --- /dev/null +++ b/odk/examples/java/Storage/Makefile @@ -0,0 +1,75 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# + +# Builds the Java Storage test example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMPONENT_NAME=JavaStorageTestExample +OUT_COMP_CLASS = $(OUT_CLASS)/$(COMPONENT_NAME) + +JAVAFILES = \ + StorageFunctionality.java \ + TestHelper.java \ + StorageTest.java \ + Test01.java \ + Test02.java \ + Test03.java \ + Test04.java \ + Test05.java \ + Test06.java \ + Test07.java \ + Test08.java \ + Test09.java + +CLASSFILES = $(patsubst %.java,$(OUT_COMP_CLASS)/%.class,$(JAVAFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_COMP_CLASS)) + + +# Targets +.PHONY: ALL +ALL : \ + JavaStorageTestExample + +include $(SETTINGS)/stdtarget.mk + +$(CLASSFILES) : $(JAVAFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_COMP_CLASS) $(JAVAFILES) + +JavaStorageTestExample : $(CLASSFILES) + @echo -------------------------------------------------------------------------------- + @echo Please use following command to execute the example! + @echo ------ + @echo $(MAKE) StorageFunctionality.run + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_COMP_CLASS)/%.class + $(SDK_JAVA) -classpath "$(SDK_CLASSPATH)" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_COMP_CLASS)) + diff --git a/odk/examples/java/Storage/StorageFunctionality.java b/odk/examples/java/Storage/StorageFunctionality.java new file mode 100644 index 000000000..5b848019b --- /dev/null +++ b/odk/examples/java/Storage/StorageFunctionality.java @@ -0,0 +1,156 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.bridge.XUnoUrlResolver; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XNamingService; +import com.sun.star.uno.XComponentContext; + +import com.sun.star.lang.*; + +public class StorageFunctionality { + + public static void main( String args[] ) + { + // connect to the office + String sConnectionString = "uno:socket,host=localhost,port=8100;urp;StarOffice.NamingService"; + + // It is possible to use a different connection string, passed as argument + if ( args.length == 1 ) { + sConnectionString = args[0]; + } + + XMultiServiceFactory xMSF = null; + + // create connection(s) and get multiservicefactory + try { + xMSF = connect( sConnectionString ); + + if ( xMSF == null ) + { + System.out.println( "Error: Couldn't get MSF!" ); + return; + } + } catch( Exception e ) { + System.out.println( "Error: Couldn't get MSF, exception: " + e ); + return; + } + + XSingleServiceFactory xStorageFactory = null; + try + { + Object oStorageFactory = xMSF.createInstance( "com.sun.star.embed.StorageFactory" ); + xStorageFactory = UnoRuntime.queryInterface( XSingleServiceFactory.class, + oStorageFactory ); + + if ( xStorageFactory == null ) + { + System.out.println( "Error: Can not get storage factory!" ); + return; + } + } + catch ( Exception e ) + { + System.out.println( "Error: Can't get storage factory, exception: " + e + "!" ); + return; + } + + boolean bTestsPassed = true; + + final int nNumTests = 9; + StorageTest pTests[] = new StorageTest[nNumTests]; + pTests[0] = new Test01( xMSF, xStorageFactory ); + pTests[1] = new Test02( xMSF, xStorageFactory ); + pTests[2] = new Test03( xMSF, xStorageFactory ); + pTests[3] = new Test04( xMSF, xStorageFactory ); + pTests[4] = new Test05( xMSF, xStorageFactory ); + pTests[5] = new Test06( xMSF, xStorageFactory ); + pTests[6] = new Test07( xMSF, xStorageFactory ); + pTests[7] = new Test08( xMSF, xStorageFactory ); + pTests[8] = new Test09( xMSF, xStorageFactory ); + + System.out.println( "\nstart testing\n" ); + + for ( int nInd = 0; nInd < nNumTests; nInd++ ) + { + String sTestName = "Test" + ( ( nInd < 9 ) ? "0" : "" ) + ( nInd + 1 ); + + System.out.println( "======= Storage test " + sTestName + " started!" ); + if ( pTests[nInd].test() ) + System.out.println( "======= Storage test " + sTestName + " passed!" ); + else + { + System.out.println( "======= Storage test " + sTestName + " failed!" ); + bTestsPassed = false; + } + } + + if ( bTestsPassed ) + System.out.println( "\ntesting passed" ); + else + System.out.println( "\ntesting failed" ); + + System.out.println( "done" ); + + System.exit( 0 ); + } + + + public static XMultiServiceFactory connect( String sConnectStr ) + throws com.sun.star.uno.Exception, + com.sun.star.uno.RuntimeException, + Exception + { + // Get component context + XComponentContext xComponentContext = + com.sun.star.comp.helper.Bootstrap.createInitialComponentContext( + null ); + + // initial serviceManager + XMultiComponentFactory xLocalServiceManager = + xComponentContext.getServiceManager(); + + // create a connector, so that it can contact the office + Object oUrlResolver = xLocalServiceManager.createInstanceWithContext( + "com.sun.star.bridge.UnoUrlResolver", xComponentContext ); + XUnoUrlResolver xUrlResolver = UnoRuntime.queryInterface( + XUnoUrlResolver.class, oUrlResolver ); + + Object oInitialObject = xUrlResolver.resolve( sConnectStr ); + XNamingService xName = UnoRuntime.queryInterface( + XNamingService.class, oInitialObject ); + + XMultiServiceFactory xMSF = null; + if( xName != null ) { + System.err.println( "got the remote naming service !" ); + Object oMSF = xName.getRegisteredObject("StarOffice.ServiceManager" ); + + xMSF = UnoRuntime.queryInterface( XMultiServiceFactory.class, oMSF ); + } + else + System.out.println( "Error: Can't get XNamingService interface from url resolver!" ); + + return xMSF; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/StorageTest.java b/odk/examples/java/Storage/StorageTest.java new file mode 100644 index 000000000..b146d2229 --- /dev/null +++ b/odk/examples/java/Storage/StorageTest.java @@ -0,0 +1,25 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +public interface StorageTest +{ + boolean test(); +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/Test01.java b/odk/examples/java/Storage/Test01.java new file mode 100644 index 000000000..649f28440 --- /dev/null +++ b/odk/examples/java/Storage/Test01.java @@ -0,0 +1,169 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.embed.*; + +public class Test01 implements StorageTest { + + XMultiServiceFactory m_xMSF; + XSingleServiceFactory m_xStorageFactory; + TestHelper m_aTestHelper; + + public Test01( XMultiServiceFactory xMSF, XSingleServiceFactory xStorageFactory ) + { + m_xMSF = xMSF; + m_xStorageFactory = xStorageFactory; + m_aTestHelper = new TestHelper( "Test01: " ); + } + + public boolean test() + { + try + { + String sTempFileURL = m_aTestHelper.CreateTempFile( m_xMSF ); + if ( sTempFileURL == null || sTempFileURL.equals("") ) + { + m_aTestHelper.Error( "No valid temporary file was created!" ); + return false; + } + + // create temporary storage based on arbitrary medium + // after such a storage is closed it is lost + Object oTempStorage = m_xStorageFactory.createInstance(); + XStorage xTempStorage = UnoRuntime.queryInterface( XStorage.class, oTempStorage ); + if ( xTempStorage == null ) + { + m_aTestHelper.Error( "Can't create temporary storage representation!" ); + return false; + } + + // open a new substorage + XStorage xTempSubStorage = m_aTestHelper.openSubStorage( xTempStorage, + "SubStorage1", + ElementModes.WRITE ); + if ( xTempSubStorage == null ) + { + m_aTestHelper.Error( "Can't create substorage!" ); + return false; + } + + byte pBytes1[] = { 1, 1, 1, 1, 1 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToSubstream( xTempSubStorage, "SubStream1", "MediaType1", true, pBytes1 ) ) + return false; + + byte pBytes2[] = { 2, 2, 2, 2, 2 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToSubstream( xTempSubStorage, "SubStream2", "MediaType2", false, pBytes2 ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempStorage, + "MediaType3", + true, + ElementModes.READWRITE ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempSubStorage, + "MediaType4", + false, + ElementModes.WRITE ) ) + return false; + + // create temporary storage based on a previously created temporary file + Object pArgs[] = new Object[2]; + pArgs[0] = sTempFileURL; + pArgs[1] = Integer.valueOf( ElementModes.WRITE ); + + Object oTempFileStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xTempFileStorage = UnoRuntime.queryInterface( XStorage.class, oTempFileStorage ); + if ( xTempFileStorage == null ) + { + m_aTestHelper.Error( "Can't create storage based on temporary file!" ); + return false; + } + + // copy xTempStorage to xTempFileStorage + // xTempFileStorage will be automatically committed + if ( !m_aTestHelper.copyStorage( xTempStorage, xTempFileStorage ) ) + return false; + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xTempStorage ) || !m_aTestHelper.disposeStorage( xTempFileStorage ) ) + return false; + + + // now check all the written and copied information + + + // the temporary file must not be locked any more after storage disposing + pArgs[1] = Integer.valueOf( ElementModes.READWRITE ); + Object oResultStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xResultStorage = UnoRuntime.queryInterface( XStorage.class, oResultStorage ); + if ( xResultStorage == null ) + { + m_aTestHelper.Error( "Can't reopen storage based on temporary file!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResultStorage, "MediaType3", true, ElementModes.READWRITE ) ) + return false; + + // open existing substorage + XStorage xResultSubStorage = m_aTestHelper.openSubStorage( xResultStorage, + "SubStorage1", + ElementModes.READ ); + if ( xResultSubStorage == null ) + { + m_aTestHelper.Error( "Can't open existing substorage!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResultSubStorage, "MediaType4", false, ElementModes.READ ) ) + return false; + + if ( !m_aTestHelper.checkStream( xResultSubStorage, "SubStream1", "MediaType1", pBytes1 ) ) + return false; + + if ( !m_aTestHelper.checkStream( xResultSubStorage, "SubStream2", "MediaType2", pBytes2 ) ) + return false; + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xResultStorage ) ) + return false; + + return true; + } + catch( Exception e ) + { + m_aTestHelper.Error( "Exception: " + e ); + return false; + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/Test02.java b/odk/examples/java/Storage/Test02.java new file mode 100644 index 000000000..92f5a8c81 --- /dev/null +++ b/odk/examples/java/Storage/Test02.java @@ -0,0 +1,165 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.io.XStream; +import com.sun.star.io.XInputStream; + +import com.sun.star.embed.*; + +public class Test02 implements StorageTest { + + XMultiServiceFactory m_xMSF; + XSingleServiceFactory m_xStorageFactory; + TestHelper m_aTestHelper; + + public Test02( XMultiServiceFactory xMSF, XSingleServiceFactory xStorageFactory ) + { + m_xMSF = xMSF; + m_xStorageFactory = xStorageFactory; + m_aTestHelper = new TestHelper( "Test02: " ); + } + + public boolean test() + { + try + { + XStream xTempFileStream = m_aTestHelper.CreateTempFileStream( m_xMSF ); + if ( xTempFileStream == null ) + return false; + + // create storage based on the temporary stream + Object pArgs[] = new Object[2]; + pArgs[0] = xTempFileStream; + pArgs[1] = Integer.valueOf( ElementModes.WRITE ); + + Object oTempStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xTempStorage = UnoRuntime.queryInterface( XStorage.class, oTempStorage ); + if ( xTempStorage == null ) + { + m_aTestHelper.Error( "Can't create temporary storage representation!" ); + return false; + } + + // open a new substorage + XStorage xTempSubStorage = m_aTestHelper.openSubStorage( xTempStorage, + "SubStorage1", + ElementModes.WRITE ); + if ( xTempSubStorage == null ) + { + m_aTestHelper.Error( "Can't create substorage!" ); + return false; + } + + byte pBytes1[] = { 1, 1, 1, 1, 1 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToSubstream( xTempSubStorage, "SubStream1", "MediaType1", true, pBytes1 ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempStorage, + "MediaType2", + true, + ElementModes.WRITE ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempSubStorage, + "MediaType3", + false, + ElementModes.WRITE ) ) + return false; + + // commit substorage first + if ( !m_aTestHelper.commitStorage( xTempSubStorage ) ) + return false; + + // commit the root storage so the contents must be stored now + if ( !m_aTestHelper.commitStorage( xTempStorage ) ) + return false; + + // dispose used storage to free resources + // the substorage dispose will be triggered by this call + if ( !m_aTestHelper.disposeStorage( xTempStorage ) ) + return false; + + + + // now check all the written information + + + // close the output part of the temporary stream + // the output part must present since we already wrote to the stream + if ( !m_aTestHelper.closeOutput( xTempFileStream ) ) + return false; + + XInputStream xTempInStream = m_aTestHelper.getInputStream( xTempFileStream ); + if ( xTempInStream == null ) + return false; + + + // open input stream + // since no mode is provided the result storage must be opened readonly + Object pOneArg[] = new Object[1]; + pOneArg[0] = xTempInStream; + + Object oResultStorage = m_xStorageFactory.createInstanceWithArguments( pOneArg ); + XStorage xResultStorage = UnoRuntime.queryInterface( XStorage.class, oResultStorage ); + if ( xResultStorage == null ) + { + m_aTestHelper.Error( "Can't open storage based on input stream!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResultStorage, "MediaType2", true, ElementModes.READ ) ) + return false; + + // open existing substorage + XStorage xResultSubStorage = m_aTestHelper.openSubStorage( xResultStorage, + "SubStorage1", + ElementModes.READ ); + if ( xResultSubStorage == null ) + { + m_aTestHelper.Error( "Can't open existing substorage!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResultSubStorage, "MediaType3", false, ElementModes.READ ) ) + return false; + + if ( !m_aTestHelper.checkStream( xResultSubStorage, "SubStream1", "MediaType1", pBytes1 ) ) + return false; + + return true; + } + catch( Exception e ) + { + m_aTestHelper.Error( "Exception: " + e ); + return false; + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/Test03.java b/odk/examples/java/Storage/Test03.java new file mode 100644 index 000000000..500d46b92 --- /dev/null +++ b/odk/examples/java/Storage/Test03.java @@ -0,0 +1,220 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.embed.*; +import com.sun.star.container.XNameAccess; + +public class Test03 implements StorageTest { + + XMultiServiceFactory m_xMSF; + XSingleServiceFactory m_xStorageFactory; + TestHelper m_aTestHelper; + + public Test03( XMultiServiceFactory xMSF, XSingleServiceFactory xStorageFactory ) + { + m_xMSF = xMSF; + m_xStorageFactory = xStorageFactory; + m_aTestHelper = new TestHelper( "Test03: " ); + } + + public boolean test() + { + try + { + // create temporary storage based on arbitrary medium + // after such a storage is closed it is lost + Object oTempStorage = m_xStorageFactory.createInstance(); + XStorage xTempStorage = UnoRuntime.queryInterface( XStorage.class, oTempStorage ); + if ( xTempStorage == null ) + { + m_aTestHelper.Error( "Can't create temporary storage representation!" ); + return false; + } + + // open a new substorage + XStorage xTempSubStorage = m_aTestHelper.openSubStorage( xTempStorage, + "SubStorage1", + ElementModes.WRITE ); + if ( xTempSubStorage == null ) + { + m_aTestHelper.Error( "Can't create substorage!" ); + return false; + } + + byte pBytes1[] = { 1, 1, 1, 1, 1 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToSubstream( xTempStorage, "SubStream1", "MediaType1", true, pBytes1 ) ) + return false; + + byte pBytes2[] = { 2, 2, 2, 2, 2 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToSubstream( xTempSubStorage, "SubStream2", "MediaType2", false, pBytes2 ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempSubStorage, + "MediaType3", + false, + ElementModes.WRITE ) ) + return false; + + if ( !m_aTestHelper.commitStorage( xTempSubStorage ) ) + return false; + + if ( !m_aTestHelper.disposeStorage( xTempSubStorage ) ) + return false; + + + // check storage hierarchy tree + + + // check that isStorageElement() and isStreamElement reacts to nonexistent object correctly + try { + xTempStorage.isStorageElement( "does not exist" ); + m_aTestHelper.Error( "Nonexistent element doesn't detected by isStorageElement() call!" ); + return false; + } + catch( com.sun.star.container.NoSuchElementException ne ) + { + } + catch( Exception e ) + { + m_aTestHelper.Error( "Wrong exception is thrown by isStorageElement() call: " + e ); + return false; + } + + try { + xTempStorage.isStreamElement( "does not exist" ); + m_aTestHelper.Error( "Nonexistent element doesn't detected by isStreamElement() call!" ); + return false; + } + catch( com.sun.star.container.NoSuchElementException ne ) + { + } + catch( Exception e ) + { + m_aTestHelper.Error( "Wrong exception is thrown by isStreamElement() call: " + e ); + return false; + } + + XNameAccess xRootNameAccess = UnoRuntime.queryInterface( XNameAccess.class, xTempStorage ); + if ( xRootNameAccess == null ) + { + m_aTestHelper.Error( "Root storage doesn't support XNameAccess!" ); + return false; + } + + try { + if ( !xTempStorage.isStorageElement( "SubStorage1" ) || xTempStorage.isStreamElement( "SubStorage1" ) ) + { + m_aTestHelper.Error( "Child 'SubStorage1' can not be detected as storage!" ); + return false; + } + + if ( xTempStorage.isStorageElement( "SubStream1" ) || !xTempStorage.isStreamElement( "SubStream1" ) ) + { + m_aTestHelper.Error( "Child 'SubStream1' can not be detected as stream!" ); + return false; + } + } + catch( Exception e ) + { + m_aTestHelper.Error( "Child's type can not be detected, exception: " + e ); + return false; + } + + + // check that root storage contents are represented correctly + String sRootCont[] = xRootNameAccess.getElementNames(); + + if ( sRootCont.length != 2 ) + { + m_aTestHelper.Error( "Root storage contains wrong amount of children!" ); + return false; + } + + if ( !( sRootCont[0].equals( "SubStorage1" ) && sRootCont[1].equals( "SubStream1" ) + || sRootCont[0].equals( "SubStream1" ) && sRootCont[1].equals( "SubStorage1" ) ) + || !( xRootNameAccess.hasByName( "SubStream1" ) && xRootNameAccess.hasByName( "SubStorage1" ) ) ) + { + m_aTestHelper.Error( "Root storage contains wrong list of children!" ); + return false; + } + + // get storage through XNameAccess + XStorage xResultSubStorage = getStorageFromNameAccess( xRootNameAccess, "SubStorage1" ); + if ( xResultSubStorage == null ) + return false; + + if ( !m_aTestHelper.checkStorageProperties( xResultSubStorage, "MediaType3", false, ElementModes.READ ) ) + return false; + + XNameAccess xChildAccess = UnoRuntime.queryInterface( XNameAccess.class, xResultSubStorage ); + if ( xChildAccess == null ) + { + m_aTestHelper.Error( "Child storage doesn't support XNameAccess!" ); + return false; + } + + if ( !xChildAccess.hasByName( "SubStream2" ) + || !xResultSubStorage.isStreamElement( "SubStream2" ) + || xResultSubStorage.isStorageElement( "SubStream2" ) ) + { + m_aTestHelper.Error( "'SubStream2' can not be detected as child stream element of 'SubStorage1'!" ); + return false; + } + + return true; + } + catch( Exception e ) + { + m_aTestHelper.Error( "Exception: " + e ); + return false; + } + } + + public XStorage getStorageFromNameAccess( XNameAccess xAccess, String sName ) + { + try + { + Object oStorage = xAccess.getByName( sName ); + XStorage xResult = UnoRuntime.queryInterface( XStorage.class, oStorage ); + + if ( xResult != null ) + return xResult; + else + m_aTestHelper.Error( "Can't retrieve substorage '" + sName + "' through XNameAccess!" ); + } + catch( Exception e ) + { + m_aTestHelper.Error( "Can't retrieve substorage '" + sName + "' through XNameAccess, exception: " + e ); + } + + return null; + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/Test04.java b/odk/examples/java/Storage/Test04.java new file mode 100644 index 000000000..535253b19 --- /dev/null +++ b/odk/examples/java/Storage/Test04.java @@ -0,0 +1,282 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.container.XNameAccess; + +import com.sun.star.embed.*; + +public class Test04 implements StorageTest { + + XMultiServiceFactory m_xMSF; + XSingleServiceFactory m_xStorageFactory; + TestHelper m_aTestHelper; + + public Test04( XMultiServiceFactory xMSF, XSingleServiceFactory xStorageFactory ) + { + m_xMSF = xMSF; + m_xStorageFactory = xStorageFactory; + m_aTestHelper = new TestHelper( "Test04: " ); + } + + public boolean test() + { + try + { + String sTempFileURL = m_aTestHelper.CreateTempFile( m_xMSF ); + if ( sTempFileURL == null || sTempFileURL.equals("") ) + { + m_aTestHelper.Error( "No valid temporary file was created!" ); + return false; + } + + // create temporary storage based on arbitrary medium + // after such a storage is closed it is lost + Object oTempStorage = m_xStorageFactory.createInstance(); + XStorage xTempStorage = UnoRuntime.queryInterface( XStorage.class, oTempStorage ); + if ( xTempStorage == null ) + { + m_aTestHelper.Error( "Can't create temporary storage representation!" ); + return false; + } + + // open substorages and create streams there + + // first substorage of the root storage + XStorage xTempSubStorage1 = m_aTestHelper.openSubStorage( xTempStorage, + "SubStorage1", + ElementModes.WRITE ); + if ( xTempSubStorage1 == null ) + { + m_aTestHelper.Error( "Can't create substorage!" ); + return false; + } + + byte pBytes1[] = { 1, 1, 1, 1, 1 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToSubstream( xTempSubStorage1, "SubStream1", "MediaType1", true, pBytes1 ) ) + return false; + + // second substorage of the root storage + XStorage xTempSubStorage2 = m_aTestHelper.openSubStorage( xTempStorage, + "SubStorage2", + ElementModes.WRITE ); + if ( xTempSubStorage2 == null ) + { + m_aTestHelper.Error( "Can't create substorage!" ); + return false; + } + + byte pBytes2[] = { 2, 2, 2, 2, 2 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToSubstream( xTempSubStorage2, "SubStream2", "MediaType2", false, pBytes2 ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempStorage, + "MediaType3", + true, + ElementModes.READWRITE ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempSubStorage1, + "MediaType4", + false, + ElementModes.WRITE ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempSubStorage2, + "MediaType5", + false, + ElementModes.WRITE ) ) + return false; + + // create temporary storage based on a previously created temporary file + Object pArgs[] = new Object[2]; + pArgs[0] = sTempFileURL; + pArgs[1] = Integer.valueOf( ElementModes.WRITE ); + + Object oTempFileStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xTempFileStorage = UnoRuntime.queryInterface( XStorage.class, oTempFileStorage ); + if ( xTempFileStorage == null ) + { + m_aTestHelper.Error( "Can't create storage based on temporary file!" ); + return false; + } + + if ( !m_aTestHelper.copyElementTo( xTempStorage, "SubStorage1", xTempFileStorage ) ) + return false; + + // if storage is not committed before disposing all the changes will be lost + if ( !m_aTestHelper.commitStorage( xTempSubStorage2 ) ) + return false; + + // a storage must be disposed before moving/removing otherwise the access will be denied + if ( !m_aTestHelper.disposeStorage( xTempSubStorage2 ) ) + return false; + + if ( !m_aTestHelper.moveElementTo( xTempStorage, "SubStorage2", xTempFileStorage ) ) + return false; + + // SubStorage2 must be removed and disposed now + try + { + xTempSubStorage2.isStreamElement( "SubStream2" ); + m_aTestHelper.Error( "SubStorage2 must be disposed already!" ); + return false; + } + catch( com.sun.star.lang.DisposedException de ) + { + } + catch( Exception e ) + { + m_aTestHelper.Error( "Wrong exception in case of disposed storage, exception: " + e ); + return false; + } + + if ( !m_aTestHelper.copyElementTo( xTempSubStorage1, "SubStream1", xTempFileStorage ) ) + return false; + + if ( !m_aTestHelper.renameElement( xTempFileStorage, "SubStream1", "SubStream1_copy" ) ) + return false; + + if ( !m_aTestHelper.moveElementTo( xTempSubStorage1, "SubStream1", xTempFileStorage ) ) + return false; + + if ( !m_aTestHelper.commitStorage( xTempFileStorage ) ) + return false; + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xTempStorage ) || !m_aTestHelper.disposeStorage( xTempFileStorage ) ) + return false; + + + // now check all the written and copied information + + + // the temporary file must not be locked any more after storage disposing + pArgs[1] = Integer.valueOf( ElementModes.READWRITE ); + Object oResStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xResStorage = UnoRuntime.queryInterface( XStorage.class, oResStorage ); + if ( xResStorage == null ) + { + m_aTestHelper.Error( "Can't reopen storage based on temporary file!" ); + return false; + } + + // open and check SubStorage1 + XStorage xResSubStorage1 = m_aTestHelper.openSubStorage( xResStorage, + "SubStorage1", + ElementModes.READ ); + if ( xResSubStorage1 == null ) + { + m_aTestHelper.Error( "Can't open existing substorage!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResSubStorage1, "MediaType4", false, ElementModes.READ ) ) + return false; + + + // open and check SubStorage2 + XStorage xResSubStorage2 = m_aTestHelper.openSubStorage( xResStorage, + "SubStorage2", + ElementModes.READ ); + if ( xResSubStorage2 == null ) + { + m_aTestHelper.Error( "Can't open existing substorage!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResSubStorage2, "MediaType5", false, ElementModes.READ ) ) + return false; + + + // check all the result streams + + if ( !m_aTestHelper.checkStream( xResStorage, "SubStream1", "MediaType1", pBytes1 ) ) + return false; + + if ( !m_aTestHelper.checkStream( xResStorage, "SubStream1_copy", "MediaType1", pBytes1 ) ) + return false; + + if ( !m_aTestHelper.checkStream( xResSubStorage1, "SubStream1", "MediaType1", pBytes1 ) ) + return false; + + if ( !m_aTestHelper.checkStream( xResSubStorage2, "SubStream2", "MediaType2", pBytes2 ) ) + return false; + + // the storage must be disposed before removing + if ( !m_aTestHelper.disposeStorage( xResSubStorage2 ) ) + return false; + + // remove element and check that it was removed completely + if ( !m_aTestHelper.removeElement( xResStorage, "SubStorage2" ) ) + return false; + + try + { + XNameAccess xResAccess = UnoRuntime.queryInterface( XNameAccess.class, xResStorage ); + if ( xResAccess.hasByName( "SubStorage2" ) ) + m_aTestHelper.Error( "SubStorage2 must be removed already!" ); + } + catch( Exception e ) + { + m_aTestHelper.Error( "Can't get access to root storage, exception: " + e ); + return false; + } + + try + { + xResSubStorage2.isStreamElement( "SubStream2" ); + + m_aTestHelper.Error( "SubStorage2 must be disposed already!" ); + return false; + } + catch( com.sun.star.lang.DisposedException de ) + { + } + catch( Exception e ) + { + m_aTestHelper.Error( "Wrong exception in case of disposed storage, exception: " + e ); + return false; + } + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xResStorage ) ) + return false; + + return true; + } + catch( Exception e ) + { + m_aTestHelper.Error( "Exception: " + e ); + return false; + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/Test05.java b/odk/examples/java/Storage/Test05.java new file mode 100644 index 000000000..29cf99d52 --- /dev/null +++ b/odk/examples/java/Storage/Test05.java @@ -0,0 +1,278 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.io.XStream; + +import com.sun.star.embed.*; + +public class Test05 implements StorageTest { + + XMultiServiceFactory m_xMSF; + XSingleServiceFactory m_xStorageFactory; + TestHelper m_aTestHelper; + + public Test05( XMultiServiceFactory xMSF, XSingleServiceFactory xStorageFactory ) + { + m_xMSF = xMSF; + m_xStorageFactory = xStorageFactory; + m_aTestHelper = new TestHelper( "Test05: " ); + } + + public boolean test() + { + try + { + String sTempFileURL = m_aTestHelper.CreateTempFile( m_xMSF ); + if ( sTempFileURL == null || sTempFileURL.equals("") ) + { + m_aTestHelper.Error( "No valid temporary file was created!" ); + return false; + } + + // create temporary storage based on a previously created temporary file + Object pArgs[] = new Object[2]; + pArgs[0] = sTempFileURL; + pArgs[1] = Integer.valueOf( ElementModes.WRITE ); + + Object oTempFileStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xTempFileStorage = UnoRuntime.queryInterface( XStorage.class, oTempFileStorage ); + if ( xTempFileStorage == null ) + { + m_aTestHelper.Error( "Can't create storage based on temporary file!" ); + return false; + } + + // open a new substorage + XStorage xTempSubStorage = m_aTestHelper.openSubStorage( xTempFileStorage, + "SubStorage1", + ElementModes.WRITE ); + if ( xTempSubStorage == null ) + { + m_aTestHelper.Error( "Can't create substorage!" ); + return false; + } + + // open a new substorage + XStorage xSubSubStorage = m_aTestHelper.openSubStorage( xTempSubStorage, + "SubSubStorage1", + ElementModes.WRITE ); + if ( xSubSubStorage == null ) + { + m_aTestHelper.Error( "Can't create substorage!" ); + return false; + } + + + byte pBytes1[] = { 1, 1, 1, 1, 1 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToSubstream( xSubSubStorage, "SubStream1", "MediaType1", true, pBytes1 ) ) + return false; + + byte pBytes2[] = { 2, 2, 2, 2, 2 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToSubstream( xSubSubStorage, "SubStream2", "MediaType2", false, pBytes2 ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempFileStorage, + "MediaType3", + true, + ElementModes.WRITE ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempSubStorage, + "MediaType4", + false, + ElementModes.WRITE ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xSubSubStorage, + "MediaType5", + false, + ElementModes.WRITE ) ) + return false; + + + // commit all the storages + if ( !m_aTestHelper.commitStorage( xSubSubStorage ) ) + return false; + + if ( !m_aTestHelper.commitStorage( xTempSubStorage ) ) + return false; + + if ( !m_aTestHelper.commitStorage( xTempFileStorage ) ) + return false; + + // try to open an opened substorage, open call must fail + if ( !m_aTestHelper.cantOpenStorage( xTempFileStorage, "SubStorage1" ) ) + return false; + + + // reopen created streams + XStream xSubStream1 = m_aTestHelper.OpenStream( xSubSubStorage, + "SubStream1", + ElementModes.READWRITE | ElementModes.NOCREATE ); + XStream xSubStream2 = m_aTestHelper.OpenStream( xSubSubStorage, + "SubStream2", + ElementModes.READ | ElementModes.NOCREATE ); + if ( xSubStream1 == null || xSubStream2 == null ) + return false; + + // it should be possible to have more than one copy of stream for reading + XStream xSubStream2clone = m_aTestHelper.OpenStream( xSubSubStorage, + "SubStream2", + ElementModes.READ | ElementModes.NOCREATE ); + + + // so now the first stream can not be open neither for reading nor for writing + if ( !m_aTestHelper.cantOpenStream( xSubSubStorage, "SubStream1", ElementModes.WRITE ) + || !m_aTestHelper.cantOpenStream( xSubSubStorage, "SubStream1", ElementModes.READ ) ) + return false; + + // the second stream can not be open for writing + if ( !m_aTestHelper.cantOpenStream( xSubSubStorage, "SubStream2", ElementModes.WRITE ) ) + return false; + + + // dispose xTestSubStorage, all the subtree must be disposed + if ( !m_aTestHelper.disposeStorage( xTempSubStorage ) ) + return false; + + // check that subtree was disposed correctly + try + { + xSubSubStorage.isStreamElement( "SubStream1" ); + m_aTestHelper.Error( "Substorage was not disposed!" ); + return false; + } + catch ( com.sun.star.lang.DisposedException de ) + {} + catch ( Exception e ) + { + m_aTestHelper.Error( "Wrong exception is thrown by disposed storage: " + e ); + return false; + } + + try + { + xSubStream1.getInputStream(); + m_aTestHelper.Error( "Writeable substream was not disposed!" ); + return false; + } + catch ( com.sun.star.lang.DisposedException de ) + {} + catch ( Exception e ) + { + m_aTestHelper.Error( "Wrong exception is thrown by disposed stream: " + e ); + return false; + } + + try + { + xSubStream2.getInputStream(); + m_aTestHelper.Error( "Readonly substream was not disposed!" ); + return false; + } + catch ( com.sun.star.lang.DisposedException de ) + {} + catch ( Exception e ) + { + m_aTestHelper.Error( "Wrong exception is thrown by disposed stream: " + e ); + return false; + } + + + // dispose root storage + if ( !m_aTestHelper.disposeStorage( xTempFileStorage ) ) + return false; + + + + // now check all the written and copied information + + + pArgs[1] = Integer.valueOf( ElementModes.READ ); + Object oResultStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xResultStorage = UnoRuntime.queryInterface( XStorage.class, oResultStorage ); + if ( xResultStorage == null ) + { + m_aTestHelper.Error( "Can't reopen storage based on temporary file!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResultStorage, "MediaType3", true, ElementModes.READ ) ) + return false; + + // open existing substorage + XStorage xResSubStorage = m_aTestHelper.openSubStorage( xResultStorage, + "SubStorage1", + ElementModes.READ ); + if ( xResSubStorage == null ) + { + m_aTestHelper.Error( "Can't open existing substorage 'SubSubStorage'!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResSubStorage, "MediaType4", false, ElementModes.READ ) ) + return false; + + // open existing substorage + XStorage xResSubSubStorage = m_aTestHelper.openSubStorage( xResSubStorage, + "SubSubStorage1", + ElementModes.READ ); + if ( xResSubSubStorage == null ) + { + m_aTestHelper.Error( "Can't open existing substorage 'SubSubStorage'!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResSubSubStorage, "MediaType5", false, ElementModes.READ ) ) + return false; + + // check substreams + if ( !m_aTestHelper.checkStream( xResSubSubStorage, "SubStream1", "MediaType1", pBytes1 ) ) + return false; + + if ( !m_aTestHelper.checkStream( xResSubSubStorage, "SubStream2", "MediaType2", pBytes2 ) ) + return false; + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xResultStorage ) ) + return false; + + return true; + } + catch( Exception e ) + { + m_aTestHelper.Error( "Exception: " + e ); + return false; + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/Test06.java b/odk/examples/java/Storage/Test06.java new file mode 100644 index 000000000..027a4a2c1 --- /dev/null +++ b/odk/examples/java/Storage/Test06.java @@ -0,0 +1,285 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.embed.*; + +public class Test06 implements StorageTest { + + XMultiServiceFactory m_xMSF; + XSingleServiceFactory m_xStorageFactory; + TestHelper m_aTestHelper; + + public Test06( XMultiServiceFactory xMSF, XSingleServiceFactory xStorageFactory ) + { + m_xMSF = xMSF; + m_xStorageFactory = xStorageFactory; + m_aTestHelper = new TestHelper( "Test06: " ); + } + + public boolean test() + { + try + { + // create temporary storage based on arbitrary medium + // after such a storage is closed it is lost + Object oTempStorage = m_xStorageFactory.createInstance(); + XStorage xTempStorage = UnoRuntime.queryInterface( XStorage.class, oTempStorage ); + if ( xTempStorage == null ) + { + m_aTestHelper.Error( "Can't create temporary storage representation!" ); + return false; + } + + try + { + xTempStorage.copyToStorage( null ); + m_aTestHelper.Error( "The method must throw an exception because of illegal parameter!" ); + return false; + } + catch( com.sun.star.lang.IllegalArgumentException iae ) + {} + catch( com.sun.star.uno.Exception ue ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception because of illegal parameter : " + e ); + return false; + } + + // open new substorages + XStorage xTempSubStorage1 = m_aTestHelper.openSubStorage( xTempStorage, + "SubStorage1", + ElementModes.WRITE ); + XStorage xTempSubStorage2 = m_aTestHelper.openSubStorage( xTempStorage, + "SubStorage2", + ElementModes.WRITE ); + if ( xTempSubStorage1 == null || xTempSubStorage2 == null ) + { + m_aTestHelper.Error( "Can't create substorage!" ); + return false; + } + + // in case stream is open for reading it must exist + try + { + xTempSubStorage1.openStreamElement( "NonExistingStream", ElementModes.READ ); + m_aTestHelper.Error( "The method must throw an exception in case of try to open nonexistent stream for reading!" ); + return false; + } + catch( com.sun.star.uno.Exception ue ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case of try to open nonexistent stream for reading : " + e ); + return false; + } + + // in case a storage is open for reading it must exist + try + { + xTempSubStorage1.openStreamElement( "NonExistingStorage", ElementModes.READ ); + m_aTestHelper.Error( "The method must throw an exception in case of try to open nonexistent storage for reading!" ); + return false; + } + catch( com.sun.star.uno.Exception ue ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case of try to open nonexistent storage for reading : " + e ); + return false; + } + + // in case of removing nonexistent element an exception must be thrown + try + { + xTempSubStorage1.removeElement( "NonExistingElement" ); + m_aTestHelper.Error( "An exception must be thrown in case of removing nonexistent element!" ); + return false; + } + catch( com.sun.star.container.NoSuchElementException ne ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case of try to remove nonexistent element : " + e ); + return false; + } + + // in case of renaming of nonexistent element an exception must be thrown + try + { + xTempSubStorage1.renameElement( "NonExistingElement", "NewName" ); + m_aTestHelper.Error( "An exception must be thrown in case of renaming nonexistent element!" ); + return false; + } + catch( com.sun.star.container.NoSuchElementException ne ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case of try to rename nonexistent element : " + e ); + return false; + } + + // in case of renaming to a name of existent element an exception must be thrown + try + { + xTempStorage.renameElement( "SubStorage1", "SubStorage2" ); + m_aTestHelper.Error( "An exception must be thrown in case of renaming to the name of existent element!" ); + return false; + } + catch( com.sun.star.container.ElementExistException ee ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case of try to rename to the name of existent element : " + e ); + return false; + } + + // in case of copying target storage must be provided + try + { + xTempStorage.copyElementTo( "SubStorage1", null, "SubStorage1" ); + m_aTestHelper.Error( "An exception must be thrown in case empty reference is provided as target for copying!" ); + return false; + } + catch( com.sun.star.lang.IllegalArgumentException iae ) + {} + catch( com.sun.star.uno.Exception ue ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case empty reference is provided as target for copying : " + e ); + return false; + } + + // in case of moving target storage must be provided + try + { + xTempStorage.moveElementTo( "SubStorage1", null, "SubStorage1" ); + m_aTestHelper.Error( "An exception must be thrown in case empty reference is provided as target for moving!" ); + return false; + } + catch( com.sun.star.lang.IllegalArgumentException iae ) + {} + catch( com.sun.star.uno.Exception ue ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case empty reference is provided as target for moving : " + e ); + return false; + } + + + // prepare target for further testings + + // create new temporary storage based on arbitrary medium + Object oTargetStorage = m_xStorageFactory.createInstance(); + XStorage xTargetStorage = UnoRuntime.queryInterface( XStorage.class, oTargetStorage ); + if ( xTargetStorage == null ) + { + m_aTestHelper.Error( "Can't create temporary storage representation!" ); + return false; + } + + // open a new substorage + XStorage xTargetSubStorage = m_aTestHelper.openSubStorage( xTargetStorage, + "SubStorage1", + ElementModes.WRITE ); + if ( xTargetSubStorage == null ) + { + m_aTestHelper.Error( "Can't create substorage!" ); + return false; + } + + // in case of copying of nonexistent element an exception must be thrown + try + { + xTempStorage.copyElementTo( "Nonexistent element", xTargetStorage, "Target" ); + m_aTestHelper.Error( "An exception must be thrown in case of copying of nonexistent element!" ); + return false; + } + catch( com.sun.star.container.NoSuchElementException ne ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case of copying of nonexistent element: " + e ); + return false; + } + + // in case of moving of nonexistent element an exception must be thrown + try + { + xTempStorage.moveElementTo( "Nonexistent element", xTargetStorage, "Target" ); + m_aTestHelper.Error( "An exception must be thrown in case of moving of nonexistent element!" ); + return false; + } + catch( com.sun.star.container.NoSuchElementException ne ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case of moving of nonexistent element: " + e ); + return false; + } + + // in case target for copying already exists an exception must be thrown + try + { + xTempStorage.copyElementTo( "SubStorage1", xTargetStorage, "SubStorage1" ); + m_aTestHelper.Error( "An exception must be thrown in case target for copying already exists!" ); + return false; + } + catch( com.sun.star.container.ElementExistException ee ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case target for copying already exists: " + e ); + return false; + } + + // in case target for moving already exists an exception must be thrown + try + { + xTempStorage.moveElementTo( "SubStorage1", xTargetStorage, "SubStorage1" ); + m_aTestHelper.Error( "An exception must be thrown in case target for moving already exists!" ); + return false; + } + catch( com.sun.star.container.ElementExistException ee ) + {} + catch( Exception e ) + { + m_aTestHelper.Error( "Unexpected exception in case target for moving already exists: " + e ); + return false; + } + + + return true; + } + catch( Exception e ) + { + m_aTestHelper.Error( "Exception: " + e ); + return false; + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/Test07.java b/odk/examples/java/Storage/Test07.java new file mode 100644 index 000000000..d96b0e1eb --- /dev/null +++ b/odk/examples/java/Storage/Test07.java @@ -0,0 +1,148 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.embed.*; + +public class Test07 implements StorageTest { + + XMultiServiceFactory m_xMSF; + XSingleServiceFactory m_xStorageFactory; + TestHelper m_aTestHelper; + + public Test07( XMultiServiceFactory xMSF, XSingleServiceFactory xStorageFactory ) + { + m_xMSF = xMSF; + m_xStorageFactory = xStorageFactory; + m_aTestHelper = new TestHelper( "Test07: " ); + } + + public boolean test() + { + try + { + String sTempFileURL = m_aTestHelper.CreateTempFile( m_xMSF ); + if ( sTempFileURL == null || sTempFileURL.equals("") ) + { + m_aTestHelper.Error( "No valid temporary file was created!" ); + return false; + } + + // create temporary storage based on arbitrary medium + // after such a storage is closed it is lost + Object oTempStorage = m_xStorageFactory.createInstance(); + XStorage xTempStorage = UnoRuntime.queryInterface( XStorage.class, oTempStorage ); + if ( xTempStorage == null ) + { + m_aTestHelper.Error( "Can't create temporary storage representation!" ); + return false; + } + + byte pBytes1[] = { 1, 1, 1, 1, 1 }; + byte pPass1[] = { 1, 2, 3, 4, 5 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToEncrSubstream( xTempStorage, "SubStream1", "MediaType1", true, pBytes1, pPass1 ) ) + return false; + + byte pBytes2[] = { 2, 2, 2, 2, 2 }; + byte pPass2[] = { 5, 4, 3, 2, 1 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + if ( !m_aTestHelper.WriteBytesToEncrSubstream( xTempStorage, "SubStream2", "MediaType2", false, pBytes2, pPass2 ) ) + return false; + + // create temporary storage based on a previously created temporary file + Object pArgs[] = new Object[2]; + pArgs[0] = sTempFileURL; + pArgs[1] = Integer.valueOf( ElementModes.WRITE ); + + Object oTempFileStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xTempFileStorage = UnoRuntime.queryInterface( XStorage.class, oTempFileStorage ); + if ( xTempFileStorage == null ) + { + m_aTestHelper.Error( "Can't create storage based on temporary file!" ); + return false; + } + + // copy xTempStorage to xTempFileStorage + // xTempFileStorage will be automatically committed + if ( !m_aTestHelper.copyStorage( xTempStorage, xTempFileStorage ) ) + return false; + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xTempStorage ) || !m_aTestHelper.disposeStorage( xTempFileStorage ) ) + return false; + + + // now check all the written and copied information + + + // the temporary file must not be locked any more after storage disposing + pArgs[1] = Integer.valueOf( ElementModes.READWRITE ); + Object oResultStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xResultStorage = UnoRuntime.queryInterface( XStorage.class, oResultStorage ); + if ( xResultStorage == null ) + { + m_aTestHelper.Error( "Can't reopen storage based on temporary file!" ); + return false; + } + + Object o2CopyStorage = m_xStorageFactory.createInstance(); + XStorage x2CopyStorage = UnoRuntime.queryInterface( XStorage.class, o2CopyStorage ); + if ( x2CopyStorage == null ) + { + m_aTestHelper.Error( "Can't create temporary storage representation!" ); + return false; + } + + if ( !m_aTestHelper.copyStorage( xResultStorage, x2CopyStorage ) ) + return false; + + if ( !m_aTestHelper.checkEncrStream( xResultStorage, "SubStream1", "MediaType1", pBytes1, pPass1 ) ) + return false; + + if ( !m_aTestHelper.checkEncrStream( xResultStorage, "SubStream2", "MediaType2", pBytes2, pPass2 ) ) + return false; + + if ( !m_aTestHelper.checkEncrStream( x2CopyStorage, "SubStream1", "MediaType1", pBytes1, pPass1 ) ) + return false; + + if ( !m_aTestHelper.checkEncrStream( x2CopyStorage, "SubStream2", "MediaType2", pBytes2, pPass2 ) ) + return false; + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xResultStorage ) ) + return false; + + return true; + } + catch( Exception e ) + { + m_aTestHelper.Error( "Exception: " + e ); + return false; + } + } + +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/Test08.java b/odk/examples/java/Storage/Test08.java new file mode 100644 index 000000000..323e2d78c --- /dev/null +++ b/odk/examples/java/Storage/Test08.java @@ -0,0 +1,224 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.embed.*; + +public class Test08 implements StorageTest { + + XMultiServiceFactory m_xMSF; + XSingleServiceFactory m_xStorageFactory; + TestHelper m_aTestHelper; + + public Test08( XMultiServiceFactory xMSF, XSingleServiceFactory xStorageFactory ) + { + m_xMSF = xMSF; + m_xStorageFactory = xStorageFactory; + m_aTestHelper = new TestHelper( "Test08: " ); + } + + public boolean test() + { + try + { + + // create temporary storage based on arbitrary medium + // after such a storage is closed it is lost + Object oTempStorage = m_xStorageFactory.createInstance(); + XStorage xTempStorage = UnoRuntime.queryInterface( XStorage.class, oTempStorage ); + if ( xTempStorage == null ) + { + m_aTestHelper.Error( "Can't create temporary storage representation!" ); + return false; + } + + // set the global password for the root storage + XEncryptionProtectedSource xTempStorageEncryption = + UnoRuntime.queryInterface( XEncryptionProtectedSource.class, xTempStorage ); + + if ( xTempStorageEncryption == null ) + { + m_aTestHelper.Message( "Optional interface XEncryptionProtectedSource is not implemented, feature can not be tested!" ); + return true; + } + + byte pPass1[] = { 1, 2, 3 }; + byte pPass2[] = { 3, 2, 1 }; + + try { + xTempStorageEncryption.setEncryptionPassword( new String(pPass1) ); + } + catch( Exception e ) + { + m_aTestHelper.Error( "Can't set a common encryption key for the storage, exception:" + e ); + return false; + } + + // open a new substorage + XStorage xTempSubStorage = m_aTestHelper.openSubStorage( xTempStorage, + "SubStorage1", + ElementModes.WRITE ); + if ( xTempSubStorage == null ) + { + m_aTestHelper.Error( "Can't create substorage!" ); + return false; + } + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + // the stream will be encrypted with common password + byte pBytes1[] = { 1, 1, 1, 1, 1 }; + if ( !m_aTestHelper.WBToSubstrOfEncr( xTempSubStorage, "SubStream1", "MediaType1", true, pBytes1, true ) ) + return false; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + // the stream will not be encrypted + byte pBytes2[] = { 2, 2, 2, 2, 2 }; + if ( !m_aTestHelper.WBToSubstrOfEncr( xTempSubStorage, "SubStream2", "MediaType2", false, pBytes2, false ) ) + return false; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + // the stream will be compressed with own password + byte pBytes3[] = { 3, 3, 3, 3, 3 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + // the stream will not be encrypted + if ( !m_aTestHelper.WriteBytesToEncrSubstream( xTempSubStorage, "SubStream3", "MediaType3", false, pBytes3, pPass2 ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempStorage, + "MediaType4", + true, + ElementModes.READWRITE ) ) + return false; + + // set "MediaType" property for storages and check that "IsRoot" and "OpenMode" properties are set correctly + if ( !m_aTestHelper.setStorageTypeAndCheckProps( xTempSubStorage, + "MediaType5", + false, + ElementModes.WRITE ) ) + return false; + + // create temporary file + String sTempFileURL = m_aTestHelper.CreateTempFile( m_xMSF ); + if ( sTempFileURL == null || sTempFileURL.equals("") ) + { + m_aTestHelper.Error( "No valid temporary file was created!" ); + return false; + } + + // create temporary storage based on a previously created temporary file + Object pArgs[] = new Object[2]; + pArgs[0] = sTempFileURL; + pArgs[1] = Integer.valueOf( ElementModes.WRITE ); + + Object oTempFileStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xTempFileStorage = UnoRuntime.queryInterface( XStorage.class, oTempFileStorage ); + if ( xTempFileStorage == null ) + { + m_aTestHelper.Error( "Can't create storage based on temporary file!" ); + return false; + } + + // copy xTempStorage to xTempFileStorage + // xTempFileStorage will be automatically committed + if ( !m_aTestHelper.copyStorage( xTempStorage, xTempFileStorage ) ) + return false; + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xTempStorage ) || !m_aTestHelper.disposeStorage( xTempFileStorage ) ) + return false; + + + // now check all the written and copied information + + + // the temporary file must not be locked any more after storage disposing + pArgs[1] = Integer.valueOf( ElementModes.READ ); + Object oResultStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xResultStorage = UnoRuntime.queryInterface( XStorage.class, oResultStorage ); + if ( xResultStorage == null ) + { + m_aTestHelper.Error( "Can't reopen storage based on temporary file!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResultStorage, "MediaType4", true, ElementModes.READ ) ) + return false; + + // open existing substorage + XStorage xResultSubStorage = m_aTestHelper.openSubStorage( xResultStorage, + "SubStorage1", + ElementModes.READ ); + if ( xResultSubStorage == null ) + { + m_aTestHelper.Error( "Can't open existing substorage!" ); + return false; + } + + if ( !m_aTestHelper.checkStorageProperties( xResultSubStorage, "MediaType5", false, ElementModes.READ ) ) + return false; + + // set the global password for the root storage + XEncryptionProtectedSource xResultStorageEncryption = + UnoRuntime.queryInterface( XEncryptionProtectedSource.class, xResultStorage ); + + if ( xResultStorageEncryption == null ) + { + m_aTestHelper.Error( "XEncryptionProtectedSource was successfully used already, so it must be supported!" ); + return false; + } + + try { + xResultStorageEncryption.setEncryptionPassword( new String(pPass2) ); + } + catch( Exception e ) + { + m_aTestHelper.Error( "Can't set a common encryption key for the storage, exception:" + e ); + return false; + } + + if ( !m_aTestHelper.checkEncrStream( xResultSubStorage, "SubStream1", "MediaType1", pBytes1, pPass1 ) ) + return false; + + if ( !m_aTestHelper.checkStream( xResultSubStorage, "SubStream2", "MediaType2", pBytes2 ) ) + return false; + + // the common root storage password should allow to open this stream + if ( !m_aTestHelper.checkStream( xResultSubStorage, "SubStream3", "MediaType3", pBytes3 ) ) + return false; + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xResultStorage ) ) + return false; + + return true; + } + catch( Exception e ) + { + m_aTestHelper.Error( "Exception: " + e ); + return false; + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/Test09.java b/odk/examples/java/Storage/Test09.java new file mode 100644 index 000000000..131ff06d8 --- /dev/null +++ b/odk/examples/java/Storage/Test09.java @@ -0,0 +1,134 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XSingleServiceFactory; + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.embed.*; + +public class Test09 implements StorageTest { + + XMultiServiceFactory m_xMSF; + XSingleServiceFactory m_xStorageFactory; + TestHelper m_aTestHelper; + + public Test09( XMultiServiceFactory xMSF, XSingleServiceFactory xStorageFactory ) + { + m_xMSF = xMSF; + m_xStorageFactory = xStorageFactory; + m_aTestHelper = new TestHelper( "Test09: " ); + } + + public boolean test() + { + try + { + + // create temporary storage based on arbitrary medium + // after such a storage is closed it is lost + Object oTempStorage = m_xStorageFactory.createInstance(); + XStorage xTempStorage = UnoRuntime.queryInterface( XStorage.class, oTempStorage ); + if ( xTempStorage == null ) + { + m_aTestHelper.Error( "Can't create temporary storage representation!" ); + return false; + } + + byte pPass1[] = { 1, 2, 3 }; + byte pPass2[] = { 3, 2, 1 }; + byte pBytes[] = { 1, 1, 1, 1, 1 }; + + // open a new substream, set "MediaType" and "Compressed" properties to it and write some bytes + // the stream will not be encrypted + if ( !m_aTestHelper.WriteBytesToEncrSubstream( xTempStorage, "SubStream1", "MediaType1", false, pBytes, pPass1 ) ) + return false; + + // create temporary file + String sTempFileURL = m_aTestHelper.CreateTempFile( m_xMSF ); + if ( sTempFileURL == null || sTempFileURL.equals( "" ) ) + { + m_aTestHelper.Error( "No valid temporary file was created!" ); + return false; + } + + // create temporary storage based on a previously created temporary file + Object pArgs[] = new Object[2]; + pArgs[0] = sTempFileURL; + pArgs[1] = Integer.valueOf( ElementModes.WRITE ); + + Object oTempFileStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xTempFileStorage = UnoRuntime.queryInterface( XStorage.class, oTempFileStorage ); + if ( xTempFileStorage == null ) + { + m_aTestHelper.Error( "Can't create storage based on temporary file!" ); + return false; + } + + // copy xTempStorage to xTempFileStorage + // xTempFileStorage will be automatically committed + if ( !m_aTestHelper.copyStorage( xTempStorage, xTempFileStorage ) ) + return false; + + // change password of the substream of new storage based on file + int nResult = m_aTestHelper.ChangeStreamPass( xTempFileStorage, "SubStream1", pPass1, pPass2 ); + if ( nResult == 0 ) + return false; // test failed + else if ( nResult == -1 ) + return true; // tested optional feature is not supported + + if ( !m_aTestHelper.commitStorage( xTempFileStorage ) ) + return false; + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xTempStorage ) || !m_aTestHelper.disposeStorage( xTempFileStorage ) ) + return false; + + + // now check all the written and copied information + + + // the temporary file must not be locked any more after storage disposing + pArgs[1] = Integer.valueOf( ElementModes.READ ); + Object oResultStorage = m_xStorageFactory.createInstanceWithArguments( pArgs ); + XStorage xResultStorage = UnoRuntime.queryInterface( XStorage.class, oResultStorage ); + if ( xResultStorage == null ) + { + m_aTestHelper.Error( "Can't reopen storage based on temporary file!" ); + return false; + } + + if ( !m_aTestHelper.checkEncrStream( xResultStorage, "SubStream1", "MediaType1", pBytes, pPass2 ) ) + return false; + + // dispose used storages to free resources + if ( !m_aTestHelper.disposeStorage( xResultStorage ) ) + return false; + + return true; + } + catch( Exception e ) + { + m_aTestHelper.Error( "Exception: " + e ); + return false; + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Storage/TestHelper.java b/odk/examples/java/Storage/TestHelper.java new file mode 100644 index 000000000..a486f1d53 --- /dev/null +++ b/odk/examples/java/Storage/TestHelper.java @@ -0,0 +1,881 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * This file is part of the LibreOffice project. + * + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + * + * This file incorporates work covered by the following license notice: + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed + * with this work for additional information regarding copyright + * ownership. The ASF licenses this file to you under the Apache + * License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of + * the License at http://www.apache.org/licenses/LICENSE-2.0 . + */ + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.AnyConverter; + +import com.sun.star.lang.*; +import com.sun.star.embed.*; +import com.sun.star.packages.*; +import com.sun.star.io.*; +import com.sun.star.beans.*; + +public class TestHelper { + + String m_sTestPrefix; + + public TestHelper( String sTestPrefix ) + { + m_sTestPrefix = sTestPrefix; + } + + public boolean WriteBytesToStream( XStream xStream, + String sStreamName, + String sMediaType, + boolean bCompressed, + byte[] pBytes ) + { + // get output stream of substream + XOutputStream xOutput = xStream.getOutputStream(); + if ( xOutput == null ) + { + Error( "Can't get XOutputStream implementation from substream '" + sStreamName + "'!" ); + return false; + } + + // get XTruncate implementation from output stream + XTruncate xTruncate = UnoRuntime.queryInterface( XTruncate.class, xOutput ); + if ( xTruncate == null ) + { + Error( "Can't get XTruncate implementation from substream '" + sStreamName + "'!" ); + return false; + } + + // write requested byte sequence + try + { + xTruncate.truncate(); + xOutput.writeBytes( pBytes ); + } + catch( Exception e ) + { + Error( "Can't write to stream '" + sStreamName + "', exception: " + e ); + return false; + } + + // get access to the XPropertySet interface + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xStream ); + if ( xPropSet == null ) + { + Error( "Can't get XPropertySet implementation from substream '" + sStreamName + "'!" ); + return false; + } + + // set properties to the stream + try + { + xPropSet.setPropertyValue( "MediaType", sMediaType ); + xPropSet.setPropertyValue( "Compressed", Boolean.valueOf( bCompressed ) ); + } + catch( Exception e ) + { + Error( "Can't set properties to substream '" + sStreamName + "', exception: " + e ); + return false; + } + + // check size property of the stream + try + { + int nSize = AnyConverter.toInt( xPropSet.getPropertyValue( "Size" ) ); + if ( nSize != pBytes.length ) + { + Error( "The 'Size' property of substream '" + sStreamName + "' contains wrong value!" ); + return false; + } + } + catch( Exception e ) + { + Error( "Can't get 'Size' property from substream '" + sStreamName + "', exception: " + e ); + return false; + } + + // free the stream resources, garbage collector may remove the object too late + XComponent xComponent = UnoRuntime.queryInterface( XComponent.class, xStream ); + if ( xComponent == null ) + { + Error( "Can't get XComponent implementation from substream '" + sStreamName + "'!" ); + return false; + } + xComponent.dispose(); + + return true; + } + + + public boolean WriteBytesToSubstream( XStorage xStorage, + String sStreamName, + String sMediaType, + boolean bCompressed, + byte[] pBytes ) + { + // open substream element + XStream xSubStream = null; + try + { + Object oSubStream = xStorage.openStreamElement( sStreamName, ElementModes.WRITE ); + xSubStream = UnoRuntime.queryInterface( XStream.class, oSubStream ); + if ( xSubStream == null ) + { + Error( "Can't create substream '" + sStreamName + "'!" ); + return false; + } + } + catch( Exception e ) + { + Error( "Can't create substream '" + sStreamName + "', exception : " + e + "!" ); + return false; + } + + return WriteBytesToStream( xSubStream, sStreamName, sMediaType, bCompressed, pBytes ); + } + + public boolean WriteBytesToEncrSubstream( XStorage xStorage, + String sStreamName, + String sMediaType, + boolean bCompressed, + byte[] pBytes, + byte[] pPass ) + { + // open substream element + XStream xSubStream = null; + try + { + Object oSubStream = xStorage.openEncryptedStreamElement( sStreamName, ElementModes.WRITE, new String(pPass) ); + xSubStream = UnoRuntime.queryInterface( XStream.class, oSubStream ); + if ( xSubStream == null ) + { + Error( "Can't create substream '" + sStreamName + "'!" ); + return false; + } + } + catch( Exception e ) + { + Error( "Can't create substream '" + sStreamName + "', exception : " + e + "!" ); + return false; + } + + return WriteBytesToStream( xSubStream, sStreamName, sMediaType, bCompressed, pBytes ); + } + + public boolean WBToSubstrOfEncr( XStorage xStorage, + String sStreamName, + String sMediaType, + boolean bCompressed, + byte[] pBytes, + boolean bEncrypted ) + { + // open substream element + XStream xSubStream = null; + try + { + Object oSubStream = xStorage.openStreamElement( sStreamName, ElementModes.WRITE ); + xSubStream = UnoRuntime.queryInterface( XStream.class, oSubStream ); + if ( xSubStream == null ) + { + Error( "Can't create substream '" + sStreamName + "'!" ); + return false; + } + } + catch( Exception e ) + { + Error( "Can't create substream '" + sStreamName + "', exception : " + e + "!" ); + return false; + } + + // get access to the XPropertySet interface + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xSubStream ); + if ( xPropSet == null ) + { + Error( "Can't get XPropertySet implementation from substream '" + sStreamName + "'!" ); + return false; + } + + // set properties to the stream + try + { + xPropSet.setPropertyValue( "Encrypted", Boolean.valueOf( bEncrypted ) ); + } + catch( Exception e ) + { + Error( "Can't set 'Encrypted' property to substream '" + sStreamName + "', exception: " + e ); + return false; + } + + return WriteBytesToStream( xSubStream, sStreamName, sMediaType, bCompressed, pBytes ); + } + + public int ChangeStreamPass( XStorage xStorage, + String sStreamName, + byte[] pOldPass, + byte[] pNewPass ) + { + // open substream element + XStream xSubStream = null; + try + { + Object oSubStream = xStorage.openEncryptedStreamElement( sStreamName, ElementModes.WRITE, new String(pOldPass) ); + xSubStream = UnoRuntime.queryInterface( XStream.class, oSubStream ); + if ( xSubStream == null ) + { + Error( "Can't open substream '" + sStreamName + "'!" ); + return 0; + } + } + catch( Exception e ) + { + Error( "Can't open substream '" + sStreamName + "', exception : " + e + "!" ); + return 0; + } + + + // change the password for the stream + XEncryptionProtectedSource xStreamEncryption = + UnoRuntime.queryInterface( XEncryptionProtectedSource.class, xSubStream ); + + if ( xStreamEncryption == null ) + { + Message( "Optional interface XEncryptionProtectedSource is not implemented, feature can not be tested!" ); + return -1; + } + + try { + xStreamEncryption.setEncryptionPassword( new String(pNewPass) ); + } + catch( Exception e ) + { + Error( "Can't change encryption key of the substream '" + sStreamName + "', exception:" + e ); + return 0; + } + + // free the stream resources, garbage collector may remove the object too late + XComponent xComponent = UnoRuntime.queryInterface( XComponent.class, xSubStream ); + if ( xComponent == null ) + { + Error( "Can't get XComponent implementation from substream '" + sStreamName + "'!" ); + return 0; + } + xComponent.dispose(); + + return 1; + } + + public boolean setStorageTypeAndCheckProps( XStorage xStorage, String sMediaType, boolean bIsRoot, int nMode ) + { + boolean bOk = false; + + // get access to the XPropertySet interface + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xStorage ); + if ( xPropSet != null ) + { + try + { + // set "MediaType" property to the stream + xPropSet.setPropertyValue( "MediaType", sMediaType ); + + // get "IsRoot" and "OpenMode" properties and control there values + boolean bPropIsRoot = AnyConverter.toBoolean( xPropSet.getPropertyValue( "IsRoot" ) ); + int nPropMode = AnyConverter.toInt( xPropSet.getPropertyValue( "OpenMode" ) ); + + bOk = true; + if ( bPropIsRoot != bIsRoot ) + { + Error( "'IsRoot' property contains wrong value!" ); + bOk = false; + } + + if ( ( bIsRoot && ( nPropMode | ElementModes.READ ) != ( nMode | ElementModes.READ ) ) + || ( !bIsRoot && ( nPropMode & nMode ) != nMode ) ) + { + Error( "'OpenMode' property contains wrong value!" ); + bOk = false; + } + } + catch( Exception e ) + { + Error( "Can't control properties of substorage, exception: " + e ); + } + } + else + { + Error( "Can't get XPropertySet implementation from storage!" ); + } + + return bOk; + } + + public boolean checkStorageProperties( XStorage xStorage, String sMediaType, boolean bIsRoot, int nMode ) + { + boolean bOk = false; + + // get access to the XPropertySet interface + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xStorage ); + if ( xPropSet != null ) + { + try + { + // get "MediaType", "IsRoot" and "OpenMode" properties and control there values + String sPropMediaType = AnyConverter.toString( xPropSet.getPropertyValue( "MediaType" ) ); + boolean bPropIsRoot = AnyConverter.toBoolean( xPropSet.getPropertyValue( "IsRoot" ) ); + int nPropMode = AnyConverter.toInt( xPropSet.getPropertyValue( "OpenMode" ) ); + + bOk = true; + if ( !sPropMediaType.equals( sMediaType ) ) + { + Error( "'MediaType' property contains wrong value, expected '" + + sMediaType + "', set '" + sPropMediaType + "' !" ); + bOk = false; + } + + if ( bPropIsRoot != bIsRoot ) + { + Error( "'IsRoot' property contains wrong value!" ); + bOk = false; + } + + if ( ( bIsRoot && ( nPropMode | ElementModes.READ ) != ( nMode | ElementModes.READ ) ) + || ( !bIsRoot && ( nPropMode & nMode ) != nMode ) ) + { + Error( "'OpenMode' property contains wrong value!" ); + bOk = false; + } + } + catch( Exception e ) + { + Error( "Can't get properties of substorage, exception: " + e ); + } + } + else + { + Error( "Can't get XPropertySet implementation from storage!" ); + } + + return bOk; + } + + public boolean InternalCheckStream( XStream xStream, + String sName, + String sMediaType, + byte[] pBytes ) + { + // get input stream of substream + XInputStream xInput = xStream.getInputStream(); + if ( xInput == null ) + { + Error( "Can't get XInputStream implementation from substream '" + sName + "'!" ); + return false; + } + + byte pContents[][] = new byte[1][]; // ??? + + // read contents + try + { + xInput.readBytes( pContents, pBytes.length + 1 ); + } + catch( Exception e ) + { + Error( "Can't read from stream '" + sName + "', exception: " + e ); + return false; + } + + // check size of stream data + if ( pContents.length == 0 ) + { + Error( "SubStream '" + sName + "' reading produced disaster!" ); + return false; + } + + if ( pBytes.length != pContents[0].length ) + { + Error( "SubStream '" + sName + "' contains wrong amount of data! (" + pContents[0].length + "/" + pBytes.length + ")" ); + return false; + } + + // check stream data + for ( int ind = 0; ind < pBytes.length; ind++ ) + { + if ( pBytes[ind] != pContents[0][ind] ) + { + Error( "SubStream '" + sName + "' contains wrong data!" ); + return false; + } + } + + + // check properties + boolean bOk = false; + + // get access to the XPropertySet interface + XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xStream ); + if ( xPropSet != null ) + { + try + { + // get "MediaType" and "Size" properties and control there values + String sPropMediaType = AnyConverter.toString( xPropSet.getPropertyValue( "MediaType" ) ); + long nPropSize = AnyConverter.toLong( xPropSet.getPropertyValue( "Size" ) ); + + bOk = true; + if ( !sPropMediaType.equals( sMediaType ) ) + { + Error( "'MediaType' property contains wrong value for stream '" + sName + "',\nexpected: '" + + sMediaType + "', set: '" + sPropMediaType + "'!" ); + bOk = false; + } + + if ( nPropSize != pBytes.length ) + { + Error( "'Size' property contains wrong value for stream'" + sName + "'!" ); + bOk = false; + } + } + catch( Exception e ) + { + Error( "Can't get properties of substream '" + sName + "', exception: " + e ); + } + } + else + { + Error( "Can't get XPropertySet implementation from stream '" + sName + "'!" ); + } + + return bOk; + } + + public boolean checkStream( XStorage xParentStorage, + String sName, + String sMediaType, + byte[] pBytes ) + { + // open substream element first + XStream xSubStream = null; + try + { + Object oSubStream = xParentStorage.openStreamElement( sName, ElementModes.READ ); + xSubStream = UnoRuntime.queryInterface( XStream.class, oSubStream ); + if ( xSubStream == null ) + { + Error( "Can't open substream '" + sName + "'!" ); + return false; + } + } + catch( Exception e ) + { + Error( "Can't open substream '" + sName + "', exception : " + e + "!" ); + return false; + } + + return InternalCheckStream( xSubStream, sName, sMediaType, pBytes ); + } + + public boolean checkEncrStream( XStorage xParentStorage, + String sName, + String sMediaType, + byte[] pBytes, + byte[] pPass ) + { + // Important: a common password for any of parent storage should not be set or + // should be different from pPass + + if ( pPass.length == 0 ) + { + Error( "Wrong password is used in the test!" ); + return false; + } + + try + { + xParentStorage.openStreamElement( sName, ElementModes.READ ); + Error( "Encrypted stream '" + sName + "' was opened without password!" ); + return false; + } + catch( WrongPasswordException wpe ) + {} + catch( Exception e ) + { + Error( "Unexpected exception in case of opening of encrypted stream '" + sName + "' without password: " + e + "!" ); + return false; + } + + byte pWrongPass[] = { 1, 1 }; + pWrongPass[0] += pPass[0]; + try + { + xParentStorage.openEncryptedStreamElement( sName, ElementModes.READ, new String(pWrongPass) ); + Error( "Encrypted stream '" + sName + "' was opened with wrong password!" ); + return false; + } + catch( WrongPasswordException wpe ) + {} + catch( Exception e ) + { + Error( "Unexpected exception in case of opening of encrypted stream '" + sName + "' with wrong password: " + e + "!" ); + return false; + } + + XStream xSubStream = null; + try + { + Object oSubStream = xParentStorage.openEncryptedStreamElement( sName, ElementModes.READ, new String(pPass) ); + xSubStream = UnoRuntime.queryInterface( XStream.class, oSubStream ); + if ( xSubStream == null ) + { + Error( "Can't open encrypted substream '" + sName + "'!" ); + return false; + } + } + catch( Exception e ) + { + Error( "Can't open encrypted substream '" + sName + "', exception : " + e + "!" ); + return false; + } + + return InternalCheckStream( xSubStream, sName, sMediaType, pBytes ); + } + + public boolean copyStorage( XStorage xSourceStorage, XStorage xDestStorage ) + { + // copy xSourceStorage to xDestStorage + try + { + xSourceStorage.copyToStorage( xDestStorage ); + } + catch( Exception e ) + { + Error( "Storage copying failed, exception: " + e ); + return false; + } + + return true; + } + + public boolean commitStorage( XStorage xStorage ) + { + // XTransactedObject must be supported by storages + XTransactedObject xTransact = UnoRuntime.queryInterface( XTransactedObject.class, xStorage ); + if ( xTransact == null ) + { + Error( "Storage doesn't implement transacted access!" ); + return false; + } + + try + { + xTransact.commit(); + } + catch( Exception e ) + { + Error( "Storage commit failed, exception:" + e ); + return false; + } + + return true; + } + + public boolean disposeStorage( XStorage xStorage ) + { + // dispose the storage + XComponent xComponent = UnoRuntime.queryInterface( XComponent.class, xStorage ); + if ( xComponent == null ) + { + Error( "Can't retrieve XComponent implementation from storage!" ); + return false; + } + + try + { + xComponent.dispose(); + } + catch( Exception e ) + { + Error( "Storage disposing failed!" ); + return false; + } + + return true; + } + + public XInputStream getInputStream( XStream xStream ) + { + XInputStream xInTemp = null; + try + { + xInTemp = xStream.getInputStream(); + if ( xInTemp == null ) + Error( "Can't get the input part of a stream!" ); + } + catch ( Exception e ) + { + Error( "Can't get the input part of a stream, exception :" + e ); + } + + return xInTemp; + } + + public boolean closeOutput( XStream xStream ) + { + XOutputStream xOutTemp = null; + try + { + xOutTemp = xStream.getOutputStream(); + if ( xOutTemp == null ) + { + Error( "Can't get the output part of a stream!" ); + return false; + } + } + catch ( Exception e ) + { + Error( "Can't get the output part of a stream, exception :" + e ); + return false; + } + + try + { + xOutTemp.closeOutput(); + } + catch ( Exception e ) + { + Error( "Can't close output part of a stream, exception :" + e ); + return false; + } + + return true; + } + + public XStorage openSubStorage( XStorage xStorage, String sName, int nMode ) + { + // open existing substorage + try + { + Object oSubStorage = xStorage.openStorageElement( sName, nMode ); + XStorage xSubStorage = UnoRuntime.queryInterface( XStorage.class, oSubStorage ); + return xSubStorage; + } + catch( Exception e ) + { + Error( "Can't open substorage '" + sName + "', exception: " + e ); + } + + return null; + } + + public XStream CreateTempFileStream( XMultiServiceFactory xMSF ) + { + // try to get temporary file representation + XStream xTempFileStream = null; + try + { + Object oTempFile = xMSF.createInstance( "com.sun.star.io.TempFile" ); + xTempFileStream = UnoRuntime.queryInterface( XStream.class, oTempFile ); + } + catch( Exception e ) + {} + + if ( xTempFileStream == null ) + Error( "Can't create temporary file!" ); + + return xTempFileStream; + } + + public String CreateTempFile( XMultiServiceFactory xMSF ) + { + String sResult = null; + + // try to get temporary file representation + XPropertySet xTempFileProps = null; + try + { + Object oTempFile = xMSF.createInstance( "com.sun.star.io.TempFile" ); + xTempFileProps = UnoRuntime.queryInterface( XPropertySet.class, oTempFile ); + } + catch( Exception e ) + {} + + if ( xTempFileProps != null ) + { + try + { + xTempFileProps.setPropertyValue( "RemoveFile", Boolean.FALSE ); + sResult = AnyConverter.toString( xTempFileProps.getPropertyValue( "Uri" ) ); + } + catch( Exception e ) + { + Error( "Can't control TempFile properties, exception: " + e ); + } + } + else + { + Error( "Can't create temporary file representation!" ); + } + + // close temporary file explicitly + try + { + XStream xStream = UnoRuntime.queryInterface( XStream.class, xTempFileProps ); + if ( xStream != null ) + { + XOutputStream xOut = xStream.getOutputStream(); + if ( xOut != null ) + xOut.closeOutput(); + + XInputStream xIn = xStream.getInputStream(); + if ( xIn != null ) + xIn.closeInput(); + } + else + Error( "Can't close TempFile!" ); + } + catch( Exception e ) + { + Error( "Can't close TempFile, exception: " + e ); + } + + return sResult; + } + + public boolean copyElementTo( XStorage xSource, String sName, XStorage xDest ) + { + // copy element with name sName from xSource to xDest + try + { + xSource.copyElementTo( sName, xDest, sName ); + } + catch( Exception e ) + { + Error( "Element copying failed, exception: " + e ); + return false; + } + + return true; + } + + public boolean moveElementTo( XStorage xSource, String sName, XStorage xDest ) + { + // move element with name sName from xSource to xDest + try + { + xSource.moveElementTo( sName, xDest, sName ); + } + catch( Exception e ) + { + Error( "Element moving failed, exception: " + e ); + return false; + } + + return true; + } + + public boolean renameElement( XStorage xStorage, String sOldName, String sNewName ) + { + // rename element with name sOldName to sNewName + try + { + xStorage.renameElement( sOldName, sNewName ); + } + catch( Exception e ) + { + Error( "Element renaming failed, exception: " + e ); + return false; + } + + return true; + } + + public boolean removeElement( XStorage xStorage, String sName ) + { + // remove element with name sName + try + { + xStorage.removeElement( sName ); + } + catch( Exception e ) + { + Error( "Element removing failed, exception: " + e ); + return false; + } + + return true; + } + + public XStream OpenStream( XStorage xStorage, + String sStreamName, + int nMode ) + { + // open substream element + XStream xSubStream = null; + try + { + Object oSubStream = xStorage.openStreamElement( sStreamName, nMode ); + xSubStream = UnoRuntime.queryInterface( XStream.class, oSubStream ); + if ( xSubStream == null ) + Error( "Can't create substream '" + sStreamName + "'!" ); + } + catch( Exception e ) + { + Error( "Can't create substream '" + sStreamName + "', exception : " + e + "!" ); + } + + return xSubStream; + } + + public boolean cantOpenStorage( XStorage xStorage, String sName ) + { + // try to open an opened substorage, open call must fail + try + { + Object oDummyStorage = xStorage.openStorageElement( sName, ElementModes.READ ); + Error( "The trying to reopen opened substorage '" + sName + "' must fail!" ); + } + catch( Exception e ) + { + return true; + } + + return false; + } + + public boolean cantOpenStream( XStorage xStorage, String sName, int nMode ) + { + // try to open the substream with specified mode must fail + try + { + Object oDummyStream = xStorage.openStreamElement( sName, nMode ); + Error( "The trying to open substoream '" + sName + "' must fail!" ); + } + catch( Exception e ) + { + return true; + } + + return false; + } + + public void Error( String sError ) + { + System.out.println( m_sTestPrefix + "Error: " + sError ); + } + + public void Message( String sError ) + { + System.out.println( m_sTestPrefix + sError ); + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Text/BookmarkInsertion.java b/odk/examples/java/Text/BookmarkInsertion.java new file mode 100644 index 000000000..0b9dd3fa9 --- /dev/null +++ b/odk/examples/java/Text/BookmarkInsertion.java @@ -0,0 +1,275 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +// comment: Step 1: get the Desktop object from the office +// Step 2: open an empty text document +// Step 3: enter an example text +// Step 4: insert some bookmarks + +// Chapter 5.1.1.4 Inserting bookmarks + + +import com.sun.star.uno.UnoRuntime; + +public class BookmarkInsertion { + + public static void main(String args[]) { + // You need the desktop to create a document + // The getDesktop method does the UNO bootstrapping, gets the + // remote service manager and the desktop object. + com.sun.star.frame.XDesktop xDesktop = null; + xDesktop = getDesktop(); + + // create text document + com.sun.star.text.XTextDocument xTextDocument = null; + xTextDocument = createTextdocument(xDesktop); + + // put example text in document + createExampleData(xTextDocument); + + + String mOffending[] = { "negro(e|es)?","bor(ed|ing)?", + "bloody?", "bleed(ing)?" }; + String mBad[] = { "possib(le|ilit(y|ies))", "real(ly)+", "brilliant" }; + + String sOffendPrefix = "Offending"; + String sBadPrefix = "BadStyle"; + + markList(xTextDocument, mOffending, sOffendPrefix); + markList(xTextDocument, mBad, sBadPrefix); + + System.out.println("Done"); + + System.exit(0); + } + + public static void markList(com.sun.star.text.XTextDocument xTextDocument, + String mList[], String sPrefix) { + int iCounter=0; + com.sun.star.uno.XInterface xSearchInterface = null; + com.sun.star.text.XTextRange xSearchTextRange = null; + + try { + for( iCounter = 0; iCounter < mList.length; iCounter++ ) { + // the findfirst returns a XInterface + xSearchInterface = FindFirst( + xTextDocument, mList[ iCounter ] ); + + if( xSearchInterface != null ) { + // get the TextRange from the XInterface + xSearchTextRange = UnoRuntime.queryInterface( + com.sun.star.text.XTextRange.class, xSearchInterface); + + InsertBookmark(xTextDocument, xSearchTextRange, + sPrefix + iCounter); + } + } + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + } + + + public static void InsertBookmark(com.sun.star.text.XTextDocument xTextDocument, + com.sun.star.text.XTextRange xTextRange, + String sBookName) { + // create a bookmark on a TextRange + try { + // get the MultiServiceFactory from the text document + com.sun.star.lang.XMultiServiceFactory xDocMSF; + xDocMSF = UnoRuntime.queryInterface( + com.sun.star.lang.XMultiServiceFactory.class, xTextDocument); + + // the bookmark service is a context dependent service, you need + // the MultiServiceFactory from the document + Object xObject = xDocMSF.createInstance("com.sun.star.text.Bookmark"); + + // set the name from the bookmark + com.sun.star.container.XNamed xNameAccess = null; + xNameAccess = UnoRuntime.queryInterface( + com.sun.star.container.XNamed.class, xObject); + + xNameAccess.setName(sBookName); + + // create a XTextContent, for the method 'insertTextContent' + com.sun.star.text.XTextContent xTextContent = null; + xTextContent = UnoRuntime.queryInterface( + com.sun.star.text.XTextContent.class, xNameAccess); + + // insertTextContent need a TextRange not a cursor to specify the + // position from the bookmark + xTextDocument.getText().insertTextContent(xTextRange, xTextContent, true); + + System.out.println("Insert bookmark: " + sBookName); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + } + + protected static com.sun.star.uno.XInterface FindFirst( + com.sun.star.text.XTextDocument xTextDocument, String sSearchString) + { + com.sun.star.util.XSearchDescriptor xSearchDescriptor = null; + com.sun.star.util.XSearchable xSearchable = null; + com.sun.star.uno.XInterface xSearchInterface = null; + + try { + xSearchable = UnoRuntime.queryInterface( + com.sun.star.util.XSearchable.class, xTextDocument); + xSearchDescriptor = xSearchable.createSearchDescriptor(); + + xSearchDescriptor.setSearchString(sSearchString); + + com.sun.star.beans.XPropertySet xPropertySet = null; + xPropertySet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xSearchDescriptor); + + xPropertySet.setPropertyValue("SearchRegularExpression", + Boolean.TRUE ); + + xSearchInterface = (com.sun.star.uno.XInterface) + xSearchable.findFirst(xSearchDescriptor); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return xSearchInterface; + } + + protected static void createExampleData( + com.sun.star.text.XTextDocument xTextDocument ) + { + com.sun.star.text.XTextCursor xTextCursor = null; + + try { + xTextCursor = xTextDocument.getText().createTextCursor(); + + xTextCursor.setString( "He heard quiet steps behind him. That didn't bode well. Who could be following him this late at night and in this deadbeat part of town? And at this particular moment, just after he pulled off the big time and was making off with the greenbacks. Was there another crook who'd had the same idea, and was now watching him and waiting for a chance to grab the fruit of his labor?" ); + xTextCursor.collapseToEnd(); + xTextCursor.setString( "Or did the steps behind him mean that one of many bloody officers in town was on to him and just waiting to pounce and snap those cuffs on his wrists? He nervously looked all around. Suddenly he saw the alley. Like lightning he darted off to the left and disappeared between the two warehouses almost falling over the trash can lying in the middle of the sidewalk. He tried to nervously tap his way along in the inky darkness and suddenly stiffened: it was a dead-end, he would have to go back the way he had come" ); + xTextCursor.collapseToEnd(); + xTextCursor.setString( "The steps got louder and louder, he saw the black outline of a figure coming around the corner. Is this the end of the line? he thought pressing himself back against the wall trying to make himself invisible in the dark, was all that planning and energy wasted? He was dripping with sweat now, cold and wet, he could smell the brilliant fear coming off his clothes. Suddenly next to him, with a barely noticeable squeak, a door swung quietly to and fro in the night's breeze." ); + + xTextCursor.gotoStart(false); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + } + + public static com.sun.star.frame.XDesktop getDesktop() { + com.sun.star.frame.XDesktop xDesktop = null; + com.sun.star.lang.XMultiComponentFactory xMCF = null; + + try { + com.sun.star.uno.XComponentContext xContext = null; + + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + + // get the remote office service manager + xMCF = xContext.getServiceManager(); + if( xMCF != null ) { + System.out.println("Connected to a running office ..."); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + xDesktop = UnoRuntime.queryInterface( + com.sun.star.frame.XDesktop.class, oDesktop); + } + else + System.out.println( "Can't create a desktop. No connection, no remote office servicemanager available!" ); + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + + return xDesktop; + } + + public static com.sun.star.text.XTextDocument createTextdocument( + com.sun.star.frame.XDesktop xDesktop ) + { + com.sun.star.text.XTextDocument aTextDocument = null; + + try { + com.sun.star.lang.XComponent xComponent = CreateNewDocument(xDesktop, + "swriter"); + aTextDocument = UnoRuntime.queryInterface( + com.sun.star.text.XTextDocument.class, xComponent); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return aTextDocument; + } + + + protected static com.sun.star.lang.XComponent CreateNewDocument( + com.sun.star.frame.XDesktop xDesktop, + String sDocumentType ) + { + String sURL = "private:factory/" + sDocumentType; + + com.sun.star.lang.XComponent xComponent = null; + com.sun.star.frame.XComponentLoader xComponentLoader = null; + com.sun.star.beans.PropertyValue xEmptyArgs[] = + new com.sun.star.beans.PropertyValue[0]; + + try { + xComponentLoader = UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, xDesktop); + + xComponent = xComponentLoader.loadComponentFromURL( + sURL, "_blank", 0, xEmptyArgs); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return xComponent ; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Text/GraphicsInserter.java b/odk/examples/java/Text/GraphicsInserter.java new file mode 100644 index 000000000..b4b5b49ea --- /dev/null +++ b/odk/examples/java/Text/GraphicsInserter.java @@ -0,0 +1,195 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; + +import java.io.PrintWriter; +import java.io.BufferedWriter; +import java.io.FileWriter; + + +public class GraphicsInserter { + public static void main(String args[]) { + if ( args.length < 1 ) + { + System.out.println( + "usage: java -jar GraphicsInserter.jar \"\"" ); + System.out.println( "\ne.g.:" ); + System.out.println( + "java -jar GraphicsInserter.jar \"file:///f:/TestGraphics.gif\"" ); + System.exit( 1 ); + } + + com.sun.star.uno.XComponentContext xContext = null; + + try { + + // bootstrap UNO and get the remote component context. The context can + // be used to get the service manager + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + // get the remote office service manager + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + /* A desktop environment contains tasks with one or more + frames in which components can be loaded. Desktop is the + environment for components which can instantiate within + frames. */ + com.sun.star.frame.XDesktop xDesktop = UnoRuntime.queryInterface(com.sun.star.frame.XDesktop.class, + xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", + xContext ) ); + + com.sun.star.frame.XComponentLoader xCompLoader = + UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, xDesktop); + + // Load a Writer document, which will be automatically displayed + com.sun.star.lang.XComponent xComp = xCompLoader.loadComponentFromURL( + "private:factory/swriter", "_blank", 0, + new com.sun.star.beans.PropertyValue[0]); + + // Querying for the interface XTextDocument on the xcomponent + com.sun.star.text.XTextDocument xTextDoc = + UnoRuntime.queryInterface( + com.sun.star.text.XTextDocument.class, xComp); + + // Querying for the interface XMultiServiceFactory on the xtextdocument + com.sun.star.lang.XMultiServiceFactory xMSFDoc = + UnoRuntime.queryInterface( + com.sun.star.lang.XMultiServiceFactory.class, xTextDoc); + + // Providing a log file for output + PrintWriter printwriterLog = new PrintWriter( + new BufferedWriter( new FileWriter("log.txt") ) ); + + Object oGraphic = null; + try { + // Creating the service GraphicObject + oGraphic =xMSFDoc + .createInstance("com.sun.star.text.TextGraphicObject"); + } + catch ( Exception exception ) { + System.out.println( "Could not create instance" ); + exception.printStackTrace( printwriterLog ); + } + + // Getting the text + com.sun.star.text.XText xText = xTextDoc.getText(); + + // Getting the cursor on the document + com.sun.star.text.XTextCursor xTextCursor = xText.createTextCursor(); + + // Querying for the interface XTextContent on the GraphicObject + com.sun.star.text.XTextContent xTextContent = + UnoRuntime.queryInterface( + com.sun.star.text.XTextContent.class, oGraphic ); + + // Printing information to the log file + printwriterLog.println( "inserting graphic" ); + try { + // Inserting the content + xText.insertTextContent(xTextCursor, xTextContent, true); + } catch ( Exception exception ) { + System.out.println( "Could not insert Content" ); + exception.printStackTrace(System.err); + } + + // Printing information to the log file + printwriterLog.println( "adding graphic" ); + + // Querying for the interface XPropertySet on GraphicObject + com.sun.star.beans.XPropertySet xPropSet = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, oGraphic); + try { + // Creating a string for the graphic url + java.io.File sourceFile = new java.io.File(args[0]); + StringBuffer sUrl = new StringBuffer("file:///"); + sUrl.append(sourceFile.getCanonicalPath().replace('\\', '/')); + System.out.println( "insert graphic \"" + sUrl + "\""); + + com.sun.star.graphic.XGraphicProvider xGraphicProvider = + UnoRuntime.queryInterface(com.sun.star.graphic.XGraphicProvider.class, + xMCF.createInstanceWithContext("com.sun.star.graphic.GraphicProvider", + xContext)); + + + com.sun.star.beans.PropertyValue[] aMediaProps = new com.sun.star.beans.PropertyValue[] { new com.sun.star.beans.PropertyValue() }; + aMediaProps[0].Name = "URL"; + aMediaProps[0].Value = sUrl; + + com.sun.star.graphic.XGraphic xGraphic = + UnoRuntime.queryInterface(com.sun.star.graphic.XGraphic.class, + xGraphicProvider.queryGraphic(aMediaProps)); + + // Setting the anchor type + xPropSet.setPropertyValue("AnchorType", + com.sun.star.text.TextContentAnchorType.AT_PARAGRAPH ); + + // Setting the graphic url + xPropSet.setPropertyValue( "Graphic", xGraphic ); + + // Setting the horizontal position + xPropSet.setPropertyValue( "HoriOrientPosition", + Integer.valueOf( 5500 ) ); + + // Setting the vertical position + xPropSet.setPropertyValue( "VertOrientPosition", + Integer.valueOf( 4200 ) ); + + // Setting the width + xPropSet.setPropertyValue( "Width", Integer.valueOf( 4400 ) ); + + // Setting the height + xPropSet.setPropertyValue( "Height", Integer.valueOf( 4000 ) ); + } catch ( Exception exception ) { + System.out.println( "Couldn't set property 'GraphicURL'" ); + exception.printStackTrace( printwriterLog ); + } + + xContext = null; + + System.exit(0); + } + catch( Exception e ) { + e.printStackTrace(System.err); + System.exit(1); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Text/HardFormatting.java b/odk/examples/java/Text/HardFormatting.java new file mode 100644 index 000000000..81a294c86 --- /dev/null +++ b/odk/examples/java/Text/HardFormatting.java @@ -0,0 +1,279 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +// comment: Step 1: get the Desktop object from the office +// Step 2: open an empty text document +// Step 3: enter an example text +// Step 4: get some text attributes +// Step 5: check the PropertyState from the selection + +// Chapter 4.1.4 Hard formatting + + +import com.sun.star.uno.UnoRuntime; + +public class HardFormatting { + + public static void main(String args[]) { + // You need the desktop to create a document + // The getDesktop method does the UNO bootstrapping, gets the + // remote service manager and the desktop object. + com.sun.star.frame.XDesktop xDesktop = null; + xDesktop = getDesktop(); + + try { + // create text document + com.sun.star.text.XTextDocument xTextDocument = null; + xTextDocument = createTextdocument(xDesktop); + + // the text interface contains all methods and properties to + // manipulate the content from a text document + com.sun.star.text.XText xText = null; + xText = xTextDocument.getText(); + + String sMyText = "A very short paragraph for illustration only"; + + // you can travel with the cursor through the text document. + // you travel only at the model, not at the view. The cursor that you can + // see on the document doesn't change the position + com.sun.star.text.XTextCursor xTextCursor = null; + xTextCursor = xTextDocument.getText().createTextCursor(); + + xText.insertString( xTextCursor, "Headline", false ); + xText.insertControlCharacter(xTextCursor, + com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false); + + xText.insertString(xTextCursor, sMyText, false); + + com.sun.star.text.XTextRange xTextRange = null; + com.sun.star.beans.XPropertySet xPropertySet = null; + + // BEGIN: 'Hard formatting' + // the text range not the cursor contains the 'parastyle' property + xTextRange = xText.getEnd(); + xPropertySet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xTextRange); + + // create a paragraph cursor to travel through the paragraphs + com.sun.star.text.XParagraphCursor xParagraphCursor = null; + xParagraphCursor = UnoRuntime.queryInterface( + com.sun.star.text.XParagraphCursor.class, xTextRange); + + xParagraphCursor.gotoStart( false ); + xParagraphCursor.gotoEndOfParagraph( true ); + xTextRange = xParagraphCursor.getText().getStart(); + + // create a WordCursor to travel into the paragraph + com.sun.star.text.XWordCursor xWordCursor = null; + xWordCursor = UnoRuntime.queryInterface( + com.sun.star.text.XWordCursor.class, xTextRange); + + // the PropertySet from the cursor contains the text attributes + xPropertySet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xWordCursor); + System.out.println( + "Parastyle : " + +xPropertySet.getPropertyValue("ParaStyleName").toString() + + "\nFontname : " + + xPropertySet.getPropertyValue("CharFontName").toString() + + "\nWeight : " + + xPropertySet.getPropertyValue("CharWeight").toString() ); + + xWordCursor.gotoNextWord(false); + xWordCursor.gotoNextWord(false); + xWordCursor.gotoEndOfWord(true); + + xPropertySet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xWordCursor); + xPropertySet.setPropertyValue("CharWeight", + new Float(com.sun.star.awt.FontWeight.BOLD)); + xPropertySet.setPropertyValue("CharColor", Integer.valueOf( 255 ) ); + + System.out.println( + "Parastyle : " + + xPropertySet.getPropertyValue("ParaStyleName").toString() + + "\nFontname : " + + xPropertySet.getPropertyValue("CharFontName").toString() + + "\nWeight : " + + xPropertySet.getPropertyValue("CharWeight").toString() ); + + // the PropertyState contains information where the attribute is set, + // is a text part hard formatted or not. + com.sun.star.beans.XPropertyState xPropertyState = null; + xPropertyState = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertyState.class, xWordCursor); + + com.sun.star.beans.PropertyState xPropertyStateValue = + xPropertyState.getPropertyState("CharWeight"); + + checkPropertyState( xWordCursor, xPropertyStateValue ); + + xWordCursor.goRight( (short) 3 , true ); + xPropertyStateValue = xPropertyState.getPropertyState("CharWeight"); + + System.out.println("Increase the selection with three characters"); + checkPropertyState(xWordCursor, xPropertyStateValue); + + xPropertyState.setPropertyToDefault("CharWeight"); + + System.out.println("Set the default value on the selection"); + xPropertyStateValue = xPropertyState.getPropertyState("CharWeight"); + checkPropertyState(xWordCursor, xPropertyStateValue); + + // END: 'Hard formatting' Section from the Cookbook + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + + System.out.println("Done"); + + System.exit(0); + + } + + + public static void checkPropertyState( + com.sun.star.text.XWordCursor xWordCursor, + com.sun.star.beans.PropertyState xPropertyStateValue ) + { + switch( xPropertyStateValue.getValue() ) { + case com.sun.star.beans.PropertyState.DIRECT_VALUE_value: { + System.out.println( "-> The selection '" + + xWordCursor.getString() + + "' completely hard formatted" ); + break; + } + + case com.sun.star.beans.PropertyState.DEFAULT_VALUE_value: { + System.out.println( "-> The selection '" + + xWordCursor.getString() + + "' isn't hard formatted" ); + break; + } + + case com.sun.star.beans.PropertyState.AMBIGUOUS_VALUE_value: { + System.out.println( "-> The selection '" + + xWordCursor.getString() + + "' isn't completely hard formatted" ); + break; + } + + default: + System.out.println( "No PropertyState found" ); + } + } + + public static com.sun.star.frame.XDesktop getDesktop() { + com.sun.star.frame.XDesktop xDesktop = null; + com.sun.star.lang.XMultiComponentFactory xMCF = null; + + try { + com.sun.star.uno.XComponentContext xContext = null; + + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + + // get the remote office service manager + xMCF = xContext.getServiceManager(); + if( xMCF != null ) { + System.out.println("Connected to a running office ..."); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + xDesktop = UnoRuntime.queryInterface( + com.sun.star.frame.XDesktop.class, oDesktop); + } + else + System.out.println( "Can't create a desktop. No connection, no remote office servicemanager available!" ); + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + + return xDesktop; + } + + public static com.sun.star.text.XTextDocument createTextdocument( + com.sun.star.frame.XDesktop xDesktop ) + { + com.sun.star.text.XTextDocument aTextDocument = null; + + try { + com.sun.star.lang.XComponent xComponent = CreateNewDocument(xDesktop, + "swriter"); + aTextDocument = UnoRuntime.queryInterface( + com.sun.star.text.XTextDocument.class, xComponent); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return aTextDocument; + } + + + protected static com.sun.star.lang.XComponent CreateNewDocument( + com.sun.star.frame.XDesktop xDesktop, + String sDocumentType ) + { + String sURL = "private:factory/" + sDocumentType; + + com.sun.star.lang.XComponent xComponent = null; + com.sun.star.frame.XComponentLoader xComponentLoader = null; + com.sun.star.beans.PropertyValue xEmptyArgs[] = + new com.sun.star.beans.PropertyValue[0]; + + try { + xComponentLoader = UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, xDesktop); + + xComponent = xComponentLoader.loadComponentFromURL( + sURL, "_blank", 0, xEmptyArgs); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return xComponent ; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Text/Makefile b/odk/examples/java/Text/Makefile new file mode 100644 index 000000000..cdfdcb29f --- /dev/null +++ b/odk/examples/java/Text/Makefile @@ -0,0 +1,135 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java Text examples of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +EXAMPLE_NAME=JavaTextExamples +OUT_APP_CLASS = $(OUT_CLASS)/$(EXAMPLE_NAME) + +APP1_NAME=BookmarkInsertion +APP1_JAR=$(OUT_APP_CLASS)/$(APP1_NAME).jar +APP2_NAME=HardFormatting +APP2_JAR=$(OUT_APP_CLASS)/$(APP2_NAME).jar +APP3_NAME=StyleCreation +APP3_JAR=$(OUT_APP_CLASS)/$(APP3_NAME).jar +APP4_NAME=StyleInitialization +APP4_JAR=$(OUT_APP_CLASS)/$(APP4_NAME).jar +APP5_NAME=SWriter +APP5_JAR=$(OUT_APP_CLASS)/$(APP5_NAME).jar +APP6_NAME=TextDocumentStructure +APP6_JAR=$(OUT_APP_CLASS)/$(APP6_NAME).jar +APP7_NAME=TextReplace +APP7_JAR=$(OUT_APP_CLASS)/$(APP7_NAME).jar +APP8_NAME=WriterSelector +APP8_JAR=$(OUT_APP_CLASS)/$(APP8_NAME).jar +APP9_NAME=GraphicsInserter +APP9_JAR=$(OUT_APP_CLASS)/$(APP9_NAME).jar + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(OUT_APP_CLASS)) + +# Targets +.PHONY: ALL +ALL : \ + $(EXAMPLE_NAME) + +include $(SETTINGS)/stdtarget.mk + +$(OUT_APP_CLASS)/%.class : %.java + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(OUT_APP_CLASS) $< + +$(OUT_APP_CLASS)/%.mf : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo Main-Class: com.sun.star.lib.loader.Loader> $@ + $(ECHOLINE)>> $@ + @echo Name: com/sun/star/lib/loader/Loader.class>> $@ + @echo Application-Class: $*>> $@ + +$(OUT_APP_CLASS)/%.jar : $(OUT_APP_CLASS)/%.mf $(OUT_APP_CLASS)/%.class + -$(MKDIR) $(subst /,$(PS),$(@D)) + +cd $(subst /,$(PS),$(OUT_APP_CLASS)) && $(SDK_JAR) cvfm $(@F) $*.mf $*.class + +$(SDK_JAR) uvf $@ $(SDK_JAVA_UNO_BOOTSTRAP_FILES) + + +$(APP1_JAR) : $(OUT_APP_CLASS)/$(APP1_NAME).mf $(OUT_APP_CLASS)/$(APP1_NAME).class +$(APP2_JAR) : $(OUT_APP_CLASS)/$(APP2_NAME).mf $(OUT_APP_CLASS)/$(APP2_NAME).class +$(APP3_JAR) : $(OUT_APP_CLASS)/$(APP3_NAME).mf $(OUT_APP_CLASS)/$(APP3_NAME).class +$(APP4_JAR) : $(OUT_APP_CLASS)/$(APP4_NAME).mf $(OUT_APP_CLASS)/$(APP4_NAME).class +$(APP5_JAR) : $(OUT_APP_CLASS)/$(APP5_NAME).mf $(OUT_APP_CLASS)/$(APP5_NAME).class +$(APP6_JAR) : $(OUT_APP_CLASS)/$(APP6_NAME).mf $(OUT_APP_CLASS)/$(APP6_NAME).class +$(APP7_JAR) : $(OUT_APP_CLASS)/$(APP7_NAME).mf $(OUT_APP_CLASS)/$(APP7_NAME).class +$(APP8_JAR) : $(OUT_APP_CLASS)/$(APP8_NAME).mf $(OUT_APP_CLASS)/$(APP8_NAME).class +$(APP9_JAR) : $(OUT_APP_CLASS)/$(APP9_NAME).mf $(OUT_APP_CLASS)/$(APP9_NAME).class + +$(EXAMPLE_NAME) : $(APP1_JAR) $(APP2_JAR) $(APP3_JAR) $(APP4_JAR) $(APP5_JAR) $(APP6_JAR) $(APP7_JAR) $(APP8_JAR) $(APP9_JAR) + @echo -------------------------------------------------------------------------------- + @echo The GraphicsInserter example loads the graphic "$(QM)./oo_smiley.gif$(QM)" into a + @echo new document. + @echo - + @echo Please use one of the following commands to execute the examples! + @echo ------ + @echo $(MAKE) BookmarkInsertion.run + @echo $(MAKE) HardFormatting.run + @echo $(MAKE) StyleCreation.run + @echo $(MAKE) StyleInitialization.run + @echo $(MAKE) SWriter.run + @echo $(MAKE) TextDocumentStructure.run + @echo $(MAKE) TextReplace.run + @echo $(MAKE) WriterSelector.run + @echo $(MAKE) GraphicsInserter.run + @echo -------- + @echo The GraphicsInserter needs parameters. Please use the following command to + @echo start the demo if you do not want the default parameters specified in the + @echo this makefile. Starting without parameters print a command line help: + @echo --- GraphicsInserter --- + @echo java -jar GraphicsInserter.jar "$(QM)graphic Url|path$(QM)" + @echo -------------------------------------------------------------------------------- + +%.run: $(OUT_APP_CLASS)/%.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< + +GraphicsInserter.run: $(OUT_APP_CLASS)/GraphicsInserter.jar + $(SDK_JAVA) -Dcom.sun.star.lib.loader.unopath="$(OFFICE_PROGRAM_PATH)" -jar $< oo_smiley.gif + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(OUT_APP_CLASS)) diff --git a/odk/examples/java/Text/SWriter.java b/odk/examples/java/Text/SWriter.java new file mode 100644 index 000000000..fc960c1f2 --- /dev/null +++ b/odk/examples/java/Text/SWriter.java @@ -0,0 +1,390 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +// comment: Step 1: bootstrap UNO and get the remote component context +// Step 2: open an empty text document +// Step 3: enter some text +// Step 4: insert a text table +// Step 5: insert colored text +// Step 6: insert a text frame + + +import com.sun.star.uno.UnoRuntime; + +public class SWriter { + + public static void main(String args[]) { + + + //oooooooooooooooooooooooooooStep 1oooooooooooooooooooooooooooooooooooooooo + // bootstrap UNO and get the remote component context. The context can + // be used to get the service manager + + com.sun.star.uno.XComponentContext xContext = null; + + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + if( xContext != null ) + System.out.println("Connected to a running office ..."); + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + //oooooooooooooooooooooooooooStep 2oooooooooooooooooooooooooooooooooooooooo + // open an empty document. In this case it's a writer document. + // For this purpose an instance of com.sun.star.frame.Desktop + // is created. It's interface XDesktop provides the XComponentLoader, + // which is used to open the document via loadComponentFromURL + + + //Open Writer document + + System.out.println("Opening an empty Writer document"); + com.sun.star.text.XTextDocument myDoc = openWriter(xContext); + + + + + //oooooooooooooooooooooooooooStep 3oooooooooooooooooooooooooooooooooooooooo + // insert some text. + // For this purpose get the Text-Object of the document and create the + // cursor. Now it is possible to insert a text at the cursor-position + // via insertString + + + + //getting the text object + com.sun.star.text.XText xText = myDoc.getText(); + + //create a cursor object + com.sun.star.text.XTextCursor xTCursor = xText.createTextCursor(); + + //inserting some Text + xText.insertString( xTCursor, "The first line in the newly created text document.\n", false ); + + //inserting a second line + xText.insertString( xTCursor, "Now we're in the second line\n", false ); + + + + + //oooooooooooooooooooooooooooStep 4oooooooooooooooooooooooooooooooooooooooo + // insert a text table. + // For this purpose get MultiServiceFactory of the document, create an + // instance of com.sun.star.text.TextTable and initialize it. Now it can + // be inserted at the cursor position via insertTextContent. + // After that some properties are changed and some data is inserted. + + + //inserting a text table + System.out.println("Inserting a text table"); + + //getting MSF of the document + com.sun.star.lang.XMultiServiceFactory xDocMSF = + UnoRuntime.queryInterface( + com.sun.star.lang.XMultiServiceFactory.class, myDoc); + + //create instance of a text table + com.sun.star.text.XTextTable xTT = null; + + try { + Object oInt = xDocMSF.createInstance("com.sun.star.text.TextTable"); + xTT = UnoRuntime.queryInterface(com.sun.star.text.XTextTable.class,oInt); + } catch (Exception e) { + System.err.println("Couldn't create instance "+ e); + e.printStackTrace(System.err); + } + + //initialize the text table with 4 columns an 4 rows + xTT.initialize(4,4); + + com.sun.star.beans.XPropertySet xTTRowPS = null; + + //insert the table + try { + xText.insertTextContent(xTCursor, xTT, false); + // get first Row + com.sun.star.container.XIndexAccess xTTRows = xTT.getRows(); + xTTRowPS = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xTTRows.getByIndex(0)); + + } catch (Exception e) { + System.err.println("Couldn't insert the table " + e); + e.printStackTrace(System.err); + } + + + // get the property set of the text table + + com.sun.star.beans.XPropertySet xTTPS = UnoRuntime.queryInterface(com.sun.star.beans.XPropertySet.class, xTT); + + // Change the BackColor + try { + xTTPS.setPropertyValue("BackTransparent", Boolean.FALSE); + xTTPS.setPropertyValue("BackColor",Integer.valueOf(13421823)); + xTTRowPS.setPropertyValue("BackTransparent", Boolean.FALSE); + xTTRowPS.setPropertyValue("BackColor",Integer.valueOf(6710932)); + + } catch (Exception e) { + System.err.println("Couldn't change the color " + e); + e.printStackTrace(System.err); + } + + // write Text in the Table headers + System.out.println("Write text in the table headers"); + + insertIntoCell("A1","FirstColumn", xTT); + insertIntoCell("B1","SecondColumn", xTT) ; + insertIntoCell("C1","ThirdColumn", xTT) ; + insertIntoCell("D1","SUM", xTT) ; + + + //Insert Something in the text table + System.out.println("Insert something in the text table"); + + (xTT.getCellByName("A2")).setValue(22.5); + (xTT.getCellByName("B2")).setValue(5615.3); + (xTT.getCellByName("C2")).setValue(-2315.7); + (xTT.getCellByName("D2")).setFormula("sum "); + + (xTT.getCellByName("A3")).setValue(21.5); + (xTT.getCellByName("B3")).setValue(615.3); + (xTT.getCellByName("C3")).setValue(-315.7); + (xTT.getCellByName("D3")).setFormula("sum "); + + (xTT.getCellByName("A4")).setValue(121.5); + (xTT.getCellByName("B4")).setValue(-615.3); + (xTT.getCellByName("C4")).setValue(415.7); + (xTT.getCellByName("D4")).setFormula("sum "); + + + //oooooooooooooooooooooooooooStep 5oooooooooooooooooooooooooooooooooooooooo + // insert a colored text. + // Get the propertySet of the cursor, change the CharColor and add a + // shadow. Then insert the Text via InsertString at the cursor position. + + + // get the property set of the cursor + com.sun.star.beans.XPropertySet xTCPS = UnoRuntime.queryInterface(com.sun.star.beans.XPropertySet.class, + xTCursor); + + // Change the CharColor and add a Shadow + try { + xTCPS.setPropertyValue("CharColor",Integer.valueOf(255)); + xTCPS.setPropertyValue("CharShadowed", Boolean.TRUE); + } catch (Exception e) { + System.err.println("Couldn't change the color " + e); + e.printStackTrace(System.err); + } + + //create a paragraph break + try { + xText.insertControlCharacter(xTCursor, + com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false); + + } catch (Exception e) { + System.err.println("Couldn't insert break "+ e); + e.printStackTrace(System.err); + } + + //inserting colored Text + System.out.println("Inserting colored Text"); + + xText.insertString(xTCursor, " This is a colored Text - blue with shadow\n", + false ); + + //create a paragraph break + try { + xText.insertControlCharacter(xTCursor, + com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false); + + } catch (Exception e) { + System.err.println("Couldn't insert break "+ e); + e.printStackTrace(System.err); + } + + //oooooooooooooooooooooooooooStep 6oooooooooooooooooooooooooooooooooooooooo + // insert a text frame. + // create an instance of com.sun.star.text.TextFrame using the MSF of the + // document. Change some properties an insert it. + // Now get the text-Object of the frame and the corresponding cursor. + // Insert some text via insertString. + + + // Create a TextFrame + com.sun.star.text.XTextFrame xTF = null; + com.sun.star.drawing.XShape xTFS = null; + + try { + Object oInt = xDocMSF.createInstance("com.sun.star.text.TextFrame"); + xTF = UnoRuntime.queryInterface( + com.sun.star.text.XTextFrame.class,oInt); + xTFS = UnoRuntime.queryInterface( + com.sun.star.drawing.XShape.class,oInt); + + com.sun.star.awt.Size aSize = new com.sun.star.awt.Size(); + aSize.Height = 400; + aSize.Width = 15000; + + xTFS.setSize(aSize); + } catch (Exception e) { + System.err.println("Couldn't create instance "+ e); + e.printStackTrace(System.err); + } + + // get the property set of the text frame + com.sun.star.beans.XPropertySet xTFPS = UnoRuntime.queryInterface(com.sun.star.beans.XPropertySet.class, xTF); + + // Change the AnchorType + try { + xTFPS.setPropertyValue("AnchorType", + com.sun.star.text.TextContentAnchorType.AS_CHARACTER); + } catch (Exception e) { + System.err.println("Couldn't change the color " + e); + e.printStackTrace(System.err); + } + + //insert the frame + System.out.println("Insert the text frame"); + + try { + xText.insertTextContent(xTCursor, xTF, false); + } catch (Exception e) { + System.err.println("Couldn't insert the frame " + e); + e.printStackTrace(System.err); + } + + //getting the text object of Frame + com.sun.star.text.XText xTextF = xTF.getText(); + + //create a cursor object + com.sun.star.text.XTextCursor xTCF = xTextF.createTextCursor(); + + //inserting some Text + xTextF.insertString(xTCF, + "The first line in the newly created text frame.", false); + + + xTextF.insertString(xTCF, + "\nWith this second line the height of the frame raises.", false); + + //insert a paragraph break + try { + xText.insertControlCharacter(xTCursor, + com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false ); + + } catch (Exception e) { + System.err.println("Couldn't insert break "+ e); + e.printStackTrace(System.err); + } + + // Change the CharColor and add a Shadow + try { + xTCPS.setPropertyValue("CharColor",Integer.valueOf(65536)); + xTCPS.setPropertyValue("CharShadowed", Boolean.FALSE); + } catch (Exception e) { + System.err.println("Couldn't change the color " + e); + e.printStackTrace(System.err); + } + + xText.insertString(xTCursor, " That's all for now !!", false ); + + System.out.println("done"); + + System.exit(0); + } + + + public static com.sun.star.text.XTextDocument openWriter( + com.sun.star.uno.XComponentContext xContext) + { + //define variables + com.sun.star.frame.XComponentLoader xCLoader; + com.sun.star.text.XTextDocument xDoc = null; + com.sun.star.lang.XComponent xComp = null; + + try { + // get the remote office service manager + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + + xCLoader = UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class, + oDesktop); + com.sun.star.beans.PropertyValue [] szEmptyArgs = + new com.sun.star.beans.PropertyValue [0]; + String strDoc = "private:factory/swriter"; + xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs); + xDoc = UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class, + xComp); + + } catch(Exception e){ + System.err.println(" Exception " + e); + e.printStackTrace(System.err); + } + return xDoc; + } + + public static void insertIntoCell(String CellName, String theText, + com.sun.star.text.XTextTable xTTbl) { + + com.sun.star.text.XText xTableText = UnoRuntime.queryInterface(com.sun.star.text.XText.class, + xTTbl.getCellByName(CellName)); + + //create a cursor object + com.sun.star.text.XTextCursor xTC = xTableText.createTextCursor(); + + com.sun.star.beans.XPropertySet xTPS = UnoRuntime.queryInterface(com.sun.star.beans.XPropertySet.class, xTC); + + try { + xTPS.setPropertyValue("CharColor",Integer.valueOf(16777215)); + } catch (Exception e) { + System.err.println(" Exception " + e); + e.printStackTrace(System.err); + } + + //inserting some Text + xTableText.setString( theText ); + + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Text/StyleCreation.java b/odk/examples/java/Text/StyleCreation.java new file mode 100644 index 000000000..d5151eca7 --- /dev/null +++ b/odk/examples/java/Text/StyleCreation.java @@ -0,0 +1,224 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +// comment: Step 1: get the Desktop object from the office +// Step 2: open an empty text document +// Step 3: create a new Paragraph style +// Step 4: apply the Paragraph style + +// Chapter 4.1.3 Defining Your Own Style + + +import com.sun.star.uno.UnoRuntime; + + +public class StyleCreation { + public static void main(String args[]) { + // You need the desktop to create a document + // The getDesktop method does the UNO bootstrapping, gets the + // remote service manager and the desktop object. + com.sun.star.frame.XDesktop xDesktop = null; + xDesktop = getDesktop(); + + try { + // create text document + com.sun.star.text.XTextDocument xTextDocument = null; + xTextDocument = createTextdocument(xDesktop); + + // the service '..ParagraphStyle' is context dependent, you need + // the multi service factory from the document to use the service + com.sun.star.lang.XMultiServiceFactory xDocMSF = + UnoRuntime.queryInterface( + com.sun.star.lang.XMultiServiceFactory.class, xTextDocument); + + // use the service 'com.sun.star.style.ParagraphStyle' + com.sun.star.uno.XInterface xInterface = (com.sun.star.uno.XInterface) + xDocMSF.createInstance("com.sun.star.style.ParagraphStyle"); + + // create a supplier to get the Style family collection + com.sun.star.style.XStyleFamiliesSupplier xSupplier = + UnoRuntime.queryInterface( + com.sun.star.style.XStyleFamiliesSupplier.class, xTextDocument ); + + // get the NameAccess interface from the Style family collection + com.sun.star.container.XNameAccess xNameAccess = + xSupplier.getStyleFamilies(); + + // select the Paragraph styles, you get the Paragraph style collection + com.sun.star.container.XNameContainer xParaStyleCollection = + UnoRuntime.queryInterface( + com.sun.star.container.XNameContainer.class, + xNameAccess.getByName("ParagraphStyles")); + + // create a PropertySet to set the properties for the new Paragraphstyle + com.sun.star.beans.XPropertySet xPropertySet = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xInterface ); + System.out.println( "create a PropertySet to set the properties for the new Paragraphstyle" ); + + // set some properties from the Paragraph style + xPropertySet.setPropertyValue("CharFontName", "Helvetica" ); + System.out.println( "set name of the font to 'Helvetica'" ); + + xPropertySet.setPropertyValue("CharHeight", new Float( 36 ) ); + System.out.println( "Change the height of th font to 36" ); + + xPropertySet.setPropertyValue("CharWeight", + new Float( com.sun.star.awt.FontWeight.BOLD ) ); + System.out.println( "set the font attribute 'Bold'" ); + + xPropertySet.setPropertyValue("CharAutoKerning", Boolean.TRUE ); + System.out.println( "set the paragraph attribute 'AutoKerning'" ); + xPropertySet.setPropertyValue("ParaAdjust", + Integer.valueOf( com.sun.star.style.ParagraphAdjust.CENTER_value ) ); + System.out.println( "set the paragraph adjust to LEFT" ); + + xPropertySet.setPropertyValue("ParaFirstLineIndent", Integer.valueOf( 0 ) ); + System.out.println( "set the first line indent to 0 cm" ); + + xPropertySet.setPropertyValue("BreakType", + com.sun.star.style.BreakType.PAGE_AFTER ); + System.out.println( "set the paragraph attribute Breaktype to PageAfter" ); + + // insert the new Paragraph style in the Paragraph style collection + xParaStyleCollection.insertByName( "myheading", xPropertySet ); + System.out.println( "create new paragraph style, with the values from the Propertyset"); + + // get the Textrange from the document + com.sun.star.text.XTextRange xTextRange = + xTextDocument.getText().getStart(); + + // get the PropertySet from the current paragraph + com.sun.star.beans.XPropertySet xParagraphPropertySet = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xTextRange ); + // change the value from the property 'ParaStyle' to apply the + // Paragraph style + // To run the sample with StarOffice 5.2 you'll have to change + // 'ParaStyleName' to 'ParaStyle' in the next line + xParagraphPropertySet.setPropertyValue("ParaStyleName", + "myheading" ); + System.out.println( "apply the new paragraph style"); + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + System.out.println("done"); + + System.exit(0); + } + + + public static com.sun.star.frame.XDesktop getDesktop() { + com.sun.star.frame.XDesktop xDesktop = null; + com.sun.star.lang.XMultiComponentFactory xMCF = null; + + try { + com.sun.star.uno.XComponentContext xContext = null; + + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + + // get the remote office service manager + xMCF = xContext.getServiceManager(); + if( xMCF != null ) { + System.out.println("Connected to a running office ..."); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + xDesktop = UnoRuntime.queryInterface( + com.sun.star.frame.XDesktop.class, oDesktop); + } + else + System.out.println( "Can't create a desktop. No connection, no remote office servicemanager available!" ); + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + + return xDesktop; + } + + public static com.sun.star.text.XTextDocument createTextdocument( + com.sun.star.frame.XDesktop xDesktop ) + { + com.sun.star.text.XTextDocument aTextDocument = null; + + try { + com.sun.star.lang.XComponent xComponent = CreateNewDocument(xDesktop, + "swriter"); + aTextDocument = UnoRuntime.queryInterface( + com.sun.star.text.XTextDocument.class, xComponent); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return aTextDocument; + } + + + protected static com.sun.star.lang.XComponent CreateNewDocument( + com.sun.star.frame.XDesktop xDesktop, + String sDocumentType ) + { + String sURL = "private:factory/" + sDocumentType; + + com.sun.star.lang.XComponent xComponent = null; + com.sun.star.frame.XComponentLoader xComponentLoader = null; + com.sun.star.beans.PropertyValue xEmptyArgs[] = + new com.sun.star.beans.PropertyValue[0]; + + try { + xComponentLoader = UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, xDesktop); + + xComponent = xComponentLoader.loadComponentFromURL( + sURL, "_blank", 0, xEmptyArgs); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return xComponent ; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Text/StyleInitialization.java b/odk/examples/java/Text/StyleInitialization.java new file mode 100644 index 000000000..63ea29b24 --- /dev/null +++ b/odk/examples/java/Text/StyleInitialization.java @@ -0,0 +1,311 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +// comment: Step 1: get the Desktop object from the office +// Step 2: open an empty text document +// Step 3: enter an example text +// Step 4: use the paragraph collection +// Step 5: apply a different paragraph style on the paragraphs + + +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.AnyConverter; + +public class StyleInitialization { + + public static void main(String args[]) { + // You need the desktop to create a document + // The getDesktop method does the UNO bootstrapping, gets the + // remote service manager and the desktop object. + com.sun.star.frame.XDesktop xDesktop = null; + xDesktop = getDesktop(); + + try { + // BEGIN: 'Style basics' Section from the Tutorial + + // create text document + com.sun.star.text.XTextDocument xTextDocument = null; + xTextDocument = createTextdocument( xDesktop ); + + // the text interface contains all methods and properties to + // manipulate the content from a text document + com.sun.star.text.XText xText = null; + xText = xTextDocument.getText(); + + String sMyText = "A very short paragraph for illustration only"; + + // you can travel with the cursor through the text document. + // you travel only at the model, not at the view. The cursor that you can + // see on the document doesn't change the position + com.sun.star.text.XTextCursor xTextCursor = null; + xTextCursor = xTextDocument.getText().createTextCursor(); + + com.sun.star.beans.XPropertySet oCPS = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xTextCursor); + try { + oCPS.setPropertyValue("CharFontName","Helvetica"); + } + catch (Exception ex) { + + } + + xText.insertString( xTextCursor, "Headline", false ); + + try { + oCPS.setPropertyValue("CharFontName","Times"); + } + catch (Exception ex) { + + } + xText.insertControlCharacter(xTextCursor, + com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false); + + xText.insertString( xTextCursor, sMyText, false ); + + com.sun.star.text.XTextRange xTextRange = null; + com.sun.star.beans.XPropertySet xPropertySet = null; + + // the text range not the cursor contains the 'parastyle' property + xTextRange = xText.getEnd(); + xPropertySet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xTextRange ); + + // To run the sample with StarOffice 5.2 you'll have to change + // 'ParaStyleName' to 'ParaStyle' in the next line + System.out.println( "Current Parastyle : " + + xPropertySet.getPropertyValue("ParaStyleName") ); + + // END: 'Style basics' Section from the Tutorial + + // There are two way to travel through the paragraphs, with a + // paragraph cursor, or an enumeration. + // You find both ways in this example + + // The first way, with the paragraph cursor + com.sun.star.text.XParagraphCursor xParagraphCursor = null; + xParagraphCursor = UnoRuntime.queryInterface( + com.sun.star.text.XParagraphCursor.class, xTextRange ); + + xParagraphCursor.gotoStart( false ); + xParagraphCursor.gotoEndOfParagraph( true ); + + // The second way, with the paragraph enumeration + com.sun.star.container.XEnumerationAccess xEnumerationAccess = null; + xEnumerationAccess = UnoRuntime.queryInterface( + com.sun.star.container.XEnumerationAccess.class, xText ); + + // the enumeration contains all paragraph from the document + com.sun.star.container.XEnumeration xParagraphEnumeration = null; + xParagraphEnumeration = xEnumerationAccess.createEnumeration(); + + com.sun.star.text.XTextContent xParagraph = null; + com.sun.star.text.XTextRange xWord = null; + + com.sun.star.container.XEnumerationAccess xParaEnumerationAccess = null; + com.sun.star.container.XEnumeration xPortionEnumeration = null; + + // check if a paragraph is available + while ( xParagraphEnumeration.hasMoreElements() ) { + // get the next paragraph + xParagraph = UnoRuntime.queryInterface( + com.sun.star.text.XTextContent.class, + xParagraphEnumeration.nextElement()); + + // you need the method getAnchor to a TextRange -> to manipulate + // the paragraph + String sText = xParagraph.getAnchor().getString(); + + // create a cursor from this paragraph + com.sun.star.text.XTextCursor xParaCursor = null; + xParaCursor = xParagraph.getAnchor().getText().createTextCursor(); + + // goto the start and end of the paragraph + xParaCursor.gotoStart( false ); + xParaCursor.gotoEnd( true ); + + // The enumeration from the paragraphs contain parts from the + // paragraph with a different attributes. + xParaEnumerationAccess = UnoRuntime.queryInterface( + com.sun.star.container.XEnumerationAccess.class, xParagraph); + xPortionEnumeration = xParaEnumerationAccess.createEnumeration(); + + while ( xPortionEnumeration.hasMoreElements() ) { + // output of all parts from the paragraph with different attributes + xWord = UnoRuntime.queryInterface( + com.sun.star.text.XTextRange.class, + xPortionEnumeration.nextElement()); + String sWordString = xWord.getString(); + System.out.println( "Content of the paragraph : " + sWordString ); + } + } + + // BEGIN: 'Finding a suitable style' Section from the Tutorial + + // create a supplier to get the styles-collection + com.sun.star.style.XStyleFamiliesSupplier xSupplier = null; + xSupplier = UnoRuntime.queryInterface( + com.sun.star.style.XStyleFamiliesSupplier.class, xTextDocument ); + + // use the name access from the collection + com.sun.star.container.XNameAccess xNameAccess = null; + xNameAccess = xSupplier.getStyleFamilies(); + + com.sun.star.container.XNameContainer xParaStyleCollection = null; + xParaStyleCollection = UnoRuntime.queryInterface( + com.sun.star.container.XNameContainer.class, xNameAccess.getByName( "ParagraphStyles" )); + + // create an array from strings with the name of all paragraph styles from the text document + String[] sElementNames = xParaStyleCollection.getElementNames(); + int iElementCount = sElementNames.length; + + for( int iCounter = 0; iCounter < iElementCount; iCounter++ ) { + // specify one paragraph style + com.sun.star.style.XStyle xStyle = null; + xStyle = UnoRuntime.queryInterface( + com.sun.star.style.XStyle.class, + xParaStyleCollection.getByName( sElementNames[iCounter] )); + + // create a property set of all properties from the style + xPropertySet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xStyle ); + + String sFontname = AnyConverter.toString(xPropertySet.getPropertyValue("CharFontName")); + sFontname = sFontname.toLowerCase(); + + // if the style use the font 'Albany', apply it to the current paragraph + if( sFontname.equals("albany") ) { + // create a property set from the current paragraph, to change the paragraph style + xPropertySet = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xTextRange ); + + // To run the sample with StarOffice 5.2 you'll have to change 'ParaStyleName' + // to 'ParaStyle' in the next line + xPropertySet.setPropertyValue("ParaStyleName", sElementNames[iCounter] ); + System.out.println( "Apply the paragraph style : " + sElementNames[iCounter] ); + break; + } + } + // END: 'Finding a suitable style' Section from the Tutorial + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + + System.out.println("Done"); + + System.exit(0); + + } + + public static com.sun.star.frame.XDesktop getDesktop() { + com.sun.star.frame.XDesktop xDesktop = null; + com.sun.star.lang.XMultiComponentFactory xMCF = null; + + try { + com.sun.star.uno.XComponentContext xContext = null; + + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + + // get the remote office service manager + xMCF = xContext.getServiceManager(); + if( xMCF != null ) { + System.out.println("Connected to a running office ..."); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + xDesktop = UnoRuntime.queryInterface( + com.sun.star.frame.XDesktop.class, oDesktop); + } + else + System.out.println( "Can't create a desktop. No connection, no remote office servicemanager available!" ); + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + + return xDesktop; + } + + public static com.sun.star.text.XTextDocument createTextdocument( + com.sun.star.frame.XDesktop xDesktop ) + { + com.sun.star.text.XTextDocument aTextDocument = null; + + try { + com.sun.star.lang.XComponent xComponent = CreateNewDocument(xDesktop, + "swriter"); + aTextDocument = UnoRuntime.queryInterface( + com.sun.star.text.XTextDocument.class, xComponent); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return aTextDocument; + } + + + protected static com.sun.star.lang.XComponent CreateNewDocument( + com.sun.star.frame.XDesktop xDesktop, + String sDocumentType ) + { + String sURL = "private:factory/" + sDocumentType; + + com.sun.star.lang.XComponent xComponent = null; + com.sun.star.frame.XComponentLoader xComponentLoader = null; + com.sun.star.beans.PropertyValue xEmptyArgs[] = + new com.sun.star.beans.PropertyValue[0]; + + try { + xComponentLoader = UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, xDesktop); + + xComponent = xComponentLoader.loadComponentFromURL( + sURL, "_blank", 0, xEmptyArgs); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return xComponent ; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Text/TextDocumentStructure.java b/odk/examples/java/Text/TextDocumentStructure.java new file mode 100644 index 000000000..7f284556d --- /dev/null +++ b/odk/examples/java/Text/TextDocumentStructure.java @@ -0,0 +1,201 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +// comment: Step 1: bootstrap UNO and get the remote component context +// Step 2: open an empty text document +// Step 3: create an enumeration of all paragraphs +// Step 4: create an enumeration of all text portions + + +import com.sun.star.uno.UnoRuntime; + +public class TextDocumentStructure { + + public static void main(String args[]) { + com.sun.star.uno.XComponentContext xContext = null; + + try { + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + // get the remote service manager + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + // create a new instance of the desktop + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + + // get the component laoder from the desktop to create a new + // text document + com.sun.star.frame.XComponentLoader xCLoader = + UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class,oDesktop); + com.sun.star.beans.PropertyValue [] szEmptyArgs = + new com.sun.star.beans.PropertyValue [0]; + String strDoc = "private:factory/swriter"; + + System.out.println("create new text document"); + + com.sun.star.lang.XComponent xComp = xCLoader.loadComponentFromURL( + strDoc, "_blank", 0, szEmptyArgs); + + // query the new document for the XTextDocument interface + com.sun.star.text.XTextDocument xTextDocument = + UnoRuntime.queryInterface( + com.sun.star.text.XTextDocument.class, xComp); + + // create some example data + com.sun.star.text.XText xText = xTextDocument.getText(); + createExampleData( xText ); + + // Begin section 'The structure of text documents' of the Tutorial + + com.sun.star.container.XEnumeration xParagraphEnumeration = null; + com.sun.star.container.XEnumerationAccess xParaEnumerationAccess = null; + com.sun.star.container.XEnumeration xTextPortionEnum; + com.sun.star.text.XTextContent xTextElement = null; + + System.out.println("create an enumeration of all paragraphs"); + // create an enumeration access of all paragraphs of a document + com.sun.star.container.XEnumerationAccess xEnumerationAccess = + UnoRuntime.queryInterface( + com.sun.star.container.XEnumerationAccess.class, xText); + xParagraphEnumeration = xEnumerationAccess.createEnumeration(); + + // Loop through all paragraphs of the document + while ( xParagraphEnumeration.hasMoreElements() ) { + xTextElement = UnoRuntime.queryInterface( + com.sun.star.text.XTextContent.class, + xParagraphEnumeration.nextElement()); + com.sun.star.lang.XServiceInfo xServiceInfo = + UnoRuntime.queryInterface( + com.sun.star.lang.XServiceInfo.class, xTextElement); + + // check ifs the current paragraph really a paragraph or an + // anchor of a frame or picture + if( xServiceInfo.supportsService("com.sun.star.text.Paragraph") ) { + com.sun.star.text.XTextRange xTextRange = + xTextElement.getAnchor(); + System.out.println( "This is a Paragraph" ); + + // create another enumeration to get all text portions of + // the paragraph + xParaEnumerationAccess = + UnoRuntime.queryInterface( + com.sun.star.container.XEnumerationAccess.class, + xTextElement); + xTextPortionEnum = xParaEnumerationAccess.createEnumeration(); + + while ( xTextPortionEnum.hasMoreElements() ) { + com.sun.star.text.XTextRange xTextPortion = + UnoRuntime.queryInterface( + com.sun.star.text.XTextRange.class, + xTextPortionEnum.nextElement()); + System.out.println( "Text from the portion : " + + xTextPortion.getString() ); + + com.sun.star.beans.XPropertySet xPropertySet = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, + xTextPortion); + System.out.println( "Name of the font : " + + xPropertySet.getPropertyValue( "CharFontName" ) ); + + // PropertyState status of each text portion. + com.sun.star.beans.XPropertyState xPropertyState = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertyState.class, + xTextPortion); + + if( xPropertyState.getPropertyState("CharWeight").equals( + com.sun.star.beans.PropertyState.AMBIGUOUS_VALUE) ) + System.out.println( "- The text range contains more than one different attributes" ); + + if( xPropertyState.getPropertyState( "CharWeight" ).equals( + com.sun.star.beans.PropertyState.DIRECT_VALUE ) ) + System.out.println( " - The text range contains hard formats" ); + + if( xPropertyState.getPropertyState( "CharWeight" ).equals( + com.sun.star.beans.PropertyState.DEFAULT_VALUE ) ) + System.out.println( " - The text range doesn't contains hard formats" ); + } + } + else + System.out.println( "The text portion isn't a text paragraph" ); + // End section 'The structure of text documents' of the Tutorial + } + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + System.out.println("done"); + System.exit(0); + } + + public static void createExampleData( com.sun.star.text.XText xText ) { + + try { + xText.setString( "This is an example sentence" ); + + com.sun.star.text.XWordCursor xWordCursor = + UnoRuntime.queryInterface( + com.sun.star.text.XWordCursor.class, xText.getStart()); + + xWordCursor.gotoNextWord(false); + xWordCursor.gotoNextWord(false); + xWordCursor.gotoEndOfWord(true); + + com.sun.star.beans.XPropertySet xPropertySet = + UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xWordCursor ); + xPropertySet.setPropertyValue("CharWeight", + new Float( com.sun.star.awt.FontWeight.BOLD )); + + System.out.println("create example data"); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Text/TextReplace.java b/odk/examples/java/Text/TextReplace.java new file mode 100644 index 000000000..588d88ae6 --- /dev/null +++ b/odk/examples/java/Text/TextReplace.java @@ -0,0 +1,224 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + + +// comment: Step 1: get the Desktop object from the office +// Step 2: open an empty text document +// Step 3: enter an example text +// Step 4: replace some english spelled words with US spelled + + + +import com.sun.star.uno.UnoRuntime; + +public class TextReplace { + + public static void main(String args[]) { + // You need the desktop to create a document + // The getDesktop method does the UNO bootstrapping, gets the + // remote service manager and the desktop object. + com.sun.star.frame.XDesktop xDesktop = null; + xDesktop = getDesktop(); + + com.sun.star.text.XTextDocument xTextDocument = + createTextdocument( xDesktop ); + + createExampleData( xTextDocument ); + + String mBritishWords[] = {"colour", "neighbour", "centre", "behaviour", + "metre", "through" }; + String mUSWords[] = { "color", "neighbor", "center", "behavior", + "meter", "thru" }; + + try { + com.sun.star.util.XReplaceDescriptor xReplaceDescr = null; + com.sun.star.util.XReplaceable xReplaceable = null; + + xReplaceable = UnoRuntime.queryInterface( + com.sun.star.util.XReplaceable.class, xTextDocument); + + // You need a descriptor to set properties for Replace + xReplaceDescr = xReplaceable.createReplaceDescriptor(); + + System.out.println("Change all occurrences of ..."); + for( int iArrayCounter = 0; iArrayCounter < mBritishWords.length; + iArrayCounter++ ) + { + System.out.println(mBritishWords[iArrayCounter] + + " -> " + mUSWords[iArrayCounter]); + // Set the properties the replace method need + xReplaceDescr.setSearchString(mBritishWords[iArrayCounter] ); + xReplaceDescr.setReplaceString(mUSWords[iArrayCounter] ); + + // Replace all words + xReplaceable.replaceAll( xReplaceDescr ); + } + + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + System.out.println("Done"); + + System.exit(0); + + } + + protected static void createExampleData( + com.sun.star.text.XTextDocument xTextDocument ) + { + // Create textdocument and insert example text + com.sun.star.text.XTextCursor xTextCursor = null; + + try { + xTextCursor = xTextDocument.getText().createTextCursor(); + com.sun.star.text.XText xText = xTextDocument.getText(); + + xText.insertString( xTextCursor, + "He nervously looked all around. Suddenly he saw his ", false ); + + xText.insertString( xTextCursor, "neighbour ", true ); + com.sun.star.beans.XPropertySet xCPS = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xTextCursor); + // Set the word blue + xCPS.setPropertyValue( "CharColor", Integer.valueOf( 255 ) ); + // Go to last character + xTextCursor.gotoEnd(false); + xCPS.setPropertyValue( "CharColor", Integer.valueOf( 0 ) ); + + xText.insertString( xTextCursor, "in the alley. Like lightning he darted off to the left and disappeared between the two warehouses almost falling over the trash can lying in the ", false ); + + xText.insertString( xTextCursor, "centre ", true ); + xCPS = UnoRuntime.queryInterface( + com.sun.star.beans.XPropertySet.class, xTextCursor); + // Set the word blue + xCPS.setPropertyValue( "CharColor", Integer.valueOf( 255 ) ); + // Go to last character + xTextCursor.gotoEnd(false); + xCPS.setPropertyValue( "CharColor", Integer.valueOf( 0 ) ); + + xText.insertString( xTextCursor, "of the sidewalk.", false ); + + xText.insertControlCharacter( xTextCursor, + com.sun.star.text.ControlCharacter.PARAGRAPH_BREAK, false ); + xText.insertString( xTextCursor, "He tried to nervously tap his way along in the inky darkness and suddenly stiffened: it was a dead-end, he would have to go back the way he had come.", false ); + + xTextCursor.gotoStart(false); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + } + + public static com.sun.star.frame.XDesktop getDesktop() { + com.sun.star.frame.XDesktop xDesktop = null; + com.sun.star.lang.XMultiComponentFactory xMCF = null; + + try { + com.sun.star.uno.XComponentContext xContext = null; + + // get the remote office component context + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + + // get the remote office service manager + xMCF = xContext.getServiceManager(); + if( xMCF != null ) { + System.out.println("Connected to a running office ..."); + + Object oDesktop = xMCF.createInstanceWithContext( + "com.sun.star.frame.Desktop", xContext); + xDesktop = UnoRuntime.queryInterface( + com.sun.star.frame.XDesktop.class, oDesktop); + } + else + System.out.println( "Can't create a desktop. No connection, no remote office servicemanager available!" ); + } + catch( Exception e) { + e.printStackTrace(System.err); + System.exit(1); + } + + + return xDesktop; + } + + public static com.sun.star.text.XTextDocument createTextdocument( + com.sun.star.frame.XDesktop xDesktop ) + { + com.sun.star.text.XTextDocument aTextDocument = null; + + try { + com.sun.star.lang.XComponent xComponent = CreateNewDocument(xDesktop, + "swriter"); + aTextDocument = UnoRuntime.queryInterface( + com.sun.star.text.XTextDocument.class, xComponent); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return aTextDocument; + } + + + protected static com.sun.star.lang.XComponent CreateNewDocument( + com.sun.star.frame.XDesktop xDesktop, + String sDocumentType ) + { + String sURL = "private:factory/" + sDocumentType; + + com.sun.star.lang.XComponent xComponent = null; + com.sun.star.frame.XComponentLoader xComponentLoader = null; + com.sun.star.beans.PropertyValue xEmptyArgs[] = + new com.sun.star.beans.PropertyValue[0]; + + try { + xComponentLoader = UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, xDesktop); + + xComponent = xComponentLoader.loadComponentFromURL( + sURL, "_blank", 0, xEmptyArgs); + } + catch( Exception e) { + e.printStackTrace(System.err); + } + + return xComponent ; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Text/WriterSelector.java b/odk/examples/java/Text/WriterSelector.java new file mode 100644 index 000000000..31d873733 --- /dev/null +++ b/odk/examples/java/Text/WriterSelector.java @@ -0,0 +1,161 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import com.sun.star.uno.UnoRuntime; + +/** This class gives you information on the selected objects (text range, text + * frame, or graphics) at an OpenOffice.org Server. The Office must be started in + * advance and you must have selected something (text, graphics, ...) + */ +public class WriterSelector { + /** + * @param args No arguments. + */ + public static void main(String args[]) { + com.sun.star.uno.XComponentContext xContext = null; + + try { + + // bootstrap UNO and get the remote component context. The context can + // be used to get the service manager + xContext = com.sun.star.comp.helper.Bootstrap.bootstrap(); + System.out.println("Connected to a running office ..."); + + // get the remote office service manager + com.sun.star.lang.XMultiComponentFactory xMCF = + xContext.getServiceManager(); + + // get a new instance of the desktop + com.sun.star.frame.XDesktop xDesktop = UnoRuntime.queryInterface(com.sun.star.frame.XDesktop.class, + xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", + xContext ) ); + + com.sun.star.frame.XComponentLoader xCompLoader = + UnoRuntime.queryInterface( + com.sun.star.frame.XComponentLoader.class, xDesktop); + + com.sun.star.lang.XComponent xComponent = + xCompLoader.loadComponentFromURL("private:factory/swriter", + "_blank", 0, new com.sun.star.beans.PropertyValue[0]); + { + com.sun.star.text.XTextDocument xDoc =UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class, + xComponent); + xDoc.getText().setString("Please select something in this text and press then \"return\" in the shell where you have started the example.\n"); + + // ensure that the document content is optimal visible + com.sun.star.frame.XModel xModel = + UnoRuntime.queryInterface( + com.sun.star.frame.XModel.class, xDoc); + + com.sun.star.view.XViewSettingsSupplier xViewSettings = + UnoRuntime.queryInterface( + com.sun.star.view.XViewSettingsSupplier.class, xModel.getCurrentController()); + xViewSettings.getViewSettings().setPropertyValue( + "ZoomType", Short.valueOf((short)0)); + } + // test document will be closed later + + System.out.println("\nPlease select something in the test document and press then \"return\" to continues the example ..."); + char c = 'X'; + do{ + c = (char) System.in.read(); + }while ((c != 13) && (c != 10)); + + // Getting the current frame from the OpenOffice.org Server. + com.sun.star.frame.XFrame xframe = xDesktop.getCurrentFrame(); + + // Getting the controller. + com.sun.star.frame.XController xController = xframe.getController(); + + com.sun.star.view.XSelectionSupplier xSelSupplier = + UnoRuntime.queryInterface( + com.sun.star.view.XSelectionSupplier.class, xController ); + + Object oSelection = xSelSupplier.getSelection(); + + com.sun.star.lang.XServiceInfo xServInfo = + UnoRuntime.queryInterface( + com.sun.star.lang.XServiceInfo.class, oSelection ); + + if ( xServInfo.supportsService("com.sun.star.text.TextRanges") ) + { + com.sun.star.container.XIndexAccess xIndexAccess = + UnoRuntime.queryInterface( + com.sun.star.container.XIndexAccess.class, oSelection); + + int count = xIndexAccess.getCount(); + com.sun.star.text.XTextRange xTextRange = null; + for ( int i = 0; i < count; i++ ) { + xTextRange = UnoRuntime.queryInterface( + com.sun.star.text.XTextRange.class, + xIndexAccess.getByIndex(i)); + + System.out.println( "You have selected a text range: \"" + + xTextRange.getString() + "\"." ); + } + } + + if ( xServInfo.supportsService("com.sun.star.text.TextGraphicObject") ) + { + System.out.println( "You have selected a graphics." ); + } + + if ( xServInfo.supportsService("com.sun.star.text.TextTableCursor") ) + { + System.out.println( "You have selected a text table." ); + } + + + // close test document + com.sun.star.util.XCloseable xCloseable = UnoRuntime.queryInterface(com.sun.star.util.XCloseable.class, + xComponent ); + + if (xCloseable != null ) { + xCloseable.close(false); + } else + { + xComponent.dispose(); + } + + System.exit(0); + } + catch( Exception e ) { + e.printStackTrace(System.err); + System.exit(1); + } + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/Text/oo_smiley.gif b/odk/examples/java/Text/oo_smiley.gif new file mode 100644 index 000000000..f9fc08d50 Binary files /dev/null and b/odk/examples/java/Text/oo_smiley.gif differ diff --git a/odk/examples/java/ToDo/Makefile b/odk/examples/java/ToDo/Makefile new file mode 100644 index 000000000..94fc4dde8 --- /dev/null +++ b/odk/examples/java/ToDo/Makefile @@ -0,0 +1,167 @@ +#************************************************************************* +# +# The Contents of this file are made available subject to the terms of +# the BSD license. +# +# Copyright 2000, 2010 Oracle and/or its affiliates. +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of Sun Microsystems, Inc. nor the names of its +# contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +#************************************************************************** + +# Builds the Java Calc Addin example of the SDK. + +PRJ=../../.. +SETTINGS=$(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +# Define non-platform/compiler specific settings +COMP_NAME=ToDo +COMP_CLASS_OUT=$(OUT_CLASS)/$(COMP_NAME) +COMP_GEN_OUT=$(OUT_MISC)/$(COMP_NAME) +COMP_RDB_NAME=$(COMP_NAME).uno.rdb +COMP_RDB=$(COMP_GEN_OUT)/$(COMP_RDB_NAME) +COMP_PACKAGE=$(OUT_BIN)/$(COMP_NAME).$(UNOOXT_EXT) +COMP_PACKAGE_URL=$(subst \\,\,"$(COMP_PACKAGE_DIR)$(PS)$(COMP_NAME).$(UNOOXT_EXT)") +COMP_JAR_NAME=$(COMP_NAME).uno.jar +COMP_JAR=$(COMP_CLASS_OUT)/$(COMP_JAR_NAME) +COMP_JAR_MANIFEST=$(COMP_CLASS_OUT)/$(COMP_NAME).uno.Manifest +COMP_UNOPKG_MANIFEST = $(COMP_GEN_OUT)/META-INF/manifest.xml +COMP_REGISTERFLAG=$(COMP_GEN_OUT)$(PS)java_$(COMP_NAME)_register_component.flag +COMP_COMPONENTS=$(COMP_NAME).components + +IDLFILES = XToDo.idl \ + ToDo.idl + +# normally the idl file should be stored in a directory tree fitting the module +# structure, for the example we know the module structure +PACKAGE = org/openoffice + +COMP_JAVAFILES = ToDo.java +COMP_CLASSFILES = $(patsubst %.java,$(COMP_CLASS_OUT)/%.class,$(COMP_JAVAFILES)) + +GEN_CLASSFILES = $(patsubst %.idl,$(COMP_CLASS_OUT)/$(PACKAGE)/%.class,$(IDLFILES)) +GEN_TYPELIST = $(subst /,.,$(patsubst %.idl,-T$(PACKAGE)/% ,$(IDLFILES))) +GEN_URDFILES = $(patsubst %.idl,$(COMP_GEN_OUT)/%.urd,$(IDLFILES)) + + +$(COMP_NAME)_CLASSFILES = $(COMP_NAME).class \ + $(COMP_NAME)$(QUOTE)$$$(COMP_NAME)Impl.class + +$(COMP_NAME)_CLASSFILES += $(subst $(COMP_CLASS_OUT)/,,$(GEN_CLASSFILES)) + +SDK_CLASSPATH = $(subst $(EMPTYSTRING) $(PATH_SEPARATOR),$(PATH_SEPARATOR),$(CLASSPATH)\ + $(PATH_SEPARATOR)$(COMP_CLASS_OUT)) + + +# Targets +.PHONY: ALL +ALL : JavaToDoExample + +include $(SETTINGS)/stdtarget.mk + +$(COMP_CLASS_OUT)/%.Manifest : + -$(MKDIR) $(subst /,$(PS),$(@D)) + @echo UNO-Type-Path: $(basename $*).uno.jar> $@ + @echo RegistrationClassName: $(basename $(basename $(@F)))>> $@ + +$(COMP_GEN_OUT)/%.urd : %.idl + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(IDLC) -C -I. -I$(IDL_DIR) -O$(COMP_GEN_OUT) $< + +$(COMP_GEN_OUT)/%.rdb : $(GEN_URDFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(REGMERGE) $@ /UCR $(GEN_URDFILES) + +$(GEN_CLASSFILES) : $(COMP_RDB) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(JAVAMAKER) -nD $(GEN_TYPELIST) -O$(COMP_CLASS_OUT) $(COMP_RDB) -X$(URE_TYPES) -X$(OFFICE_TYPES) + +$(COMP_CLASSFILES) : $(COMP_JAVAFILES) $(GEN_CLASSFILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_JAVAC) $(JAVAC_FLAGS) -classpath "$(SDK_CLASSPATH)" -d $(COMP_CLASS_OUT) $(COMP_JAVAFILES) + +# rule for component jar file +$(COMP_JAR) : $(COMP_JAR_MANIFEST) $(COMP_CLASSFILES) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + cd $(subst /,$(PS),$(COMP_CLASS_OUT)) && $(SDK_JAR) cvfm $(@F) $( $@ + @echo $(OSEP)!DOCTYPE manifest:manifest PUBLIC "$(QM)-//OpenOffice.org//DTD Manifest 1.0//EN$(QM)" "$(QM)Manifest.dtd$(QM)"$(CSEP) >> $@ + @echo $(OSEP)manifest:manifest xmlns:manifest="$(QM)http://openoffice.org/2001/manifest$(QM)"$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-typelibrary;type=RDB$(QM)" >> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(subst /META-INF,,$(subst $(OUT_MISC)/,,$(@D))).uno.rdb$(QM)"/$(CSEP) >> $@ + @echo $(SQM) $(SQM)$(OSEP)manifest:file-entry manifest:media-type="$(QM)application/vnd.sun.star.uno-components$(QM)">> $@ + @echo $(SQM) $(SQM)manifest:full-path="$(QM)$(COMP_NAME).components$(QM)"/$(CSEP)>> $@ + @echo $(OSEP)/manifest:manifest$(CSEP) >> $@ + +# rule for component package file +$(COMP_PACKAGE) : $(COMP_RDB) $(COMP_JAR) $(COMP_UNOPKG_MANIFEST) $(COMP_NAME).components + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ $(COMP_NAME).components + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_RDB_NAME) + cd $(subst /,$(PS),$(COMP_CLASS_OUT)) && $(SDK_ZIP) -u ../../bin/$(@F) $(COMP_JAR_NAME) + cd $(subst /,$(PS),$(COMP_GEN_OUT)) && $(SDK_ZIP) -u ../../bin/$(@F) META-INF/manifest.xml + +$(COMP_REGISTERFLAG) : $(COMP_PACKAGE) +ifeq "$(SDK_AUTO_DEPLOYMENT)" "YES" + -$(DEL) $(subst \\,\,$(subst /,$(PS),$@)) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(DEPLOYTOOL) $(COMP_PACKAGE_URL) + @echo flagged > $(subst /,$(PS),$@) +else + @echo -------------------------------------------------------------------------------- + @echo If you want to install your component automatically, please set the environment + @echo variable SDK_AUTO_DEPLOYMENT = YES. But note that auto deployment is only + @echo possible if no office instance is running. + @echo -------------------------------------------------------------------------------- +endif + +JavaToDoExample : $(COMP_REGISTERFLAG) + @echo -------------------------------------------------------------------------------- + @echo The $(COMP_NAME) Java component was installed if SDK_AUTO_DEPLOYMENT = YES. + @echo Please load the "$(QM)ToDo.ods$(QM)" document to see how this component works, see + @echo the example description. + @echo - + @echo $(MAKE) ToDo.ods.load + @echo -------------------------------------------------------------------------------- + +ToDo.ods.load : $(COMP_REGISTERFLAG) + "$(OFFICE_PROGRAM_PATH)$(PS)soffice" $(basename $@) + +.PHONY: clean +clean : + -$(DELRECURSIVE) $(subst /,$(PS),$(COMP_CLASS_OUT)) + -$(DELRECURSIVE) $(subst /,$(PS),$(COMP_GEN_OUT)) + -$(DEL) $(subst \\,\,$(subst /,$(PS),$(COMP_PACKAGE_URL))) diff --git a/odk/examples/java/ToDo/ToDo.components b/odk/examples/java/ToDo/ToDo.components new file mode 100644 index 000000000..0b667b96a --- /dev/null +++ b/odk/examples/java/ToDo/ToDo.components @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/odk/examples/java/ToDo/ToDo.idl b/odk/examples/java/ToDo/ToDo.idl new file mode 100644 index 000000000..d632831c4 --- /dev/null +++ b/odk/examples/java/ToDo/ToDo.idl @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_ORG_OPENOFFICE_TODO_IDL +#define INCLUDED_ORG_OPENOFFICE_TODO_IDL + +#include + +/// org +module org { + /// openoffice + module openoffice { + + /// example service + service ToDo: XToDo; + }; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/ToDo/ToDo.java b/odk/examples/java/ToDo/ToDo.java new file mode 100644 index 000000000..312ab42d3 --- /dev/null +++ b/odk/examples/java/ToDo/ToDo.java @@ -0,0 +1,932 @@ +/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.GregorianCalendar; + +import com.sun.star.beans.XPropertySet; +import com.sun.star.container.XIndexAccess; +import com.sun.star.lang.XMultiComponentFactory; +import com.sun.star.lang.XMultiServiceFactory; +import com.sun.star.lang.XServiceInfo; +import com.sun.star.lang.XSingleComponentFactory; +import com.sun.star.lib.uno.helper.Factory; +import com.sun.star.lib.uno.helper.WeakBase; +import com.sun.star.sheet.XCellRangeMovement; +import com.sun.star.sheet.XFunctionAccess; +import com.sun.star.sheet.XSpreadsheet; +import com.sun.star.sheet.XSpreadsheetDocument; +import com.sun.star.table.CellAddress; +import com.sun.star.table.CellRangeAddress; +import com.sun.star.table.XCell; +import com.sun.star.table.XCellRange; +import com.sun.star.table.XColumnRowRange; +import com.sun.star.table.XTableRows; +import com.sun.star.text.XSimpleText; +import com.sun.star.text.XText; +import com.sun.star.text.XTextCursor; +import com.sun.star.text.XTextField; +import com.sun.star.text.XTextRange; +import com.sun.star.uno.UnoRuntime; +import com.sun.star.uno.XComponentContext; +import org.openoffice.XToDo; + +/** This class capsulates the class, that implements the minimal component, a + * factory for creating the service (__getServiceFactory) and a + * method, that writes the information into the given registry key + * (__writeRegistryServiceInfo). + */ +public class ToDo { + + /** This class implements the component. At least the interfaces + * XInterface, XTypeProvider, and XWeak implemented by the helper class + * WeakBase and XServiceInfo should be provided by the service. + */ + public static class ToDoImpl extends WeakBase implements XServiceInfo, XToDo { + + /** The service name, that must be used to get an instance of this service. + */ + private static final String __serviceName = "org.openoffice.ToDo"; + + /** The initial component contextr, that gives access to + * the service manager, supported singletons, ... + * It's often later used + */ + private XComponentContext m_cmpCtx; + + /** The service manager, that gives access to all registered services. + * It's often later used + */ + private XMultiComponentFactory m_xMCF; + + // Implementation helper variables + private static final int INT_COLUMN_FEATURE = 0; + private static final int INT_COLUMN_NEEDEDDAYS = 2; + private static final int INT_COLUMN_STARTDATE = 3; + private static final int INT_COLUMN_START_DAY_OF_WEEK = 4; + private static final int INT_COLUMN_ENDDATE = 5; + private static final int INT_COLUMN_END_DAY_OF_WEEK = 6; + private static final int INT_COLUMN_DUEDATE = 7; + private static final int INT_COLUMN_STATUS = 8; + + private static final int INT_ROW_FROM = 14; // 8 + + private static final int INT_ROW_HOLIDAYS_START = 4; + private static final int INT_COLUMN_HOLIDAYS_START = 7; // 10 + + private static final String STRING_SEPARATOR = "/"; + + + /** The constructor of the inner class has a XComponenContext parameter. + * @param xCompContext the initial component context + */ + public ToDoImpl(XComponentContext xCompContext) { + try { + m_cmpCtx = xCompContext; + m_xMCF = m_cmpCtx.getServiceManager(); + } + catch( Exception e ) { + e.printStackTrace(System.err); + } + } + + /** This method returns an array of all supported service names. + * @return Array of supported service names. + */ + public String[] getSupportedServiceNames() { + return getServiceNames(); + } + + private static String[] getServiceNames() { + String[] sSupportedServiceNames = { __serviceName }; + return sSupportedServiceNames; + } + + /** This method returns true, if the given service will be + * supported by the component. + * @return True, if the given service name will be supported. + */ + public boolean supportsService(String sServiceName) { + return sServiceName.equals( __serviceName ); + } + + /** Return the class name of the component. + * @return Class name of the component. + */ + public String getImplementationName() { + return ToDoImpl.class.getName(); + } + + /** For every bug/feature listed in a spreadsheet document this method + * calculates the start date, day of week of the start date, the end date + * and the day of week of the end date. All calculations are dependent + * on the values of "Needed Days", "Due Date" and "Status". The columns + * "Needed Days" and "Status" are mandatory. The first feature/bug should + * be placed in row nine. The date to start the calculation should be + * placed in cell C6. The private holidays should be placed in cell K4/K5 + * and below. All rows will be calculated up to the first empty cell in + * the first column. If a cell in the column "Due Date" will be colored + * red, you should take a look at your entries. + * @param aInstance Spreadsheet document. + * @throws com.sun.star.uno.RuntimeException This exception could occur + * at every interface method. + */ + public void recalc( java.lang.Object aInstance ) + throws com.sun.star.uno.RuntimeException { + try { + // Querying for the interface XSpreadsheetDocument + XSpreadsheetDocument xspreadsheetdocument = + UnoRuntime.queryInterface( + XSpreadsheetDocument.class, aInstance ); + + // Querying for the interface XIndexAccess + XIndexAccess xindexaccess = UnoRuntime.queryInterface( XIndexAccess.class, + xspreadsheetdocument.getSheets() ); + + // Getting the first XSpreadsheet + XSpreadsheet xspreadsheet = UnoRuntime.queryInterface( + XSpreadsheet.class, xindexaccess.getByIndex( 0 )); + + // Querying for the interface XCellRange on the XSpreadsheet + XCellRange xcellrange = UnoRuntime.queryInterface( XCellRange.class, xspreadsheet ); + + /* Getting the gregorian calendar with the date on which to start + the calculation */ + GregorianCalendar gregCalAbsoluteStartDate = + this.getGregorianCalendarFromString(this.getStringFromCell( + xcellrange, 5, 2 ) ); + gregCalAbsoluteStartDate.add( Calendar.DATE, -1 ); + + // Set the start date with the absolute start date + GregorianCalendar gregCalStartDate = + (GregorianCalendar) gregCalAbsoluteStartDate.clone(); + + /* Creating the service FunctionAccess, which allows generic + access to all spreadsheet functions */ + Object objectFunctionAccess = + m_xMCF.createInstanceWithContext( + "com.sun.star.sheet.FunctionAccess", m_cmpCtx ); + + // Querying for the interface XFunctionAccess on service + // FunctionAccess + XFunctionAccess xfunctionaccess = UnoRuntime.queryInterface(XFunctionAccess.class, + objectFunctionAccess ); + + // Creating vector for holidays + ArrayList vectorHolidays = new ArrayList(); + + // Get the Official Holidays + this.getOfficialHolidays( vectorHolidays, xcellrange, + xfunctionaccess, + gregCalStartDate.get( + Calendar.YEAR ) ); + + // Get the private holidays + this.getPrivateHolidays(vectorHolidays, xcellrange, + xfunctionaccess); + + // Getting the object array of holidays + Object[] objectSortedHolidays = vectorHolidays.toArray(); + + // Sorting the holidays + Arrays.sort( objectSortedHolidays ); + + // Collect the Official Holidays and the private holidays + Object [][]objectHolidays = + new Object[][] { objectSortedHolidays }; + + // Row index + int intRowTo = ToDoImpl.INT_ROW_FROM - 1; + + // Getting the feature of the first cell + String sFeature = this.getStringFromCell(xcellrange, + intRowTo + 1, + ToDoImpl.INT_COLUMN_FEATURE); + + // Determine the last row with an entry in the first column + while ( ( sFeature != null ) && + ( !sFeature.equals( "" ) ) ) { + intRowTo++; + sFeature = this.getStringFromCell( xcellrange, + intRowTo + 1, ToDoImpl.INT_COLUMN_FEATURE ); + } + + // Setting the last row to be calculated + final int INT_ROW_TO = intRowTo + 1; + + // Deleting cells which will be recalculated + for ( int intRow = ToDoImpl.INT_ROW_FROM; intRow < INT_ROW_TO + 5; + intRow++ ) { + for ( int intColumn = ToDoImpl.INT_COLUMN_STARTDATE; + intColumn <= ToDoImpl.INT_COLUMN_END_DAY_OF_WEEK; + intColumn++ ) { + this.setStringToCell(xcellrange, intRow, intColumn, ""); + } + } + + /* Clearing the background color of the due date cells and setting + the hyperlink to the bugtracker */ + for (int intRow = ToDoImpl.INT_ROW_FROM; intRow < INT_ROW_TO; intRow++) + { + // Querying for the interface XPropertySet for the cell + // providing the due date + XPropertySet xpropertyset = UnoRuntime.queryInterface(XPropertySet.class, + xcellrange.getCellByPosition( + ToDoImpl.INT_COLUMN_DUEDATE, + intRow )); + + // Changing the background color of the cell to white + xpropertyset.setPropertyValue( "CellBackColor", + Integer.valueOf( 16777215 ) ); + + // Getting the cell of the bug id + XCell xcell = xcellrange.getCellByPosition( + ToDoImpl.INT_COLUMN_FEATURE, intRow ); + + // Querying for the interface XSimpleText + XSimpleText xsimpletext = UnoRuntime.queryInterface( XSimpleText.class, xcell ); + + // Getting the text cursor + XTextCursor xtextcursor = xsimpletext.createTextCursor(); + + // Querying for the interface XTextRange + XTextRange xtextrange = UnoRuntime.queryInterface( XTextRange.class, xtextcursor ); + + // Getting the bug ID from the cell + String sBugID = xtextrange.getString(); + if ( !sBugID.startsWith( + "http://www.openoffice.org/issues/show_bug.cgi?id=") ) { + String sBugIDLink = + "http://www.openoffice.org/issues/show_bug.cgi?id=" + sBugID; + + // Querying for the interface XMultiServiceFactory + XMultiServiceFactory xMSFTextField = + UnoRuntime.queryInterface( + XMultiServiceFactory.class, aInstance ); + + // Creating an instance of the text field URL + Object objectTextField = + xMSFTextField.createInstance( + "com.sun.star.text.TextField.URL" ); + + // Querying for the interface XTextField + XTextField xtextfield = UnoRuntime.queryInterface( XTextField.class, + objectTextField ); + + // Querying for the interface XPropertySet + XPropertySet xpropertysetTextField = UnoRuntime.queryInterface( XPropertySet.class, + xtextfield ); + + // Setting the URL + xpropertysetTextField.setPropertyValue( "URL", + sBugIDLink ); + + // Setting the representation of the URL + xpropertysetTextField.setPropertyValue( "Representation", + sBugID ); + + // Querying for the interface XText + XText xtext = UnoRuntime.queryInterface( + XText.class, xcell ); + + // Delete cell content + xtextrange.setString( "" ); + + // Inserting the text field URL to the cell + xtext.insertTextContent( xtextrange, xtextfield, false ); + } + } + + // Processing all features/bugs in the table + for (int intRow = ToDoImpl.INT_ROW_FROM; intRow < INT_ROW_TO; intRow++) + { + // Getting the cell of the column "Needed Days" in the + // current row + XCell xcell = xcellrange.getCellByPosition( + INT_COLUMN_NEEDEDDAYS, intRow ); + + // Getting the number of needed days to perform the feature + int intNeededDays = (int) Math.round( xcell.getValue() ); + + // Getting the content of a specified cell + String sStatus = this.getStringFromCell( xcellrange, + intRow, ToDoImpl.INT_COLUMN_STATUS ); + + /* Testing if the number of needed days is greater than + zero and if + the status is not "done" */ + if ( ( intNeededDays > 0 ) + && !( sStatus.toLowerCase().trim().equals("done")) ) { + // Getting the start date after a specified number of + // workdays + gregCalStartDate = this.getWorkday( + gregCalStartDate, 1, objectHolidays, + xfunctionaccess ); + + // Getting a string with the date format jjjj-mm-dd from + // the gregorian calendar + String sDate = this.getStringFromGregorianCalendar( + gregCalStartDate ); + + // Set the start date in the specified cell of the table + this.setStringToCell(xcellrange, intRow, + ToDoImpl.INT_COLUMN_STARTDATE, sDate); + + // For the start day set the day of week in the specified + // cell of the table + this.setDayOfWeek( gregCalStartDate, + xcellrange, intRow, + ToDoImpl.INT_COLUMN_START_DAY_OF_WEEK ); + + // Getting the end date after a specified number of workdays + GregorianCalendar gregCalEndDate = + this.getWorkday( gregCalStartDate, + intNeededDays - 1, + objectHolidays, xfunctionaccess ); + + // Creating a string with the date format jjjj-mm-dd + sDate = this.getStringFromGregorianCalendar( + gregCalEndDate ); + + // Set the end date in the specified cell of the table + this.setStringToCell( xcellrange, intRow, + ToDoImpl.INT_COLUMN_ENDDATE, sDate ); + + // For the end day set the day of week in the specified + // cell of the table + this.setDayOfWeek(gregCalEndDate, xcellrange, + intRow, ToDoImpl.INT_COLUMN_END_DAY_OF_WEEK); + + // Set the initial date for the next loop + gregCalStartDate = ( GregorianCalendar ) + gregCalEndDate.clone(); + + // Get the due date from the table + String sDueDate = this.getStringFromCell( + xcellrange, intRow, ToDoImpl.INT_COLUMN_DUEDATE ); + + // Testing if the due date is not empty + if ( !sDueDate.equals( "" ) ) { + GregorianCalendar gregCalDueDate = + this.getGregorianCalendarFromString(sDueDate); + + // Testing if the due date is before the calculated + // end date + if ( gregCalDueDate.before( + gregCalEndDate ) ) { + /* Getting the date when the processing of the + feature/bug should + be started at the latest */ + GregorianCalendar gregCalLatestDateToStart = + this.getWorkday(gregCalDueDate, + -( intNeededDays - 1 ), + objectHolidays, + xfunctionaccess); + + // Begin with the current row + int intRowToInsert = intRow; + + // Get the start date for the feature/bug in the + // current row + GregorianCalendar gregCalPreviousStartDate = + this.getGregorianCalendarFromString( + this.getStringFromCell( + xcellrange, intRowToInsert, + ToDoImpl.INT_COLUMN_STARTDATE ) ); + + // Testing if we have to search for an earlier date + // to begin + while ((gregCalLatestDateToStart.before( + gregCalPreviousStartDate)) && + (INT_ROW_FROM != intRowToInsert)) { + // Decrease the row + intRowToInsert--; + + // Get the start date for the feature/bug in + // the current row + String sStartDate = this.getStringFromCell( + xcellrange, intRowToInsert, + ToDoImpl.INT_COLUMN_STARTDATE ); + + // Search until a valid start date is found + while ( sStartDate.equals( "" ) ) { + // Decrease the row + intRowToInsert--; + + // Get the start date for the feature/bug + // in the current row + sStartDate = this.getStringFromCell( + xcellrange, intRowToInsert, + ToDoImpl.INT_COLUMN_STARTDATE ); + } + + // Get the GregorianCalendar format for the + // start date + gregCalPreviousStartDate = + this.getGregorianCalendarFromString( + sStartDate ); + } + + // Getting the cell of the column "Needed Days" + // in the row where to insert + XCell xcellNeededDaysWhereToInsert = + xcellrange.getCellByPosition( + INT_COLUMN_NEEDEDDAYS, intRowToInsert ); + // Getting the number of needed days to perform + // the feature + int intNeededDaysWhereToInsert = (int) + Math.round( + xcellNeededDaysWhereToInsert.getValue()); + + GregorianCalendar gregCalPreviousNewEndDate = + this.getWorkday(gregCalPreviousStartDate, + intNeededDays - 1 + + intNeededDaysWhereToInsert, + objectHolidays, + xfunctionaccess); + String sPreviousDueDate = this.getStringFromCell( + xcellrange, intRowToInsert, + ToDoImpl.INT_COLUMN_DUEDATE ); + + GregorianCalendar gregCalPreviousDueDate = null; + + if ( !sPreviousDueDate.equals( "" ) ) { + gregCalPreviousDueDate = + this.getGregorianCalendarFromString( + sPreviousDueDate ); + } + + if ( ( intRowToInsert == intRow ) || + ( gregCalPreviousNewEndDate.after( + gregCalPreviousDueDate ) ) ) { + // Querying for the interface XPropertySet for + // the cell providing the due date + XPropertySet xpropertyset = UnoRuntime.queryInterface( + XPropertySet.class, + xcellrange.getCellByPosition( + ToDoImpl.INT_COLUMN_DUEDATE, + intRow ) ); + + // Changing the background color of the cell + // to red + xpropertyset.setPropertyValue( + "CellBackColor", Integer.valueOf( 16711680 ) ); + } else { + // Querying for the interface XColumnRowRange + // on the XCellRange + XColumnRowRange xcolumnrowrange = + UnoRuntime.queryInterface( + XColumnRowRange.class, xcellrange ); + // Inserting one row to the table + XTableRows xTableRows = + xcolumnrowrange.getRows(); + xTableRows.insertByIndex( intRowToInsert, 1 ); + + // Querying for the interface + // XCellRangeMovement on XCellRange + XCellRangeMovement xcellrangemovement = + UnoRuntime.queryInterface( + XCellRangeMovement.class, xcellrange ); + + // Creating the cell address of the destination + CellAddress celladdress = new CellAddress(); + celladdress.Sheet = 0; + celladdress.Column = 0; + celladdress.Row = intRowToInsert; + + // Creating the cell range of the source + CellRangeAddress cellrangeaddress = + new CellRangeAddress(); + cellrangeaddress.Sheet = 0; + cellrangeaddress.StartColumn = 0; + cellrangeaddress.StartRow = intRow + 1; + cellrangeaddress.EndColumn = 8; + cellrangeaddress.EndRow = intRow + 1; + + // Moves the cell range to another position in + // the document + xcellrangemovement.moveRange(celladdress, + cellrangeaddress); + + // Removing the row not needed anymore + xcolumnrowrange.getRows().removeByIndex(intRow + + 1, 1); + + // Set the current row, because we want to + // recalculate all rows below + intRow = intRowToInsert - 1; + + // Tests at which line we want to insert + if ( intRow >= ToDoImpl.INT_ROW_FROM ) { + // Get the start date + gregCalStartDate = + this.getGregorianCalendarFromString( + this.getStringFromCell( xcellrange, + intRow,ToDoImpl.INT_COLUMN_ENDDATE)); + } + else { + // Set the start date with the absolute s + // tart date + gregCalStartDate = (GregorianCalendar) + gregCalAbsoluteStartDate.clone(); + } + } + } + } + } + } + } + catch( Exception exception ) { + showExceptionMessage( exception ); + } + } + + /** Getting a string from a gregorian calendar. + * @param gregCal Date to be converted. + * @return string (converted gregorian calendar). + */ + private String getStringFromGregorianCalendar( GregorianCalendar gregCal ) { + String sDate = ( gregCal.get( Calendar.MONTH ) + 1 ) + + STRING_SEPARATOR + gregCal.get( Calendar.DATE ) + + STRING_SEPARATOR + gregCal.get( Calendar.YEAR ); + + return sDate; + } + + /** Getting a GregorianCalendar from a string. + * @param sDate String to be converted. + * @return The result of the converting of the string. + */ + private GregorianCalendar getGregorianCalendarFromString( String sDate ) { + int []intDateValue = this.getDateValuesFromString( sDate ); + + return( new GregorianCalendar( intDateValue[ 2 ], intDateValue[ 0 ], + intDateValue[ 1 ] ) ); + } + + /** Getting the day, month and year from a string. + * @param sDate String to be parsed. + * @return Returns an array of integer variables. + */ + private int[] getDateValuesFromString( String sDate) { + int[] intDateValues = new int[ 3 ]; + + int intPositionFirstTag = sDate.indexOf( STRING_SEPARATOR ); + int intPositionSecondTag = sDate.indexOf(STRING_SEPARATOR, + intPositionFirstTag + 1); + + // Getting the value of the month + intDateValues[ 0 ] = Integer.parseInt( + sDate.substring(0, intPositionFirstTag)) - 1; + // Getting the value of the day + intDateValues[ 1 ] = Integer.parseInt( + sDate.substring(intPositionFirstTag + 1, intPositionSecondTag)); + // Getting the value of the year + intDateValues[ 2 ] = Integer.parseInt( + sDate.substring(intPositionSecondTag + 1, sDate.length())); + + return intDateValues; + } + + /** Getting a content from a specified cell. + * @param xcellrange Providing access to cells. + * @param intRow Number of row. + * @param intColumn Number of column. + * @return String from the specified cell. + */ + private String getStringFromCell( XCellRange xcellrange, int intRow, + int intColumn ) { + XTextRange xtextrangeStartDate = null; + + try { + // Getting the cell holding the information about the start date + XCell xcellStartDate = xcellrange.getCellByPosition(intColumn, + intRow); + // Querying for the interface XTextRange on the XCell + xtextrangeStartDate = UnoRuntime.queryInterface(XTextRange.class, xcellStartDate); + } + catch( Exception exception ) { + this.showExceptionMessage( exception ); + } + + // Getting the start date + return xtextrangeStartDate.getString().trim(); + } + + /** Writing a specified string to a specified cell. + * @param xcellrange Providing access to the cells. + * @param intRow Number of row. + * @param intColumn Number of column. + * @param sDate Date to write to the cell. + */ + private void setStringToCell( XCellRange xcellrange, int intRow, + int intColumn, String sDate ) { + try { + // Getting the cell holding the information on the day to start + XCell xcellStartDate = xcellrange.getCellByPosition(intColumn, + intRow); + // Querying for the interface XTextRange on the XCell + XTextRange xtextrange = UnoRuntime.queryInterface(XTextRange.class, xcellStartDate); + // Setting the new start date + xtextrange.setString( sDate ); + } + catch( Exception exception ) { + this.showExceptionMessage( exception ); + } + } + + /** Calculates the week of day and calls the method "setStringToCell". + * @param gregCal Day to be written to the cell. + * @param xcellrange Providing access to the cells. + * @param intRow Number of row. + * @param intColumn Number of column. + */ + private void setDayOfWeek( GregorianCalendar gregCal, + XCellRange xcellrange, int intRow, + int intColumn) { + int intDayOfWeek = gregCal.get( Calendar.DAY_OF_WEEK ); + String sDayOfWeek = ""; + if ( intDayOfWeek == Calendar.MONDAY ) { + sDayOfWeek = "MON"; + } else if ( intDayOfWeek == Calendar.TUESDAY ) { + sDayOfWeek = "TUE"; + } else if ( intDayOfWeek == Calendar.WEDNESDAY ) { + sDayOfWeek = "WED"; + } else if ( intDayOfWeek == Calendar.THURSDAY ) { + sDayOfWeek = "THU"; + } else if ( intDayOfWeek == Calendar.FRIDAY ) { + sDayOfWeek = "FRI"; + } + + this.setStringToCell( xcellrange, intRow, intColumn, + sDayOfWeek ); + } + + /** Calculates the dates of the official holidays with help of Calc + * functions. + * @param vectorHolidays Holding all holidays. + * @param xcellrange Providing the cells. + * @param xfunctionaccess Provides access to functions of the Calc. + * @param intYear Year to calculate the official holidays. + */ + private void getOfficialHolidays( + ArrayList vectorHolidays, + XCellRange xcellrange, + XFunctionAccess xfunctionaccess, + int intYear ) { + try { + // Official Holidays for how many years? + final int intHowManyYears = 2; + + // Get the Official Holiday for two years + for ( int intNumberOfYear = 0; + intNumberOfYear <= ( intHowManyYears - 1 ); + intNumberOfYear++ ) { + intYear += intNumberOfYear; + + // Getting the Easter sunday + Double dEasterSunday = ( Double ) + xfunctionaccess.callFunction( + "EASTERSUNDAY", new Object[] { Integer.valueOf(intYear) }); + + int intEasterSunday = (int)Math.round( + dEasterSunday.doubleValue()); + + // New-year + vectorHolidays.add( xfunctionaccess.callFunction( + "DATE", + new Object[] { + Integer.valueOf( intYear ), + Integer.valueOf( 1 ), + Integer.valueOf( 1 ) } )); + + // Good Friday + vectorHolidays.add( + new Double( intEasterSunday - 2 ) ); + + // Easter monday + vectorHolidays.add( + new Double( intEasterSunday + 1 ) ); + + // Labour Day + vectorHolidays.add( xfunctionaccess.callFunction( + "DATE", + new Object[] { + Integer.valueOf( intYear ), + Integer.valueOf( 5 ), + Integer.valueOf( 1 ) } )); + + // Ascension Day + vectorHolidays.add(new Double(intEasterSunday + 39 )); + + // Pentecost monday + vectorHolidays.add(new Double(intEasterSunday + 50 )); + + // German Unification + vectorHolidays.add( xfunctionaccess.callFunction( + "DATE", + new Object[] { + Integer.valueOf( intYear ), + Integer.valueOf( 10 ), + Integer.valueOf( 3 ) } )); + + // Christmas Day First + vectorHolidays.add( xfunctionaccess.callFunction( + "DATE", + new Object[] { + Integer.valueOf( intYear ), + Integer.valueOf( 12 ), + Integer.valueOf( 25 ) } )); + + // Christmas Day Second + vectorHolidays.add( xfunctionaccess.callFunction( + "DATE", + new Object[] { + Integer.valueOf( intYear ), + Integer.valueOf( 12 ), + Integer.valueOf( 26 ) } )); + } + } + catch( Exception exception ) { + this.showExceptionMessage( exception ); + } + } + + /** Returns the serial number of the date before or after a specified + * number of workdays. + * @param gregCalStartDate Date to start with the calculation. + * @param intDays Number of workdays (e.g. 5 or -3). + * @param objectHolidays Private and public holidays to take into account. + * @param xfunctionaccess Allows to call functions from the Calc. + * @return The gregorian date before or after a specified number of + * workdays. + */ + private GregorianCalendar getWorkday( + GregorianCalendar gregCalStartDate, + int intDays, Object[][] objectHolidays, + XFunctionAccess xfunctionaccess ) { + GregorianCalendar gregCalWorkday = null; + + try { + // Getting the value of the start date + Double dDate = ( Double ) xfunctionaccess.callFunction( + "DATE", + new Object[] { + Integer.valueOf( gregCalStartDate.get( Calendar.YEAR ) ), + Integer.valueOf( gregCalStartDate.get( Calendar.MONTH ) + 1 ), + Integer.valueOf( gregCalStartDate.get( Calendar.DATE ) ) + } ); + + Double dWorkday = ( Double ) xfunctionaccess.callFunction( + "com.sun.star.sheet.addin.Analysis.getWorkday", + new Object[] { dDate, Integer.valueOf( intDays ), objectHolidays } ); + + Double dYear = ( Double ) xfunctionaccess.callFunction( + "YEAR", new Object[] { dWorkday } ); + Double dMonth = ( Double ) xfunctionaccess.callFunction( + "MONTH", new Object[] { dWorkday } ); + Double dDay = ( Double ) xfunctionaccess.callFunction( + "DAY", new Object[] { dWorkday } ); + + gregCalWorkday = new GregorianCalendar( + dYear.intValue(), + dMonth.intValue() - 1, + dDay.intValue() ); + } + catch( Exception exception ) { + this.showExceptionMessage( exception ); + } + + return gregCalWorkday; + } + + /** Getting the holidays from the spreadsheet. + * @param vectorHolidays Holding all holidays. + * @param xcellrange Providing the cells. + * @param xfunctionaccess Provides the access to functions of the Calc. + */ + private void getPrivateHolidays( ArrayList vectorHolidays, + XCellRange xcellrange, + XFunctionAccess xfunctionaccess ) { + try { + int intRow = ToDoImpl.INT_ROW_HOLIDAYS_START; + int intColumn = ToDoImpl.INT_COLUMN_HOLIDAYS_START; + + double dHolidayStart = xcellrange.getCellByPosition( + intColumn, intRow ).getValue(); + + double dHolidayEnd = xcellrange.getCellByPosition( + intColumn + 1, intRow ).getValue(); + + while ( dHolidayStart != 0 ) { + if ( dHolidayEnd == 0 ) { + vectorHolidays.add( + Integer.valueOf( (int) Math.round( + dHolidayStart ) ) ); + } + else { + for ( int intHoliday = (int) Math.round( + dHolidayStart ); + intHoliday <= (int) Math.round( dHolidayEnd ); + intHoliday++ ) { + vectorHolidays.add( new Double( intHoliday ) ); + } + } + + intRow++; + dHolidayStart = xcellrange.getCellByPosition( + intColumn, intRow).getValue(); + dHolidayEnd = xcellrange.getCellByPosition( + intColumn + 1, intRow).getValue(); + } + } + catch( Exception exception ) { + this.showExceptionMessage( exception ); + } + } + + /** Showing the stack trace in a JOptionPane. + * @param sMessage The message to show. + */ + private void showMessage( String sMessage ) { + javax.swing.JFrame jframe = new javax.swing.JFrame(); + jframe.setLocation(100, 100); + jframe.setSize(300, 200); + jframe.setVisible(true); + javax.swing.JOptionPane.showMessageDialog( + jframe, sMessage, "Debugging information", + javax.swing.JOptionPane.INFORMATION_MESSAGE); + jframe.dispose(); + } + + /** Writing the stack trace from an exception to a string and calling + * the method showMessage() with this string. + * @param exception The occurred exception. + * @see #showMessage(String) + */ + private void showExceptionMessage( Exception exception ) { + java.io.StringWriter swriter = new java.io.StringWriter(); + java.io.PrintWriter printwriter = + new java.io.PrintWriter( swriter ); + exception.printStackTrace( printwriter); + System.err.println( exception ); + this.showMessage( swriter.getBuffer().substring(0) ); + } + } + + /** + * Gives a factory for creating the service. + * This method is called by the JavaLoader + *

+ * @return returns a XSingleComponentFactory for creating + * the component + * @param sImplName the name of the implementation for which a + * service is desired + * @see com.sun.star.comp.loader.JavaLoader + */ + public static XSingleComponentFactory __getComponentFactory(String sImplName) { + XSingleComponentFactory xFactory = null; + + if ( sImplName.equals( ToDoImpl.class.getName() ) ) + xFactory = Factory.createComponentFactory(ToDoImpl.class, + ToDoImpl.getServiceNames()); + + return xFactory; + } +} + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/java/ToDo/ToDo.ods b/odk/examples/java/ToDo/ToDo.ods new file mode 100644 index 000000000..344a5c2e9 Binary files /dev/null and b/odk/examples/java/ToDo/ToDo.ods differ diff --git a/odk/examples/java/ToDo/XToDo.idl b/odk/examples/java/ToDo/XToDo.idl new file mode 100644 index 000000000..11a107c08 --- /dev/null +++ b/odk/examples/java/ToDo/XToDo.idl @@ -0,0 +1,53 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/************************************************************************* + * + * The Contents of this file are made available subject to the terms of + * the BSD license. + * + * Copyright 2000, 2010 Oracle and/or its affiliates. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of Sun Microsystems, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE + * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + *************************************************************************/ + +#ifndef INCLUDED_ORG_OPENOFFICE_XTODO_IDL +#define INCLUDED_ORG_OPENOFFICE_XTODO_IDL + + +/// org +module org { + /// openoffice + module openoffice { + /// example interface + interface XToDo { + void recalc( [in] any aInstance ); + }; + }; +}; + +#endif + +/* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/odk/examples/python/toolpanel/CalcWindowState.xcu b/odk/examples/python/toolpanel/CalcWindowState.xcu new file mode 100644 index 000000000..9abb827d8 --- /dev/null +++ b/odk/examples/python/toolpanel/CalcWindowState.xcu @@ -0,0 +1,29 @@ + + + + + + + + ToolPanel Proof of Concept + + + true + + + + + diff --git a/odk/examples/python/toolpanel/Factory.xcu b/odk/examples/python/toolpanel/Factory.xcu new file mode 100644 index 000000000..bc9b5feef --- /dev/null +++ b/odk/examples/python/toolpanel/Factory.xcu @@ -0,0 +1,34 @@ + + + + + + + + toolpanel + + + myToolPanelPoc + + + + + + org.libreoffice.example.toolpanel.pocFactory + + + + + diff --git a/odk/examples/python/toolpanel/META-INF/manifest.xml b/odk/examples/python/toolpanel/META-INF/manifest.xml new file mode 100644 index 000000000..300501b7f --- /dev/null +++ b/odk/examples/python/toolpanel/META-INF/manifest.xml @@ -0,0 +1,23 @@ + + + + + + + + diff --git a/odk/examples/python/toolpanel/Makefile b/odk/examples/python/toolpanel/Makefile new file mode 100644 index 000000000..a2e77f057 --- /dev/null +++ b/odk/examples/python/toolpanel/Makefile @@ -0,0 +1,29 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# + +PRJ = ../../.. +SETTINGS = $(PRJ)/settings + +include $(SETTINGS)/settings.mk +include $(SETTINGS)/std.mk + +FILES = \ + CalcWindowState.xcu \ + Factory.xcu \ + META-INF/manifest.xml \ + description.xml \ + toolPanelPocBasic/Module1.xba \ + toolPanelPocBasic/dialog.xlb \ + toolPanelPocBasic/script.xlb \ + toolpanel.component \ + toolpanel.py \ + toolpanels/poc.xdl + +$(OUT_BIN)/toolpanel.$(UNOOXT_EXT): $(FILES) + -$(MKDIR) $(subst /,$(PS),$(@D)) + $(SDK_ZIP) $@ $^ diff --git a/odk/examples/python/toolpanel/description.xml b/odk/examples/python/toolpanel/description.xml new file mode 100644 index 000000000..c448e8541 --- /dev/null +++ b/odk/examples/python/toolpanel/description.xml @@ -0,0 +1,13 @@ + + + + + + diff --git a/odk/examples/python/toolpanel/readme b/odk/examples/python/toolpanel/readme new file mode 100644 index 000000000..5dedd9385 --- /dev/null +++ b/odk/examples/python/toolpanel/readme @@ -0,0 +1,13 @@ + +This extension is a Proof of concept on implementing Toolpanel in Python + +- make will create the oxt + - provided sdk environment is set + - alternatively zip the files and name it toolpanel.oxt +- install it +- activate Task Panes in menu (check View > Task Pane menu) +- enjoy! + +The events of the controls (Click me button) in the task panel are handled by basic macro code to illustrate that Toolpanel definition and events codes are independent. One could use any language to react on events + +Then focus only on .py and xml files for the toolpanel activation analysis diff --git a/odk/examples/python/toolpanel/toolPanelPocBasic/Module1.xba b/odk/examples/python/toolpanel/toolPanelPocBasic/Module1.xba new file mode 100644 index 000000000..9d44f7f01 --- /dev/null +++ b/odk/examples/python/toolpanel/toolPanelPocBasic/Module1.xba @@ -0,0 +1,29 @@ + + + +global theDialog + + +Sub dialogOnLoad(event) + + theDialog = event.source + +End Sub + +sub buttonClick(event) + + + theButton = theDialog.getControl("CommandButton1") + theTextField = theDialog.getControl("TextInfo") + + colors = Array(rgb(255,0,0),rgb(0,255,0),rgb(0,0,255)) + rank = getSystemTicks() mod 3 + + theDialog.Model.BackgroundColor = colors(rank) + theTextField.text = cstr(Now) + chr(10)+"Color " + cstr(rank) + " randomly applied" + + theButton.label = "Click Me to change color" + + +end sub + \ No newline at end of file diff --git a/odk/examples/python/toolpanel/toolPanelPocBasic/dialog.xlb b/odk/examples/python/toolpanel/toolPanelPocBasic/dialog.xlb new file mode 100644 index 000000000..a738363ea --- /dev/null +++ b/odk/examples/python/toolpanel/toolPanelPocBasic/dialog.xlb @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/odk/examples/python/toolpanel/toolPanelPocBasic/script.xlb b/odk/examples/python/toolpanel/toolPanelPocBasic/script.xlb new file mode 100644 index 000000000..4d9cc4d51 --- /dev/null +++ b/odk/examples/python/toolpanel/toolPanelPocBasic/script.xlb @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/odk/examples/python/toolpanel/toolpanel.component b/odk/examples/python/toolpanel/toolpanel.component new file mode 100644 index 000000000..d7fde3545 --- /dev/null +++ b/odk/examples/python/toolpanel/toolpanel.component @@ -0,0 +1,16 @@ + + + + + + + + + diff --git a/odk/examples/python/toolpanel/toolpanel.py b/odk/examples/python/toolpanel/toolpanel.py new file mode 100644 index 000000000..8fcfb3f32 --- /dev/null +++ b/odk/examples/python/toolpanel/toolpanel.py @@ -0,0 +1,139 @@ +# +# This file is part of the LibreOffice project. +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. +# +# This file incorporates work covered by the following license notice: +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to you under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of +# the License at http://www.apache.org/licenses/LICENSE-2.0 . +# +# inspired by core/testautomation/extensions/optional/input/extension_sources/TaskPaneComponent +# + +import uno +import unohelper + +from com.sun.star.ui import XUIElementFactory +from com.sun.star.ui import XUIElement +from com.sun.star.ui.UIElementType import TOOLPANEL as unoTOOLPANEL +from com.sun.star.ui import XToolPanel + +implementation_name = "org.libreoffice.example.toolpanel.pocFactory" # as defined in Factory.xcu +implementation_services = ("org.libreoffice.example.toolpanel.pocFactory",) + +xdlPath = "toolpanels/poc.xdl" # the path inside the oxt +extensionID = "org.libreoffice.example.toolpanel" # as defined in description.xml + +######################################################################## +######################################################################## + +class pocToolPanel( unohelper.Base, XToolPanel ): + + def __init__ ( self, xPanelWindow, ctx ): + + self.ctx = ctx + self.PanelWindow = xPanelWindow + self.Window = xPanelWindow + + def createAccessible( self, i_parentAccessible ): + + return self.PanelWindow + +######################################################################## +######################################################################## + +class pyPanel( unohelper.Base, XUIElement ): + + def __init__ ( self, ctx, xFrame, xParentWindow, url ): + + self.ctx = ctx + self.xParentWindow = xParentWindow + self.toolpanel = None + self.m_panelRootWindow = None + + self.Frame = xFrame + self.ResourceURL = url + self.Type = unoTOOLPANEL + + + def getRealInterface( self ): + + if not self.toolpanel: + rootWindow = self.getOrCreatePanelRootWindow() + self.toolpanel = pocToolPanel(rootWindow, self.ctx) + + return self.toolpanel + + def getOrCreatePanelRootWindow( self ): + + pip = self.ctx.getValueByName("/singletons/com.sun.star.deployment.PackageInformationProvider" ) + s = pip.getPackageLocation(extensionID) + dialogUrl = s + "/" + xdlPath + + provider = self.ctx.ServiceManager.createInstanceWithContext("com.sun.star.awt.ContainerWindowProvider",self.ctx) + self.m_panelRootWindow = provider.createContainerWindow(dialogUrl,"",self.xParentWindow, None) + + return self.m_panelRootWindow + + def postDisposing( self ): + + super.postDisposing() + + if self.m_panelRootWindow: + self.m_panelRootWindow.dispose() + self.m_panelRootWindow = None + + self.toolpanel = None + + return + +####################################################################### +####################################################################### + +class pocFactory( unohelper.Base, XUIElementFactory ): + + def __init__ ( self, ctx ): + + self.ctx = ctx + + def createUIElement( self, url, properties ): + + xParentWindow = None + xFrame = None + xUIElement = None + + for arg in properties: + if arg.Name == "Frame": + xFrame = arg.Value + elif arg.Name == "ParentWindow": + xParentWindow = arg.Value + + if xFrame and xParentWindow: + try: + xUIElement = pyPanel(self.ctx, xFrame, xParentWindow, url) + except Exception as e: + print(e) + + return xUIElement + +######################################################################## +######################################################################## + +# pythonloader looks for a static g_ImplementationHelper variable +g_ImplementationHelper = unohelper.ImplementationHelper () + +# add the FormatFactory class to the implementation container, +# which the loader uses to register/instantiate the component. +g_ImplementationHelper.addImplementation (pocFactory, + implementation_name, + implementation_services, + ) + diff --git a/odk/examples/python/toolpanel/toolpanels/poc.xdl b/odk/examples/python/toolpanel/toolpanels/poc.xdl new file mode 100644 index 000000000..2e07cd628 --- /dev/null +++ b/odk/examples/python/toolpanel/toolpanels/poc.xdl @@ -0,0 +1,11 @@ + + + + + + + + + + + -- cgit v1.2.3