2003/03/29 22:16:22
[org.ibex.core.git] / src / org / xwt / plat / Java2.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt.plat;
3
4 import java.awt.*;
5 import java.awt.event.*;
6 import java.awt.image.*;
7 import java.awt.datatransfer.*;
8 import java.net.*;
9 import java.io.*;
10 import java.util.*;
11 import org.xwt.util.*;
12 import org.xwt.*;
13 import java.lang.reflect.*;
14
15
16 /** Platform class for most reasonable Java1.2+ Java2s */
17 public class Java2 extends AWT {
18
19     private boolean isJava14 = false;
20     protected boolean _supressDirtyOnResize() { return isJava14 ? false : true; }
21
22     public Java2() {
23         // disable the focus manager so we can intercept the tab key
24         String versionString = System.getProperty("java.version", "");
25         int secondDecimal = versionString.substring(versionString.indexOf('.') + 1).indexOf('.');
26         if (secondDecimal != -1) versionString = versionString.substring(0, secondDecimal);
27         double version = Double.parseDouble(versionString);
28         if (version >= 1.4) {
29             isJava14 = true;
30             try {
31                 Toolkit t = java.awt.Toolkit.getDefaultToolkit();
32                 Method m = java.awt.Toolkit.class.getMethod("setDynamicLayout", new Class[] { Boolean.class });
33                 m.invoke(t, new Object[] { Boolean.TRUE });
34             } catch (Exception e) {
35                 Log.log(this, "Exception while trying to enable AWT Dynamic Layout");
36                 Log.log(this, e);
37             }
38         }
39         javax.swing.FocusManager.setCurrentManager(new javax.swing.FocusManager() {
40                 public void processKeyEvent(Component focusedComponent, KeyEvent anEvent) { }
41                 public void focusPreviousComponent(Component aComponent) { }
42                 public void focusNextComponent(Component aComponent) { }
43             });
44     }
45
46     /** this is done with reflection in case a new version of the plugin comes out that doesn't let us pull the sun.plugin.* trick */
47     protected synchronized org.xwt.Proxy _detectProxy() {
48         return (org.xwt.Proxy)java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
49                 public Object run() {
50                     try {
51                         org.xwt.Proxy pi = new org.xwt.Proxy();
52                         
53                         Class PluginProxyHandler = Class.forName("sun.plugin.protocol.PluginProxyHandler");
54                         Method getDefaultProxyHandler = PluginProxyHandler.getMethod("getDefaultProxyHandler", new Class[] { });
55                         Object proxyHandler = getDefaultProxyHandler.invoke(null, new Object[] { });
56                         
57                         Class ProxyHandler = Class.forName("sun.plugin.protocol.ProxyHandler");
58                         Method getProxyInfo = ProxyHandler.getMethod("getProxyInfo", new Class[] { URL.class });
59                         Object proxyInfo = getProxyInfo.invoke(proxyHandler, new Object[] { new URL("http://www.xwt.org") });
60                         
61                         Class ProxyInfo = Class.forName("sun.plugin.protocol.ProxyInfo");
62                         
63                         if (((Boolean)ProxyInfo.getMethod("isSocksUsed", new Class[] { }).invoke(proxyInfo, new Object[] { })).booleanValue()) {
64                             pi.socksProxyHost =
65                                 (String)ProxyInfo.getMethod("getSocksProxy", new Class[] { }).invoke(proxyInfo, new Object[] { });
66                             pi.socksProxyPort =
67                                 ((Integer)ProxyInfo.getMethod("getSocksPort", new Class[] { }).invoke(proxyInfo, new Object[] { })).intValue();
68                         }
69                         
70                         if (((Boolean)ProxyInfo.getMethod("isProxyUsed", new Class[] { }).invoke(proxyInfo, new Object[] { })).booleanValue()) {
71                             pi.httpProxyHost =
72                                 (String)ProxyInfo.getMethod("getProxy", new Class[] { }).invoke(proxyInfo, new Object[] { });
73                             pi.httpProxyPort =
74                                 ((Integer)ProxyInfo.getMethod("getPort", new Class[] { }).invoke(proxyInfo, new Object[] { })).intValue();
75                         }
76                         
77                         if (pi.httpProxyHost != null || pi.socksProxyHost != null) return pi;
78                         else return null;
79
80                     } catch (Throwable e) {
81                         if (Log.on) Log.log(this, "exception while querying sun.plugin.protocol.PluginProxyHandler: " + e);
82                         return null;
83                     }
84                 }});
85     }
86
87     protected Socket __getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
88         return super._getSocket(host, port, ssl, negotiate);
89     }
90     protected Socket _getSocket(final String host, final int port, final boolean ssl, final boolean negotiate) throws IOException {
91         return (Socket)java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
92                 public Object run() {
93                     try {
94                         return __getSocket(host, port, ssl, negotiate);
95                     } catch (Exception e) {
96                         if (Log.on) Log.log(Java2.class, "Error attempting to create socket");
97                         if (Log.on) Log.log(Java2.class, e);
98                         return null;
99                     }
100                 }
101             });
102     }
103     
104     protected DoubleBuffer _createDoubleBuffer(int w, int h, Surface owner) { return new Java2DoubleBuffer(w, h); }
105     protected Surface _createSurface(final Box root, final boolean framed) {
106         return (Surface)java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
107                 public Object run() {
108                     if (isJava14) {
109                         try {
110                              // weaken the binding here to avoid link errors on 1.3.x
111                              Class java14SurfaceClass = Class.forName(Java2.class.getName() + "$Java14Surface");
112                              Constructor ctor = java14SurfaceClass.getConstructor(new Class[] { Box.class, Boolean.TYPE });
113                              return (Surface)ctor.newInstance(new Object[] { root, new Boolean(framed) });
114                         } catch (Exception e) {
115                             Log.log(this, e);
116                             throw new LinkageError("error: " + e);
117                         }
118                     } else {
119                         return new Java2Surface(root, framed);
120                     }
121                 }
122             });
123     }
124
125     // Inner Classes //////////////////////////////////////////////////////////////////
126
127     private static Cursor invisibleCursor =
128         Toolkit.getDefaultToolkit().createCustomCursor(new BufferedImage(2, 2, BufferedImage.TYPE_INT_ARGB),
129                                                        new Point(1, 1), "invisible");
130
131     protected static class Java2Surface extends AWTSurface {
132         
133         public Java2Surface(Box root, boolean framed) { super(root, framed); }
134
135         public void blit(DoubleBuffer s, int sx, int sy, int dx, int dy, int dx2, int dy2) {
136             if (ourGraphics == null) {
137                 ourGraphics = window.getGraphics();
138
139                 // sometimes jdk1.4 doesn't set the clip properly when we're in the middle of a resize
140                 ourGraphics.setClip(insets.left, insets.top, width + insets.left, height + insets.top);
141             }
142             _doDrawImage(ourGraphics, ((AWTDoubleBuffer)s).i, dx + insets.left, dy + insets.top, dx2 + insets.left, dy2 + insets.top,
143                          sx, sy, sx + (dx2 - dx), sy + (dy2 - dy), null);
144         }
145
146         protected void _setMinimized(boolean b) {
147             if (frame == null) {
148                 if (Log.on) Log.log(this, "JDK 1.2 can only minimize frames, not windows");
149                 return;
150             }
151             if (b) frame.setState(java.awt.Frame.ICONIFIED);
152             else frame.setState(java.awt.Frame.NORMAL);
153         }
154
155         public void syncCursor() {
156             if (cursor.equals("invisible")) window.setCursor(invisibleCursor);
157             else super.syncCursor();
158         }
159     }
160
161     protected static class Java14Surface extends Java2Surface implements WindowStateListener {
162         public Java14Surface(Box root, boolean framed) {
163             super(root, true);
164             // JDK1.4 doesn't like java.lang.Window's...
165             if (!framed) ((Frame)window).setUndecorated(true);
166             window.addWindowStateListener(this);
167             window.setVisible(true);
168         }
169
170         protected void makeVisible() { }
171         
172         protected void _setMaximized(boolean m) {
173             if (frame == null) {
174                 if (Log.on) Log.log(this, "JDK 1.4 can only maximize frames, not windows");
175                 return;
176             }
177             frame.setExtendedState(m ? Frame.MAXIMIZED_BOTH : (minimized ? Frame.ICONIFIED : Frame.NORMAL));
178         }
179         protected void _setMinimized(boolean m) {
180             if (frame == null) {
181                 if (Log.on) Log.log(this, "JDK 1.4 can only minimize frames, not windows");
182                 return;
183             }
184             frame.setExtendedState(m ? Frame.ICONIFIED : (maximized ? Frame.MAXIMIZED_BOTH : Frame.NORMAL));
185         }
186         public void windowStateChanged(WindowEvent e) {
187             if (e.getOldState() != e.getNewState()) {
188                 if ((e.getNewState() & Frame.MAXIMIZED_BOTH) != 0) Maximized(true);
189                 else if (((e.getOldState() & Frame.MAXIMIZED_BOTH) != 0) && (e.getNewState() & Frame.MAXIMIZED_BOTH) == 0)
190                     Maximized(false);
191             }
192         }
193     }
194
195     protected static class Java2DoubleBuffer extends AWTDoubleBuffer {
196         private static ColorModel cm = Toolkit.getDefaultToolkit().getColorModel();
197         private static Hashtable emptyHashtable = new Hashtable();
198         private static short[] sbank = null;
199         private static int[] ibank = null;
200         private static byte[] bbank = null;
201         private static int bank_start = 0;
202         
203         public void drawPicture(Picture source, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) {
204             _doDrawImage(g, ((AWTPicture)source).i, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
205         }
206         
207         public Java2DoubleBuffer(int w, int h) {
208             SampleModel sm = cm.createCompatibleSampleModel(w, h);
209             int numSamples = w * h * sm.getNumDataElements();
210             DataBuffer buf = null;
211             if (sm.getDataType() == DataBuffer.TYPE_USHORT) {
212                 if (sbank == null || numSamples > 512 * 512 / 3) {
213                     buf = new DataBufferUShort(numSamples);
214                 } else {
215                     if (numSamples > sbank.length - bank_start) {
216                         bank_start = 0;
217                         sbank = new short[512 * 512];
218                     }
219                     buf = new DataBufferUShort(sbank, numSamples, bank_start);
220                     bank_start += numSamples;
221                 }
222             } else if (sm.getDataType() == DataBuffer.TYPE_BYTE) {
223                 if (bbank == null || numSamples > 512 * 512 / 3) {
224                     buf = new DataBufferByte(numSamples);
225                 } else {
226                     if (numSamples > bbank.length - bank_start) {
227                         bank_start = 0;
228                         bbank = new byte[512 * 512];
229                     }
230                     buf = new DataBufferByte(bbank, numSamples, bank_start);
231                     bank_start += numSamples;
232                 }
233             } else if (sm.getDataType() == DataBuffer.TYPE_INT) {
234                 if (ibank == null || numSamples > 512 * 512 / 3) {
235                     buf = new DataBufferInt(numSamples);
236                 } else {
237                     if (numSamples > ibank.length - bank_start) {
238                         bank_start = 0;
239                         ibank = new int[512 * 512];
240                     }
241                     buf = new DataBufferInt(ibank, numSamples, bank_start);
242                     bank_start += numSamples;
243                 }
244             }
245             i = new BufferedImage(cm, Raster.createWritableRaster(sm, buf, null), false,  emptyHashtable);
246             g = i.getGraphics();
247         }
248     }
249
250     /** used to avoid garbage creation with getClipBounds() */
251     private static Rectangle clipBounds = new Rectangle();
252     
253     protected static void _doDrawImage(Graphics g, Image i, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver o) {
254         if (dx1 == dx2 || dy1 == dy2) return;
255         g.drawImage(i, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, o);
256     }
257
258     protected org.xwt.Weak _getWeak(Object o) { return new Java2Weak(o); }
259     private static class Java2Weak extends java.lang.ref.WeakReference implements org.xwt.Weak {
260         public Java2Weak(Object o) { super(o); }
261     }
262
263     private String __getClipBoard() { return super._getClipBoard(); }
264     protected String _getClipBoard() {
265         return (String)java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
266                 public Object run() { return __getClipBoard();  }
267             });
268     }
269
270     private void __setClipBoard(String s) { super._setClipBoard(s); }
271     protected void _setClipBoard(final String s) {
272         java.security.AccessController.doPrivileged(new java.security.PrivilegedAction() {
273                 public Object run() {
274                     __setClipBoard(s);
275                     return null;
276                 }
277             });
278     }
279
280     protected String getDescriptiveName() { return isJava14 ? "Java 1.4+ JVM" : "Java 1.2+ JVM"; }
281
282     protected void _newBrowserWindow(String url) {
283         if (Main.applet == null) {
284             if (Log.on) Log.log(this, "Main.applet is null; cannot invoke showDocument()");
285             return;
286         }
287         if (Log.on) Log.log(this, "asking browser to show URL " + url);
288         try {
289             Main.applet.getAppletContext().showDocument(new URL(url), "_blank");
290         } catch (MalformedURLException e) {
291             if (Log.on) Log.log(this, e);
292         }
293     }
294
295 }