Debian Codegraph @

documentation-sources/content/xdocs/using/scripting/java.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 Java</title>
31 </header>
32
33 <body>
34 <p>
35 This page explains how to manipulate the DOM tree of an SVG
36 document from a Java program.
37 </p>
38
39 <section id="Swing">
40 <title>How to manipulate a document in a JSVGCanvas</title>
41 <p>
42 The follow code template demonstrates how to manipulate an SVG
43 document displayed in a
44 <a class="class" href="../../javadoc/org/apache/batik/swing/JSVGCanvas.html">JSVGCanvas</a>
45 directly from a Java program.
46 </p>
47 <note>
48 You don’t have to worry about graphics updates; after each event
49 listener invocation the canvas is updated if needed.
50 </note>
51 <source>import java.awt.event.WindowAdapter;
52 import java.awt.event.WindowEvent;
53
54 import javax.swing.JFrame;
55
56 import org.apache.batik.swing.JSVGCanvas;
57 import org.apache.batik.swing.svg.SVGLoadEventDispatcherAdapter;
58 import org.apache.batik.swing.svg.SVGLoadEventDispatcherEvent;
59 import org.apache.batik.script.Window;
60
61 import org.w3c.dom.Document;
62 import org.w3c.dom.Element;
63 import org.w3c.dom.events.Event;
64 import org.w3c.dom.events.EventListener;
65 import org.w3c.dom.events.EventTarget;
66
67 public class SVGApplication {
68
69 public static void main(String[] args) {
70 new SVGApplication();
71 }
72
73 JFrame frame;
74 JSVGCanvas canvas;
75 Document document;
76 Window window;
77
78 public SVGApplication() {
79 frame = new JFrame();
80 canvas = new JSVGCanvas();
81 // Forces the canvas to always be dynamic even if the current
82 // document does not contain scripting or animation.
83 canvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
84 canvas.addSVGLoadEventDispatcherListener
85 (new SVGLoadEventDispatcherAdapter() {
86 public void svgLoadEventDispatchStarted
87 (SVGLoadEventDispatcherEvent e) {
88 // At this time the document is available...
89 document = canvas.getSVGDocument();
90 // ...and the window object too.
91 window = canvas.getUpdateManager().
92 getScriptingEnvironment().createWindow();
93 // Registers the listeners on the document
94 // just before the SVGLoad event is
95 // dispatched.
96 registerListeners();
97 // It is time to pack the frame.
98 frame.pack();
99 }
100 });
101
102 frame.addWindowListener(new WindowAdapter() {
103 public void windowOpened(WindowEvent e) {
104 // The canvas is ready to load the base document
105 // now, from the AWT thread.
106 canvas.setURI("doc.svg");
107 }
108 });
109
110 frame.getContentPane().add(canvas);
111 frame.setSize(800, 600);
112 frame.show();
113 }
114
115 public void registerListeners() {
116 // Gets an element from the loaded document.
117 Element elt = document.getElementById("elt-id");
118 EventTarget t = (EventTarget)elt;
119
120 // Adds a 'onload' listener
121 t.addEventListener("SVGLoad", new OnLoadAction(), false);
122
123 // Adds a 'onclick' listener
124 t.addEventListener("click", new OnClickAction(), false);
125 }
126
127 public class OnLoadAction implements EventListener {
128 public void handleEvent(Event evt) {
129 // Perform some actions here...
130
131 // ...for example start an animation loop:
132 window.setInterval(new Animation(), 50);
133 }
134 }
135
136 public class OnClickAction implements EventListener {
137 public void handleEvent(Event evt) {
138 // Perform some actions here...
139
140 // ...for example schedule an action for later:
141 window.setTimeout(new DelayedTask(), 500);
142 }
143 }
144
145 public class Animation implements Runnable {
146 public void run() {
147 // Insert animation code here...
148 }
149 }
150
151 public class DelayedTask implements Runnable {
152 public void run() {
153 // Perform some actions here...
154
155 // ...for example displays an alert dialog:
156 window.alert("Delayed Action invoked!");
157 }
158 }
159 }
160 </source>
161 </section>
162
163 <section id="Threads">
164 <title>Writing thread-safe code</title>
165 <p>
166 The DOM listeners registered on the SVG document are called from
167 the canvas update thread. To avoid race conditions, do not manipulate
168 the DOM tree from another thread.
169 </p>
170 <p>
171 The way to switch from an external thread to the canvas update
172 thread is to use the following code:
173 </p>
174 <source>// Returns immediately
175 canvas.getUpdateManager().getUpdateRunnableQueue().
176 invokeLater(new Runnable() {
177 public void run() {
178 // Insert some actions on the DOM here
179 }
180 });</source>
181 <p>or:</p>
182 <source>// Waits until the Runnable is invoked
183 canvas.getUpdateManager().getUpdateRunnableQueue().
184 invokeAndWait(new Runnable() {
185 public void run() {
186 // Insert some actions on the DOM here
187 }
188 });</source>
189 <p>
190 Like with event listeners, when a
191 <a class="class" href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runnable.html">Runnable</a>
192 is invoked from the update thread, the graphics are updated.
193 </p>
194 <note>
195 It is very dangerous to call <code>invokeAndWait</code> from the
196 Swing event thread. This is the only thread that can be
197 used to interact with Swing components. In some cases
198 DOM calls may need to query the canvas for information
199 (such as actual Swing component size, etc). If this
200 happens you will get a thread deadlock. You should
201 only make invokeAndWait calls from “third party” threads.
202 </note>
203 </section>
204
205 <section id="SVGDOM">
206 <title>Using the SVG DOM</title>
207 <p>
208 Batik provides a fairly complete implementation of the
209 SVG DOM. The SVG DOM provides all the functionality most
210 applications require. In particular, the DOM implements
211 DOM Events, including mutation and UI Events. As an example,
212 DOM events allow you to get notified when the cursor moves over
213 elements of interest:
214 </p>
215 <source>// Element of Interest.
216 Element theElem = ...;
217 ((EventTarget) theElem).addEventListener("mouseover", mouseOverListener, true);</source>
218 <p>
219 where <code>mouseOverListener</code> implements the
220 <a class="class" href="http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/events/EventListener.html">org.w3c.dom.events.EventListener</a>
221 interface. This interface consists of the method:
222 </p>
223 <source>void handleEvent(Event evt);</source>
224 <p>
225 This is called whenever the event occurs with the
226 element it is registered on. It is worth reviewing the
227 DOM Events specification as there are many useful features
228 to this interface that are not immediately obvious.
229 </p>
230 <p>
231 It is also worth looking at the DOM interfaces defined
232 by the SVG specification as they provide a large number
233 of useful methods, in particular those of
234 <a class="class" href="../../javadoc/org/w3c/dom/svg/SVGLocatable.html">SVGLocatable</a>:
235 </p>
236 <source>// Returns Bounding box of SVG Element.
237 public SVGRect getBBox ( );
238 // Returns the transformation matrix to the screen.
239 public SVGMatrix getScreenCTM ( );
240 // Returns the transformation matrix to the given element.
241 public SVGMatrix getTransformToElement ( SVGElement element )
242 throws SVGException;</source>
243 <p>
244 In particular, <code>getScreenCTM</code> is very useful for
245 taking the <code>clientX</code> and <code>clientY</code> attributes of
246 the DOM
247 <a class="class" href="http://java.sun.com/j2se/1.5.0/docs/api/org/w3c/dom/events/UIEvent.html">UIEvent</a>
248 and mapping them to the coordinate system of an element in the SVG
249 document:
250 </p>
251 <source>SVGMatrix mat = elem.getScreenCTM();
252 SVGMatrix imat = mat.inverse();
253 SVGPoint cPt = document.getRootElement().createSVGPoint();
254 cPt.setX(uiEvt.getClientX());
255 cPt.setY(uiEvt.getClientY());
256 cPt = cPt.matrixTransform(imat);</source>
257 </section>
258
259 <section id="javaInDocument">
260 <title>Referencing Java code from a document</title>
261 <p>
262 Batik implements the Java bindings for SVG, and thus allows Java
263 code to be referenced from <code>script</code> elements.
264 This feature is available to any application of Batik that uses
265 the bridge module (for example the Swing component and the
266 transcoders).
267 </p>
268 <p>
269 In order to use this extension, the <code>type</code> attribute
270 of a <code>script</code> element must be set to
271 <code>application/java-archive</code>. In addition, the
272 <code>xlink:href</code> attribute must be the URI of a jar file
273 that contains the code to run.
274 </p>
275 <p>
276 The manifest of this jar file must contains an entry of the form:
277 </p>
278 <source>SVG-Handler-Class: <em>classname</em></source>
279 <p>
280 where <em>classname</em> must be the name of a class that
281 implements the
282 <a class="class" href="../../javadoc/org/w3c/dom/svg/EventListenerInitializer.html">org.w3c.dom.svg.EventListenerInitializer</a>
283 interface. Just before the document <code>SVGLoad</code> event
284 is fired, an instance of this class is created, and this instance has
285 its <code>initializeEventListeners</code> method invoked. Note that
286 there is no way to specify Java handlers in event attributes on
287 SVG elements, so having the <code>initializeEventListeners</code>
288 call <code>addEventListener</code> on a node is the only way to
289 attach a Java listener from within the document.
290 </p>
291 <p>
292 The class specified by <code>SVG-Handler-Class</code> can be contained
293 directly in the jar file, but it is also possible for it to be
294 contained in a jar file added to the classpath using the
295 <code>Class-Path</code> entry of the manifest.
296 </p>
297 </section>
298
299 </body>
300 </document>