Debian Codegraph @

freehep-graphicsio-latex/src/main/java/org/freehep/graphicsio/latex/LatexGraphics2D.java

raw symbols SCIP
1 // Copyright 2004-2006, FreeHEP
2 package org.freehep.graphicsio.latex;
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.Rectangle;
14 import java.awt.Shape;
15 import java.awt.TexturePaint;
16 import java.awt.geom.AffineTransform;
17 import java.awt.image.RenderedImage;
18 import java.io.File;
19 import java.io.FileNotFoundException;
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.io.OutputStream;
23 import java.io.PrintStream;
24
25 import org.freehep.graphicsio.AbstractVectorGraphicsIO;
26 import org.freehep.util.ScientificFormat;
27
28 /**
29 * @author Andre Bach
30 * @author Mark Donszelmann
31 * @version $Id: freehep-graphicsio-latex/src/main/java/org/freehep/graphicsio/latex/LatexGraphics2D.java cba39eb5843a 2006/03/20 18:04:28 duns $
32 */
33 public class LatexGraphics2D extends AbstractVectorGraphicsIO {
34 /*
35 * ================================================================================
36 * Table of Contents: ------------------ 1. Constructors & Factory Methods
37 * 2. Document Settings 3. Header, Trailer, Multipage & Comments 3.1 Header &
38 * Trailer 3.2 MultipageDocument methods 4. Create & Dispose 5. Drawing
39 * Methods 5.1. shapes (draw/fill) 5.1.1. lines, rectangles, round
40 * rectangles 5.1.2. polylines, polygons 5.1.3. ovals, arcs 5.1.4. shapes
41 * 5.2. Images 5.3. Strings 6. Transformations 7. Clipping 8. Graphics State /
42 * Settings 8.1. stroke/linewidth 8.2. paint/color 8.3. font 8.4. rendering
43 * hints 9. Auxiliary 10. Private/Utility Methos
44 * ================================================================================
45 */
46
47 private PrintStream ps;
48
49 private AffineTransform pageTrans = new AffineTransform();
50
51 private double componentHeight;
52
53 private static double pageHeight;
54
55 private static double pageWidth;
56
57 private int numberClips = 0;
58
59 private float width = 1.f;
60
61 private float[] dash;
62
63 private Color savedColor;
64
65 private float savedWidth;
66
67 private float[] savedDash;
68
69 /*
70 * ================================================================================
71 * 1. Constructors & Factory Methods
72 * ================================================================================
73 */
74 public LatexGraphics2D(File file, Dimension size)
75 throws FileNotFoundException {
76 this(new FileOutputStream(file), size, true);
77 }
78
79 public LatexGraphics2D(File file, Component component)
80 throws FileNotFoundException {
81 this(new FileOutputStream(file), component, true);
82 }
83
84 public LatexGraphics2D(OutputStream os, Component component,
85 boolean doRestoreOnDispose) {
86 super(component, doRestoreOnDispose);
87 init(os);
88 componentHeight = component.getSize().getHeight();
89 pageWidth = component.getSize().getWidth();
90 }
91
92 public LatexGraphics2D(OutputStream os, Dimension size,
93 boolean doRestoreOnDispose) {
94 super(size, doRestoreOnDispose);
95 init(os);
96 }
97
98 private void init(OutputStream os) {
99 ps = new PrintStream(os);
100 }
101
102 protected LatexGraphics2D(LatexGraphics2D graphics,
103 boolean doRestoreOnDispose) {
104 super(graphics, doRestoreOnDispose);
105 ps = graphics.ps;
106 }
107
108 /*
109 * ================================================================================ |
110 * 2. Document Settings
111 * ================================================================================
112 */
113
114 /*
115 * ================================================================================ |
116 * 3. Header, Trailer, Multipage & Comments
117 * ================================================================================
118 */
119 /* 3.1 Header & Trailer */
120 public void writeHeader() throws IOException {
121 ps.println("\\documentclass{article}");
122 ps.println("\\usepackage[noxcolor]{pstricks}");
123 ps.println("\\usepackage{pst-grad}");
124 ps.println("\\pagestyle{empty}");
125 ps.println("\\begin{document}");
126 ps.println("\\begin{pspicture}(5,20)(15,15)");
127 ps.println("\\psset{unit=1pt}"); // One thing that should be changed
128 // for scaling.
129
130 ps.println("% componentHeight = " + componentHeight);
131 ps.println("% pageWidth = " + pageWidth);
132 ps.println("% pageHeight = " + pageHeight);
133 pageHeight = componentHeight;
134 ps.println("% pageHeight = " + pageHeight);
135 pageTrans.scale(1, -1);
136 pageTrans.translate(0, -pageHeight);
137 transform(pageTrans);
138 }
139
140 public void writeBackground() throws IOException {
141 // writeWarning(getClass()+": writeBackground() not implemented.");
142 // Write out the background to the output stream.
143 ps.println("% writeBackground() called");
144 }
145
146 public void writeTrailer() throws IOException {
147 ps.println("\\end{pspicture}");
148 ps.println("\\end{document}");
149 }
150
151 public void closeStream() throws IOException {
152 ps.close();
153 }
154
155 /* 3.2 MultipageDocument methods */
156
157 /*
158 * ================================================================================
159 * 4. Create & Dispose
160 * ================================================================================
161 */
162
163 public Graphics create() {
164 ps.println("% create() called");
165 LatexGraphics2D g = new LatexGraphics2D(this, true);
166 try {
167 g.writeGraphicsSave(getColor(), width, dash);
168 } catch (IOException e) {
169 handleException(e);
170 }
171 return g;
172 }
173
174 public Graphics create(double x, double y, double width, double height) {
175 ps.println("% create(x,y,width,height) called");
176 ps.println("% x = " + x);
177 ps.println("% y = " + y);
178 ps.println("% width = " + width);
179 ps.println("% height = " + height);
180 LatexGraphics2D g = new LatexGraphics2D(this, true);
181 try {
182 g.writeGraphicsSave(getColor(), width, dash);
183 } catch (IOException e) {
184 handleException(e);
185 }
186 g.clipRect(x, y, width, height);
187 return g;
188 }
189
190 protected void writeGraphicsSave(Color c, double w, float[] d)
191 throws IOException {
192 savedColor = c;
193 savedWidth = (float) w;
194 savedDash = d;
195 }
196
197 protected void writeGraphicsSave() throws IOException {
198 }
199
200 protected void writeGraphicsRestore() throws IOException {
201 while (numberClips > 0) {
202 ps.println("\\endpsclip");
203 numberClips--;
204 }
205 // If the current color was written inside a clip statement, it will not
206 // be
207 // remembered outside of it, so the restore must always be written.
208 if (/* savedColor != getColor() && */savedColor != null)
209 writePaint(savedColor);
210 /* if (savedWidth != width) */writeWidth(savedWidth);
211 /* if (savedDash != dash) */writeDash(savedDash, 0.0f);
212 }
213
214 /*
215 * ================================================================================ |
216 * 5. Drawing Methods
217 * ================================================================================
218 */
219 /* 5.1.4. shapes */
220
221 public void draw(Shape shape) {
222 LatexPathConstructor pc = new LatexPathConstructor(ps);
223 try {
224 if (getStroke() instanceof BasicStroke) {
225 ps.println("\\pscustom[fillstyle=none]{");
226 pc.addPath(shape, getTransform());
227 ps.println("}");
228 } else {
229 ps.println("\\pscustom[linestyle=none]{");
230 pc.addPath(getStroke().createStrokedShape(shape), getTransform());
231 ps.println("}");
232 }
233 } catch (IOException e) {
234 handleException(e);
235 }
236 }
237
238 public void fill(Shape shape) {
239 LatexPathConstructor pc = new LatexPathConstructor(ps);
240 try {
241 ps.println("\\pscustom[linestyle=none]{");
242 pc.addPath(shape, getTransform());
243 ps.println("}");
244 } catch (IOException e) {
245 handleException(e);
246 }
247 }
248
249 public void fillAndDraw(Shape shape, Color fillColor) {
250 LatexPathConstructor pc = new LatexPathConstructor(ps);
251 try {
252 ps.println("\\newrgbcolor{colorfill}{"
253 + fixedPrecision(fillColor.getRed() / 255.) + " "
254 + fixedPrecision(fillColor.getGreen() / 255.) + " "
255 + fixedPrecision(fillColor.getBlue() / 255.) + "}");
256 ps
257 .println("\\pscustom[fillstyle=solid,fillcolor=colorfill,linecolor=current]{");
258 pc.addPath(shape, getTransform());
259 ps.println("}");
260 } catch (IOException e) {
261 handleException(e);
262 }
263 }
264
265 /* 5.2. Images */
266 public void copyArea(int x, int y, int width, int height, int dx, int dy) {
267 // Mostly unimplemented.
268 ps.println("% copyArea(x,y,width,height,dx,dy) called");
269 }
270
271 protected void writeImage(RenderedImage image, AffineTransform xform,
272 Color bkg) throws IOException {
273 // writeWarning(getClass()+": writeImage(RenderedImage, AffineTransform,
274 // Color) not implemented.");
275 // Write out the image.
276 ps.println("% writeImage(image,xform,bkg) called");
277 }
278
279 /* 5.3. Strings */
280 protected void writeString(String str, double x, double y)
281 throws IOException {
282 ps.println("% string componentHeight = " + componentHeight);
283 ps.println("% string pageHeight = " + pageHeight);
284 y = -y + pageHeight;
285
286 ps.print("\\put(" + fixedPrecision(x) + "," + fixedPrecision(y) + "){");
287 ps.print("\\fontsize{" + getFont().getSize() + "}{"
288 + fixedPrecision(1.2 * getFont().getSize()) + "}");
289 ps.print("\\textcolor{current}{");
290
291 if (getFont().getFamily().equals("Serif"))
292 ps.print("\\rmfamily ");
293 if (getFont().getFamily().equals("SansSerif"))
294 ps.print("\\sffamily ");
295 if (getFont().getFamily().equals("Monospaced"))
296 ps.print("\\ttfamily ");
297
298 switch (getFont().getStyle()) {
299 case 0:
300 ps.print("\\upshape ");
301 break;
302 case 1:
303 ps.print("\\bfseries ");
304 break;
305 case 2:
306 ps.print("\\itshape ");
307 break;
308 case 3:
309 ps.print("\\bfseries \\itshape ");
310 break;
311 default:
312 }
313
314 ps.println(fixString(str) + "}}");
315 }
316
317 // Certain chars can only be printed in the LaTeX math environment, or
318 // are commands and must be preceded by a backslash.
319 protected String fixString(String str) {
320 StringBuffer buffer = new StringBuffer(str);
321 for (int i = 0; i < buffer.length(); i++) {
322 switch (buffer.charAt(i)) {
323 default:
324 break;
325 case '{':
326 case '}':
327 case '#':
328 case '%':
329 case '&':
330 case '$':
331 case '_':
332 buffer.insert(i, '\\');
333 i++;
334 break;
335 case '<':
336 case '>':
337 buffer.insert(i, '$');
338 buffer.insert((i + 2), '$');
339 i += 2;
340 break;
341 case '\\':
342 buffer.delete(i, (i + 1));
343 buffer.insert(i, "$\\backslash$");
344 i += 11;
345 break;
346 }
347 }
348 return buffer.toString();
349 }
350
351 /*
352 * ================================================================================ |
353 * 6. Transformations
354 * ================================================================================
355 */
356
357 protected void writeTransform(AffineTransform t) throws IOException {
358 // Ignored, transforms are pre-calculated before written to LaTeX.
359 }
360
361 protected void writeSetTransform(AffineTransform t) throws IOException {
362 // Ignored, transforms are pre-calculated before written to LaTeX.
363 }
364
365 /*
366 * ================================================================================ |
367 * 7. Clipping
368 * ================================================================================
369 */
370 protected void writeClip(Shape s) throws IOException {
371 if (s == null || !isProperty(CLIP)) {
372 return;
373 }
374
375 ps.println("\\psclip{");
376 LatexPathConstructor pc = new LatexPathConstructor(ps);
377 try {
378 ps.println("\\pscustom[linestyle=none,fillstyle=none]{");
379 pc.addPath(s, getTransform());
380 ps.println("}");
381 } catch (IOException e) {
382 handleException(e);
383 }
384 ps.println("}");
385 numberClips++;
386 }
387
388 protected void writeSetClip(Shape s) throws IOException {
389 // clear existing clips
390 while (numberClips > 0) {
391 ps.println("\\endpsclip");
392 numberClips--;
393 }
394
395 writeClip(s);
396 }
397
398 /*
399 * ================================================================================ |
400 * 8. Graphics State
401 * ================================================================================
402 */
403 /* 8.1. stroke/linewidth */
404 protected void writeWidth(float width) throws IOException {
405 ps.println("\\psset{linewidth=" + width + "}");
406 this.width = width;
407 }
408
409 protected void writeCap(int cap) throws IOException {
410 // Not supported in LaTeX PSTricks when using lineto.
411 ps.println("% writeCap(int cap) called, not supported");
412 /*
413 * switch (cap) { case 0: ps.println("\\psset{arrows=-}"); break; case
414 * 1: ps.println("\\psset{arrows=c-c}"); break; case 2:
415 * ps.println("\\psset{arrows=C-C}"); break; default: }
416 */
417 }
418
419 protected void writeJoin(int join) throws IOException {
420 // Not supported in LaTeX PSTricks.
421 ps.println("% writeJoin(int join) called, not supported");
422 }
423
424 protected void writeMiterLimit(float limit) throws IOException {
425 // Not supported in LaTeX PSTricks.
426 ps.println("% writeMiterLimit(float limit) called, not supported");
427 }
428
429 protected void writeDash(float[] dash, float phase) throws IOException {
430 this.dash = dash;
431 if (dash == null || dash.length == 0) {
432 ps.println("\\psset{linestyle=solid}");
433 return;
434 }
435
436 // Dotted lines must be dealt with separately.
437 if (dash[0] == 0.0) {
438 ps.println("\\psset{linestyle=dotted,dotsep="
439 + fixedPrecision(dash[1]) + "}");
440 return;
441 }
442
443 // In more complex patterns, dots will appear as very thin dashes.
444 ps.print("\\psset{linestyle=dashed,dash=");
445 for (int i = 0; i < dash.length - 1; i++) {
446 ps.print(fixedPrecision(dash[i]) + " ");
447 }
448 ps.print(fixedPrecision(dash[dash.length - 1]));
449 ps.println("}");
450 }
451
452 /* 8.2. paint/color */
453 public void setPaintMode() {
454 // Mostly unimplemented.
455 ps.println("% setPaintMode() called");
456 }
457
458 public void setXORMode(Color c1) {
459 // Mostly unimplemented.
460 ps.println("% setXORMode(Color c1) called");
461 }
462
463 protected void writePaint(Color p) throws IOException {
464 ps.println("\\newrgbcolor{current}{"
465 + fixedPrecision(p.getRed() / 255.) + " "
466 + fixedPrecision(p.getGreen() / 255.) + " "
467 + fixedPrecision(p.getBlue() / 255.) + "}");
468 ps
469 .println("\\psset{linecolor=current,fillcolor=current,fillstyle=solid}");
470 }
471
472 protected void writePaint(GradientPaint p) throws IOException {
473 double gradTheta = Math.atan((p.getPoint1().getY() - p.getPoint2()
474 .getY())
475 / (p.getPoint1().getX() - p.getPoint2().getX()));
476 ps.println("\\newrgbcolor{gradbegin}{"
477 + fixedPrecision(p.getColor1().getRed() / 255.) + " "
478 + fixedPrecision(p.getColor1().getGreen() / 255.) + " "
479 + fixedPrecision(p.getColor1().getBlue() / 255.) + "}");
480 ps.println("\\newrgbcolor{gradend}{"
481 + fixedPrecision(p.getColor2().getRed() / 255.) + " "
482 + fixedPrecision(p.getColor2().getGreen() / 255.) + " "
483 + fixedPrecision(p.getColor2().getBlue() / 255.) + "}");
484 ps.println("\\psset{gradmidpoint=1,gradangle="
485 + Math.toDegrees(gradTheta) + ",fillstyle=gradient}");
486 }
487
488 protected void writePaint(TexturePaint p) throws IOException {
489 // Not supported in LaTeX PSTricks.
490 ps
491 .println("% writePaint(TexturePaint p) called, not supported, crosshatch substituted");
492 ps.println("\\psset{fillstyle=crosshatch}");
493 }
494
495 protected void writePaint(Paint p) throws IOException {
496 writeWarning(getClass() + ": writePaint(Paint) not implemented for "
497 + p.getClass());
498 // Write out the paint.
499 ps.println("% writePaint(Paint p) called");
500 }
501
502 /* 8.3. font */
503 protected void writeFont(Font font) throws IOException {
504 // written when needed
505 }
506
507 /* 8.4. rendering hints */
508
509 /*
510 * ================================================================================ |
511 * 9. Auxiliary
512 * ================================================================================
513 */
514 public GraphicsConfiguration getDeviceConfiguration() {
515 // Mostly unimplemented
516 return null;
517 }
518
519 public boolean hit(Rectangle rect, Shape s, boolean onStroke) {
520 // Mostly unimplemented
521 return false;
522 }
523
524 public void writeComment(String comment) throws IOException {
525 ps.println("% " + comment);
526 }
527
528 public void writeWarning(String msg) {
529 System.out.println(msg);
530 }
531
532 public String toString() {
533 return "LatexGraphics";
534 }
535
536 private static ScientificFormat scientific = new ScientificFormat(5, 100,
537 false);
538
539 public static String fixedPrecision(double d) {
540 return scientific.format(d);
541 }
542 }