Difference between revisions of "Documentation/DevGuide/Scripting/Writing Macros"

From Apache OpenOffice Wiki
Jump to: navigation, search
m
(7 intermediate revisions by 3 users not shown)
Line 8: Line 8:
 
__NOTOC__
 
__NOTOC__
 
=== The HelloWorld macro ===
 
=== The HelloWorld macro ===
 +
Here is a comparison of HelloWorld macros in the different script languages available in {{PRODUCTNAME}}.
  
When the user creates a new macro in BeanShell or JavaScript, the default content of the macro is the HelloWorld. Here is what the code looks like for BeanShell:
+
==== Basic ====
 +
<source lang="oobas">
 +
Sub writeHelloWorld()
 +
Dim oDoc As Object, xText As Object, xTextRange As Object
  
 +
oDoc = ThisComponent
 +
xText = oDoc.getText()
 +
xTextRange = xText.getEnd()
 +
xTextRange.CharBackColor = 1234567
 +
xTextRange.CharHeight = 16.0
 +
' CharUnderline receives a group constant
 +
xTextRange.CharUnderline = com.sun.star.awt.FontUnderline.WAVE
 +
' CharPosture receives an enum
 +
xTextRange.CharPosture = com.sun.star.awt.FontSlant.ITALIC
 +
xTextRange.setString( "Hello World (in Basic)" )
 +
End Sub
 +
</source>
 +
Basic interprets pairs of get and set methods at UNO objects as object properties if they follow this pattern:
 +
 +
  SomeType getSomeProperty()
 +
  void setSomeProperty(SomeType aValue)
 +
 +
Using these facilities some lines can be simplified:
 +
<source lang="oobas">
 +
xText = oDoc.Text
 +
xTextRange = xText.End
 +
xTextRange.String = "Hello World (in Basic)"
 +
</source>
 +
 +
Service properties can be directly accessed in Basic, it is not necessary to use <code>getPropertyValue</code> or <code>setPropertyValue</code> methods.
 +
 +
==== BeanShell ====
 +
As BeanShell accepts typeless variables, the code is simplified compared to Java.
 
  <source lang="java">
 
  <source lang="java">
  import com.sun.star.uno.UnoRuntime;
+
import com.sun.star.uno.UnoRuntime;
 
+
import com.sun.star.text.XTextDocument;
  import com.sun.star.text.XTextDocument;
+
import com.sun.star.text.XText;
  import com.sun.star.text.XText;
+
import com.sun.star.text.XTextRange;
  import com.sun.star.text.XTextRange;
+
import com.sun.star.beans.XPropertySet;
 
+
import com.sun.star.awt.FontSlant;
  oDoc = XSCRIPTCONTEXT.getDocument();
+
import com.sun.star.awt.FontUnderline;
  xTextDoc = (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class,oDoc);
+
 
  xText = xTextDoc.getText();
+
oDoc = XSCRIPTCONTEXT.getDocument();
  xTextRange = xText.getEnd();
+
 
  xTextRange.setString( "Hello World (in BeanShell)" );
+
xTextDoc = UnoRuntime.queryInterface(XTextDocument.class,oDoc);
 
+
xText = xTextDoc.getText();
  // BeanShell OpenOffice.org scripts should always return 0
+
xTextRange = xText.getEnd();
  return 0;
+
pv = UnoRuntime.queryInterface(XPropertySet.class, xTextRange);
 +
 
 +
pv.setPropertyValue("CharBackColor", 1234567);
 +
pv.setPropertyValue("CharHeight", 16.0);
 +
// CharUnderline receives a group constant
 +
pv.setPropertyValue("CharUnderline", com.sun.star.awt.FontUnderline.WAVE);
 +
// CharPosture receives an enum
 +
pv.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC) ;
 +
 
 +
xTextRange.setString( "Hello World (in BeanShell)" );
 +
return 0;
 
  </source>
 
  </source>
  
As BeanShell accepts typeless variables, the queryInterface instructions can be simplified.
+
BeanShell interprets pairs of get and set methods at UNO objects as object properties if they follow this pattern:
 
+
Like OpenOffice.org Basic, BeanShell interprets pairs of get and set methods at UNO objects as object properties if they follow this pattern:
+
  
 
   SomeType getSomeProperty()
 
   SomeType getSomeProperty()
 
   void setSomeProperty(SomeType aValue)
 
   void setSomeProperty(SomeType aValue)
  
