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