KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > nightlabs > editor2d > viewer > j2dswt > SWTGraphics2D


1 package org.nightlabs.editor2d.viewer.j2dswt;
2
3 import java.awt.AlphaComposite JavaDoc;
4 import java.awt.BasicStroke JavaDoc;
5 import java.awt.Color JavaDoc;
6 import java.awt.Composite JavaDoc;
7 import java.awt.Font JavaDoc;
8 import java.awt.FontMetrics JavaDoc;
9 import java.awt.GradientPaint JavaDoc;
10 import java.awt.Graphics JavaDoc;
11 import java.awt.Graphics2D JavaDoc;
12 import java.awt.GraphicsConfiguration JavaDoc;
13 import java.awt.Image JavaDoc;
14 import java.awt.Paint JavaDoc;
15 import java.awt.Rectangle JavaDoc;
16 import java.awt.RenderingHints JavaDoc;
17 import java.awt.Shape JavaDoc;
18 import java.awt.Stroke JavaDoc;
19 import java.awt.TexturePaint JavaDoc;
20 import java.awt.Toolkit JavaDoc;
21 import java.awt.RenderingHints.Key;
22 import java.awt.font.FontRenderContext JavaDoc;
23 import java.awt.font.GlyphVector JavaDoc;
24 import java.awt.geom.AffineTransform JavaDoc;
25 import java.awt.geom.PathIterator JavaDoc;
26 import java.awt.geom.Point2D JavaDoc;
27 import java.awt.image.BufferedImage JavaDoc;
28 import java.awt.image.BufferedImageOp JavaDoc;
29 import java.awt.image.ColorModel JavaDoc;
30 import java.awt.image.DirectColorModel JavaDoc;
31 import java.awt.image.ImageObserver JavaDoc;
32 import java.awt.image.IndexColorModel JavaDoc;
33 import java.awt.image.RenderedImage JavaDoc;
34 import java.awt.image.WritableRaster JavaDoc;
35 import java.awt.image.renderable.RenderableImage JavaDoc;
36 import java.text.AttributedCharacterIterator JavaDoc;
37 import java.util.Map JavaDoc;
38
39 import org.eclipse.swt.SWT;
40 import org.eclipse.swt.graphics.Device;
41 import org.eclipse.swt.graphics.FontData;
42 import org.eclipse.swt.graphics.GC;
43 import org.eclipse.swt.graphics.ImageData;
44 import org.eclipse.swt.graphics.PaletteData;
45 import org.eclipse.swt.graphics.Path;
46 import org.eclipse.swt.graphics.Pattern;
47 import org.eclipse.swt.graphics.RGB;
48 import org.eclipse.swt.graphics.Transform;
49 import org.eclipse.swt.widgets.Display;
50
51 /**
52  * The SWTGraphics2D class wraps the Graphics2D around a given SWt GC and try to mimics as
53  * much of the original Graphics2D behavior as possible, only using GC methods.
54  * <p>
55  * This class can be used wherever a standard Graphics2D object is legal. The main purpose
56  * of this class is then to reuse Java2D code without changing it, while drawing directly
57  * in an SWT Drawable.
58  * </p>
59  *
60  * @author Christophe Avare
61  * @author Grant Slender
62  * @version $Revision: 1.2 $
63  * @since 1.0
64  */

