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