KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > batik > apps > slideshow > Main


1 /*
2
3    Copyright 1999-2003 The Apache Software Foundation
4
5    Licensed under the Apache License, Version 2.0 (the "License");
6    you may not use this file except in compliance with the License.
7    You may obtain a copy of the License at
8
9        http://www.apache.org/licenses/LICENSE-2.0
10
11    Unless required by applicable law or agreed to in writing, software
12    distributed under the License is distributed on an "AS IS" BASIS,
13    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14    See the License for the specific language governing permissions and
15    limitations under the License.
16
17 */

18
19 package org.apache.batik.apps.slideshow;
20
21 import java.awt.Color JavaDoc;
22 import java.awt.Cursor JavaDoc;
23 import java.awt.Dimension JavaDoc;
24 import java.awt.Graphics JavaDoc;
25 import java.awt.Graphics2D JavaDoc;
26 import java.awt.Point JavaDoc;
27 import java.awt.Rectangle JavaDoc;
28 import java.awt.Toolkit JavaDoc;
29 import java.awt.event.MouseAdapter JavaDoc;
30 import java.awt.event.MouseEvent JavaDoc;
31 import java.awt.image.BufferedImage JavaDoc;
32 import java.io.BufferedReader JavaDoc;
33 import java.io.File JavaDoc;
34 import java.io.FileNotFoundException JavaDoc;
35 import java.io.FileReader JavaDoc;
36 import java.io.IOException JavaDoc;
37 import java.net.MalformedURLException JavaDoc;
38 import java.net.URL JavaDoc;
39 import java.util.Vector JavaDoc;
40
41 import javax.swing.JComponent JavaDoc;
42 import javax.swing.JWindow JavaDoc;
43
44 import org.apache.batik.bridge.BridgeContext;
45 import org.apache.batik.bridge.DocumentLoader;
46 import org.apache.batik.bridge.GVTBuilder;
47 import org.apache.batik.bridge.UserAgent;
48 import org.apache.batik.bridge.UserAgentAdapter;
49 import org.apache.batik.bridge.ViewBox;
50 import org.apache.batik.gvt.GraphicsNode;
51 import org.apache.batik.gvt.renderer.StaticRenderer;
52 import org.w3c.dom.Document JavaDoc;
53 import org.w3c.dom.Element JavaDoc;
54 import org.w3c.dom.svg.SVGDocument;
55
56 public class Main extends JComponent JavaDoc {
57
58     StaticRenderer renderer;
59     UserAgent userAgent;
60     DocumentLoader loader;
61     BridgeContext ctx;
62
63     BufferedImage JavaDoc image;
64     BufferedImage JavaDoc display;
65     File JavaDoc [] files;
66
67     static int duration = 3000;
68     static int frameDelay = duration+7000;
69
70     boolean done = false;
71
72     public Main(File JavaDoc []files, Dimension JavaDoc size) {
73         setBackground(Color.black);
74         this.files = files;
75         renderer = new StaticRenderer();
76         userAgent = new UserAgentAdapter();
77         loader = new DocumentLoader(userAgent);
78         ctx = new BridgeContext(userAgent, loader);
79
80         if (size == null) {
81             size = Toolkit.getDefaultToolkit().getScreenSize();
82         }
83
84         setPreferredSize(size);
85         setDoubleBuffered(false);
86         addMouseListener(new MouseAdapter JavaDoc() {
87                 public void mouseClicked(MouseEvent JavaDoc me) {
88                     if (done)
89                         System.exit(0);
90                     else
91                         togglePause();
92                 }
93             });
94
95         size.width += 2;
96         size.height += 2;
97         display = new BufferedImage JavaDoc(size.width, size.height,
98                                     BufferedImage.TYPE_INT_BGR);
99
100         Thread JavaDoc t = new RenderThread();
101         t.start();
102
103         JWindow JavaDoc w = new JWindow JavaDoc();
104         w.setBackground(Color.black);
105         w.getContentPane().setBackground(Color.black);
106         w.getContentPane().add(this);
107         w.pack();
108         w.setLocation(new Point JavaDoc(-1, -1));
109         w.setVisible(true);
110     }
111
112     class RenderThread extends Thread JavaDoc {
113         public void run() {
114             renderer.setDoubleBuffered(true);
115             for (int i=0; i<files.length; i++) {
116                 GraphicsNode gvtRoot = null;
117                 GVTBuilder builder = new GVTBuilder();
118
119                 try {
120                     System.out.println("Reading: " + files[i]);
121                     Document JavaDoc svgDoc = loader.loadDocument
122                         (files[i].toURL().toString());
123                     System.out.println("Building: " + files[i]);
124                     gvtRoot = builder.build(ctx, svgDoc);
125                     System.out.println("Rendering: " + files[i]);
126                     renderer.setTree(gvtRoot);
127
128                     Element JavaDoc elt = ((SVGDocument)svgDoc).getRootElement();
129                     renderer.setTransform
130                         (ViewBox.getViewTransform
131                          (null, elt, display.getWidth(), display.getHeight()));
132
133                     renderer.updateOffScreen(display.getWidth(),
134                                              display.getHeight());
135
136                     Rectangle JavaDoc r = new Rectangle JavaDoc(0, 0,
137                                                 display.getWidth(),
138                                                 display.getHeight());
139                     renderer.repaint(r);
140                     System.out.println("Painting: " + files[i]);
141                     image = renderer.getOffScreen();
142                     setTransition(image);
143                 } catch (Exception JavaDoc ex) {
144                     ex.printStackTrace();
145                 }
146             }
147             if (transitionThread != null) {
148                 try {
149                     transitionThread.join();
150                 } catch (InterruptedException JavaDoc ie) { }
151                 done = true;
152                 setCursor(new Cursor JavaDoc(Cursor.WAIT_CURSOR));
153             }
154         }
155     }
156
157     Thread JavaDoc transitionThread = null;
158
159     public void setTransition(BufferedImage JavaDoc newImg) {
160         synchronized (this) {
161             while (transitionThread != null) {
162                 try {
163                     wait();
164                 } catch (InterruptedException JavaDoc ie) { }
165             }
166             transitionThread = new TransitionThread(newImg);
167             transitionThread.start();
168         }
169     }
170
171
172     long startLastTransition=0;
173
174     boolean paused = false;
175
176     public void togglePause() {
177         synchronized(this) {
178             paused = !paused;
179             Cursor JavaDoc c;
180             if (paused) {
181                 c = new Cursor JavaDoc(Cursor.WAIT_CURSOR);
182             } else {
183                 c = new Cursor JavaDoc(Cursor.DEFAULT_CURSOR);
184                 if (transitionThread != null) {
185                     synchronized (transitionThread) {
186                         transitionThread.notifyAll();
187                     }
188                 }
189             }
190             setCursor(c);
191         }
192     }
193
194     class TransitionThread extends Thread JavaDoc {
195         BufferedImage JavaDoc src;
196         int blockw = 75;
197         int blockh = 75;
198
199         public TransitionThread(BufferedImage JavaDoc bi) {
200             src = bi;
201         }
202
203         public void run() {
204             int xblocks = (display.getWidth()+blockw-1)/blockw;
205             int yblocks = (display.getHeight()+blockh-1)/blockh;
206             int nblocks = xblocks*yblocks;
207
208             int tblock = duration/nblocks;
209             
210             Point JavaDoc [] rects = new Point JavaDoc[nblocks];
211             for (int y=0; y<yblocks; y++)
212                 for (int x=0; x<xblocks; x++)
213                     rects[y*xblocks+x] = new Point JavaDoc(x, y);
214
215             Graphics2D JavaDoc g2d = display.createGraphics();
216             g2d.setColor(new Color JavaDoc(0,0,0));
217
218             long currTrans = System.currentTimeMillis();
219             while ((currTrans-startLastTransition) < frameDelay) {
220                 try {
221                     long stime = frameDelay-(currTrans-startLastTransition);
222                     if (stime > 500) {
223                         System.gc();
224                         currTrans = System.currentTimeMillis();
225                         stime = frameDelay-(currTrans-startLastTransition);
226                     }
227                     if (stime > 0) sleep(stime);
228                 } catch (InterruptedException JavaDoc ie) { }
229                 currTrans = System.currentTimeMillis();
230             }
231
232             synchronized(this) {
233                 while (paused) {
234                     try {
235                         wait();
236                     } catch (InterruptedException JavaDoc ie) { }
237                 }
238             }
239
240             long last = startLastTransition = System.currentTimeMillis();
241             
242             for (int i=0; i<rects.length; i++) {
243                 int idx = (int)(Math.random()*(rects.length-i));
244                 Point JavaDoc pt = rects[idx];
245                 for (int j=idx+1; j<rects.length-i;j++)
246                     rects[j-1] = rects[j];
247                 int x=pt.x*blockw, y=pt.y*blockh;
248                 int w=blockw, h = blockh;
249                 if (x+w > src.getWidth()) w = src.getWidth()-x;
250                 if (y+h > src.getHeight()) h = src.getHeight()-y;
251
252                 synchronized (display) {
253                     g2d.fillRect(x, y, w, h);
254                     BufferedImage JavaDoc sub;
255
256                     sub = src.getSubimage(x, y, w, h);
257                     g2d.drawImage(sub, null, x, y);
258                 }
259
260                 repaint(x, y, w, h);
261                 long current = System.currentTimeMillis();
262                 try {
263                     long dt = current-last;
264                     if (dt < tblock)
265                         sleep(tblock-dt);
266                 } catch (InterruptedException JavaDoc ie) { }
267                 last = current;
268             }
269
270             synchronized (Main.this) {
271                 transitionThread = null;
272                 Main.this.notifyAll();
273             }
274         }
275     }
276
277     public void paint(Graphics JavaDoc g) {
278         Graphics2D JavaDoc g2d = (Graphics2D JavaDoc)g;
279         if (display == null) return;
280         // System.out.println("Drawing Image: " + display);
281
g2d.drawImage(display, null, 0, 0);
282     }
283
284     public static void readFileList(String JavaDoc file, Vector JavaDoc fileVec) {
285         BufferedReader JavaDoc br;
286         try {
287             br = new BufferedReader JavaDoc(new FileReader JavaDoc(file));
288         } catch(FileNotFoundException JavaDoc fnfe) {
289             System.err.println("Unable to open file-list: " + file);
290             return;
291         }
292         try {
293             URL JavaDoc flURL = new File JavaDoc(file).toURL();
294             String JavaDoc line;
295             while ((line = br.readLine()) != null) {
296                 String JavaDoc str = line;
297                 int idx = str.indexOf('#');
298                 if (idx != -1)
299                     str = str.substring(0, idx);
300                 str.trim();
301                 if (str.length() == 0)
302                     continue;
303                 try {
304                     URL JavaDoc imgURL = new URL JavaDoc(flURL, str);
305                     fileVec.add(imgURL.getFile());
306                 } catch (MalformedURLException JavaDoc mue) {
307                     System.err.println("Can't make sense of line:\n " + line);
308                 }
309             }
310         } catch (IOException JavaDoc ioe) {
311             System.err.println("Error while reading file-list: " + file);
312         }
313     }
314
315     public static void main(String JavaDoc []args) {
316
317         Vector JavaDoc fileVec = new Vector JavaDoc();
318
319         Dimension JavaDoc d = null;
320         
321         if (args.length == 0) {
322             showUsage();
323             return;
324         }
325
326         for (int i=0; i<args.length; i++) {
327             if ((args[i].equals("-h")) ||
328                 (args[i].equals("-help")) ||
329                 (args[i].equals("--help"))){
330                 showUsage();
331                 return;
332             } else if (args[i].equals("--")) {
333                 i++;
334                 while(i < args.length) {
335                     fileVec.add(args[i++]);
336                 }
337                 break;
338             } else if ((args[i].equals("-fl"))||
339                      (args[i].equals("--file-list"))) {
340                 if (i+1 == args.length) {
341                     System.err.println
342                         ("Must provide name of file list file after " +
343                          args[i]);
344                     break;
345                 }
346                 readFileList(args[i+1], fileVec);
347                 i++;
348             } else if ((args[i].equals("-ft"))||
349                        (args[i].equals("--frame-time"))) {
350                 if (i+1 == args.length) {
351                     System.err.println
352                         ("Must provide time in millis after " + args[i]);
353                     break;
354                 }
355                 try {
356                     frameDelay = Integer.decode(args[i+1]).intValue();
357                     i++;
358                 } catch (NumberFormatException JavaDoc nfe) {
359                     System.err.println
360                         ("Can't parse frame time: " + args[i+1]);
361                 }
362             } else if ((args[i].equals("-tt"))||
363                        (args[i].equals("--transition-time"))) {
364                 if (i+1 == args.length) {
365                     System.err.println
366                         ("Must provide time in millis after " + args[i]);
367                     break;
368                 }
369                 try {
370                     duration = Integer.decode(args[i+1]).intValue();
371                     i++;
372                 } catch (NumberFormatException JavaDoc nfe) {
373                     System.err.println
374                         ("Can't parse transition time: " + args[i+1]);
375                 }
376             } else if ((args[i].equals("-ws"))||
377                        (args[i].equals("--window-size"))) {
378                 
379                 if (i+1 == args.length) {
380                     System.err.println
381                         ("Must provide window size [w,h] after " + args[i]);
382                     break;
383                 }
384                 try {
385                     int idx = args[i+1].indexOf(',');
386                     int w, h;
387                     if (idx == -1)
388                         w = h = Integer.decode(args[i+1]).intValue();
389                     else {
390                         String JavaDoc wStr = args[i+1].substring(0,idx);
391                         String JavaDoc hStr = args[i+1].substring(idx+1);
392                         w = Integer.decode(wStr).intValue();
393                         h = Integer.decode(hStr).intValue();
394                     }
395                     d = new Dimension JavaDoc(w, h);
396                     i++;
397                 } catch (NumberFormatException JavaDoc nfe) {
398                     System.err.println
399                         ("Can't parse window size: " + args[i+1]);
400                 }
401             } else
402                 fileVec.add(args[i]);
403         }
404             
405         File JavaDoc [] files = new File JavaDoc[fileVec.size()];
406
407
408         for (int i=0; i<fileVec.size(); i++) {
409             try {
410                 files[i] = new File JavaDoc((String JavaDoc)fileVec.get(i));
411             } catch (Exception JavaDoc ex) {
412                 ex.printStackTrace();
413             }
414         }
415
416         new Main(files, d);
417     }
418
419     public static void showUsage() {
420         System.out.println
421 ("Options:\n" +
422  " -- : Remaining args are file names\n" +
423  " -fl <file>\n" +
424  " --file-list <file> : file contains list of images to\n" +
425  " show one per line\n" +
426  " -ws <width>[,<height>]\n" +
427  " -window-size <width>[,<height>] : Set the size of slideshow window\n" +
428  " defaults to full screen\n" +
429  " -ft <int>\n" +
430  " --frame-time <int> : Amount of time in millisecs to\n" +
431  " show each frame.\n" +
432  " Includes transition time.\n" +
433  " -tt <int>\n" +
434  " --transition-time <int> : Amount of time in millisecs to\n" +
435  " transition between frames.\n" +
436  " <file> : SVG file to display");
437     }
438
439 }
440
Popular Tags