preliminary core conversion
[org.ibex.core.git] / src / org / ibex / graphics / Surface.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex.graphics;
3
4 import org.ibex.js.*;
5 import org.ibex.util.*;
6 import org.ibex.plat.*;
7
8 import org.ibex.core.*;  // FIXME
9
10 /** 
11  *  A Surface, as described in the Ibex Reference.
12  *
13  *  Platform subclasses should include an inner class subclass of
14  *  Surface to return from the Platform._createSurface() method
15  */
16 public abstract class Surface extends PixelBuffer implements Task {
17
18     // Static Data ////////////////////////////////////////////////////////////////////////////////
19
20     private static final JS T = JS.T;
21     private static final JS F = JS.F;
22
23     /** all instances of Surface which need to be refreshed by the Scheduler */
24     public static Vec allSurfaces = new Vec();
25     
26     /** When set to true, render() should abort as soon as possible and restart the rendering process */
27     public volatile boolean abort = false;
28
29     // these three variables are used to ensure that user resizes trump programmatic resizes
30     public volatile boolean syncRootBoxToSurface = false;
31     public volatile int pendingWidth = 0;
32     public volatile int pendingHeight = 0;
33
34     public static boolean alt = false;          ///< true iff the alt button is pressed down
35     public static boolean control = false;      ///< true iff the control button is pressed down
36     public static boolean shift = false;        ///< true iff the shift button is pressed down
37     public static boolean button1 = false;      ///< true iff button 1 is depressed
38     public static boolean button2 = false;      ///< true iff button 2 is depressed
39     public static boolean button3 = false;      ///< true iff button 3 is depressed
40
41
42     // Instance Data ///////////////////////////////////////////////////////////////////////
43
44     public Box root;                                   ///< The Box at the root of this surface
45     public String cursor = "default";                  ///< The active cursor to switch to when syncCursor() is called
46     public int mousex;                                 ///< x position of the mouse
47     public int mousey;                                 ///< y position of the mouse
48     public int _mousex;                                ///< x position of the mouse FIXME
49     public int _mousey;                                ///< y position of the mouse FIXME
50     public int newmousex = -1;                         ///< x position of the mouse, in real time; this lets us collapse Move's
51     public int newmousey = -1;                         ///< y position of the mouse, in real time; this lets us collapse Move's
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     public boolean unrendered = true;                  ///< True iff this surface has not yet been rendered
55     DirtyList dirtyRegions = new DirtyList();          ///< Dirty regions on the surface
56
57     // Used For Simulating Clicks and DoubleClicks /////////////////////////////////////////////////
58
59     int last_press_x = Integer.MAX_VALUE;      ///< the x-position of the mouse the last time a Press message was enqueued
60     int last_press_y = Integer.MAX_VALUE;      ///< the y-position of the mouse the last time a Press message was enqueued
61     static int lastClickButton = 0;            ///< the last button to recieve a Click message; used for simulating DoubleClick's
62     static long lastClickTime = 0;             ///< the last time a Click message was processed; used for simulating DoubleClick's
63     
64     
65     // Methods to be overridden by subclasses ///////////////////////////////////////////////////////
66
67     public abstract void toBack();                     ///< should push surface to the back of the stacking order
68     public abstract void toFront();                    ///< should pull surface to the front of the stacking order
69     public abstract void syncCursor();                 ///< set the actual cursor to this.cursor if they do not match
70     public abstract void setInvisible(boolean b);      ///< If <tt>b</tt>, make window invisible; otherwise, make it non-invisible.
71     protected abstract void _setMaximized(boolean b);  ///< If <tt>b</tt>, maximize the surface; otherwise, un-maximize it.
72     protected abstract void _setMinimized(boolean b);  ///< If <tt>b</tt>, minimize the surface; otherwise, un-minimize it.
73     public abstract void setLocation();                ///< Set the surface's x/y position to that of the root box
74     protected abstract void _setSize(int w, int h);    ///< set the actual size of the surface
75     public abstract void setTitleBarText(String s);    ///< Sets the surface's title bar text, if applicable
76     public abstract void setIcon(Picture i);           ///< Sets the surface's title bar text, if applicable
77     public abstract void _dispose();                   ///< Destroy the surface
78     public void setMinimumSize(int minx, int miny, boolean resizable) { }
79     protected void setSize(int w, int h) { _setSize(w, h); }
80
81     public static Picture scarImage = null;
82
83     // Helper methods for subclasses ////////////////////////////////////////////////////////////
84
85     protected final void Press(final int button) {
86         last_press_x = mousex;
87         last_press_y = mousey;
88
89         if (button == 1) button1 = true;
90         else if (button == 2) button2 = true;
91         else if (button == 3) button3 = true;
92
93         if (button == 1) new Message("_Press1", T, root);
94         else if (button == 2) new Message("_Press2", T, root);
95         else if (button == 3) {
96             Scheduler.add(new Task() { public void perform() throws JSExn {
97                 Platform.clipboardReadEnabled = true;
98                 try {
99                     root.putAndTriggerTraps(JS.S("_Press3"), T);
100                 } finally {
101                     Platform.clipboardReadEnabled = false;
102                 }
103             }});
104         }
105     }
106
107     protected final void Release(int button) {
108         if (button == 1) button1 = false;
109         else if (button == 2) button2 = false;
110         else if (button == 3) button3 = false;
111
112         if (button == 1) new Message("_Release1", T, root);
113         else if (button == 2) new Message("_Release2", T, root);
114         else if (button == 3) new Message("_Release3", T, root);
115
116         if (Platform.needsAutoClick() && Math.abs(last_press_x - mousex) < 5 && Math.abs(last_press_y - mousey) < 5) Click(button);
117         last_press_x = Integer.MAX_VALUE;
118         last_press_y = Integer.MAX_VALUE;
119     }
120
121     protected final void Click(int button) {
122         if (button == 1) new Message("_Click1", T, root);
123         else if (button == 2) new Message("_Click2", T, root);
124         else if (button == 3) new Message("_Click3", T, root);
125         if (Platform.needsAutoDoubleClick()) {
126             long now = System.currentTimeMillis();
127             if (lastClickButton == button && now - lastClickTime < 350) DoubleClick(button);
128             lastClickButton = button;
129             lastClickTime = now;
130         }
131     }
132
133     private final static JS MOVE = JS.S("_Move");
134     /** we enqueue ourselves in the Scheduler when we have a Move message to deal with */
135     private Task mover = new Task() {
136             public void perform() {
137                 if (mousex == newmousex && mousey == newmousey) return;
138                 int oldmousex = mousex;     mousex = newmousex;
139                 int oldmousey = mousey;     mousey = newmousey;
140                 String oldcursor = cursor;  cursor = "default";
141                 // FIXME: Root (ONLY) gets motion events outside itself (if trapped)
142                 if (oldmousex != mousex || oldmousey != mousey)
143                     root.putAndTriggerTrapsAndCatchExceptions(MOVE, T);
144                 if (!cursor.equals(oldcursor)) syncCursor();
145             } };
146
147     /**
148      *  Notify Ibex that the mouse has moved. If the mouse leaves the
149      *  surface, but the host windowing system does not provide its new
150      *  position (for example, a Java MouseListener.mouseExited()
151      *  message), the subclass should use (-1,-1).
152      */
153     protected final void Move(final int newmousex, final int newmousey) {
154         this.newmousex = newmousex;
155         this.newmousey = newmousey;
156         Scheduler.add(mover);
157     }
158
159     protected final void HScroll(int pixels) { new Message("_HScroll", JS.N(pixels), root); }
160     protected final void VScroll(int pixels) { new Message("_VScroll", JS.N(pixels), root); }
161     protected final void HScroll(float lines) { new Message("_HScroll", JS.N(lines), root); }
162     protected final void VScroll(float lines) { new Message("_VScroll", JS.N(lines), root); }
163
164     /** subclasses should invoke this method when the user resizes the window */
165     protected final void SizeChange(final int width, final int height) {
166         if (unrendered || (pendingWidth == width && pendingHeight == height)) return;
167         pendingWidth = width;
168         pendingHeight = height;
169         syncRootBoxToSurface = true;
170         abort = true;
171         Scheduler.renderAll();
172     }
173
174     // FEATURE: can we avoid creating objects here?
175     protected final void PosChange(final int x, final int y) {
176         Scheduler.add(new Task() { public void perform() throws JSExn {
177             root.x = x;
178             root.y = y;
179             root.putAndTriggerTrapsAndCatchExceptions(JS.S("PosChange"), T);
180         }});
181     }
182
183     private final String[] doubleClick = new String[] { null, "_DoubleClick1", "_DoubleClick2", "_DoubleClick3" };
184     protected final void DoubleClick(int button) { new Message(doubleClick[button], T, root); }
185     protected final void KeyPressed(String key) { new Message("_KeyPressed", JS.S(key), root); }
186     protected final void KeyReleased(String key) { new Message("_KeyReleased", JS.S(key), root); }
187     protected final void Close() { new Message("Close", T, root); }
188     protected final void Minimized(boolean b) { minimized = b; new Message("Minimized", b ? T : F, root); }
189     protected final void Maximized(boolean b) { maximized = b; new Message("Maximized", b ? T : F, root); }
190     protected final void Focused(boolean b) { new Message("Focused", b ? T : F, root); }
191
192     private boolean scheduled = false;
193     public void Refresh() { if (!scheduled) Scheduler.add(this); scheduled = true; }
194     public void perform() { scheduled = false; Scheduler.renderAll(); }
195
196     public final void setMaximized(boolean b) { if (b != maximized) _setMaximized(maximized = b); }
197     public final void setMinimized(boolean b) { if (b != minimized) _setMinimized(minimized = b); }
198
199
200     // Other Methods ///////////////////////////////////////////////////////////////////////////////
201
202     /** Indicates that the Surface is no longer needed */
203     public final void dispose(boolean quitIfAllSurfacesGone) {
204         if (Log.on) Log.info(this, "disposing " + this);
205         allSurfaces.removeElement(this);
206         _dispose();
207         if (allSurfaces.size() == 0) {
208             if (Log.on) Log.info(this, "exiting because last surface was destroyed");
209             System.exit(0);
210         }
211     }
212
213     public void dirty(int x, int y, int w, int h) {
214         dirtyRegions.dirty(x, y, w, h);
215         Refresh();
216     }
217
218     public static Surface fromBox(Box b) {
219         // FIXME use a hash table here
220         for(int i=0; i<allSurfaces.size(); i++) {
221             Surface s = (Surface)allSurfaces.elementAt(i);
222             if (s.root == b) return s;
223         }
224         return null;
225     }
226
227     public Surface(Box root) {
228         this.root = root;
229         // FIXME: document this in the reference
230         if (!root.test(root.HSHRINK) && root.maxwidth == Integer.MAX_VALUE)
231             root.maxwidth = Platform.getScreenWidth() / 2;
232         if (!root.test(root.VSHRINK) && root.maxheight == Integer.MAX_VALUE)
233             root.maxheight = Platform.getScreenHeight() / 2;
234         root.setWidth(root.minwidth,
235                       root.test(root.HSHRINK)
236                       ? Math.max(root.minwidth, root.contentwidth)
237                       : Math.min(Platform.getScreenWidth(), root.maxwidth));
238         root.setHeight(root.minheight,
239                       root.test(root.VSHRINK)
240                       ? Math.max(root.minheight, root.contentheight)
241                       : 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 Affine identity = 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         scheduled = false;
253         // make sure the root is properly sized
254         do {
255             abort = false;
256             root.pack();
257             if (syncRootBoxToSurface) {
258                 root.setWidth(root.minwidth, pendingWidth);
259                 root.setHeight(root.minheight, pendingHeight);
260                 syncRootBoxToSurface = false;
261             }
262             int rootwidth = root.test(root.HSHRINK) ? root.contentwidth : root.maxwidth;
263             int rootheight = root.test(root.VSHRINK) ? root.contentheight : root.maxheight;
264             if (rootwidth != root.width || rootheight != root.height) {
265                 // dirty the place where the scar used to be and where it is now
266                 dirty(0, root.height - scarImage.height, scarImage.width, scarImage.height);
267                 dirty(0, rootheight - scarImage.height, scarImage.width, scarImage.height);
268             }
269             root.reflow();
270             setSize(rootwidth, rootheight);
271             /*String oldcursor = cursor;
272             cursor = "default";
273             root.putAndTriggerTrapsAndCatchExceptions("_Move", JS.T);
274             if (!cursor.equals(oldcursor)) syncCursor();*/
275         } while(abort);
276
277         int[][] dirt = dirtyRegions.flush();
278         for(int i = 0; dirt != null && i < dirt.length; i++) {
279             if (dirt[i] == null) continue;
280             int x = dirt[i][0], y = dirt[i][1], w = dirt[i][2], h = dirt[i][3];
281             if (x < 0) x = 0;
282             if (y < 0) y = 0;
283             if (x+w > root.width) w = root.width - x;
284             if (y+h > root.height) h = root.height - y;
285             if (w <= 0 || h <= 0) continue;
286
287             root.render(0, 0, x, y, x + w, y + h, this, identity);
288             drawPicture(scarImage, 0, root.height - scarImage.height, x, y, x+w, y+h);
289             
290             if (abort) {
291                 // x,y,w,h is only partially reconstructed, so we must be careful not to re-blit it
292                 dirtyRegions.dirty(x, y, w, h);
293                 // put back all the dirty regions we haven't yet processed (including the current one)
294                 for(int j=i; j<dirt.length; j++)
295                     if (dirt[j] != null)
296                         dirtyRegions.dirty(dirt[j][0], dirt[j][1], dirt[j][2], dirt[j][3]);
297                 return;
298             }
299         }
300
301         unrendered = false;
302     }
303
304     // FEATURE: reinstate recycler
305     public class Message implements Task {
306         
307         private Box boxContainingMouse;
308         private JS value;
309         public String name;
310         
311         Message(String name, JS value, Box boxContainingMouse) {
312             this.boxContainingMouse = boxContainingMouse;
313             this.name = name;
314             this.value = value;
315             Scheduler.add(this);
316         }
317         
318         public void perform() throws JSExn {
319             if (name.equals("_KeyPressed")) {
320                 String value = JS.toString(this.value);
321                 if (value.toLowerCase().endsWith("shift")) shift = true;     else if (shift) value = value.toUpperCase();
322                 if (value.toLowerCase().equals("alt")) alt = true;           else if (alt) value = "A-" + value;
323                 if (value.toLowerCase().endsWith("control")) control = true; else if (control) value = "C-" + value;
324                 if (value.equals("C-v") || value.equals("A-v")) Platform.clipboardReadEnabled = true;
325                 this.value = JS.S(value);
326             } else if (name.equals("_KeyReleased")) {
327                 String value = JS.toString(this.value);
328                 if (value.toLowerCase().equals("alt")) alt = false;
329                 else if (value.toLowerCase().equals("control")) control = false;
330                 else if (value.toLowerCase().equals("shift")) shift = false;
331                 this.value = JS.S(value);
332             } else if (name.equals("_HScroll") || name.equals("_VScroll")) {
333                 // FIXME: technically points != pixels
334                 if (JS.isInt(value))
335                     value = JS.N(JS.toInt(value) * root.fontSize());
336             }
337             try {
338                 boxContainingMouse.putAndTriggerTrapsAndCatchExceptions(JS.S(name), value);
339             } finally {
340                 Platform.clipboardReadEnabled = false;
341             }
342         }
343         public String toString() { return "Message [name=" + name + ", value=" + value + "]"; }
344     }
345
346
347     // Default PixelBuffer implementation /////////////////////////////////////////////////////////
348
349     public static abstract class DoubleBufferedSurface extends Surface {
350
351         public DoubleBufferedSurface(Box root) { super(root); }
352         PixelBuffer backbuffer = Platform.createPixelBuffer(Platform.getScreenWidth(), Platform.getScreenHeight(), this);
353         DirtyList screenDirtyRegions = new DirtyList();
354
355         public void drawPicture(Picture source, int dx, int dy, int cx1, int cy1, int cx2, int cy2) {
356             screenDirtyRegions.dirty(cx1, cy1, cx2 - cx1, cy2 - cy1);
357             backbuffer.drawPicture(source, dx, dy, cx1, cy1, cx2, cy2);
358         }
359
360         public void drawGlyph(Font.Glyph source, int dx, int dy, int cx1, int cy1, int cx2, int cy2, int argb) {
361             screenDirtyRegions.dirty(cx1, cy1, cx2 - cx1, cy2 - cy1);
362             backbuffer.drawGlyph(source, dx, dy, cx1, cy1, cx2, cy2, argb);
363         }
364
365         public void fillTrapezoid(int x1, int x2, int y1, int x3, int x4, int y2, int color) {
366             screenDirtyRegions.dirty(Math.min(x1, x3), y1, Math.max(x2, x4) - Math.min(x1, x3), y2 - y1);
367             backbuffer.fillTrapezoid(x1, x2, y1, x3, x4, y2, color);
368         }
369
370         public void render() {
371             super.render();
372             if (abort) return;
373             int[][] dirt = screenDirtyRegions.flush();
374             for(int i = 0; dirt != null && i < dirt.length; i++) {
375                 if (dirt[i] == null) continue;
376                 int x = dirt[i][0];
377                 int y = dirt[i][1];
378                 int w = dirt[i][2];
379                 int h = dirt[i][3];
380                 if (x < 0) x = 0;
381                 if (y < 0) y = 0;
382                 if (x+w > root.width) w = root.width - x;
383                 if (y+h > root.height) h = root.height - y;
384                 if (w <= 0 || h <= 0) continue;
385                 if (abort) return;
386                 blit(backbuffer, x, y, x, y, w + x, h + y);
387             }
388         }
389
390         /** This is how subclasses signal a 'shallow dirty', indicating that although the backbuffer is valid, the screen is not */
391         public final void Dirty(int x, int y, int w, int h) {
392             screenDirtyRegions.dirty(x, y, w, h);
393             Scheduler.renderAll();
394         }
395
396         public void dirty(int x, int y, int w, int h) {
397             screenDirtyRegions.dirty(x, y, w, h);
398             super.dirty(x, y, w, h);
399         }
400
401         /** copies a region from the doublebuffer to this surface */
402         public abstract void blit(PixelBuffer source, int sx, int sy, int dx, int dy, int dx2, int dy2);
403
404     }
405
406 }