### Complete URI Examples (Extension - All Users) Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework Examples of complete URIs for calling scripts from extensions installed for all users. Note the 'share:uno_packages/...' path for location. ```uri vnd.sun.star.script:myLibrary.myModule.myMacro?language=Basic&location=application ``` ```uri vnd.sun.star.script:myLibrary.myMacro.bsh?language=BeanShell&location=share:uno_packages/myExtension.oxt ``` ```uri vnd.sun.star.script:myLibrary.myMethod?language=Java&location=share:uno_packages/myExtension.oxt ``` ```uri vnd.sun.star.script:myLibrary.myMacro.js?language=JavaScript&location=share:uno_packages/myExtension.oxt ``` ```uri vnd.sun.star.script:myExtension.oxt|myScript|myModule.py$myFunction?language=Python&location=share:uno_packages ``` -------------------------------- ### Example StarBasic Macro URL Source: https://wiki.documentfoundation.org/Documentation/DevGuide/OfficeDev/Frame-Controller-Model_Paradigm_in_OpenOffice.org Provides an example of a StarBasic macro URL, demonstrating how to specify the library, module, and method with arguments. ```text macro:///MyLib.MyModule.MyMethod(foo,bar) ``` -------------------------------- ### Install Shared Extension via Command Line Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Extensions Use the unopkg tool with the --shared flag to install an extension for all users in a windowless environment. ```bash [/program] $ unopkg add --shared my_extension.oxt ``` -------------------------------- ### Example Macro URL Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Office_Development A concrete example of a macro URL referencing a specific library, module, and method with arguments. ```text macro:///MyLib.MyModule.MyMethod(foo,bar) ``` -------------------------------- ### Start Office Bean on Windows Source: https://wiki.documentfoundation.org/Documentation/DevGuide/JavaBean_for_Office_Components Use this command to start the Office Bean on Windows, enabling it to accept connections via a named pipe. Ensure the pipe name is correctly formatted. ```bash # WINDOWS soffice.exe -bean -accept=pipe,name=_Office;urp;StarOffice.NamingService ``` -------------------------------- ### Configure and Start Presentation Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Drawing_Documents_and_Presentation_Documents Modify presentation properties such as looping and full-screen mode before starting the presentation. ```java XPresentationSupplier xPresSupplier = UnoRuntime.queryInterface( XPresentationSupplier.class, xComponent); XPresentation xPresentation = xPresSupplier.getPresentation(); XPropertySet xPresPropSet = UnoRuntime.queryInterface( XPropertySet.class, xPresentation); xPresPropSet.setPropertyValue("IsEndless", Boolean.TRUE); xPresPropSet.setPropertyValue("IsFullScreen", Boolean.TRUE); xPresPropSet.setPropertyValue("Pause", Integer.valueOf(0)); xPresentation.start(); ``` -------------------------------- ### Constructing PropertyValue for HyperlinkStart Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Text_Documents An example demonstrating how to construct a PropertyValue sequence to define a hyperlink start token within an index. This is specifically applicable to tables of content. ```java PropertyValue[] indexTokens = new PropertyValue[1]; indexTokens [0] = new PropertyValue(); indexTokens [0].Name = "TokenType"; indexTokens [0].Value = "TokenHyperlinkStart"; ``` -------------------------------- ### Creating a UNO Struct with CoreReflection in C++ Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO This C++ example illustrates the steps required to create a UNO struct using the CoreReflection service. It involves obtaining the service manager, creating the CoreReflection service, getting the IDL class for the struct, and then creating an instance of the struct. ```cpp // create the service manager of LibreOffice IDispatch* pdispFactory= NULL; CLSID clsFactory= {0x82154420,0x0FBF,0x11d4,{0x83, 0x13,0x00,0x50,0x04,0x52,0x6A,0xB4}}; hr= CoCreateInstance( clsFactory, NULL, CLSCTX_ALL, __uuidof(IDispatch), (void**)&pdispFactory); // create the CoreReflection service OLECHAR* funcName= L"createInstance"; DISPID id; pdispFactory->GetIDsOfNames( IID_NULL, &funcName, 1, LOCALE_USER_DEFAULT, &id); VARIANT param1; VariantInit( ¶m1); param1.vt= VT_BSTR; param1.bstrVal= SysAllocString( L"com.sun.star.reflection.CoreReflection"); DISPPARAMS dispparams= { ¶m1, 0, 1, 0}; VARIANT result; VariantInit( &result); hr= pdispFactory->Invoke( id, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispparams, &result, NULL, 0); IDispatch* pdispCoreReflection= result.pdispVal; pdispCoreReflection->AddRef(); VariantClear( &result); // create the struct's idl class object OLECHAR* strforName= L"forName"; hr= pdispCoreReflection->GetIDsOfNames( IID_NULL, &strforName, 1, LOCALE_USER_DEFAULT, &id); VariantClear( ¶m1); param1.vt= VT_BSTR; param1.bstrVal= SysAllocString(L"com.sun.star.beans.PropertyValue"); hr= pdispCoreReflection->Invoke( id, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispparams, &result, NULL, 0); IDispatch* pdispClass= result.pdispVal; pdispClass->AddRef(); VariantClear( &result); // create the struct OLECHAR* strcreateObject= L"createObject"; hr= pdispClass->GetIDsOfNames( IID_NULL,&strcreateObject, 1, LOCALE_USER_DEFAULT, &id) IDispatch* pdispPropertyValue= NULL; VariantClear( ¶m1); param1.vt= VT_DISPATCH | VT_BYREF; param1.ppdispVal= &pdispPropertyValue; hr= pdispClass->Invoke( id, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &dispparams, NULL, NULL, 0); // do something with the struct pdispPropertyValue contained in dispparams // ... pdispPropertyValue->Release(); pdispClass->Release(); pdispCoreReflection->Release(); pdispFactory->Release(); ``` -------------------------------- ### Complete URI Examples (My Macros) Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework Examples of complete URIs for calling scripts stored in 'My Macros'. These URIs specify the script path, language, and location. ```uri vnd.sun.star.script:myLibrary.myModule.myMacro?language=Basic&location=application ``` ```uri vnd.sun.star.script:myLibrary.myMacro.bsh?language=BeanShell&location=user ``` ```uri vnd.sun.star.script:myLibrary.myMethod?language=Java&location=user ``` ```uri vnd.sun.star.script:myLibrary.myMacro.js?language=JavaScript&location=user ``` ```uri vnd.sun.star.script:myModule.py$myFunction?language=Python&location=user ``` -------------------------------- ### Install Extension via Command Line Source: https://wiki.documentfoundation.org/Documentation/DevGuide/LibreOffice_Basic Use the 'unopkg add' command to install a LibreOffice extension package from the command line. Ensure you are in the OfficePath/program directory. ```bash [/program] $ unopkg add my_package.oxt ``` -------------------------------- ### Help Content URL Examples Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Universal_Content_Providers Illustrates various valid URL formats for accessing help content, demonstrating different combinations of parameters and paths. Some parameters are optional but recommended for specific functionalities. ```text _vnd.sun.star.help://?System=WIN &Language=de_ ``` ```text _vnd.sun.star.help://swriter?System=WIN &Language=de&Query=text&HitCount=120&Scope=Heading_ ``` ```text _vnd.sun.star.help://portal/4711?System=UNIX &Language=en_US&HelpPrefix=http%3A%2F%2Fportal%2Fportal_ ``` -------------------------------- ### Specify Extension Target Platforms Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Extensions Examples of the platform tag in description.xml used to control installation compatibility. ```XML ``` ```XML ``` ```XML ``` -------------------------------- ### Define Automation Properties in MIDL Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO Example of defining property get and put operations in MIDL for an Automation object. ```MIDL // MIDL [propget,...] HRESULT Item([in] VARIANT val1, [out, retval] VARIANT* pVal); [propput,...] HRESULT Item([in] VARIANT val1, [in] VARIANT newVal); ``` -------------------------------- ### License Selection Examples Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Extensions A collection of XML configurations demonstrating various locale matching scenarios and fallback behaviors. ```xml ``` ```xml ``` ```xml ``` ```xml ``` -------------------------------- ### Initialize the Universal Content Broker Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Universal_Content_Broker Demonstrates the instantiation of the com.sun.star.ucb.UniversalContentBroker service using the 'Local' and 'Office' configuration keys. ```java import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.uno.Exception; import com.sun.star.uno.XInterface; boolean initUCB() { ///////////////////////////////////////////////////////////////////// // Obtain Process Service Manager. ///////////////////////////////////////////////////////////////////// XMultiServiceFactory xServiceFactory = ... ///////////////////////////////////////////////////////////////////// // Create UCB. This needs to be done only once per process. ///////////////////////////////////////////////////////////////////// XInterface xUCB; try { // Supply configuration to use for this UCB instance... String[] keys = new String[2]; keys[ 0 ] = "Local"; keys[ 1 ] = "Office"; xUCB = xServiceFactory.createInstanceWithArguments( "com.sun.star.ucb.UniversalContentBroker", keys ); } catch (com.sun.star.uno.Exception e) { } if (xUCB == null) return false; return true; } ``` -------------------------------- ### VB: Create a Sequence of Sequences Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO To pass a sequence of sequences to a UNO method expecting `sequence>`, create a Variant array where each element is a Long array. This example demonstrates the setup in Visual Basic. ```vb Dim seq(1) As Variant Dim ar1(3) As Long Dim ar2(4) As Long 'fill ar1, ar2 ... seq(0) = ar1 seq(1) = ar2 objUno.foo seq ``` -------------------------------- ### Sample uno-desc.xml File Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework An example configuration file showing how macro libraries are defined for different scripting languages within an extension. ```xml ``` -------------------------------- ### Creating and Using a UNO Struct with CoreReflection in VBScript Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO This VBScript example shows how to create a UNO struct using the com.sun.star.reflection.CoreReflection service. It involves getting the type description for 'com.sun.star.awt.Size', creating an object, setting its properties, and passing it to a UNO function. ```vbscript 'VBScript in Windows Scripting Host 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") 'get a type description class for Size Set classSize= objCoreReflection.forName("com.sun.star.awt.Size") 'create the actual object Dim aSize classSize.createObject aSize 'use aSize aSize.Width= 100 aSize.Height= 12 'pass the struct into the function objXShape.setSize aSize ``` -------------------------------- ### Markup for Multi-line Code Examples Source: https://wiki.documentfoundation.org/Documentation/DevGuide/IDL_Documentation_Guidelines Use the markup for multiple line code examples. It is often used with specific language tags like @example StarBASIC. ```StarBASIC aCmp = StarDesktop.loadComponentFromURL( ... ) if ( isnull(aCmp) ) .... endif ``` -------------------------------- ### Insert Date Field Example Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Graphical_User_Interfaces Example of how to insert and configure a UnoControlDateField in LibreOffice Basic. ```APIDOC ## POST /api/insertDateField ### Description This endpoint demonstrates the creation and configuration of a `com.sun.star.awt.UnoControlDateField` within a LibreOffice dialog. It sets various properties including dropdown calendar, dimensions, name, and date-related settings like format, minimum, and maximum dates. It also attaches a `SpinListener` to handle changes in the control's value. ### Method POST ### Endpoint /api/insertDateField ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body This endpoint does not directly accept a request body. The function `insertDateField` is a method within a larger context, likely a dialog creation class. ### Request Example ```java private XPropertySet insertDateField(XSpinListener _xSpinListener, int _nPosX, int _nPosY, int _nWidth){ XPropertySet xDFModelPSet = null; try{ String sName = createUniqueName(m_xDlgModelNameContainer, "DateField"); Object oDFModel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlDateFieldModel"); XMultiPropertySet xDFModelMPSet = UnoRuntime.queryInterface(XMultiPropertySet.class, oDFModel); 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)}); m_xDlgModelNameContainer.insertByName(sName, oDFModel); xDFModelPSet = UnoRuntime.queryInterface(XPropertySet.class, oDFModel); 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); XSpinField xSpinField = UnoRuntime.queryInterface(XSpinField.class, oDFControl); xSpinField.addSpinListener(_xSpinListener); } catch (com.sun.star.uno.Exception ex) { ex.printStackTrace(System.err); } return xDFModelPSet; } ``` ### Response #### Success Response (200) - **XPropertySet** (`object`) - A property set for the created date field model. #### Response Example ```json { "message": "DateField created successfully", "propertySet": "[XPropertySet object reference]" } ``` ``` -------------------------------- ### Instantiate UNO Service with Arguments Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO Use createInstanceWithArguments on the service manager to initialize a service with specific arguments. Ensure the service supports com.sun.star.lang.XMultiServiceFactory. ```Basic Dim args(1) args(0) = "Important information" args(1) = "Even more important information" oService = oServiceMgr.createInstanceWithArguments _ ( "com.sun.star.nowhere.ServiceThatNeedsInitialization", args() ) ``` -------------------------------- ### HCP Workplace Printers URL Example Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Universal_Content_Providers Example URL for an HCP link pointing to 'Workplace/Printers'. ```plaintext vnd.sun.star.hier:/Workplace/Printers ``` -------------------------------- ### FirstLoadComponent Java Implementation Source: https://wiki.documentfoundation.org/Documentation/DevGuide/First_Steps Demonstrates bootstrapping the LibreOffice component context, creating a new spreadsheet, and performing basic cell operations. ```java 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); // ********************************************************* ``` -------------------------------- ### XTextRange Start and End Methods Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Text_Documents Methods to retrieve the start and end positions of a text range. ```IDL com::sun::star::text::XTextRange getStart() com::sun::star::text::XTextRange getEnd() ``` -------------------------------- ### Connect to Office via C++ Source: https://wiki.documentfoundation.org/Documentation/DevGuide/First_Steps Uses the C++ UNO bootstrap helper to initialize the component context. ```cpp #include #include #include #include SAL_IMPLEMENT_MAIN() { try { css::uno::Reference xContext( cppu::bootstrap()); std::cout << "Connected to a running office ..." << std::endl; css::uno::Reference xMCF = xContext->getServiceManager(); std::string available = xMCF != nullptr ? "available" : "not available"; std::cout << "remote ServiceManager is " + available << std::endl; } catch (css::uno::Exception &e) { std::cout << e.Message << std::endl; return 1; } return 0; } ``` -------------------------------- ### Create and Configure Custom Shows Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Drawing_Documents_and_Presentation_Documents Demonstrates creating two custom shows ('ShortVersion' and 'LongVersion') with different slide ranges and setting one as the active presentation. ```java XDrawPagesSupplier xDrawPagesSupplier = UnoRuntime.queryInterface( XDrawPagesSupplier.class, xComponent); 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 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++) { XNamed xPageName = UnoRuntime.queryInterface(XNamed.class, xDrawPages.getByIndex(i)); xPageName.setName(aNameArray[i]); } /* 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 = (XCustomPresentationSupplier) UnoRuntime.queryInterface(XCustomPresentationSupplier.class, xComponent); /* 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; /* instanciate an IndexContainer that will take a list of draw pages for the first custom show */ xObj = xFactory.createInstance(); xContainer = (XIndexContainer) UnoRuntime.queryInterface(XIndexContainer.class, xObj); for (i = 5; i < 10; i++) xContainer.insertByIndex(xContainer.getCount(), xDrawPages.getByIndex(i)); xNameContainer.insertByName("ShortVersion", xContainer); /* instanciate an IndexContainer that will take a list of draw page for a 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, xComponent); XPresentation xPresentation = xPresSupplier.getPresentation(); XPropertySet xPresPropSet = UnoRuntime.queryInterface( XPropertySet.class, xPresentation); xPresPropSet.setPropertyValue("CustomShow", "ShortVersion"); ``` -------------------------------- ### Calculate negative value example Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO Specific calculation example for passing 32768 to a two-byte unsigned integer. ```text -32768 = 32768 - (65535 + 1) ``` -------------------------------- ### Create and Register a New DataSource Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Database_Access Demonstrates creating a new generic data source, registering it with the database context, and configuring properties like URL and password requirements. ```Java // creates a new DataSource public static void createNewDataSource(XMultiServiceFactory _rMSF) throws com.sun.star.uno.Exception { // the XSingleServiceFactory of the database context creates new generic // com.sun.star.sdb.DataSources (!) // retrieve the database context at the global service manager and get its // XSingleServiceFactory interface XSingleServiceFactory xFac = UnoRuntime.queryInterface( XSingleServiceFactory.class, _rMSF.createInstance("com.sun.star.sdb.DatabaseContext")); // instantiate an empty data source at the XSingleServiceFactory // interface of the DatabaseContext Object xDs = xFac.createInstance(); // register it with the database context XNamingService xServ = UnoRuntime.queryInterface(XNamingService.class, xFac); XStorable store = UnoRuntime.queryInterface(XStorable.class, xDs); XModel model = UnoRuntime.queryInterface(XModel.class, xDs); store.storeAsURL("file:///c:/test.odb",model.getArgs()); xServ.registerObject("NewDataSourceName", xDs); // setting the necessary data source properties XPropertySet xDsProps = UnoRuntime.queryInterface(XPropertySet.class, xDs); // Adabas D URL xDsProps.setPropertyValue("URL", "sdbc:adabas::MYDB1"); // force password dialog xDsProps.setPropertyValue("IsPasswordRequired", Boolean.TRUE); // suggest dsadmin as user name xDsProps.setPropertyValue("User", "dsadmin"); store.store(); } ``` -------------------------------- ### Insert Time Field Example Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Graphical_User_Interfaces Java code example demonstrating how to insert a UnoControlTimeField into a dialog model. ```APIDOC ## POST /api/dialogs/timefield ### Description Inserts a UnoControlTimeField into a dialog model with specified properties. ### Method POST ### Endpoint /api/dialogs/timefield ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (parameters are passed as method arguments in the example) ### Request Example ```java 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; } ``` ### Response #### Success Response (200) - **XPropertySet** (object) - The property set of the created time field model. ``` -------------------------------- ### Disposing Handler Example Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO An example of a disposing handler that clears the _officeComponentLoader reference and updates a label when the connection is lost. ```APIDOC ## Disposing Handler Example ### Description This code snippet demonstrates a `disposing` method, likely part of a component's lifecycle management. It's responsible for cleaning up resources when the component is being disposed of, specifically when the connection to the office application is lost (e.g., due to a crash or termination). ### Method ```java 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"); } ``` ### Explanation - When the `disposing` method is called, it signifies that the underlying connection or component is no longer available. - `_officeComponentLoader = null;`: This line nullifies a reference to an office component loader, releasing the associated resources and indicating that the component is no longer managed. - `_txtLabel.setText("disconnected");`: This line updates a user interface element (likely a text label) to inform the user that the connection to the office application has been lost. ``` -------------------------------- ### Create a service instance Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO Initializes a component via the service manager, returning a generic XInterface proxy. ```java XInterface xint= (XInterface) serviceManager.createInstance("com.sun.star.bridge.oleautomation.Factory"); ``` -------------------------------- ### Creating Initial Component Context and Service Manager Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO Demonstrates how to obtain the initial component context and service manager in Java. This is a prerequisite for creating UNO objects. ```java XComponentContext xLocalContext = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null); // initial serviceManager XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager(); ``` -------------------------------- ### Configure LibreOffice Listening Mode via Setup.xcu Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO Modify the Setup.xcu file to enable listening mode. This change affects the entire installation. If the tag is not present, add it within the \"Office\" node. ```xml ``` ```xml socket,host=localhost,port=2002;urp;StarOffice.ServiceManager ``` ```xml ``` -------------------------------- ### DCP and HTTP URL Examples Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Universal_Content_Providers Examples of valid identifiers for DCP resources using both custom and standard protocols. ```text vnd.sun.star.webdav://localhost/davhome/ ``` ```text vnd.sun.star.webdav://davserver.com/Documents/report.sdw ``` ```text http://davserver.com/Documents/report.sdw ``` -------------------------------- ### HCP Bookmarks URL Example Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Universal_Content_Providers Example URL for an HCP link pointing to 'Bookmarks/Sun Microssystems Home Page'. ```plaintext vnd.sun.star.hier:/Bookmarks/Sun%20Microssystems%20Home%20Page ``` -------------------------------- ### Connect to Office via Python Source: https://wiki.documentfoundation.org/Documentation/DevGuide/First_Steps Uses the officehelper module to bootstrap the connection. ```python import officehelper try: xContext = officehelper.bootstrap() print("Connected to a running office ...") xMCF = xContext.getServiceManager() available = "not available" if xMCF is None else "available" print("remote ServiceManager is " + available) except Exception as e: print(e) ``` -------------------------------- ### Basic Connection Establishment Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Database_Access A simple example of creating a database connection using a URL. ```Java Connection xConnection = DriverManager.getConnection(url); ``` -------------------------------- ### Example Dialog URL (Document) Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework An example URL for loading a dialog named 'MyDocumentDialog' from a library named 'MyDocumentLibrary' stored within a document. ```text vnd.sun.star.script:MyDocumentLibrary.MyDocumentDialog?location=document ``` -------------------------------- ### Implement ScriptProviderForYourLanguage Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework A complete implementation example of a ScriptProvider, including service registration methods for LibreOffice. ```java import com.sun.star.uno.XComponentContext; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.lang.XSingleServiceFactory; import com.sun.star.registry.XRegistryKey; import com.sun.star.comp.loader.FactoryHelper; import com.sun.star.lang.XServiceInfo; import com.sun.star.lang.XInitialization; import com.sun.star.script.provider.XScriptContext; import com.sun.star.script.provider.XScript; import com.sun.star.script.framework.provider.ScriptProvider; import com.sun.star.script.framework.provider.ScriptEditor; import com.sun.star.script.framework.container.ScriptMetaData; public class ScriptProviderForYourLanguage { public static class _ScriptProviderForYourLanguage extends ScriptProvider { public _ScriptProviderForYourLanguage(XComponentContext ctx) { super (ctx, "YourLanguage"); } public XScript getScript(String scriptURI) throws com.sun.star.uno.RuntimeException, com.sun.star.script.provider.ScriptFrameworkErrorException { YourLanguageScript script = null; try { ScriptMetaData scriptMetaData = getScriptData(scriptURI); XScriptContext xScriptContext = getScriptingContext(); script = new YourLanguageScript(xScriptContext, scriptMetaData); } catch (com.sun.star.uno.Exception e) { System.err.println("Failed to get script: " + scriptURI); } return script; } public boolean hasScriptEditor() { return true; } public ScriptEditor getScriptEditor() { return new ScriptEditorForYourLanguage(); } } // code to register and create a service factory for ScriptProviderForYourLanguage // this code is the standard code for registering classes which implement UNO services public static XSingleServiceFactory __getServiceFactory( String implName, XMultiServiceFactory multiFactory, XRegistryKey regKey ) { XSingleServiceFactory xSingleServiceFactory = null; if ( implName.equals( ScriptProviderForYourLanguage._ScriptProviderForYourLanguage.class.getName() ) ) { xSingleServiceFactory = FactoryHelper.getServiceFactory( ScriptProviderForYourLanguage._ScriptProviderForYourLanguage.class, "com.sun.star.script.provider.ScriptProviderForYourLanguage", multiFactory, regKey ); } return xSingleServiceFactory; } public static boolean __writeRegistryServiceInfo( XRegistryKey regKey ) { String impl = "ScriptProviderForYourLanguage$_ScriptProviderForYourLanguage"; String service1 = "com.sun.star.script.provider.ScriptProvider"; String service2 = "com.sun.star.script.provider.LanguageScriptProvider"; String service3 = "com.sun.star.script.provider.ScriptProviderForYourLanguage"; FactoryHelper.writeRegistryServiceInfo(impl, service1, regKey); FactoryHelper.writeRegistryServiceInfo(impl, service2, regKey); FactoryHelper.writeRegistryServiceInfo(impl, service3, regKey); return true; } } ``` -------------------------------- ### Example UNO Interface Definition Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Professional_UNO This section provides an example of UNO IDL definitions for a struct and an interface, illustrating how different data types and parameters are declared. ```uno struct FooStruct { long nval; string strval; }; interface XFoo { string funcOne([in] string value); FooStruct funcTwo([inout] FooStruct value); sequence funcThree([out] sequence value); }; ``` -------------------------------- ### Execute Component via Basic Macro Source: https://wiki.documentfoundation.org/Documentation/DevGuide/LibreOffice_Basic Instantiates the sample component service and triggers the execution method. ```LibreOffice Basic Sub Main Dim oJobExecutor oJobExecutor = CreateUnoService("com.sun.star.examples.SampleDialog") oJobExecutor.trigger("execute") End Sub ``` -------------------------------- ### Create and Insert Text Table Example Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Text_Documents Demonstrates the creation of a text table, its initialization with specified dimensions, insertion into the document, and basic formatting of rows and cells. Includes setting background colors and inserting text and values. ```java /** 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 BackTransparant 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() ); ``` -------------------------------- ### Example Dialog URL (Application) Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework An example URL for loading a dialog named 'MyDialog' from a library named 'MyDialogLibrary' stored in the application's dialog area. ```text vnd.sun.star.script:MyDialogLibrary.MyDialog?location=application ``` -------------------------------- ### Example ScriptEditorForYourLanguage Implementation Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Scripting_Framework An example implementation of the ScriptEditor interface for a custom language. This class demonstrates how to handle script editing, template retrieval, and file extension definition. ```java import com.sun.star.script.framework.provider.ScriptEditor; import com.sun.star.script.provider.XScriptContext; import com.sun.star.script.framework.container.ScriptMetaData; import javax.swing.*; public class ScriptEditorForYourLanguage implements ScriptEditor { public Object execute() { return null; } public void indicateErrorLine( int lineNum ) { return; } public void edit(XScriptContext context, ScriptMetaData entry) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JTextArea ta = new JTextArea(); entry.loadSource(); ta.setText(entry.getSource()); frame.getContentPane().add(ta); frame.setSize(400, 400); frame.show(); } public String getTemplate() { return "the code for a YourLanguage script"; } public String getExtension() { return "yl"; } } ``` -------------------------------- ### Configure Line Properties in Java Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Drawing_Documents_and_Presentation_Documents Demonstrates setting line style, dash pattern, color, and width for an existing shape using XPropertySet. ```Java /* create a blue line with dashes and dots */ XPropertySet xPropSet = UnoRuntime.queryInterface( XPropertySet.class, xShape ); xPropSet.setPropertyValue( "LineStyle", 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 ) ); ``` -------------------------------- ### Create LibreOffice Window using XWindowPeer (Hack) Source: https://wiki.documentfoundation.org/Documentation/DevGuide/Office_Development This method is a workaround for situations where direct integration is difficult. It involves adding the com.sun.star.awt.XWindowPeer interface and then querying for com.sun.star.awt.XSystemDependentWindowPeer to get the HWND. Use this when the legal method is not feasible. ```java com.sun.star.awt.XToolkit xToolkit = UnoRuntime.queryInterface(com.sun.star.awt.XToolkit.class, xSMGR.createInstance("com.sun.star.awt.Toolkit")); // this is the canvas object with the JNI methods aParentView = ... // some JNI methods cannot work before this aParentView.setVisible(true); // now wrap the canvas (JavaWindowPeerFake) and add the necessary interfaces com.sun.star.awt.XWindowPeer xParentPeer = UnoRuntime.queryInterface(com.sun.star.awt.XWindowPeer.class, new JavaWindowPeerFake(aParentView)); 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 (aParentView.getNativeWindowSystemType()== com.sun.star.lang.SystemDependent.SYSTEM_WIN32) aDescriptor.WindowAttributes = com.sun.star.awt.WindowAttribute.SHOW; else aDescriptor.WindowAttributes = com.sun.star.awt.WindowAttribute.SYSTEMDEPENDENT; // now the toolkit can create an com.sun.star.awt.XWindow com.sun.star.awt.XWindowPeer xPeer = xToolkit.createWindow( aDescriptor ); com.sun.star.awt.XWindow xWindow = (com.sun.star.awt.XWindow)UnoRuntime.queryInterface(com.sun.star.awt.XWindow.class, xPeer); ``` -------------------------------- ### Start Office Bean on Unix Source: https://wiki.documentfoundation.org/Documentation/DevGuide/JavaBean_for_Office_Components This command starts the Office Bean on Unix-like systems, configuring it to listen for connections through a named pipe. The pipe name should follow the specified format. ```bash # UNIX soffice -bean "-accept=pipe,name=_Office;urp;StarOffice.NamingService" ```