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