2 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
5 // FIXME: are traps on x/y meaningful?
6 // FIXME: if we trap on cols, then set rows to 0 (forcing cols to 1), does the cols trap get triggered?
7 // FIXME: if we change min{width/height}, thereby forcing a change to max{min/height}, does a trap on those get triggered?
8 // FIXME: trap on numchildren? replaces ChildChanged?
9 // FIXME: trap on visible, trigger when parent visibility changes
11 // FIXME: ax/ay nonsense
12 // FIXME: mouse move/release still needs to propagate to boxen in which the mouse was pressed and is still held down
14 // FEATURE: mark to reflow starting with a certain child
15 // FEATURE: reintroduce surface.abort
19 import org.ibex.util.*;
20 import org.ibex.graphics.*;
24 * Encapsulates the data for a single Ibex box as well as all layout
28 * <p>The rendering process consists of four phases; each requires
29 * one DFS pass over the tree</p>
30 * <ol><li> <b>pack()</b>: each box sets its childrens' row/col
31 * <ol><li> <b>constrain()</b>: contentwidth is computed
32 * <li> <b>resize()</b>: width/height and x/y positions are set
33 * <li> <b>render()</b>: children draw their content onto the PixelBuffer.
36 * The first three passes together are called the <i>reflow</i>
37 * phase. Reflowing is done in a seperate pass since SizeChanges
38 * trigger a Surface.abort; if rendering were done in the same pass,
39 * rendering work done prior to the Surface.abort would be wasted.
41 public final class Box extends JSScope implements Task {
43 // Macros //////////////////////////////////////////////////////////////////////
45 final void REPLACE() { for(Box b2 = this; b2 != null && !b2.test(REPLACE); b2 = b2.parent) b2.set(REPLACE); }
46 final void RECONSTRAIN() { for(Box b2 = this; b2 != null && !b2.test(RECONSTRAIN); b2 = b2.parent) b2.set(RECONSTRAIN); }
47 final void REPACK() { for(Box b2 = this; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK); }
49 //#define CHECKSET_SHORT(prop) short nu = (short)toInt(value); if (nu == prop) break; prop = nu;
50 //#define CHECKSET_INT(prop) int nu = toInt(value); if (nu == prop) break; prop = nu;
51 //#define CHECKSET_FLAG(flag) boolean nu = toBoolean(value); if (nu == test(flag)) break; if (nu) set(flag); else clear(flag);
52 //#define CHECKSET_BOOLEAN(prop) boolean nu = toBoolean(value); if (nu == prop) break; prop = nu;
53 //#define CHECKSET_STRING(prop) if ((value==null&&prop==null)||(value!=null&&JS.toString(value).equals(prop))) break; prop=JS.toString(value);
55 public Box() { super(null); }
58 static Hash boxToCursor = new Hash(500, 3);
60 static final Font DEFAULT_FONT = Font.getFont((Stream)Main.builtin.get("fonts/vera/Vera.ttf"), 10);
63 // Flags //////////////////////////////////////////////////////////////////////
65 static final int MOUSEINSIDE = 0x00000001;
66 static final int VISIBLE = 0x00000002;
67 static final int PACKED = 0x00000004;
68 static final int HSHRINK = 0x00000008;
69 static final int VSHRINK = 0x00000010;
70 static final int BLACK = 0x00000020; // for red-black code
72 static final int FIXED = 0x00000040;
73 static final boolean ROWS = true;
74 static final boolean COLS = false;
76 static final int ISROOT = 0x00000080;
77 static final int REPACK = 0x00000100;
78 static final int RECONSTRAIN = 0x00000200;
79 static final int REPLACE = 0x00000400;
81 static final int ALIGN_TOP = 0x00001000;
82 static final int ALIGN_BOTTOM = 0x00002000;
83 static final int ALIGN_LEFT = 0x00004000;
84 static final int ALIGN_RIGHT = 0x00008000;
85 static final int ALIGNS = 0x0000f000;
86 static final int CURSOR = 0x00010000; // if true, this box has a cursor in the cursor hash; FEATURE: GC issues?
87 static final int CLIP = 0x00020000;
88 static final int STOP_UPWARD_PROPAGATION = 0x00040000;
89 static final int MOVED = 0x00080000;
92 // Instance Data //////////////////////////////////////////////////////////////////////
96 int flags = VISIBLE | PACKED | REPACK | RECONSTRAIN | REPLACE | FIXED | STOP_UPWARD_PROPAGATION | CLIP | MOVED;
98 private String text = null;
99 private Font font = DEFAULT_FONT;
100 private Picture texture = null;
101 private short strokewidth = 1;
102 public int fillcolor = 0x00000000;
103 private int strokecolor = 0xFF000000;
105 private int aspect = 0;
107 // specified directly by user
108 public int minwidth = 0;
109 public int maxwidth = Integer.MAX_VALUE;
110 public int minheight = 0;
111 public int maxheight = Integer.MAX_VALUE;
112 private short rows = 1;
113 private short cols = 0;
114 private short rowspan = 1;
115 private short colspan = 1;
117 // computed during reflow
118 private short row = 0;
119 private short col = 0;
122 public int ax = 0; // FEATURE: roll these into x/y; requires lots of changes
123 public int ay = 0; // FEATURE: roll these into x/y; requires lots of changes; perhaps y()?
124 public int width = 0;
125 public int height = 0;
126 private int contentwidth = 0; // == max(minwidth, textwidth, sum(child.contentwidth))
127 private int contentheight = 0;
130 private VectorGraphics.VectorPath path = null;
131 private Affine transform = null;
132 private VectorGraphics.RasterPath rpath = null;
133 private Affine rtransform = null;
136 //#define DIRTY dirty()
138 // Instance Methods /////////////////////////////////////////////////////////////////////
140 public final int fontSize() { return font == null ? DEFAULT_FONT.pointsize : font.pointsize; }
142 /** invoked when a resource needed to render ourselves finishes loading */
143 public void perform() throws JSExn {
144 if (texture == null) { Log.warn(Box.class, "perform() called with null texture"); return; }
145 if (texture.isLoaded) {
146 setWidth(max(texture.width, maxwidth), maxwidth);
147 setHeight(max(texture.height, maxheight), maxheight);
149 else { JS res = texture.stream; texture = null; throw new JSExn("image not found: "+res.unclone()); }
152 // FEATURE: use cx2/cy2 format
153 /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
154 public void dirty() { dirty(0, 0, width, height); }
155 public void dirty(int x, int y, int w, int h) {
156 for(Box cur = this; cur != null; cur = cur.parent) {
157 // x and y have a different meaning on the root box
158 if (cur.parent != null && cur.test(CLIP)) {
159 w = min(x + w, cur.width) - max(x, 0);
160 h = min(y + h, cur.height) - max(y, 0);
164 if (w <= 0 || h <= 0) return;
165 if (cur.parent == null && cur.getSurface() != null) cur.getSurface().dirty(x, y, w, h);
172 // Reflow ////////////////////////////////////////////////////////////////////////////////////////
174 /** should only be invoked on the root box */
175 public void reflow() { pack(); resize(x, y, maxwidth, maxheight); place(); }
177 private static Box[] frontier = new Box[65535];
178 /** pack the boxes into rows and columns, compute contentwidth */
180 if (!test(REPACK)) { constrain(); return; }
181 boolean haskid = false;
182 for(Box child = getChild(0); child != null; child = child.nextSibling()) { haskid = true; child.pack(); }
183 if (!haskid) { clear(REPACK); constrain(); return; }
184 int frontier_size = 0;
185 //#repeat COLS/ROWS rows/cols cols/rows col/row row/col colspan/rowspan rowspan/colspan \
186 // contentheight/contentwidth contentwidth/contentheight
187 if (test(FIXED) == COLS) {
189 for(Box child = getChild(0); child != null; child = child.nextSibling()) {
190 if (!child.test(PACKED) || !child.test(VISIBLE)) continue;
191 if (cols == 1) { child.row = rows; rows += child.rowspan; child.col = 0; continue; }
192 child.col = (short)(frontier_size <= 0 ? 0 : (frontier[frontier_size-1].col + frontier[frontier_size-1].colspan));
193 child.row = (short)(frontier_size <= 0 ? 0 : frontier[frontier_size-1].row);
194 if (child.col + min(cols,child.colspan) > cols) { child.col = 0; child.row++; }
195 for(int i=0; i<frontier_size; i++)
196 if (frontier[i].row + frontier[i].rowspan <= child.row) {
197 frontier[i--] = frontier[--frontier_size]; frontier[frontier_size] = null;
198 } else if (frontier[i].col<child.col+min(cols,child.colspan)&&frontier[i].col+frontier[i].colspan>child.col) {
199 child.col = (short)(frontier[i].col + frontier[i].colspan);
200 if (child.col + min(cols,child.colspan) > cols) {
201 child.row = (short)(frontier[i].row + frontier[i].rowspan);
202 for(i--; i>0; i--) child.row = (short)min(row, frontier[i].row + frontier[i].rowspan);
203 child.col = (short)0;
207 frontier[frontier_size++] = child;
209 for(int i=0; i<frontier_size; i++){ rows=(short)max(rows, frontier[i].row + frontier[i].rowspan); frontier[i] = null; }
213 set(RECONSTRAIN); // FIXME: be smarter / more incremental
217 public void constrain() {
218 if (!test(RECONSTRAIN)) return;
220 //#repeat contentwidth/contentheight contentheight/contentwidth minwidth/minheight row/col col/row \
221 // textwidth/textheight maxwidth/maxheight cols/rows rows/cols colspan/rowspan rowspan/colspan
222 contentwidth = bound(minwidth,
223 max(contentwidth, font == null || text == null ? 0 : font.textwidth(text)),
226 set(REPLACE); // FIXME: be smarter / more incremental
229 void resize(int x, int y, int width, int height) {
230 if (x == this.x && y == this.y && width == this.width && height == this.height) return;
231 boolean sizechange = (this.width != width || this.height != height) && getTrap("SizeChange") != null;
232 int thisx = parent == null ? 0 : this.x;
233 int thisy = parent == null ? 0 : this.y;
234 Box who = (parent == null ? this : parent);
235 if (this.x != x || this.y != y) set(MOVED);
236 if (texture == null && (text == null || text.equals("")) && !test(MOVED)) {
237 if ((fillcolor & 0xff000000) != 0 || parent == null) {
238 who.dirty(thisx+min(this.width,width), thisy, Math.abs(width-this.width), max(this.height, height));
239 who.dirty(thisx, thisy+min(this.height,height), max(this.width, width), Math.abs(height-this.height));
241 this.width = width; this.height = height; this.x = x; this.y = y;
243 who.dirty(thisx, thisy, this.width, this.height);
244 this.width = width; this.height = height; this.x = x; this.y = y;
247 if (sizechange) putAndTriggerTrapsAndCatchExceptions("SizeChange", T);
250 private float targetColumnSize = (float)0.0;
251 private float targetRowSize = (float)0.0;
252 private static float[] sizes = new float[65535];
253 private static float[] sizes_v = new float[65535];
254 private static int[] regions = new int[65535];
255 private static int[] regions_v = new int[65535];
256 private static int numregions = 0;
257 private static int numregions_v = 0;
259 void solve(boolean findMinimum) {
260 int numkids = 0; for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling()) numkids++;
261 //#repeat col/row colspan/rowspan contentwidth/contentheight width/height HSHRINK/VSHRINK numregions/numregions_v \
262 // maxwidth/maxheight cols/rows minwidth/minheight regions/regions_v targetColumnSize/targetRowSize sizes/sizes_v \
265 if (findMinimum) contentwidth = 0;
266 else targetColumnSize = 0;
267 } else if (cols == 1) {
270 for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling())
271 contentwidth = max(contentwidth, c.contentwidth);
273 targetColumnSize = width;
275 } else if (cols > 1) do {
277 // FIXME: cache these?
280 for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling()) {
281 regions[numregions++] = c.col;
282 regions[numregions++] = min(cols, c.col+c.colspan);
284 Vec.sortInts(regions, 0, numregions);
286 int newnumregions = numregions;
287 for(int i=1; i<numregions; i++) {
288 if (regions[j] != regions[i]) j++;
289 else newnumregions--;
290 regions[j] = regions[i];
292 numregions = newnumregions;
293 if (regions[numregions-1] == cols) numregions--;
294 else regions[numregions] = cols;
296 int target = findMinimum ? 0 : Math.max(width, contentwidth);
297 // priority 0: (inviolable) honor minwidths
298 // priority 1: sum of columns no greater than parent
299 // priority 2: honor maxwidths
300 // priority 3: equalize columns
301 float targetColumnSize = target == 0 ? 0 : this.targetColumnSize;
302 float last_columnsize = 0;
303 float last_total = 0;
305 boolean first = true;
308 for(int r=0; r<numregions; r++) total += (sizes[r] = (float)(targetColumnSize * (regions[r+1]-regions[r])));
310 for(Box child = firstPackedChild(); child != null; child = child.nextPackedSibling())
311 for(int r=(child.col==0?0:minregion); r<numregions; r++) {
312 if (regions[r+1] < child.col) continue;
313 if (regions[r] >= min(child.col+child.colspan,cols)) { minregion = r; break; }
315 int child_maxwidth = child.test(HSHRINK)?child.contentwidth:child.maxwidth;
316 if (sizes[r] <= (float)(targetColumnSize*(regions[r+1]-regions[r])))
317 if ((child.colspan * targetColumnSize) > (child_maxwidth + (float)0.5))
318 sizes[r] = (float)Math.min(sizes[r], (regions[r+1]-regions[r])*(child_maxwidth/child.colspan));
319 if ((child.colspan * targetColumnSize) < (child.contentwidth - (float)0.5))
320 sizes[r] = (float)Math.max(sizes[r], (regions[r+1]-regions[r])*(child.contentwidth/child.colspan));
323 float save = targetColumnSize;
324 if (Math.abs(total - target) <= (float)1.0) break;
326 if (Math.abs(total - last_total) <= (float)1.0) break;
328 last_columnsize = ((total - target) / (float)cols) + targetColumnSize;
330 if (total < target) targetColumnSize += Math.abs((last_columnsize - targetColumnSize) / (float)1.1);
331 else if (total > target) targetColumnSize -= Math.abs((last_columnsize - targetColumnSize) / (float)1.1);
332 last_columnsize = save;
336 if (findMinimum) contentwidth = Math.round(total);
337 else this.targetColumnSize = targetColumnSize;
344 for(Box child = getChild(0); child != null; child = child.nextSibling()) {
345 if (!child.test(VISIBLE)) continue;
346 if (!child.test(REPLACE)) continue;
347 int child_width, child_height, child_x, child_y;
348 if (!child.test(PACKED)) {
349 child_width = child.test(HSHRINK) ? child.contentwidth : min(child.maxwidth, width - Math.abs(child.ax));
350 child_height = child.test(VSHRINK) ? child.contentheight : min(child.maxheight, height - Math.abs(child.ay));
351 child_width = max(child.minwidth, child_width);
352 child_height = max(child.minheight, child_height);
353 int gap_x = width - child_width;
354 int gap_y = height - child_height;
355 child_x = child.ax + (child.test(ALIGN_RIGHT) ? gap_x : !child.test(ALIGN_LEFT) ? gap_x / 2 : 0);
356 child_y = child.ay + (child.test(ALIGN_BOTTOM) ? gap_y : !child.test(ALIGN_TOP) ? gap_y / 2 : 0);
359 //#repeat col/row colspan/rowspan contentwidth/contentheight width/height colMaxWidth/rowMaxHeight \
360 // child_x/child_y x/y HSHRINK/VSHRINK maxwidth/maxheight cols/rows minwidth/minheight x_slack/y_slack \
361 // child_width/child_height ALIGN_RIGHT/ALIGN_BOTTOM ALIGN_LEFT/ALIGN_TOP lp_h/lp \
362 // numregions/numregions_v regions/regions_v targetColumnSize/targetRowSize sizes/sizes_v
368 for(int r=0; r<numregions; r++) {
369 if (regions[r] < child.col) child_x += Math.round(sizes[r]);
370 else if (regions[r] < child.col+child.colspan) child_width += Math.round(sizes[r]);
373 diff = (child_width - (child.test(HSHRINK) ? child.contentwidth : min(child_width, child.maxwidth)));
374 child_x += (child.test(ALIGN_RIGHT) ? diff : child.test(ALIGN_LEFT) ? 0 : diff / 2);
378 if (test(MOVED)) child.set(MOVED);
379 child.resize(child_x, child_y, child_width, child_height);
383 for(Box child = getChild(0); child != null; child = child.nextSibling())
384 if (child.test(VISIBLE) && child.treeSize() > 0)
390 // Rendering Pipeline /////////////////////////////////////////////////////////////////////
392 /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
393 public void render(int parentx, int parenty, int cx1, int cy1, int cx2, int cy2, PixelBuffer buf, Affine a) {
394 if (!test(VISIBLE)) return;
395 int globalx = parentx + (parent == null ? 0 : x);
396 int globaly = parenty + (parent == null ? 0 : y);
398 // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
400 cx1 = max(cx1, globalx);
401 cy1 = max(cy1, globaly);
402 cx2 = min(cx2, globalx + width);
403 cy2 = min(cy2, globaly + height);
404 if (cx2 <= cx1 || cy2 <= cy1) return;
407 if ((fillcolor & 0xFF000000) != 0x00000000 || parent == null)
408 buf.fillTrapezoid(cx1, cx2, cy1, cx1, cx2, cy2, (fillcolor & 0xFF000000) == 0 ? 0xffffffff : fillcolor);
410 if (texture != null && texture.isLoaded)
411 for(int x = globalx; x < cx2; x += texture.width)
412 for(int y = globaly; y < cy2; y += texture.height)
413 buf.drawPicture(texture, x, y, cx1, cy1, cx2, cy2);
415 if (text != null && !text.equals("") && font != null) {
416 int gap_x = width - font.textwidth(text);
417 int gap_y = height - font.textheight(text);
418 int text_x = globalx + (test(ALIGN_RIGHT) ? gap_x : !test(ALIGN_LEFT) ? gap_x/2 : 0);
419 int text_y = globaly + (test(ALIGN_BOTTOM) ? gap_y : !test(ALIGN_TOP) ? gap_y/2 : 0);
420 font.rasterizeGlyphs(text, buf, strokecolor, text_x, text_y, cx1, cy1, cx2, cy2);
423 for(Box b = getChild(0); b != null; b = b.nextSibling())
424 b.render(globalx, globaly, cx1, cy1, cx2, cy2, buf, null);
428 // Methods to implement org.ibex.js.JS //////////////////////////////////////
431 public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
437 if (b.parent != this)
438 return (redirect == null || redirect == this) ?
440 redirect.callMethod(method, a0, a1, a2, rest, nargs);
441 return N(b.getIndexInParent());
446 ret.put("x", N(b.localToGlobalX(0) - localToGlobalX(0)));
447 ret.put("y", N(b.localToGlobalY(0) - localToGlobalY(0)));
453 return super.callMethod(method, a0, a1, a2, rest, nargs);
456 public Object get(Object name) throws JSExn {
457 if (name instanceof Number)
458 return redirect == null ? null : redirect == this ? getChild(toInt(name)) : redirect.get(name);
461 case "surface": return parent == null ? null : parent.getAndTriggerTraps("surface");
462 case "indexof": return METHOD;
463 case "distanceto": return METHOD;
464 case "text": return text;
465 case "path": throw new JSExn("cannot read from the path property");
466 case "fill": return Color.colorToString(fillcolor);
467 case "strokecolor": return Color.colorToString(strokecolor);
468 case "textcolor": return Color.colorToString(strokecolor);
469 case "font": return font == null ? null : font.stream;
470 case "fontsize": return font == null ? N(10) : N(font.pointsize);
471 case "strokewidth": return N(strokewidth);
472 case "align": return alignToString();
473 case "thisbox": return this;
474 case "shrink": return B(test(HSHRINK) || test(VSHRINK));
475 case "hshrink": return B(test(HSHRINK));
476 case "vshrink": return B(test(VSHRINK));
477 case "aspect": return N(aspect);
478 case "x": return (parent == null || !test(VISIBLE)) ? N(0) : test(PACKED) ? N(x) : N(ax);
479 case "y": return (parent == null || !test(VISIBLE)) ? N(0) : test(PACKED) ? N(y) : N(ay);
480 case "cols": return test(FIXED) == COLS ? N(cols) : N(0);
481 case "rows": return test(FIXED) == ROWS ? N(rows) : N(0);
482 case "colspan": return N(colspan);
483 case "rowspan": return N(rowspan);
484 case "width": getRoot().reflow(); return N(width);
485 case "height": getRoot().reflow(); return N(height);
486 case "minwidth": return N(minwidth);
487 case "maxwidth": return N(maxwidth);
488 case "minheight": return N(minheight);
489 case "maxheight": return N(maxheight);
490 case "clip": return B(test(CLIP));
491 case "visible": return B(test(VISIBLE) && (parent == null || (parent.get("visible") == T)));
492 case "packed": return B(test(PACKED));
493 case "globalx": return N(localToGlobalX(0));
494 case "globaly": return N(localToGlobalY(0));
495 case "cursor": return test(CURSOR) ? boxToCursor.get(this) : null;
497 if (getSurface() == null) return null;
498 if (getSurface()._mousex == Integer.MAX_VALUE)
499 throw new JSExn("you cannot read from the box.mouse property in background thread context");
501 case "numchildren": return redirect == null ? N(0) : redirect == this ? N(treeSize()) : redirect.get("numchildren");
502 case "redirect": return redirect == null ? null : redirect == this ? T : redirect.get("redirect");
503 case "Minimized": if (parent == null && getSurface() != null) return B(getSurface().minimized);
504 default: return super.get(name);
506 throw new Error("unreachable"); // unreachable
509 private class Mouse extends JS.Cloneable {
510 public Object get(Object key) {
512 case "x": return N(globalToLocalX(getSurface()._mousex));
513 case "y": return N(globalToLocalY(getSurface()._mousey));
515 // this might not get recomputed if we change mousex/mousey...
516 case "inside": return B(test(MOUSEINSIDE));
522 //#repeat setWidth/setHeight minwidth/minheight maxwidth/maxheight pendingWidth/pendingHeight
523 public void setWidth(int min, int max) {
524 // FIXME: deal with conflicting min/max
525 if (this.minwidth == min && this.maxwidth == max) return;
529 if (parent != null || getSurface() == null) return;
530 getSurface().pendingWidth = maxwidth;
532 // FIXME: the repeat doesn't work right here
533 getSurface().setMinimumSize(minwidth, minheight, minwidth != maxwidth || minheight != maxheight);
537 public void put(Object name, Object value) throws JSExn {
538 if (name instanceof Number) { put(toInt(name), value); return; }
540 case "thisbox": if (value == null) removeSelf();
541 case "text": if (value == null) value = ""; CHECKSET_STRING(text); RECONSTRAIN(); DIRTY;
542 case "strokecolor": value = N(Color.stringToColor((String)value)); CHECKSET_INT(strokecolor); DIRTY;
543 case "textcolor": value = N(Color.stringToColor((String)value)); CHECKSET_INT(strokecolor); DIRTY;
544 case "strokewidth": CHECKSET_SHORT(strokewidth); DIRTY;
545 case "shrink": CHECKSET_FLAG(HSHRINK | VSHRINK); RECONSTRAIN();
546 case "hshrink": CHECKSET_FLAG(HSHRINK); RECONSTRAIN();
547 case "vshrink": CHECKSET_FLAG(VSHRINK); RECONSTRAIN();
548 case "width": setWidth(toInt(value), toInt(value));
549 case "height": setHeight(toInt(value), toInt(value));
550 case "maxwidth": setWidth(minwidth, toInt(value));
551 case "minwidth": setWidth(toInt(value), maxwidth);
552 case "maxheight": setHeight(minheight, toInt(value));
553 case "minheight": setHeight(toInt(value), maxheight);
554 case "colspan": if (toInt(value) > 0) { CHECKSET_SHORT(colspan); if (parent != null) parent.REPACK(); }
555 case "rowspan": if (toInt(value) > 0) { CHECKSET_SHORT(rowspan); if (parent != null) parent.REPACK(); }
556 case "visible": CHECKSET_FLAG(VISIBLE); RECONSTRAIN(); DIRTY;
557 case "packed": CHECKSET_FLAG(PACKED); if (parent != null) { parent.REPACK(); } else { REPACK(); }
558 case "align": clear(ALIGNS); setAlign(value == null ? "center" : value); REPLACE();
559 case "cursor": setCursor(value);
560 case "fill": setFill(value);
561 case "clip": CHECKSET_FLAG(CLIP); if (parent == null) DIRTY; else parent.DIRTY;
562 case "rows": CHECKSET_SHORT(rows); if (rows==0){set(FIXED, COLS);if(cols==0)cols=1;} else set(FIXED, ROWS); REPACK();
563 case "cols": CHECKSET_SHORT(cols); if (cols==0){set(FIXED, ROWS);if(rows==0)rows=1;} else set(FIXED, COLS); REPACK();
567 int mousex = toInt(((JS)value).get("x"));
568 int mousey = toInt(((JS)value).get("y"));
569 getSurface()._mousex = localToGlobalX(mousex);
570 getSurface()._mousey = localToGlobalY(mousey);
572 case "Minimized": if (parent == null && getSurface() != null) getSurface().minimized = toBoolean(value); // FEATURE
573 case "Maximized": if (parent == null && getSurface() != null) getSurface().maximized = toBoolean(value); // FEATURE
574 case "Close": if (parent == null && getSurface() != null) getSurface().dispose(true);
576 for(Box cur = (Box)value; cur != null || cur == redirect; cur = cur.parent)
577 if (cur == redirect) { redirect = (Box)value; return; }
578 JS.error("redirect can only be set to a descendant of its current value");
579 case "fontsize": font = Font.getFont(font == null ? null : font.stream, toInt(value)); RECONSTRAIN(); DIRTY;
581 if(!(value instanceof Stream)) throw new JSExn("You can only put streams to the font property");
582 if (font == value) return; // FIXME: unclone()
583 font = value == null ? null : Font.getFont((Stream)value, font == null ? 10 : font.pointsize);
586 case "x": if (parent==null && Surface.fromBox(this)!=null) {
589 if (test(PACKED) && parent != null) return;
593 case "y": if (parent==null && Surface.fromBox(this)!=null) {
596 if (test(PACKED) && parent != null) return;
600 case "titlebar": if (getSurface()!=null) getSurface().setTitleBarText(toString(value)); super.put(name,value);
603 case "Press1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
604 case "Press2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
605 case "Press3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
606 case "Release1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
607 case "Release2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
608 case "Release3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
609 case "Click1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
610 case "Click2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
611 case "Click3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
612 case "DoubleClick1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
613 case "DoubleClick2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
614 case "DoubleClick3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
615 case "KeyPressed": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
616 case "KeyReleased": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
617 case "Move": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
618 case "HScroll": if (!test(STOP_UPWARD_PROPAGATION) && parent != null)
619 parent.putAndTriggerTraps(name, N(((Number)value).floatValue() * ((float)parent.fontSize()) / ((float)fontSize())));
620 case "VScroll": if (!test(STOP_UPWARD_PROPAGATION) && parent != null)
621 parent.putAndTriggerTraps(name, N(((Number)value).floatValue() * ((float)parent.fontSize()) / ((float)fontSize())));
623 case "_Move": propagateDownward(name, value, false);
624 case "_Press1": propagateDownward(name, value, false);
625 case "_Press2": propagateDownward(name, value, false);
626 case "_Press3": propagateDownward(name, value, false);
627 case "_Release1": propagateDownward(name, value, false);
628 case "_Release2": propagateDownward(name, value, false);
629 case "_Release3": propagateDownward(name, value, false);
630 case "_Click1": propagateDownward(name, value, false);
631 case "_Click2": propagateDownward(name, value, false);
632 case "_Click3": propagateDownward(name, value, false);
633 case "_DoubleClick1": propagateDownward(name, value, false);
634 case "_DoubleClick2": propagateDownward(name, value, false);
635 case "_DoubleClick3": propagateDownward(name, value, false);
636 case "_KeyPressed": propagateDownward(name, value, false);
637 case "_KeyReleased": propagateDownward(name, value, false);
638 case "_HScroll": propagateDownward(name, value, false);
639 case "_VScroll": propagateDownward(name, value, false);
641 case "SizeChange": return;
642 case "ChildChange": return;
643 case "Enter": return;
644 case "Leave": return;
646 default: super.put(name, value);
650 private String alignToString() {
651 switch(flags & ALIGNS) {
652 case (ALIGN_TOP | ALIGN_LEFT): return "topleft";
653 case (ALIGN_BOTTOM | ALIGN_LEFT): return "bottomleft";
654 case (ALIGN_TOP | ALIGN_RIGHT): return "topright";
655 case (ALIGN_BOTTOM | ALIGN_RIGHT): return "bottomright";
656 case ALIGN_TOP: return "top";
657 case ALIGN_BOTTOM: return "bottom";
658 case ALIGN_LEFT: return "left";
659 case ALIGN_RIGHT: return "right";
660 case 0: return "center";
661 default: throw new Error("invalid alignment flags: " + (flags & ALIGNS));
665 private void setAlign(Object value) {
668 case "topleft": set(ALIGN_TOP | ALIGN_LEFT);
669 case "bottomleft": set(ALIGN_BOTTOM | ALIGN_LEFT);
670 case "topright": set(ALIGN_TOP | ALIGN_RIGHT);
671 case "bottomright": set(ALIGN_BOTTOM | ALIGN_RIGHT);
672 case "top": set(ALIGN_TOP);
673 case "bottom": set(ALIGN_BOTTOM);
674 case "left": set(ALIGN_LEFT);
675 case "right": set(ALIGN_RIGHT);
676 default: JS.log("invalid alignment \"" + value + "\"");
680 private void setCursor(Object value) {
681 if (value == null) { clear(CURSOR); boxToCursor.remove(this); return; }
682 if (value.equals(boxToCursor.get(this))) return;
684 boxToCursor.put(this, value);
685 Surface surface = getSurface();
686 if (surface == null) return;
687 String tempcursor = surface.cursor;
688 propagateDownward(null, null, false);
689 if (surface.cursor != tempcursor) surface.syncCursor();
692 private void setFill(Object value) throws JSExn {
694 if (texture == null && fillcolor == 0) return;
697 } else if (value instanceof String) {
698 int newfillcolor = Color.stringToColor((String)value);
699 if (newfillcolor == fillcolor) return;
700 fillcolor = newfillcolor;
702 } else if (value instanceof JS) {
703 Picture newtex = Picture.load((JS)value, this);
704 if (texture == newtex) return;
707 if (texture != null && texture.isLoaded) perform();
709 throw new JSExn("fill must be null, a String, or a stream, not a " + value.getClass());
715 * Handles events which propagate down the box tree. If obscured
716 * is set, then we merely check for Enter/Leave.
718 private void propagateDownward(Object name_, Object value, boolean obscured) {
720 String name = (String)name_;
721 if (getSurface() == null) return;
722 int x = globalToLocalX(getSurface()._mousex);
723 int y = globalToLocalY(getSurface()._mousey);
724 boolean wasinside = test(MOUSEINSIDE);
725 boolean isinside = test(VISIBLE) && inside(x, y) && !obscured;
726 if (!wasinside && isinside) {
728 putAndTriggerTrapsAndCatchExceptions("Enter", T);
730 if (isinside && test(CURSOR)) getSurface().cursor = (String)boxToCursor.get(this);
731 if (wasinside && !isinside) {
733 putAndTriggerTrapsAndCatchExceptions("Leave", T);
736 boolean found = false;
737 if (wasinside || isinside)
738 for(Box child = getChild(treeSize() - 1); child != null; child = child.prevSibling()) {
739 boolean save_stop = child.test(STOP_UPWARD_PROPAGATION);
740 Object value2 = value;
741 if (name.equals("_HScroll") || name.equals("_VScroll"))
742 value2 = N(((Number)value).floatValue() * ((float)child.fontSize()) / (float)fontSize());
743 if (obscured || !child.inside(x - child.x, y - child.y)) {
744 child.propagateDownward(name, value2, true);
747 child.clear(STOP_UPWARD_PROPAGATION);
748 if (name != null) child.putAndTriggerTrapsAndCatchExceptions(name, value2);
749 else child.propagateDownward(name, value2, obscured);
751 if (save_stop) child.set(STOP_UPWARD_PROPAGATION); else child.clear(STOP_UPWARD_PROPAGATION);
753 if (child.inside(x - child.x, y - child.y))
754 if (name != null && name.equals("_Move")) obscured = true;
758 if (!obscured && !found)
759 if ("_Move".equals(name) || name.startsWith("_Release") || wasinside)
761 putAndTriggerTrapsAndCatchExceptions(name.substring(1), value);
764 /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface */
765 public static Box whoIs(Box cur, int x, int y) {
767 if (cur.parent != null) throw new Error("whoIs may only be invoked on the root box of a surface");
771 // WARNING: this method is called from the event-queueing thread -- it may run concurrently with
772 // ANY part of Ibex, and is UNSYNCHRONIZED for performance reasons. BE CAREFUL HERE.
774 if (!cur.test(VISIBLE)) return null;
775 if (!cur.inside(x - globalx, y - globaly)) return cur.parent == null ? cur : null;
777 for(int i=cur.treeSize() - 1; i>=0; i--) {
778 Box child = cur.getChild(i);
779 if (child == null) continue; // since this method is unsynchronized, we have to double-check
782 if (child.test(VISIBLE) && child.inside(x - globalx, y - globaly)) { cur = child; continue OUTER; }
792 // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
794 void mark_for_repack() { REPACK(); }
795 public Enumeration keys() { throw new Error("you cannot apply for..in to a " + this.getClass().getName()); }
796 public Box getRoot() { return parent == null ? this : parent.getRoot(); }
797 public Surface getSurface() { return Surface.fromBox(getRoot()); }
798 Box nextPackedSibling() { Box b = nextSibling(); return b == null || (b.test(PACKED | VISIBLE)) ? b : b.nextPackedSibling(); }
799 Box firstPackedChild() { Box b = getChild(0); return b == null || (b.test(PACKED | VISIBLE)) ? b : b.nextPackedSibling(); }
800 public int globalToLocalX(int x) { return parent == null ? x : parent.globalToLocalX(x - this.x); }
801 public int globalToLocalY(int y) { return parent == null ? y : parent.globalToLocalY(y - this.y); }
802 public int localToGlobalX(int x) { return parent == null ? x : parent.globalToLocalX(x + this.x); }
803 public int localToGlobalY(int y) { return parent == null ? y : parent.globalToLocalY(y + this.y); }
805 static short min(short a, short b) { if (a<b) return a; else return b; }
806 static int min(int a, int b) { if (a<b) return a; else return b; }
807 static float min(float a, float b) { if (a<b) return a; else return b; }
809 static short max(short a, short b) { if (a>b) return a; else return b; }
810 static int max(int a, int b) { if (a>b) return a; else return b; }
811 static float max(float a, float b) { if (a>b) return a; else return b; }
813 static int min(int a, int b, int c) { if (a<=b && a<=c) return a; else if (b<=c && b<=a) return b; else return c; }
814 static int max(int a, int b, int c) { if (a>=b && a>=c) return a; else if (b>=c && b>=a) return b; else return c; }
815 static int bound(int a, int b, int c) { if (c < b) return c; if (a > b) return a; return b; }
816 final boolean inside(int x, int y) { return test(VISIBLE) && x >= 0 && y >= 0 && x < width && y < height; }
818 void set(int mask) { flags |= mask; }
819 void set(int mask, boolean setclear) { if (setclear) set(mask); else clear(mask); }
820 void clear(int mask) { flags &= ~mask; }
821 boolean test(int mask) { return ((flags & mask) == mask); }
824 // Tree Handling //////////////////////////////////////////////////////////////////////
826 public final int getIndexInParent() { return parent == null ? 0 : parent.indexNode(this); }
827 public final Box nextSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) + 1); }
828 public final Box prevSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) - 1); }
829 public final Box getChild(int i) {
830 if (i < 0) return null;
831 if (i >= treeSize()) return null;
832 return (Box)getNode(i);
835 // Tree Manipulation /////////////////////////////////////////////////////////////////////
837 public void removeSelf() {
838 if (parent != null) { parent.removeChild(parent.indexNode(this)); return; }
839 Surface surface = Surface.fromBox(this);
840 if (surface != null) surface.dispose(true);
843 /** remove the i^th child */
844 public void removeChild(int i) {
848 b.clear(MOUSEINSIDE);
852 putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
855 public void put(int i, Object value) throws JSExn {
858 if (value != null && !(value instanceof Box)) {
859 if (Log.on) JS.warn("attempt to set a numerical property on a box to a non-box");
863 if (redirect == null) {
864 if (value == null) putAndTriggerTrapsAndCatchExceptions("ChildChange", getChild(i));
865 else JS.warn("attempt to add/remove children to/from a node with a null redirect");
867 } else if (redirect != this) {
868 if (value != null) putAndTriggerTrapsAndCatchExceptions("ChildChange", value);
869 redirect.put(i, value);
871 Box b = (Box)redirect.get(new Integer(i));
872 if (b != null) putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
875 } else if (value == null) {
876 if (i < 0 || i > treeSize()) return;
879 putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
884 // check if box being moved is currently target of a redirect
885 for(Box cur = b.parent; cur != null; cur = cur.parent)
886 if (cur.redirect == b) {
887 if (Log.on) JS.warn("attempt to move a box that is the target of a redirect");
891 // check for recursive ancestor violation
892 for(Box cur = this; cur != null; cur = cur.parent)
894 if (Log.on) JS.warn("attempt to make a node a parent of its own ancestor");
895 if (Log.on) Log.info(this, "box == " + this + " ancestor == " + b);
899 if (b.parent != null) b.parent.removeChild(b.parent.indexNode(b));
903 // need both of these in case child was already uncalc'ed
908 putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
912 public void putAndTriggerTrapsAndCatchExceptions(Object name, Object val) {
914 putAndTriggerTraps(name, val);
916 JS.log("caught js exception while putting to trap \""+name+"\"");
918 } catch (Exception e) {
919 JS.log("caught exception while putting to trap \""+name+"\"");