2004/01/11 00:49:54
[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(Stream 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.diag(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         private static ColorModel cmodel = new DirectColorModel(32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
121
122         // this doesn't work on Win32 because the JVM is broken
123         /*
124         static final ColorModel cmodel = new ColorModel(8) {
125             public int getRed(int p) { return 0; }
126             public int getGreen(int p) { return 0; }
127             public int getBlue(int p) { return 0; }
128             public int getAlpha(int p) { return p & 0xFF; }
129         };
130         */
131
132         public AWTGlyph(org.xwt.Font f, char c) { super(f, c); }
133         Image getImage() {
134             if (i == null && isLoaded) {
135
136                 int[] data2 = new int[data.length];
137                 for(int i=0; i<data2.length; i++) data2[i] = ((data[i]) & 0xff) << 24;
138
139                 MemoryImageSource mis = new MemoryImageSource(width, height, cmodel, data2, 0, width);
140                 mis.setAnimated(true);
141                 i = Toolkit.getDefaultToolkit().createImage(mis);
142                 MediaTracker mediatracker = new MediaTracker(new Canvas());
143                 mediatracker.addImage(i, 1);
144                 try { mediatracker.waitForAll(); } catch (InterruptedException e) { }
145                 mediatracker.removeImage(i);
146                 synchronized(AWTPixelBuffer.class) { 
147                     if (AWTPixelBuffer.component == null) {
148                         AWTPixelBuffer.component = new Frame();
149                         AWTPixelBuffer.component.setVisible(false);
150                         AWTPixelBuffer.component.addNotify();
151                     }
152                 }
153                 data = null;
154             }
155             return i;
156         }
157     }
158
159     protected static class AWTPicture extends Picture {
160         public Image i = null;
161         private static ColorModel cmodel = new DirectColorModel(32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
162         
163         boolean initialized = false;
164         public AWTPicture(Stream r) { super(r); }
165         public void init() {
166             if (initialized) return;
167             initialized = true;
168             MemoryImageSource mis = new MemoryImageSource(width, height, cmodel, data, 0, width);
169             mis.setAnimated(true);
170             i = Toolkit.getDefaultToolkit().createImage(mis);
171             MediaTracker mediatracker = new MediaTracker(new Canvas());
172             mediatracker.addImage(i, 1);
173             try { mediatracker.waitForAll(); } catch (InterruptedException e) { }
174             mediatracker.removeImage(i);
175             synchronized(AWTPixelBuffer.class) { 
176                 if (AWTPixelBuffer.component == null) {
177                     AWTPixelBuffer.component = new Frame();
178                     AWTPixelBuffer.component.setVisible(false);
179                     AWTPixelBuffer.component.addNotify();
180                 }
181             }
182         }
183     }
184     
185     protected static class AWTPixelBuffer extends PixelBuffer {
186         
187         protected Image i = null;
188         protected Graphics g = null;
189         
190         /** JDK1.1 platforms require that a component be associated with each off-screen buffer */
191         static Component component = null;
192
193         protected AWTPixelBuffer() { }
194         public AWTPixelBuffer(int w, int h) {
195             synchronized(AWTPixelBuffer.class) {
196                 if (component == null) {
197                     component = new Frame();
198                     component.setVisible(false);
199                     component.addNotify();
200                 }
201             }
202             i = component.createImage(w, h);
203             g = i.getGraphics();
204         }
205         
206         public int getHeight() { return i == null ? 0 : i.getHeight(null); }
207         public int getWidth() { return i == null ? 0 : i.getWidth(null); }
208
209         public void drawPicture(Picture source, int dx, int dy, int cx1, int cy1, int cx2, int cy2) {
210             ((AWTPicture)source).init();
211             g.setClip(cx1, cy1, cx2 - cx1, cy2 - cy1);
212             g.drawImage(((AWTPicture)source).i, dx, dy, null);
213             g.setClip(0, 0, i.getWidth(null), i.getHeight(null));
214         }
215
216         /** implemented with java.awt 1.1's setXORMode() */
217         public void drawGlyph(org.xwt.Font.Glyph source, int dx, int dy, int cx1, int cy1, int cx2, int cy2, int rgb) {
218
219             // XOR the target region
220             g.setXORMode(new Color((rgb & 0x00ff0000) >> 16, (rgb & 0x0000ff00) >> 8, rgb & 0x000000ff));
221             g.setColor(new Color(0x0, 0x0, 0x0));
222             g.fillRect(cx1, cy1, cx2 - cx1, cy2 - cy1);
223
224             // blacken the area we want the glyph to cover
225             g.setPaintMode();
226             g.setClip(cx1, cy1, cx2 - cx1, cy2 - cy1);
227             g.drawImage(((AWTGlyph)source).getImage(), dx, dy, null);
228             g.setClip(0, 0, i.getWidth(null), i.getHeight(null));
229
230             // XOR back, turning black into the chosen rgb color
231             g.setXORMode(new Color((rgb & 0x00ff0000) >> 16, (rgb & 0x0000ff00) >> 8, rgb & 0x000000ff));
232             g.setColor(new Color(0x0, 0x0, 0x0));
233             g.fillRect(cx1, cy1, cx2 - cx1, cy2 - cy1);
234
235             // restore the graphics context
236             g.setPaintMode();
237         }
238
239         // FIXME: try to use os acceleration
240         public void fillTrapezoid(int x1, int x2, int y1, int x3, int x4, int y2, int argb) {
241             g.setColor(new Color((argb & 0x00FF0000) >> 16, (argb & 0x0000FF00) >> 8, (argb & 0x000000FF)));
242             if (x1 == x3 && x2 == x4) {
243                 g.fillRect(x1, y1, x4 - x1, y2 - y1);
244             } else for(int y=y1; y<y2; y++) {
245                 int _x1 = (int)Math.floor((y - y1) * (x3 - x1) / (y2 - y1) + x1);
246                 int _y1 = (int)Math.floor(y);
247                 int _x2 = (int)Math.ceil((y - y1) * (x4 - x2) / (y2 - y1) + x2);
248                 int _y2 = (int)Math.floor(y) + 1;
249                 if (_x1 > _x2) { int _x0 = _x1; _x1 = _x2; _x2 = _x0; }
250                 g.fillRect(_x1, _y1, _x2 - _x1, _y2 - _y1);
251             }
252         }
253     }
254     
255     
256     protected static class AWTSurface extends Surface.DoubleBufferedSurface
257         implements MouseListener, MouseMotionListener, KeyListener, ComponentListener, WindowListener {
258
259         public void blit(PixelBuffer s, int sx, int sy, int dx, int dy, int dx2, int dy2) {
260             insets = (frame == null ? window : frame).getInsets();
261             window.getGraphics().drawImage(((AWTPixelBuffer)s).i,
262                                   dx + insets.left,
263                                   dy + insets.top,
264                                   dx2 + insets.left,
265                                   dy2 + insets.top,
266                                   sx, sy, sx + (dx2 - dx), sy + (dy2 - dy), null);
267         }
268         
269         /** if (component instanceof Frame) then frame == window else frame == null */
270         Frame frame = null;
271         Window window = null;
272         
273         /** our component's insets */
274         protected Insets insets = new Insets(0, 0, 0, 0);
275         
276         /** some JDKs let us recycle a single Dimension object when calling getSize() */
277         Dimension singleSize = new Dimension();
278         
279         public void toBack() { if (window != null) window.toBack(); }
280         public void toFront() { if (window != null) window.toFront(); }
281         public void setLocation() { window.setLocation(root.x, root.y); }
282         public void setTitleBarText(String s) { if (frame != null) frame.setTitle(s); }
283         public void setIcon(Picture i) { if (frame != null) frame.setIconImage(((AWTPicture)i).i); }
284         public void _setSize(int width, int height) { window.setSize(width + (insets.left + insets.right), height + (insets.top + insets.bottom)); }
285         public void setInvisible(boolean b) { window.setVisible(!b); }
286         protected void _setMinimized(boolean b) { if (Log.on) Log.info(this, "JDK 1.1 platforms cannot minimize or unminimize windows"); }
287         protected void _setMaximized(boolean b) {
288             if (!b) {
289                 if (Log.on) Log.info(this, "JDK 1.1 platforms cannot unmaximize windows");
290                 return;
291             }
292             window.setLocation(new Point(0, 0));
293             window.setSize(Toolkit.getDefaultToolkit().getScreenSize());
294         }
295
296         class InnerFrame extends Frame {
297             public InnerFrame() throws java.lang.UnsupportedOperationException { }
298             public void update(Graphics gr) { paint(gr); }
299             public void paint(Graphics gr) {
300                 Rectangle r = gr.getClipBounds();
301
302                 // ugly hack for Java1.4 dynamicLayout on Win32 -- this catches expansions during smooth resize
303                 int newwidth = Math.max(r.x - insets.left + r.width, root.width);
304                 int newheight = Math.max(r.y - insets.top + r.height, root.height);
305                 if (newwidth > root.width || newheight > root.height)
306                     componentResized(window.getWidth() - insets.left - insets.right,
307                                      window.getHeight() - insets.top - insets.bottom);
308
309                 Dirty(r.x - insets.left, r.y - insets.top, r.width, r.height);
310             }
311         }
312
313         class InnerWindow extends Window {
314             public InnerWindow() throws java.lang.UnsupportedOperationException { super(new Frame()); }
315             public void update(Graphics gr) { paint(gr); }
316             public void paint(Graphics gr) {
317                 Rectangle r = gr.getClipBounds();
318                 Dirty(r.x - insets.left, r.y - insets.top, r.width, r.height);
319             }
320         }
321
322         public void render() {
323             // useful optimizatin;
324             window.setBackground((root.fillcolor & 0xFF000000) == 0 ?
325                                  Color.white :
326                                  new Color((root.fillcolor >> 16) & 0xff,
327                                            (root.fillcolor >> 8) & 0xff,
328                                            (root.fillcolor) & 0xff));
329             super.render();
330         }
331
332         AWTSurface(Box root, boolean framed) {
333             super(root);
334             try {
335                 if (framed) window = frame = new InnerFrame();
336                 else window = new InnerWindow();
337
338             // this is here to catch HeadlessException on jdk1.4
339             } catch (java.lang.UnsupportedOperationException e) {
340                 if (Log.on) Log.info(this, "Exception thrown in AWTSurface$InnerFrame() -- this should never happen");
341                 if (Log.on) Log.info(this, e);
342             }
343
344             insets = window.getInsets();
345             
346             window.addMouseListener(this);
347             window.addKeyListener(this);
348             window.addComponentListener(this);
349             window.addMouseMotionListener(this);
350             window.addWindowListener(this);
351
352             // IMPORTANT: this must be called before render() to ensure
353             // that our peer has been created
354             makeVisible();
355         }
356
357         protected void makeVisible() { window.setVisible(true); }
358         
359         public void _dispose() {
360             window.removeMouseListener(this);
361
362             // removed to work around a jdk1.3 bug
363             /* window.removeKeyListener(this); */
364
365             window.removeComponentListener(this);
366             window.removeMouseMotionListener(this);
367             window.removeWindowListener(this);
368             window.dispose();
369         }
370
371         public void syncCursor() {
372             if (cursor.equals("crosshair")) window.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
373             else if (cursor.equals("east")) window.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
374             else if (cursor.equals("move")) window.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
375             else if (cursor.equals("north")) window.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
376             else if (cursor.equals("northeast")) window.setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR));
377             else if (cursor.equals("northwest")) window.setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR));
378             else if (cursor.equals("south")) window.setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
379             else if (cursor.equals("southeast")) window.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
380             else if (cursor.equals("southwest")) window.setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
381             else if (cursor.equals("text")) window.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
382             else if (cursor.equals("west")) window.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
383             else if (cursor.equals("wait")) window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
384             else if (cursor.equals("hand")) window.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
385             else window.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
386         }
387         
388         // AWT Message translation ////////////////////////////////////////////////////////////////
389         
390         // these functions are all executed in the AWT thread, not the
391         // MessageQueue thread. As a result, they must be *extremely*
392         // careful about invoking methods on instances of Box. Currently,
393         // they should only enqueue messages, use Box.whoIs()
394         // (unsynchronized but thought to be safe), and modify members of
395         // Surface.
396         
397         public void componentHidden(ComponentEvent e) { }
398         public void componentShown(ComponentEvent e) { }
399         public void windowOpened(WindowEvent e) { }
400         public void windowClosed(WindowEvent e) { }
401         public void windowClosing(WindowEvent e) { Close(); }
402         public void windowIconified(WindowEvent e) { Minimized(true); }
403         public void windowDeiconified(WindowEvent e) { dirty(0, 0, root.width, root.height); Minimized(false); }
404         public void windowActivated(WindowEvent e) { Focused(true); }
405         public void windowDeactivated(WindowEvent e) { Focused(false); }
406         public void componentMoved(ComponentEvent e) { PosChange(window.getLocation().x + insets.left, window.getLocation().y + insets.top); }
407
408         public void componentResized(ComponentEvent e) {
409             // we have to periodically do this; I don't know why
410             insets = window.getInsets();
411             componentResized(window.getWidth() - insets.left - insets.right, window.getHeight() - insets.top - insets.bottom);
412         }
413
414         public void componentResized(int newwidth, int newheight) { SizeChange(newwidth, newheight); }
415
416         public void keyTyped(KeyEvent k) { }
417         public void keyPressed(KeyEvent k) { KeyPressed(translateKey(k)); }
418         public void keyReleased(KeyEvent k) { KeyReleased(translateKey(k)); }
419         public void mouseExited(MouseEvent m) { mouseMoved(m); }
420         public void mouseEntered(MouseEvent m) { mouseMoved(m); }
421         public void mouseDragged(MouseEvent m) { mouseMoved(m); }
422         public void mouseMoved(MouseEvent m) {
423
424             // ugly hack for Java1.4 dynamicLayout on Win32 -- this catches contractions during smooth resize
425             int newwidth = window.getWidth() - insets.left - insets.right;
426             int newheight = window.getHeight() - insets.top - insets.bottom;
427             if (newwidth != root.width || newheight != root.height) componentResized(newwidth, newheight);
428             
429             Move(m.getX() - insets.left, m.getY() - insets.top);
430         }
431         public void mousePressed(MouseEvent m) { Press(modifiersToButtonNumber(m.getModifiers())); }
432         public void mouseReleased(MouseEvent m) { Release(modifiersToButtonNumber(m.getModifiers())); }
433         public void mouseClicked(MouseEvent m) {
434             if (m.getClickCount() == 2) DoubleClick(modifiersToButtonNumber(m.getModifiers()));
435             else Click(modifiersToButtonNumber(m.getModifiers()));
436         }
437         
438         String translateKey(KeyEvent k) {
439             switch (k.getKeyCode()) {
440             case KeyEvent.VK_ALT: return "alt";
441             case KeyEvent.VK_BACK_SPACE: return "back_space";
442             case KeyEvent.VK_CONTROL: return "control";
443             case KeyEvent.VK_DELETE: return "delete";
444             case KeyEvent.VK_DOWN: return "down";
445             case KeyEvent.VK_END: return "end";
446             case KeyEvent.VK_ENTER: return "enter";
447             case KeyEvent.VK_ESCAPE: return "escape";
448             case KeyEvent.VK_F1: return "f1";
449             case KeyEvent.VK_F10: return "f10";
450             case KeyEvent.VK_F11: return "f11";
451             case KeyEvent.VK_F12: return "f12";
452             case KeyEvent.VK_F2: return "f2";
453             case KeyEvent.VK_F3: return "f3";
454             case KeyEvent.VK_F4: return "f4";
455             case KeyEvent.VK_F5: return "f5";
456             case KeyEvent.VK_F6: return "f6"; 
457             case KeyEvent.VK_F7: return "f7";
458             case KeyEvent.VK_F8: return "f8";
459             case KeyEvent.VK_F9: return "f9";
460             case KeyEvent.VK_HOME: return "home";
461             case KeyEvent.VK_INSERT: return "insert";
462             case KeyEvent.VK_LEFT: return "left";
463             case KeyEvent.VK_META: return "alt";
464             case KeyEvent.VK_PAGE_DOWN: return "page_down";
465             case KeyEvent.VK_PAGE_UP: return "page_up";
466             case KeyEvent.VK_PAUSE: return "pause";
467             case KeyEvent.VK_PRINTSCREEN: return "printscreen";
468             case KeyEvent.VK_RIGHT: return "right";
469             case KeyEvent.VK_SHIFT: return "shift";
470             case KeyEvent.VK_TAB: return "tab";
471             case KeyEvent.VK_UP: return "up";
472             default:
473                 char c = k.getKeyChar();
474                 if (c >= 1 && c <= 26) c = (char)('a' + c - 1);
475                 return String.valueOf(c);
476             }
477         }
478     }
479
480     protected void _decodeJPEG(InputStream is, Picture p) {
481         try {
482             Image i = Toolkit.getDefaultToolkit().createImage(InputStreamToByteArray.convert(is));
483             MediaTracker mediatracker = new MediaTracker(new Canvas());
484             mediatracker.addImage(i, 1);
485             try { mediatracker.waitForAll(); } catch (InterruptedException e) { }
486             mediatracker.removeImage(i);
487             final int width = i.getWidth(null);
488             final int height = i.getHeight(null);
489             final int[] data = new int[width * height];
490             PixelGrabber pg = new PixelGrabber(i, 0, 0, width, height, data, 0, width);
491             pg.grabPixels();
492             if ((pg.getStatus() & ImageObserver.ABORT) != 0)
493                 Log.info(this, "PixelGrabber reported an error while decoding JPEG image");
494             p.width = width;
495             p.height = height;
496             p.data = data;
497         } catch (Exception e) {
498             Log.info(this, "Exception caught while decoding JPEG image");
499             Log.info(this, e);
500         }
501     }
502 }