Using these facilities the above example can be simplified:
+
Using these facilities some lines can be simplified:
  
 
  <source lang="java">
 
  <source lang="java">
  import com.sun.star.uno.UnoRuntime;
 
 
 
  import com.sun.star.text.XTextDocument;
 
  import com.sun.star.text.XText;
 
  import com.sun.star.text.XTextRange;
 
 
 
  oDoc = XSCRIPTCONTEXT.Document;
 
  xTextDoc = UnoRuntime.queryInterface(XTextDocument.class,oDoc);
 
 
   xText = xTextDoc.Text;
 
   xText = xTextDoc.Text;
 
   xTextRange = xText.End;
 
   xTextRange = xText.End;
 
   xTextRange.String = "Hello World (in BeanShell)";
 
   xTextRange.String = "Hello World (in BeanShell)";
 
 
  // BeanShell OpenOffice.org scripts should always return 0
 
  return 0;
 
 
  </source>
 
  </source>
  
Here is the same code in JavaScript:
+
Service properties are only accessed with <code>getPropertyValue</code> or <code>setPropertyValue</code>.
 +
 
 +
==== JavaScript ====
 +
As JavaScript accepts typeless variables, the code is simplified compared to Java.
 
  <source lang="javascript">
 
  <source lang="javascript">
  importClass(Packages.com.sun.star.uno.UnoRuntime);
+
importClass(Packages.com.sun.star.uno.UnoRuntime)
  importClass(Packages.com.sun.star.text.XTextDocument);
+
importClass(Packages.com.sun.star.text.XTextDocument)
  importClass(Packages.com.sun.star.text.XText);
+
importClass(Packages.com.sun.star.text.XText)
  importClass(Packages.com.sun.star.text.XTextRange);
+
importClass(Packages.com.sun.star.text.XTextRange)
 
+
importClass(Packages.com.sun.star.beans.XPropertySet)
  oDoc = XSCRIPTCONTEXT.getDocument();
+
importClass(Packages.com.sun.star.awt.FontSlant)
  xTextDoc = UnoRuntime.queryInterface(XTextDocument,oDoc);
+
importClass(Packages.com.sun.star.awt.FontUnderline)
  xText = xTextDoc.getText();
+
 
  xTextRange = xText.getEnd();
+
oDoc = XSCRIPTCONTEXT.getDocument()
  xTextRange.setString( "Hello World (in JavaScript)" );
+
xTextDoc = UnoRuntime.queryInterface(XTextDocument,oDoc)
 +
xText = xTextDoc.getText()
 +
xTextRange = xText.getEnd()
 +
pv = UnoRuntime.queryInterface(XPropertySet, xTextRange)
 +
 
 +
pv.setPropertyValue("CharHeight", 16.0) // Double
 +
// CharBackColor receives an Integer
 +
pv.setPropertyValue("CharBackColor", new java.lang.Integer(1234567))
 +
// CharUnderline receives a group constant
 +
pv.setPropertyValue("CharUnderline",
 +
  new java.lang.Short(Packages.com.sun.star.awt.FontUnderline.WAVE))
 +
// CharPosture receives an enum
 +
pv.setPropertyValue("CharPosture", Packages.com.sun.star.awt.FontSlant.ITALIC)
 +
xTextRange.setString( "Hello World (in JavaScript)" )
 
  </source>
 
  </source>
Here is the code for HelloWorld in Java:
+
 
 +
JavaScript does not accept the simplifications seen in Basic and BeanShell.
 +
 
 +
Setting an integer value to a property requires to use a java class.
 +
 
 +
==== Java ====
 +
Other sections of this document provide numerous Java examples. Here is the HelloWorld provided in {{PRODUCTNAME}}
 
  <source lang="java">
 
  <source lang="java">
 
   import com.sun.star.uno.UnoRuntime;
 
   import com.sun.star.uno.UnoRuntime;
Line 91: Line 142:
 
   }
 
   }
 
  </source>
 
  </source>
The table below outlines some of the features of macro development in the different languages:
+
 
 +
===== Compiling and Deploying Java macros =====
 +
 
 +
Because Java is a compiled language it is not possible to execute Java source code as a macro directly from within {{PRODUCTNAME}}. The code must first be compiled and then deployed within a {{PRODUCTNAME}} installation or document. The following steps show how to create a Java macro using the HelloWorld example code:
 +
 
 +
* Create a ''HelloWorld'' directory for your macro
 +
* Create a ''HelloWorld.java'' file using the HelloWorld source code
 +
* Compile the ''HelloWorld.java'' file. The following jar files from the ''program/classes'' directory of a {{PRODUCTNAME}} installation must be in the classpath: ''ridl.jar'', ''unoil.jar'', ''jurt.jar''
 +
