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