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