* Create a ''HelloWorld.jar'' file containing the ''HelloWorld.class'' file
 +
* Create a ''parcel-descriptor.xml'' file for your macro
 +
<source lang="xml">
 +
  <?xml version="1.0" encoding="UTF-8"?>
 +
 
 +
  <parcel language="Java" xmlns:parcel="scripting.dtd">
 +
    <script language="Java">
 +
      <locale lang="en">
 +
        <displayname value="HelloWorld"/>
 +
        <description>
 +
          Prints "Hello World".
 +
        </description>
 +
      </locale>
 +
      <functionname value="HelloWorld.printHW"/>
 +
      <logicalname value="HelloWorld.printHW"/>
 +
      <languagedepprops>
 +
          <prop name="classpath" value="HelloWorld.jar"/>
 +
      </languagedepprops>
 +
    </script>
 +
  </parcel>
 +
</source>
 +
The ''parcel-descriptor.xml'' file is used by the Scripting Framework to find macros. The functionname element indicates the name of the Java method which should be executed as a macro. The classpath element can be used to indicate any jar or class files which are used by the macro. If the classpath element is not included, then the directory in which the ''parcel-desciptor.xml'' file is found and any jar files in that directory will be used as the classpath. The necessary Java UNO classes are available automatically.
 +
 
 +
* Copy the HelloWorld directory into the ''share/Scripts/java'' (or ''basis/share/Scripts/java'') directory of a {{PRODUCTNAME}} installation or into the ''user/Scripts/java'' directory of a user installation. If you want to deploy the macro to a document you need to place it in a ''Scripts/java'' directory within the document zip file.
 +
* If {{PRODUCTNAME}} is running, you will need to restart it in order for the macro to appear in the Macro Selector dialog.
 +
 
 +
{{Note|The ''parcel-descriptor.xml'' file is also used to detect BeanShell and JavaScript macros. It is created automatically when creating macros using the Organizer dialogs for BeanShell and JavaScript.}}
 +
 
 +
If these files are embedded in document file, they have to be registered in META-INF/manifest.xml:  
 +
<source lang="xml">
 +
<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="Scripts/java/Test/parcel-descriptor.xml"/>
 +
<manifest:file-entry manifest:media-type="application/binary" manifest:full-path="Scripts/java/Test/test.jar"/>
 +
<manifest:file-entry manifest:media-type="" manifest:full-path="Scripts/java/Test/"/>
 +
<manifest:file-entry manifest:media-type="" manifest:full-path="Scripts/java/"/>
 +
<manifest:file-entry manifest:media-type="" manifest:full-path="Scripts/"/>
 +
</source>
 +
 
 +
==== Python ====
 +
 
 +
A Python module may contain several scripts.
 +
<source lang="python">
 +
def HelloPython( ):
 +
import uno
 +
 
 +
def HelloPython( ):
 +
    oDoc = XSCRIPTCONTEXT.getDocument()
 +
    xText = oDoc.getText()
 +
    xTextRange = xText.getEnd()
 +
   
 +
    xTextRange.CharHeight = 16.0
 +
    xTextRange.CharBackColor = 1234567
 +
    # CharUnderline receives a group constant
 +
    xTextRange.CharUnderline = uno.getConstantByName("com.sun.star.awt.FontUnderline.WAVE")
 +
    # CharPosture receives an enum
 +
    xTextRange.CharPosture = uno.getConstantByName("com.sun.star.awt.FontSlant.ITALIC")
 +
   
 +
    xTextRange.setString( "Hello World (in Python)" )
 +
    return None
 +
</source>
 +
Python interprets pairs of get and set methods at UNO objects as object properties if they follow this pattern:
 +
 
 +
  SomeType getSomeProperty()
 +
  void setSomeProperty(SomeType aValue)
 +
 
 +
Using these facilities some lines can be simplified:
 +
<source lang="python">
 +
    xText = oDoc.Text
 +
    xTextRange = xText.End
 +
    xTextRange.String = "Hello World (in Python)"
 +
</source>
 +
Service properties can be directly accessed in Python, no need to use <code>getPropertyValue</code> or <code>setPropertyValue</code>.
 +
 
 +
