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