65 public class SWTGraphics2D
66 extends Graphics2D JavaDoc
67 {
68     private final static AffineTransform JavaDoc IDENTITY = new AffineTransform JavaDoc();
69
70     /**
71      * All current rendering hints. Only renderings hints meaningful to the current
72      * implementation are stored in this map, others are silently ignored.
73      */

74     private RenderingHints JavaDoc hints = new RenderingHints JavaDoc(null);
75
76     /**
77      * The last valus of GC.getBackground().
78      *
79      * @see swapColors()
80      */

81     private org.eclipse.swt.graphics.Color oldBg;
82
83     /**
84      * The last valus of GC.getForeground().
85      *
86      * @see swapColors()
87      */

88     private org.eclipse.swt.graphics.Color oldFg;
89
90     /**
91      * If true, this flag means the fg / bg colors must be swapped before rendering. This
92      * flag is normally set to true to prevent the fillXXX methods to render using the
93      * background color (the SWT behavior) instead of the foreground color (the AWT
94      * behavior).
95      */

96     private boolean needSwap = true;
97
98     private GC _gc;
99
100     private Device _dev;
101
102     public SWTGraphics2D(GC gc, Device dev) {
103         super();
104         _gc = gc;
105         _dev = (dev == null) ? Display.getDefault() : dev;
106         switch (_gc.getAntialias()) {
107             case SWT.OFF :
108                 hints.put(RenderingHints.KEY_ANTIALIASING,
109                     RenderingHints.VALUE_ANTIALIAS_OFF);
110                 break;
111             case SWT.ON :
112                 hints.put(RenderingHints.KEY_ANTIALIASING,
113                     RenderingHints.VALUE_ANTIALIAS_ON);
114                 break;
115             case SWT.DEFAULT :
116                 hints.put(RenderingHints.KEY_ANTIALIASING,
117                     RenderingHints.VALUE_ANTIALIAS_DEFAULT);
118                 break;
119         }
120         switch (_gc.getTextAntialias()) {
121             case SWT.OFF :
122                 hints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
123                     RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
124                 break;
125             case SWT.ON :
126                 hints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
127                     RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
128                 break;
129             case SWT.DEFAULT :
130                 hints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
131                     RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
132                 break;
133         }
134     }
135
136     public SWTGraphics2D(GC gc) {
137         this(gc, null);
138     }
139
140     /**
141      * Swap the GC foreground and background colors.
142      * <p>
143      * It is expected that methods like fillXXX have a call to this method before and
144      * after the actual call (calling swapColors in pairs restores the initial state).
145      * </p>
146      */

147     private void swapColors() {
148         if (needSwap) {
149             oldBg = _gc.getBackground();
150             oldFg = _gc.getForeground();
151             _gc.setBackground(oldFg);
152             _gc.setForeground(oldBg);
153         }
154     }
155
156     /**
157      * Converts a Java2D AffineTransform into an SWT Transform.
158      * <p>
159      * The caller must call dispose() on the returned instance.
160      * </p>
161      * <p>
162      * This method is not static because the returned transform is bound to the same
163      * Device as the orginal GC this instance represents.
164      * </p>
165      *
166      * @param t
167      * The Java2D affine transform
168      * @return An SWT Transform initialized with the affine transform values
169      */

170     public Transform JavaDoc toSWTTransform(AffineTransform JavaDoc t) {
171         double[] m = new double[6];
172         t.getMatrix(m);
173         return new Transform JavaDoc(_dev, (float) m[0], (float) m[1], (float) m[2],
174             (float) m[3], (float) m[4], (float) m[5]);
175     }
176
177     /**
178      * Converts a SWT Transform into an Java2D AffineTransform
179      * @param t
180      * @return
181      */

182     public AffineTransform JavaDoc toAWTTransform(Transform JavaDoc t) {
183         float[] m = new float[6];
184         t.getElements(m);
185         return new AffineTransform JavaDoc(m);
186     }
187     
188     /**
189      * Converts an SWT Color into an AWT Color.
190      * <p>
191      * The returned Color have its alpha channel set to the current alpha value of the GC.
192      * As a consequence, colors cannot be cached or resused.
193      * </p>
194      *
195      * @param rgb
196      * The SWT color
197      * @return The AWT color
198      */

199     public Color JavaDoc toAWTColor(org.eclipse.swt.graphics.Color rgb) {
200         return new Color JavaDoc(rgb.getRed(), rgb.getGreen(), rgb.getBlue(), _gc.getAlpha());
201     }
202
203     /**
204      * Converts an AWT Color into an SWT Color.
205      * <p>
206      * The alpha channel of the AWT color is lost in the process.
207      * </p>
208      * <p>
209      * The caller must call dispose() on the returned instance.
210      * </p>
211      * <p>
212      * This method is not static because the returned color is bound to the same Device as
213      * the orginal GC this instance represents.
214      * </p>
215      *
216      * @param rgba
217      * @return
218      */

219     public org.eclipse.swt.graphics.Color toSWTColor(Color JavaDoc rgba) {
220         return new org.eclipse.swt.graphics.Color(_dev, rgba.getRed(), rgba.getGreen(),
221             rgba.getBlue());
222     }
223
224     /**
225      * Converts a Java2D Shape into an SWT Path object.
226      * <p>
227      * Coordinates are supposed to be expressed in the original (untransformed) user space
228      * following the Java2D convention for coordinates.
229      * </p>
230      * <p>
231      * This method uses the PathIterator mechanism to iterate over the shape.
232      * </p>
233      * <p>
234      * The caller must call dispose() on the returned instance.
235      * </p>
236      * <p>
237      * This method is not static because the returned path is bound to the same Device as
238      * the orginal GC this instance represents.
239      * </p>
240      *
241      * @param s
242      * The Shape to convert
243      * @return The equivalent Path
244      */

245     public Path toPath(Shape JavaDoc s) {
246         float[] coords = new float[6];
247         Path p = new Path(_dev);
248         PathIterator JavaDoc it = s.getPathIterator(IDENTITY);
249         while (!it.isDone()) {
250             int type = it.currentSegment(coords);
251             switch (type) {
252                 case PathIterator.SEG_MOVETO :
253                     p.moveTo(coords[0], coords[1]);
254                     break;
255                 case PathIterator.SEG_LINETO :
256                     p.lineTo(coords[0], coords[1]);
257                     break;
258                 case PathIterator.SEG_QUADTO :
259                     p.quadTo(coords[0], coords[1], coords[2], coords[3]);
260                     break;
261                 case PathIterator.SEG_CUBICTO :
262                     p.cubicTo(coords[0], coords[1], coords[2], coords[3], coords[4],
263                         coords[5]);
264                     break;
265                 // FIXME: after the SEG_CLOSE, we should be prepared for a new path.
266
// FIXME: we should consider the winding rule.
267
case PathIterator.SEG_CLOSE :
268                     p.close();
269                     break;
270             }
271             it.next();
272         }
273         return p;
274     }
275
276     public void addRenderingHints(Map JavaDoc<?, ?> map) {
277         setRenderingHints(map);
278     }
279
280     public void clip(Shape JavaDoc s) {
281         Path p = toPath(s);
282         _gc.setClipping(p);
283         p.dispose();
284     }
285
286     public void draw(Shape JavaDoc s) {
287         Path p = toPath(s);
288         _gc.drawPath(p);
289         p.dispose();
290     }
291
292     public void drawGlyphVector(GlyphVector JavaDoc g, float x, float y) {
293         // TODO Auto-generated method stub
294

295     }
296
297     public void drawImage(BufferedImage JavaDoc img, BufferedImageOp JavaDoc op, int x, int y) {
298         BufferedImage JavaDoc bi = op.createCompatibleDestImage(img, null);
299         org.eclipse.swt.graphics.Image swtImage = toSWT(bi);
300         _gc.drawImage(swtImage, x, y);
301     }
302
303     public static final int DEFAULT_IMAGE_TYPE = BufferedImage.TYPE_INT_ARGB;
304     public boolean drawImage(Image JavaDoc img, AffineTransform JavaDoc xform, ImageObserver JavaDoc obs)
305     {
306         if (img instanceof BufferedImage JavaDoc) {
307             BufferedImage JavaDoc bi = (BufferedImage JavaDoc) img;
308             Transform JavaDoc oldTransform = new Transform JavaDoc(_dev);
309             _gc.getTransform(oldTransform);
310             _gc.setTransform(toSWTTransform(xform));
311             org.eclipse.swt.graphics.Image swtImage = toSWT(bi);
312             _gc.drawImage(swtImage, (int)xform.getTranslateX(), (int)xform.getTranslateY());
313             return true;
314         }
315         return false;
316     }
317
318     public void drawRenderableImage(RenderableImage JavaDoc img, AffineTransform JavaDoc xform) {
319         // TODO Auto-generated method stub
320

321     }
322
323     public void drawRenderedImage(RenderedImage JavaDoc img, AffineTransform JavaDoc xform) {
324         // TODO Auto-generated method stub
325

326     }
327
328     public void drawString(AttributedCharacterIterator JavaDoc iterator, float x, float y) {
329         // FIXME
330
}
331
332     public void drawString(AttributedCharacterIterator JavaDoc iterator, int x, int y) {
333         // FIXME
334
}
335
336     public void drawString(String JavaDoc s, float x, float y) {
337         drawString(s, (int) x, (int) y);
338     }
339
340     public void drawString(String JavaDoc str, int x, int y) {
341         int fh = _gc.getFontMetrics().getAscent();
342         _gc.drawString(str, x, y - fh, true);
343     }
344
345     public void fill(Shape JavaDoc s) {
346         Path p = toPath(s);
347         swapColors();
348         _gc.fillPath(p);
349         swapColors();
350         p.dispose();
351     }
352
353     public Color JavaDoc getBackground() {
354         return toAWTColor(_gc.getBackground());
355     }
356
357     /**
358      * Only SRC rule is meaningful in SWT!
359      */

360     public Composite JavaDoc getComposite() {
361         return AlphaComposite.Src;
362     }
363
364     public GraphicsConfiguration JavaDoc getDeviceConfiguration() {
365         // FIXME
366
return null;
367     }
368
369     public FontRenderContext JavaDoc getFontRenderContext() {
370         // FIXME
371
return null;
372     }
373
374     public Paint JavaDoc getPaint() {
375         return toAWTColor(_gc.getBackground());
376     }
377
378     public Object JavaDoc getRenderingHint(Key hintKey) {
379         return hints.get(hintKey);
380     }
381
382     public RenderingHints JavaDoc getRenderingHints() {
383         return hints;
384     }
385
386     public Stroke JavaDoc getStroke() {
387         // FIXME
388
return null;
389     }
390
391     public AffineTransform JavaDoc getTransform()
392     {
393         Transform JavaDoc t = new Transform JavaDoc(_dev);
394         _gc.getTransform(t);
395         AffineTransform JavaDoc at = toAWTTransform(t);
396         t.dispose();
397         return at;
398     }
399
400     public boolean hit(Rectangle JavaDoc rect, Shape JavaDoc s, boolean onStroke) {
401         // TODO Auto-generated method stub
402
return false;
403     }
404
405     public void rotate(double theta, double x, double y) {
406         // TODO Auto-generated method stub
407

408     }
409
410     public void rotate(double theta) {
411         Transform JavaDoc t = new Transform JavaDoc(_dev);
412         _gc.getTransform(t);
413         t.rotate((float) Math.toDegrees(theta));
414         _gc.setTransform(t);
415         t.dispose();
416     }
417
418     public void scale(double sx, double sy) {
419         Transform JavaDoc t = new Transform JavaDoc(_dev);
420         _gc.getTransform(t);
421         t.scale((float) sx, (float) sy);
422         _gc.setTransform(t);
423         t.dispose();
424     }
425
426     public void setBackground(Color JavaDoc color) {
427         _gc.setBackground(toSWTColor(color));
428         _gc.setAlpha(color.getAlpha());
429     }
430
431     /**
432      * Composite ops are ignored for SWT compatibility.
433      */

434     public void setComposite(Composite JavaDoc comp) {
435     }
436
437     /**
438      * Approximate a Paint object with an SWT equivalent.
439      *
440      * @see java.awt.Graphics2D#setPaint(java.awt.Paint)
441      */

442     public void setPaint(Paint JavaDoc paint) {
443         needSwap = true;
444         if (paint instanceof Color JavaDoc) {
445             setColor((Color JavaDoc) paint);
446         } else if (paint instanceof GradientPaint JavaDoc) {
447             GradientPaint JavaDoc gp = (GradientPaint JavaDoc) paint;
448             Point2D JavaDoc p1 = gp.getPoint1();
449             Point2D JavaDoc p2 = gp.getPoint2();
450             org.eclipse.swt.graphics.Color c1 = toSWTColor(gp.getColor1());
451             org.eclipse.swt.graphics.Color c2 = toSWTColor((gp.getColor2()));
452             Pattern p = new Pattern(_dev, (float) p1.getX(), (float) p1.getY(),
453                 (float) p2.getX(), (float) p2.getY(), c1, c2);
454             _gc.setBackgroundPattern(p);
455             c1.dispose();
456             c2.dispose();
457             needSwap = false;
458         } else if (paint instanceof TexturePaint JavaDoc) {
459             TexturePaint JavaDoc tp = (TexturePaint JavaDoc) paint;
460             BufferedImage JavaDoc awtImg = tp.getImage();
461             org.eclipse.swt.graphics.Image swtImg = new org.eclipse.swt.graphics.Image(
462                 _dev, awtImg.getWidth(), awtImg.getHeight());
463             // FIXME: convert a BufferedImage to an SWT Image
464
Pattern p = new Pattern(_dev, swtImg);
465             _gc.setForegroundPattern(p);
466             swtImg.dispose();
467         }
468     }
469
470     /**
471      * Only honor KEY_ANTIALIASING, KEY_TEXT_ANTIALIASING and KEY_INTERPOLATION.
472      */

473     public void setRenderingHint(Key hintKey, Object JavaDoc hintValue) {
474         // FIXME
475
if (hintKey == RenderingHints.KEY_ANTIALIASING) {
476             if (hintValue == RenderingHints.VALUE_ANTIALIAS_OFF) {
477                 _gc.setAntialias(SWT.OFF);
478             } else if (hintValue == RenderingHints.VALUE_ANTIALIAS_ON) {
479                 _gc.setAntialias(SWT.ON);
480             } else {
481                 _gc.setAntialias(SWT.DEFAULT);
482             }
483             hints.put(hintKey, hintValue);
484         }
485         if (hintKey == RenderingHints.KEY_TEXT_ANTIALIASING) {
486             if (hintValue == RenderingHints.VALUE_TEXT_ANTIALIAS_OFF) {
487                 _gc.setTextAntialias(SWT.OFF);
488             } else if (hintValue == RenderingHints.VALUE_TEXT_ANTIALIAS_ON) {
489                 _gc.setTextAntialias(SWT.ON);
490             } else {
491                 _gc.setTextAntialias(SWT.DEFAULT);
492             }
493             hints.put(hintKey, hintValue);
494         }
495         if (hintKey == RenderingHints.KEY_INTERPOLATION) {
496             if (hintValue == RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR) {
497                 _gc.setInterpolation(SWT.LOW);
498             } else if ((hintValue == RenderingHints.VALUE_INTERPOLATION_BILINEAR)
499                 || (hintValue == RenderingHints.VALUE_INTERPOLATION_BICUBIC)) {
500                 _gc.setTextAntialias(SWT.HIGH);
501             } else {
502                 _gc.setTextAntialias(SWT.DEFAULT);
503             }
504             hints.put(hintKey, hintValue);
505         }
506     }
507
508     public void setRenderingHints(Map JavaDoc<?, ?> hints) {
509         for (Object JavaDoc hint : hints.keySet()) {
510             setRenderingHint((Key) hint, hints.get(hint));
511         }
512     }
513
514     /**
515      * Convert a Stroke into chnage in the GC attributes.
516      * <p>
517      * The line width is a silly integer in SWT, which means it cannot be accurately used
518      * with non-identity transforms!
519      * </p>
520      * <p>
521      * The mitter limit value cannot be specified in SWT and thus is ignored.
522      * </p>
523      * <p>
524      * The dashes for custom line styles are, like the line width, expressed in pixels!
525      * </p>
526      */

527     public void setStroke(Stroke JavaDoc s) {
528         // We can only do things for BasicStroke objects!
529
if (s instanceof BasicStroke JavaDoc) {
530             BasicStroke JavaDoc bs = (BasicStroke JavaDoc) s;
531
532             // Set the line width
533
_gc.setLineWidth((int) bs.getLineWidth());
534
535             // Set the line join
536
switch (bs.getLineJoin()) {
537                 case BasicStroke.JOIN_BEVEL :
538                     _gc.setLineJoin(SWT.JOIN_BEVEL);
539                     break;
540                 case BasicStroke.JOIN_MITER :
541                     _gc.setLineJoin(SWT.JOIN_MITER);
542                     break;
543                 case BasicStroke.JOIN_ROUND :
544                     _gc.setLineJoin(SWT.JOIN_ROUND);
545                     break;
546             }
547
548             // set the line cap
549
switch (bs.getEndCap()) {
550                 case BasicStroke.CAP_BUTT :
551                     _gc.setLineCap(SWT.CAP_FLAT);
552                     break;
553                 case BasicStroke.CAP_ROUND :
554                     _gc.setLineCap(SWT.CAP_ROUND);
555                     break;
556                 case BasicStroke.CAP_SQUARE :
557                     _gc.setLineCap(SWT.CAP_SQUARE);
558                     break;
559             }
560
561             // Set the line style to solid by default
562
_gc.setLineStyle(SWT.LINE_SOLID);
563
564             // Look for any line style
565
float[] dashes = bs.getDashArray();
566             if (dashes != null) {
567                 // Dumb approximation here!
568
// FIXME: should look closer at units for lines dashes
569
int[] a = new int[dashes.length];
570                 for (int i = 0; i < a.length; i++) {
571                     a[i] = (int) dashes[i];
572                 }
573                 // this also sets the line style to LINE_CUSTOM
574
_gc.setLineDash(a);
575                 a = null;
576                 dashes = null;
577             }
578         }
579     }
580
581     public void setTransform(AffineTransform JavaDoc tx) {
582         Transform JavaDoc t = toSWTTransform(tx);
583         _gc.setTransform(t);
584         t.dispose();
585     }
586
587     /**
588      * The shear transform is manually computed, no SWT equivalent.
589      */

590     public void shear(double shx, double shy) {
591         Transform JavaDoc t = new Transform JavaDoc(_dev);
592         _gc.getTransform(t);
593         Transform JavaDoc shear = new Transform JavaDoc(_dev, 1f, (float) shx, (float) shy, 1f, 0, 0);
594         t.multiply(shear);
595         _gc.setTransform(t);
596         t.dispose();
597     }
598
599     
600     public void transform(AffineTransform JavaDoc Tx) {
601         Transform JavaDoc t = new Transform JavaDoc(_dev);
602         _gc.getTransform(t);
603         t.multiply(toSWTTransform(Tx));
604         _gc.setTransform(t);
605         t.dispose();
606     }
607
608     public void translate(double tx, double ty) {
609         Transform JavaDoc t = new Transform JavaDoc(_dev);
610         _gc.getTransform(t);
611         t.translate((float) tx, (float) ty);
612         _gc.setTransform(t);
613         t.dispose();
614     }
615
616     public void translate(int x, int y) {
617         translate((double) x, (double) y);
618     }
619
620     public void clearRect(int x, int y, int width, int height) {
621         int alpha = _gc.getAlpha();
622         _gc.setAlpha(0);
623         // FIXME: check which color is actually used in fillRectangle!
624
_gc.fillRectangle(x, y, width, height);
625         _gc.setAlpha(alpha);
626     }
627
628     /**
629      * clipRect() performs a cumulative intersection of the new rectangle and the current
630      * clip rectangle.
631      */

632     public void clipRect(int x, int y, int width, int height) {
633         org.eclipse.swt.graphics.Rectangle clip = _gc.getClipping();
634         clip.intersect(new org.eclipse.swt.graphics.Rectangle(x, y, width, height));
635         _gc.setClipping(clip);
636     }
637
638     public void copyArea(int x, int y, int width, int height, int dx, int dy) {
639         _gc.copyArea(x, y, width, height, dx, dy);
640     }
641
642     public Graphics JavaDoc create() {
643         return new SWTGraphics2D(_gc, _dev);
644     }
645
646     public void dispose() {
647         _gc = null;
648         _dev = null;
649         hints.clear();
650         hints = null;
651     }
652
653     public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
654         _gc.drawArc(x, y, width, height, startAngle, arcAngle);
655     }
656
657     public boolean drawImage(Image JavaDoc img, int x, int y, Color JavaDoc bgcolor,
658         ImageObserver JavaDoc observer) {
659         // TODO Auto-generated method stub
660
return false;
661     }
662
663     public boolean drawImage(Image JavaDoc img, int x, int y, ImageObserver JavaDoc observer) {
664         // TODO Auto-generated method stub
665
return false;
666     }
667
668     public boolean drawImage(Image JavaDoc img, int x, int y, int width, int height,
669         Color JavaDoc bgcolor, ImageObserver JavaDoc observer) {
670         // TODO Auto-generated method stub
671
return false;
672     }
673
674     public boolean drawImage(Image JavaDoc img, int x, int y, int width, int height,
675         ImageObserver JavaDoc observer) {
676         // TODO Auto-generated method stub
677
return false;
678     }
679
680     public boolean drawImage(Image JavaDoc img, int dx1, int dy1, int dx2, int dy2, int sx1,
681         int sy1, int sx2, int sy2, Color JavaDoc bgcolor, ImageObserver JavaDoc observer) {
682         // TODO Auto-generated method stub
683
return false;
684     }
685
686     public boolean drawImage(Image JavaDoc img, int dx1, int dy1, int dx2, int dy2, int sx1,
687         int sy1, int sx2, int sy2, ImageObserver JavaDoc observer) {
688         // TODO Auto-generated method stub
689
return false;
690     }
691
692     public void drawLine(int x1, int y1, int x2, int y2) {
693         _gc.drawLine(x1, y1, x2, y2);
694     }
695
696     public void drawOval(int x, int y, int width, int height) {
697         _gc.drawOval(x, y, width, height);
698     }
699
700     public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) {
701         int[] buf = new int[nPoints * 2];
702         int j = 0;
703         for (int i = 0; i < nPoints; i++) {
704             buf[j++] = xPoints[i];
705             buf[j++] = yPoints[i];
706         }
707         _gc.drawPolygon(buf);
708         buf = null;
709     }
710
711     public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) {
712         int[] buf = new int[nPoints * 2];
713         int j = 0;
714         for (int i = 0; i < nPoints; i++) {
715             buf[j++] = xPoints[i];
716             buf[j++] = yPoints[i];
717         }
718         _gc.drawPolyline(buf);
719         buf = null;
720     }
721
722     public void drawRoundRect(int x, int y, int width, int height, int arcWidth,
723         int arcHeight) {
724         _gc.drawRoundRectangle(x, y, width, height, arcWidth, arcHeight);
725     }
726
727     /**
728      * This method must swap colors if required.
729      *
730      */

