initial checkin
[org.ibex.nanogoat.git] / src / org / ibex / Surface.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex;
3
4 import org.ibex.js.*;
5 import org.ibex.util.*;
6
7 /** 
8  *  A Surface, as described in the Ibex Reference.
9  *
10  *  Platform subclasses should include an inner class subclass of
11  *  Surface to return from the Platform._createSurface() method
12  */
13 public abstract class Surface extends PixelBuffer implements Scheduler.Task {
14
15     private final static boolean NANOGOAT_KEEP_ALL_METHODS = true;
16
17     // Static Data ////////////////////////////////////////////////////////////////////////////////
18
19     private static Boolean T = Boolean.TRUE;
20     private static Boolean F = Boolean.FALSE;
21
22     /** all instances of Surface which need to be refreshed by the Scheduler */
23     public static Vec allSurfaces = new Vec();
24     
25     /** When set to true, render() should abort as soon as possible and restart the rendering process */
26     volatile boolean abort = false;
27
28     // these three variables are used to ensure that user resizes trump programmatic resizes
29     volatile boolean syncRootBoxToSurface = false;
30     volatile int pendingWidth = 0;
31     volatile int pendingHeight = 0;
32
33     public static boolean alt = false;          ///< true iff the alt button is pressed down
34     public static boolean control = false;      ///< true iff the control button is pressed down
35     public static boolean shift = false;        ///< true iff the shift button is pressed down
36     public static boolean button1 = false;      ///< true iff button 1 is depressed
37     public static boolean button2 = false;      ///< true iff button 2 is depressed
38     public static boolean button3 = false;      ///< true iff button 3 is depressed
39
40
41     // Instance Data ///////////////////////////////////////////////////////////////////////
42
43     public Box root;                                   ///< The Box at the root of this surface
44     public String cursor = "default";                  ///< The active cursor to switch to when syncCursor() is called
45     public int mousex;                                 ///< x position of the mouse
46     public int mousey;                                 ///< y position of the mouse
47     public int _mousex;                                ///< x position of the mouse FIXME
48     public int _mousey;                                ///< y position of the mouse FIXME
49     public int newmousex = -1;                         ///< x position of the mouse, in real time; this lets us collapse Move's
50     public int newmousey = -1;                         ///< y position of the mouse, in real time; this lets us collapse Move's
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     DirtyList dirtyRegions = new DirtyList();          ///< Dirty regions on the surface
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 setMinimumSize(int minx, int miny, boolean resizable) { }
77     protected void setSize(int w, int h) { _setSize(w, h); }
78
79
80     // Helper methods for subclasses ////////////////////////////////////////////////////////////
81
82     protected final void Press(final int button) {
83         last_press_x = mousex;
84         last_press_y = mousey;
85
86         if (button == 1) button1 = true;
87         else if (button == 2) button2 = true;
88         else if (button == 3) button3 = true;
89
90         if (button == 1) new Message("_Press1", T, root);
91         else if (button == 2) new Message("_Press2", T, root);
92         else if (button == 3) {
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 Message("_Release1", T, root);
110         else if (button == 2) new Message("_Release2", T, root);
111         else if (button == 3) new Message("_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 Message("_Click1", T, root);
120         else if (button == 2) new Message("_Click2", T, root);
121         else if (button == 3) new Message("_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     private Scheduler.Task mover = new Scheduler.Task() {
132             public void perform() {
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                     root.putAndTriggerTrapsAndCatchExceptions("_Move", T);
140                 if (!cursor.equals(oldcursor)) syncCursor();
141             } };
142
143     /**
144      *  Notify Ibex that the mouse has moved. If the mouse leaves the
145      *  surface, but the host windowing system does not provide its new
146      *  position (for example, a Java MouseListener.mouseExited()
147      *  message), the subclass should use (-1,-1).
148      */
149     protected final void Move(final int newmousex, final int newmousey) {
150         this.newmousex = newmousex;
151         this.newmousey = newmousey;
152         Scheduler.add(mover);
153     }
154
155     protected final void HScroll(int pixels) { new Message("_HScroll", new Integer(pixels), root); }
156     protected final void VScroll(int pixels) { new Message("_VScroll", new Integer(pixels), root); }
157     protected final void HScroll(float lines) { new Message("_HScroll", new Float(lines), root); }
158     protected final void VScroll(float lines) { new Message("_VScroll", new Float(lines), root); }
159
160     /** subclasses should invoke this method when the user resizes the window */
161     protected final void SizeChange(final int width, final int height) {
162         if (pendingWidth == width && pendingHeight == height) return;
163         pendingWidth = width;
164         pendingHeight = height;
165         syncRootBoxToSurface = true;
166         abort = true;
167         Scheduler.renderAll();
168     }
169
170     // FEATURE: can we avoid creating objects here?
171     protected final void PosChange(final int x, final int y) {
172         Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn {
173             root.x = x;
174             root.y = y;
175             root.putAndTriggerTrapsAndCatchExceptions("PosChange", T);
176         }});
177     }
178
179     private final String[] doubleClick = new String[] { null, "_DoubleClick1", "_DoubleClick2", "_DoubleClick3" };
180     protected final void DoubleClick(int button) { new Message(doubleClick[button], T, root); }
181     protected final void KeyPressed(String key) { new Message("_KeyPressed", key, root); }
182     protected final void KeyReleased(String key) { new Message("_KeyReleased", key, root); }
183     protected final void Close() { new Message("Close", T, root); }
184     protected final void Minimized(boolean b) { minimized = b; new Message("Minimized", b ? T : F, root); }
185     protected final void Maximized(boolean b) { maximized = b; new Message("Maximized", b ? T : F, root); }
186     protected final void Focused(boolean b) { new Message("Focused", b ? T : F, root); }
187
188     private boolean scheduled = false;
189     public void Refresh() { if (!scheduled) Scheduler.add(this); scheduled = true; }
190     public void perform() { scheduled = false; Scheduler.renderAll(); }
191
192     public final void setMaximized(boolean b) { if (b != maximized) _setMaximized(maximized = b); }
193     public final void setMinimized(boolean b) { if (b != minimized) _setMinimized(minimized = b); }
194
195
196     // Other Methods ///////////////////////////////////////////////////////////////////////////////
197
198     /** Indicates that the Surface is no longer needed */
199     public final void dispose(boolean quitIfAllSurfacesGone) {
200         if (Log.on) Log.info(this, "disposing " + this);
201         allSurfaces.removeElement(this);
202         _dispose();
203         if (allSurfaces.size() == 0) {
204             if (Log.on) Log.info(this, "exiting because last surface was destroyed");
205             System.exit(0);
206         }
207     }
208
209     public void dirty(int x, int y, int w, int h) {
210         dirtyRegions.dirty(x, y, w, h);
211         Refresh();
212     }
213
214     public static Surface fromBox(Box b) {
215         // FIXME use a hash table here
216         for(int i=0; i<allSurfaces.size(); i++) {
217             Surface s = (Surface)allSurfaces.elementAt(i);
218             if (s.root == b) return s;
219         }
220         return null;
221     }
222
223     public Surface(Box root) {
224         this.root = root;
225         root.setMaxWidth(JS.N(Math.min(Platform.getScreenWidth(), root.maxwidth)));
226         root.setMaxHeight(JS.N(Math.min(Platform.getScreenHeight(), root.maxheight)));
227         Surface old = fromBox(root);
228         if (old != null) old.dispose(false);
229         else root.removeSelf();
230         Refresh();
231     }
232
233     private static VectorGraphics.Affine identity = VectorGraphics.Affine.identity();
234
235     /** runs the prerender() and render() pipelines in the root Box to regenerate the backbuffer, then blits it to the screen */
236     public synchronized void render() {
237         scheduled = false;
238         // make sure the root is properly sized
239         do {
240             abort = false;
241             root.repack();
242             if (syncRootBoxToSurface) {
243                 root.setMaxWidth(JS.N(pendingWidth));
244                 root.setMaxHeight(JS.N(pendingHeight));
245                 syncRootBoxToSurface = false;
246             }
247             if (root.maxwidth != root.width || root.maxheight != root.height) {
248                 // dirty the place where the scar used to be and where it is now
249                 dirty(0, root.height - Main.scarImage.height, Main.scarImage.width, Main.scarImage.height);
250                 dirty(0, root.maxheight - Main.scarImage.height, Main.scarImage.width, Main.scarImage.height);
251             }
252             root.resize(root.x, root.y, root.maxwidth, root.maxheight);
253             root.resize_children();
254             setSize(root.width, root.height);
255             String oldcursor = cursor;
256             cursor = "default";
257             root.putAndTriggerTrapsAndCatchExceptions("_Move", JS.T);
258             if (!cursor.equals(oldcursor)) syncCursor();
259         } while(abort);
260
261         int[][] dirt = dirtyRegions.flush();
262         for(int i = 0; dirt != null && i < dirt.length; i++) {
263             if (dirt[i] == null) continue;
264             int x = dirt[i][0], y = dirt[i][1], w = dirt[i][2], h = dirt[i][3];
265             if (x < 0) x = 0;
266             if (y < 0) y = 0;
267             if (x+w > root.width) w = root.width - x;
268             if (y+h > root.height) h = root.height - y;
269             if (w <= 0 || h <= 0) continue;
270
271             root.render(0, 0, x, y, x + w, y + h, this, identity);
272             drawPicture(Main.scarImage, 0, root.height - Main.scarImage.height, x, y, x+w, y+h);
273             
274             if (abort) {
275                 // x,y,w,h is only partially reconstructed, so we must be careful not to re-blit it
276                 dirtyRegions.dirty(x, y, w, h);
277                 // put back all the dirty regions we haven't yet processed (including the current one)
278                 for(int j=i; j<dirt.length; j++)
279                     if (dirt[j] != null)
280                         dirtyRegions.dirty(dirt[j][0], dirt[j][1], dirt[j][2], dirt[j][3]);
281                 return;
282             }
283         }
284     }
285
286     // FEATURE: reinstate recycler
287     public class Message implements Scheduler.Task {
288         
289         private Box boxContainingMouse;
290         private Object value;
291         public String name;
292         
293         Message(String name, Object value, Box boxContainingMouse) {
294             this.boxContainingMouse = boxContainingMouse;
295             this.name = name;
296             this.value = value;
297             Scheduler.add(this);
298         }
299         
300         public void perform() {
301             if (name.equals("_KeyPressed")) {
302                 String value = (String)this.value;
303                 if (value.toLowerCase().endsWith("shift")) shift = true;     else if (shift) value = value.toUpperCase();
304                 if (value.toLowerCase().equals("alt")) alt = true;           else if (alt) value = "A-" + value;
305                 if (value.toLowerCase().endsWith("control")) control = true; else if (control) value = "C-" + value;
306                 if (value.equals("C-v") || value.equals("A-v")) Platform.clipboardReadEnabled = true;
307                 this.value = value;
308             } else if (name.equals("_KeyReleased")) {
309                 String value = (String)this.value;
310                 if (value.toLowerCase().equals("alt")) alt = false;
311                 else if (value.toLowerCase().equals("control")) control = false;
312                 else if (value.toLowerCase().equals("shift")) shift = false;
313                 this.value = value;
314             } else if (name.equals("_HScroll") || name.equals("_VScroll")) {
315                 // FIXME: technically points != pixels
316                 if (value instanceof Integer)
317                     value = new Float(((Integer)value).intValue() * root.fontSize());
318             }
319             try {
320                 boxContainingMouse.putAndTriggerTrapsAndCatchExceptions(name, value);
321             } finally {
322                 Platform.clipboardReadEnabled = false;
323             }
324         }
325         public String toString() { return "Message [name=" + name + ", value=" + value + "]"; }
326     }
327
328
329     // Default PixelBuffer implementation /////////////////////////////////////////////////////////
330
331     public static abstract class DoubleBufferedSurface extends Surface {
332
333         public DoubleBufferedSurface(Box root) { super(root); }
334         PixelBuffer backbuffer = Platform.createPixelBuffer(Platform.getScreenWidth(), Platform.getScreenHeight(), this);
335         DirtyList screenDirtyRegions = new DirtyList();
336
337         public void drawPicture(Picture source, int dx, int dy, int cx1, int cy1, int cx2, int cy2) {
338             screenDirtyRegions.dirty(cx1, cy1, cx2 - cx1, cy2 - cy1);
339             backbuffer.drawPicture(source, dx, dy, cx1, cy1, cx2, cy2);
340         }
341
342         public void drawGlyph(Font.Glyph source, int dx, int dy, int cx1, int cy1, int cx2, int cy2, int argb) {
343             screenDirtyRegions.dirty(cx1, cy1, cx2 - cx1, cy2 - cy1);
344             backbuffer.drawGlyph(source, dx, dy, cx1, cy1, cx2, cy2, argb);
345         }
346
347         public void fillTrapezoid(int x1, int x2, int y1, int x3, int x4, int y2, int color) {
348             screenDirtyRegions.dirty(Math.min(x1, x3), y1, Math.max(x2, x4) - Math.min(x1, x3), y2 - y1);
349             backbuffer.fillTrapezoid(x1, x2, y1, x3, x4, y2, color);
350         }
351
352         public void render() {
353             super.render();
354             if (abort) return;
355             int[][] dirt = screenDirtyRegions.flush();
356             for(int i = 0; dirt != null && i < dirt.length; i++) {
357                 if (dirt[i] == null) continue;
358                 int x = dirt[i][0];
359                 int y = dirt[i][1];
360                 int w = dirt[i][2];
361                 int h = dirt[i][3];
362                 if (x < 0) x = 0;
363                 if (y < 0) y = 0;
364                 if (x+w > root.width) w = root.width - x;
365                 if (y+h > root.height) h = root.height - y;
366                 if (w <= 0 || h <= 0) continue;
367                 if (abort) return;
368                 blit(backbuffer, x, y, x, y, w + x, h + y);
369             }
370         }
371
372         /** This is how subclasses signal a 'shallow dirty', indicating that although the backbuffer is valid, the screen is not */
373         public final void Dirty(int x, int y, int w, int h) {
374             screenDirtyRegions.dirty(x, y, w, h);
375             Scheduler.renderAll();
376         }
377
378         public void dirty(int x, int y, int w, int h) {
379             screenDirtyRegions.dirty(x, y, w, h);
380             super.dirty(x, y, w, h);
381         }
382
383         /** copies a region from the doublebuffer to this surface */
384         public abstract void blit(PixelBuffer source, int sx, int sy, int dx, int dy, int dx2, int dy2);
385
386     }
387
388 }