bf38ca1340c32abc4e7e15e67f05fa913054fc5f
[scilab.git] / scilab / modules / graphic_export / src / java / org / scilab / modules / graphic_export / Export.java
1 /*
2  * Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
3  * Copyright (C) 2012 - Scilab Enterprises - Calixte Denizet
4  *
5  * This file must be used under the terms of the CeCILL.
6  * This source file is licensed as described in the file COPYING, which
7  * you should have received as part of this distribution.  The terms
8  * are also available at
9  * http://www.cecill.info/licences/Licence_CeCILL_V2.1-en.txt
10  *
11  */
12
13 package org.scilab.modules.graphic_export;
14
15 import java.awt.Dimension;
16 import java.awt.Font;
17 import java.awt.Graphics2D;
18 import java.awt.Shape;
19 import java.awt.geom.AffineTransform;
20 import java.awt.geom.Ellipse2D;
21 import java.awt.geom.Path2D;
22 import java.awt.geom.PathIterator;
23 import java.awt.image.BufferedImage;
24 import java.io.BufferedOutputStream;
25 import java.io.ByteArrayOutputStream;
26 import java.io.File;
27 import java.io.FileNotFoundException;
28 import java.io.FileOutputStream;
29 import java.io.IOException;
30 import java.io.OutputStream;
31 import java.io.OutputStreamWriter;
32 import java.io.Writer;
33 import java.lang.reflect.Constructor;
34 import java.lang.reflect.InvocationTargetException;
35 import java.lang.reflect.Type;
36 import java.nio.charset.Charset;
37 import java.nio.charset.CharsetEncoder;
38 import java.text.AttributedCharacterIterator;
39 import java.util.HashMap;
40 import java.util.Map;
41 import java.util.WeakHashMap;
42
43 import org.apache.batik.dom.GenericDOMImplementation;
44 import org.apache.batik.svggen.SVGGeneratorContext;
45 import org.apache.batik.svggen.SVGGraphics2D;
46 import org.apache.fop.Version;
47 import org.apache.fop.svg.PDFDocumentGraphics2D;
48 import org.apache.xmlgraphics.java2d.GraphicContext;
49 import org.apache.xmlgraphics.java2d.ps.AbstractPSDocumentGraphics2D;
50 import org.apache.xmlgraphics.java2d.ps.EPSDocumentGraphics2D;
51 import org.apache.xmlgraphics.java2d.ps.PSDocumentGraphics2D;
52 import org.apache.xmlgraphics.ps.DSCConstants;
53 import org.apache.xmlgraphics.ps.PSGenerator;
54 import org.scilab.forge.scirenderer.Canvas;
55 import org.scilab.forge.scirenderer.implementation.g2d.G2DCanvas;
56 import org.scilab.forge.scirenderer.implementation.g2d.G2DCanvasFactory;
57 import org.scilab.forge.scirenderer.implementation.jogl.JoGLCanvas;
58 import org.scilab.forge.scirenderer.implementation.jogl.JoGLCanvasFactory;
59 import org.scilab.modules.commons.ScilabCommonsUtils;
60 import org.scilab.modules.graphic_export.convertToPPM.PPMEncoder;
61 import org.scilab.modules.graphic_objects.figure.Figure;
62 import org.scilab.modules.graphic_objects.graphicController.GraphicController;
63 import org.scilab.modules.graphic_objects.graphicObject.GraphicObjectProperties;
64 import org.scilab.modules.renderer.JoGLView.DrawerVisitor;
65 import org.w3c.dom.DOMImplementation;
66 import org.w3c.dom.Document;
67
68 /**
69  * Main class to export
70  * Dependancies are put in inner classes to avoid the deps loading.
71  *
72  * @author Calixte DENIZET
73  */
74 public class Export {
75
76     public static final int SUCCESS = 0;
77     public static final int IOEXCEPTION_ERROR = 1;
78     public static final int INVALID_FILE = 2;
79     public static final int MEMORY_ERROR = 3;
80     public static final int UNKNOWN_ERROR = 4;
81     public static final int FILENOTFOUND_ERROR = 5;
82
83     private static final float DEFAULT_JPEG_COMPRESSION = 0.95f;
84
85     private static final String CLASSPATH_PDF_PS_EPS_EXPORT_NAME = "pdf_ps_eps_graphic_export";
86     private static final String CLASSPATH_SVG_EXPORT_NAME = "svg_graphic_export";
87     private static final String CLASSPATH_EMF_EXPORT_NAME = "emf_graphic_export";
88
89     private static final Map<DrawerVisitor, Exporter> visitorsToExp = new WeakHashMap<DrawerVisitor, Exporter>();
90
91     private static final Map<String, Integer> extToType = new HashMap<String, Integer>();
92     static {
93         extToType.put("bmp", 1);
94         extToType.put("gif", 2);
95         extToType.put("jpeg", 3);
96         extToType.put("jpg", 3);
97         extToType.put("png", 4);
98         extToType.put("ppm", 5);
99         extToType.put("eps", 6);
100         extToType.put("pdf", 7);
101         extToType.put("svg", 8);
102         extToType.put("ps", 9);
103         extToType.put("pos", 9);
104         extToType.put("emf", 10);
105     }
106
107     private static boolean emfLoaded;
108     private static boolean svgLoaded;
109     private static boolean pdfLoaded;
110
111     public enum TYPE { PNG, JPEG, GIF, BMP, PPM, SVG, PS, EPS, PDF, EMF }
112     private static final TYPE[] types = new TYPE[] {TYPE.PNG, TYPE.BMP, TYPE.GIF, TYPE.JPEG, TYPE.PNG, TYPE.PPM, TYPE.EPS, TYPE.PDF, TYPE.SVG, TYPE.PS, TYPE.EMF};
113
114     /**
115      * @param type the image type
116      * @return true if bitmap image format
117      */
118     public static boolean isBitmapFormat(TYPE type) {
119         return type == TYPE.PNG || type == TYPE.JPEG || type == TYPE.GIF || type == TYPE.BMP || type == TYPE.PPM;
120     }
121
122     public static int getType(String ext) {
123         Integer type = extToType.get(ext.toLowerCase());
124         if (type == null) {
125             return -1;
126         }
127
128         return type;
129     }
130
131     /**
132      * Export in drawing in a Graphics2D
133      * @param uid the figure uid
134      * @param type the export type
135      * @param fileName the file name
136      * @param params the export paramaters
137      * @return the export status
138      */
139     public static int export(int uid, int type, String fileName, ExportParams params, boolean headless) {
140         // Check that the fileName contains an extension
141         int dotPosition = fileName.lastIndexOf('.'); // position of the dot
142         boolean extensionFound = false;
143         if (dotPosition > 0 && dotPosition <= fileName.length() - 2) {
144             extensionFound = true;
145         }
146
147         String extendedFilename = fileName;
148         if (!extensionFound) { // Add default extension if no one found
149             String[] extensions = {"png", "bmp", "gif", "jpeg", "png", "ppm", "eps", "pdf", "svg", "ps", "emf"};
150             extendedFilename = fileName + "." + extensions[type];
151         }
152
153         DrawerVisitor visitor = DrawerVisitor.getVisitor(uid);
154         if (visitor != null) {
155             Canvas canvas = visitor.getCanvas();
156             if (canvas instanceof JoGLCanvas && isBitmapFormat(types[type]) && visitor.getFigure().getVisible()) {
157                 try {
158                     return exportBitmap(uid, type, extendedFilename, true, params);
159                 } catch (OutOfMemoryError e) {
160                     return MEMORY_ERROR;
161                 } catch (Throwable e) {
162                     return UNKNOWN_ERROR;
163                 }
164             }
165         }
166
167         return exportVectorial(uid, type, extendedFilename, params, headless);
168     }
169
170     /**
171      * Export in drawing in a Graphics2D
172      * @param uid the figure uid
173      * @param type the export type
174      * @param fileName the file name
175      * @param params the export paramaters
176      * @return the export status
177      */
178     public static int exportVectorial(int uid, int type, String fileName, ExportParams params, boolean headless) {
179         if (fileName == null) {
180             return INVALID_FILE;
181         }
182
183         File f = new File(fileName);
184         int ret = Utils.checkWritePermission(f);
185         if (ret != SUCCESS) {
186             return ret;
187         }
188
189         try {
190             return exportVectorial(uid, types[type], f, params, headless);
191         } catch (IOException e) {
192             if (e instanceof FileNotFoundException) {
193                 return FILENOTFOUND_ERROR;
194             }
195             return IOEXCEPTION_ERROR;
196         }
197     }
198
199     /**
200      * Export in drawing in a Graphics2D
201      * @param uid the figure uid
202      * @param type the export type
203      * @param file the file where to export
204      * @param params the export paramaters
205      */
206     public static int exportVectorial(int uid, TYPE type, File file, ExportParams params, boolean headless) throws IOException {
207         Figure figure = (Figure) GraphicController.getController().getObjectFromId(uid);
208
209         if (!headless) {
210             Exporter exporter = getExporter(type);
211             Integer[] dims = figure.getAxesSize();
212             int width = dims[0];
213             int height = dims[1];
214
215             Graphics2D g2d = exporter.getGraphics2D(width, height, file, params);
216             if (g2d == null) {
217                 return FILENOTFOUND_ERROR;
218             }
219
220             params.setParamsOnGraphics(g2d);
221
222             Canvas canvas = G2DCanvasFactory.createCanvas(g2d, width, height);
223             DrawerVisitor oldVisitor = DrawerVisitor.getVisitor(uid);
224             DrawerVisitor visitor = new DrawerVisitor(null, canvas, figure) {
225                 @Override
226                 public void updateObject(Integer id, int property) {
227                     // Don't update during the export
228                 }
229
230                 @Override
231                 public void visit(Figure figure) {
232                     // Fix for bug 13676: allow vectorial export even if the figure is invisible
233                     synchronized (figure) {
234                         super.visit(figure);
235                         if (!figure.getVisible()) {
236                             askAcceptVisitor(figure.getChildren());
237                         }
238                     }
239                 }
240             };
241
242             try {
243                 canvas.setMainDrawer(visitor);
244                 canvas.redraw();
245                 exporter.write();
246             } catch (OutOfMemoryError e) {
247                 return MEMORY_ERROR;
248             } catch (IOException e) {
249                 throw e;
250             } catch (Throwable e) {
251                 return UNKNOWN_ERROR;
252             } finally {
253                 GraphicController.getController().unregister(visitor);
254                 DrawerVisitor.changeVisitor(figure, oldVisitor);
255                 exporter.dispose();
256                 exporter = null;
257                 visitorsToExp.remove(visitor);
258                 canvas.destroy();
259             }
260         } else {
261             DrawerVisitor visitor = DrawerVisitor.getVisitor(uid);
262             if (visitor.getCanvas() instanceof G2DCanvas) {
263                 G2DCanvas canvas = (G2DCanvas) visitor.getCanvas();
264                 canvas.enableDraw();
265                 Exporter exporter = null;
266                 try {
267                     canvas.redraw();
268                     exporter = visitorsToExp.get(visitor);
269                     if (exporter != null) {
270                         exporter.file = file;
271                         exporter.write();
272                     }
273                 } catch (OutOfMemoryError e) {
274                     return MEMORY_ERROR;
275                 } catch (IOException e) {
276                     throw e;
277                 } catch (Throwable e) {
278                     return UNKNOWN_ERROR;
279                 } finally {
280                     if (exporter != null) {
281                         exporter.dispose();
282                         exporter = null;
283                         visitorsToExp.remove(visitor);
284                     }
285                     DrawerVisitor.changeVisitor(figure, null);
286                     GraphicController.getController().unregister(visitor);
287                     canvas.destroy();
288                 }
289             }
290         }
291
292         return SUCCESS;
293     }
294
295     /**
296      * Export in getting a buffered image from JoGL
297      * @param uid the figure uid
298      * @param type the export type
299      * @param fileName the file name
300      * @param fromScreen if true, then use the screen view
301      * @param params the export paramaters
302      * @return the export status
303      */
304     public static int exportBitmap(int uid, int type, String fileName, boolean fromScreen, ExportParams params) {
305         if (fileName == null) {
306             return INVALID_FILE;
307         }
308
309         File f = new File(fileName);
310         int ret = Utils.checkWritePermission(f);
311         if (ret != SUCCESS) {
312             return ret;
313         }
314
315         try {
316             exportBitmap(uid, types[type], f, fromScreen, params);
317         } catch (IOException e) {
318             if (e instanceof FileNotFoundException) {
319                 return FILENOTFOUND_ERROR;
320             }
321             return IOEXCEPTION_ERROR;
322         }
323
324         return SUCCESS;
325     }
326
327     /**
328      * Export in getting a buffered image from JoGL
329      * @param uid the figure uid
330      * @param type the export type
331      * @param file the file where to export
332      * @param fromScreen if true, then use the screen view
333      * @param params the export paramaters
334      */
335     public static void exportBitmap(int uid, TYPE type, File file, boolean fromScreen, ExportParams params) throws IOException {
336         if (isBitmapFormat(type)) {
337             JoGLCanvas joglCanvas = null;
338             if (fromScreen) {
339                 DrawerVisitor visitor = DrawerVisitor.getVisitor(uid);
340                 Canvas canvas = visitor.getCanvas();
341                 if (canvas instanceof JoGLCanvas) {
342                     joglCanvas = (JoGLCanvas) canvas;
343                 }
344             } else {
345                 Figure figure = (Figure) GraphicController.getController().getObjectFromId(uid);
346                 Integer[] dims = figure.getAxesSize();
347                 DrawerVisitor oldVisitor = DrawerVisitor.getVisitor(uid);
348                 joglCanvas = (JoGLCanvas) JoGLCanvasFactory.createCanvas(dims[0], dims[1]);
349                 DrawerVisitor visitor = new DrawerVisitor(null, joglCanvas, figure) {
350                     @Override
351                     public void updateObject(Integer id, int property) {
352                         // Don't update during the export
353                     }
354
355                     @Override
356                     public void deleteObject(Integer id) {
357                         // Don't delete during the export
358                     }
359                 };
360                 joglCanvas.setMainDrawer(visitor);
361                 joglCanvas.redraw();
362                 GraphicController.getController().unregister(visitor);
363                 DrawerVisitor.changeVisitor(figure, oldVisitor);
364             }
365
366             if (joglCanvas != null) {
367                 BufferedImage image = joglCanvas.getImage();
368                 //joglCanvas.destroy();
369                 PNGExporter exporter = (PNGExporter) getExporter(type);
370                 exporter.setImage(file, image, params);
371                 exporter.write();
372                 exporter.dispose();
373             }
374         }
375     }
376
377     /**
378      * Export in drawing in a Graphics2D
379      * @param uid the figure uid
380      * @param type the export type
381      * @param file the file where to export
382      * @param params the export paramaters
383      */
384     public static void setVisitor(int uid, int type, final ExportParams params) {
385         final Exporter exporter = getExporter(types[type]);
386         Figure figure = (Figure) GraphicController.getController().getObjectFromId(uid);
387         final Integer[] dims = figure.getAxesSize();
388         int width = dims[0];
389         int height = dims[1];
390
391         final Graphics2D g2d = exporter.getGraphics2D(width, height, null, params);
392         params.setParamsOnGraphics(g2d);
393
394         final G2DCanvas canvas = G2DCanvasFactory.createCanvas(g2d, width, height);
395         canvas.disableDraw();
396         DrawerVisitor visitor = new DrawerVisitor(null, canvas, figure) {
397             @Override
398             public void deleteObject(Integer id) {
399                 // Don't delete during the export
400             }
401
402             @Override
403             public void updateObject(Integer id, int property) {
404                 if (needUpdate(id, property)) {
405                     axesDrawer.update(id, property);
406                     if (property == GraphicObjectProperties.__GO_AXES_SIZE__) {
407                         Integer[] size = getFigure().getAxesSize();
408                         if (size[0] != dims[0] || size[1] != dims[1]) {
409                             Graphics2D newg2d = exporter.getGraphics2D(size[0], size[1], null, params);
410                             params.setParamsOnGraphics(newg2d);
411                             canvas.setGraphics(newg2d, size[0], size[1]);
412                             dims[0] = size[0];
413                             dims[1] = size[1];
414
415                             g2d.dispose();
416                         }
417                     } else if (property == GraphicObjectProperties.__GO_ANTIALIASING__) {
418                         canvas.setAntiAliasingLevel(getFigure().getAntialiasing());
419                     }
420                 }
421             }
422         };
423         visitor.setDrawingTools(canvas.getDrawingTools());
424         canvas.setMainDrawer(visitor);
425         visitorsToExp.put(visitor, exporter);
426     }
427
428     /**
429      * Get an exporter from a type
430      * @param type the exporter type.
431      * @return the corresponding exporter/
432      */
433     private static Exporter getExporter(TYPE type) {
434         switch (type) {
435             case PNG :
436                 return new PNGExporter();
437             case GIF :
438                 return new GIFExporter();
439             case JPEG :
440                 return new JPEGExporter();
441             case BMP :
442                 return new BMPExporter();
443             case PPM :
444                 return new PPMExporter();
445             case SVG :
446                 if (!svgLoaded) {
447                     ScilabCommonsUtils.loadOnUse(CLASSPATH_SVG_EXPORT_NAME);
448                     svgLoaded = true;
449                 }
450                 return new SVGExporter();
451             case PDF :
452                 loadPDF();
453                 return new PDFExporter();
454             case PS :
455                 loadPDF();
456                 return new PSExporter();
457             case EPS :
458                 loadPDF();
459                 return new EPSExporter();
460             case EMF :
461                 if (!emfLoaded) {
462                     ScilabCommonsUtils.loadOnUse(CLASSPATH_EMF_EXPORT_NAME);
463                     emfLoaded = true;
464                 }
465                 return new EMFExporter();
466             default :
467                 break;
468         }
469
470         return null;
471     }
472
473     /**
474      * Load the PDF/PS/EPS dependencies
475      */
476     private static final void loadPDF() {
477         if (!pdfLoaded) {
478             ScilabCommonsUtils.loadOnUse(CLASSPATH_PDF_PS_EPS_EXPORT_NAME);
479             pdfLoaded = true;
480         }
481     }
482
483     /**
484      * Interface to export
485      */
486     private static abstract class Exporter {
487
488         protected File file;
489
490         /**
491          * @param width graphics width
492          * @param height graphisc height
493          * @param file the file
494          * @param params the export parameters
495          */
496         abstract Graphics2D getGraphics2D(int width, int height, File file, ExportParams params);
497
498         /**
499          * Write the file
500          */
501         abstract void write() throws IOException;
502
503         abstract void dispose();
504     }
505
506     /**
507      * PNG Exporter
508      */
509     private static class PNGExporter extends Exporter {
510
511         protected BufferedImage image;
512         protected Graphics2D g2d;
513         protected ExportParams params;
514
515         public PNGExporter() { }
516
517         public void setImage(File file, BufferedImage image, ExportParams params) {
518             this.file = file;
519             this.image = image;
520             this.params = params;
521         }
522
523         @Override
524         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
525             this.file = file;
526             this.params = params;
527             image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
528             g2d = image.createGraphics();
529
530             return g2d;
531         }
532
533         @Override
534         public void write() throws IOException {
535             ExportBitmap.writeFile(image, "png", file);
536         }
537
538         @Override
539         public void dispose() {
540             if (g2d != null) {
541                 g2d.dispose();
542             }
543         }
544     }
545
546     /**
547      * GIF Exporter
548      */
549     private static class GIFExporter extends PNGExporter {
550
551         public GIFExporter() { }
552
553         @Override
554         public void write() throws IOException {
555             ExportBitmap.writeFile(image, "gif", file);
556         }
557     }
558
559     /**
560      * BMP Exporter
561      */
562     private static class BMPExporter extends PNGExporter {
563
564         public BMPExporter() { }
565
566         @Override
567         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
568             this.file = file;
569             this.params = params;
570             image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
571             g2d = image.createGraphics();
572
573             return g2d;
574         }
575
576         @Override
577         public void write() throws IOException {
578             ExportBitmap.writeFile(image, "bmp", file);
579         }
580     }
581
582     /**
583      * JPEG Exporter
584      */
585     private static class JPEGExporter extends BMPExporter {
586
587         public JPEGExporter() { }
588
589         @Override
590         public void write() throws IOException {
591             if (params.compressionQuality == -1) {
592                 ExportBitmap.writeJPEG(image, DEFAULT_JPEG_COMPRESSION, file);
593             } else {
594                 ExportBitmap.writeJPEG(image, params.compressionQuality, file);
595             }
596         }
597     }
598
599     /**
600      * PPM Exporter
601      */
602     private static class PPMExporter extends BMPExporter {
603
604         public PPMExporter() { }
605
606         @Override
607         public void write() throws IOException {
608             OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
609             PPMEncoder encoder = new PPMEncoder(image, out);
610             int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
611             encoder.encodeStart(image.getWidth(), image.getHeight());
612             encoder.encodePixels(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
613             out.flush();
614             out.close();
615         }
616     }
617
618     /**
619      * SVG Exporter
620      */
621     private static class SVGExporter extends Exporter {
622
623         private SVGGraphics2D g2d;
624         private ExportParams params;
625
626         public SVGExporter() { }
627
628         @Override
629         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
630             this.file = file;
631             this.params = params;
632             DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
633             Document document = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null);
634             final SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(document);
635             ctx.setComment("Generated by Scilab with Batik SVG Generator");
636             // TODO: better handle of LaTeX fonts (should remove the 'true' below and include the font in the SVG)
637             // same thing for PDF & co...
638             ctx.setEmbeddedFontsOn(true);
639             g2d = new SVGGraphics2D(ctx, false) {
640
641                 @Override
642                 public void drawString(String s, float x, float y) {
643                     textAsShapes = getFont().getFontName().startsWith("jlm");
644                     super.drawString(s, x, y);
645                 }
646
647                 @Override
648                 public void drawString(AttributedCharacterIterator ati, float x, float y) {
649                     textAsShapes = getFont().getFontName().startsWith("jlm");
650                     super.drawString(ati, x, y);
651                 }
652             };
653             if (params.orientation == ExportParams.LANDSCAPE) {
654                 g2d.setSVGCanvasSize(new Dimension(height, width));
655                 AffineTransform transf = AffineTransform.getRotateInstance(Math.PI / 2);
656                 transf.preConcatenate(AffineTransform.getTranslateInstance(height, 0));
657                 g2d.setTransform(transf);
658             } else {
659                 g2d.setSVGCanvasSize(new Dimension(width, height));
660             }
661             return g2d;
662         }
663
664         @Override
665         public void write() throws IOException {
666             boolean useCSS = true;
667             OutputStream svgs = new BufferedOutputStream(new FileOutputStream(file));
668             Writer out = new OutputStreamWriter(svgs, "UTF-8");
669             g2d.stream(out, useCSS);
670             svgs.flush();
671             svgs.close();
672         }
673
674         @Override
675         public void dispose() {
676             if (g2d != null) {
677                 g2d.dispose();
678             }
679         }
680     }
681
682     /**
683      * PDF Exporter
684      */
685     private static class PDFExporter extends Exporter {
686
687         private OutputStream out;
688         private PDFDocumentGraphics2D g2d;
689         private ExportParams params;
690         private ByteArrayOutputStream buffer;
691
692         public PDFExporter() { }
693
694         @Override
695         public Graphics2D getGraphics2D(int width, int height, File file, ExportParams params) {
696             this.file = file;
697             this.params = params;
698             try {
699                 if (file == null) {
700                     buffer = new ByteArrayOutputStream();
701                     out = new BufferedOutputStream(buffer);
702                 } else {
703                     out = new BufferedOutputStream(new FileOutputStream(file));
704                 }
705                 g2d = new PDFDocumentGraphics2D(true);
706                 g2d.setupDefaultFontInfo();
707                 g2d.getPDFDocument().getInfo().setProducer("Generated by Scilab with Apache FOP Version " + Version.getVersion());
708                 g2d.setGraphicContext(new GraphicContext());
709                 if (params.orientation == ExportParams.LANDSCAPE) {
710                     g2d.setupDocument(out, height, width);
711                     g2d.setSVGDimension(height, width);
712                     double s = PDFDocumentGraphics2D.NORMAL_PDF_RESOLUTION / g2d.getDeviceDPI();
713                     AffineTransform transf = AffineTransform.getRotateInstance(Math.PI / 2);
714                     transf.preConcatenate(AffineTransform.getTranslateInstance(height / s, 0));
715                     g2d.setTransform(transf);
716                 } else {
717                     g2d.setupDocument(out, width, height);
718                     g2d.setSVGDimension(width, height);
719                 }
720             } catch (IOException e) { }
721
722             return g2d;
723         }
724
725         @Override
726         public void write() throws IOException {
727             if (g2d != null) {
728                 g2d.finish();
729             }
730             if (buffer != null && file != null) {
731                 FileOutputStream fos = new FileOutputStream(file);
732                 buffer.writeTo(fos);
733                 buffer.close();
734                 fos.flush();
735                 fos.close();
736             }
737             if (out != null) {
738                 out.close();
739             }
740         }
741
742         @Override
743         public void dispose() {
744             g2d.dispose();
745         }
746     }
747
748     /**
749      * PS Exporter
750      */
751     private static class PSExporter extends Exporter {
752
753         protected OutputStream out;
754         protected AbstractPSDocumentGraphics2D g2d;
755         protected ExportParams params;
756         protected ByteArrayOutputStream buffer;
757
758         public PSExporter() { }
759
760         @Override
761         public Graphics2D getGraphics2D(int width, int height, File file, final ExportParams params) {
762             this.file = file;
763             this.params = params;
764             try {
765                 if (file == null) {
766                     buffer = new ByteArrayOutputStream();
767                     out = new BufferedOutputStream(buffer);
768                 } else {
769                     out = new BufferedOutputStream(new FileOutputStream(file));
770                 }
771                 g2d = new PSDocumentGraphics2D(true, out, width, height) {
772                     @Override
773                     protected void writePageHeader() throws IOException {
774                         super.writePageHeader();
775                         if (params.orientation == ExportParams.LANDSCAPE) {
776                             gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape");
777                         } else {
778                             gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Portrait");
779                         }
780                         gen.writeln("/ReEncode { /MyEncoding exch def exch findfont dup length dict begin {def} forall /Encoding MyEncoding def currentdict end definefont } def");
781                         gen.writeln("/Helvetica /HelveticaLatin1 ISOLatin1Encoding ReEncode");
782                         gen.writeln("/Times /TimesLatin1 ISOLatin1Encoding ReEncode");
783                         gen.writeln("/DP {/Points exch def N Points 0 get Points 1 get M 2 2 Points length 1 sub {/i exch def Points i get Points i 1 add get L}for} def");
784                     }
785
786                     @Override
787                     public void drawString(String s, float x, float y) {
788                         if (s != null && !s.isEmpty()) {
789                             CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder();
790                             if (encoder.canEncode(s)) {
791                                 Font font = getFont();
792                                 boolean sserif = font.getName().equals("SansSerif");
793                                 boolean serif = font.getName().equals("Serif");
794                                 if (sserif || serif) {
795                                     try {
796                                         preparePainting();
797                                         establishColor(getColor());
798                                         gen.writeln((sserif ? "/HelveticaLatin1" : "/TimesLatin1") + " " + gen.formatDouble(getFont().getSize()) + " F");
799
800                                         gen.saveGraphicsState();
801                                         Shape imclip = getClip();
802                                         writeClip(imclip);
803
804                                         AffineTransform trans = getTransform();
805                                         boolean newTransform = gen.getCurrentState().checkTransform(trans) && !trans.isIdentity();
806
807                                         if (newTransform) {
808                                             gen.concatMatrix(trans);
809                                         }
810
811                                         gen.writeln(gen.formatDouble(x)
812                                                     + " " + gen.formatDouble(y)
813                                                     + " M 1 -1 scale");
814
815                                         StringBuffer buf = new StringBuffer("(");
816                                         for (int i = 0; i < s.length(); i++) {
817                                             PSGenerator.escapeChar(s.charAt(i), buf);
818                                         }
819                                         buf.append(") t");
820
821                                         gen.writeln(buf.toString());
822
823                                         gen.restoreGraphicsState();
824                                     } catch (IOException e) {
825                                         System.err.println(e);
826                                     }
827
828                                     return;
829                                 }
830                             }
831
832                             super.drawString(s, x, y);
833                         }
834                     }
835
836                     @Override
837                     public boolean shouldBeClipped(Shape clip, Shape s) {
838                         if (clip == null || s == null) {
839                             return false;
840                         }
841
842                         return clip.getBounds2D().intersects(s.getBounds2D());
843                     }
844
845                     @Override
846                     public int processShape(Shape s) throws IOException {
847                         if (s instanceof Ellipse2D.Double) {
848                             Ellipse2D.Double ell = (Ellipse2D.Double) s;
849                             if (ell.height == ell.width) {
850                                 gen.writeln(gen.formatDouble(ell.x + ell.width / 2)
851                                             + " " + gen.formatDouble(ell.y + ell.height / 2)
852                                             + " " + gen.formatDouble(ell.width / 2)
853                                             + " " + gen.formatDouble(0d)
854                                             + " " + gen.formatDouble(360d)
855                                             + " arc cp");
856
857                                 return PathIterator.WIND_NON_ZERO;
858                             }
859                         } else if (s instanceof Path2D) {
860                             StringBuilder buffer = new StringBuilder();
861                             double[] coords = new double[6];
862                             PathIterator it = ((Path2D) s).getPathIterator(new AffineTransform());
863                             if (!it.isDone()) {
864                                 int type = it.currentSegment(coords);
865                                 if (type == PathIterator.SEG_MOVETO) {
866                                     buffer.append("[").append(gen.formatDouble(coords[0])).append(" ").append(gen.formatDouble(coords[1]));
867                                     it.next();
868                                 } else {
869                                     return super.processShape(s);
870                                 }
871                             } else {
872                                 return super.processShape(s);
873                             }
874
875                             for (; !it.isDone(); it.next()) {
876                                 int type = it.currentSegment(coords);
877                                 if (type == PathIterator.SEG_LINETO) {
878                                     buffer.append(" ").append(gen.formatDouble(coords[0])).append(" ").append(gen.formatDouble(coords[1]));
879                                 } else {
880                                     return super.processShape(s);
881                                 }
882                             }
883                             buffer.append("] DP");
884                             gen.writeln(buffer.toString());
885                             return PathIterator.WIND_NON_ZERO;
886                         }
887
888                         return super.processShape(s);
889                     }
890                 };
891                 g2d.setGraphicContext(new GraphicContext());
892             } catch (IOException e) { }
893
894             return g2d;
895         }
896
897         @Override
898         public void write() throws IOException {
899             if (g2d != null) {
900                 g2d.finish();
901             }
902             if (buffer != null && file != null) {
903                 FileOutputStream fos = new FileOutputStream(file);
904                 buffer.writeTo(fos);
905                 buffer.close();
906                 fos.flush();
907                 fos.close();
908             }
909             if (out != null) {
910                 out.close();
911             }
912         }
913
914         @Override
915         public void dispose() {
916             if (g2d != null) {
917                 g2d.dispose();
918             }
919         }
920     }
921
922     /**
923      * EPS Exporter
924      */
925     private static class EPSExporter extends PSExporter {
926
927         public EPSExporter() { }
928
929         @Override
930         public Graphics2D getGraphics2D(int width, int height, File file, final ExportParams params) {
931             this.file = file;
932             this.params = params;
933             try {
934                 if (file == null) {
935                     buffer = new ByteArrayOutputStream();
936                     out = new BufferedOutputStream(buffer);
937                 } else {
938                     out = new BufferedOutputStream(new FileOutputStream(file));
939                 }
940                 g2d = new EPSDocumentGraphics2D(true) {
941                     @Override
942                     protected void writePageHeader() throws IOException {
943                         super.writePageHeader();
944                         if (params.orientation == ExportParams.LANDSCAPE) {
945                             gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape");
946                         } else {
947                             gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Portrait");
948                         }
949                         gen.writeln("/ReEncode { /MyEncoding exch def exch findfont dup length dict begin {def} forall /Encoding MyEncoding def currentdict end definefont } def");
950                         gen.writeln("/Helvetica /HelveticaLatin1 ISOLatin1Encoding ReEncode");
951                         gen.writeln("/Times /TimesLatin1 ISOLatin1Encoding ReEncode");
952
953                         // DP macro is used to draw an array as a polyline
954                         gen.writeln("/DP {/Points exch def Points 0 get Points 1 get M 2 2 Points length 1 sub {/i exch def Points i get Points i 1 add get L}for} def");
955                     }
956
957                     @Override
958                     public boolean shouldBeClipped(Shape clip, Shape s) {
959                         if (clip == null || s == null) {
960                             return false;
961                         }
962
963                         return clip.getBounds2D().intersects(s.getBounds2D());
964                     }
965
966                     @Override
967                     public void drawString(String s, float x, float y) {
968                         if (s != null && !s.isEmpty()) {
969                             CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder();
970                             if (encoder.canEncode(s)) {
971                                 Font font = getFont();
972                                 boolean sserif = font.getName().equals("SansSerif");
973                                 boolean serif = font.getName().equals("Serif");
974                                 if (sserif || serif) {
975                                     try {
976                                         preparePainting();
977                                         establishColor(getColor());
978                                         gen.writeln((sserif ? "/HelveticaLatin1" : "/TimesLatin1") + " " + gen.formatDouble(getFont().getSize()) + " F");
979
980                                         gen.saveGraphicsState();
981                                         Shape imclip = getClip();
982                                         writeClip(imclip);
983
984                                         AffineTransform trans = getTransform();
985                                         boolean newTransform = gen.getCurrentState().checkTransform(trans) && !trans.isIdentity();
986
987                                         if (newTransform) {
988                                             gen.concatMatrix(trans);
989                                         }
990
991                                         gen.writeln(gen.formatDouble(x)
992                                                     + " " + gen.formatDouble(y)
993                                                     + " M 1 -1 scale");
994
995                                         StringBuffer buf = new StringBuffer("(");
996                                         for (int i = 0; i < s.length(); i++) {
997                                             PSGenerator.escapeChar(s.charAt(i), buf);
998                                         }
999                                         buf.append(") t");
1000
1001                                         gen.writeln(buf.toString());
1002
1003                                         gen.restoreGraphicsState();
1004                                     } catch (IOException e) {
1005                                         System.err.println(e);
1006                                     }
1007
1008                                     return;
1009                                 }
1010                             }
1011
1012                             super.drawString(s, x, y);
1013                         }
1014                     }
1015
1016                     @Override
1017                     public int processShape(Shape s) throws IOException {
1018                         if (s instanceof Ellipse2D.Double) {
1019                             Ellipse2D.Double ell = (Ellipse2D.Double) s;
1020                             if (ell.height == ell.width) {
1021                                 gen.writeln(gen.formatDouble(ell.x + ell.width / 2)
1022                                             + " " + gen.formatDouble(ell.y + ell.height / 2)
1023                                             + " " + gen.formatDouble(ell.width / 2)
1024                                             + " " + gen.formatDouble(0d)
1025                                             + " " + gen.formatDouble(360d)
1026                                             + " arc cp");
1027
1028                                 return PathIterator.WIND_NON_ZERO;
1029                             }
1030                         } else if (s instanceof Path2D) {
1031                             StringBuilder buffer = new StringBuilder();
1032                             double[] coords = new double[6];
1033                             PathIterator it = ((Path2D) s).getPathIterator(new AffineTransform());
1034                             if (!it.isDone()) {
1035                                 int type = it.currentSegment(coords);
1036                                 if (type == PathIterator.SEG_MOVETO) {
1037                                     buffer.append("[").append(gen.formatDouble(coords[0])).append(" ").append(gen.formatDouble(coords[1]));
1038                                     it.next();
1039                                 } else {
1040                                     return super.processShape(s);
1041                                 }
1042                             } else {
1043                                 return super.processShape(s);
1044                             }
1045
1046                             for (; !it.isDone(); it.next()) {
1047                                 int type = it.currentSegment(coords);
1048                                 if (type == PathIterator.SEG_LINETO) {
1049                                     buffer.append(" ").append(gen.formatDouble(coords[0])).append(" ").append(gen.formatDouble(coords[1]));
1050                                 } else {
1051                                     return super.processShape(s);
1052                                 }
1053                             }
1054                             buffer.append("] DP");
1055                             gen.writeln(buffer.toString());
1056                             return PathIterator.WIND_NON_ZERO;
1057                         }
1058
1059                         return super.processShape(s);
1060                     }
1061
1062                 };
1063                 g2d.setupDocument(out, width, height);
1064                 g2d.setGraphicContext(new GraphicContext());
1065             } catch (IOException e) { }
1066
1067             return g2d;
1068         }
1069     }
1070
1071     /**
1072      * EMF Exporter
1073      */
1074     private static class EMFExporter extends Exporter {
1075
1076         private OutputStream out;
1077         private Class<Graphics2D> g2dClass;
1078         private Constructor<Graphics2D> g2dCtor;
1079         private Graphics2D g2d;
1080         private ByteArrayOutputStream buffer;
1081
1082         public EMFExporter() {
1083             try {
1084                 g2dClass = (Class<Graphics2D>) Class.forName("org.freehep.graphicsio.emf.EMFGraphics2D");
1085             } catch (ClassNotFoundException e) {
1086                 throw new RuntimeException("This Scilab build does not provide EMF support");
1087             }
1088
1089             final Constructor[] ctors = g2dClass.getDeclaredConstructors();
1090             Constructor ctor = null;
1091             for (int i = 0; i < ctors.length; i++) {
1092                 ctor = ctors[i];
1093                 final Type[] args = ctor.getGenericParameterTypes();
1094                 if (args.length != 2) {
1095                     continue;
1096                 }
1097                 if (args[0] != OutputStream.class) {
1098                     continue;
1099                 }
1100                 if (args[1] != Dimension.class) {
1101                     continue;
1102                 }
1103
1104                 g2dCtor = ctor;
1105                 break;
1106             }
1107         }
1108
1109         @Override
1110         public Graphics2D getGraphics2D(int width, int height, File file, final ExportParams params) {
1111             this.file = file;
1112             try {
1113                 if (file == null) {
1114                     buffer = new ByteArrayOutputStream();
1115                     out = new BufferedOutputStream(buffer);
1116                 } else {
1117                     out = new BufferedOutputStream(new FileOutputStream(file));
1118                 }
1119                 if (params.orientation == ExportParams.LANDSCAPE) {
1120                     g2d = g2dCtor.newInstance(out, new Dimension(height, width));
1121                     g2dClass.getMethod("startExport").invoke(g2d);
1122                     AffineTransform transf = AffineTransform.getRotateInstance(Math.PI / 2);
1123                     transf.preConcatenate(AffineTransform.getTranslateInstance(height, 0));
1124                     g2d.setTransform(transf);
1125                 } else {
1126                     g2d = g2dCtor.newInstance(out, new Dimension(width, height));
1127                     g2dClass.getMethod("startExport").invoke(g2d);
1128                 }
1129             } catch (IOException e) {
1130             } catch (IllegalAccessException e) {
1131             } catch (IllegalArgumentException e) {
1132             } catch (InvocationTargetException e) {
1133             } catch (NoSuchMethodException e) {
1134             } catch (SecurityException e) {
1135             } catch (InstantiationException e) {
1136             }
1137
1138             return g2d;
1139         }
1140
1141         @Override
1142         public void write() throws IOException {
1143             if (g2d != null) {
1144                 try {
1145                     g2dClass.getMethod("endExport").invoke(g2d);
1146                     g2dClass.getMethod("closeStream").invoke(g2d);
1147                 } catch (IllegalAccessException e) {
1148                 } catch (IllegalArgumentException e) {
1149                 } catch (InvocationTargetException e) {
1150                 } catch (NoSuchMethodException e) {
1151                 } catch (SecurityException e) {
1152                 }
1153             }
1154             if (buffer != null && file != null) {
1155                 FileOutputStream fos = new FileOutputStream(file);
1156                 buffer.writeTo(fos);
1157                 buffer.close();
1158                 fos.flush();
1159                 fos.close();
1160             }
1161             if (out != null) {
1162                 out.close();
1163             }
1164         }
1165
1166         @Override
1167         public void dispose() {
1168             if (g2d != null) {
1169                 g2d.dispose();
1170             }
1171         }
1172     }
1173 }