731     public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
732         swapColors();
733         _gc.fillArc(x, y, width, height, startAngle, arcAngle);
734         swapColors();
735     }
736
737     /**
738      * This method must swap colors if required.
739      *
740      */

741     public void fillOval(int x, int y, int width, int height) {
742         swapColors();
743         _gc.fillOval(x, y, width, height);
744         swapColors();
745     }
746
747     /**
748      * This method must swap colors if required.
749      *
750      */

751     public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) {
752         int[] buf = new int[nPoints * 2];
753         int j = 0;
754         for (int i = 0; i < nPoints; i++) {
755             buf[j++] = xPoints[i];
756             buf[j++] = yPoints[i];
757         }
758         swapColors();
759         _gc.fillPolygon(buf);
760         swapColors();
761         buf = null;
762     }
763
764     /**
765      * This method must swap colors if required.
766      *
767      */

768     public void fillRect(int x, int y, int width, int height) {
769         swapColors();
770         _gc.fillRectangle(x, y, width, height);
771         swapColors();
772     }
773
774     /**
775      * This method must swap colors if required.
776      *
777      */

778     public void fillRoundRect(int x, int y, int width, int height, int arcWidth,
779         int arcHeight) {
780         swapColors();
781         _gc.fillRoundRectangle(x, y, width, height, arcWidth, arcHeight);
782         swapColors();
783     }
784
785     /**
786      * Because GC is missing a getClipping() method that returns the Path set on input,
787      * only the clip rectangle is available! This method is thus a synonym for
788      * getClipBounds().
789      */

