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