Debian Codegraph @

freehep-graphicsio-cgm/src/main/java/org/freehep/graphicsio/cgm/CGMGraphics2D.java

raw symbols SCIP
1 // Copyright 2000-2006 FreeHEP
2 package org.freehep.graphicsio.cgm;
3
4 import java.awt.BasicStroke;
5 import java.awt.Color;
6 import java.awt.Component;
7 import java.awt.Dimension;
8 import java.awt.Font;
9 import java.awt.GradientPaint;
10 import java.awt.Graphics;
11 import java.awt.GraphicsConfiguration;
12 import java.awt.Paint;
13 import java.awt.Point;
14 import java.awt.Rectangle;
15 import java.awt.Shape;
16 import java.awt.TexturePaint;
17 import java.awt.geom.AffineTransform;
18 import java.awt.geom.Point2D;
19 import java.awt.geom.Rectangle2D;
20 import java.awt.image.ColorModel;
21 import java.awt.image.Raster;
22 import java.awt.image.RenderedImage;
23 import java.io.BufferedOutputStream;
24 import java.io.BufferedWriter;
25 import java.io.File;
26 import java.io.FileNotFoundException;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.io.OutputStream;
30 import java.io.OutputStreamWriter;
31 import java.text.SimpleDateFormat;
32 import java.util.Date;
33 import java.util.Properties;
34
35 import org.freehep.graphics2d.PrintColor;
36 import org.freehep.graphics2d.VectorGraphics;
37 import org.freehep.graphicsio.AbstractVectorGraphicsIO;
38 import org.freehep.graphicsio.PageConstants;
39 import org.freehep.util.UserProperties;
40 import org.freehep.util.io.TaggedOutput;
41
42 /**
43 * Implementation of <tt>VectorGraphics</tt> that writes the output to a CGM
44 * file. Users of this class have to generate a <tt>TagWriter</tt> and create
45 * an instance by invoking the factory method or the constructor. Document
46 * specific settings like page size can then be made by the appropriate setter
47 * methods. Before starting to draw, <tt>startExport()</tt> must be called.
48 * When drawing is finished, call <tt>endExport()</tt>.
49 *
50 * @author Mark Donszelmann
51 * @author Ian Graham - fixed constructor bug, added writeImage for raster
52 * support, and refactored for reuse
53 * @version $Id: freehep-graphicsio-cgm/src/main/java/org/freehep/graphicsio/cgm/CGMGraphics2D.java d9a2ef8950b1 2006/03/03 19:08:18 duns $
54 */
55 public class CGMGraphics2D extends AbstractVectorGraphicsIO {
56
57 /*
58 * ================================================================================
59 * Table of Contents: ------------------ 1. Constructors & Factory Methods
60 * 2. Document Settings 3. Header, Trailer, Multipage & Comments 3.1 Header &
61 * Trailer 3.3 comments 4. Create 5. Drawing Methods 5.1. shapes (draw/fill)
62 * 5.1.1. lines, rectangles, round rectangles 5.1.2. polylines, polygons
63 * 5.1.3. ovals, arcs 5.1.4. shapes 5.2. Images 5.3. Strings 6.
64 * Transformations 7. Clipping 8. Graphics State / Settings 8.1.
65 * stroke/linewidth 8.2. paint/color 8.3. font 8.4. rendering hints 9.
66 * Private/Utility Methos 9.1. drawing, shape creation 9.2. font, strings
67 * 9.3. images 9.4. transformations 11. Todo List
68 * ================================================================================
69 */
70
71 private static final String rootKey = CGMGraphics2D.class.getName();
72
73 private static final Color DEFAULT_TRANSPARENT_CELL_COLOR = new Color(1, 2,
74 3); // unlikely in real use
75
76 public static final String BACKGROUND = rootKey + "."
77 + PageConstants.BACKGROUND;
78
79 public static final String BACKGROUND_COLOR = rootKey + "."
80 + PageConstants.BACKGROUND_COLOR;
81
82 public static final String BINARY = rootKey + ".Binary";
83
84 public static final String AUTHOR = rootKey + ".Author";
85
86 public static final String TITLE = rootKey + ".Title";
87
88 public static final String SUBJECT = rootKey + ".Subject";
89
90 public static final String KEYWORDS = rootKey + ".Keywords";
91
92 private static final UserProperties defaultProperties = new UserProperties();
93 static {
94 defaultProperties.setProperty(BACKGROUND, false);
95 defaultProperties.setProperty(BACKGROUND_COLOR, Color.GRAY);
96
97 defaultProperties.setProperty(BINARY, true);
98 defaultProperties.setProperty(AUTHOR, "");
99 defaultProperties.setProperty(TITLE, "");
100 defaultProperties.setProperty(SUBJECT, "");
101 defaultProperties.setProperty(KEYWORDS, "");
102 }
103
104 public static Properties getDefaultProperties() {
105 return defaultProperties;
106 }
107
108 public static void setDefaultProperties(Properties newProperties) {
109 defaultProperties.setProperties(newProperties);
110 }
111
112 public final static String version = "$Revision$";
113
114 private static final int CGM_VERSION = 3;
115
116 private static final double FONTSIZE_CORRECTION = 0.8;
117
118 private static final String[] STANDARD_FONT = { "Courier", "Courier-Bold",
119 "Courier-Italic", "Courier-BoldItalic", "Helvetica",
120 "Helvetica-Bold", "Helvetica-Italic", "Helvetica-BoldItalic",
121 "TimesRoman", "TimesRoman-Bold", "TimesRoman-Italic",
122 "TimesRoman-BoldItalic", "Symbol", "ZapfDingbats" };
123
124 // output
125 private OutputStream ros;
126
127 private TaggedOutput os;
128
129 private Color transparentCellColor = null;
130
131 /*
132 * ================================================================================ |
133 * 1. Constructors & Factory Methods
134 * ================================================================================
135 */
136
137 public CGMGraphics2D(File file, Dimension size)
138 throws FileNotFoundException {
139 this(new FileOutputStream(file), size);
140 }
141
142 public CGMGraphics2D(File file, Component component)
143 throws FileNotFoundException {
144 this(new FileOutputStream(file), component);
145 }
146
147 public CGMGraphics2D(OutputStream os, Dimension size) {
148 super(size, false);
149 init(os);
150 }
151
152 public CGMGraphics2D(OutputStream os, Component component) {
153 super(component, false);
154 init(os);
155 }
156
157 private void init(OutputStream os) {
158 this.ros = os;
159 initProperties(defaultProperties);
160 }
161
162 /** Cloneconstructor */
163 protected CGMGraphics2D(CGMGraphics2D graphics) {
164 super(graphics, false);
165
166 os = graphics.os;
167 transparentCellColor = graphics.transparentCellColor;
168 }
169
170 /*
171 * ================================================================================ |
172 * 2. Document Settings
173 * ================================================================================
174 */
175
176 /*
177 * ================================================================================ |
178 * 3. Header, Trailer, Multipage & Comments
179 * ================================================================================
180 */
181
182 /*--------------------------------------------------------------------------------
183 | 3.1 Header & Trailer
184 *--------------------------------------------------------------------------------*/
185
186 /**
187 * Writes the catalog, docinfo, preferences, and (as we use only single page
188 * output the page tree. Written as a template method to enable reuse.
189 */
190 public void writeHeader() throws IOException {
191 if (isProperty(BINARY)) {
192 os = new CGMOutputStream(new BufferedOutputStream(ros), CGM_VERSION);
193 ((CGMOutputStream) os).setRealPrecision(false, true);
194 } else {
195 os = new CGMWriter(new BufferedWriter(new OutputStreamWriter(ros)),
196 CGM_VERSION);
197 ((CGMWriter) os).setRealPrecision(false, true);
198 }
199
200 os.writeTag(new BeginMetafile(
201 "Generated by CGMGraphics2D, FreeHEP Graphics2D Driver"));
202 writeMetafileDescriptor();
203
204 os.writeTag(new BeginPicture("Picture"));
205 writePictureDescriptor();
206
207 writeBeginningOfPictureBody();
208
209 // FIXME
210 if (getClip() != null) {
211 setClip(getClip());
212 }
213 }
214
215 protected void writeMetafileDescriptor() throws IOException {
216 String producer = getClass().getName();
217 if (!isDeviceIndependent()) {
218 producer += " " + version.substring(1, version.length() - 1);
219 }
220 os.writeTag(new MetafileVersion(CGM_VERSION));
221 os.writeTag(new MetafileDescription("Producer: " + producer));
222 os.writeTag(new MetafileDescription("Creator: " + getCreator()));
223 // info
224 os.writeTag(new MetafileDescription("Title: " + getProperty(TITLE)));
225 os.writeTag(new MetafileDescription("Author: " + getProperty(AUTHOR)));
226 os
227 .writeTag(new MetafileDescription("Subject: "
228 + getProperty(SUBJECT)));
229 os.writeTag(new MetafileDescription("Info: " + getProperty(KEYWORDS)));
230
231 if (!isDeviceIndependent()) {
232 os.writeTag(new MetafileDescription("CreationDate: "
233 + (new SimpleDateFormat().format(new Date()))));
234 }
235 os.writeTag(new MetafileElementList(MetafileElementList.VERSION_3_SET));
236 os.writeTag(new VDCType(VDCType.REAL));
237 // os.writeTag(new VDCRealPrecision()); // PowerPoint 10 does not accept
238 os.writeTag(new FontList(STANDARD_FONT));
239 os.writeTag(new ClipIndicator(true));
240 }
241
242 protected void writePictureDescriptor() throws IOException {
243 os.writeTag(new ColorSelectionMode(ColorSelectionMode.DIRECT));
244 os.writeTag(new EdgeWidthSpecificationMode(
245 EdgeWidthSpecificationMode.ABSOLUTE));
246 os.writeTag(new LineWidthSpecificationMode(
247 LineWidthSpecificationMode.ABSOLUTE));
248 Dimension size = getSize();
249 os.writeTag(new VDCExtent(new Point2D.Double(0, size.height),
250 new Point2D.Double(size.width, 0)));
251 }
252
253 protected void writeBeginningOfPictureBody() throws IOException {
254 setTransparentCellColor(DEFAULT_TRANSPARENT_CELL_COLOR);
255 os.writeTag(new BeginPictureBody());
256 os.writeTag(new EdgeVisibility(false));
257 os.writeTag(new EdgeCap(EdgeCap.BUTT));
258 os.writeTag(new LineCap(LineCap.BUTT));
259 os.writeTag(new EdgeColor(Color.black));
260 os.writeTag(new FillColor(Color.black));
261 os.writeTag(new LineColor(Color.black));
262 os.writeTag(new TextColor(Color.black));
263 // os.writeTag(new TransparentCellColour(true, new Color(0, 0, 0)));
264 os.writeTag(new EdgeJoin(EdgeJoin.MITRE));
265 os.writeTag(new LineJoin(LineJoin.MITRE));
266 os.writeTag(new EdgeType(EdgeType.SOLID));
267 os.writeTag(new LineType(LineType.SOLID));
268 os.writeTag(new EdgeWidth(1));
269 os.writeTag(new LineWidth(1));
270 os.writeTag(new InteriorStyle(InteriorStyle.SOLID));
271 os.writeTag(new CharacterHeight(getFont().getSize()));
272 os.writeTag(new TextFontIndex(fontIndex(getFont())));
273 }
274
275 public void writeBackground() throws IOException {
276 // since CGM is non-transparent, write current background
277 if (isProperty(BACKGROUND)) {
278 setBackground(getPropertyColor(BACKGROUND_COLOR));
279 } else {
280 setBackground(getComponent() != null ? getComponent()
281 .getBackground() : Color.WHITE);
282 }
283 clearRect(0.0, 0.0, getSize().width, getSize().height);
284 }
285
286 public void writeTrailer() throws IOException {
287 os.writeTag(new EndPicture());
288 os.writeTag(new EndMetafile());
289 }
290
291 public void closeStream() throws IOException {
292 os.close();
293 }
294
295 /*
296 * ================================================================================ |
297 * 4. Create
298 * ================================================================================
299 */
300
301 public Graphics create() {
302 try {
303 writeGraphicsSave();
304 } catch (IOException e) {
305 handleException(e);
306 }
307 return new CGMGraphics2D(this);
308 }
309
310 public Graphics create(double x, double y, double width, double height) {
311 try {
312 writeGraphicsSave();
313 } catch (IOException e) {
314 handleException(e);
315 }
316 VectorGraphics graphics = new CGMGraphics2D(this);
317 graphics.translate(x, y);
318 graphics.clipRect(0, 0, width, height);
319 return graphics;
320 }
321
322 protected void writeGraphicsSave() throws IOException {
323 // not applicable
324 }
325
326 protected void writeGraphicsRestore() throws IOException {
327 // not applicable
328 }
329
330 /*
331 * ================================================================================ |
332 * 5. Drawing Methods
333 * ================================================================================
334 */
335 /* 5.1.4. shapes */
336 public void draw(Shape s) {
337 try {
338 if (getStroke() instanceof BasicStroke) {
339 // in this case we've already handled the stroke
340 drawPath(s, false);
341 } else {
342 // otherwise handle it now
343 drawPath(getStroke().createStrokedShape(s), true);
344 }
345 } catch (IOException e) {
346 handleException(e);
347 }
348 }
349
350 public void fill(Shape s) {
351 try {
352 drawPath(s, true);
353 } catch (IOException e) {
354 handleException(e);
355 }
356 }
357
358 // TODO: Does not use current stroke yet
359 public void fillAndDraw(Shape s, Color fillColor) {
360 try {
361 setNonStrokeColor(fillColor);
362 drawPath(s, true);
363 setNonStrokeColor(getColor());
364 drawPath(s, false);
365 } catch (IOException e) {
366 handleException(e);
367 }
368 }
369
370 private void drawPath(Shape s, boolean fill) throws IOException {
371 // use a resolution compatible with the current transform
372 AffineTransform t = getTransform();
373 double resolution = 0.5 / (20 * Math.min(t.getScaleX(), t.getScaleY()));
374
375 CGMPathConstructor path = new CGMPathConstructor(os, fill,
376 getTransform(), resolution);
377 boolean eo = path.addPath(s);
378 path.writePolyline();
379 if (!eo) {
380 writeWarning(getClass()
381 + ": cannot fill using non-zero winding rule.");
382 }
383 }
384
385 /* 5.2. Images */
386 public void copyArea(int x, int y, int width, int height, int dx, int dy) {
387 writeWarning(getClass()
388 + ": copyArea(int, int, int, int, int, int) not implemented.");
389 }
390
391 protected void writeImage(RenderedImage image, AffineTransform xform,
392 Color bkg) throws IOException {
393
394 int originX = image.getMinX();
395 int originY = image.getMinY();
396 int width = image.getWidth();
397 int height = image.getHeight();
398 Point untransformedP = new Point(originX, originY);
399 Point untransformedQ = new Point(originX + width, originY + height);
400 Point untransformedR = new Point(originX + width, 0);
401 AffineTransform compoundTransform = getTransform();
402 compoundTransform.concatenate(xform);
403 Point2D p = compoundTransform.transform(untransformedP, null);
404 Point2D q = compoundTransform.transform(untransformedQ, null);
405 Point2D r = compoundTransform.transform(untransformedR, null);
406
407 ColorModel colorModel = image.getColorModel();
408 Raster raster = image.getData();
409 Object currentDataElements = null;
410 Color[][] colorArray = new Color[height][width];
411 for (int xIndex = 0; xIndex < width; xIndex++) {
412 for (int yIndex = 0; yIndex < height; yIndex++) {
413 Color color;
414 currentDataElements = raster.getDataElements(xIndex, yIndex,
415 currentDataElements);
416 int alphaComponent = colorModel.getAlpha(currentDataElements);
417 if (alphaComponent > 0 || transparentCellColor == null) {
418 int redComponent = colorModel.getRed(currentDataElements);
419 int greenComponent = colorModel
420 .getGreen(currentDataElements);
421 int blueComponent = colorModel.getBlue(currentDataElements);
422 color = new Color(redComponent, greenComponent,
423 blueComponent, alphaComponent);
424 } else {
425 color = transparentCellColor;
426 }
427 colorArray[yIndex][xIndex] = color;
428 }
429 }
430
431 CellArray cgmCellArray = new CellArray(p, q, r, colorArray);
432 os.writeTag(cgmCellArray);
433 }
434
435 /* 5.3. Strings */
436 protected void writeString(String str, double x, double y)
437 throws IOException {
438 Point2D point = new Point2D.Double(x, y);
439 AffineTransform currentTransform = new AffineTransform(getTransform());
440 currentTransform.concatenate(getFont().getTransform());
441 os.writeTag(new CharacterOrientation(-currentTransform.getShearX(),
442 -currentTransform.getScaleY(), currentTransform.getScaleX(),
443 currentTransform.getShearY()));
444 os.writeTag(new Text(currentTransform.transform(point, point), str));
445 }
446
447 /*
448 * ================================================================================ |
449 * 6. Transformations
450 * ================================================================================
451 */
452 protected void writeTransform(AffineTransform t) throws IOException {
453 // ignored, coordinates are pre-calculated before written to CGM
454 }
455
456 protected void writeSetTransform(AffineTransform t) throws IOException {
457 // ignored, coordinates are pre-calculated before written to CGM
458 }
459
460 /*
461 * ================================================================================ |
462 * 7. Clipping
463 * ================================================================================
464 */
465 protected void writeClip(Shape s) throws IOException {
466 if (s instanceof Rectangle2D) {
467 AffineTransform currentTransform = getTransform();
468 Point2D xy = currentTransform.transform(
469 new Point2D.Double(
470 ((Rectangle2D)s).getX(),
471 ((Rectangle2D)s).getY()), null);
472 Point2D wh = currentTransform.deltaTransform(
473 new Point2D.Double(
474 ((Rectangle2D)s).getWidth(),
475 ((Rectangle2D)s).getHeight()), null);
476
477 os.writeTag(
478 new ClipRectangle(
479 new Rectangle2D.Double(
480 xy.getX(),
481 xy.getY(),
482 wh.getX(),
483 wh.getY())));
484 } else {
485 writeWarning(getClass()+": writeClip(Shape) not implemented.");
486 }
487 }
488
489
490
491 protected void writeSetClip(Shape s) throws IOException {
492 writeWarning(getClass()+": writeSetClip(Shape) not implemented.");
493 }
494
495 /*
496 * ================================================================================ |
497 * 8. Graphics State
498 * ================================================================================
499 */
500 /* 8.1. stroke/linewidth */
501 protected void writeWidth(float width) throws IOException {
502 os.writeTag(new EdgeWidth(width));
503 os.writeTag(new LineWidth(width));
504 }
505
506 protected void writeCap(int cap) throws IOException {
507 switch (cap) {
508 case BasicStroke.CAP_BUTT:
509 os.writeTag(new EdgeCap(EdgeCap.BUTT));
510 os.writeTag(new LineCap(LineCap.BUTT));
511 break;
512 case BasicStroke.CAP_ROUND:
513 os.writeTag(new EdgeCap(EdgeCap.ROUND));
514 os.writeTag(new LineCap(LineCap.ROUND));
515 break;
516 case BasicStroke.CAP_SQUARE:
517 os.writeTag(new EdgeCap(EdgeCap.SQUARE));
518 os.writeTag(new LineCap(LineCap.SQUARE));
519 break;
520 }
521 }
522
523 protected void writeJoin(int join) throws IOException {
524 switch (join) {
525 default:
526 case BasicStroke.JOIN_MITER:
527 os.writeTag(new EdgeJoin(EdgeJoin.MITRE));
528 os.writeTag(new LineJoin(LineJoin.MITRE));
529 break;
530 case BasicStroke.JOIN_ROUND:
531 os.writeTag(new EdgeJoin(EdgeJoin.ROUND));
532 os.writeTag(new LineJoin(LineJoin.ROUND));
533 break;
534 case BasicStroke.JOIN_BEVEL:
535 os.writeTag(new EdgeJoin(EdgeJoin.BEVEL));
536 os.writeTag(new LineJoin(LineJoin.BEVEL));
537 break;
538 }
539 }
540
541 protected void writeMiterLimit(float limit) throws IOException {
542 os.writeTag(new MitreLimit(limit));
543 }
544
545 protected void writeDash(float[] dash, float phase) throws IOException {
546 // NOTE: patterns are ignored, a guess is made
547 switch (dash.length) {
548 case 0:
549 os.writeTag(new EdgeType(EdgeType.SOLID));
550 os.writeTag(new LineType(LineType.SOLID));
551 break;
552 default:
553 case 1:
554 os.writeTag(new EdgeType(EdgeType.DASH));
555 os.writeTag(new LineType(LineType.DASH));
556 break;
557 case 2:
558 os.writeTag(new EdgeType(EdgeType.DOT));
559 os.writeTag(new LineType(LineType.DOT));
560 break;
561 case 3:
562 os.writeTag(new EdgeType(EdgeType.DASH_DOT));
563 os.writeTag(new LineType(LineType.DASH_DOT));
564 break;
565 case 4:
566 os.writeTag(new EdgeType(EdgeType.DASH_DOT_DOT));
567 os.writeTag(new LineType(LineType.DASH_DOT_DOT));
568 break;
569 }
570 }
571
572 /* 8.2. paint/color */
573 public void setPaintMode() {
574 writeWarning(getClass() + ": setPaintMode() not implemented.");
575 }
576
577 public void setXORMode(Color c1) {
578 writeWarning(getClass() + ": setXORMode(Color) not implemented.");
579 }
580
581 public void setTransparentCellColor(Color color) throws IOException {
582 if (color != null) {
583 os.writeTag(new TransparentCellColour(true, color));
584 } else {
585 os.writeTag(new TransparentCellColour(false, null));
586 }
587 transparentCellColor = color;
588 }
589
590 protected void writePaint(Color c) throws IOException {
591 os.writeTag(new LineColor(c));
592 os.writeTag(new EdgeColor(c));
593 os.writeTag(new FillColor(c));
594 os.writeTag(new TextColor(c));
595 }
596
597 protected void writePaint(GradientPaint paint) throws IOException {
598 // NOTE: CGM does not support gradients, so we average the colors
599 setColor(PrintColor.mixColor(paint.getColor1(), paint.getColor2()));
600 }
601
602 protected void writePaint(TexturePaint p) throws IOException {
603 writeWarning(getClass() + ": writePaint(TexturePaint) not implemented.");
604 }
605
606 protected void writePaint(Paint p) throws IOException {
607 writeWarning(getClass() + ": writePaint(Paint) not implemented for "
608 + p.getClass());
609 }
610
611 /* 8.3. font */
612 protected void writeFont(Font font) throws IOException {
613 os.writeTag(new TextFontIndex(fontIndex(font)));
614 os.writeTag(new CharacterHeight(font.getSize() * FONTSIZE_CORRECTION));
615 }
616
617 /*
618 * ================================================================================ |
619 * 9. Auxiliary
620 * ================================================================================
621 */
622 public GraphicsConfiguration getDeviceConfiguration() {
623 writeWarning(getClass() + ": getDeviceConfiguration() not implemented.");
624 return null;
625 }
626
627 public boolean hit(Rectangle rect, Shape s, boolean onStroke) {
628 writeWarning(getClass()
629 + ": hit(Rectangle, Shape, boolean) not implemented.");
630 return false;
631 }
632
633 public void writeComment(String comment) throws IOException {
634 // comments are ignored and disabled, because they confuse compressed
635 // streams
636 }
637
638 public String toString() {
639 return "CGMGraphics2D";
640 }
641
642 /*
643 * ================================================================================ |
644 * 10. Private/Utility Methos
645 * ================================================================================
646 */
647 private static int fontIndex(Font font) {
648 StringBuffer fontName = new StringBuffer(font.getName());
649 if (font.isBold() || font.isItalic())
650 fontName.append("-");
651 if (font.isBold())
652 fontName.append("Bold");
653 if (font.isItalic())
654 fontName.append("Italic");
655 String name = fontName.toString();
656 for (int i = 0; i < STANDARD_FONT.length; i++) {
657 if (name.equals(STANDARD_FONT[i]))
658 return i + 1;
659 }
660 return 5; // Helvetica
661 }
662
663 private void setNonStrokeColor(Color c) throws IOException {
664 os.writeTag(new FillColor(getPrintColor(c)));
665 }
666
667 // private void setStrokeColor(Color c) throws IOException {
668 // os.writeTag(new LineColor(getPrintColor(c)));
669 // }
670
671 /**
672 * Return the tagged output stream to which to write tags.
673 *
674 * @return TaggedOutput
675 */
676 protected TaggedOutput getTaggedOutput() {
677 return os;
678 }
679
680 }