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