=== Features of script languages supported by {{PRODUCTNAME}} ===
  
 
{|border="1" cellpadding=4 style="border-collapse:collapse;"
 
{|border="1" cellpadding=4 style="border-collapse:collapse;"
 
|-bgcolor=#EDEDED
 
|-bgcolor=#EDEDED
!Language  
+
!Language feature
!Interpreted
+
!Basic
!Typeless
+
!BeanShell
!Editor
+
!JavaScript
!Debugger
+
!Java macro
 +
!Python
 
|-
 
|-
|BeanShell
+
|Interpreted
 
|Yes  
 
|Yes  
 
|Yes  
 
|Yes  
 +
|Yes
 +
|No
 
|Yes  
 
|Yes  
 +
|-
 +
|Integrated editor
 +
|Yes, colored
 +
|Yes
 +
|Yes
 +
|No
 
|No  
 
|No  
 
|-
 
|-
|JavaScript
+
|Integrated debugger
 
|Yes  
 
|Yes  
 +
|No
 
|Yes  
 
|Yes  
 +
|No
 +
|No
 +
|-
 +
|Script organizer
 
|Yes  
 
|Yes  
 +
|Yes
 
|Yes  
 
|Yes  
 +
|No
 +
|No
 
|-
 
|-
|Java
+
|Script encryption
 +
|Possible
 
|No  
 
|No  
 
|No  
 
|No  
 
|No  
 
|No  
 
|No  
 
|No  
 +
|-
 +
|Typeless variables
 +
|Yes: Variant
 +
|Yes
 +
|Yes
 +
|No
 +
|Yes
 +
|-
 +
|Getter/Setter
 +
|Yes
 +
|Yes
 +
|No
 +
|No
 +
|Yes
 +
|-
 +
|Direct property access
 +
|Yes
 +
|No
 +
|No
 +
|No
 +
|Yes
 +
|-
 +
|Function for Calc formula
 +
|Yes
 +
|No
 +
|No
 +
|No
 +
|No
 +
|-
 +
|UNO component creation
 +
|No
 +
|No
 +
|No
 +
|Yes
 +
|Yes
 
|}
 
|}
  
 
{{Documentation/Note|Instructions on compiling and deploying Java macros can be found later in this chapter.}}
 
  
 
=== Using the {{PRODUCTNAME}} API from macros ===
 
=== Using the {{PRODUCTNAME}} API from macros ===
  
All BeanShell, JavaScript and Java macros are supplied with a variable of type <idl>com.sun.star.script.provider.XScriptContext</idl> which can be used to access the {{PRODUCTNAME}} API. This type has three methods:
+
BeanShell, JavaScript, Java, Python macros are supplied with a variable of type <idl>com.sun.star.script.provider.XScriptContext</idl> which can be used to access the {{PRODUCTNAME}} API. This interface has three methods:
  
 
* <idl>com.sun.star.frame.XModel</idl> <code>getDocument( )</code>
 
* <idl>com.sun.star.frame.XModel</idl> <code>getDocument( )</code>
Line 134: Line 316:
 
:Returns the <code>XComponentContext</code> interface which is used to create instances of services (see [[Documentation/DevGuide/ProUNO/Service Manager and Component Context|Service Manager and Component Context]])
 
:Returns the <code>XComponentContext</code> interface which is used to create instances of services (see [[Documentation/DevGuide/ProUNO/Service Manager and Component Context|Service Manager and Component Context]])
  
Depending on the language the macro accesses the <code>XScriptContext</code> type in different ways:
+
Depending on the language the macro accesses <code>XScriptContext</code> in different ways:
  
 
* '''BeanShell''': Using the global variable <code>XSCRIPTCONTEXT</code>
 
* '''BeanShell''': Using the global variable <code>XSCRIPTCONTEXT</code>
Line 144: Line 326:
 
* '''Java''': The first parameter passed to the macro method is always of type <code>XScriptContext</code>
 
* '''Java''': The first parameter passed to the macro method is always of type <code>XScriptContext</code>
 
   Xmodel xDocModel = xScriptContext.getDocument();
 
   Xmodel xDocModel = xScriptContext.getDocument();
 +
 +
* '''Python''': Using the global variable <code>XSCRIPTCONTEXT</code>
 +
  oDoc = XSCRIPTCONTEXT.getDocument()
  
 
=== Handling arguments passed to macros ===
 
=== Handling arguments passed to macros ===
Line 162: Line 347:
  
 
The ButtonPressHandler macros in the Highlight library of a {{PRODUCTNAME}} installation show how a macro can handle arguments.
 
The ButtonPressHandler macros in the Highlight library of a {{PRODUCTNAME}} installation show how a macro can handle arguments.
 +
 +
* '''Python''': The arguments are passed as parameters of the called function.
 +
  
 
=== Creating dialogs from macros ===
 
=== Creating dialogs from macros ===
  
