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.
8 // FIXME: are traps on x/y meaningful?
9 // FIXME: if we trap on cols, then set rows to 0 (forcing cols to 1), does the cols trap get triggered?
10 // FIXME: if we change min{width/height}, thereby forcing a change to max{min/height}, does a trap on those get triggered?
11 // FIXME: trap on numchildren? replaces ChildChanged?
12 // FIXME: trap on visible, trigger when parent visibility changes
14 // FIXME: ax/ay nonsense
15 // FIXME: mouse move/release still needs to propagate to boxen in which the mouse was pressed and is still held down
17 // FEATURE: mark to reflow starting with a certain child
18 // FEATURE: reintroduce surface.abort
22 import org.ibex.util.*;
23 import org.ibex.graphics.*;
27 * Encapsulates the data for a single Ibex box as well as all layout
31 * <p>The rendering process consists of four phases; each requires
32 * one DFS pass over the tree</p>
33 * <ol><li> <b>pack()</b>: each box sets its childrens' row/col
34 * <ol><li> <b>constrain()</b>: contentwidth is computed
35 * <li> <b>resize()</b>: width/height and x/y positions are set
36 * <li> <b>render()</b>: children draw their content onto the PixelBuffer.
39 * The first three passes together are called the <i>reflow</i>
40 * phase. Reflowing is done in a seperate pass since SizeChanges
41 * trigger a Surface.abort; if rendering were done in the same pass,
42 * rendering work done prior to the Surface.abort would be wasted.
44 public final class Box extends JS.O implements Task {
46 // Macros //////////////////////////////////////////////////////////////////////
48 final void REPLACE() { for(Box b2 = this; b2 != null && !b2.test(REPLACE); b2 = b2.parent) b2.set(REPLACE); }
49 final void RECONSTRAIN() { for(Box b2 = this; b2 != null && !b2.test(RECONSTRAIN); b2 = b2.parent) b2.set(RECONSTRAIN); }
50 final void REPACK() { for(Box b2 = this; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK); }
52 //#define CHECKSET_SHORT(prop) short nu = (short)toInt(value); if (nu == prop) break; prop = nu;
53 //#define CHECKSET_INT(prop) int nu = toInt(value); if (nu == prop) break; prop = nu;
54 //#define CHECKSET_FLAG(flag) boolean nu = toBoolean(value); if (nu == test(flag)) break; if (nu) set(flag); else clear(flag);
55 //#define CHECKSET_BOOLEAN(prop) boolean nu = toBoolean(value); if (nu == prop) break; prop = nu;
56 //#define CHECKSET_STRING(prop) if ((value==null&&prop==null)||(value!=null&&JS.toString(value).equals(prop))) break; prop=JS.toString(value);
59 static Hash boxToCursor = new Hash(500, 3);
61 static final Font DEFAULT_FONT;
63 try { DEFAULT_FONT = Font.getFont((JS)Main.builtin.get(JS.S("fonts/vera/Vera.ttf")), 10); }
64 catch(JSExn e) { throw new Error("Error loading default font: " + e); }
68 // Flags //////////////////////////////////////////////////////////////////////
70 static final int MOUSEINSIDE = 0x00000001;
71 static final int VISIBLE = 0x00000002;
72 static final int PACKED = 0x00000004;
73 public static final int HSHRINK = 0x00000008;
74 public static final int VSHRINK = 0x00000010;
75 static final int BLACK = 0x00000020; // for red-black code
77 static final int FIXED = 0x00000040;
78 static final boolean ROWS = true;
79 static final boolean COLS = false;
81 static final int ISROOT = 0x00000080;
82 static final int REPACK = 0x00000100;
83 static final int RECONSTRAIN = 0x00000200;
84 static final int REPLACE = 0x00000400;
86 static final int ALIGN_TOP = 0x00001000;
87 static final int ALIGN_BOTTOM = 0x00002000;
88 static final int ALIGN_LEFT = 0x00004000;
89 static final int ALIGN_RIGHT = 0x00008000;
90 static final int ALIGNS = 0x0000f000;
91 static final int CURSOR = 0x00010000; // if true, this box has a cursor in the cursor hash; FEATURE: GC issues?
92 static final int CLIP = 0x00020000;
93 static final int STOP_UPWARD_PROPAGATION = 0x00040000;
94 static final int MOVED = 0x00080000;
97 // Instance Data //////////////////////////////////////////////////////////////////////
101 int flags = VISIBLE | PACKED | REPACK | RECONSTRAIN | REPLACE | FIXED | STOP_UPWARD_PROPAGATION | CLIP | MOVED;
103 private BalancedTree bt;
105 private String text = null;
106 private Font font = DEFAULT_FONT;
107 private Picture texture = null;
108 private short strokewidth = 1;
109 public int fillcolor = 0x00000000;
110 private int strokecolor = 0xFF000000;
112 private int aspect = 0;
114 // specified directly by user
115 public int minwidth = 0;
116 public int maxwidth = Integer.MAX_VALUE;
117 public int minheight = 0;
118 public int maxheight = Integer.MAX_VALUE;
119 private short rows = 1;
120 private short cols = 0;
121 private short rowspan = 1;
122 private short colspan = 1;
124 // computed during reflow
125 private short row = 0;
126 private short col = 0;
129 public int ax = 0; // FEATURE: roll these into x/y; requires lots of changes
130 public int ay = 0; // FEATURE: roll these into x/y; requires lots of changes; perhaps y()?
131 public int width = 0;
132 public int height = 0;
133 public int contentwidth = 0; // == max(minwidth, textwidth, sum(child.contentwidth))
134 public int contentheight = 0;
136 private Path path = null;
138 private Affine transform = null;
139 private VectorGraphics.RasterPath rpath = null;
140 private Affine rtransform = null;
143 // Instance Methods /////////////////////////////////////////////////////////////////////
145 public final int fontSize() { return font == null ? DEFAULT_FONT.pointsize : font.pointsize; }
147 /** invoked when a resource needed to render ourselves finishes loading */
148 public void perform() throws JSExn {
149 if (texture == null) { Log.warn(Box.class, "perform() called with null texture"); return; }
150 if (texture.isLoaded) {
151 setWidth(max(texture.width, minwidth), maxwidth);
152 setHeight(max(texture.height, minheight), maxheight);
154 else { JS res = texture.stream; texture = null; throw new JSExn("image not found: "+res.unclone()); }
157 // FEATURE: use cx2/cy2 format
158 /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
159 public void dirty() { dirty(0, 0, width, height); }
160 public void dirty(int x, int y, int w, int h) {
161 for(Box cur = this; cur != null; cur = cur.parent) {
162 // x and y have a different meaning on the root box
163 if (cur.parent != null && cur.test(CLIP)) {
164 w = min(x + w, cur.width) - max(x, 0);
165 h = min(y + h, cur.height) - max(y, 0);
169 if (w <= 0 || h <= 0) return;
170 if (cur.parent == null && cur.getSurface() != null) cur.getSurface().dirty(x, y, w, h);
177 // Reflow ////////////////////////////////////////////////////////////////////////////////////////
179 /** should only be invoked on the root box */
180 public void reflow() {
183 test(HSHRINK) ? contentwidth : maxwidth,
184 test(VSHRINK) ? contentheight : maxheight);
188 private static Box[] frontier = new Box[65535];
189 /** pack the boxes into rows and columns, compute contentwidth */
191 if (!test(REPACK)) { constrain(); return; }
192 boolean haskid = false;
193 for(Box child = getChild(0); child != null; child = child.nextSibling()) { haskid = true; child.pack(); }
194 if (!haskid) { clear(REPACK); constrain(); return; }
195 int frontier_size = 0;
196 //#repeat COLS/ROWS rows/cols cols/rows col/row row/col colspan/rowspan rowspan/colspan \
197 // contentheight/contentwidth contentwidth/contentheight
198 if (test(FIXED) == COLS) {
200 for(Box child = getChild(0); child != null; child = child.nextSibling()) {
201 if (!child.test(PACKED) || !child.test(VISIBLE)) continue;
202 if (cols == 1) { child.row = rows; rows += child.rowspan; child.col = 0; continue; }
203 child.col = (short)(frontier_size <= 0 ? 0 : (frontier[frontier_size-1].col + frontier[frontier_size-1].colspan));
204 child.row = (short)(frontier_size <= 0 ? 0 : frontier[frontier_size-1].row);
205 if (child.col + min(cols,child.colspan) > cols) { child.col = 0; child.row++; }
206 for(int i=0; i<frontier_size; i++)
207 if (frontier[i].row + frontier[i].rowspan <= child.row) {
208 frontier[i--] = frontier[--frontier_size]; frontier[frontier_size] = null;
209 } else if (frontier[i].col<child.col+min(cols,child.colspan)&&frontier[i].col+frontier[i].colspan>child.col) {
210 child.col = (short)(frontier[i].col + frontier[i].colspan);
211 if (child.col + min(cols,child.colspan) > cols) {
212 child.row = (short)(frontier[i].row + frontier[i].rowspan);
213 for(i--; i>0; i--) child.row = (short)min(row, frontier[i].row + frontier[i].rowspan);
214 child.col = (short)0;
218 frontier[frontier_size++] = child;
220 for(int i=0; i<frontier_size; i++){ rows=(short)max(rows, frontier[i].row + frontier[i].rowspan); frontier[i] = null; }
224 set(RECONSTRAIN); // FIXME: be smarter / more incremental
228 public void constrain() {
229 if (!test(RECONSTRAIN)) return;
231 //#repeat contentwidth/contentheight contentheight/contentwidth minwidth/minheight row/col col/row \
232 // textwidth/textheight maxwidth/maxheight cols/rows rows/cols colspan/rowspan rowspan/colspan
233 contentwidth = bound(minwidth,
234 max(contentwidth, font == null || text == null ? 0 : font.textwidth(text)),
237 set(REPLACE); // FIXME: be smarter / more incremental
240 private final static JS SIZECHANGE = JS.S("SizeChange");
242 void resize(int x, int y, int width, int height) {
243 if (x == this.x && y == this.y && width == this.width && height == this.height) return;
244 boolean sizechange = (this.width != width || this.height != height) && hasTrap(SIZECHANGE);
245 int thisx = parent == null ? 0 : this.x;
246 int thisy = parent == null ? 0 : this.y;
247 Box who = (parent == null ? this : parent);
248 if (this.x != x || this.y != y) set(MOVED);
249 if (texture == null && (text == null || text.equals("")) && !test(MOVED)) {
250 if ((fillcolor & 0xff000000) != 0 || parent == null) {
251 who.dirty(thisx+min(this.width,width), thisy, Math.abs(width-this.width), max(this.height, height));
252 who.dirty(thisx, thisy+min(this.height,height), max(this.width, width), Math.abs(height-this.height));
254 this.width = width; this.height = height; this.x = x; this.y = y;
256 who.dirty(thisx, thisy, this.width, this.height);
257 this.width = width; this.height = height; this.x = x; this.y = y;
260 if (sizechange) putAndTriggerTrapsAndCatchExceptions(SIZECHANGE, T);
263 private float targetColumnSize = (float)0.0;
264 private float targetRowSize = (float)0.0;
265 private static float[] sizes = new float[65535];
266 private static float[] sizes_v = new float[65535];
267 private static int[] regions = new int[65535];
268 private static int[] regions_v = new int[65535];
269 private static int numregions = 0;
270 private static int numregions_v = 0;
272 void solve(boolean findMinimum) {
273 int numkids = 0; for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling()) numkids++;
274 //#repeat col/row colspan/rowspan contentwidth/contentheight width/height HSHRINK/VSHRINK numregions/numregions_v \
275 // maxwidth/maxheight cols/rows minwidth/minheight regions/regions_v targetColumnSize/targetRowSize sizes/sizes_v \
278 if (findMinimum) contentwidth = 0;
279 else targetColumnSize = 0;
280 } else if (cols == 1) {
283 for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling())
284 contentwidth = max(contentwidth, c.contentwidth);
286 targetColumnSize = width;
288 } else if (cols > 1) do {
290 // FIXME: cache these?
293 for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling()) {
294 regions[numregions++] = c.col;
295 regions[numregions++] = min(cols, c.col+c.colspan);
297 Vec.sortInts(regions, 0, numregions);
299 int newnumregions = numregions;
300 for(int i=1; i<numregions; i++) {
301 if (regions[j] != regions[i]) j++;
302 else newnumregions--;
303 regions[j] = regions[i];
305 numregions = newnumregions;
306 if (regions[numregions-1] == cols) numregions--;
307 else regions[numregions] = cols;
309 int target = findMinimum ? 0 : Math.max(width, contentwidth);
310 // priority 0: (inviolable) honor minwidths
311 // priority 1: sum of columns no greater than parent
312 // priority 2: honor maxwidths
313 // priority 3: equalize columns
314 float targetColumnSize = target == 0 ? 0 : this.targetColumnSize;
315 float last_columnsize = 0;
316 float last_total = 0;
318 boolean first = true;
321 for(int r=0; r<numregions; r++) total += (sizes[r] = (float)(targetColumnSize * (regions[r+1]-regions[r])));
323 for(Box child = firstPackedChild(); child != null; child = child.nextPackedSibling())
324 for(int r=(child.col==0?0:minregion); r<numregions; r++) {
325 if (regions[r+1] < child.col) continue;
326 if (regions[r] >= min(child.col+child.colspan,cols)) { minregion = r; break; }
328 int child_maxwidth = child.test(HSHRINK)?child.contentwidth:child.maxwidth;
329 if (sizes[r] <= (float)(targetColumnSize*(regions[r+1]-regions[r])))
330 if ((child.colspan * targetColumnSize) > (child_maxwidth + (float)0.5))
331 sizes[r] = (float)Math.min(sizes[r], (regions[r+1]-regions[r])*(child_maxwidth/child.colspan));
332 if ((child.colspan * targetColumnSize) < (child.contentwidth - (float)0.5))
333 sizes[r] = (float)Math.max(sizes[r], (regions[r+1]-regions[r])*(child.contentwidth/child.colspan));
336 float save = targetColumnSize;
337 if (Math.abs(total - target) <= (float)1.0) break;
339 if (Math.abs(total - last_total) <= (float)1.0) break;
341 last_columnsize = ((total - target) / (float)cols) + targetColumnSize;
343 if (total < target) targetColumnSize += Math.abs((last_columnsize - targetColumnSize) / (float)1.1);
344 else if (total > target) targetColumnSize -= Math.abs((last_columnsize - targetColumnSize) / (float)1.1);
345 last_columnsize = save;
349 if (findMinimum) contentwidth = Math.round(total);
350 else this.targetColumnSize = targetColumnSize;
357 for(Box child = getChild(0); child != null; child = child.nextSibling()) {
358 if (!child.test(VISIBLE)) continue;
359 if (!child.test(REPLACE)) continue;
360 int child_width, child_height, child_x, child_y;
361 if (!child.test(PACKED)) {
362 child_width = child.test(HSHRINK) ? child.contentwidth : min(child.maxwidth, width - Math.abs(child.ax));
363 child_height = child.test(VSHRINK) ? child.contentheight : min(child.maxheight, height - Math.abs(child.ay));
364 child_width = max(child.minwidth, child_width);
365 child_height = max(child.minheight, child_height);
366 int gap_x = width - child_width;
367 int gap_y = height - child_height;
368 child_x = child.ax + (child.test(ALIGN_RIGHT) ? gap_x : !child.test(ALIGN_LEFT) ? gap_x / 2 : 0);
369 child_y = child.ay + (child.test(ALIGN_BOTTOM) ? gap_y : !child.test(ALIGN_TOP) ? gap_y / 2 : 0);
372 //#repeat col/row colspan/rowspan contentwidth/contentheight width/height colMaxWidth/rowMaxHeight \
373 // child_x/child_y x/y HSHRINK/VSHRINK maxwidth/maxheight cols/rows minwidth/minheight x_slack/y_slack \
374 // child_width/child_height ALIGN_RIGHT/ALIGN_BOTTOM ALIGN_LEFT/ALIGN_TOP lp_h/lp \
375 // numregions/numregions_v regions/regions_v targetColumnSize/targetRowSize sizes/sizes_v
381 for(int r=0; r<numregions; r++) {
382 if (regions[r] < child.col) child_x += Math.round(sizes[r]);
383 else if (regions[r] < child.col+child.colspan) child_width += Math.round(sizes[r]);
386 diff = (child_width - (child.test(HSHRINK) ? child.contentwidth : min(child_width, child.maxwidth)));
387 child_x += (child.test(ALIGN_RIGHT) ? diff : child.test(ALIGN_LEFT) ? 0 : diff / 2);
391 if (test(MOVED)) child.set(MOVED);
392 child.resize(child_x, child_y, child_width, child_height);
396 for(Box child = getChild(0); child != null; child = child.nextSibling())
397 if (child.test(VISIBLE) && child.treeSize() > 0)
403 // Rendering Pipeline /////////////////////////////////////////////////////////////////////
405 /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
406 public void render(int parentx, int parenty, int cx1, int cy1, int cx2, int cy2, PixelBuffer buf, Affine a) {
407 if (!test(VISIBLE)) return;
408 int globalx = parentx + (parent == null ? 0 : x);
409 int globaly = parenty + (parent == null ? 0 : y);
411 // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
413 cx1 = max(cx1, globalx);
414 cy1 = max(cy1, globaly);
415 cx2 = min(cx2, globalx + width);
416 cy2 = min(cy2, globaly + height);
417 if (cx2 <= cx1 || cy2 <= cy1) return;
420 if ((fillcolor & 0xFF000000) != 0x00000000 || parent == null)
421 buf.fillTrapezoid(cx1, cx2, cy1, cx1, cx2, cy2, (fillcolor & 0xFF000000) == 0 ? 0xffffffff : fillcolor);
423 if (texture != null && texture.isLoaded)
424 for(int x = globalx; x < cx2; x += texture.width)
425 for(int y = globaly; y < cy2; y += texture.height)
426 buf.drawPicture(texture, x, y, cx1, cy1, cx2, cy2);
428 if (text != null && !text.equals("") && font != null) {
429 int gap_x = width - font.textwidth(text);
430 int gap_y = height - font.textheight(text);
431 int text_x = globalx + (test(ALIGN_RIGHT) ? gap_x : !test(ALIGN_LEFT) ? gap_x/2 : 0);
432 int text_y = globaly + (test(ALIGN_BOTTOM) ? gap_y : !test(ALIGN_TOP) ? gap_y/2 : 0);
433 font.rasterizeGlyphs(text, buf, strokecolor, text_x, text_y, cx1, cy1, cx2, cy2);
436 if (path != null) path.realize(Affine.translate(globalx, globaly)).stroke(buf, 1, strokecolor);
438 for(Box b = getChild(0); b != null; b = b.nextSibling())
439 b.render(globalx, globaly, cx1, cy1, cx2, cy2, buf, null);
443 // Methods to implement org.ibex.js.JS //////////////////////////////////////
446 public JS callMethod(JS method, JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
449 //#switch(JS.toString(method))
452 if (b.parent != this)
453 return (redirect == null || redirect == this) ?
455 redirect.callMethod(method, a0, a1, a2, rest, nargs);
456 return N(b.getIndexInParent());
461 ret.put(JS.S("x"), N(b.localToGlobalX(0) - localToGlobalX(0)));
462 ret.put(JS.S("y"), N(b.localToGlobalY(0) - localToGlobalY(0)));
468 return super.callMethod(method, a0, a1, a2, rest, nargs);
471 public JS get(JS name) throws JSExn {
473 return redirect == null ? null : redirect == this ? getChild(JS.toInt(name)) : redirect.get(name);
475 //#switch(JS.toString(name))
476 case "surface": return parent == null ? null : parent.getAndTriggerTraps(name);
477 case "indexof": return METHOD;
478 case "distanceto": return METHOD;
479 case "text": return JS.S(text);
481 if (path != null) return JS.S(path.toString());
482 if (text == null) return null;
483 if (font == null) return null;
485 for(int i=0; i<text.length(); i++) ret += font.glyphs[text.charAt(i)].path;
488 case "fill": return JS.S(Color.colorToString(fillcolor));
489 case "strokecolor": return JS.S(Color.colorToString(strokecolor));
490 case "textcolor": return JS.S(Color.colorToString(strokecolor));
491 case "font": return font == null ? null : font.stream;
492 case "fontsize": return font == null ? N(10) : N(font.pointsize);
493 case "strokewidth": return N(strokewidth);
494 case "align": return JS.S(alignToString());
495 case "thisbox": return this;
496 case "shrink": return B(test(HSHRINK) || test(VSHRINK));
497 case "hshrink": return B(test(HSHRINK));
498 case "vshrink": return B(test(VSHRINK));
499 case "aspect": return N(aspect);
500 case "x": return (parent == null || !test(VISIBLE)) ? N(0) : test(PACKED) ? N(x) : N(ax);
501 case "y": return (parent == null || !test(VISIBLE)) ? N(0) : test(PACKED) ? N(y) : N(ay);
502 case "cols": return test(FIXED) == COLS ? N(cols) : N(0);
503 case "rows": return test(FIXED) == ROWS ? N(rows) : N(0);
504 case "colspan": return N(colspan);
505 case "rowspan": return N(rowspan);
506 case "width": getRoot().reflow(); return N(width);
507 case "height": getRoot().reflow(); return N(height);
508 case "minwidth": return N(minwidth);
509 case "maxwidth": return N(maxwidth);
510 case "minheight": return N(minheight);
511 case "maxheight": return N(maxheight);
512 case "clip": return B(test(CLIP));
513 case "visible": return B(test(VISIBLE) && (parent == null || (parent.get(JS.S("visible")) == T)));
514 case "packed": return B(test(PACKED));
515 case "globalx": return N(localToGlobalX(0));
516 case "globaly": return N(localToGlobalY(0));
517 case "cursor": return test(CURSOR) ? JS.S((String)boxToCursor.get(this)) : null;
519 if (getSurface() == null) return null;
520 if (getSurface()._mousex == Integer.MAX_VALUE)
521 throw new JSExn("you cannot read from the box.mouse property in background thread context");
523 case "numchildren": return redirect == null ? N(0) : redirect == this ? N(treeSize()) : redirect.get(JS.S("numchildren"));
524 case "redirect": return redirect == null ? null : redirect == this ? T : redirect.get(JS.S("redirect"));
525 case "Minimized": if (parent == null && getSurface() != null) return B(getSurface().minimized);
526 default: return super.get(name);
528 throw new Error("unreachable"); // unreachable
531 private class Mouse extends JS implements JS.Cloneable {
532 public JS get(JS key) throws JSExn {
533 //#switch(JS.toString(key))
534 case "x": return N(globalToLocalX(getSurface()._mousex));
535 case "y": return N(globalToLocalY(getSurface()._mousey));
537 // this might not get recomputed if we change mousex/mousey...
538 case "inside": return B(test(MOUSEINSIDE));
544 //#repeat setWidth/setHeight minwidth/minheight maxwidth/maxheight pendingWidth/pendingHeight
545 public void setWidth(int min, int max) {
546 // FIXME: deal with conflicting min/max
547 if (this.minwidth == min && this.maxwidth == max) return;
551 if (parent != null || getSurface() == null) return;
552 getSurface().pendingWidth = maxwidth;
554 // FIXME: the repeat doesn't work right here
555 getSurface().setMinimumSize(minwidth, minheight, minwidth != maxwidth || minheight != maxheight);
559 public void put(JS name, JS value) throws JSExn {
560 if (JS.isInt(name)) { put(JS.toInt(name), value); return; }
561 //#switch(JS.toString(name))
562 case "thisbox": if (value == null) removeSelf();
563 case "text": { String s = value == null ? "" : JS.toString(value); CHECKSET_STRING(text); RECONSTRAIN(); dirty(); }
564 case "strokecolor": value = N(Color.stringToColor(JS.toString(value))); CHECKSET_INT(strokecolor); dirty();
565 case "textcolor": value = N(Color.stringToColor(JS.toString(value))); CHECKSET_INT(strokecolor); dirty();
566 case "strokewidth": CHECKSET_SHORT(strokewidth); dirty();
567 case "shrink": CHECKSET_FLAG(HSHRINK | VSHRINK); RECONSTRAIN();
568 case "hshrink": CHECKSET_FLAG(HSHRINK); RECONSTRAIN();
569 case "vshrink": CHECKSET_FLAG(VSHRINK); RECONSTRAIN();
570 case "path": path = Path.parse(toString(value)); RECONSTRAIN(); dirty();
571 case "width": setWidth(toInt(value), toInt(value));
572 case "height": setHeight(toInt(value), toInt(value));
573 case "maxwidth": setWidth(minwidth, toInt(value));
574 case "minwidth": setWidth(toInt(value), maxwidth);
575 case "maxheight": setHeight(minheight, toInt(value));
576 case "minheight": setHeight(toInt(value), maxheight);
577 case "colspan": if (toInt(value) > 0) { CHECKSET_SHORT(colspan); if (parent != null) parent.REPACK(); }
578 case "rowspan": if (toInt(value) > 0) { CHECKSET_SHORT(rowspan); if (parent != null) parent.REPACK(); }
579 case "visible": CHECKSET_FLAG(VISIBLE); RECONSTRAIN(); dirty();
580 case "packed": CHECKSET_FLAG(PACKED); if (parent != null) { parent.REPACK(); } else { REPACK(); }
581 case "align": clear(ALIGNS); setAlign(value); REPLACE();
582 case "cursor": setCursor(JS.toString(value));
583 case "fill": setFill(value);
584 case "clip": CHECKSET_FLAG(CLIP); if (parent == null) dirty(); else parent.dirty();
585 case "rows": CHECKSET_SHORT(rows); if (rows==0){set(FIXED, COLS);if(cols==0)cols=1;} else set(FIXED, ROWS); REPACK();
586 case "cols": CHECKSET_SHORT(cols); if (cols==0){set(FIXED, ROWS);if(rows==0)rows=1;} else set(FIXED, COLS); REPACK();
590 int mousex = toInt(((JS)value).get(JS.S("x")));
591 int mousey = toInt(((JS)value).get(JS.S("y")));
592 getSurface()._mousex = localToGlobalX(mousex);
593 getSurface()._mousey = localToGlobalY(mousey);
595 case "Minimized": if (parent == null && getSurface() != null) getSurface().minimized = toBoolean(value); // FEATURE
596 case "Maximized": if (parent == null && getSurface() != null) getSurface().maximized = toBoolean(value); // FEATURE
597 case "Close": if (parent == null && getSurface() != null) getSurface().dispose(true);
599 for(Box cur = (Box)value; cur != null || cur == redirect; cur = cur.parent)
600 if (cur == redirect) { redirect = (Box)value; return; }
601 JS.error("redirect can only be set to a descendant of its current value");
602 case "fontsize": font = Font.getFont(font == null ? null : font.stream, toInt(value)); RECONSTRAIN(); dirty();
604 if(!(value instanceof Stream)) throw new JSExn("You can only put streams to the font property");
605 //FIXME: if (font == value) return; // FIXME: unclone()
606 font = value == null ? null : Font.getFont((Stream)value, font == null ? 10 : font.pointsize);
609 case "x": if (parent==null && Surface.fromBox(this)!=null) {
612 if (test(PACKED) && parent != null) return;
616 case "y": if (parent==null && Surface.fromBox(this)!=null) {
619 if (test(PACKED) && parent != null) return;
623 case "titlebar": if (getSurface()!=null) getSurface().setTitleBarText(toString(value)); super.put(name,value);
626 case "Press1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
627 case "Press2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
628 case "Press3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
629 case "Release1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
630 case "Release2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
631 case "Release3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
632 case "Click1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
633 case "Click2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
634 case "Click3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
635 case "DoubleClick1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
636 case "DoubleClick2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
637 case "DoubleClick3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
638 case "KeyPressed": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
639 case "KeyReleased": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
640 case "Move": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
641 case "HScroll": if (!test(STOP_UPWARD_PROPAGATION) && parent != null)
642 parent.putAndTriggerTraps(name, N(JS.toFloat(value) * ((float)parent.fontSize()) / ((float)fontSize())));
643 case "VScroll": if (!test(STOP_UPWARD_PROPAGATION) && parent != null)
644 parent.putAndTriggerTraps(name, N(JS.toFloat(value) * ((float)parent.fontSize()) / ((float)fontSize())));
646 case "_Move": propagateDownward(name, value, false);
647 case "_Press1": propagateDownward(name, value, false);
648 case "_Press2": propagateDownward(name, value, false);
649 case "_Press3": propagateDownward(name, value, false);
650 case "_Release1": propagateDownward(name, value, false);
651 case "_Release2": propagateDownward(name, value, false);
652 case "_Release3": propagateDownward(name, value, false);
653 case "_Click1": propagateDownward(name, value, false);
654 case "_Click2": propagateDownward(name, value, false);
655 case "_Click3": propagateDownward(name, value, false);
656 case "_DoubleClick1": propagateDownward(name, value, false);
657 case "_DoubleClick2": propagateDownward(name, value, false);
658 case "_DoubleClick3": propagateDownward(name, value, false);
659 case "_KeyPressed": propagateDownward(name, value, false);
660 case "_KeyReleased": propagateDownward(name, value, false);
661 case "_HScroll": propagateDownward(name, value, false);
662 case "_VScroll": propagateDownward(name, value, false);
664 case "SizeChange": return;
665 case "ChildChange": return;
666 case "Enter": return;
667 case "Leave": return;
669 default: super.put(name, value);
673 private String alignToString() {
674 switch(flags & ALIGNS) {
675 case (ALIGN_TOP | ALIGN_LEFT): return "topleft";
676 case (ALIGN_BOTTOM | ALIGN_LEFT): return "bottomleft";
677 case (ALIGN_TOP | ALIGN_RIGHT): return "topright";
678 case (ALIGN_BOTTOM | ALIGN_RIGHT): return "bottomright";
679 case ALIGN_TOP: return "top";
680 case ALIGN_BOTTOM: return "bottom";
681 case ALIGN_LEFT: return "left";
682 case ALIGN_RIGHT: return "right";
683 case 0: return "center";
684 default: throw new Error("invalid alignment flags: " + (flags & ALIGNS));
688 private void setAlign(JS value) throws JSExn {
690 //#switch(JS.toString(value))
691 case "topleft": set(ALIGN_TOP | ALIGN_LEFT);
692 case "bottomleft": set(ALIGN_BOTTOM | ALIGN_LEFT);
693 case "topright": set(ALIGN_TOP | ALIGN_RIGHT);
694 case "bottomright": set(ALIGN_BOTTOM | ALIGN_RIGHT);
695 case "top": set(ALIGN_TOP);
696 case "bottom": set(ALIGN_BOTTOM);
697 case "left": set(ALIGN_LEFT);
698 case "right": set(ALIGN_RIGHT);
699 default: JS.log("invalid alignment \"" + JS.debugToString(value) + "\"");
703 private void setCursor(String value) throws JSExn {
704 if (value == null) { clear(CURSOR); boxToCursor.remove(this); return; }
705 if (value.equals(boxToCursor.get(this))) return;
707 boxToCursor.put(this, value);
708 Surface surface = getSurface();
709 if (surface == null) return;
710 String tempcursor = surface.cursor;
711 propagateDownward(null, null, false);
712 if (surface.cursor != tempcursor) surface.syncCursor();
715 private void setFill(JS value) throws JSExn {
717 if (texture == null && fillcolor == 0) return;
720 } else if (JS.isString(value)) {
721 int newfillcolor = Color.stringToColor(JS.toString(value));
722 if (newfillcolor == fillcolor) return;
723 fillcolor = newfillcolor;
726 Picture newtex = Picture.load((JS)value, this);
727 if (texture == newtex) return;
730 if (texture != null && texture.isLoaded) perform();
736 * Handles events which propagate down the box tree. If obscured
737 * is set, then we merely check for Enter/Leave.
739 private void propagateDownward(JS name_, JS value, boolean obscured) throws JSExn {
741 String name = JS.toString(name_);
742 if (getSurface() == null) return;
743 int x = globalToLocalX(getSurface()._mousex);
744 int y = globalToLocalY(getSurface()._mousey);
745 boolean wasinside = test(MOUSEINSIDE);
746 boolean isinside = test(VISIBLE) && inside(x, y) && !obscured;
747 if (!wasinside && isinside) {
749 putAndTriggerTrapsAndCatchExceptions(JS.S("Enter"), T);
751 if (isinside && test(CURSOR)) getSurface().cursor = (String)boxToCursor.get(this);
752 if (wasinside && !isinside) {
754 putAndTriggerTrapsAndCatchExceptions(JS.S("Leave"), T);
757 boolean found = false;
758 if (wasinside || isinside)
759 for(Box child = getChild(treeSize() - 1); child != null; child = child.prevSibling()) {
760 boolean save_stop = child.test(STOP_UPWARD_PROPAGATION);
762 if (name.equals("_HScroll") || name.equals("_VScroll"))
763 value2 = N(JS.toFloat(value) * ((float)child.fontSize()) / (float)fontSize());
764 if (obscured || !child.inside(x - child.x, y - child.y)) {
765 child.propagateDownward(name_, value2, true);
768 child.clear(STOP_UPWARD_PROPAGATION);
769 if (name != null) child.putAndTriggerTrapsAndCatchExceptions(name_, value2);
770 else child.propagateDownward(name_, value2, obscured);
772 if (save_stop) child.set(STOP_UPWARD_PROPAGATION); else child.clear(STOP_UPWARD_PROPAGATION);
774 if (child.inside(x - child.x, y - child.y))
775 if (name != null && name.equals("_Move")) obscured = true;
779 if (!obscured && !found)
780 if ("_Move".equals(name) || name.startsWith("_Release") || wasinside)
782 putAndTriggerTrapsAndCatchExceptions(JS.S(name.substring(1)), value);
785 /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface */
786 public static Box whoIs(Box cur, int x, int y) {
788 if (cur.parent != null) throw new Error("whoIs may only be invoked on the root box of a surface");
792 // WARNING: this method is called from the event-queueing thread -- it may run concurrently with
793 // ANY part of Ibex, and is UNSYNCHRONIZED for performance reasons. BE CAREFUL HERE.
795 if (!cur.test(VISIBLE)) return null;
796 if (!cur.inside(x - globalx, y - globaly)) return cur.parent == null ? cur : null;
798 for(int i=cur.treeSize() - 1; i>=0; i--) {
799 Box child = cur.getChild(i);
800 if (child == null) continue; // since this method is unsynchronized, we have to double-check
803 if (child.test(VISIBLE) && child.inside(x - globalx, y - globaly)) { cur = child; continue OUTER; }
813 // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
815 void mark_for_repack() { REPACK(); }
816 public Enumeration keys() { throw new Error("you cannot apply for..in to a " + this.getClass().getName()); }
817 public Box getRoot() { return parent == null ? this : parent.getRoot(); }
818 public Surface getSurface() { return Surface.fromBox(getRoot()); }
819 Box nextPackedSibling() { Box b = nextSibling(); return b == null || (b.test(PACKED | VISIBLE)) ? b : b.nextPackedSibling(); }
820 Box firstPackedChild() { Box b = getChild(0); return b == null || (b.test(PACKED | VISIBLE)) ? b : b.nextPackedSibling(); }
821 public int globalToLocalX(int x) { return parent == null ? x : parent.globalToLocalX(x - this.x); }
822 public int globalToLocalY(int y) { return parent == null ? y : parent.globalToLocalY(y - this.y); }
823 public int localToGlobalX(int x) { return parent == null ? x : parent.globalToLocalX(x + this.x); }
824 public int localToGlobalY(int y) { return parent == null ? y : parent.globalToLocalY(y + this.y); }
826 static short min(short a, short b) { if (a<b) return a; else return b; }
827 static int min(int a, int b) { if (a<b) return a; else return b; }
828 static float min(float a, float b) { if (a<b) return a; else return b; }
830 static short max(short a, short b) { if (a>b) return a; else return b; }
831 static int max(int a, int b) { if (a>b) return a; else return b; }
832 static float max(float a, float b) { if (a>b) return a; else return b; }
834 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; }
835 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; }
836 static int bound(int a, int b, int c) { if (c < b) return c; if (a > b) return a; return b; }
837 final boolean inside(int x, int y) { return test(VISIBLE) && x >= 0 && y >= 0 && x < width && y < height; }
839 void set(int mask) { flags |= mask; }
840 void set(int mask, boolean setclear) { if (setclear) set(mask); else clear(mask); }
841 void clear(int mask) { flags &= ~mask; }
842 public boolean test(int mask) { return ((flags & mask) == mask); }
845 // Tree Handling //////////////////////////////////////////////////////////////////////
847 public final int getIndexInParent() { return parent == null ? 0 : parent.indexNode(this); }
848 public final Box nextSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) + 1); }
849 public final Box prevSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) - 1); }
850 public final Box getChild(int i) {
851 if (i < 0) return null;
852 if (i >= treeSize()) return null;
853 return (Box)getNode(i);
856 // Tree Manipulation /////////////////////////////////////////////////////////////////////
858 public void removeSelf() {
859 if (parent != null) { parent.removeChild(parent.indexNode(this)); return; }
860 Surface surface = Surface.fromBox(this);
861 if (surface != null) surface.dispose(true);
864 /** remove the i^th child */
865 public void removeChild(int i) {
869 b.clear(MOUSEINSIDE);
873 putAndTriggerTrapsAndCatchExceptions(JS.S("ChildChange"), b);
876 public void put(int i, JS value) throws JSExn {
879 if (value != null && !(value instanceof Box)) {
880 if (Log.on) JS.warn("attempt to set a numerical property on a box to a non-box");
884 if (redirect == null) {
885 if (value == null) putAndTriggerTrapsAndCatchExceptions(JS.S("ChildChange"), getChild(i));
886 else JS.warn("attempt to add/remove children to/from a node with a null redirect");
888 } else if (redirect != this) {
889 if (value != null) putAndTriggerTrapsAndCatchExceptions(JS.S("ChildChange"), value);
890 redirect.put(i, value);
892 Box b = (Box)redirect.get(JS.N(i));
893 if (b != null) putAndTriggerTrapsAndCatchExceptions(JS.S("ChildChange"), b);
896 } else if (value == null) {
897 if (i < 0 || i > treeSize()) return;
900 putAndTriggerTrapsAndCatchExceptions(JS.S("ChildChange"), b);
905 // check if box being moved is currently target of a redirect
906 for(Box cur = b.parent; cur != null; cur = cur.parent)
907 if (cur.redirect == b) {
908 if (Log.on) JS.warn("attempt to move a box that is the target of a redirect");
912 // check for recursive ancestor violation
913 for(Box cur = this; cur != null; cur = cur.parent)
915 if (Log.on) JS.warn("attempt to make a node a parent of its own ancestor");
916 if (Log.on) Log.info(this, "box == " + this + " ancestor == " + b);
920 if (b.parent != null) b.parent.removeChild(b.parent.indexNode(b));
924 // need both of these in case child was already uncalc'ed
929 putAndTriggerTrapsAndCatchExceptions(JS.S("ChildChange"), b);
933 public void putAndTriggerTrapsAndCatchExceptions(JS name, JS val) {
935 putAndTriggerTraps(name, val);
937 JS.log("caught js exception while putting to trap \""+ JS.debugToString(name)+"\"");
939 } catch (Exception e) {
940 JS.log("caught exception while putting to trap \""+ JS.debugToString(name)+"\"");
945 // BalancedTree functions
946 private void insertNode(int p, Box b) {
947 if(bt == null) bt = new BalancedTree();
951 private int treeSize() { return bt == null ? 0 : bt.treeSize(); }
952 private int indexNode(Box b) { return bt == null ? -1 : bt.indexNode(b); }
953 private void deleteNode(int p) { bt.deleteNode(p); }
954 private Box getNode(int p) { return (Box)bt.getNode(p); }