790     public Shape JavaDoc getClip() {
791         return getClipBounds();
792     }
793
794     public Rectangle JavaDoc getClipBounds() {
795         org.eclipse.swt.graphics.Rectangle r = _gc.getClipping();
796         return new Rectangle JavaDoc(r.x, r.y, r.width, r.height);
797     }
798
799     public Color JavaDoc getColor() {
800         return toAWTColor(_gc.getForeground());
801     }
802
803     /**
804      * Font size in Java2D is expressed in pixels??? The javadoc says that font sizes are
805      * in points!
806      * <p>
807      * Font size is converted in pixels by multiplying SWT font size by screen DPI / 72.
808      * </p>
809      */

810     public Font JavaDoc getFont() {
811         FontData f = _gc.getFont().getFontData()[0];
812         int style = Font.PLAIN;
813         if ((f.getStyle() & SWT.BOLD) != 0) {
814             style = Font.BOLD;
815         }
816         if ((f.getStyle() & SWT.ITALIC) != 0) {
817             style |= Font.ITALIC;
818         }
819         // FIXME: the font used is the font size not pixel size as per Java2D
820
int pixels = (int) (f.getHeight() * _dev.getDPI().x / 72.0);
821         return new Font JavaDoc(f.getName(), style, pixels);
822     }
823
824     public FontMetrics JavaDoc getFontMetrics(Font JavaDoc f) {
825         return Toolkit.getDefaultToolkit().getFontMetrics(f);
826     }
827
828     public void setClip(int x, int y, int width, int height) {
829         _gc.setClipping(x, y, width, height);
830     }
831
832     public void setClip(Shape JavaDoc clip) {
833         Path p = toPath(clip);
834         _gc.setClipping(p);
835         p.dispose();
836     }
837
838     public void setColor(Color JavaDoc c) {
839         _gc.setForeground(toSWTColor(c));
840         _gc.setAlpha(c.getAlpha());
841         needSwap = true;
842     }
843
844     /**
845      * Font size in Java2D is expressed in pixels??? The javadoc says that font sizes are
846      * in points!
847      * <p>
848      * Font size is converted in points by multiplying AWT font size by 72/ screen DPI.
849      * </p>
850      */

