2003/09/27 06:42:26
[org.ibex.core.git] / src / org / xwt / plat / AWT.java
index 6a55e92..e186789 100644 (file)
@@ -1,9 +1,8 @@
-// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
+// Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
 package org.xwt.plat;
 
 import org.xwt.*;
 import org.xwt.util.*;
-import org.mozilla.javascript.*;
 import java.net.*;
 import java.io.*;
 import java.util.*;
@@ -11,20 +10,42 @@ import java.awt.*;
 import java.awt.datatransfer.*;
 import java.awt.image.*;
 import java.awt.event.*;
-import java.applet.*;
 
 /** Platform subclass for all VM's providing AWT 1.1 functionality */
-public class AWT extends Platform {
+public class AWT extends JVM {
 
     protected String getDescriptiveName() { return "Generic JDK 1.1+ with AWT"; }
-    protected DoubleBuffer _createDoubleBuffer(int w, int h, Surface owner) { return new AWTDoubleBuffer(w, h); }
+    protected PixelBuffer _createPixelBuffer(int w, int h, Surface owner) { return new AWTPixelBuffer(w, h); }
     protected Picture _createPicture(int[] b, int w, int h) { return new AWTPicture(b, w, h); }
     protected int _getScreenWidth() { return Toolkit.getDefaultToolkit().getScreenSize().width; }
     protected int _getScreenHeight() { return Toolkit.getDefaultToolkit().getScreenSize().height; }
     protected Surface _createSurface(Box b, boolean framed) { return new AWTSurface(b, framed); }
-    protected int _stringWidth(String font, String text) { return getFont(font).metrics.stringWidth(text); }
-    protected int _getMaxAscent(String font) { return getFont(font).metrics.getMaxAscent(); }
-    protected int _getMaxDescent(String font) { return getFont(font).metrics.getMaxDescent(); }
+
+    protected void postInit() {
+        System.setProperty("com.apple.mrj.application.live-resize", "true");
+        System.setProperty("com.apple.mrj.application.growbox.intrudes", "false");
+        if (Log.on) Log.log(Platform.class, "               color depth = " + Toolkit.getDefaultToolkit().getColorModel().getPixelSize() + "bpp");
+    }
+
+    protected void _criticalAbort(String message) {
+        if (Log.on) Log.log(this, message);
+        final Dialog d = new Dialog(new Frame(), "XWT Cannot Continue");
+        d.setLayout(new BorderLayout());
+        TextArea ta = new TextArea("XWT cannot continue because:\n\n" + message, 10, 80);
+        ta.setEditable(false);
+        d.add(ta, "Center");
+        Button b = new Button("OK");
+        b.addActionListener(new ActionListener() {
+                public void actionPerformed(ActionEvent e) {
+                    d.dispose();
+                }
+            });
+        d.add(b, "South");
+        d.setModal(true);
+        d.pack();
+        d.show();
+        new Semaphore().block();
+    }
 
     protected String _getClipBoard() {
         Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
@@ -43,26 +64,70 @@ public class AWT extends Platform {
     /** some platforms (cough, cough, NetscapeVM) have totally broken modifier masks; they will need to override this */
     protected static int modifiersToButtonNumber(int modifiers) {
         if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) return 1;
-        if ((modifiers & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) return 3;
-        if ((modifiers & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) return 2;
+        if ((modifiers & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) {
+            // ugh, MacOSX reports the right mouse button as BUTTON2_MASK...
+            if (System.getProperty("os.name", "").startsWith("Mac OS X")) return 2;
+            return 3;
+        }
+        if ((modifiers & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
+            // ugh, MacOSX reports the right mouse button as BUTTON2_MASK...
+            if (System.getProperty("os.name", "").startsWith("Mac OS X")) return 3;
+            return 2;
+        }
         return 0;
     }
 
+    static class FileDialogHelper extends FileDialog implements WindowListener, ComponentListener {
+        Semaphore s;
+        public FileDialogHelper(String suggestedFileName, Semaphore s, boolean write) {
+            super(new Frame(), write ? "Save" : "Open", write ? FileDialog.SAVE : FileDialog.LOAD);
+            this.s = s;
+            addWindowListener(this);
+            addComponentListener(this);
+            if (suggestedFileName.indexOf(File.separatorChar) == -1) {
+                setFile(suggestedFileName);
+            } else {
+                setDirectory(suggestedFileName.substring(0, suggestedFileName.lastIndexOf(File.separatorChar)));
+                setFile(suggestedFileName.substring(suggestedFileName.lastIndexOf(File.separatorChar) + 1));
+            }
+            show();
+        }
+        public void windowActivated(WindowEvent e) { }
+        public void windowClosed(WindowEvent e) { s.release(); }
+        public void windowClosing(WindowEvent e) { }
+        public void windowDeactivated(WindowEvent e) { }
+        public void windowDeiconified(WindowEvent e) { }
+        public void windowIconified(WindowEvent e) { }
+        public void windowOpened(WindowEvent e) { }
+        public void componentHidden(ComponentEvent e) { s.release(); }
+        public void componentMoved(ComponentEvent e) { }
+        public void componentResized(ComponentEvent e) { }
+        public void componentShown(ComponentEvent e) { }
+    };
+
+    protected String _fileDialog(String suggestedFileName, boolean write) {
+        final Semaphore s = new Semaphore();
+        FileDialogHelper fd = new FileDialogHelper(suggestedFileName, s, write);
+        s.block();
+        return fd.getDirectory() == null ? null : (fd.getDirectory() + File.separatorChar + fd.getFile());
+    }
+
+
     // Inner Classes /////////////////////////////////////////////////////////////////////////////////////
 
-    protected static class AWTPicture implements Picture {
+    protected static class AWTPicture extends Picture {
         public int getHeight() { return i.getHeight(null); }
         public int getWidth() { return i.getWidth(null); } 
         public int[] getData() { return data; }
 
         int[] data = null;
         public Image i = null;
-        private static MediaTracker mediatracker = new MediaTracker(new Canvas());
         private static ColorModel cmodel = new DirectColorModel(32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
         
         public AWTPicture(int[] b, int w, int h) {
             data = b;
             Image img = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, cmodel, b, 0, w));
+            MediaTracker mediatracker = new MediaTracker(new Canvas());
             mediatracker.addImage(img, 1);
             try { mediatracker.waitForAll(); } catch (InterruptedException e) { }
             mediatracker.removeImage(img);
@@ -70,20 +135,23 @@ public class AWT extends Platform {
         }
     }
     
-    protected static class AWTDoubleBuffer implements DoubleBuffer {
+    protected static class AWTPixelBuffer extends PixelBuffer {
         
         protected Image i = null;
         protected Graphics g = null;
         
         /** JDK1.1 platforms require that a component be associated with each off-screen buffer */
         static Component component = null;
-        static {
-             component = new Frame();
-             component.setVisible(false);
-             component.addNotify();
-        }
 
-        public AWTDoubleBuffer(int w, int h) {
+        protected AWTPixelBuffer() { }
+        public AWTPixelBuffer(int w, int h) {
+            synchronized(AWTPixelBuffer.class) {
+                if (component == null) {
+                    component = new Frame();
+                    component.setVisible(false);
+                    component.addNotify();
+                }
+            }
             i = component.createImage(w, h);
             g = i.getGraphics();
         }
@@ -100,28 +168,38 @@ public class AWT extends Platform {
             g.drawImage(((AWTPicture)source).i, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
         }
         
-        public void drawString(String font, String text, int x, int y, int argb) {
-            // FEATURE: use an LRU cache for Color objects
-            g.setColor(new Color((argb & 0x00FF0000) >> 16, (argb & 0x0000FF00) >> 8, (argb & 0x000000FF)));
-            g.setFont(getFont(font));
-            g.drawString(text, x, y + 2);
-        }
-        
         public void fillRect(int x, int y, int x2, int y2, int argb) {
             // FEATURE: use an LRU cache for Color objects
-            g.setColor(new Color((argb & 0x00FF0000) >> 16, (argb & 0x0000FF00) >> 8, (argb & 0x000000FF)));
-            g.fillRect(x, y, x2 - x, y2 - y);
         }
 
+        // FIXME: try to use os acceleration
+        public void fillTrapezoid(int x1, int x2, int y1, int x3, int x4, int y2, int argb) {
+            g.setColor(new Color((argb & 0x00FF0000) >> 16, (argb & 0x0000FF00) >> 8, (argb & 0x000000FF)));
+            if (x1 == x3 && x2 == x4) {
+                g.fillRect(x1, y1, x4 - x1, y2 - y1);
+            } else for(int y=y1; y<y2; y++) {
+                int _x1 = (int)Math.floor((y - y1) * (x3 - x1) / (y2 - y1) + x1);
+                int _y1 = (int)Math.floor(y);
+                int _x2 = (int)Math.ceil((y - y1) * (x4 - x2) / (y2 - y1) + x2);
+                int _y2 = (int)Math.floor(y) + 1;
+                if (_x1 > _x2) { int _x0 = _x1; _x1 = _x2; _x2 = _x0; }
+                g.fillRect(_x1, _y1, _x2 - _x1, _y2 - _y1);
+            }
+        }
     }
     
     
-    protected static class AWTSurface extends Surface
+    protected static class AWTSurface extends Surface.DoubleBufferedSurface
         implements MouseListener, MouseMotionListener, KeyListener, ComponentListener, WindowListener {
 
-        public void blit(DoubleBuffer s, int sx, int sy, int dx, int dy, int dx2, int dy2) {
+        public void blit(PixelBuffer s, int sx, int sy, int dx, int dy, int dx2, int dy2) {
             if (ourGraphics == null) ourGraphics = window.getGraphics();
-            ourGraphics.drawImage(((AWTDoubleBuffer)s).i, dx + insets.left, dy + insets.top, dx2 + insets.left, dy2 + insets.top,
+            insets = (frame == null ? window : frame).getInsets();
+            ourGraphics.drawImage(((AWTPixelBuffer)s).i,
+                                  dx + insets.left,
+                                  dy + insets.top,
+                                  dx2 + insets.left,
+                                  dy2 + insets.top,
                                   sx, sy, sx + (dx2 - dx), sy + (dy2 - dy), null);
         }
         
@@ -140,7 +218,7 @@ public class AWT extends Platform {
         
         public void toBack() { if (window != null) window.toBack(); }
         public void toFront() { if (window != null) window.toFront(); }
-        public void setLocation(int x, int y) { window.setLocation(x, y); }
+        public void setLocation() { window.setLocation(root.x, root.y); }
         public void setTitleBarText(String s) { if (frame != null) frame.setTitle(s); }
         public void setIcon(Picture i) { if (frame != null) frame.setIconImage(((AWTPicture)i).i); }
         public void setSize(int width, int height) { window.setSize(width + (insets.left + insets.right), height + (insets.top + insets.bottom)); }
@@ -154,22 +232,45 @@ public class AWT extends Platform {
             window.setLocation(new Point(0, 0));
             window.setSize(Toolkit.getDefaultToolkit().getScreenSize());
         }
-        
+
+        class InnerFrame extends Frame {
+            public InnerFrame() throws java.lang.UnsupportedOperationException { }
+            public void update(Graphics gr) { paint(gr); }
+            public void paint(Graphics gr) {
+                Rectangle r = gr.getClipBounds();
+
+                // ugly hack for Java1.4 dynamicLayout on Win32 -- this catches expansions during smooth resize
+                int newwidth = Math.max(r.x - insets.left + r.width, root.width);
+                int newheight = Math.max(r.y - insets.top + r.height, root.height);
+                if (newwidth > root.width || newheight > root.height)
+                    componentResized(window.getWidth() - insets.left - insets.right, window.getHeight() - insets.top - insets.bottom);
+
+                Dirty(r.x - insets.left, r.y - insets.top, r.width, r.height);
+            }
+        }
+
+        class InnerWindow extends Window {
+            public InnerWindow() throws java.lang.UnsupportedOperationException { super(new Frame()); }
+            public void update(Graphics gr) { paint(gr); }
+            public void paint(Graphics gr) {
+                Rectangle r = gr.getClipBounds();
+                Dirty(r.x - insets.left, r.y - insets.top, r.width, r.height);
+            }
+        }
+
         AWTSurface(Box root, boolean framed) {
             super(root);
-            
-            if (framed) window = frame = new Frame() {
-                    public void update(Graphics gr) { paint(gr); }
-                    public void paint(Graphics gr) {
-                        Rectangle r = gr.getClipBounds();
-                        Dirty(r.x - insets.left, r.y - insets.top, r.width, r.height);
-                    } };
-            else window = new Window(new Frame()) {
-                    public void update(Graphics gr) { paint(gr); }
-                    public void paint(Graphics gr) {
-                        Rectangle r = gr.getClipBounds();
-                        Dirty(r.x - insets.left, r.y - insets.top, r.width, r.height);
-                    } };
+            try {
+                if (framed) window = frame = new InnerFrame();
+                else window = new InnerWindow();
+
+            // this is here to catch HeadlessException on jdk1.4
+            } catch (java.lang.UnsupportedOperationException e) {
+                if (Log.on) Log.log(this, "Exception thrown in AWTSurface$InnerFrame() -- this should never happen");
+                if (Log.on) Log.log(this, e);
+            }
+
+            insets = window.getInsets();
             
             window.addMouseListener(this);
             window.addKeyListener(this);
@@ -179,10 +280,10 @@ public class AWT extends Platform {
 
             // IMPORTANT: this must be called before render() to ensure
             // that our peer has been created
-            window.setVisible(true);
-
-            insets = window.getInsets();
+            makeVisible();
         }
+
+        protected void makeVisible() { window.setVisible(true); }
         
         public void _dispose() {
             window.removeMouseListener(this);
@@ -228,24 +329,44 @@ public class AWT extends Platform {
         public void windowClosed(WindowEvent e) { }
         public void windowClosing(WindowEvent e) { Close(); }
         public void windowIconified(WindowEvent e) { Minimized(true); }
-        public void windowDeiconified(WindowEvent e) { dirty(0, 0, width, height); Minimized(false); }
+        public void windowDeiconified(WindowEvent e) { dirty(0, 0, root.width, root.height); Minimized(false); }
         public void windowActivated(WindowEvent e) { Focused(true); }
         public void windowDeactivated(WindowEvent e) { Focused(false); }
-        public void componentMoved(ComponentEvent e) { PosChange(window.getLocation().x, window.getLocation().y); }
+        public void componentMoved(ComponentEvent e) { PosChange(window.getLocation().x + insets.left, window.getLocation().y + insets.top); }
+
         public void componentResized(ComponentEvent e) {
             // we have to periodically do this; I don't know why
             insets = window.getInsets();
-            SizeChange(window.getWidth(), window.getHeight());
+            componentResized(window.getWidth() - insets.left - insets.right, window.getHeight() - insets.top - insets.bottom);
+        }
+
+        public void componentResized(int newwidth, int newheight) {
+            int oldwidth = root.width;
+            int oldheight = root.height;
+            SizeChange(newwidth, newheight);
+
+            // we do this because JVMs which don't clear the background won't force repaints of these areas
+            root.dirty(Math.min(oldwidth, newwidth), 0, Math.abs(oldwidth - newwidth), Math.max(oldheight, newheight));
+            root.dirty(0, Math.min(oldheight, newheight), Math.max(oldwidth, newwidth), Math.abs(oldheight - newheight));
+
             ourGraphics = null;
         }
-        
+
         public void keyTyped(KeyEvent k) { }
         public void keyPressed(KeyEvent k) { KeyPressed(translateKey(k)); }
         public void keyReleased(KeyEvent k) { KeyReleased(translateKey(k)); }
         public void mouseExited(MouseEvent m) { mouseMoved(m); }
         public void mouseEntered(MouseEvent m) { mouseMoved(m); }
         public void mouseDragged(MouseEvent m) { mouseMoved(m); }
-        public void mouseMoved(MouseEvent m) { Move(m.getX() - insets.left, m.getY() - insets.top); }
+        public void mouseMoved(MouseEvent m) {
+
+            // ugly hack for Java1.4 dynamicLayout on Win32 -- this catches contractions during smooth resize
+            int newwidth = window.getWidth() - insets.left - insets.right;
+            int newheight = window.getHeight() - insets.top - insets.bottom;
+            if (newwidth != root.width || newheight != root.height) componentResized(newwidth, newheight);
+            
+            Move(m.getX() - insets.left, m.getY() - insets.top);
+        }
         public void mousePressed(MouseEvent m) { Press(modifiersToButtonNumber(m.getModifiers())); }
         public void mouseReleased(MouseEvent m) { Release(modifiersToButtonNumber(m.getModifiers())); }
         public void mouseClicked(MouseEvent m) {
@@ -271,7 +392,7 @@ public class AWT extends Platform {
             case KeyEvent.VK_F3: return "f3";
             case KeyEvent.VK_F4: return "f4";
             case KeyEvent.VK_F5: return "f5";
-            case KeyEvent.VK_F6: return "f6";
+            case KeyEvent.VK_F6: return "f6"; 
             case KeyEvent.VK_F7: return "f7";
             case KeyEvent.VK_F8: return "f8";
             case KeyEvent.VK_F9: return "f9";
@@ -287,73 +408,35 @@ public class AWT extends Platform {
             case KeyEvent.VK_SHIFT: return "shift";
             case KeyEvent.VK_TAB: return "tab";
             case KeyEvent.VK_UP: return "up";
-
-            // we special-case letters since (C-a).getKeyChar() != 'a'
-            case KeyEvent.VK_A: return "a";
-            case KeyEvent.VK_B: return "b";
-            case KeyEvent.VK_C: return "c";
-            case KeyEvent.VK_D: return "d";
-            case KeyEvent.VK_E: return "e";
-            case KeyEvent.VK_F: return "f";
-            case KeyEvent.VK_G: return "g";
-            case KeyEvent.VK_H: return "h";
-            case KeyEvent.VK_I: return "i";
-            case KeyEvent.VK_J: return "j";
-            case KeyEvent.VK_K: return "k";
-            case KeyEvent.VK_L: return "l";
-            case KeyEvent.VK_M: return "m";
-            case KeyEvent.VK_N: return "n";
-            case KeyEvent.VK_O: return "o";
-            case KeyEvent.VK_P: return "p";
-            case KeyEvent.VK_Q: return "q";
-            case KeyEvent.VK_R: return "r";
-            case KeyEvent.VK_S: return "s";
-            case KeyEvent.VK_T: return "t";
-            case KeyEvent.VK_U: return "u";
-            case KeyEvent.VK_V: return "v";
-            case KeyEvent.VK_W: return "w";
-            case KeyEvent.VK_X: return "x";
-            case KeyEvent.VK_Y: return "y";
-            case KeyEvent.VK_Z: return "z";
-            default: return String.valueOf(k.getKeyChar());
+            default:
+                char c = k.getKeyChar();
+                if (c >= 1 && c <= 26) c = (char)('a' + c - 1);
+                return String.valueOf(c);
             }
         }
     }
 
-    // Font Handling Stuff //////////////////////////////////////////////////////////
-
-    protected String[] _listFonts() { return fontList; }
-    private static String[] fontList;
-    static {
-        String[] awtfonts = Toolkit.getDefaultToolkit().getFontList();
-        fontList = new String[awtfonts.length * 4];
-        for(int i=0; i<awtfonts.length; i++) {
-            fontList[i * 4] = awtfonts[i] + "*";
-            fontList[i * 4 + 1] = awtfonts[i] + "*b";
-            fontList[i * 4 + 2] = awtfonts[i] + "*i";
-            fontList[i * 4 + 3] = awtfonts[i] + "*bi";
-        }
-    }
-
-    private static Hash fontCache = new Hash();
-    private static ParsedFont pf = new ParsedFont();
-    private static MetricatedFont getFont(String font) {
-        MetricatedFont ret = (MetricatedFont)fontCache.get(font);
-        if (ret == null) {
-            pf.parse(font);
-            if (pf.name.equals("tty")) pf.name = "monospace";
-            ret = new MetricatedFont(pf.name, (pf.bold ? Font.BOLD : 0) | (pf.italic ? Font.ITALIC : 0), pf.size);
-            fontCache.put(font, ret);
-        }
-        return ret;
-    }
-    
-    private static class MetricatedFont extends Font {
-        public FontMetrics metrics = null;
-        public MetricatedFont(String name, int size, int style) {
-            super(name, size, style);
-            metrics = Toolkit.getDefaultToolkit().getFontMetrics(this);
+    protected Picture _decodeJPEG(InputStream is, String name) {
+        try {
+            Image i = Toolkit.getDefaultToolkit().createImage(InputStreamToByteArray.convert(is));
+            MediaTracker mediatracker = new MediaTracker(new Canvas());
+            mediatracker.addImage(i, 1);
+            try { mediatracker.waitForAll(); } catch (InterruptedException e) { }
+            mediatracker.removeImage(i);
+            final int width = i.getWidth(null);
+            final int height = i.getHeight(null);
+            final int[] data = new int[width * height];
+            PixelGrabber pg = new PixelGrabber(i, 0, 0, width, height, data, 0, width);
+            pg.grabPixels();
+            if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
+                Log.log(this, "PixelGrabber reported an error while decoding JPEG image " + name);
+                return null;
+            }
+            return Platform.createPicture(data, width, height);
+        } catch (Exception e) {
+            Log.log(this, "Exception caught while decoding JPEG image " + name);
+            Log.log(this, e);
+            return null;
         }
     }
-            
 }