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