851     public void setFont(Font JavaDoc font) {
852         int style = SWT.NORMAL;
853         if (font.isBold()) {
854             style |= SWT.BOLD;
855         }
856         if (font.isItalic()) {
857             style |= SWT.ITALIC;
858         }
859         // FIXME: the font used is the font size not pixel size as per Java2D
860
int points = (int) (font.getSize2D() * 72.0 / _dev.getDPI().x);
861
862         org.eclipse.swt.graphics.Font f = new org.eclipse.swt.graphics.Font(_dev, font
863             .getFamily(), points, style);
864         _gc.setFont(f);
865         f.dispose();
866     }
867
868     public void setPaintMode() {
869         _gc.setXORMode(false);
870     }
871
872     public void setXORMode(Color JavaDoc c1) {
873         // FIXME: alternate color should be set to c1?
874
_gc.setXORMode(true);
875     }
876     
877     /**
878      * converts a SWT Image to a SWT BufferedImage
879      * taken from http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet156.java
880      *
881      * @param data The ImageData of the SWT Image (@link org.eclipse.swt.graphics.Image.getImageData())
882      * @return a (@link java.awt.image.BufferedImage) which is identical to the original SWT Image
883      */

884     public BufferedImage JavaDoc toAWT(ImageData data)
885     {
886         ColorModel JavaDoc colorModel = null;
887         PaletteData palette = data.palette;
888         if (palette.isDirect) {
889             colorModel = new DirectColorModel JavaDoc(data.depth, palette.redMask, palette.greenMask, palette.blueMask);
890             BufferedImage JavaDoc bufferedImage = new BufferedImage JavaDoc(colorModel, colorModel.createCompatibleWritableRaster(data.width, data.height), false, null);
891             WritableRaster JavaDoc raster = bufferedImage.getRaster();
892             int[] pixelArray = new int[3];
893             for (int y = 0; y < data.height; y++) {
894                 for (int x = 0; x < data.width; x++) {
895                     int pixel = data.getPixel(x, y);
896                     RGB rgb = palette.getRGB(pixel);
897                     pixelArray[0] = rgb.red;
898                     pixelArray[1] = rgb.green;
899                     pixelArray[2] = rgb.blue;
900                     raster.setPixels(x, y, 1, 1, pixelArray);
901                 }
902             }
903             return bufferedImage;
904         } else {
905             RGB[] rgbs = palette.getRGBs();
906             byte[] red = new byte[rgbs.length];
907             byte[] green = new byte[rgbs.length];
908             byte[] blue = new byte[rgbs.length];
909             for (int i = 0; i < rgbs.length; i++) {
910                 RGB rgb = rgbs[i];
911                 red[i] = (byte)rgb.red;
912                 green[i] = (byte)rgb.green;
913                 blue[i] = (byte)rgb.blue;
914             }
915             if (data.transparentPixel != -1) {
916                 colorModel = new IndexColorModel JavaDoc(data.depth, rgbs.length, red, green, blue, data.transparentPixel);
917             } else {
918                 colorModel = new IndexColorModel JavaDoc(data.depth, rgbs.length, red, green, blue);
919             }
920             BufferedImage JavaDoc bufferedImage = new BufferedImage JavaDoc(colorModel, colorModel.createCompatibleWritableRaster(data.width, data.height), false, null);
921             WritableRaster JavaDoc raster = bufferedImage.getRaster();
922             int[] pixelArray = new int[1];
923             for (int y = 0; y < data.height; y++) {
924                 for (int x = 0; x < data.width; x++) {
925                     int pixel = data.getPixel(x, y);
926                     pixelArray[0] = pixel;
927                     raster.setPixel(x, y, pixelArray);
928                 }
929             }
930             return bufferedImage;
931         }
932     }
933     
934     /**
935      * converts an AWT BufferedImage to an SWT ImageData
936      * taken from http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet156.java
937      *
938      * @param bufferedImage the (@link java.awt.image.BufferedImage) to convert
939      * @return a (@link org.eclipse.swt.graphics) which can be used to construct a SWT Image
940      */

