f8766ba90f89194a646733fb9193b70e552607c6
[org.ibex.core.git] / src / org / xwt / plat / POSIX.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [LGPL]
2 package org.xwt.plat;
3
4 import java.awt.*;
5 import java.awt.image.*;
6 import gnu.gcj.RawData;
7 import java.net.*;
8 import java.lang.reflect.*;
9 import java.io.*;
10 import java.util.*;
11 import java.awt.peer.*;
12 import org.xwt.util.*;
13 import org.xwt.*;
14
15 /** Platform implementation for POSIX compliant operating systems with an X11 Server */
16 public class POSIX extends GCJ {
17
18     // Static Data ///////////////////////////////////////////////////////////
19
20     /**
21      *  When the user reads from the clipboard, the main thread blocks
22      *  on this semaphore until we get an X11 SelectionNotify. Crude,
23      *  but effective. We know that only one thread will ever block on
24      *  this, since only one thread can ever be running JavaScript.
25      */
26     public static Semaphore waiting_for_selection_event = new Semaphore();
27
28     /** our local (in-process) copy of the clipboard */
29     public static String clipboard = null;
30
31     /** map from Window's (casted to jlong, wrapped in java.lang.Long) to X11Surface objects */
32     public static Hashtable windowToSurfaceMap = new Hashtable();
33
34
35     // General Methods ///////////////////////////////////////////////////////
36
37     protected String _getAltKeyName() { return System.getProperty("os.name", "").indexOf("SunOS") != -1 ? "Meta" : "Alt"; }
38     protected String[] _listFonts() { return fontList; }
39     protected String getDescriptiveName() { return "GCJ Linux Binary"; }
40     protected Picture _createPicture(int[] data, int w, int h) { return new POSIX.X11Picture(data, w, h); }
41     protected DoubleBuffer _createDoubleBuffer(int w, int h, Surface owner) { return new POSIX.X11DoubleBuffer(w, h); }
42     protected Surface _createSurface(Box b, boolean framed) { return new X11Surface(b, framed); }
43     protected boolean _needsAutoClick() { return true; }
44     protected native int _getScreenWidth();
45     protected native int _getScreenHeight();
46     protected native String _getClipBoard();
47     protected native void _setClipBoard(String s);
48     protected native int _stringWidth(String font, String text);
49     protected native int _getMaxAscent(String font);
50     protected native int _getMaxDescent(String font);
51     protected boolean _needsAutoDoubleClick() { return true; }
52     protected native void eventThread();
53     private native void natInit();
54
55     /** returns the $BROWSER environment variable, since System.getEnv() is useless */
56     private static native String getEnv(String key);
57
58     /** spawns a process which is immune to SIGHUP */
59     private static native void spawnChildProcess(String[] command);
60
61     protected synchronized HTTP.ProxyInfo _detectProxy() {
62
63         HTTP.ProxyInfo ret = new HTTP.ProxyInfo();
64
65         ret.httpProxyHost = getEnv("http_proxy");
66         if (ret.httpProxyHost != null) {
67             if (ret.httpProxyHost.startsWith("http://")) ret.httpProxyHost = ret.httpProxyHost.substring(7);
68             if (ret.httpProxyHost.endsWith("/")) ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.length() - 1);
69             if (ret.httpProxyHost.indexOf(':') != -1) {
70                 ret.httpProxyPort = Integer.parseInt(ret.httpProxyHost.substring(ret.httpProxyHost.indexOf(':') + 1));
71                 ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.indexOf(':'));
72             } else {
73                 ret.httpProxyPort = 80;
74             }
75         }
76
77         ret.httpsProxyHost = getEnv("https_proxy");
78         if (ret.httpsProxyHost != null) {
79             if (ret.httpsProxyHost.startsWith("https://")) ret.httpsProxyHost = ret.httpsProxyHost.substring(7);
80             if (ret.httpsProxyHost.endsWith("/")) ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.length() - 1);
81             if (ret.httpsProxyHost.indexOf(':') != -1) {
82                 ret.httpsProxyPort = Integer.parseInt(ret.httpsProxyHost.substring(ret.httpsProxyHost.indexOf(':') + 1));
83                 ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.indexOf(':'));
84             } else {
85                 ret.httpsProxyPort = 80;
86             }
87         }
88
89         ret.socksProxyHost = getEnv("socks_proxy");
90         if (ret.socksProxyHost != null) {
91             if (ret.socksProxyHost.startsWith("socks://")) ret.socksProxyHost = ret.socksProxyHost.substring(7);
92             if (ret.socksProxyHost.endsWith("/")) ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.length() - 1);
93             if (ret.socksProxyHost.indexOf(':') != -1) {
94                 ret.socksProxyPort = Integer.parseInt(ret.socksProxyHost.substring(ret.socksProxyHost.indexOf(':') + 1));
95                 ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.indexOf(':'));
96             } else {
97                 ret.socksProxyPort = 80;
98             }
99         }
100
101         String noproxy = getEnv("no_proxy");
102         if (noproxy != null) {
103             StringTokenizer st = new StringTokenizer(noproxy, ",");
104             ret.excluded = new String[st.countTokens()];
105             for(int i=0; st.hasMoreTokens(); i++) ret.excluded[i] = st.nextToken();
106         }
107
108         if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
109         return ret;
110     }
111
112     protected void _newBrowserWindow(String url) {
113         String browserString = getEnv("BROWSER");
114         if (browserString == null) {
115             browserString = "netscape " + url;
116         } else if (browserString.indexOf("%s") != -1) {
117             browserString =
118                 browserString.substring(0, browserString.indexOf("%s")) +
119                 url + browserString.substring(browserString.indexOf("%s") + 2);
120         } else {
121             browserString += " " + url;
122         }
123
124         StringTokenizer st = new StringTokenizer(browserString, " ");
125         String[] cmd = new String[st.countTokens()];
126         for(int i=0; st.hasMoreTokens(); i++) {
127             cmd[i] = st.nextToken();
128             System.out.println(i + ":" + cmd[i]);
129         }
130
131         spawnChildProcess(cmd);
132     }
133
134     public POSIX() { }
135     public void init() {
136         natInit();
137         (new Thread() { public void run() { eventThread(); } }).start();
138         initFonts();
139     }
140
141     // X11Surface /////////////////////////////////////////////////////
142
143     /** Implements a Surface as an X11 Window */
144     public static class X11Surface extends Surface {
145         
146         gnu.gcj.RawData window;
147         gnu.gcj.RawData gc;
148         boolean framed = false;
149         Semaphore waitForCreation = new Semaphore();
150         
151         public native void setInvisible(boolean i);
152         public void _setMaximized(boolean m) { if (Log.on) Log.log(this, "POSIX/X11 can't maximize windows"); }
153         public native void setIcon(Picture p);
154         public native void _setMinimized(boolean b);
155         public native void setTitleBarText(String s);
156         public native void setSize(int w, int h);
157         public native void setLocation(int x, int y);
158         public native void natInit();
159         public native void toFront();
160         public native void toBack();
161         public native void syncCursor();
162         public native void _dispose();
163         public native void setLimits(int minw, int minh, int maxw, int maxh);
164         public native void blit(DoubleBuffer s, int sx, int sy, int dx, int dy, int dx2, int dy2);
165         public native void dispatchEvent(gnu.gcj.RawData ev);
166
167         public X11Surface(Box root, boolean framed) {
168             super(root);
169             this.framed = framed;
170             natInit();
171         }        
172     
173     }
174
175
176     // Our Subclass of Picture ///////////////////////////////////////////////
177
178     /**
179      *  Implements a Picture. No special X11 structure is created
180      *  unless the image has no alpha (in which case a
181      *  non-shared-pixmap DoubleBuffer is created), or all-or-nothing
182      *  alpha (in which case a non-shared-pixmap DoubleBuffer with a
183      *  stipple bitmap is created).
184      */
185     public static class X11Picture implements Picture {
186         
187         int width;
188         int height;
189         int[] data = null;
190         public X11DoubleBuffer doublebuf = null;
191
192         public int getWidth() { return width; }
193         public int getHeight() { return height; }
194
195         public X11Picture(int[] data, int w, int h) {
196             this.data = data;
197             this.width = w;
198             this.height = h;
199             boolean needsStipple = false;
200
201             // if we have any non-0x00, non-0xFF alphas, we can't double buffer ourselves
202             for(int i=0; i<w*h; i++)
203                 if ((data[i] & 0xFF000000) == 0xFF000000)
204                     needsStipple = true;
205                 else if ((data[i] & 0xFF000000) != 0x00)
206                     return;
207
208             buildDoubleBuffer(needsStipple);
209         }
210
211         void buildDoubleBuffer(boolean needsStipple) {
212             if (doublebuf != null) return;
213             // no point in using a shared pixmap since we'll only write to this image once
214             X11DoubleBuffer b = new X11DoubleBuffer(width, height, false);
215             b.drawPicture(this, 0, 0);
216             if (needsStipple) b.createStipple(this);
217             doublebuf = b;
218         }
219
220     }
221
222     /**
223      *  An X11DoubleBuffer is implemented as an X11 pixmap. "Normal"
224      *  DoubleBuffers will use XShm shared pixmaps if
225      *  available. X11DoubleBuffers created to accelerate Pictures
226      *  with all-or-nothing alpha will not use shared pixmaps, however
227      *  (since they are only written to once.
228      */
229     public static class X11DoubleBuffer implements DoubleBuffer {
230
231         int clipx, clipy, clipw, cliph;
232         int width;
233         int height;
234
235         /** DoubleBuffers of X11Pictures can have stipples -- the stipple of the Picture */
236         RawData stipple = null;
237
238         /** Sets the DoubleBuffer's internal stipple to the alpha==0x00 regions of xpi */
239         public native void createStipple(X11Picture xpi);
240         
241         RawData pm;                    // Pixmap (if any) representing this Picture
242         boolean shared_pixmap = false; // true if pm is a ShmPixmap
243         RawData fake_ximage = null;    // a 'fake' XImage corresponding to the shared pixmap; gives us the address and depth parameters
244         RawData shm_segment = null;    // XShmSegmentInfo
245
246         RawData gc;                    // Graphics Context on pm (never changes, so it's fast)
247         RawData clipped_gc;            // Graphics Context on pm, use this one if you need a clip/stipple
248
249         /** DoubleBuffer mode */
250         public X11DoubleBuffer(int w, int h) { this(w, h, true); }
251         public X11DoubleBuffer(int w, int h, boolean shared_pixmap) {
252             width = clipw = w;
253             height = cliph = h;
254             clipx = clipy = 0;
255             this.shared_pixmap = shared_pixmap;
256             natInit();
257         }
258
259         public void setClip(int x, int y, int x2, int y2) {
260             clipx = x; if (clipx < 0) clipx = 0;
261             clipy = y; if (clipy < 0) clipy = 0;
262             clipw = x2 - x; if (clipw < 0) clipw = 0;
263             cliph = y2 - y; if (cliph < 0) cliph = 0;
264         }
265         
266         public void drawPicture(Picture source, int x, int y) {
267             drawPicture(source, x, y, x + source.getWidth(), y + source.getHeight(), 0, 0, source.getWidth(), source.getHeight());
268         }
269
270         public void drawPicture(Picture source, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) {
271             if (!(dx2 - dx1 != sx2 - sx1 || dy2 - dy1 != sy2 - sy1) && ((X11Picture)source).doublebuf != null)
272                 fastDrawPicture(source, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
273             else 
274                 slowDrawPicture(source, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
275         }
276
277         /** fast path for image drawing (no scaling, all-or-nothing alpha) */
278         public native void fastDrawPicture(Picture source, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2);
279
280         /** slow path for image drawing */
281         public native void slowDrawPicture(Picture source, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2);
282
283         public int getWidth() { return width; }
284         public int getHeight() { return height; }
285         public native void natInit();
286         public native void fillRect(int x, int y, int x2, int y2, int color);
287         public native void drawString(String font, String text, int x, int y, int color);
288         public native void finalize();
289
290     }
291
292
293     // Font Handling ////////////////////////////////////////////////////////////////////
294
295     static String[] fontList = null;
296
297     /** hashtable of all built in X11 fonts; key is XWT font spec, value is X11 font string */
298     static Hashtable nativeFontList = new Hashtable();
299
300     /** cache of all already-looked-up X11 fonts; key is XWT font name, value is a WrappedRawData */
301     static Hashtable xwtFontToFontStruct = new Hashtable();
302
303     /** dumps a list of X11 font strings */
304     private native String[] listNativeFonts();
305
306     /** load native font list */
307     public void initFonts() {
308         // use the font list to build nativeFontList
309         String[] fonts = listNativeFonts();
310
311         for(int k=0; k<fonts.length; k++) {
312             String s = fonts[k].toLowerCase();
313             StringTokenizer st = new StringTokenizer(s, "-", false);
314             String[] font = new String[st.countTokens()];
315             
316             try {
317                 for(int i=0; st.hasMoreTokens(); i++) font[i] = st.nextToken();
318
319                 // limit to iso8559 until we can do I18N properly....
320                 if (font.length > 13) {
321                     if (!font[13].equals("iso8559")) continue;
322                     if (font.length < 15 || !font[14].equals("1")) continue;
323                 }
324
325                 String name = font[1];
326                 String size = font[6];
327                 String slant = (font[3].equals("i") || font[3].equals("o")) ? "i" : "";
328                 String bold = font[2].equals("bold") ? "b" : "";
329                 String tail = s.substring(1 + font[0].length() + 1 + font[1].length() + 1 + font[2].length() + 1 +
330                                           font[3].length() + 1 + font[4].length() + 1);
331                 
332                 if (bold.equals("*") && slant.equals("*")) {
333                     nativeFontList.put(name + size, font[0] + "-" + font[1] + "-regular-r-" + font[4] + "-" + tail);
334                     nativeFontList.put(name + size + "b", font[0] + "-" + font[1] + "-bold-r-" + font[4] + "-" + tail);
335                     nativeFontList.put(name + size + "i", font[0] + "-" + font[1] + "-regular-i-" + font[4] + "-" + tail);
336                     nativeFontList.put(name + size + "bi", font[0] + "-" + font[1] + "-bold-i-" + font[4] + "-" + tail);
337                     
338                 } else if (bold.equals("*")) {
339                     nativeFontList.put(name + size + slant, font[0] + "-" + font[1] + "-regular-" + font[3] + "-" + font[4] + "-" + tail);
340                     nativeFontList.put(name + size + "b" + slant, font[0] + "-" + font[1] + "-bold-" + font[3] + "-" + font[4] + "-" + tail);
341                     
342                 } else if (slant.equals("*")) {
343                     nativeFontList.put(name + size + bold, font[0] + "-" + font[1] + "-" + font[2] + "-r-" + font[4] + "-" + tail);
344                     nativeFontList.put(name + size + bold + "i", font[0] + "-" + font[1] + "-" + font[2] + "-i-" + font[4] + "-" + tail);
345                     
346                 } else {
347                     nativeFontList.put(name + size + bold + slant, s);
348                     
349                 }
350             } catch (ArrayIndexOutOfBoundsException e) {
351                 if (Log.on) Log.log(this, "skipping incomplete font string " + s);
352                 continue;
353             }
354         }
355         fontList = new String[nativeFontList.size()];
356         Enumeration e = nativeFontList.keys();
357         for(int i=0; e.hasMoreElements(); i++) fontList[i] = (String)e.nextElement();
358     }
359
360     /** so we can put XFontStruct's into Hashtables */
361     private static class WrappedRawData {
362         public RawData wrapee = null;
363         public WrappedRawData(RawData r) { wrapee = r; }
364     }
365
366     /** translates an X11 font string into an XFontStruct* */
367     public static native gnu.gcj.RawData fontStringToStruct(String s);
368
369     /** translates an XWT font string into an XFontStruct*, performing caching as well */
370     public static RawData fontToXFont(String s) {
371         if (s == null) s = "sansserif";
372         s = s.toLowerCase();
373         
374         WrappedRawData wrap = (WrappedRawData)xwtFontToFontStruct.get(s);
375         if (wrap != null) return wrap.wrapee;
376
377         String bestmatch = "";
378         int metric = -1 * Integer.MAX_VALUE;
379         ParsedFont arg = new ParsedFont(s);
380         ParsedFont pf = new ParsedFont();
381
382         if (arg.size == -1) arg.size = 10;
383         Enumeration e = nativeFontList.keys();
384         while(e.hasMoreElements()) {
385             String jfont = (String)e.nextElement();
386             pf.parse(jfont);
387             int thismetric = 0;
388             if (!pf.name.equals(arg.name)) {
389                 if (pf.name.equals("lucidabright") && arg.name.equals("serif")) thismetric -= 1000;
390                 else if (pf.name.equals("times") && arg.name.equals("serif")) thismetric -= 2000;
391                 else if (pf.name.equals("helvetica") && arg.name.equals("sansserif")) thismetric -= 1000;
392                 else if (pf.name.equals("courier") && arg.name.equals("monospaced")) thismetric -= 1000;
393                 else if (pf.name.equals("lucida") && arg.name.equals("dialog")) thismetric -= 1000;
394                 else if (pf.name.equals("helvetica") && arg.name.equals("dialog")) thismetric -= 2000;
395                 else if (pf.name.equals("fixed") && arg.name.equals("tty")) thismetric -= 1000;
396                 else if (pf.name.equals("sansserif")) thismetric -= 4000;
397                 else thismetric -= 4004;
398             }
399             if (pf.size != 0) thismetric -= Math.abs(pf.size - arg.size) * 4;
400             if (pf.bold != arg.bold) thismetric -= 1;
401             if (pf.italic != arg.italic) thismetric -= 1;
402             if (thismetric > metric) {
403                 metric = thismetric;
404                 bestmatch = jfont;
405             }
406         }
407         
408         pf.parse(bestmatch);
409         String target = (String)nativeFontList.get(bestmatch);
410         if (pf.size == 0) {
411             int i = 0;
412             for(int j=0; j<6; j++) i = target.indexOf('-', i + 1);
413             target = target.substring(0, i + 1) + arg.size + target.substring(target.indexOf('-', i+1));
414         }
415         RawData ret = fontStringToStruct(target);
416         if (ret == null) ret = fontStringToStruct("fixed");
417         xwtFontToFontStruct.put(s, new WrappedRawData(ret));
418         return ret;
419     }
420
421
422 }