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