|
|
How to build a Scripting Runtime?
Contents How to build a Scripting Runtime? What the Scripting Framework Provides What a new Runtime needs to provide: Loading and running the script Passing Useful data to the Script Parameters passed to the Script Current Runtimes invocation Parameter support Framework invocation Parameter support ReferenceDeveloper's Guide: Scripting Framework Online API documentation: http://framework.openoffice.org/scripting/EDR-IDLDocs/drafts/com/sun/star/script/framework Scripting Framework Website: http://framework.openoffice.org/scripting IntroductionBy creating a new Scripting Runtime a developer can add support for the scripting language of their choice to OpenOffice.org. The Scripting Framework provides all the required plumbing needed to facilitate the deployment, binding and invocation of scripts for an runtime. The runtime just has to provide the language specific execution environment for the script and execute it. The framework takes care of the rest. What the Scripting Framework Provides
What a new Runtime needs to provide:
UNO Language BridgeThere must be a supported UNO bridge for the scripting language to allow the framework to make calls against this new scripting runtime. The bridge will take care of all the parameter marshaling that needs to occur as the framework makes the call to the invoke method written in the new language. The Java and BeanShell Runtimes are supported by the existing Java UNO bridge. Any scripting language with a Java implementation could use the Java UNO bridge, such as Jython [Python], Jacl [Tcl/TK] andRhino [Javascript]. As other bridges become available native support could be added, for instance with the new PyUNO bridge, a Python Runtime could be written in Python.
The RuntimeRequired InterfacesThe Runtime is a normal UNO component, so it needs to support the following interfaces [Refer to the Developer's Guide for details on creating UNO Components]. Interface: com.sun.star.lang.XTypeProvider Interface: com.sun.star.lang.XServiceInfo In addition to the normal component interfaces above the Runtime must support the following interface to allow the framework to invoke the scripts in a language independent fashion: Interface: drafts.com.sun.star.script.framework.XScriptInvocation This interface supports one method, invoke( ), whose parameters and types are described below. Invoke ( )Returns: Any Throws: IllegalArgumentException, CannotConvertException,
The following sections describe the parameters to the invoke ( ) method call and how they can be used by a Runtime to setup an execution environment for a script and then load and run the script. ScriptURIThe scriptURI is the original script URI that was passed during the invoke.
This information should not be required by a runtime as the framework will have already resolved the script to a specific script and loaded up the detailed script information by the time the Runtime's invoke method is called [ refer to Appendix I for details on the framework's current resolution strategy]. If a runtime needs to parse the script URI, to perform it's own processing the scriptURI is provided to allow it to do so. The syntax of the script URI is:
script://<logical_name>['?'<query_element>('&'<query_element>)*]] where : query_element = <word>'='<name>
Example of Script URI: script://Tools.Convert.ToEuro? language=Java& function=com.sun.star.beans.tools.Standard.Convert.toEuro& location=user In the assign dialogs the user will see the Tools.Convert.ToEuro script name in the list of available scripts when Java is the selected language and user the selected location. Selecting this script will assign the above script URI to the menu, key or event binding as appropriate for the assign dialog invoked. It will be stored in the matching configuration file for later retrieval when the binding is invoked.
InvocationCtxThe invocationCtx is an implementation of XPropertySet setup by the framework to give a Runtime access both to the context from which the script was invoked (the current document) and the detailed information on the script itself which a Runtime will need to load and run the script (SCRIPT_INFO). InvocationCtx Property Set
Accesing properties from the invocationCtx property set [examples in Java]:
First get the property set from the invocationCtx: XPropertySet invocationCtxPropSet = ( XPropertySet ) UnoRuntime.queryInterface( XPropertySet.class, invocationCtx );
Then get the required property [use one of the property keys above]: Object propObject = invocationCtxPropSet.getPropertyValue( <Property Key> );
Query the returned object for the required object type: typedPropObject = ( <Property Type> ) UnoRuntime.queryInterface( <Property Type>.class, propObject );
For example to access the SCRIPT_INFO property: Object propObject = invocationCtxPropSet.getPropertyValue( “SCRIPT_INFO” ); scriptInfoPropObject = ( XScriptInfo ) UnoRuntime.queryInterface( XScriptInfo.class, propObject );
Loading and running the scriptThe framework will resolve the script URI to a specific script and load up the script information into a XScriptInfo object. This is then set as a property of the invocationCtx which is passed onto the Runtime in the Runtime's invoke ( ) method call. This contains the key information required by the Runtime to execute the script, it gives the Runtime access to all of the information about this specific script, including physical location and any language specific information that the Runtime requires to run the script, such as Classpath in the case of the Java and BeanShell runtimes. The Runtime can access the SCRIPT_INFO property of the invocationCtx as described above. Once it has the XScriptInfo it can use methods to get all the information it needs to load and run the script. Obtain the XScriptInfo as described above and use the following XScriptInfo interface methods to access the required data:
Typically the information in the invocationCtx and ScriptInfo information is used as follows by a Runtime [Note: though specific to the Java and BeanShell Runtimes, the general logical flow will be the same for most Runtimes] Runtime Invocation
Passing Useful data to the ScriptIt is up to the Runtime to decide what information to pass to a running script. It makes sense to pass information to the script which makes the script writer's job easier, such as a reference to the current document (available from the invocationCtx), reference to the service manager (available from the component context passed into the Runtime component's constructor by UNO) and a reference to the desktop (available from UNO using this service manager). In both the Java Runtime and the BeanShell runtime this context information is made available to the running script in the form of a XScriptContext. This provides accessor methods to get the current document, the current desktop and the component context. In the Java Runtime it's passed as the first parameter to the script and in the Beanshell Runtime it's setup in the runtime environment variable, “context”.
Interface: drafts.com.sun.star.script.framework.runtime.XScriptContext
Loading ScriptsScripts can be loaded from the user or share application directories or from a document. The parcelURI which provides the path to the script to load is in the form of an encoded URI. When the Runtime is using the parcelURI to load a script the Runtime needs to take account of this fact and process the parcelURI appropriately before it it is used. If you use the UNO UCB API, such as the XSimpleFileAccess, then you do not need to alter the encoded URI at all. If you want to use it to load the script just append a forward slash before appending the appropriate script filename and pass it to the appropriate XSimpleFileAccess methods. The Java and BeanShell Runtimes use XSimpleFileAccess [openFileRead(), getSize()] and XInputStream [readBytes() and closeInput()] to read in the script and setup a byte array input stream to the document script. This in turn is used to create a custom stream handler that can then be used with both the ClassLoader and URL classes, to allow the Runtimes to load up classes and scripts from the document. Any Java based Runtime can use the helper classes in UCBStreamHandler.java and PathUtils.java.
The parcelURI is in an encoded URL format.. The specification for URLs, RFC 1738 : http://www.rfc-editor.org/rfc/rfc1738.txt, limits the use of allowed characters in URLs to a subset of the US-ASCII character set. For a URL to be a well formed URL conformant with the URL specification it must encode any characters in the URL which fall outside this limited set. URL encoding of a character consists of a "%" symbol, followed by the two-digit hexadecimal representation (case-insensitive) of the ISO-Latin code point for the character. Characters which need to be encoded include; ASCII control characters, non ASCII characters, reserved characters [specific to URL syntax including Backslash (%5C) ] and unsafe characters [optional but may cause problems in a URL, including Space (%20) and Forward slash (%2F)]. The following table outlines what is passed to the Runtime for a given application or document script. It shows the type of processing that needs to be carried out before using the parcelURI to create a full path to access the application script from the file system or the document script from the document [The example uses the BeanShell Runtime, but the principal's are the same for any Runtime].
Parameters passed to the ScriptJava RuntimeTo run a Java script in OpenOffice.org, you must create a public Java class with at least one public Java method that takes an XScriptContext as it's first parameter. If no such method exists the Runtime will throw an exception. BeanShell RuntimeBeanShell scripts are single .bsh files, there are no parameter requirements when running BeanShell scripts. The Runtime does make the XScriptContext available in the BeanShell environment, but the script can use or ignore it as it sees fit. Current Runtimes invocation Parameter support
Framework invocation Parameter supportThe framework scripts can be invoked either directly using a call to XFunction, obtained from a suitably constructed XFunctionProvider or indirectly using one of the XFispatch methods. Interface: com::sun::star::frame::XDispatch Interface: drafts::com::sun::star::script::framework::provider::XFunctionProvider The appropriate dispatch handler will be invoked for the framework, based on the protocol of the scriptURI passed in [The Script Framework protocol handler, com.sun.star.comp.ScriptProtocolHandler, is registered in the ProtocolHandler.xcu configuration file when the framework is installed and handles URI's for the “script://” protocol].
Input ParamsIf a script is invoked from a menu, key or event binding setup using the Assign dialogs, there is no way to pass an input parameter to the script . However, it is possible to pass input parameters to a script if you invoke it from another script using either the XDispatch [asynchronous] or XFunction [synchronous] interfaces as shown below: Example using XFunction to Invoke a Script. with several input parameters Sub DisplayEuroConversionRates ( conversionRatesRile as String, numConversions as integer) dim args(0) args(0) = ThisComponent
' Create your FunctionProvider and obtain a Script Function from it. FuncProvider = createUnoService(“drafts.com.sun.star.script.framework.provider.FunctionProvider”) FuncProvider.initialize( args() ) Func = FuncProvider.getFunction( “script://Tools.Convert.DisplayEuroRates?_ language=Java&function=com.sun.star.beans.tools.Standard.Convert.displayEuro&location=user”)
Dim inArgs(1) Dim outArgs() Dim outIndex()
' Setup Input Param arguments inArgs(0) = conversionRatesFile inArgs(1) = numConversions
result = Func.invoke( inArgs(), outIndex(), outArgs() ) // Out params not handled by Java or BeanShell End Sub
Example using XDispatch to Invoke a Script with several input parameters
sub DisplayEuroConversionRates( conversionRatesFile as String, numConversions as integer) dim url as new com.sun.star.util.URL document = ThisComponent.CurrentController.Frame parser = createUnoService(“com.sun.star.util.URLTransformer”) dim args1(1) as new com.sun.star.beans.PropertyValue
' Setup Input Param arguments ' Note: args1(x).Name can be left blank ' Set argsl(x).Name to “Referrer” if you do not want it added as an input param args1(0).Value = conversionRatesFile args1(1).Value = numConversions
url.Complete = “script://Tools.Convert.DisplayEuroRates?_ language=Java&function=com.sun.star.beans.tools.Standard.Convert.displayEuro&location=user” parser.parseStrict(url) disp = document.queryDispatch(url,“”,0)
disp.dispatch(url, args1()) 'No access to Out params End Sub
Output ParamsAre currently not supported in the Java and BeanShell Runtimes. If you do implement them in your Runtime, the XDispatch script protocol handler has no way to process them [supports one way call only]. You would only be able to process them if you use the XFunction interface above in the calling script. ReturnsThe script runtime can return the result of the script in an Any if it makes sense to do so. The return result must be a type that is supported by the UNO language bridge being used by the Runtime [generally a primitive type or an UNO type]. If an unsupported type is passed back by the script the UNO bridge will cause an assert. Both the Java and BeanShell runtimes pass back the return value of scripts they invoke, it is the responsibility of the script writers to return types supported by the UNO bridge [refer to the Developer's Guide]. If there is no return value or the Runtime chooses not to support return values from scripts, it must always return a void Any [created as follows in Java: new Any(new Type(), null);] ErrorsIf any problems arise in the Runtime the following exceptions can be thrown by the invoke call. The Runtime should make sure the errors raised match the meaning of the the exceptions given below.
Runtime SingletonThe Runtime must be setup as a Singleton. The name of the singleton must follow the following scheme: theScriptRuntimeFor<Runtime Language> For example for Java the singleton is named theScriptRuntimeForJava and for BeanShell it is named theScriptRuntimeForBeanShell. This needs to be done programmatically in the _writeRegistryServiceInfo( ) method of the XServiceInfo service. In this method you need to create the appropriate singleton registry key under the UNO/Singletons key in the Office registration database in the [refer to example below for BeanShell]. [Note: this is an undocumented feature of 643 builds and above and is not covered in the Developer's Guide]. Singleton Registry Entry: [Implementation Name]+ "/UNO/SINGLETONS/” + [Service Module] + “.theScriptRuntimeFor<Runtime Language>” BeanShell Examplepublic static boolean __writeRegistryServiceInfo( XRegistryKey regKey ) { String impl = "com.sun.star.scripting.runtime.beanshell.ScriptRuntimeForBeanShell$_ScriptRuntimeForBeanShell"; String serviceModule = "drafts.com.sun.star.script.framework"; String service = serviceModule + ".ScriptRuntimeForBeanShell";
if (FactoryHelper.writeRegistryServiceInfo(impl, service, regKey)) { try { XRegistryKey newKey = regKey.createKey( impl + "/UNO/SINGLETONS/”+ serviceModule + “.theScriptRuntimeForBeanShell"); newKey.setStringValue(service); return true; } catch (Exception ex) { System.err.println("Error registering ScriptRuntimeForBeanShell: " + ex); } } return false; } PackagingThe new Runtime must be packaged as an UNO Component. Refer to the Developer's Guide on instructions on how to use the pkgchk tool to package the Runtime and any additional resources it may require. Creating ScriptsIf you want to allow your users to create script parcels for the new language Runtime, you can create a tool to create a script parcel, or you can use the existing command line tools to do so. The script parcel is just a zip file containing the script and any associated resources and a parcel-descriptor.xml file, which gives the details of the script, including language specific information that may be needed to run the script. You could write your own tools to create the parcel-descriptor.xml file. Refer to Appendix I for the parcel-descriptor.xml DTD. Binding to ScriptsIf a Runtime has been installed the Assign dialogs will automatically detect the new language Scripting Runtime singleton. The language will then be available as a choice in the language drop down combo of all of the assign dialogs. Choosing it the user will be presented with a list of any scripts for this language, deployed into the specified location [installation – user/ share; document]. The Runtime developer has nothing to do other than make sure the Runtime is registered as a singleton using the above naming scheme.
Appendix IScripting Framework ResolutionIf a Script URI has all of the key fields filled out [logical name, language, function and location] then the Script URI will be unambiguously matched to only one physically deployed script. If no match is found then a Runtime exception is raised by the framework.
What happens if you omit some or all of the optional fields? The framework will attempt to resolve the Script URI to one of the deployed scripts as follows.
In the future it may be possible to configure the framework's resolution strategies if the Script URI is not fully qualified. Runtime Specific ResolutionIn some Runtime's it may
be necessary to do further resolution checks, based not just on the
function name, but also on the Parameter list passed down to the
script.
Appendix IIParcel Descriptor DTD and sample XMLEach script must contain a parcel-descriptor.xml file which provides all the necessary metadata for the script. The DTD for the parcel-descriptor.xml follows <?xml version="1.0" encoding="UTF-8"?>
<!-- DTD for Parcel Meta data for use in the OpenOffice.org Scripting Framework Project -->
<!ELEMENT logicalname EMPTY>
<!ELEMENT description (#PCDATA)>
<!ELEMENT displayname EMPTY>
<!ELEMENT locale (displayname?, description?)>
<!ELEMENT functionname EMPTY>
<!ELEMENT prop EMPTY>
<!ELEMENT languagedepprops (prop+)>
<!ELEMENT file (prop*)>
<!ELEMENT fileset (file+)>
<!ELEMENT script (locale+, functionname, logicalname, languagedepprops*, fileset*)>
<!ELEMENT parcel (script+)>
<!ATTLIST logicalname
value CDATA #REQUIRED
>
<!ATTLIST displayname
value CDATA #REQUIRED
>
<!ATTLIST locale
lang CDATA #REQUIRED
>
<!ATTLIST functionname
value CDATA #REQUIRED
>
<!ATTLIST logicalname
value CDATA #REQUIRED
>
<!ATTLIST prop
name CDATA #REQUIRED
value CDATA #REQUIRED
>
<!ATTLIST file
name CDATA #REQUIRED
>
<!ATTLIST fileset
name CDATA #IMPLIED
>
<!ATTLIST script
language CDATA #REQUIRED
>
<!ATTLIST parcel
language CDATA #REQUIRED
>The following is an example of a parcel-descriptor.xml file that defines a script, implemented in Java. The languagedepprops element is used to extend the JVM's classpath. <?xml version="1.0" encoding="UTF-8"?>
<!--Sample Meta Data for use with the Scripting Framework Project in OpenOffice.org -->
<!DOCTYPE parcel SYSTEM "parcel.dtd">
<parcel language="Java">
<script language="Java">
<locale lang="english">
<displayname value="Memory.usage"/>
<description>
Displays the memory current memory usage
</description>
</locale>
<functionname value="memoryUtils.memoryUsage"/>
<logicalname value="MemoryUtils.MemUsage"/>
<languagedepprops>
<prop name="classpath" value="/opt/foo.jar:/usr/java/src.jar"/>
</languagedepprops>
<fileset>
<file name="mems.txt">
<prop name="type" value="resource"/>
</file>
</fileset>
</script>
</parcel>
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||


