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