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