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