Debian Codegraph @

documentation-sources/content/xdocs/using/scripting/ecmascript.xml

raw
1 <?xml version="1.0"?>
2
3 <!--
4
5 Licensed to the Apache Software Foundation (ASF) under one or more
6 contributor license agreements. See the NOTICE file distributed with
7 this work for additional information regarding copyright ownership.
8 The ASF licenses this file to You under the Apache License, Version 2.0
9 (the "License"); you may not use this file except in compliance with
10 the License. You may obtain a copy of the License at
11
12 http://www.apache.org/licenses/LICENSE-2.0
13
14 Unless required by applicable law or agreed to in writing, software
15 distributed under the License is distributed on an "AS IS" BASIS,
16 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 See the License for the specific language governing permissions and
18 limitations under the License.
19
20 -->
21
22 <!-- ========================================================================= -->
23 <!-- author [email protected] -->
24 <!-- version $Id$ -->
25 <!-- ========================================================================= -->
26
27 <!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
28 <document>
29 <header>
30 <title>Scripting with ECMAScript</title>
31 </header>
32
33 <body>
34 <p>
35 This page is a brief introduction to scripting SVG documents with
36 ECMAScript, and how Batik’s ECMAScript environment can be extended.
37 </p>
38
39 <section id="scriptingBasics">
40 <title>Scripting basics</title>
41 <p>
42 As the ECMAScript language (the standardised version of JavaScript)
43 is one of the most popular scripting languages, and as the SVG
44 specification states that an SVG conforming implementation must
45 support it, SVG documents processed by Batik support scripting
46 with ECMAScript using Mozilla’s ECMAScript interpreter,
47 <a href="http://www.mozilla.org/rhino/">Rhino</a>.
48 </p>
49 <p>
50 There are two places in an SVG file where you can put scripts.
51 </p>
52 <p>
53 The first one is in the <code>script</code>
54 element, where you can place any code, including function
55 definitions, to be executed just before the document
56 <code>SVGLoad</code> event is fired.
57 </p>
58 <source><![CDATA[<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
59 <script type="text/ecmascript">
60 // ECMAScript code to be executed
61 </script>
62
63 <!-- Remainder of the document... -->
64 </svg>]]></source>
65 <p>
66 You can also attach script to respond to user or document
67 events using attributes on SVG elements. As shown in the
68 previous example, the scripting language must be set on
69 the <code>script</code> element. However, for event handling
70 the default language type <code>text/ecmascript</code>
71 is assumed. If you want to change it you can use
72 the <code>contentScriptType</code> attribute on the
73 <code>svg</code> element.
74 </p>
75 <p>
76 The event attribute can contain any script code to execute when the
77 event reaches the element (as described by the
78 <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow">DOM event flow</a>)
79 in either the bubbling or at-target phases. The following example
80 will change the <code>rect</code> to be filled in blue when it is
81 clicked.
82 </p>
83 <source><![CDATA[<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
84 <rect x="0" y="0" width="10" height="10"
85 onclick="evt.target.setAttribute('fill', 'blue')"/>
86 </svg>]]></source>
87 <p>
88 Note that inside the event attribute script, there is a variable
89 called <code>evt</code> that is a reference to the
90 <a class="class" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event">Event</a>
91 object that represents the event that is being handled.
92 </p>
93 <p>
94 For more information on using scripting in SVG you can have a look at:
95 </p>
96 <ul>
97 <li>
98 the <a href="http://www.w3.org/TR/SVG11/script.html">scripting
99 chapter of the SVG specification</a>, for advanced information on
100 scripting in SVG, and
101 </li>
102 <li>
103 the <a href="http://www.ecma.ch/ecma1/stand/ecma-262.htm">ECMAScript
104 specification</a>, for advanced information on the ECMAScript
105 language.
106 </li>
107 </ul>
108 </section>
109
110 <section id="rhinoFeatures">
111 <title>Using Rhino features</title>
112
113 <p>
114 Rhino has a number of features beyond those supported by standard
115 ECMAScript interpreters, and these can be used with Batik. One
116 useful feature is that ECMAScript code can use Java classes and
117 objects, and not just the standard ECMAScript primitive types and
118 host objects exposed by Batik.
119 </p>
120 <p>
121 To create an instance of a Java class from ECMAScript, you first need
122 to import the package in which it resides. This is done using the
123 <code>importPackage</code> global function that Rhino provides.
124 For example, to import the <code>javax.swing.JFrame</code> class,
125 you use:
126 </p>
127 <source>importPackage(Packages.javax.swing);</source>
128 <p>
129 This then exposes a global property for each class in the
130 <code>javax.swing</code> package that you can use to create a new
131 object of this class, similar to a <code>import javax.swing.*;</code>
132 statement in Java. We can use the exposed <code>JFrame</code>
133 property to create a new instance of this class:
134 </p>
135 <source>var frame = new JFrame("My test frame");</source>
136 <p>
137 Note how an ECMAScript string value is passed as the parameter to
138 <code>JFrame</code>’s constructor. Rhino will attempt to convert
139 ECMAScript values into appropriate Java primitive types or objects
140 to make underlying constructor or method calls. In this instance,
141 the ECMAScript string value is converted into a
142 <code>java.lang.String</code> object to be passed to the constructor.
143 </p>
144 <p>
145 Now that we have a reference to this Java object, we can call any
146 method on it as we usually would from Java code. The following
147 complete example demonstrates this, where clicking the green
148 circle will pop up a frame:
149 </p>
150 <source><![CDATA[<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
151 <circle cx="50" cy="50" r="50" fill="green" onclick="showFrame()"/>
152 <script type="text/ecmascript">
153 importPackage(Packages.javax.swing);
154
155 function showFrame() {
156 var frame = new JFrame("My test frame");
157 var label = new JLabel("Hello from Java objects created in ECMAScript!");
158 label.setHorizontalAlignment(SwingConstants.CENTER);
159 frame.getContentPane().add(label);
160 frame.setSize(400, 100);
161 frame.setVisible(true);
162 frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
163 }
164 </script>
165 </svg>]]></source>
166
167 <p>
168 For more information on scripting Java classes from ECMAScript code,
169 see Rhino's
170 <a href="http://www.mozilla.org/rhino/ScriptingJava.html">Scripting
171 Java</a> document.
172 </p>
173 </section>
174
175 <section id="customizingRhino">
176 <title>Customizing the Rhino interpreter</title>
177
178 <p>
179 A useful example of customization of the Rhino interpreter comes from
180 the fact that the ECMAScript specification doesn’t provide any
181 predefined I/O facilities to interact with the console. However, it is
182 very common for ECMAScript compatible languages to provide a function
183 named <code>print</code> to output messages to the console. We will
184 describe here an example of customization of the Batik Rhino
185 interpreter to add such functionality to it.
186 </p>
187 <p>
188 You should first subclass the default Batik ECMAScript interpreter to
189 add the functionality to it as below.
190 </p>
191 <source>import org.apache.batik.script.rhino.RhinoInterpreter;
192
193 import java.net.URL;
194
195 import org.mozilla.javascript.Context;
196 import org.mozilla.javascript.Function;
197 import org.mozilla.javascript.Scriptable;
198 import org.mozilla.javascript.ScriptableObject;
199 import org.mozilla.javascript.PropertyException;
200
201 public class ExtendedRhinoInterpreter extends RhinoInterpreter {
202
203 public ExtendedRhinoInterpreter(URL documentURL) {
204 super(documentURL);
205
206 // Array of functions to put in the global object.
207 final String[] names = { "print" }
208 try {
209 // Add the functions to the global object.
210 getGlobalObject().defineFunctionProperties
211 (names, ExtendedRhinoInterpreter.class,
212 ScriptableObject.DONTENUM);
213 } catch (PropertyException e) {
214 throw new Error(e);
215 }
216 }
217
218 public static void print(Context cx, Scriptable thisObj,
219 Object[] args, Function funObj) {
220 for (int i = 0; i &lt; args.length; i++) {
221 if (i &gt; 0) {
222 System.out.print(" ");
223 }
224
225 // Convert the ECMAScript value into a string form.
226 String s = Context.toString(args[i]);
227 System.out.print(s);
228 }
229 System.out.println();
230 }
231 }</source>
232 <p>
233 Now, you need to tell to Batik to use this interpreter instead of the
234 default one. For that, you must first define a factory to create
235 instances of your interpreter.
236 </p>
237 <source>import org.apache.batik.script.Interpreter;
238 import org.apache.batik.script.rhino.RhinoInterpreterFactory;
239
240 public class ExtendedRhinoInterpreterFactory extends RhinoInterpreterFactory {
241
242 public Interpreter createInterpreter(URL documentURL, boolean isSVG12) {
243 return new ExtendedRhinoInterpreter(documentURL);
244 }
245 }</source>
246 <p>
247 Then, you must build an
248 <a class="class" href="../../javadoc/org/apache/batik/script/InterpreterPool.html">IntepreterPool</a>
249 that will use this factory, and then set the pool on the
250 <a class="class" href="../../javadoc/org/apache/batik/bridge/BridgeContext.html">BridgeContext</a>
251 of your application.
252 </p>
253 <source>org.apache.batik.bridge.BridgeContext ctx = ...;
254 org.apache.batik.script.InterpreterPool pool =
255 new org.apache.batik.script.InterpreterPool();
256 InterpreterFactory f = new ExtendedRhinoInterpreterFactory();
257
258 // Register the interpreter factory for all four MIME types that
259 // Batik normally supports for ECMAScript.
260 pool.putInterpreterFactory("text/ecmascript", f);
261 pool.putInterpreterFactory("text/javascript", f);
262 pool.putInterpreterFactory("application/ecmascript", f);
263 pool.putInterpreterFactory("application/javascript", f);
264 ctx.setIntepreterPool(pool);</source>
265 <p>
266 For example if you are using the Batik SVG browser application you
267 should be able to use the previous piece of code on a subclass of the
268 <a class="class" href="../../javadoc/org/apache/batik/swing/JSVGCanvas.html">JSVGCanvas</a>
269 class in the <code>createBridgeContext()</code> method.
270 </p>
271 <p>
272 For further information on working with Rhino, consult the
273 <a href="http://www.mozilla.org/rhino/">Rhino website</a>.
274 </p>
275 </section>
276 </body>
277 </document>