2003/12/29 03:25:43
[org.ibex.core.git] / src / org / xwt / plat / AWT.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt.plat;
3
4 import org.xwt.*;
5 import org.xwt.util.*;
6 import java.net.*;
7 import java.io.*;
8 import java.util.*;
9 import java.awt.*;
10 import java.awt.datatransfer.*;
11 import java.awt.image.*;
12 import java.awt.event.*;
13
14 /** Platform subclass for all VM's providing AWT 1.1 functionality */
15 public class AWT extends JVM {
16
17     protected String getDescriptiveName() { return "Generic JDK 1.1+ with AWT"; }
18     protected PixelBuffer _createPixelBuffer(int w, int h, Surface owner) { return new AWTPixelBuffer(w, h); }
19     protected Picture _createPicture(Res r) { return new AWTPicture(r); }
20     protected int _getScreenWidth() { return Toolkit.getDefaultToolkit().getScreenSize().width; }
21     protected int _getScreenHeight() { return Toolkit.getDefaultToolkit().getScreenSize().height; }
22     protected Surface _createSurface(Box b, boolean framed) { return new AWTSurface(b, framed); }
23
24     protected void postInit() {
25         if (Log.on) Log.info(Platform.class, "               color depth = " +
26                             Toolkit.getDefaultToolkit().getColorModel().getPixelSize() + "bpp");
27     }
28
29     protected void _criticalAbort(String message) {
30         if (Log.on) Log.info(this, message);
31         final Dialog d = new Dialog(new Frame(), "XWT Cannot Continue");
32         d.setLayout(new BorderLayout());
33         TextArea ta = new TextArea("XWT cannot continue because:\n\n" + message, 10, 80);
34         ta.setEditable(false);
35         d.add(ta, "Center");
36         Button b = new Button("OK");
37         b.addActionListener(new ActionListener() {
38                 public void actionPerformed(ActionEvent e) {
39                     d.dispose();
40                 }
41             });
42         d.add(b, "South");
43         d.setModal(true);
44         d.pack();
45         d.show();
46         new Semaphore().block();
47     }
48
49     protected String _getClipBoard() {
50         Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
51         if (cb == null) return null;
52         Transferable clipdata = cb.getContents(null);
53         try { return (String)clipdata.getTransferData(DataFlavor.stringFlavor); } catch (Exception ex) { return null; }
54     }
55
56     protected void _setClipBoard(String s) {
57         Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
58         if (clipboard == null) return;
59         StringSelection clipString = new StringSelection(s);
60         clipboard.setContents(clipString, clipString);
61     }
62
63     /** some platforms (cough, cough, NetscapeVM) have totally broken modifier masks; they will need to override this */
64     protected static int modifiersToButtonNumber(int modifiers) {
65         if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) return 1;
66         if ((modifiers & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) {
67             // ugh, MacOSX reports the right mouse button as BUTTON2_MASK...
68             if (System.getProperty("os.name", "").startsWith("Mac OS X")) return 2;
69             return 3;
70         }
71         if ((modifiers & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
72             // ugh, MacOSX reports the right mouse button as BUTTON2_MASK...
73             if (System.getProperty("os.name", "").startsWith("Mac OS X")) return 3;
74             return 2;
75         }
76         return 0;
77     }
78
79     static class FileDialogHelper extends FileDialog implements WindowListener, ComponentListener {
80         Semaphore s;
81         public FileDialogHelper(String suggestedFileName, Semaphore s, boolean write) {
82             super(new Frame(), write ? "Save" : "Open", write ? FileDialog.SAVE : FileDialog.LOAD);
83             this.s = s;
84             addWindowListener(this);
85             addComponentListener(this);
86             if (suggestedFileName.indexOf(File.separatorChar) == -1) {
87                 setFile(suggestedFileName);
88             } else {
89                 setDirectory(suggestedFileName.substring(0, suggestedFileName.lastIndexOf(File.separatorChar)));
90                 setFile(suggestedFileName.substring(suggestedFileName.lastIndexOf(File.separatorChar) + 1));
91             }
92             show();
93         }
94         public void windowActivated(WindowEvent e) { }
95         public void windowClosed(WindowEvent e) { s.release(); }
96         public void windowClosing(WindowEvent e) { }
97         public void windowDeactivated(WindowEvent e) { }
98         public void windowDeiconified(WindowEvent e) { }
99         public void windowIconified(WindowEvent e) { }
100         public void windowOpened(WindowEvent e) { }
101         public void componentHidden(ComponentEvent e) { s.release(); }
102         public void componentMoved(ComponentEvent e) { }
103         public void componentResized(ComponentEvent e) { }
104         public void componentShown(ComponentEvent e) { }
105     };
106
107     protected String _fileDialog(String suggestedFileName, boolean write) {
108         final Semaphore s = new Semaphore();
109         FileDialogHelper fd = new FileDialogHelper(suggestedFileName, s, write);
110         s.block();
111         return fd.getDirectory() == null ? null : (fd.getDirectory() + File.separatorChar + fd.getFile());
112     }
113
114
115     // Inner Classes /////////////////////////////////////////////////////////////////////////////////////
116
117     protected org.xwt.Font.Glyph _createGlyph(org.xwt.Font f, char c) { return new AWTGlyph(f, c); }
118     protected static class AWTGlyph extends org.xwt.Font.Glyph {
119         private Image i = null;
120         static final ColorModel cmodel = new ColorModel(8) {
121             public int getRed(int p) { return 0; }
122             public int getGreen(int p) { return 0; }
123             public int getBlue(int p) { return 0; }
124             public int getAlpha(int p) { return p & 0xFF; }
125         };
126
127         public AWTGlyph(org.xwt.Font f, char c) { super(f, c); }
128         Image getImage() {
129             if (i == null && isLoaded) {
130                 i = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, cmodel, data, 0, width));
131                 MediaTracker mediatracker = new MediaTracker(new Canvas());
132                 mediatracker.addImage(i, 1);
133                 try { mediatracker.waitForAll(); } catch (InterruptedException e) { }
134                 mediatracker.removeImage(i);
135                 synchronized(AWTPixelBuffer.class) { 
136                     if (AWTPixelBuffer.component == null) {
137                         AWTPixelBuffer.component = new Frame();
138                         AWTPixelBuffer.component.setVisible(false);
139                         AWTPixelBuffer.component.addNotify();
140                     }
141                 }
142                 data = null;
143             }
144             return i;
145         }
146     }
147
148     protected static class AWTPicture extends Picture {
149         public Image i = null;
150         private static ColorModel cmodel = new DirectColorModel(32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
151         
152         boolean initialized = false;
153         public AWTPicture(Res r) { super(r); }
154         public void init() {
155             if (initialized) return;
156             initialized = true;
157             i = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, cmodel, data, 0, width));
158             MediaTracker mediatracker = new MediaTracker(new Canvas());
159             mediatracker.addImage(i, 1);
160             try { mediatracker.waitForAll(); } catch (InterruptedException e) { }
161             mediatracker.removeImage(i);
162             synchronized(AWTPixelBuffer.class) { 
163                 if (AWTPixelBuffer.component == null) {
164                     AWTPixelBuffer.component = new Frame();
165                     AWTPixelBuffer.component.setVisible(false);
166                     AWTPixelBuffer.component.addNotify();
167                 }
168             }
169         }
170     }
171     
172     protected static class AWTPixelBuffer extends PixelBuffer {
173         
174         protected Image i = null;
175         protected Graphics g = null;
176         
177         /** JDK1.1 platforms require that a component be associated with each off-screen buffer */
178         static Component component = null;
179
180         protected AWTPixelBuffer() { }
181         public AWTPixelBuffer(int w, int h) {
182             synchronized(AWTPixelBuffer.class) {
183                 if (component == null) {
184                     component = new Frame();
185                     component.setVisible(false);
186                     component.addNotify();
187                 }
188             }
189             i = component.createImage(w, h);
190             g = i.getGraphics();
191         }
192         
193         public int getHeight() { return i == null ? 0 : i.getHeight(null); }
194         public int getWidth() { return i == null ? 0 : i.getWidth(null); }
195
196         public void drawPicture(Picture source, int dx, int dy, int cx1, int cy1, int cx2, int cy2) {
197             ((AWTPicture)source).init();
198             g.setClip(cx1, cy1, cx2 - cx1, cy2 - cy1);
199             g.drawImage(((AWTPicture)source).i, dx, dy, null);
200             g.setClip(0, 0, i.getWidth(null), i.getHeight(null));
201         }
202
203         /** implemented with java.awt 1.1's setXORMode() */
204         public void drawGlyph(org.xwt.Font.Glyph source, int dx, int dy, int cx1, int cy1, int cx2, int cy2, int rgb) {
205
206             // XOR the target region
207             g.setXORMode(new Color((rgb & 0x00ff0000) >> 16, (rgb & 0x0000ff00) >> 8, rgb & 0x000000ff));
208             g.setColor(new Color(0x0, 0x0, 0x0));
209             g.fillRect(cx1, cy1, cx2 - cx1, cy2 - cy1);
210
211             // blacken the area we want the glyph to cover
212             g.setPaintMode();
213             g.setClip(cx1, cy1, cx2 - cx1, cy2 - cy1);
214             g.drawImage(((AWTGlyph)source).getImage(), dx, dy, null);
215             g.setClip(0, 0, i.getWidth(null), i.getHeight(null));
216
217             // XOR back, turning black into the chosen rgb color
218             g.setXORMode(new Color((rgb & 0x00ff0000) >> 16, (rgb & 0x0000ff00) >> 8, rgb & 0x000000ff));
219             g.setColor(new Color(0x0, 0x0, 0x0));
220             g.fillRect(cx1, cy1, cx2 - cx1, cy2 - cy1);
221
222             // restore the graphics context
223             g.setPaintMode();
224         }
225
226         // FIXME: try to use os acceleration
227         public void fillTrapezoid(int x1, int x2, int y1, int x3, int x4, int y2, int argb) {
228             g.setColor(new Color((argb & 0x00FF0000) >> 16, (argb & 0x0000FF00) >> 8, (argb & 0x000000FF)));
229             if (x1 == x3 && x2 == x4) {
230                 g.fillRect(x1, y1, x4 - x1, y2 - y1);
231             } else for(int y=y1; y<y2; y++) {
232                 int _x1 = (int)Math.floor((y - y1) * (x3 - x1) / (y2 - y1) + x1);
233                 int _y1 = (int)Math.floor(y);
234                 int _x2 = (int)Math.ceil((y - y1) * (x4 - x2) / (y2 - y1) + x2);
235                 int _y2 = (int)Math.floor(y) + 1;
236                 if (_x1 > _x2) { int _x0 = _x1; _x1 = _x2; _x2 = _x0; }
237                 g.fillRect(_x1, _y1, _x2 - _x1, _y2 - _y1);
238             }
239         }
240     }
241     
242     
243     protected static class AWTSurface extends Surface.DoubleBufferedSurface
244         implements MouseListener, MouseMotionListener, KeyListener, ComponentListener, WindowListener {
245
246         public void blit(PixelBuffer s, int sx, int sy, int dx, int dy, int dx2, int dy2) {
247             insets = (frame == null ? window : frame).getInsets();
248             window.getGraphics().drawImage(((AWTPixelBuffer)s).i,
249                                   dx + insets.left,
250                                   dy + insets.top,
251                                   dx2 + insets.left,
252                                   dy2 + insets.top,
253                                   sx, sy, sx + (dx2 - dx), sy + (dy2 - dy), null);
254         }
255         
256         /** if (component instanceof Frame) then frame == window else frame == null */
257         Frame frame = null;
258         Window window = null;
259         
260         /** our component's insets */
261         protected Insets insets = new Insets(0, 0, 0, 0);
262         
263         /** some JDKs let us recycle a single Dimension object when calling getSize() */
264         Dimension singleSize = new Dimension();
265         
266         public void toBack() { if (window != null) window.toBack(); }
267         public void toFront() { if (window != null) window.toFront(); }
268         public void setLocation() { window.setLocation(root.x, root.y); }
269         public void setTitleBarText(String s) { if (frame != null) frame.setTitle(s); }
270         public void setIcon(Picture i) { if (frame != null) frame.setIconImage(((AWTPicture)i).i); }
271         public void _setSize(int width, int height) { window.setSize(width + (insets.left + insets.right), height + (insets.top + insets.bottom)); }
272         public void setInvisible(boolean b) { window.setVisible(!b); }
273         protected void _setMinimized(boolean b) { if (Log.on) Log.info(this, "JDK 1.1 platforms cannot minimize or unminimize windows"); }
274         protected void _setMaximized(boolean b) {
275             if (!b) {
276                 if (Log.on) Log.info(this, "JDK 1.1 platforms cannot unmaximize windows");
277                 return;
278             }
279             window.setLocation(new Point(0, 0));
280             window.setSize(Toolkit.getDefaultToolkit().getScreenSize());
281         }
282
283         class InnerFrame extends Frame {
284             public InnerFrame() throws java.lang.UnsupportedOperationException { }
285             public void update(Graphics gr) { paint(gr); }
286             public void paint(Graphics gr) {
287                 Rectangle r = gr.getClipBounds();
288
289                 // ugly hack for Java1.4 dynamicLayout on Win32 -- this catches expansions during smooth resize
290                 int newwidth = Math.max(r.x - insets.left + r.width, root.width);
291                 int newheight = Math.max(r.y - insets.top + r.height, root.height);
292                 if (newwidth > root.width || newheight > root.height)
293                     componentResized(window.getWidth() - insets.left - insets.right,
294                                      window.getHeight() - insets.top - insets.bottom);
295
296                 Dirty(r.x - insets.left, r.y - insets.top, r.width, r.height);
297             }
298         }
299
300         class InnerWindow extends Window {
301             public InnerWindow() throws java.lang.UnsupportedOperationException { super(new Frame()); }
302             public void update(Graphics gr) { paint(gr); }
303             public void paint(Graphics gr) {
304                 Rectangle r = gr.getClipBounds();
305                 Dirty(r.x - insets.left, r.y - insets.top, r.width, r.height);
306             }
307         }
308
309         public void render() {
310             // useful optimizatin;
311             window.setBackground((root.fillcolor & 0xFF000000) == 0 ?
312                                  Color.white :
313                                  new Color((root.fillcolor >> 16) & 0xff,
314                                            (root.fillcolor >> 8) & 0xff,
315                                            (root.fillcolor) & 0xff));
316             super.render();
317         }
318
319         AWTSurface(Box root, boolean framed) {
320             super(root);
321             try {
322                 if (framed) window = frame = new InnerFrame();
323                 else window = new InnerWindow();
324
325             // this is here to catch HeadlessException on jdk1.4
326             } catch (java.lang.UnsupportedOperationException e) {
327                 if (Log.on) Log.info(this, "Exception thrown in AWTSurface$InnerFrame() -- this should never happen");
328                 if (Log.on) Log.info(this, e);
329             }
330
331             insets = window.getInsets();
332             
333             window.addMouseListener(this);
334             window.addKeyListener(this);
335             window.addComponentListener(this);
336             window.addMouseMotionListener(this);
337             window.addWindowListener(this);
338
339             // IMPORTANT: this must be called before render() to ensure
340             // that our peer has been created
341             makeVisible();
342         }
343
344         protected void makeVisible() { window.setVisible(true); }
345         
346         public void _dispose() {
347             window.removeMouseListener(this);
348
349             // removed to work around a jdk1.3 bug
350             /* window.removeKeyListener(this); */
351
352             window.removeComponentListener(this);
353             window.removeMouseMotionListener(this);
354             window.removeWindowListener(this);
355             window.dispose();
356         }
357
358         public void syncCursor() {
359             if (cursor.equals("crosshair")) window.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
360             else if (cursor.equals("east")) window.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
361             else if (cursor.equals("move")) window.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
362             else if (cursor.equals("north")) window.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
363             else if (cursor.equals("northeast")) window.setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR));
364             else if (cursor.equals("northwest")) window.setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR));
365             else if (cursor.equals("south")) window.setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
366             else if (cursor.equals("southeast")) window.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
367             else if (cursor.equals("southwest")) window.setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
368             else if (cursor.equals("text")) window.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
369             else if (cursor.equals("west")) window.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
370             else if (cursor.equals("wait")) window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
371             else if (cursor.equals("hand")) window.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
372             else window.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
373         }
374         
375         // AWT Message translation ////////////////////////////////////////////////////////////////
376         
377         // these functions are all executed in the AWT thread, not the
378         // MessageQueue thread. As a result, they must be *extremely*
379         // careful about invoking methods on instances of Box. Currently,
380         // they should only enqueue messages, use Box.whoIs()
381         // (unsynchronized but thought to be safe), and modify members of
382         // Surface.
383         
384         public void componentHidden(ComponentEvent e) { }
385         public void componentShown(ComponentEvent e) { }
386         public void windowOpened(WindowEvent e) { }
387         public void windowClosed(WindowEvent e) { }
388         public void windowClosing(WindowEvent e) { Close(); }
389         public void windowIconified(WindowEvent e) { Minimized(true); }
390         public void windowDeiconified(WindowEvent e) { dirty(0, 0, root.width, root.height); Minimized(false); }
391         public void windowActivated(WindowEvent e) { Focused(true); }
392         public void windowDeactivated(WindowEvent e) { Focused(false); }
393         public void componentMoved(ComponentEvent e) { PosChange(window.getLocation().x + insets.left, window.getLocation().y + insets.top); }
394
395         public void componentResized(ComponentEvent e) {
396             // we have to periodically do this; I don't know why
397             insets = window.getInsets();
398             componentResized(window.getWidth() - insets.left - insets.right, window.getHeight() - insets.top - insets.bottom);
399         }
400
401         public void componentResized(int newwidth, int newheight) {
402             int oldwidth = root.width;
403             int oldheight = root.height;
404             SizeChange(newwidth, newheight);
405         }
406
407         public void keyTyped(KeyEvent k) { }
408         public void keyPressed(KeyEvent k) { KeyPressed(translateKey(k)); }
409         public void keyReleased(KeyEvent k) { KeyReleased(translateKey(k)); }
410         public void mouseExited(MouseEvent m) { mouseMoved(m); }
411         public void mouseEntered(MouseEvent m) { mouseMoved(m); }
412         public void mouseDragged(MouseEvent m) { mouseMoved(m); }
413         public void mouseMoved(MouseEvent m) {
414
415             // ugly hack for Java1.4 dynamicLayout on Win32 -- this catches contractions during smooth resize
416             int newwidth = window.getWidth() - insets.left - insets.right;
417             int newheight = window.getHeight() - insets.top - insets.bottom;
418             if (newwidth != root.width || newheight != root.height) componentResized(newwidth, newheight);
419             
420             Move(m.getX() - insets.left, m.getY() - insets.top);
421         }
422         public void mousePressed(MouseEvent m) { Press(modifiersToButtonNumber(m.getModifiers())); }
423         public void mouseReleased(MouseEvent m) { Release(modifiersToButtonNumber(m.getModifiers())); }
424         public void mouseClicked(MouseEvent m) {
425             if (m.getClickCount() == 2) DoubleClick(modifiersToButtonNumber(m.getModifiers()));
426             else Click(modifiersToButtonNumber(m.getModifiers()));
427         }
428         
429         String translateKey(KeyEvent k) {
430             switch (k.getKeyCode()) {
431             case KeyEvent.VK_ALT: return "alt";
432             case KeyEvent.VK_BACK_SPACE: return "back_space";
433             case KeyEvent.VK_CONTROL: return "control";
434             case KeyEvent.VK_DELETE: return "delete";
435             case KeyEvent.VK_DOWN: return "down";
436             case KeyEvent.VK_END: return "end";
437             case KeyEvent.VK_ENTER: return "enter";
438             case KeyEvent.VK_ESCAPE: return "escape";
439             case KeyEvent.VK_F1: return "f1";
440             case KeyEvent.VK_F10: return "f10";
441             case KeyEvent.VK_F11: return "f11";
442             case KeyEvent.VK_F12: return "f12";
443             case KeyEvent.VK_F2: return "f2";
444             case KeyEvent.VK_F3: return "f3";
445             case KeyEvent.VK_F4: return "f4";
446             case KeyEvent.VK_F5: return "f5";
447             case KeyEvent.VK_F6: return "f6"; 
448             case KeyEvent.VK_F7: return "f7";
449             case KeyEvent.VK_F8: return "f8";
450             case KeyEvent.VK_F9: return "f9";
451             case KeyEvent.VK_HOME: return "home";
452             case KeyEvent.VK_INSERT: return "insert";
453             case KeyEvent.VK_LEFT: return "left";
454             case KeyEvent.VK_META: return "alt";
455             case KeyEvent.VK_PAGE_DOWN: return "page_down";
456             case KeyEvent.VK_PAGE_UP: return "page_up";
457             case KeyEvent.VK_PAUSE: return "pause";
458             case KeyEvent.VK_PRINTSCREEN: return "printscreen";
459             case KeyEvent.VK_RIGHT: return "right";
460             case KeyEvent.VK_SHIFT: return "shift";
461             case KeyEvent.VK_TAB: return "tab";
462             case KeyEvent.VK_UP: return "up";
463             default:
464                 char c = k.getKeyChar();
465                 if (c >= 1 && c <= 26) c = (char)('a' + c - 1);
466                 return String.valueOf(c);
467             }
468         }
469     }
470
471     protected void _decodeJPEG(InputStream is, Picture p) {
472         try {
473             Image i = Toolkit.getDefaultToolkit().createImage(InputStreamToByteArray.convert(is));
474             MediaTracker mediatracker = new MediaTracker(new Canvas());
475             mediatracker.addImage(i, 1);
476             try { mediatracker.waitForAll(); } catch (InterruptedException e) { }
477             mediatracker.removeImage(i);
478             final int width = i.getWidth(null);
479             final int height = i.getHeight(null);
480             final int[] data = new int[width * height];
481             PixelGrabber pg = new PixelGrabber(i, 0, 0, width, height, data, 0, width);
482             pg.grabPixels();
483             if ((pg.getStatus() & ImageObserver.ABORT) != 0)
484                 Log.info(this, "PixelGrabber reported an error while decoding JPEG image");
485             p.width = width;
486             p.height = height;
487             p.data = data;
488         } catch (Exception e) {
489             Log.info(this, "Exception caught while decoding JPEG image");
490             Log.info(this, e);
491         }
492     }
493 }