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.
5 package org.ibex.graphics;
8 import org.ibex.util.*;
9 import org.ibex.plat.*;
11 import org.ibex.core.*; // FIXME
14 * A Surface, as described in the Ibex Reference.
16 * Platform subclasses should include an inner class subclass of
17 * Surface to return from the Platform._createSurface() method
19 public abstract class Surface extends PixelBuffer implements Callable {
21 // Static Data ////////////////////////////////////////////////////////////////////////////////
23 private static final JS T = JSU.T;
24 private static final JS F = JSU.F;
26 /** all instances of Surface which need to be refreshed by the Scheduler */
27 public static Vec allSurfaces = new Vec();
29 /** When set to true, render() should abort as soon as possible and restart the rendering process */
30 public volatile boolean abort = false;
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;
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
45 // Instance Data ///////////////////////////////////////////////////////////////////////
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
60 // Used For Simulating Clicks and DoubleClicks /////////////////////////////////////////////////
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
68 // Methods to be overridden by subclasses ///////////////////////////////////////////////////////
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); }
84 public static Picture scarImage = null;
86 // Helper methods for subclasses ////////////////////////////////////////////////////////////
88 protected final void Press(final int button) {
89 last_press_x = mousex;
90 last_press_y = mousey;
92 if (button == 1) button1 = true;
93 else if (button == 2) button2 = true;
94 else if (button == 3) button3 = true;
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 Scheduler.add(new Callable() { public Object run(Object o) throws JSExn {
100 Platform.clipboardReadEnabled = true;
102 root.putAndTriggerTraps(JSU.S("_Press3"), T);
104 Platform.clipboardReadEnabled = false;
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;
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);
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;
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;
137 private final static JS MOVE = JSU.S("_Move");
138 /** we enqueue ourselves in the 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();
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).
158 protected final void Move(final int newmousex, final int newmousey) {
159 this.newmousex = newmousex;
160 this.newmousey = newmousey;
161 Scheduler.add(mover);
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); }
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;
176 Scheduler.renderAll();
179 // FEATURE: can we avoid creating objects here?
180 protected final void PosChange(final int x, final int y) {
181 Scheduler.add(new Callable() { public Object run(Object o) throws JSExn {
184 root.putAndTriggerTrapsAndCatchExceptions(JSU.S("PosChange"), T);
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); }
198 private boolean scheduled = false;
199 public void Refresh() { if (!scheduled) Scheduler.add(this); scheduled = true; }
200 public Object run(Object o) { scheduled = false; Scheduler.renderAll(); return null; }
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); }
206 // Other Methods ///////////////////////////////////////////////////////////////////////////////
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);
213 if (allSurfaces.size() == 0) {
214 if (Log.on) Log.info(this, "exiting because last surface was destroyed");
219 public void dirty(int x, int y, int w, int h) {
220 dirtyRegions.dirty(x, y, w, h);
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;
233 public Surface(Box 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();
254 private static Affine identity = Affine.identity();
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() {
259 // make sure the root is properly sized
263 if (syncRootBoxToSurface) {
264 root.setWidth(root.minwidth, pendingWidth);
265 root.setHeight(root.minheight, pendingHeight);
266 syncRootBoxToSurface = false;
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);
276 setSize(rootwidth, rootheight);
277 /*String oldcursor = cursor;
279 root.putAndTriggerTrapsAndCatchExceptions("_Move", JSU.T);
280 if (!cursor.equals(oldcursor)) syncCursor();*/
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];
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;
293 root.render(0, 0, x, y, x + w, y + h, this, identity);
294 drawPicture(scarImage, 0, root.height - scarImage.height, x, y, x+w, y+h);
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++)
302 dirtyRegions.dirty(dirt[j][0], dirt[j][1], dirt[j][2], dirt[j][3]);
310 // FEATURE: reinstate recycler
311 public class Message implements Callable {
313 private Box boxContainingMouse;
317 Message(String name, JS value, Box boxContainingMouse) {
318 this.boxContainingMouse = boxContainingMouse;
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());
344 boxContainingMouse.putAndTriggerTrapsAndCatchExceptions(JSU.S(name), value);
346 Platform.clipboardReadEnabled = false;
350 public String toString() { return "Message [name=" + name + ", value=" + JSU.str(value) + "]"; }
354 // Default PixelBuffer implementation /////////////////////////////////////////////////////////
356 public static abstract class DoubleBufferedSurface extends Surface {
358 public DoubleBufferedSurface(Box root) { super(root); }
359 PixelBuffer backbuffer = Platform.createPixelBuffer(Platform.getScreenWidth(), Platform.getScreenHeight(), this);
360 DirtyList screenDirtyRegions = new DirtyList();
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);
367 public void drawGlyph(Font.Glyph source, int dx, int dy, int cx1, int cy1, int cx2, int cy2, int argb) {
368 screenDirtyRegions.dirty(cx1, cy1, cx2 - cx1, cy2 - cy1);
369 backbuffer.drawGlyph(source, dx, dy, cx1, cy1, cx2, cy2, argb);
372 public void fillTrapezoid(int x1, int x2, int y1, int x3, int x4, int y2, int color) {
373 screenDirtyRegions.dirty(Math.min(x1, x3), y1, Math.max(x2, x4) - Math.min(x1, x3), y2 - y1);
374 backbuffer.fillTrapezoid(x1, x2, y1, x3, x4, y2, color);
377 public void render() {
380 int[][] dirt = screenDirtyRegions.flush();
381 for(int i = 0; dirt != null && i < dirt.length; i++) {
382 if (dirt[i] == null) continue;
389 if (x+w > root.width) w = root.width - x;
390 if (y+h > root.height) h = root.height - y;
391 if (w <= 0 || h <= 0) continue;
393 blit(backbuffer, x, y, x, y, w + x, h + y);
397 /** This is how subclasses signal a 'shallow dirty', indicating that although the backbuffer is valid, the screen is not */
398 public final void Dirty(int x, int y, int w, int h) {
399 screenDirtyRegions.dirty(x, y, w, h);
400 Scheduler.renderAll();
403 public void dirty(int x, int y, int w, int h) {
404 screenDirtyRegions.dirty(x, y, w, h);
405 super.dirty(x, y, w, h);
408 /** copies a region from the doublebuffer to this surface */
409 public abstract void blit(PixelBuffer source, int sx, int sy, int dx, int dy, int dx2, int dy2);