2002/07/02 00:18:00
[org.ibex.core.git] / src / org / xwt / plat / AWT.java
1 // Copyright 2002 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 org.mozilla.javascript.*;
7 import java.net.*;
8 import java.io.*;
9 import java.util.*;
10 import java.awt.*;
11 import java.awt.datatransfer.*;
12 import java.awt.image.*;
13 import java.awt.event.*;
14 import java.applet.*;
15
16 /** Platform subclass for all VM's providing AWT 1.1 functionality */
17 public class AWT extends Platform {
18
19     protected String getDescriptiveName() { return "Generic JDK 1.1+ with AWT"; }
20     protected DoubleBuffer _createDoubleBuffer(int w, int h, Surface owner) { return new AWTDoubleBuffer(w, h); }
21     protected Picture _createPicture(int[] b, int w, int h) { return new AWTPicture(b, w, h); }
22     protected int _getScreenWidth() { return Toolkit.getDefaultToolkit().getScreenSize().width; }
23     protected int _getScreenHeight() { return Toolkit.getDefaultToolkit().getScreenSize().height; }
24     protected Surface _createSurface(Box b, boolean framed) { return new AWTSurface(b, framed); }
25     protected int _stringWidth(String font, String text) { return getFont(font).metrics.stringWidth(text); }
26     protected int _getMaxAscent(String font) { return getFont(font).metrics.getMaxAscent(); }
27     protected int _getMaxDescent(String font) { return getFont(font).metrics.getMaxDescent(); }
28     protected boolean _supressDirtyOnResize() { return true; }
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) return 3;
68         if ((modifiers & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) return 2;
69         return 0;
70     }
71
72     static class FileDialogHelper extends FileDialog implements WindowListener, ComponentListener {
73         Semaphore s;
74         public FileDialogHelper(String suggestedFileName, Semaphore s, boolean write) {
75             super(new Frame(), write ? "Save" : "Open", write ? FileDialog.SAVE : FileDialog.LOAD);
76             this.s = s;
77             addWindowListener(this);
78             addComponentListener(this);
79             if (suggestedFileName.indexOf(File.separatorChar) == -1) {
80                 setFile(suggestedFileName);
81             } else {
82                 setDirectory(suggestedFileName.substring(0, suggestedFileName.lastIndexOf(File.separatorChar)));
83                 setFile(suggestedFileName.substring(suggestedFileName.lastIndexOf(File.separatorChar) + 1));
84             }
85             show();
86         }
87         public void windowActivated(WindowEvent e) { }
88         public void windowClosed(WindowEvent e) { s.release(); }
89         public void windowClosing(WindowEvent e) { }
90         public void windowDeactivated(WindowEvent e) { }
91         public void windowDeiconified(WindowEvent e) { }
92         public void windowIconified(WindowEvent e) { }
93         public void windowOpened(WindowEvent e) { }
94         public void componentHidden(ComponentEvent e) { s.release(); }
95         public void componentMoved(ComponentEvent e) { }
96         public void componentResized(ComponentEvent e) { }
97         public void componentShown(ComponentEvent e) { }
98     };
99
100     protected String _fileDialog(String suggestedFileName, boolean write) {
101         final Semaphore s = new Semaphore();
102         FileDialogHelper fd = new FileDialogHelper(suggestedFileName, s, write);
103         s.block();
104         return fd.getDirectory() + File.separatorChar + fd.getFile();
105     }
106
107
108     // Inner Classes /////////////////////////////////////////////////////////////////////////////////////
109
110     protected static class AWTPicture implements Picture {
111         public int getHeight() { return i.getHeight(null); }
112         public int getWidth() { return i.getWidth(null); } 
113         public int[] getData() { return data; }
114
115         int[] data = null;
116         public Image i = null;
117         private static MediaTracker mediatracker = new MediaTracker(new Canvas());
118         private static ColorModel cmodel = new DirectColorModel(32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
119         
120         public AWTPicture(int[] b, int w, int h) {
121             data = b;
122             Image img = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, cmodel, b, 0, w));
123             mediatracker.addImage(img, 1);
124             try { mediatracker.waitForAll(); } catch (InterruptedException e) { }
125             mediatracker.removeImage(img);
126             this.i = img;
127         }
128     }
129     
130     protected static class AWTDoubleBuffer implements DoubleBuffer {
131         
132         protected Image i = null;
133         protected Graphics g = null;
134         
135         /** JDK1.1 platforms require that a component be associated with each off-screen buffer */
136         static Component component = null;
137
138         protected AWTDoubleBuffer() { }
139         public AWTDoubleBuffer(int w, int h) {
140             synchronized(AWTDoubleBuffer.class) {
141                 if (component == null) {
142                     component = new Frame();
143                     component.setVisible(false);
144                     component.addNotify();
145                 }
146             }
147             i = component.createImage(w, h);
148             g = i.getGraphics();
149         }
150         
151         public int getHeight() { return i == null ? 0 : i.getHeight(null); }
152         public int getWidth() { return i == null ? 0 : i.getWidth(null); }
153         public void setClip(int x, int y, int x2, int y2) { g.setClip(x, y, x2 - x, y2 - y); }
154
155         public void drawPicture(Picture source, int x, int y) {
156             drawPicture(source, x, y, x + source.getWidth(), y + source.getHeight(), 0, 0, source.getWidth(), source.getHeight());
157         }
158
159         public void drawPicture(Picture source, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) {
160             g.drawImage(((AWTPicture)source).i, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
161         }
162         
163         public void drawString(String font, String text, int x, int y, int argb) {
164             // FEATURE: use an LRU cache for Color objects
165             g.setColor(new Color((argb & 0x00FF0000) >> 16, (argb & 0x0000FF00) >> 8, (argb & 0x000000FF)));
166             g.setFont(getFont(font));
167             g.drawString(text, x, y + 2);
168         }
169         
170         public void fillRect(int x, int y, int x2, int y2, int argb) {
171             // FEATURE: use an LRU cache for Color objects
172             g.setColor(new Color((argb & 0x00FF0000) >> 16, (argb & 0x0000FF00) >> 8, (argb & 0x000000FF)));
173             g.fillRect(x, y, x2 - x, y2 - y);
174         }
175
176     }
177     
178     
179     protected static class AWTSurface extends Surface
180         implements MouseListener, MouseMotionListener, KeyListener, ComponentListener, WindowListener {
181
182         public void blit(DoubleBuffer s, int sx, int sy, int dx, int dy, int dx2, int dy2) {
183             if (ourGraphics == null) ourGraphics = window.getGraphics();
184             ourGraphics.drawImage(((AWTDoubleBuffer)s).i, dx + insets.left, dy + insets.top, dx2 + insets.left, dy2 + insets.top,
185                                   sx, sy, sx + (dx2 - dx), sy + (dy2 - dy), null);
186         }
187         
188         /** if (component instanceof Frame) then frame == window else frame == null */
189         Frame frame = null;
190         Window window = null;
191         
192         /** our component's insets */
193         protected Insets insets = new Insets(0, 0, 0, 0);
194         
195         /** a Graphics context on <code>window</code> */
196         protected Graphics ourGraphics = null;
197         
198         /** some JDKs let us recycle a single Dimension object when calling getSize() */
199         Dimension singleSize = new Dimension();
200         
201         public void toBack() { if (window != null) window.toBack(); }
202         public void toFront() { if (window != null) window.toFront(); }
203         public void setLocation(int x, int y) { window.setLocation(x, y); }
204         public void setTitleBarText(String s) { if (frame != null) frame.setTitle(s); }
205         public void setIcon(Picture i) { if (frame != null) frame.setIconImage(((AWTPicture)i).i); }
206         public void setSize(int width, int height) { window.setSize(width + (insets.left + insets.right), height + (insets.top + insets.bottom)); }
207         public void setInvisible(boolean b) { window.setVisible(!b); }
208         protected void _setMinimized(boolean b) { if (Log.on) Log.log(this, "JDK 1.1 platforms cannot minimize or unminimize windows"); }
209         protected void _setMaximized(boolean b) {
210             if (!b) {
211                 if (Log.on) Log.log(this, "JDK 1.1 platforms cannot unmaximize windows");
212                 return;
213             }
214             window.setLocation(new Point(0, 0));
215             window.setSize(Toolkit.getDefaultToolkit().getScreenSize());
216         }
217
218         class InnerFrame extends Frame {
219             public InnerFrame() throws java.lang.UnsupportedOperationException { }
220             public void update(Graphics gr) { paint(gr); }
221             public void paint(Graphics gr) {
222                 Rectangle r = gr.getClipBounds();
223
224                 // ugly hack for Java1.4 dynamicLayout on Win32 -- this catches expansions during smooth resize
225                 int newwidth = Math.max(r.x - insets.left + r.width, width);
226                 int newheight = Math.max(r.y - insets.top + r.height, height);
227                 if (newwidth > width || newheight > height)
228                     componentResized(window.getWidth() - insets.left - insets.right, window.getHeight() - insets.top - insets.bottom);
229
230                 Dirty(r.x - insets.left, r.y - insets.top, r.width, r.height);
231
232                 // this is safe because AWT's low-level drawing functions are threadsafe
233                 blitDirtyScreenRegions();
234             }
235         }
236
237         class InnerWindow extends Window {
238             public InnerWindow() throws java.lang.UnsupportedOperationException { super(new Frame()); }
239             public void update(Graphics gr) { paint(gr); }
240             public void paint(Graphics gr) {
241                 Rectangle r = gr.getClipBounds();
242                 Dirty(r.x - insets.left, r.y - insets.top, r.width, r.height);
243
244                 // this is safe because AWT's low-level drawing functions are threadsafe
245                 blitDirtyScreenRegions();
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             window.setVisible(true);
272
273         }
274         
275         public void _dispose() {
276             window.removeMouseListener(this);
277
278             // removed to work around a jdk1.3 bug
279             /* window.removeKeyListener(this); */
280
281             window.removeComponentListener(this);
282             window.removeMouseMotionListener(this);
283             window.removeWindowListener(this);
284             window.dispose();
285         }
286
287         public void syncCursor() {
288             if (cursor.equals("crosshair")) window.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
289             else if (cursor.equals("east")) window.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
290             else if (cursor.equals("move")) window.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
291             else if (cursor.equals("north")) window.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
292             else if (cursor.equals("northeast")) window.setCursor(Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR));
293             else if (cursor.equals("northwest")) window.setCursor(Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR));
294             else if (cursor.equals("south")) window.setCursor(Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
295             else if (cursor.equals("southeast")) window.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
296             else if (cursor.equals("southwest")) window.setCursor(Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
297             else if (cursor.equals("text")) window.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
298             else if (cursor.equals("west")) window.setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
299             else if (cursor.equals("wait")) window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
300             else if (cursor.equals("hand")) window.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
301             else window.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
302         }
303         
304         // AWT Message translation ////////////////////////////////////////////////////////////////
305         
306         // these functions are all executed in the AWT thread, not the
307         // MessageQueue thread. As a result, they must be *extremely*
308         // careful about invoking methods on instances of Box. Currently,
309         // they should only enqueue messages, use Box.whoIs()
310         // (unsynchronized but thought to be safe), and modify members of
311         // Surface.
312         
313         public void componentHidden(ComponentEvent e) { }
314         public void componentShown(ComponentEvent e) { }
315         public void windowOpened(WindowEvent e) { }
316         public void windowClosed(WindowEvent e) { }
317         public void windowClosing(WindowEvent e) { Close(); }
318         public void windowIconified(WindowEvent e) { Minimized(true); }
319         public void windowDeiconified(WindowEvent e) { dirty(0, 0, width, height); Minimized(false); }
320         public void windowActivated(WindowEvent e) { Focused(true); }
321         public void windowDeactivated(WindowEvent e) { Focused(false); }
322         public void componentMoved(ComponentEvent e) { PosChange(window.getLocation().x, window.getLocation().y); }
323
324         public void componentResized(ComponentEvent e) {
325             // we have to periodically do this; I don't know why
326             insets = window.getInsets();
327             componentResized(window.getWidth() - insets.left - insets.right, window.getHeight() - insets.top - insets.bottom);
328         }
329
330         public void componentResized(int newwidth, int newheight) {
331             int oldwidth = width;
332             int oldheight = height;
333             SizeChange(newwidth, newheight);
334
335             // we do this because JVMs which don't clear the background won't force repaints of these areas
336             root.dirty(Math.min(oldwidth, newwidth), 0, Math.abs(oldwidth - newwidth), Math.max(oldheight, newheight));
337             root.dirty(0, Math.min(oldheight, newheight), Math.max(oldwidth, newwidth), Math.abs(oldheight - newheight));
338
339             ourGraphics = null;
340         }
341         
342         public void keyTyped(KeyEvent k) { }
343         public void keyPressed(KeyEvent k) { KeyPressed(translateKey(k)); }
344         public void keyReleased(KeyEvent k) { KeyReleased(translateKey(k)); }
345         public void mouseExited(MouseEvent m) { mouseMoved(m); }
346         public void mouseEntered(MouseEvent m) { mouseMoved(m); }
347         public void mouseDragged(MouseEvent m) { mouseMoved(m); }
348         public void mouseMoved(MouseEvent m) {
349
350             // ugly hack for Java1.4 dynamicLayout on Win32 -- this catches contractions during smooth resize
351             int newwidth = window.getWidth() - insets.left - insets.right;
352             int newheight = window.getHeight() - insets.top - insets.bottom;
353             if (newwidth != width || newheight != height) componentResized(newwidth, newheight);
354             
355             Move(m.getX() - insets.left, m.getY() - insets.top);
356         }
357         public void mousePressed(MouseEvent m) { Press(modifiersToButtonNumber(m.getModifiers())); }
358         public void mouseReleased(MouseEvent m) { Release(modifiersToButtonNumber(m.getModifiers())); }
359         public void mouseClicked(MouseEvent m) {
360             if (m.getClickCount() == 2) DoubleClick(modifiersToButtonNumber(m.getModifiers()));
361             else Click(modifiersToButtonNumber(m.getModifiers()));
362         }
363         
364         String translateKey(KeyEvent k) {
365             switch (k.getKeyCode()) {
366             case KeyEvent.VK_ALT: return "alt";
367             case KeyEvent.VK_BACK_SPACE: return "back_space";
368             case KeyEvent.VK_CONTROL: return "control";
369             case KeyEvent.VK_DELETE: return "delete";
370             case KeyEvent.VK_DOWN: return "down";
371             case KeyEvent.VK_END: return "end";
372             case KeyEvent.VK_ENTER: return "enter";
373             case KeyEvent.VK_ESCAPE: return "escape";
374             case KeyEvent.VK_F1: return "f1";
375             case KeyEvent.VK_F10: return "f10";
376             case KeyEvent.VK_F11: return "f11";
377             case KeyEvent.VK_F12: return "f12";
378             case KeyEvent.VK_F2: return "f2";
379             case KeyEvent.VK_F3: return "f3";
380             case KeyEvent.VK_F4: return "f4";
381             case KeyEvent.VK_F5: return "f5";
382             case KeyEvent.VK_F6: return "f6";
383             case KeyEvent.VK_F7: return "f7";
384             case KeyEvent.VK_F8: return "f8";
385             case KeyEvent.VK_F9: return "f9";
386             case KeyEvent.VK_HOME: return "home";
387             case KeyEvent.VK_INSERT: return "insert";
388             case KeyEvent.VK_LEFT: return "left";
389             case KeyEvent.VK_META: return "alt";
390             case KeyEvent.VK_PAGE_DOWN: return "page_down";
391             case KeyEvent.VK_PAGE_UP: return "page_up";
392             case KeyEvent.VK_PAUSE: return "pause";
393             case KeyEvent.VK_PRINTSCREEN: return "printscreen";
394             case KeyEvent.VK_RIGHT: return "right";
395             case KeyEvent.VK_SHIFT: return "shift";
396             case KeyEvent.VK_TAB: return "tab";
397             case KeyEvent.VK_UP: return "up";
398             default:
399                 char c = k.getKeyChar();
400                 if (c >= 1 && c <= 26) c = (char)('a' + c - 1);
401                 return String.valueOf(c);
402             }
403         }
404     }
405
406     // Font Handling Stuff //////////////////////////////////////////////////////////
407
408     protected String[] _listFonts() { return fontList; }
409     private static String[] fontList;
410     static {
411         String[] awtfonts = Toolkit.getDefaultToolkit().getFontList();
412         fontList = new String[awtfonts.length * 4];
413         for(int i=0; i<awtfonts.length; i++) {
414             fontList[i * 4] = awtfonts[i] + "*";
415             fontList[i * 4 + 1] = awtfonts[i] + "*b";
416             fontList[i * 4 + 2] = awtfonts[i] + "*i";
417             fontList[i * 4 + 3] = awtfonts[i] + "*bi";
418         }
419     }
420
421     private static Hash fontCache = new Hash();
422     private static ParsedFont pf = new ParsedFont();
423     private static MetricatedFont getFont(String font) {
424         MetricatedFont ret = (MetricatedFont)fontCache.get(font);
425         if (ret == null) {
426             pf.parse(font);
427             if (pf.name.equals("tty")) pf.name = "monospace";
428             ret = new MetricatedFont(pf.name, (pf.bold ? Font.BOLD : 0) | (pf.italic ? Font.ITALIC : 0), pf.size);
429             fontCache.put(font, ret);
430         }
431         return ret;
432     }
433     
434     private static class MetricatedFont extends Font {
435         public FontMetrics metrics = null;
436         public MetricatedFont(String name, int size, int style) {
437             super(name, size, style);
438             metrics = Toolkit.getDefaultToolkit().getFontMetrics(this);
439         }
440     }
441             
442 }