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