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 // FEATURE: mark to reflow starting with a certain child
12 // FEATURE: reintroduce surface.abort
16 import org.ibex.util.*;
17 import org.ibex.translators.*;
21 * Encapsulates the data for a single Ibex box as well as all layout
25 * <p>The rendering process consists of four phases; each requires
26 * one DFS pass over the tree</p>
27 * <ol><li> <b>pack()</b>: each box sets its childrens' row/col
28 * <ol><li> <b>constrain()</b>: contentwidth is computed
29 * <li> <b>resize()</b>: width/height and x/y positions are set
30 * <li> <b>render()</b>: children draw their content onto the PixelBuffer.
33 * The first three passes together are called the <i>reflow</i>
34 * phase. Reflowing is done in a seperate pass since SizeChanges
35 * trigger a Surface.abort; if rendering were done in the same pass,
36 * rendering work done prior to the Surface.abort would be wasted.
38 public final class Box extends JSScope implements Scheduler.Task {
40 // Macros //////////////////////////////////////////////////////////////////////
42 final void REPLACE() { for(Box b2 = this; b2 != null && !b2.test(REPLACE); b2 = b2.parent) b2.set(REPLACE); }
43 final void RECONSTRAIN() { for(Box b2 = this; b2 != null && !b2.test(RECONSTRAIN); b2 = b2.parent) b2.set(RECONSTRAIN); }
44 final void REPACK() { for(Box b2 = this; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK); }
46 //#define CHECKSET_SHORT(prop) short nu = (short)toInt(value); if (nu == prop) break; prop = nu;
47 //#define CHECKSET_INT(prop) int nu = toInt(value); if (nu == prop) break; prop = nu;
48 //#define CHECKSET_FLAG(flag) boolean nu = toBoolean(value); if (nu == test(flag)) break; if (nu) set(flag); else clear(flag);
49 //#define CHECKSET_BOOLEAN(prop) boolean nu = toBoolean(value); if (nu == prop) break; prop = nu;
50 //#define CHECKSET_STRING(prop) if ((value==null&&prop==null)||(value!=null&&JS.toString(value).equals(prop))) break; prop=JS.toString(value);
52 protected Box() { super(null); }
54 static Hash boxToCursor = new Hash(500, 3); // FIXME memory leak
55 static final Font DEFAULT_FONT = Font.getFont((Stream)Main.builtin.get("fonts/vera/Vera.ttf"), 10);
58 // events can have write traps, but not read traps
59 static final String[] events = new String[] {
60 "Press1", "Press2", "Press3",
61 "Release1", "Release2", "Release3",
62 "Click1", "Click2", "Click3",
63 "DoubleClick1", "DoubleClick2", "DoubleClick3",
64 "Enter", "Leave", "Move", "ChildChange",
65 "KeyPressed", "KeyReleased", "SizeChange",
66 "Focused", "Maximized", "Minimized", "Close"
69 // Flags //////////////////////////////////////////////////////////////////////
71 static final int MOUSEINSIDE = 0x00000001;
72 static final int VISIBLE = 0x00000002;
73 static final int PACKED = 0x00000004;
74 static final int HSHRINK = 0x00000008;
75 static final int VSHRINK = 0x00000010;
76 static final int BLACK = 0x00000020; // for red-black code
78 static final int FIXED = 0x00000040;
79 static final boolean ROWS = true;
80 static final boolean COLS = false;
82 static final int ISROOT = 0x00000080;
83 static final int REPACK = 0x00000100;
84 static final int RECONSTRAIN = 0x00000200;
85 static final int REPLACE = 0x00000400;
87 static final int ALIGN_TOP = 0x00001000;
88 static final int ALIGN_BOTTOM = 0x00002000;
89 static final int ALIGN_LEFT = 0x00004000;
90 static final int ALIGN_RIGHT = 0x00008000;
91 static final int ALIGNS = 0x0000f000;
92 static final int CURSOR = 0x00010000; // if true, this box has a cursor in the cursor hash; FEATURE: GC issues?
93 static final int CLIP = 0x00020000;
94 static final int STOP_UPWARD_PROPAGATION = 0x00040000;
95 static final int MOVED = 0x00080000;
98 // Instance Data //////////////////////////////////////////////////////////////////////
102 int flags = VISIBLE | PACKED | REPACK | RECONSTRAIN | REPLACE | FIXED | STOP_UPWARD_PROPAGATION | CLIP | MOVED;
104 private String text = null;
105 private Font font = DEFAULT_FONT;
106 private Picture texture = null;
107 private short strokewidth = 1;
108 public int fillcolor = 0x00000000;
109 private int strokecolor = 0xFF000000;
111 private int aspect = 0;
113 // specified directly by user
114 public int minwidth = 0;
115 public int maxwidth = Integer.MAX_VALUE;
116 public int minheight = 0;
117 public int maxheight = Integer.MAX_VALUE;
118 private short rows = 1;
119 private short cols = 0;
120 private short rowspan = 1;
121 private short colspan = 1;
123 // computed during reflow
124 private short row = 0;
125 private short col = 0;
128 public int ax = 0; // FEATURE: roll these into x/y; requires lots of changes
129 public int ay = 0; // FEATURE: roll these into x/y; requires lots of changes; perhaps y()?
130 public int width = 0;
131 public int height = 0;
132 private int contentwidth = 0; // == max(minwidth, textwidth, sum(child.contentwidth))
133 private int contentheight = 0;
136 private VectorGraphics.VectorPath path = null;
137 private VectorGraphics.Affine transform = null;
138 private VectorGraphics.RasterPath rpath = null;
139 private VectorGraphics.Affine rtransform = null;
142 //#define DIRTY dirty()
144 // Instance Methods /////////////////////////////////////////////////////////////////////
146 public final int fontSize() { return font == null ? DEFAULT_FONT.pointsize : font.pointsize; }
148 /** invoked when a resource needed to render ourselves finishes loading */
149 public void perform() throws JSExn {
150 if (texture == null) { Log.warn(Box.class, "perform() called with null texture"); return; }
151 if (texture.isLoaded) {
152 setMinWidth(max(texture.width, minwidth));
153 setMinHeight(max(texture.height, minheight));
155 else { JS res = texture.stream; texture = null; throw new JSExn("image not found: "+res.unclone()); }
158 // FEATURE: use cx2/cy2 format
159 /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
160 public void dirty() { dirty(0, 0, width, height); }
161 public void dirty(int x, int y, int w, int h) {
162 for(Box cur = this; cur != null; cur = cur.parent) {
163 // x and y have a different meaning on the root box
164 if (cur.parent != null && cur.test(CLIP)) {
165 w = min(x + w, cur.width) - max(x, 0);
166 h = min(y + h, cur.height) - max(y, 0);
170 if (w <= 0 || h <= 0) return;
171 if (cur.parent == null && cur.getSurface() != null) cur.getSurface().dirty(x, y, w, h);
178 // Reflow ////////////////////////////////////////////////////////////////////////////////////////
180 /** should only be invoked on the root box */
181 void reflow() { pack(); resize(x, y, maxwidth, maxheight); place(); }
183 private static Box[] frontier = new Box[65535];
184 /** pack the boxes into rows and columns, compute contentwidth */
186 if (!test(REPACK)) { constrain(); return; }
187 boolean haskid = false;
188 for(Box child = getChild(0); child != null; child = child.nextSibling()) { haskid = true; child.pack(); }
189 if (!haskid) { clear(REPACK); constrain(); return; }
190 int frontier_size = 0;
191 //#repeat COLS/ROWS rows/cols cols/rows col/row row/col colspan/rowspan rowspan/colspan \
192 // contentheight/contentwidth contentwidth/contentheight
193 if (test(FIXED) == COLS) {
195 for(Box child = getChild(0); child != null; child = child.nextSibling()) {
196 if (!child.test(PACKED) || !child.test(VISIBLE)) continue;
197 if (cols == 1) { child.row = rows; rows += child.rowspan; child.col = 0; continue; }
198 child.col = (short)(frontier_size <= 0 ? 0 : (frontier[frontier_size-1].col + frontier[frontier_size-1].colspan));
199 child.row = (short)(frontier_size <= 0 ? 0 : frontier[frontier_size-1].row);
200 if (child.col + min(cols,child.colspan) > cols) { child.col = 0; child.row++; }
201 for(int i=0; i<frontier_size; i++)
202 if (frontier[i].row + frontier[i].rowspan <= child.row) {
203 frontier[i--] = frontier[--frontier_size]; frontier[frontier_size] = null;
204 } else if (frontier[i].col<child.col+min(cols,child.colspan)&&frontier[i].col+frontier[i].colspan>child.col) {
205 child.col = (short)(frontier[i].col + frontier[i].colspan);
206 if (child.col + min(cols,child.colspan) > cols) {
207 child.row = (short)(frontier[i].row + frontier[i].rowspan);
208 for(i--; i>0; i--) child.row = (short)min(row, frontier[i].row + frontier[i].rowspan);
209 child.col = (short)0;
213 frontier[frontier_size++] = child;
215 for(int i=0; i<frontier_size; i++){ rows=(short)max(rows, frontier[i].row + frontier[i].rowspan); frontier[i] = null; }
219 set(RECONSTRAIN); // FIXME: be smarter / more incremental
223 public void constrain() {
224 if (!test(RECONSTRAIN)) return;
226 //#repeat contentwidth/contentheight contentheight/contentwidth minwidth/minheight row/col col/row \
227 // textwidth/textheight maxwidth/maxheight cols/rows rows/cols colspan/rowspan rowspan/colspan
228 contentwidth = bound(minwidth,
229 max(contentwidth, font == null || text == null ? 0 : font.textwidth(text)),
232 set(REPLACE); // FIXME: be smarter / more incremental
235 void resize(int x, int y, int width, int height) {
236 if (x == this.x && y == this.y && width == this.width && height == this.height) return;
237 boolean sizechange = (this.width != width || this.height != height) && getTrap("SizeChange") != null;
238 int thisx = parent == null ? 0 : this.x;
239 int thisy = parent == null ? 0 : this.y;
240 Box who = (parent == null ? this : parent);
241 if (this.x != x || this.y != y) set(MOVED);
242 if (texture == null && (text == null || text.equals("")) && !test(MOVED)) {
243 if ((fillcolor & 0xff000000) != 0 || parent == null) {
244 who.dirty(thisx+min(this.width,width), thisy, Math.abs(width-this.width), max(this.height, height));
245 who.dirty(thisx, thisy+min(this.height,height), max(this.width, width), Math.abs(height-this.height));
247 this.width = width; this.height = height; this.x = x; this.y = y;
249 who.dirty(thisx, thisy, this.width, this.height);
250 this.width = width; this.height = height; this.x = x; this.y = y;
253 if (sizechange) putAndTriggerTrapsAndCatchExceptions("SizeChange", T);
256 private float targetColumnSize = (float)0.0;
257 private float targetRowSize = (float)0.0;
258 private static float[] sizes = new float[65535];
259 private static float[] sizes_v = new float[65535];
260 private static int[] regions = new int[65535];
261 private static int[] regions_v = new int[65535];
262 private static int numregions = 0;
263 private static int numregions_v = 0;
265 void solve(boolean findMinimum) {
266 int numkids = 0; for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling()) numkids++;
267 //#repeat col/row colspan/rowspan contentwidth/contentheight width/height HSHRINK/VSHRINK numregions/numregions_v \
268 // maxwidth/maxheight cols/rows minwidth/minheight regions/regions_v targetColumnSize/targetRowSize sizes/sizes_v \
271 if (findMinimum) contentwidth = 0;
272 else targetColumnSize = 0;
273 } else if (cols == 1) {
276 for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling())
277 contentwidth = max(contentwidth, c.contentwidth);
279 targetColumnSize = width;
281 } else if (cols > 1) do {
283 // FIXME: cache these?
286 for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling()) {
287 regions[numregions++] = c.col;
288 regions[numregions++] = min(cols, c.col+c.colspan);
290 Vec.sortInts(regions, 0, numregions);
292 int newnumregions = numregions;
293 for(int i=1; i<numregions; i++) {
294 if (regions[j] != regions[i]) j++;
295 else newnumregions--;
296 regions[j] = regions[i];
298 numregions = newnumregions;
299 if (regions[numregions-1] == cols) numregions--;
300 else regions[numregions] = cols;
302 int target = findMinimum ? 0 : Math.max(width, contentwidth);
303 // priority 0: (inviolable) honor minwidths
304 // priority 1: sum of columns no greater than parent
305 // priority 2: honor maxwidths
306 // priority 3: equalize columns
307 float targetColumnSize = target == 0 ? 0 : this.targetColumnSize;
308 float last_columnsize = 0;
309 float last_total = 0;
311 boolean first = true;
314 for(int r=0; r<numregions; r++) total += (sizes[r] = (float)(targetColumnSize * (regions[r+1]-regions[r])));
316 for(Box child = firstPackedChild(); child != null; child = child.nextPackedSibling())
317 for(int r=(child.col==0?0:minregion); r<numregions; r++) {
318 if (regions[r+1] < child.col) continue;
319 if (regions[r] >= min(child.col+child.colspan,cols)) { minregion = r; break; }
321 int child_maxwidth = child.test(HSHRINK)?child.contentwidth:child.maxwidth;
322 if (sizes[r] <= (float)(targetColumnSize*(regions[r+1]-regions[r])))
323 if ((child.colspan * targetColumnSize) > (child_maxwidth + (float)0.5))
324 sizes[r] = (float)Math.min(sizes[r], (regions[r+1]-regions[r])*(child_maxwidth/child.colspan));
325 if ((child.colspan * targetColumnSize) < (child.contentwidth - (float)0.5))
326 sizes[r] = (float)Math.max(sizes[r], (regions[r+1]-regions[r])*(child.contentwidth/child.colspan));
329 float save = targetColumnSize;
330 if (Math.abs(total - target) <= (float)1.0) break;
332 if (Math.abs(total - last_total) <= (float)1.0) break;
334 last_columnsize = ((total - target) / (float)cols) + targetColumnSize;
336 if (total < target) targetColumnSize += Math.abs((last_columnsize - targetColumnSize) / (float)1.1);
337 else if (total > target) targetColumnSize -= Math.abs((last_columnsize - targetColumnSize) / (float)1.1);
338 last_columnsize = save;
342 if (findMinimum) contentwidth = Math.round(total);
343 else this.targetColumnSize = targetColumnSize;
350 for(Box child = getChild(0); child != null; child = child.nextSibling()) {
351 if (!child.test(VISIBLE)) continue;
352 if (!child.test(REPLACE)) continue;
353 int child_width, child_height, child_x, child_y;
354 if (!child.test(PACKED)) {
355 child_width = child.test(HSHRINK) ? child.contentwidth : min(child.maxwidth, width - Math.abs(child.ax));
356 child_height = child.test(VSHRINK) ? child.contentheight : min(child.maxheight, height - Math.abs(child.ay));
357 child_width = max(child.minwidth, child_width);
358 child_height = max(child.minheight, child_height);
359 int gap_x = width - child_width;
360 int gap_y = height - child_height;
361 child_x = child.ax + (child.test(ALIGN_RIGHT) ? gap_x : !child.test(ALIGN_LEFT) ? gap_x / 2 : 0);
362 child_y = child.ay + (child.test(ALIGN_BOTTOM) ? gap_y : !child.test(ALIGN_TOP) ? gap_y / 2 : 0);
365 //#repeat col/row colspan/rowspan contentwidth/contentheight width/height colMaxWidth/rowMaxHeight \
366 // child_x/child_y x/y HSHRINK/VSHRINK maxwidth/maxheight cols/rows minwidth/minheight x_slack/y_slack \
367 // child_width/child_height ALIGN_RIGHT/ALIGN_BOTTOM ALIGN_LEFT/ALIGN_TOP lp_h/lp \
368 // numregions/numregions_v regions/regions_v targetColumnSize/targetRowSize sizes/sizes_v
374 for(int r=0; r<numregions; r++) {
375 if (regions[r] < child.col) child_x += Math.round(sizes[r]);
376 else if (regions[r] < child.col+child.colspan) child_width += Math.round(sizes[r]);
379 diff = (child_width - (child.test(HSHRINK) ? child.contentwidth : min(child_width, child.maxwidth)));
380 child_x += (child.test(ALIGN_RIGHT) ? diff : child.test(ALIGN_LEFT) ? 0 : diff / 2);
384 if (test(MOVED)) child.set(MOVED);
385 child.resize(child_x, child_y, child_width, child_height);
389 for(Box child = getChild(0); child != null; child = child.nextSibling())
390 if (child.test(VISIBLE) && child.treeSize() > 0)
396 // Rendering Pipeline /////////////////////////////////////////////////////////////////////
398 /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
399 void render(int parentx, int parenty, int cx1, int cy1, int cx2, int cy2, PixelBuffer buf, VectorGraphics.Affine a) {
400 if (!test(VISIBLE)) return;
401 int globalx = parentx + (parent == null ? 0 : x);
402 int globaly = parenty + (parent == null ? 0 : y);
404 // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
406 cx1 = max(cx1, globalx);
407 cy1 = max(cy1, globaly);
408 cx2 = min(cx2, globalx + width);
409 cy2 = min(cy2, globaly + height);
410 if (cx2 <= cx1 || cy2 <= cy1) return;
413 if ((fillcolor & 0xFF000000) != 0x00000000 || parent == null)
414 buf.fillTrapezoid(cx1, cx2, cy1, cx1, cx2, cy2, (fillcolor & 0xFF000000) == 0 ? 0xffffffff : fillcolor);
416 if (texture != null && texture.isLoaded)
417 for(int x = globalx; x < cx2; x += texture.width)
418 for(int y = globaly; y < cy2; y += texture.height)
419 buf.drawPicture(texture, x, y, cx1, cy1, cx2, cy2);
421 if (text != null && !text.equals("") && font != null) {
422 int gap_x = width - font.textwidth(text);
423 int gap_y = height - font.textheight(text);
424 int text_x = globalx + (test(ALIGN_RIGHT) ? gap_x : !test(ALIGN_LEFT) ? gap_x/2 : 0);
425 int text_y = globaly + (test(ALIGN_BOTTOM) ? gap_y : !test(ALIGN_TOP) ? gap_y/2 : 0);
426 font.rasterizeGlyphs(text, buf, strokecolor, text_x, text_y, cx1, cy1, cx2, cy2);
429 for(Box b = getChild(0); b != null; b = b.nextSibling())
430 b.render(globalx, globaly, cx1, cy1, cx2, cy2, buf, null);
434 // Methods to implement org.ibex.js.JS //////////////////////////////////////
437 public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
443 if (b.parent != this)
444 return (redirect == null || redirect == this) ?
446 redirect.callMethod(method, a0, a1, a2, rest, nargs);
447 return N(b.getIndexInParent());
452 ret.put("x", N(b.localToGlobalX(0) - localToGlobalX(0)));
453 ret.put("y", N(b.localToGlobalY(0) - localToGlobalY(0)));
459 return super.callMethod(method, a0, a1, a2, rest, nargs);
462 public Object get(Object name) throws JSExn {
463 if (name instanceof Number)
464 return redirect == null ? null : redirect == this ? getChild(toInt(name)) : redirect.get(name);
467 case "surface": return parent == null ? null : parent.getAndTriggerTraps("surface");
468 case "indexof": return METHOD;
469 case "distanceto": return METHOD;
470 case "text": return text;
471 case "path": throw new JSExn("cannot read from the path property");
472 case "fill": return colorToString(fillcolor);
473 case "strokecolor": return colorToString(strokecolor);
474 case "textcolor": return colorToString(strokecolor);
475 case "font": return font == null ? null : font.stream;
476 case "fontsize": return font == null ? N(10) : N(font.pointsize);
477 case "strokewidth": return N(strokewidth);
478 case "align": return alignToString();
479 case "thisbox": return this;
480 case "shrink": return B(test(HSHRINK) || test(VSHRINK));
481 case "hshrink": return B(test(HSHRINK));
482 case "vshrink": return B(test(VSHRINK));
483 case "aspect": return N(aspect);
484 case "x": return (parent == null || !test(VISIBLE)) ? N(0) : test(PACKED) ? N(x) : N(ax);
485 case "y": return (parent == null || !test(VISIBLE)) ? N(0) : test(PACKED) ? N(y) : N(ay);
486 case "cols": return test(FIXED) == COLS ? N(cols) : N(0);
487 case "rows": return test(FIXED) == ROWS ? N(rows) : N(0);
488 case "colspan": return N(colspan);
489 case "rowspan": return N(rowspan);
490 case "width": getRoot().reflow(); return N(width);
491 case "height": getRoot().reflow(); return N(height);
492 case "minwidth": return N(minwidth);
493 case "maxwidth": return N(maxwidth);
494 case "minheight": return N(minheight);
495 case "maxheight": return N(maxheight);
496 case "clip": return B(test(CLIP));
497 case "visible": return B(test(VISIBLE) && (parent == null || (parent.get("visible") == T)));
498 case "packed": return B(test(PACKED));
499 case "globalx": return N(localToGlobalX(0));
500 case "globaly": return N(localToGlobalY(0));
501 case "cursor": return test(CURSOR) ? boxToCursor.get(this) : null;
503 if (getSurface() == null) return null;
504 if (getSurface()._mousex == Integer.MAX_VALUE)
505 throw new JSExn("you cannot read from the box.mouse property in background thread context");
507 case "numchildren": return redirect == null ? N(0) : redirect == this ? N(treeSize()) : redirect.get("numchildren");
508 case "redirect": return redirect == null ? null : redirect == this ? T : redirect.get("redirect");
509 case "Minimized": if (parent == null && getSurface() != null) return B(getSurface().minimized);
510 default: return super.get(name);
512 throw new Error("unreachable"); // unreachable
515 private class Mouse extends JS.Cloneable {
516 public Object get(Object key) {
518 case "x": return N(globalToLocalX(getSurface()._mousex));
519 case "y": return N(globalToLocalY(getSurface()._mousey));
521 // this might not get recomputed if we change mousex/mousey...
522 case "inside": return B(test(MOUSEINSIDE));
528 public void setMaxWidth(Object value) {
529 do { CHECKSET_INT(maxwidth); RECONSTRAIN(); } while(false);
530 if (parent == null && getSurface() != null) getSurface().pendingWidth = maxwidth;
532 public void setMaxHeight(Object value) {
533 do { CHECKSET_INT(maxheight); RECONSTRAIN(); } while(false);
534 if (parent == null && getSurface() != null) getSurface().pendingHeight = maxheight;
537 private void setMinWidth(int m) { if (this.minwidth != m) { RECONSTRAIN(); this.minwidth = m; } }
538 private void setMinHeight(int m) { if (this.minheight != m) { RECONSTRAIN(); this.minheight = m; } }
540 public void put(Object name, Object value) throws JSExn {
541 if (name instanceof Number) { put(toInt(name), value); return; }
543 case "text": if (value == null) value = ""; CHECKSET_STRING(text); RECONSTRAIN(); DIRTY;
544 case "strokecolor": value = N(stringToColor((String)value)); CHECKSET_INT(strokecolor); DIRTY;
545 case "textcolor": value = N(stringToColor((String)value)); CHECKSET_INT(strokecolor); DIRTY;
546 case "strokewidth": CHECKSET_SHORT(strokewidth); DIRTY;
547 case "shrink": put("hshrink", value); put("vshrink", value);
548 case "hshrink": CHECKSET_FLAG(HSHRINK); RECONSTRAIN();
549 case "vshrink": CHECKSET_FLAG(VSHRINK); RECONSTRAIN();
550 case "width": put("maxwidth", value); put("minwidth", value);
551 case "height": put("maxheight", value); put("minheight", value);
552 case "maxwidth": setMaxWidth(value);
553 case "minwidth": CHECKSET_INT(minwidth); RECONSTRAIN();
554 if (parent == null && getSurface() != null)
555 getSurface().setMinimumSize(minwidth, minheight, minwidth != maxwidth || minheight != maxheight);
556 case "maxheight": setMaxHeight(value);
557 case "minheight": CHECKSET_INT(minheight); RECONSTRAIN();
558 if (parent == null && getSurface() != null)
559 getSurface().setMinimumSize(minwidth, minheight, minwidth != maxwidth || minheight != maxheight);
560 case "colspan": if (toInt(value) > 0) { CHECKSET_SHORT(colspan); if (parent != null) parent.REPACK(); }
561 case "rowspan": if (toInt(value) > 0) { CHECKSET_SHORT(rowspan); if (parent != null) parent.REPACK(); }
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();
564 case "clip": CHECKSET_FLAG(CLIP); if (parent == null) DIRTY; else parent.DIRTY;
565 case "visible": CHECKSET_FLAG(VISIBLE); RECONSTRAIN(); DIRTY;
566 case "packed": CHECKSET_FLAG(PACKED); if (parent != null) parent.REPACK();
567 case "align": clear(ALIGNS); setAlign(value == null ? "center" : value); REPLACE();
568 case "cursor": setCursor(value);
569 case "fill": setFill(value);
571 int mousex = toInt(((JS)value).get("x"));
572 int mousey = toInt(((JS)value).get("y"));
573 getSurface()._mousex = localToGlobalX(mousex);
574 getSurface()._mousey = localToGlobalY(mousey);
575 case "Minimized": if (parent == null && getSurface() != null) getSurface().minimized = toBoolean(value); // FEATURE
576 case "Maximized": if (parent == null && getSurface() != null) getSurface().maximized = toBoolean(value); // FEATURE
577 case "Close": if (parent == null && getSurface() != null) getSurface().dispose(true);
579 if (value == null) { redirect = null; return; }
580 for(Box cur = (Box)value; cur != null; cur = cur.parent)
581 if (cur == redirect) {
582 redirect = (Box)value;
585 JS.error("redirect can only be set to a descendant of its current value");
587 if(!(value instanceof Stream)) throw new JSExn("You can only put streams to the font property");
588 font = value == null ? null : Font.getFont((Stream)value, font == null ? 10 : font.pointsize);
591 case "fontsize": font = Font.getFont(font == null ? null : font.stream, toInt(value)); RECONSTRAIN(); DIRTY;
592 case "x": if (parent==null && Surface.fromBox(this)!=null) {
595 if (test(PACKED) && parent != null) return;
599 case "y": if (parent==null && Surface.fromBox(this)!=null) {
602 if (test(PACKED) && parent != null) return;
607 if (getSurface() != null && value != null) getSurface().setTitleBarText(JS.toString(value));
608 super.put(name,value);
610 case "Press1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
611 case "Press2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
612 case "Press3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
613 case "Release1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
614 case "Release2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
615 case "Release3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
616 case "Click1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
617 case "Click2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
618 case "Click3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
619 case "DoubleClick1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
620 case "DoubleClick2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
621 case "DoubleClick3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
622 case "KeyPressed": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
623 case "KeyReleased": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
624 case "Move": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value);
626 case "HScroll": if (!test(STOP_UPWARD_PROPAGATION) && parent != null)
627 parent.putAndTriggerTraps(name, N(((Number)value).floatValue() * ((float)parent.fontSize()) / ((float)fontSize())));
628 case "VScroll": if (!test(STOP_UPWARD_PROPAGATION) && parent != null)
629 parent.putAndTriggerTraps(name, N(((Number)value).floatValue() * ((float)parent.fontSize()) / ((float)fontSize())));
631 case "_Move": propagateDownward(name, value, false);
632 case "_Press1": propagateDownward(name, value, false);
633 case "_Press2": propagateDownward(name, value, false);
634 case "_Press3": propagateDownward(name, value, false);
635 case "_Release1": propagateDownward(name, value, false);
636 case "_Release2": propagateDownward(name, value, false);
637 case "_Release3": propagateDownward(name, value, false);
638 case "_Click1": propagateDownward(name, value, false);
639 case "_Click2": propagateDownward(name, value, false);
640 case "_Click3": propagateDownward(name, value, false);
641 case "_DoubleClick1": propagateDownward(name, value, false);
642 case "_DoubleClick2": propagateDownward(name, value, false);
643 case "_DoubleClick3": propagateDownward(name, value, false);
644 case "_KeyPressed": propagateDownward(name, value, false);
645 case "_KeyReleased": propagateDownward(name, value, false);
646 case "_HScroll": propagateDownward(name, value, false);
647 case "_VScroll": propagateDownward(name, value, false);
649 case "SizeChange": return;
650 case "ChildChange": return;
651 case "Enter": return;
652 case "Leave": return;
654 case "thisbox": if (value == null) removeSelf();
656 default: super.put(name, value);
660 private String alignToString() {
661 switch(flags & ALIGNS) {
662 case (ALIGN_TOP | ALIGN_LEFT): return "topleft";
663 case (ALIGN_BOTTOM | ALIGN_LEFT): return "bottomleft";
664 case (ALIGN_TOP | ALIGN_RIGHT): return "topright";
665 case (ALIGN_BOTTOM | ALIGN_RIGHT): return "bottomright";
666 case ALIGN_TOP: return "top";
667 case ALIGN_BOTTOM: return "bottom";
668 case ALIGN_LEFT: return "left";
669 case ALIGN_RIGHT: return "right";
670 case 0: return "center";
671 default: throw new Error("invalid alignment flags: " + (flags & ALIGNS));
675 private void setAlign(Object value) {
677 case "center": clear(ALIGNS);
678 case "topleft": set(ALIGN_TOP | ALIGN_LEFT);
679 case "bottomleft": set(ALIGN_BOTTOM | ALIGN_LEFT);
680 case "topright": set(ALIGN_TOP | ALIGN_RIGHT);
681 case "bottomright": set(ALIGN_BOTTOM | ALIGN_RIGHT);
682 case "top": set(ALIGN_TOP);
683 case "bottom": set(ALIGN_BOTTOM);
684 case "left": set(ALIGN_LEFT);
685 case "right": set(ALIGN_RIGHT);
686 default: JS.log("invalid alignment \"" + value + "\"");
690 private void setCursor(Object value) {
691 if (value == null) { clear(CURSOR); boxToCursor.remove(this); return; }
692 if (value.equals(boxToCursor.get(this))) return;
694 boxToCursor.put(this, value);
695 Surface surface = getSurface();
696 if (surface != null) {
697 String tempcursor = surface.cursor;
698 propagateDownward(null, null, false);
699 if (surface.cursor != tempcursor) surface.syncCursor();
703 private void setFill(Object value) throws JSExn {
705 // FIXME: Check this... does this make it transparent?
708 } else if (value instanceof String) {
709 // FIXME check double set
710 int newfillcolor = stringToColor((String)value);
711 if (newfillcolor == fillcolor) return;
712 fillcolor = newfillcolor;
713 } else if(value instanceof JS) {
714 texture = Picture.load((JS)value, this);
715 if (texture != null && texture.isLoaded) perform();
717 throw new JSExn("fill must be null, a String, or a stream, not a " + value.getClass());
722 // FIXME: mouse move/release still needs to propagate to boxen in which the mouse was pressed and is still held down
724 * Handles events which propagate down the box tree. If obscured
725 * is set, then we merely check for Enter/Leave.
727 private void propagateDownward(Object name_, Object value, boolean obscured) {
729 String name = (String)name_;
730 if (getSurface() == null) return;
731 int x = globalToLocalX(getSurface()._mousex);
732 int y = globalToLocalY(getSurface()._mousey);
733 boolean wasinside = test(MOUSEINSIDE);
734 boolean isinside = test(VISIBLE) && inside(x, y) && !obscured;
735 if (!wasinside && isinside) {
737 putAndTriggerTrapsAndCatchExceptions("Enter", T);
739 if (isinside && test(CURSOR)) getSurface().cursor = (String)boxToCursor.get(this);
740 if (wasinside && !isinside) {
742 putAndTriggerTrapsAndCatchExceptions("Leave", T);
745 boolean found = false;
746 if (wasinside || isinside)
747 for(Box child = getChild(treeSize() - 1); child != null; child = child.prevSibling()) {
748 boolean save_stop = child.test(STOP_UPWARD_PROPAGATION);
749 Object value2 = value;
750 if (name.equals("_HScroll") || name.equals("_VScroll"))
751 value2 = N(((Number)value).floatValue() * ((float)child.fontSize()) / (float)fontSize());
752 if (obscured || !child.inside(x - child.x, y - child.y)) {
753 child.propagateDownward(name, value2, true);
756 child.clear(STOP_UPWARD_PROPAGATION);
757 if (name != null) child.putAndTriggerTrapsAndCatchExceptions(name, value2);
758 else child.propagateDownward(name, value2, obscured);
760 if (save_stop) child.set(STOP_UPWARD_PROPAGATION); else child.clear(STOP_UPWARD_PROPAGATION);
762 if (child.inside(x - child.x, y - child.y))
763 if (name != null && name.equals("_Move")) obscured = true;
767 if (!obscured && !found)
768 if ("_Move".equals(name) || name.startsWith("_Release") || wasinside)
770 putAndTriggerTrapsAndCatchExceptions(name.substring(1), value);
773 private static int stringToColor(String s) {
774 // FIXME support three-char strings by doubling digits
775 if (s == null) return 0x00000000;
776 else if (SVG.colors.get(s) != null) return 0xFF000000 | toInt(SVG.colors.get(s));
777 else if (s.length() == 7 && s.charAt(0) == '#') try {
780 (Integer.parseInt(s.substring(1, 3), 16) << 16) |
781 (Integer.parseInt(s.substring(3, 5), 16) << 8) |
782 Integer.parseInt(s.substring(5, 7), 16);
783 } catch (NumberFormatException e) {
784 Log.info(Box.class, "invalid color " + s);
787 else return 0; // FEATURE: error?
790 private static String colorToString(int argb) {
791 if ((argb & 0xFF000000) == 0) return null;
792 String red = Integer.toHexString((argb & 0x00FF0000) >> 16);
793 String green = Integer.toHexString((argb & 0x0000FF00) >> 8);
794 String blue = Integer.toHexString(argb & 0x000000FF);
795 if (red.length() < 2) red = "0" + red;
796 if (blue.length() < 2) blue = "0" + blue;
797 if (green.length() < 2) green = "0" + green;
798 return "#" + red + green + blue;
801 /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface */
802 public static Box whoIs(Box cur, int x, int y) {
804 if (cur.parent != null) throw new Error("whoIs may only be invoked on the root box of a surface");
808 // WARNING: this method is called from the event-queueing thread -- it may run concurrently with
809 // ANY part of Ibex, and is UNSYNCHRONIZED for performance reasons. BE CAREFUL HERE.
811 if (!cur.test(VISIBLE)) return null;
812 if (!cur.inside(x - globalx, y - globaly)) return cur.parent == null ? cur : null;
814 for(int i=cur.treeSize() - 1; i>=0; i--) {
815 Box child = cur.getChild(i);
816 if (child == null) continue; // since this method is unsynchronized, we have to double-check
819 if (child.test(VISIBLE) && child.inside(x - globalx, y - globaly)) { cur = child; continue OUTER; }
829 // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
831 void mark_for_repack() { REPACK(); }
832 public Enumeration keys() { throw new Error("you cannot apply for..in to a " + this.getClass().getName()); }
833 public Box getRoot() { return parent == null ? this : parent.getRoot(); }
834 public Surface getSurface() { return Surface.fromBox(getRoot()); }
835 Box nextPackedSibling() { Box b = nextSibling(); return b == null || (b.test(PACKED | VISIBLE)) ? b : b.nextPackedSibling(); }
836 Box firstPackedChild() { Box b = getChild(0); return b == null || (b.test(PACKED | VISIBLE)) ? b : b.nextPackedSibling(); }
837 public int globalToLocalX(int x) { return parent == null ? x : parent.globalToLocalX(x - this.x); }
838 public int globalToLocalY(int y) { return parent == null ? y : parent.globalToLocalY(y - this.y); }
839 public int localToGlobalX(int x) { return parent == null ? x : parent.globalToLocalX(x + this.x); }
840 public int localToGlobalY(int y) { return parent == null ? y : parent.globalToLocalY(y + this.y); }
842 static short min(short a, short b) { if (a<b) return a; else return b; }
843 static int min(int a, int b) { if (a<b) return a; else return b; }
844 static float min(float a, float b) { if (a<b) return a; else return b; }
846 static short max(short a, short b) { if (a>b) return a; else return b; }
847 static int max(int a, int b) { if (a>b) return a; else return b; }
848 static float max(float a, float b) { if (a>b) return a; else return b; }
850 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; }
851 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; }
852 static int bound(int a, int b, int c) { if (c < b) return c; if (a > b) return a; return b; }
853 final boolean inside(int x, int y) { return test(VISIBLE) && x >= 0 && y >= 0 && x < width && y < height; }
855 void set(int mask) { flags |= mask; }
856 void set(int mask, boolean setclear) { if (setclear) set(mask); else clear(mask); }
857 void clear(int mask) { flags &= ~mask; }
858 boolean test(int mask) { return ((flags & mask) == mask); }
861 // Tree Handling //////////////////////////////////////////////////////////////////////
863 public final int getIndexInParent() { return parent == null ? 0 : parent.indexNode(this); }
864 public final Box nextSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) + 1); }
865 public final Box prevSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) - 1); }
866 public final Box getChild(int i) {
867 if (i < 0) return null;
868 if (i >= treeSize()) return null;
869 return (Box)getNode(i);
872 // Tree Manipulation /////////////////////////////////////////////////////////////////////
875 if (parent != null) { parent.removeChild(parent.indexNode(this)); return; }
876 Surface surface = Surface.fromBox(this);
877 if (surface != null) surface.dispose(true);
880 /** remove the i^th child */
881 public void removeChild(int i) {
885 b.clear(MOUSEINSIDE);
889 putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
892 public void put(int i, Object value) throws JSExn {
895 if (value != null && !(value instanceof Box)) {
896 if (Log.on) JS.warn("attempt to set a numerical property on a box to a non-box");
900 if (redirect == null) {
901 if (value == null) putAndTriggerTrapsAndCatchExceptions("ChildChange", getChild(i));
902 else JS.warn("attempt to add/remove children to/from a node with a null redirect");
904 } else if (redirect != this) {
905 if (value != null) putAndTriggerTrapsAndCatchExceptions("ChildChange", value);
906 redirect.put(i, value);
908 Box b = (Box)redirect.get(new Integer(i));
909 if (b != null) putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
912 } else if (value == null) {
913 if (i < 0 || i > treeSize()) return;
916 putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
921 // check if box being moved is currently target of a redirect
922 for(Box cur = b.parent; cur != null; cur = cur.parent)
923 if (cur.redirect == b) {
924 if (Log.on) JS.warn("attempt to move a box that is the target of a redirect");
928 // check for recursive ancestor violation
929 for(Box cur = this; cur != null; cur = cur.parent)
931 if (Log.on) JS.warn("attempt to make a node a parent of its own ancestor");
932 if (Log.on) Log.info(this, "box == " + this + " ancestor == " + b);
936 if (b.parent != null) b.parent.removeChild(b.parent.indexNode(b));
940 // need both of these in case child was already uncalc'ed
945 putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
949 void putAndTriggerTrapsAndCatchExceptions(Object name, Object val) {
951 putAndTriggerTraps(name, val);
953 JS.log("caught js exception while putting to trap \""+name+"\"");
955 } catch (Exception e) {
956 JS.log("caught exception while putting to trap \""+name+"\"");
971 if (rpath == null) rpath = path.realize(transform == null ? VectorGraphics.Affine.identity() : transform);
972 if ((flags & HSHRINK) != 0) contentwidth = max(contentwidth, rpath.boundingBoxWidth());
973 if ((flags & VSHRINK) != 0) contentheight = max(contentheight, rpath.boundingBoxHeight());
974 // FIXME: separate offset_x needed for the path
976 // #repeat x1/y1 x2/y2 x3/y3 x4/y4 contentwidth/contentheight left/top right/bottom
977 int x1 = transform == null ? 0 : (int)transform.multiply_px(0, 0);
978 int x2 = transform == null ? 0 : (int)transform.multiply_px(contentwidth, 0);
979 int x3 = transform == null ? contentwidth : (int)transform.multiply_px(contentwidth, contentheight);
980 int x4 = transform == null ? contentwidth : (int)transform.multiply_px(0, contentheight);
981 int left = min(min(x1, x2), min(x3, x4));
982 int right = max(max(x1, x2), max(x3, x4));
983 contentwidth = max(contentwidth, right - left);
984 offset_x = -1 * left;
991 if (rtransform == null) rpath = null;
992 else if (!rtransform.equalsIgnoringTranslation(a)) rpath = null;
994 rpath.translate((int)(a.e - rtransform.e), (int)(a.f - rtransform.f));
995 rtransform = a.copy();
997 if (rpath == null) rpath = path.realize((rtransform = a) == null ? VectorGraphics.Affine.identity() : a);
998 if ((strokecolor & 0xff000000) != 0) rpath.stroke(buf, 1, strokecolor);
999 if ((fillcolor & 0xff000000) != 0) rpath.fill(buf, new VectorGraphics.SingleColorPaint(fillcolor));
1005 VectorGraphics.Affine a2 = VectorGraphics.Affine.translate(b.x, b.y);
1006 if (transform != null) a2.multiply(transform);
1007 a2.multiply(VectorGraphics.Affine.translate(offset_x, offset_y));