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