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