941     public ImageData toSWTImageData(BufferedImage JavaDoc bufferedImage)
942     {
943         if (bufferedImage.getColorModel() instanceof DirectColorModel JavaDoc) {
944             DirectColorModel JavaDoc colorModel = (DirectColorModel JavaDoc)bufferedImage.getColorModel();
945             PaletteData palette = new PaletteData(colorModel.getRedMask(), colorModel.getGreenMask(), colorModel.getBlueMask());
946             ImageData data = new ImageData(bufferedImage.getWidth(), bufferedImage.getHeight(), colorModel.getPixelSize(), palette);
947             WritableRaster JavaDoc raster = bufferedImage.getRaster();
948             int[] pixelArray = new int[3];
949             for (int y = 0; y < data.height; y++) {
950                 for (int x = 0; x < data.width; x++) {
951                     raster.getPixel(x, y, pixelArray);
952                     int pixel = palette.getPixel(new RGB(pixelArray[0], pixelArray[1], pixelArray[2]));
953                     data.setPixel(x, y, pixel);
954                 }
955             }
956             return data;
957         } else if (bufferedImage.getColorModel() instanceof IndexColorModel JavaDoc) {
958             IndexColorModel JavaDoc colorModel = (IndexColorModel JavaDoc)bufferedImage.getColorModel();
959             int size = colorModel.getMapSize();
960             byte[] reds = new byte[size];
961             byte[] greens = new byte[size];
962             byte[] blues = new byte[size];
963             colorModel.getReds(reds);
964             colorModel.getGreens(greens);
965             colorModel.getBlues(blues);
966             RGB[] rgbs = new RGB[size];
967             for (int i = 0; i < rgbs.length; i++) {
968                 rgbs[i] = new RGB(reds[i] & 0xFF, greens[i] & 0xFF, blues[i] & 0xFF);
969             }
970             PaletteData palette = new PaletteData(rgbs);
971             ImageData data = new ImageData(bufferedImage.getWidth(), bufferedImage.getHeight(), colorModel.getPixelSize(), palette);
972             data.transparentPixel = colorModel.getTransparentPixel();
973             WritableRaster JavaDoc raster = bufferedImage.getRaster();
974             int[] pixelArray = new int[1];
975             for (int y = 0; y < data.height; y++) {
976                 for (int x = 0; x < data.width; x++) {
977                     raster.getPixel(x, y, pixelArray);
978                     data.setPixel(x, y, pixelArray[0]);
979                 }
980             }
981             return data;
982         }
983         return null;
984     }
985     
986     public org.eclipse.swt.graphics.Image toSWT(BufferedImage JavaDoc img)
987     {
988         return new org.eclipse.swt.graphics.Image(_dev, toSWTImageData(img));
989     }
990 }
991
Popular Tags