2002/08/07 04:42:00
[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 value of the environment variable key, or null if no such key exists */
56     protected 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 void _newBrowserWindow(String url) {
62         String browserString = getEnv("BROWSER");
63         if (browserString == null) {
64             browserString = "netscape " + url;
65         } else if (browserString.indexOf("%s") != -1) {
66             browserString =
67                 browserString.substring(0, browserString.indexOf("%s")) +
68                 url + browserString.substring(browserString.indexOf("%s") + 2);
69         } else {
70             browserString += " " + url;
71         }
72
73         StringTokenizer st = new StringTokenizer(browserString, " ");
74         String[] cmd = new String[st.countTokens()];
75         for(int i=0; st.hasMoreTokens(); i++) {
76             cmd[i] = st.nextToken();
77             System.out.println(i + ":" + cmd[i]);
78         }
79
80         spawnChildProcess(cmd);
81     }
82
83     public POSIX() { }
84     public void init() {
85         natInit();
86         (new Thread() { public void run() { eventThread(); } }).start();
87         initFonts();
88     }
89
90     // X11Surface /////////////////////////////////////////////////////
91
92     /** Implements a Surface as an X11 Window */
93     public static class X11Surface extends Surface {
94         
95         gnu.gcj.RawData window;
96         gnu.gcj.RawData gc;
97         boolean framed = false;
98         Semaphore waitForCreation = new Semaphore();
99         
100         public native void setInvisible(boolean i);
101         public void _setMaximized(boolean m) { if (Log.on) Log.log(this, "POSIX/X11 can't maximize windows"); }
102         public native void setIcon(Picture p);
103         public native void _setMinimized(boolean b);
104         public native void setTitleBarText(String s);
105         public native void setSize(int w, int h);
106         public native void setLocation(int x, int y);
107         public native void natInit();
108         public native void toFront();
109         public native void toBack();
110         public native void syncCursor();
111         public native void _dispose();
112         public native void setLimits(int minw, int minh, int maxw, int maxh);
113         public native void blit(DoubleBuffer s, int sx, int sy, int dx, int dy, int dx2, int dy2);
114         public native void dispatchEvent(gnu.gcj.RawData ev);
115
116         public X11Surface(Box root, boolean framed) {
117             super(root);
118             this.framed = framed;
119             natInit();
120         }        
121     
122     }
123
124
125     // Our Subclass of Picture ///////////////////////////////////////////////
126
127     /**
128      *  Implements a Picture. No special X11 structure is created
129      *  unless the image has no alpha (in which case a
130      *  non-shared-pixmap DoubleBuffer is created), or all-or-nothing
131      *  alpha (in which case a non-shared-pixmap DoubleBuffer with a
132      *  stipple bitmap is created).
133      */
134     public static class X11Picture implements Picture {
135         
136         int width;
137         int height;
138         int[] data = null;
139         public X11DoubleBuffer doublebuf = null;
140
141         public int getWidth() { return width; }
142         public int getHeight() { return height; }
143
144         public X11Picture(int[] data, int w, int h) {
145             this.data = data;
146             this.width = w;
147             this.height = h;
148             boolean needsStipple = false;
149
150             // if we have any non-0x00, non-0xFF alphas, we can't double buffer ourselves
151             for(int i=0; i<w*h; i++)
152                 if ((data[i] & 0xFF000000) == 0xFF000000)
153                     needsStipple = true;
154                 else if ((data[i] & 0xFF000000) != 0x00)
155                     return;
156
157             buildDoubleBuffer(needsStipple);
158         }
159
160         void buildDoubleBuffer(boolean needsStipple) {
161             if (doublebuf != null) return;
162             // no point in using a shared pixmap since we'll only write to this image once
163             X11DoubleBuffer b = new X11DoubleBuffer(width, height, false);
164             b.drawPicture(this, 0, 0);
165             if (needsStipple) b.createStipple(this);
166             doublebuf = b;
167         }
168
169     }
170
171     /**
172      *  An X11DoubleBuffer is implemented as an X11 pixmap. "Normal"
173      *  DoubleBuffers will use XShm shared pixmaps if
174      *  available. X11DoubleBuffers created to accelerate Pictures
175      *  with all-or-nothing alpha will not use shared pixmaps, however
176      *  (since they are only written to once.
177      */
178     public static class X11DoubleBuffer implements DoubleBuffer {
179
180         int clipx, clipy, clipw, cliph;
181         int width;
182         int height;
183
184         /** DoubleBuffers of X11Pictures can have stipples -- the stipple of the Picture */
185         RawData stipple = null;
186
187         /** Sets the DoubleBuffer's internal stipple to the alpha==0x00 regions of xpi */
188         public native void createStipple(X11Picture xpi);
189         
190         RawData pm;                    // Pixmap (if any) representing this Picture
191         boolean shared_pixmap = false; // true if pm is a ShmPixmap
192         RawData fake_ximage = null;    // a 'fake' XImage corresponding to the shared pixmap; gives us the address and depth parameters
193         RawData shm_segment = null;    // XShmSegmentInfo
194
195         RawData gc;                    // Graphics Context on pm (never changes, so it's fast)
196         RawData clipped_gc;            // Graphics Context on pm, use this one if you need a clip/stipple
197
198         /** DoubleBuffer mode */
199         public X11DoubleBuffer(int w, int h) { this(w, h, true); }
200         public X11DoubleBuffer(int w, int h, boolean shared_pixmap) {
201             width = clipw = w;
202             height = cliph = h;
203             clipx = clipy = 0;
204             this.shared_pixmap = shared_pixmap;
205             natInit();
206         }
207
208         public void setClip(int x, int y, int x2, int y2) {
209             clipx = x; if (clipx < 0) clipx = 0;
210             clipy = y; if (clipy < 0) clipy = 0;
211             clipw = x2 - x; if (clipw < 0) clipw = 0;
212             cliph = y2 - y; if (cliph < 0) cliph = 0;
213         }
214         
215         public void drawPicture(Picture source, int x, int y) {
216             drawPicture(source, x, y, x + source.getWidth(), y + source.getHeight(), 0, 0, source.getWidth(), source.getHeight());
217         }
218
219         public void drawPicture(Picture source, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) {
220             if (!(dx2 - dx1 != sx2 - sx1 || dy2 - dy1 != sy2 - sy1) && ((X11Picture)source).doublebuf != null)
221                 fastDrawPicture(source, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
222             else 
223                 slowDrawPicture(source, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
224         }
225
226         /** fast path for image drawing (no scaling, all-or-nothing alpha) */
227         public native void fastDrawPicture(Picture source, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2);
228
229         /** slow path for image drawing */
230         public native void slowDrawPicture(Picture source, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2);
231
232         public int getWidth() { return width; }
233         public int getHeight() { return height; }
234         public native void natInit();
235         public native void fillRect(int x, int y, int x2, int y2, int color);
236         public native void drawString(String font, String text, int x, int y, int color);
237         public native void finalize();
238
239     }
240
241
242     // Font Handling ////////////////////////////////////////////////////////////////////
243
244     static String[] fontList = null;
245
246     /** hashtable of all built in X11 fonts; key is XWT font spec, value is X11 font string */
247     static Hashtable nativeFontList = new Hashtable();
248
249     /** cache of all already-looked-up X11 fonts; key is XWT font name, value is a WrappedRawData */
250     static Hashtable xwtFontToFontStruct = new Hashtable();
251
252     /** dumps a list of X11 font strings */
253     private native String[] listNativeFonts();
254
255     /** load native font list */
256     public void initFonts() {
257         // use the font list to build nativeFontList
258         String[] fonts = listNativeFonts();
259
260         Vector v = new Vector();
261         for(int k=0; k<fonts.length; k++) {
262
263             String s = fonts[k].toLowerCase();
264             String s2 = s;
265             try {
266                 v.setSize(0);
267                 s = s.substring(s.indexOf('-') + 1);
268                 while (s.indexOf('-') != -1) {
269                     v.addElement(s.substring(0, s.indexOf('-')));
270                     s = s.substring(s.indexOf('-') + 1);
271                 }
272                 v.addElement(s);
273                 String[] font = new String[v.size()];
274                 v.copyInto(font);
275
276                 // limit to iso8559 until we can do I18N properly....
277                 if (font.length > 12) {
278                     if (!font[12].equals("iso8859") && !font[12].equals("")) continue;
279                     if (font.length < 14 || !font[13].equals("1")) continue;
280                 }
281
282                 String name = font[1];
283                 String size = font[6];
284                 String slant = (font[3].equals("i") || font[3].equals("o")) ? "i" : "";
285                 String bold = font[2].equals("bold") ? "b" : "";
286                 String tail = s2.substring(1 + font[0].length() + 1 + font[1].length() + 1 + font[2].length() + 1 +
287                                            font[3].length() + 1 + font[4].length() + 1);
288                 
289                 if (bold.equals("*") && slant.equals("*")) {
290                     nativeFontList.put(name + size, font[0] + "-" + font[1] + "-regular-r-" + font[4] + "-" + tail);
291                     nativeFontList.put(name + size + "b", font[0] + "-" + font[1] + "-bold-r-" + font[4] + "-" + tail);
292                     nativeFontList.put(name + size + "i", font[0] + "-" + font[1] + "-regular-i-" + font[4] + "-" + tail);
293                     nativeFontList.put(name + size + "bi", font[0] + "-" + font[1] + "-bold-i-" + font[4] + "-" + tail);
294                     
295                 } else if (bold.equals("*")) {
296                     nativeFontList.put(name + size + slant, font[0] + "-" + font[1] + "-regular-" + font[3] + "-" + font[4] + "-" + tail);
297                     nativeFontList.put(name + size + "b" + slant, font[0] + "-" + font[1] + "-bold-" + font[3] + "-" + font[4] + "-" + tail);
298                     
299                 } else if (slant.equals("*")) {
300                     nativeFontList.put(name + size + bold, font[0] + "-" + font[1] + "-" + font[2] + "-r-" + font[4] + "-" + tail);
301                     nativeFontList.put(name + size + bold + "i", font[0] + "-" + font[1] + "-" + font[2] + "-i-" + font[4] + "-" + tail);
302                     
303                 } else {
304                     nativeFontList.put(name + size + bold + slant, s2);
305                     
306                 }
307             } catch (ArrayIndexOutOfBoundsException e) {
308                 if (Log.on) Log.log(this, "skipping incomplete font string " + s2);
309                 continue;
310             }
311         }
312         fontList = new String[nativeFontList.size()];
313         Enumeration e = nativeFontList.keys();
314         for(int i=0; e.hasMoreElements(); i++) fontList[i] = (String)e.nextElement();
315     }
316
317     /** so we can put XFontStruct's into Hashtables */
318     private static class WrappedRawData {
319         public RawData wrapee = null;
320         public WrappedRawData(RawData r) { wrapee = r; }
321     }
322
323     /** translates an X11 font string into an XFontStruct* */
324     public static native gnu.gcj.RawData fontStringToStruct(String s);
325
326     /** translates an XWT font string into an XFontStruct*, performing caching as well */
327     public static RawData fontToXFont(String s) {
328         if (s == null) s = "sansserif";
329         s = s.toLowerCase();
330         
331         WrappedRawData wrap = (WrappedRawData)xwtFontToFontStruct.get(s);
332         if (wrap != null) return wrap.wrapee;
333
334         String bestmatch = "";
335         int metric = -1 * Integer.MAX_VALUE;
336         ParsedFont arg = new ParsedFont(s);
337         ParsedFont pf = new ParsedFont();
338
339         if (arg.size == -1) arg.size = 10;
340         Enumeration e = nativeFontList.keys();
341         while(e.hasMoreElements()) {
342             String jfont = (String)e.nextElement();
343             pf.parse(jfont);
344             int thismetric = 0;
345             if (!pf.name.equals(arg.name)) {
346                 if (pf.name.equals("lucidabright") && arg.name.equals("serif")) thismetric -= 1000;
347                 else if (pf.name.equals("times") && arg.name.equals("serif")) thismetric -= 2000;
348                 else if (pf.name.equals("helvetica") && arg.name.equals("sansserif")) thismetric -= 1000;
349                 else if (pf.name.equals("courier") && arg.name.equals("monospaced")) thismetric -= 1000;
350                 else if (pf.name.equals("lucida") && arg.name.equals("dialog")) thismetric -= 1000;
351                 else if (pf.name.equals("helvetica") && arg.name.equals("dialog")) thismetric -= 2000;
352                 else if (pf.name.equals("fixed") && arg.name.equals("tty")) thismetric -= 1000;
353                 else if (pf.name.equals("sansserif")) thismetric -= 4000;
354                 else thismetric -= 4004;
355             }
356             if (pf.size != 0) thismetric -= Math.abs(pf.size - arg.size) * 4;
357             if (pf.bold != arg.bold) thismetric -= 1;
358             if (pf.italic != arg.italic) thismetric -= 1;
359             if (thismetric > metric) {
360                 metric = thismetric;
361                 bestmatch = jfont;
362             }
363         }
364         
365         pf.parse(bestmatch);
366         String target = (String)nativeFontList.get(bestmatch);
367         if (pf.size == 0) {
368             int i = 0;
369             for(int j=0; j<6; j++) i = target.indexOf('-', i + 1);
370             target = target.substring(0, i + 1) + arg.size + target.substring(target.indexOf('-', i+1));
371         }
372         if (Log.on) Log.log(POSIX.class, "mapping font \"" + s + "\" to \"" + target + "\"");
373         RawData ret = fontStringToStruct(target);
374         if (ret == null) ret = fontStringToStruct("fixed");
375         xwtFontToFontStruct.put(s, new WrappedRawData(ret));
376         return ret;
377     }
378
379
380 }