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