2003/09/23 08:24:59
[org.ibex.core.git] / src / org / xwt / Surface.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import org.bouncycastle.util.encoders.Base64;
5 import org.xwt.util.*;
6 import java.io.*;
7 import java.util.*;
8
9 /** 
10  *  A Surface, as described in the XWT Reference.
11  *
12  *  Platform subclasses should include an inner class subclass of
13  *  Surface to return from the Platform._createSurface() method
14  *
15  *  Note that the members in the section 'state variables' are either
16  *  in real-time (the actual size/position/state), or in
17  *  MessageQueue-time (the size/position/state at the time that the
18  *  now-executing message was enqueued). This distinction is important.
19  */
20 public abstract class Surface extends PixelBuffer {
21
22     /** Dirty regions on the screen which need to be rebuilt using Surface.blit() */
23     DirtyList screenDirtyRegions = new DirtyList();
24
25     public int getWidth() { return root == null ? 0 : root.width; }
26     public int getHeight() { return root == null ? 0 : root.height; }
27         
28     // Static Data ////////////////////////////////////////////////////////////////////////////////
29
30     /**< the most recently enqueued Move message; used to throttle the message rate */
31     private static Message lastMoveMessage = null;
32
33     /** all instances of Surface which need to be refreshed by the MessageQueue */
34     public static Vec allSurfaces = new Vec();
35     
36     /** When set to true, render() should abort as soon as possible and restart the rendering process */
37     static volatile boolean abort = false;
38
39     public static boolean alt = false;          /**< true iff the alt button is pressed down, in real time */
40     public static boolean control = false;      /**< true iff the control button is pressed down, in real time */
41     public static boolean shift = false;        /**< true iff the shift button is pressed down, in real time */
42     public static boolean button1 = false;      /**< true iff button 1 is depressed, in MessageQueue-time */
43     public static boolean button2 = false;      /**< true iff button 2 is depressed, in MessageQueue-time */
44     public static boolean button3 = false;      /**< true iff button 3 is depressed, in MessageQueue-time */
45
46
47     // Instance Data ///////////////////////////////////////////////////////////////////////
48
49     public Box root;      /**< The Box at the root of this surface */
50     public String cursor = "default";
51
52     public int mousex;      /**< the x position of the mouse, relative to this Surface, in MessageQueue-time */
53     public int mousey;      /**< the y position of the mouse, relative to this Surface, in MessageQueue-time */
54     public boolean minimized = false;      /**< True iff this surface is minimized, in real time */
55     public boolean maximized = false;      /**< True iff this surface is maximized, in real time */
56
57
58     // Used For Simulating Clicks and DoubleClicks /////////////////////////////////////////////////
59
60     int last_press_x = Integer.MAX_VALUE;      /**< the x-position of the mouse the last time a Press message was enqueued */
61     int last_press_y = Integer.MAX_VALUE;      /**< the y-position of the mouse the last time a Press message was enqueued */
62     static int lastClickButton = 0;            /**< the last button to recieve a Click message; used for simulating DoubleClick's */
63     static long lastClickTime = 0;             /**< the last time a Click message was processed; used for simulating DoubleClick's */
64     
65     
66     // Methods to be overridden by subclasses ///////////////////////////////////////////////////////
67
68     public abstract void toBack();      /**< when invoked, the surface should push itself to the back of the stacking order */
69     public abstract void toFront();     /**< when invoked, the surface should pull itself to the front of the stacking order */
70     public abstract void syncCursor();  /**< the <i>actual</i> cursor for this surface to the cursor referenced by <tt>cursor</tt> */
71     public abstract void setInvisible(boolean b);      /**< If <tt>b</tt>, make window invisible; otherwise, make it non-invisible. */
72     protected abstract void _setMaximized(boolean b);  /**< If <tt>b</tt>, maximize the surface; otherwise, un-maximize it. */
73     protected abstract void _setMinimized(boolean b);  /**< If <tt>b</tt>, minimize the surface; otherwise, un-minimize it. */
74     protected abstract void setSize(int width, int height);  /**< Sets the surface's width and height. */
75     public abstract void setLocation();                      /**< Set the surface's x/y position to that of the root box */
76     public abstract void setTitleBarText(String s);      /**< Sets the surface's title bar text, if applicable */
77     public abstract void setIcon(Picture i);      /**< Sets the surface's title bar text, if applicable */
78     public abstract void _dispose();      /**< Destroy the surface */
79     public void setLimits(int min_width, int min_height, int max_width, int max_height) { }
80
81
82     // Helper methods for subclasses ////////////////////////////////////////////////////////////
83
84     protected final void Press(final int button) {
85         last_press_x = mousex;
86         last_press_y = mousey;
87
88         if (button == 1) button1 = true;
89         else if (button == 2) button2 = true;
90         else if (button == 3) button3 = true;
91
92         if (button == 1) new SimpleMessage("Press1", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
93         else if (button == 2) new SimpleMessage("Press2", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
94         else if (button == 3) {
95             final Box who = Box.whoIs(root, mousex, mousey);
96             Message.Q.add(new Message() { public void perform() {
97                 Platform.clipboardReadEnabled = true;
98                 root.put("Press3", Boolean.TRUE);
99                 Platform.clipboardReadEnabled = false;
100             }});
101         }
102     }
103
104     protected final void Release(int button) {
105         if (button == 1) button1 = false;
106         else if (button == 2) button2 = false;
107         else if (button == 3) button3 = false;
108
109         if (button == 1) new SimpleMessage("Release1", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
110         else if (button == 2) new SimpleMessage("Release2", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
111         else if (button == 3) new SimpleMessage("Release3", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
112
113         if (Platform.needsAutoClick() && Math.abs(last_press_x - mousex) < 5 && Math.abs(last_press_y - mousey) < 5) Click(button);
114         last_press_x = Integer.MAX_VALUE;
115         last_press_y = Integer.MAX_VALUE;
116     }
117
118     protected final void Click(int button) {
119         if (button == 1) new SimpleMessage("Click1", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
120         else if (button == 2) new SimpleMessage("Click2", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
121         else if (button == 3) new SimpleMessage("Click3", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
122         if (Platform.needsAutoDoubleClick()) {
123             long now = System.currentTimeMillis();
124             if (lastClickButton == button && now - lastClickTime < 350) DoubleClick(button);
125             lastClickButton = button;
126             lastClickTime = now;
127         }
128     }
129
130     protected final void DoubleClick(int button) {
131         if (button == 1) new SimpleMessage("DoubleClick1", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
132         else if (button == 2) new SimpleMessage("DoubleClick2", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
133         else if (button == 3) new SimpleMessage("DoubleClick3", Boolean.TRUE, Box.whoIs(root, mousex, mousey));
134     }
135
136     /** sends a KeyPressed message; subclasses should not add the C- or A- prefixes, nor should they capitalize alphabet characters */
137     protected final void KeyPressed(String key) {
138         if (key == null) return;
139
140         if (key.toLowerCase().endsWith("shift")) shift = true;
141         else if (shift) key = key.toUpperCase();
142
143         if (key.toLowerCase().equals("alt")) alt = true;
144         else if (alt) key = "A-" + key;
145
146         if (key.toLowerCase().endsWith("control")) control = true;
147         else if (control) key = "C-" + key;
148
149         final String fkey = key;
150         Message.Q.add(new KMessage(key));
151     }
152
153     // This is implemented as a private static class instead of an anonymous class to work around a GCJ bug
154     private class KMessage implements Message {
155         String key = null;
156         public KMessage(String k) { key = k; }
157         public void perform() {
158             if (key.equals("C-v") || key.equals("A-v")) Platform.clipboardReadEnabled = true;
159             /* FIXME
160             outer: for(int i=0; i<keywatchers.size(); i++) {
161                 Box b = (Box)keywatchers.elementAt(i);
162                 for(Box cur = b; cur != null; cur = cur.getParent())
163                     if ((cur.flags & cur.INVISIBLE_FLAG) != 0) continue outer;
164                 b.put("KeyPressed", key);
165             }
166             */
167             Platform.clipboardReadEnabled = false;
168         }
169     }
170
171     /** sends a KeyReleased message; subclasses should not add the C- or A- prefixes, nor should they capitalize alphabet characters */
172     protected final void KeyReleased(final String key) {
173         if (key == null) return;
174         if (key.toLowerCase().equals("alt")) alt = false;
175         else if (key.toLowerCase().equals("control")) control = false;
176         else if (key.toLowerCase().equals("shift")) shift = false;
177         Message.Q.add(new Message() { public void perform() {
178             /* FIXME
179             outer: for(int i=0; i<keywatchers.size(); i++) {
180                 Box b = (Box)keywatchers.elementAt(i);
181                 for(Box cur = b; cur != null; cur = cur.getParent())
182                     if ((cur.flags & cur.INVISIBLE_FLAG) != 0) continue outer;
183                 b.put("KeyReleased", key);
184             }
185             */
186         }});
187     }
188
189     /**
190      *  Notify XWT that the mouse has moved. If the mouse leaves the
191      *  surface, but the host windowing system does not provide its new
192      *  position (for example, a Java MouseListener.mouseExited()
193      *  message), the subclass should use (-1,-1).
194      */
195     protected final void Move(final int newmousex, final int newmousey) {
196         Message.Q.add(lastMoveMessage = new Message() { public void perform() {
197             synchronized(Surface.this) {
198
199                 // if move messages are arriving faster than we can process them, we just start ignoring them
200                 if (lastMoveMessage != this) return;
201
202                 int oldmousex = mousex;
203                 int oldmousey = mousey;
204                 mousex = newmousex;
205                 mousey = newmousey;
206
207                 String oldcursor = cursor;
208                 cursor = "default";
209
210                 // Root gets motion events outside itself (if trapped, of course)
211                 if (!root.inside(oldmousex, oldmousey) && !root.inside(mousex, mousey) && (button1 || button2 || button3))
212                     root.put("Move", Boolean.TRUE);
213
214                 root.Move(oldmousex, oldmousey, mousex, mousey);
215                 if (!cursor.equals(oldcursor)) syncCursor();
216             }
217         }});
218     }
219
220     protected final void SizeChange(final int width, final int height) {
221         Message.Q.add(new Message() { public void perform() {
222             if (width == root.width && height == root.height) return;
223             root.width = width;
224             root.height = height;
225             root.needs_reflow = true;
226         }});
227         abort = true;
228     }
229
230     protected final void PosChange(final int x, final int y) {
231         Message.Q.add(new Message() { public void perform() {
232             root.put("x", new Integer(x));
233             root.put("y", new Integer(y));
234         }});
235     }
236
237     protected final void Close() { new SimpleMessage("Close", Boolean.TRUE, root); }
238     protected final void Minimized(boolean b) { minimized = b; new SimpleMessage("Minimized", b ? Boolean.TRUE : Boolean.FALSE, root); }
239     protected final void Maximized(boolean b) { maximized = b; new SimpleMessage("Maximized", b ? Boolean.TRUE : Boolean.FALSE, root); }
240     protected final void Focused(boolean b) { new SimpleMessage("Focused", b ? Boolean.TRUE : Boolean.FALSE, root); }
241     public static void Refresh() { Message.Q.refresh(); }
242
243
244     // Other Methods ///////////////////////////////////////////////////////////////////////////////
245
246     public final void setMaximized(boolean b) { if (b != maximized) _setMaximized(maximized = b); }
247     public final void setMinimized(boolean b) { if (b != minimized) _setMinimized(minimized = b); }
248
249     /** wrapper for setSize() which makes sure to dirty the place where the scar used to be */
250     void setSize() {
251         root.width = Math.max(root.width, scarPicture.getWidth());
252         root.height = Math.max(root.height, scarPicture.getHeight());
253         dirty(hscar, root.height - vscar - scarPicture.getHeight(), scarPicture.getWidth(), scarPicture.getHeight());
254         setSize(root.width, root.height);
255     }
256
257     /** Indicates that the Surface is no longer needed */
258     public final void dispose(boolean quitIfAllSurfacesGone) {
259         if (root == null) return;
260         if (Log.on) Log.log(this, "disposing " + this);
261         allSurfaces.removeElement(this);
262         _dispose();
263
264         // quit when all windows are closed
265         if (allSurfaces.size() == 0 && quitIfAllSurfacesGone && Main.doneInitializing) {
266             if (Log.on) Log.log(this, "exiting because last surface was destroyed");
267             System.exit(0);
268         }
269     }
270
271     public void dirty(int x, int y, int w, int h) {
272         backbufferDirtyRegions.dirty(x, y, w, h);
273         Refresh();
274     }
275
276     public Surface(Box root) {
277         this.root = root;
278         if (root.surface != null && root.surface.root == root) {
279             root.surface.dispose(false);
280         } else {
281             root.remove();
282         }
283         root.surface = this;
284
285         // make sure the root is properly sized
286         do { abort = false; root.reflow(); } while(abort);
287
288         root.dirty();
289         Refresh();
290     }
291
292     /** runs the prerender() and render() pipelines in the root Box to regenerate the backbuffer, then blits it to the screen */
293     public synchronized void render() {
294
295         // make sure the root is properly sized
296         do {
297             abort = false;
298             root.reflow();
299             // update mouseinside and trigger Enter/Leave as a result of box size/position changes
300             String oldcursor = cursor;
301             cursor = "default";
302             root.Move(mousex, mousey, mousex, mousey);
303             if (!cursor.equals(oldcursor)) syncCursor();
304         } while(abort);
305
306         Box.sizePosChangesSinceLastRender = 0;
307         int[][] dirt = backbufferDirtyRegions.flush();
308         for(int i = 0; dirt != null && i < dirt.length; i++) {
309             if (dirt[i] == null) continue;
310             int x = dirt[i][0];
311             int y = dirt[i][1];
312             int w = dirt[i][2];
313             int h = dirt[i][3];
314             if (x < 0) x = 0;
315             if (y < 0) y = 0;
316             if (x+w > root.width) w = root.width - x;
317             if (y+h > root.height) h = root.height - y;
318             if (w <= 0 || h <= 0) continue;
319
320             root.render(0, 0, x, y, w, h, this);
321             
322             // if any area under the scar was repainted, rescar that area
323             if (x < hscar + scarPicture.getWidth() &&
324                 y + h > root.height - scarPicture.getHeight() - vscar) {
325                 int _x1 = Math.max(x, hscar);
326                 int _x2 = Math.min(x + w, hscar + scarPicture.getWidth());
327                 int _y1 = Math.max(y, root.height - scarPicture.getHeight() - vscar);
328                 int _y2 = Math.min(y + h, root.height - vscar);
329                 
330                 drawPicture(scarPicture, _x1, _y1, _x2, _y2,
331                             _x1,
332                             _y1 - (root.height - scarPicture.getHeight()),
333                             _x2,
334                             _y2 - (root.height - scarPicture.getHeight())
335                             );
336             }
337
338             if (abort) {
339
340                 // x,y,w,h is only partially reconstructed, so we must be careful not to re-blit it
341                 screenDirtyRegions.dirty(x, y, w, h);
342
343                 // put back all the dirty regions we haven't yet processed (including the current one)
344                 for(int j=i; j<dirt.length; j++)
345                     if (dirt[j] != null)
346                         backbufferDirtyRegions.dirty(dirt[j][0], dirt[j][1], dirt[j][2], dirt[j][3]);
347
348                 // tail-recurse
349                 render();
350                 return;
351             }
352
353             // now that we've reconstructed this region in the backbuffer, queue it to be reblitted
354             screenDirtyRegions.dirty(x, y, w, h);
355         }
356
357     }
358
359     // FEATURE: reinstate recycler
360     public class SimpleMessage implements Message {
361         
362         private Box boxContainingMouse;
363         private Object value;
364         public String name;
365         
366         SimpleMessage(String name, Object value, Box boxContainingMouse) {
367             this.boxContainingMouse = boxContainingMouse;
368             this.name = name;
369             this.value = value;
370             Message.Q.add(this);
371         }
372         
373         public void perform() { boxContainingMouse.put(name, value); }
374         public String toString() { return "SimpleMessage [name=" + name + ", value=" + value + "]"; }
375
376     }
377
378     /** Dirty regions on the backbuffer which need to be rebuilt using Box.render() */
379     private DirtyList backbufferDirtyRegions = new DirtyList();
380         
381     // Scar-Related Stuff ////////////////////////////////////////////////////////////////////
382
383     /** the scar image drawn on the bottom right hand corner */
384     static Picture scarPicture = null;
385
386
387     // Default PixelBuffer implementation /////////////////////////////////////////////////////////
388
389     public static abstract class DoubleBufferedSurface extends Surface {
390
391         public DoubleBufferedSurface(Box root) {
392             super(root);
393
394             // this is a bit dangerous since we're passing ourselves to another method before subclasses' ctors have run...        
395             backbuffer = Platform.createPixelBuffer(Platform.getScreenWidth(), Platform.getScreenHeight(), this);
396         }
397
398         /** The automatic double buffer for the root box */
399         PixelBuffer backbuffer = null;
400         
401         public void drawPicture(Picture source, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) {
402             backbuffer.drawPicture(source, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
403         }
404         
405         public void fillRect(int x1, int y1, int x2, int y2, int color) {
406             backbuffer.fillRect(x1, y1, x2, y2, color);
407         }
408         
409         /** This is how subclasses signal a 'shallow dirty', indicating that although the backbuffer is valid, the screen is not */
410         public final void Dirty(int x, int y, int w, int h) {
411             screenDirtyRegions.dirty(x, y, w, h);
412             Refresh();
413         }
414
415         /** copies a region from the doublebuffer to this surface */
416         public abstract void blit(PixelBuffer source, int sx, int sy, int dx, int dy, int dx2, int dy2);
417
418
419         /** blits from the backbuffer to the screen for all regions of the screen which have become dirty */
420         public synchronized void blitDirtyScreenRegions() { blitDirtyScreenRegions(-1, -1, 0, 0); }
421         
422         /** same as blitDirtyScreenRegions(), except that it will skip any regions within a,b,c,d */
423         private synchronized void blitDirtyScreenRegions(int a, int b, int c, int d) {
424             
425             int[][] dirt = screenDirtyRegions.flush();
426             if (Main.showRenders && dirt != null && dirt.length > 0 && a == -1)
427                 blit(backbuffer, 0, 0, 0, 0, root.width, root.height);
428             
429             for(int i = 0; dirt != null && i < dirt.length; i++) {
430                 if (dirt[i] == null) continue;
431                 int x = dirt[i][0];
432                 int y = dirt[i][1];
433                 int w = dirt[i][2];
434                 int h = dirt[i][3];
435                 if (x < 0) x = 0;
436                 if (y < 0) y = 0;
437                 if (x+w > root.width) w = root.width - x;
438                 if (y+h > root.height) h = root.height - y;
439                 if (w <= 0 || h <= 0) continue;
440                 
441                 // if any part of this region falls within the "bad region", just skip it
442                 boolean hhit = (x >= a && x <= a + c) || (x+w >= a && x+w <= a + c);
443                 boolean vhit = (y >= b && y <= b + d) || (y+h >= b && y+h <= b + d);
444                 if (hhit && vhit) {
445                     screenDirtyRegions.dirty(x, y, w, h);
446                     continue;
447                 }
448                 
449                 blit(backbuffer, x, y, x, y, w + x, h + y);
450                 
451             }
452
453         }
454     }
455
456     public static final int hscar = 0;
457     public static final int vscar = 0;
458
459 }