1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  package net.sourceforge.jeuclid.swt;
20  
21  import java.awt.image.BufferedImage;
22  import java.awt.image.DataBuffer;
23  import java.awt.image.DataBufferByte;
24  import java.awt.image.Raster;
25  import java.io.IOException;
26  
27  import net.sourceforge.jeuclid.LayoutContext;
28  import net.sourceforge.jeuclid.converter.Converter;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.eclipse.swt.graphics.ImageData;
33  import org.eclipse.swt.graphics.PaletteData;
34  import org.w3c.dom.Node;
35  
36  
37  
38  
39  
40  
41  public final class MathRenderer {
42  
43      private static final int COLOR_ENTRIES = 3;
44  
45      private static final int BITS_PER_PIXEL = MathRenderer.COLOR_ENTRIES * 8;
46  
47      private static final PaletteData PALETTE_BGR = new PaletteData(0xff,
48              0xff00, 0xff0000);
49  
50      private static final class SingletonHolder {
51          private static final MathRenderer INSTANCE = new MathRenderer();
52  
53          private SingletonHolder() {
54          }
55      }
56  
57      
58  
59  
60      private static final Log LOGGER = LogFactory.getLog(MathRenderer.class);
61  
62      private final Converter converter = Converter.getInstance();
63  
64      
65  
66  
67      private MathRenderer() {
68          
69      }
70  
71      
72  
73  
74  
75  
76      public static MathRenderer getInstance() {
77          return MathRenderer.SingletonHolder.INSTANCE;
78      }
79  
80      
81  
82  
83  
84  
85  
86  
87  
88  
89      public ImageData render(final Node document,
90              final LayoutContext layoutContext) {
91          ImageData renderedFormula;
92          if (document == null) {
93              renderedFormula = null;
94          } else {
95              try {
96                  final BufferedImage bi = this.converter.render(document,
97                          layoutContext, BufferedImage.TYPE_3BYTE_BGR);
98                  final Raster r = bi.getRaster();
99                  final DataBuffer b = r.getDataBuffer();
100                 final DataBufferByte db = (DataBufferByte) b;
101                 final byte[] data = db.getData();
102                 final int w = bi.getWidth();
103                 renderedFormula = new ImageData(w, bi.getHeight(),
104                         MathRenderer.BITS_PER_PIXEL, MathRenderer.PALETTE_BGR,
105                         MathRenderer.COLOR_ENTRIES * w, data);
106             } catch (IOException io) {
107                 MathRenderer.LOGGER.warn(io.getMessage(), io);
108                 renderedFormula = null;
109             }
110         }
111         return renderedFormula;
112     }
113 
114 }