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