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