2003/12/30 21:59:52
[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.js.*;
6 import org.xwt.util.*;
7 import java.io.*;
8 import java.util.*;
9
10 /** 
11  *  A Surface, as described in the XWT Reference.
12  *
13  *  Platform subclasses should include an inner class subclass of
14  *  Surface to return from the Platform._createSurface() method
15  *
16  *  Note that the members in the section 'state variables' are either
17  *  in real-time (the actual size/position/state), or in
18  *  Scheduler-time (the size/position/state at the time that the
19  *  now-executing message was enqueued). This distinction is important.
20  */
21 public abstract class Surface extends PixelBuffer implements Scheduler.Task {
22
23     // Static Data ////////////////////////////////////////////////////////////////////////////////
24
25     private static Boolean T = Boolean.TRUE;
26     private static Boolean F = Boolean.FALSE;
27
28     /** all instances of Surface which need to be refreshed by the Scheduler */
29     public static Vec allSurfaces = new Vec();
30     
31     /** When set to true, render() should abort as soon as possible and restart the rendering process */
32     volatile boolean abort = false;
33     volatile int pendingWidth = -1;
34     volatile int pendingHeight = -1;
35
36     public static boolean alt = false;          ///< true iff the alt button is pressed down, in real time
37     public static boolean control = false;      ///< true iff the control button is pressed down, in real time
38     public static boolean shift = false;        ///< true iff the shift button is pressed down, in real time
39     public static boolean button1 = false;      ///< true iff button 1 is depressed, in Scheduler-time
40     public static boolean button2 = false;      ///< true iff button 2 is depressed, in Scheduler-time
41     public static boolean button3 = false;      ///< true iff button 3 is depressed, in Scheduler-tiem
42
43      
44
45     // Instance Data ///////////////////////////////////////////////////////////////////////
46
47     public Box root;                                   ///< The Box at the root of this surface
48     public String cursor = "default";                  ///< The active cursor to switch to when syncCursor() is called
49     public int mousex;                                 ///< x position of the mouse, in Scheduler-time
50     public int mousey;                                 ///< y position of the mouse, in Scheduler-time
51     public int _mousex;                                ///< x position of the mouse, in Scheduler-time
52     public int _mousey;                                ///< y position of the mouse, in Scheduler-time
53     public int newmousex = -1;                         ///< x position of the mouse, in realtime
54     public int newmousey = -1;                         ///< y position of the mouse, in realtime
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     DirtyList dirtyRegions = new DirtyList();  ///< Dirty regions on the *screen*
58
59     // Used For Simulating Clicks and DoubleClicks /////////////////////////////////////////////////
60
61     int last_press_x = Integer.MAX_VALUE;      ///< the x-position of the mouse the last time a Press message was enqueued
62     int last_press_y = Integer.MAX_VALUE;      ///< the y-position of the mouse the last time a Press message was enqueued
63     static int lastClickButton = 0;            ///< the last button to recieve a Click message; used for simulating DoubleClick's
64     static long lastClickTime = 0;             ///< the last time a Click message was processed; used for simulating DoubleClick's
65     
66     
67     // Methods to be overridden by subclasses ///////////////////////////////////////////////////////
68
69     public abstract void toBack();                     ///< should push surface to the back of the stacking order
70     public abstract void toFront();                    ///< should pull surface to the front of the stacking order
71     public abstract void syncCursor();                 ///< set the actual cursor to this.cursor if they do not match
72     public abstract void setInvisible(boolean b);      ///< If <tt>b</tt>, make window invisible; otherwise, make it non-invisible.
73     protected abstract void _setMaximized(boolean b);  ///< If <tt>b</tt>, maximize the surface; otherwise, un-maximize it.
74     protected abstract void _setMinimized(boolean b);  ///< If <tt>b</tt>, minimize the surface; otherwise, un-minimize it.
75     public abstract void setLocation();                ///< Set the surface's x/y position to that of the root box
76     protected abstract void _setSize(int w, int h);    ///< set the actual size of the surface
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) { /* FIXME */ }
81
82
83     // Helper methods for subclasses ////////////////////////////////////////////////////////////
84
85     protected final void Press(final int button) {
86         last_press_x = mousex;
87         last_press_y = mousey;
88
89         if (button == 1) button1 = true;
90         else if (button == 2) button2 = true;
91         else if (button == 3) button3 = true;
92
93         if (button == 1) new SimpleMessage("_Press1", T, root);
94         else if (button == 2) new SimpleMessage("_Press2", T, root);
95         else if (button == 3) {
96             final Box who = root;
97             Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn {
98                 Platform.clipboardReadEnabled = true;
99                 try {
100                     root.putAndTriggerTraps("_Press3", T);
101                 } finally {
102                     Platform.clipboardReadEnabled = false;
103                 }
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", T, root);
114         else if (button == 2) new SimpleMessage("_Release2", T, root);
115         else if (button == 3) new SimpleMessage("_Release3", T, root);
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", T, root);
124         else if (button == 2) new SimpleMessage("_Click2", T, root);
125         else if (button == 3) new SimpleMessage("_Click3", T, root);
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     /** we enqueue ourselves in the Scheduler when we have a Move message to deal with */
135     public void perform() {
136         if (mousex == newmousex && mousey == newmousey) return;
137         int oldmousex = mousex;     mousex = newmousex;
138         int oldmousey = mousey;     mousey = newmousey;
139         String oldcursor = cursor;  cursor = "default";
140         // Root gets motion events outside itself (if trapped)
141         if (!root.inside(oldmousex, oldmousey) && !root.inside(mousex, mousey) && (button1 || button2 || button3))
142             try {
143                 root.putAndTriggerTraps("_Move", T);
144             } catch (JSExn e) {
145                 Log.info(Surface.class, "Exception thrown from Move message handler");
146                 JS.log(e);
147             }
148         if (!cursor.equals(oldcursor)) syncCursor();
149     }
150
151     /**
152      *  Notify XWT that the mouse has moved. If the mouse leaves the
153      *  surface, but the host windowing system does not provide its new
154      *  position (for example, a Java MouseListener.mouseExited()
155      *  message), the subclass should use (-1,-1).
156      */
157     protected final void Move(final int newmousex, final int newmousey) {
158         this.newmousex = newmousex;
159         this.newmousey = newmousey;
160         Scheduler.add(this);
161     }
162
163     /** subclasses should invoke this method when the user resizes the window */
164     protected final void SizeChange(final int width, final int height) {
165         pendingWidth = width;
166         pendingHeight = height;
167         Refresh();
168         Scheduler.add(new Scheduler.Task() { public void perform() { }});
169     }
170
171     // FEATURE: can we avoid creating objects here?
172     protected final void PosChange(final int x, final int y) {
173         Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn {
174             root.x = x;
175             root.y = y;
176             root.putAndTriggerTraps("PosChange", T);
177         }});
178     }
179
180     private final String[] doubleClick = new String[] { null, "_DoubleClick1", "_DoubleClick2", "_DoubleClick3" };
181     protected final void DoubleClick(int button) { new SimpleMessage(doubleClick[button], T, root); }
182     protected final void KeyPressed(String key) { new SimpleMessage("_KeyPressed", key, root); }
183     protected final void KeyReleased(String key) { new SimpleMessage("_KeyReleased", key, root); }
184     protected final void Close() { new SimpleMessage("Close", T, root); }
185     protected final void Minimized(boolean b) { minimized = b; new SimpleMessage("Minimized", b ? T : F, root); }
186     protected final void Maximized(boolean b) { maximized = b; new SimpleMessage("Maximized", b ? T : F, root); }
187     protected final void Focused(boolean b) { new SimpleMessage("Focused", b ? T : F, root); }
188     public void Refresh() { abort = true; }
189
190     public final void setMaximized(boolean b) { if (b != maximized) _setMaximized(maximized = b); }
191     public final void setMinimized(boolean b) { if (b != minimized) _setMinimized(minimized = b); }
192
193
194     // Other Methods ///////////////////////////////////////////////////////////////////////////////
195
196     /** Indicates that the Surface is no longer needed */
197     public final void dispose(boolean quitIfAllSurfacesGone) {
198         if (Log.on) Log.info(this, "disposing " + this);
199         allSurfaces.removeElement(this);
200         _dispose();
201         if (allSurfaces.size() == 0) {
202             if (Log.on) Log.info(this, "exiting because last surface was destroyed");
203             System.exit(0);
204         }
205     }
206
207     public void dirty(int x, int y, int w, int h) {
208         dirtyRegions.dirty(x, y, w, h);
209         Refresh();
210     }
211
212     public static Surface fromBox(Box b) {
213         for(int i=0; i<allSurfaces.size(); i++) {
214             Surface s = (Surface)allSurfaces.elementAt(i);
215             if (s.root == b) return s;
216         }
217         return null;
218     }
219
220     public Surface(Box root) {
221         this.root = root;
222         root.setMaxWidth(JS.N(Math.min(Platform.getScreenWidth(), root.maxwidth)));
223         root.setMaxHeight(JS.N(Math.min(Platform.getScreenHeight(), root.maxheight)));
224         Surface old = fromBox(root);
225         if (old != null) old.dispose(false);
226         else root.removeSelf();
227         Refresh();
228     }
229
230     private static VectorGraphics.Affine identity = VectorGraphics.Affine.identity();
231
232     /** runs the prerender() and render() pipelines in the root Box to regenerate the backbuffer, then blits it to the screen */
233     public synchronized void render() {
234         // make sure the root is properly sized
235         do {
236             abort = false;
237             root.repack();
238             if (pendingWidth != -1) root.setMaxWidth(JS.N(pendingWidth));
239             if (pendingHeight != -1) root.setMaxHeight(JS.N(pendingHeight));
240             // dirty the place where the scar used to be in case the root window size was programmatically changed
241             if (root.maxwidth != root.width || root.maxheight != root.height)
242                 root.dirty(0, root.height - Main.scarImage.height, Main.scarImage.width, Main.scarImage.height);
243             root.resize(root.x, root.y, root.maxwidth, root.maxheight);
244             root.resize_children();
245             _setSize(root.width, root.height);
246             String oldcursor = cursor;
247             cursor = "default";
248             root.putAndTriggerTrapsAndCatchExceptions("_Move", JS.T);
249             if (!cursor.equals(oldcursor)) syncCursor();
250         } while(abort);
251
252         int[][] dirt = dirtyRegions.flush();
253         for(int i = 0; dirt != null && i < dirt.length; i++) {
254             if (dirt[i] == null) continue;
255             int x = dirt[i][0], y = dirt[i][1], w = dirt[i][2], h = dirt[i][3];
256             if (x < 0) x = 0;
257             if (y < 0) y = 0;
258             if (x+w > root.width) w = root.width - x;
259             if (y+h > root.height) h = root.height - y;
260             if (w <= 0 || h <= 0) continue;
261
262             root.render(0, 0, x, y, x + w, y + h, this, identity);
263             drawPicture(Main.scarImage, 0, root.height - Main.scarImage.height, x, y, w, h);
264             
265             if (abort) {
266
267                 // x,y,w,h is only partially reconstructed, so we must be careful not to re-blit it
268                 dirtyRegions.dirty(x, y, w, h);
269
270                 // put back all the dirty regions we haven't yet processed (including the current one)
271                 for(int j=i; j<dirt.length; j++)
272                     if (dirt[j] != null)
273                         dirtyRegions.dirty(dirt[j][0], dirt[j][1], dirt[j][2], dirt[j][3]);
274
275                 return;
276             }
277         }
278     }
279
280     // FEATURE: reinstate recycler
281     public class SimpleMessage implements Scheduler.Task {
282         
283         private Box boxContainingMouse;
284         private Object value;
285         public String name;
286         
287         SimpleMessage(String name, Object value, Box boxContainingMouse) {
288             this.boxContainingMouse = boxContainingMouse;
289             this.name = name;
290             this.value = value;
291             Scheduler.add(this);
292         }
293         
294         public void perform() {
295             if (name.equals("_KeyPressed")) {
296                 String value = (String)this.value;
297                 if (value.toLowerCase().endsWith("shift")) shift = true;     else if (shift) value = value.toUpperCase();
298                 if (value.toLowerCase().equals("alt")) alt = true;           else if (alt) value = "A-" + value;
299                 if (value.toLowerCase().endsWith("control")) control = true; else if (control) value = "C-" + value;
300                 if (value.equals("C-v") || value.equals("A-v")) Platform.clipboardReadEnabled = true;
301                 this.value = value;
302             } else if (name.equals("_KeyReleased")) {
303                 String value = (String)this.value;
304                 if (value.toLowerCase().equals("alt")) alt = false;
305                 else if (value.toLowerCase().equals("control")) control = false;
306                 else if (value.toLowerCase().equals("shift")) shift = false;
307                 this.value = value;
308             }
309             try {
310                 boxContainingMouse.putAndTriggerTraps(name, value);
311             } catch (JSExn e) {
312                 Log.info(Surface.class, "Exception thrown from "+name+" handler");
313                 JS.log(e);
314             } finally {
315                 Platform.clipboardReadEnabled = false;
316             }
317         }
318         public String toString() { return "SimpleMessage [name=" + name + ", value=" + value + "]"; }
319
320     }
321
322
323     // Default PixelBuffer implementation /////////////////////////////////////////////////////////
324
325     public static abstract class DoubleBufferedSurface extends Surface {
326
327         public DoubleBufferedSurface(Box root) { super(root); }
328         PixelBuffer backbuffer = Platform.createPixelBuffer(Platform.getScreenWidth(), Platform.getScreenHeight(), this);
329         DirtyList screenDirtyRegions = new DirtyList();
330
331         public void drawPicture(Picture source, int dx, int dy, int cx1, int cy1, int cx2, int cy2) {
332             screenDirtyRegions.dirty(cx1, cy1, cx2 - cx1, cy2 - cy1);
333             backbuffer.drawPicture(source, dx, dy, cx1, cy1, cx2, cy2);
334         }
335
336         public void drawGlyph(Font.Glyph source, int dx, int dy, int cx1, int cy1, int cx2, int cy2, int argb) {
337             screenDirtyRegions.dirty(cx1, cy1, cx2 - cx1, cy2 - cy1);
338             backbuffer.drawGlyph(source, dx, dy, cx1, cy1, cx2, cy2, argb);
339         }
340
341         public void fillTrapezoid(int x1, int x2, int y1, int x3, int x4, int y2, int color) {
342             screenDirtyRegions.dirty(Math.min(x1, x3), y1, Math.max(x2, x4) - Math.min(x1, x3), y2 - y1);
343             backbuffer.fillTrapezoid(x1, x2, y1, x3, x4, y2, color);
344         }
345
346         public void render() {
347             super.render();
348             if (abort) return;
349             int[][] dirt = screenDirtyRegions.flush();
350             for(int i = 0; dirt != null && i < dirt.length; i++) {
351                 if (dirt[i] == null) continue;
352                 int x = dirt[i][0];
353                 int y = dirt[i][1];
354                 int w = dirt[i][2];
355                 int h = dirt[i][3];
356                 if (x < 0) x = 0;
357                 if (y < 0) y = 0;
358                 if (x+w > root.width) w = root.width - x;
359                 if (y+h > root.height) h = root.height - y;
360                 if (w <= 0 || h <= 0) continue;
361                 if (abort) return;
362                 blit(backbuffer, x, y, x, y, w + x, h + y);
363             }
364         }
365
366         /** This is how subclasses signal a 'shallow dirty', indicating that although the backbuffer is valid, the screen is not */
367         public final void Dirty(int x, int y, int w, int h) {
368             screenDirtyRegions.dirty(x, y, w, h);
369             Scheduler.renderAll();
370         }
371
372         public void dirty(int x, int y, int w, int h) {
373             screenDirtyRegions.dirty(x, y, w, h);
374             super.dirty(x, y, w, h);
375         }
376
377         /** copies a region from the doublebuffer to this surface */
378         public abstract void blit(PixelBuffer source, int sx, int sy, int dx, int dy, int dx2, int dy2);
379
380     }
381
382 }