Dialogs which have been built in the Dialog Editor can be loaded by macros using the <idl>com.sun.star.awt.XDialogProvider</idl> API. The <code>XDialogProvider</code> interface has one method <code>createDialog()</code> which takes a string as a parameter. This string is the URL to the dialog. The URL is formed as follows:
+
Dialogs which have been built in the Dialog Editor can be loaded by macros using the <idl>com.sun.star.awt.XDialogProvider</idl> API. The method <code>createDialog()</code> from interface <code>XDialogProvider</code> uses a string as a parameter. This string is the URL to the dialog. It is formed as follows:
  
 
   vnd.sun.star.script:DIALOGREF?location=[application|document]
 
   vnd.sun.star.script:DIALOGREF?location=[application|document]
Line 212: Line 400:
 
   }
 
   }
 
  </source>
 
  </source>
=== Compiling and Deploying Java macros ===
 
  
Because Java is a compiled language it is not possible to execute Java source code as a macro directly from within {{PRODUCTNAME}}. The code must first be compiled and then deployed within a {{PRODUCTNAME}} installation or document. The following steps show how to create a Java macro using the HelloWorld example code:
+
=== Calling a macro with the Scripting Framework ===
  
* Create a ''HelloWorld'' directory for your macro
+
The service <idl>com.sun.star.script.provider.ScriptProvider</idl> exports interface <idls>com.sun.star.script.provider.XScriptProvider</idls> which offers method <code>getScript( )</code>. This method returns an interface <idls>com.sun.star.script.provider.XScript</idls> which offers the method <code>invoke( )</code> which will call the script with parameters if necessary.
* Create a ''HelloWorld.java'' file using the HelloWorld source code
+
 
* Compile the ''HelloWorld.java'' file. The following jar files from the ''program/classes'' directory of a {{PRODUCTNAME}} installation must be in the classpath: ''ridl.jar'', ''unoil.jar'', ''jurt.jar''
+
The identity and location of the called script is contained in an URI, which follows a [[Documentation/DevGuide/Scripting/Scripting_Framework_URI_Specification|particular syntax]].
* Create a ''HelloWorld.jar'' file containing the ''HelloWorld.class'' file
+
 
* Create a ''parcel-descriptor.xml'' file for your macro
+
 
<source lang="xml">
+
Here are links to some code examples written by the community:
  <?xml version="1.0" encoding="UTF-8"?>
+
* [http://codesnippets.services.openoffice.org/Office/Office.HowToCallJavaProgramUsingScriptingFramework.snip Java calling a Java script]
 
+
* [http://www.oooforum.org/forum/viewtopic.phtml?t=69328 Java calling a Basic macro]
  <parcel language="Java" xmlns:parcel="scripting.dtd">
+
* [http://www.oooforum.org/forum/viewtopic.phtml?t=59534 Basic macro calling a Python script]
    <script language="Java">
+
* [http://www.oooforum.org/forum/viewtopic.phtml?t=69350 Python script calling a Basic macro]
      <locale lang="en">
+
        <displayname value="HelloWorld"/>
+
        <description>
+
          Prints "Hello World".
+
        </description>
+
      </locale>
+
      <functionname value="HelloWorld.printHW"/>
+
      <logicalname value="HelloWorld.printHW"/>
+
      <languagedepprops>
+
          <prop name="classpath" value="HelloWorld.jar"/>
+
      </languagedepprops>
+
    </script>
+
  </parcel>
+
</source>
+
The ''parcel-descriptor.xml'' file is used by the Scripting Framework to find macros. The functionname element indicates the name of the Java method which should be executed as a macro. The classpath element can be used to indicate any jar or class files which are used by the macro. If the classpath element is not included, then the directory in which the ''parcel-desciptor.xml'' file is found and any jar files in that directory will be used as the classpath. The necessary Java UNO classes are available automatically.
+
  
* Copy the HelloWorld directory into the ''share/Scripts/java'' directory of a {{PRODUCTNAME}} installation or into the ''user/Scripts/java'' directory of a user installation. If you want to deploy the macro to a document you need to place it in a ''Scripts/java'' directory within the document zip file.
 
* If {{PRODUCTNAME}} is running, you will need to restart it in order for the macro to appear in the Macro Selector dialog.
 
  
{{Documentation/Note|The ''parcel-descriptor.xml'' file is also used to detect BeanShell and JavaScript macros. It is created automatically when creating macros using the Organizer dialogs for BeanShell and JavaScript.}}
 
  
 
{{PDL1}}
 
{{PDL1}}
  
 
[[Category:Documentation/Developer's Guide/Scripting]]
 
[[Category:Documentation/Developer's Guide/Scripting]]

Revision as of 20:57, 3 July 2018



The HelloWorld macro

Here is a comparison of HelloWorld macros in the different script languages available in OpenOffice.org.

Basic

Sub writeHelloWorld()
Dim oDoc As Object, xText As Object, xTextRange As Object
 
oDoc = ThisComponent
xText = oDoc.getText()
xTextRange = xText.getEnd()
xTextRange.CharBackColor = 1234567
xTextRange.CharHeight = 16.0
' CharUnderline receives a group constant
xTextRange.CharUnderline = com.sun.star.awt.FontUnderline.WAVE
' CharPosture receives an enum
xTextRange.CharPosture = com.sun.star.awt.FontSlant.ITALIC
xTextRange.setString( "Hello World (in Basic)" )
End Sub

Basic interprets pairs of get and set methods at UNO objects as object properties if they follow this pattern:

 SomeType getSomeProperty()
 void setSomeProperty(SomeType aValue)

Using these facilities some lines can be simplified:

xText = oDoc.Text
xTextRange = xText.End
xTextRange.String = "Hello World (in Basic)"

Service properties can be directly accessed in Basic, it is not necessary to use getPropertyValue or setPropertyValue methods.

BeanShell

As BeanShell accepts typeless variables, the code is simplified compared to Java.

import com.sun.star.uno.UnoRuntime;
import com.sun.star.text.XTextDocument;
import com.sun.star.text.XText;
import com.sun.star.text.XTextRange;
import com.sun.star.beans.XPropertySet;
import com.sun.star.awt.FontSlant;
import com.sun.star.awt.FontUnderline;
 
oDoc = XSCRIPTCONTEXT.getDocument();
 
xTextDoc = UnoRuntime.queryInterface(XTextDocument.class,oDoc);
xText = xTextDoc.getText();
xTextRange = xText.getEnd();
pv = UnoRuntime.queryInterface(XPropertySet.class, xTextRange);
 
pv.setPropertyValue("CharBackColor", 1234567);
pv.setPropertyValue("CharHeight", 16.0);
// CharUnderline receives a group constant
pv.setPropertyValue("CharUnderline", com.sun.star.awt.FontUnderline.WAVE);
// CharPosture receives an enum
pv.setPropertyValue("CharPosture", com.sun.star.awt.FontSlant.ITALIC) ;
 
xTextRange.setString( "Hello World (in BeanShell)" );
return 0;

BeanShell interprets pairs of get and set methods at UNO objects as object properties if they follow this pattern:

 SomeType getSomeProperty()
 void setSomeProperty(SomeType aValue)

Using these facilities some lines can be simplified:

  xText = xTextDoc.Text;
  xTextRange = xText.End;
  xTextRange.String = "Hello World (in BeanShell)";

Service properties are only accessed with getPropertyValue or setPropertyValue.

JavaScript

As JavaScript accepts typeless variables, the code is simplified compared to Java.

importClass(Packages.com.sun.star.uno.UnoRuntime)
importClass(Packages.com.sun.star.text.XTextDocument)
importClass(Packages.com.sun.star.text.XText)
importClass(Packages.com.sun.star.text.XTextRange)
importClass(Packages.com.sun.star.beans.XPropertySet)
importClass(Packages.com.sun.star.awt.FontSlant)
importClass(Packages.com.sun.star.awt.FontUnderline)
 
oDoc = XSCRIPTCONTEXT.getDocument()
xTextDoc = UnoRuntime.queryInterface(XTextDocument,oDoc)
xText = xTextDoc.getText()
xTextRange = xText.getEnd()
pv = UnoRuntime.queryInterface(XPropertySet, xTextRange)
 
pv.setPropertyValue("CharHeight", 16.0) // Double
// CharBackColor receives an Integer
pv.setPropertyValue("CharBackColor", new java.lang.Integer(1234567))
// CharUnderline receives a group constant
pv.setPropertyValue("CharUnderline",
   new java.lang.Short(Packages.com.sun.star.awt.FontUnderline.WAVE))
// CharPosture receives an enum
pv.setPropertyValue("CharPosture", Packages.com.sun.star.awt.FontSlant.ITALIC) 
xTextRange.setString( "Hello World (in JavaScript)" )

JavaScript does not accept the simplifications seen in Basic and BeanShell.

Setting an integer value to a property requires to use a java class.

Java

Other sections of this document provide numerous Java examples. Here is the HelloWorld provided in OpenOffice.org

  import com.sun.star.uno.UnoRuntime;
  import com.sun.star.frame.XModel;
  import com.sun.star.text.XTextDocument;
  import com.sun.star.text.XTextRange;
  import com.sun.star.text.XText;
  import com.sun.star.script.provider.XScriptContext;
 
  public class HelloWorld {
      public static void printHW(XScriptContext xScriptContext)
      {
          XModel xDocModel = xScriptContext.getDocument();
 
          // getting the text document object
          XTextDocument xtextdocument = (XTextDocument) UnoRuntime.queryInterface(
              XTextDocument.class, xDocModel);
 
          XText xText = xtextdocument.getText();
          XTextRange xTextRange = xText.getEnd();
          xTextRange.setString( "Hello World (in Java)" );
      }
  }
Compiling and Deploying Java macros

Because Java is a compiled language it is not possible to execute Java source code as a macro directly from within OpenOffice.org. The code must first be compiled and then deployed within a OpenOffice.org installation or document. The following steps show how to create a Java macro using the HelloWorld example code:

  • Create a HelloWorld directory for your macro
  • Create a HelloWorld.java file using the HelloWorld source code
  • Compile the HelloWorld.java file. The following jar files from the program/classes directory of a OpenOffice.org installation must be in the classpath: ridl.jar, unoil.jar, jurt.jar
  • Create a HelloWorld.jar file containing the HelloWorld.class file
  • Create a parcel-descriptor.xml file for your macro
  <?xml version="1.0" encoding="UTF-8"?>
 
  <parcel language="Java" xmlns:parcel="scripting.dtd">
    <script language="Java">
      <locale lang="en">
        <displayname value="HelloWorld"/>
        <description>
          Prints "Hello World".
        </description>
      </locale>
      <functionname value="HelloWorld.printHW"/>
      <logicalname value="HelloWorld.printHW"/>
      <languagedepprops>
          <prop name="classpath" value="HelloWorld.jar"/>
      </languagedepprops>
    </script>
  </parcel>

The parcel-descriptor.xml file is used by the Scripting Framework to find macros. The functionname element indicates the name of the Java method which should be executed as a macro. The classpath element can be used to indicate any jar or class files which are used by the macro. If the classpath element is not included, then the directory in which the parcel-desciptor.xml file is found and any jar files in that directory will be used as the classpath. The necessary Java UNO classes are available automatically.

  • Copy the HelloWorld directory into the share/Scripts/java (or basis/share/Scripts/java) directory of a OpenOffice.org installation or into the user/Scripts/java directory of a user installation. If you want to deploy the macro to a document you need to place it in a Scripts/java directory within the document zip file.
  • If OpenOffice.org is running, you will need to restart it in order for the macro to appear in the Macro Selector dialog.
Documentation note.png The parcel-descriptor.xml file is also used to detect BeanShell and JavaScript macros. It is created automatically when creating macros using the Organizer dialogs for BeanShell and JavaScript.

If these files are embedded in document file, they have to be registered in META-INF/manifest.xml:

<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="Scripts/java/Test/parcel-descriptor.xml"/>
<manifest:file-entry manifest:media-type="application/binary" manifest:full-path="Scripts/java/Test/test.jar"/>
<manifest:file-entry manifest:media-type="" manifest:full-path="Scripts/java/Test/"/>
<manifest:file-entry manifest:media-type="" manifest:full-path="Scripts/java/"/>
<manifest:file-entry manifest:media-type="" manifest:full-path="Scripts/"/>

Python

A Python module may contain several scripts.

def HelloPython( ):
import uno
 
def HelloPython( ):
    oDoc = XSCRIPTCONTEXT.getDocument()
    xText = oDoc.getText()
    xTextRange = xText.getEnd()
 
    xTextRange.CharHeight = 16.0
    xTextRange.CharBackColor = 1234567
    # CharUnderline receives a group constant
    xTextRange.CharUnderline = uno.getConstantByName("com.sun.star.awt.FontUnderline.WAVE")
    # CharPosture receives an enum
    xTextRange.CharPosture = uno.getConstantByName("com.sun.star.awt.FontSlant.ITALIC")
 
    xTextRange.setString( "Hello World (in Python)" )
    return None

Python interprets pairs of get and set methods at UNO objects as object properties if they follow this pattern:

 SomeType getSomeProperty()
 void setSomeProperty(SomeType aValue)

Using these facilities some lines can be simplified:

    xText = oDoc.Text
    xTextRange = xText.End
    xTextRange.String = "Hello World (in Python)"

Service properties can be directly accessed in Python, no need to use getPropertyValue or setPropertyValue.

Features of script languages supported by OpenOffice.org

Language feature Basic BeanShell JavaScript Java macro Python
Interpreted Yes Yes Yes No Yes
Integrated editor Yes, colored Yes Yes No No
Integrated debugger Yes No Yes No No
Script organizer Yes Yes Yes No No
Script encryption Possible No No No No
Typeless variables Yes: Variant Yes Yes No Yes
Getter/Setter Yes Yes No No Yes
Direct property access Yes No No No Yes
Function for Calc formula Yes No No No No
UNO component creation No No No Yes Yes


Using the OpenOffice.org API from macros

BeanShell, JavaScript, Java, Python macros are supplied with a variable of type com.sun.star.script.provider.XScriptContext which can be used to access the OpenOffice.org API. This interface has three methods:

Returns the XModel interface of the document for which the macro was invoked (see Using the Component Framework)
Returns the XDesktop interface for the application which can be used to access open document, and load documents (see Using the Desktop)
Returns the XComponentContext interface which is used to create instances of services (see Service Manager and Component Context)

Depending on the language the macro accesses XScriptContext in different ways:

  • BeanShell: Using the global variable XSCRIPTCONTEXT
 oDoc = XSCRIPTCONTEXT.getDocument();
  • JavaScript: Using the global variable XSCRIPTCONTEXT
 oDoc = XSCRIPTCONTEXT.getDocument();
  • Java: The first parameter passed to the macro method is always of type XScriptContext
 Xmodel xDocModel = xScriptContext.getDocument();
  • Python: Using the global variable XSCRIPTCONTEXT
 oDoc = XSCRIPTCONTEXT.getDocument()

Handling arguments passed to macros

In certain cases arguments may be passed to macros, for example, when a macro is assigned to a button in a document. In this case the arguments are passed to the macro as follows:

  • BeanShell: In the global Object[] variable ARGUMENTS
 event = (ActionEvent) ARGUMENTS[0];
  • JavaScript: In the global Object[] variable ARGUMENTS
 event = ARGUMENTS[0];
  • Java: The arguments are passed as an Object[] in the second parameter to the macro method
 public void handleButtonPress(
     XScriptContext xScriptContext, Object[] args)

Each of the arguments in the Object[] are of the UNO type Any. For more information on how the Any type is used in Java see Type Mappings.

The ButtonPressHandler macros in the Highlight library of a OpenOffice.org installation show how a macro can handle arguments.

  • Python: The arguments are passed as parameters of the called function.


Creating dialogs from macros

Dialogs which have been built in the Dialog Editor can be loaded by macros using the com.sun.star.awt.XDialogProvider API. The method createDialog() from interface XDialogProvider uses a string as a parameter. This string is the URL to the dialog. It is formed as follows:

 vnd.sun.star.script:DIALOGREF?location=[application|document]

where DIALOGREF is the name of the dialog that you want to create, and location is either application or document depending on where the dialog is stored.

For example if you wanted to load dialog called MyDialog, which is in a Dialog Library called MyDialogLibrary in the OpenOffice.org dialogs area of your installation then the URL would be:

 vnd.sun.star.script:MyDialogLibrary.MyDialog?location=application

If you wanted to load a dialog called MyDocumentDialog which in a library called MyDocumentLibrary which is located in a document then the URL would be:

 vnd.sun.star.script:MyDocumentLibrary.MyDocumentDialog?location=document

The following code shows how to create a dialog from a Java macro:

  public XDialog getDialog(XScriptContext context)
  {
      XDialog theDialog;
 
      // We must pass the XModel of the current document when creating a DialogProvider object
      Object[] args = { context.getDocument() };
 
      Object obj;
      try {
          obj = xmcf.createInstanceWithArgumentsAndContext(
              "com.sun.star.awt.DialogProvider", args, context.getComponentContext());
      }
      catch (com.sun.star.uno.Exception e) {
          System.err.println("Error getting DialogProvider object");
          return null;
      }
 
      XDialogProvider xDialogProvider = (XDialogProvider)
          UnoRuntime.queryInterface(XDialogProvider.class, obj);
 
      // Got DialogProvider, now get dialog 
      try {
          theDialog = xDialogProvider.createDialog(
              "vnd.sun.star.script:MyDialogLibrary.MyDialog?location=application");
      }
      catch (java.lang.Exception e) {
          System.err.println("Got exception on first creating dialog: " + e.getMessage());
      }
      return theDialog;
  }

Calling a macro with the Scripting Framework

The service com.sun.star.script.provider.ScriptProvider exports interface XScriptProvider which offers method getScript( ). This method returns an interface XScript which offers the method invoke( ) which will call the script with parameters if necessary.

The identity and location of the called script is contained in an URI, which follows a particular syntax.


Here are links to some code examples written by the community:


Content on this page is licensed under the Public Documentation License (PDL).
Personal tools
In other languages