1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
8 import org.mozilla.javascript.*;
12 * Encapsulates the data for a single XWT box as well as all layout
17 * This is the real meat of XWT. Part of its monolithic design is for
18 * performance reasons: deep inheritance heirarchies are slow, and
19 * neither javago nor GCJ can inline across class boundaries.
22 * <p>The rendering process consists of two phases:</p>
24 * <ol><li> <b>Prerendering pipeline</b>: a set of methods that
25 * traverse the tree (DFS, postorder) immediately before
26 * rendering. These methods calculate the appropriate size
27 * and position for all boxes. If no changes requiring a
28 * re-prerender have been made to a box or any of its
29 * descendants, <tt>needs_prerender</tt> will be false, and the box
30 * and its descendants will be skipped.
32 * <li> <b>Rendering pipeline</b>: a second set of methods that
33 * traverses the tree (DFS, preorder) and renders each Box
34 * onto the associated Surface. The render() method takes a
35 * region (x,y,w,h) as an argument, and will only render
36 * onto pixels within that region. Boxes which lie
37 * completely outside that region will be skipped.
41 * Either of these two phases may <i>abort</i> at any time by setting
42 * <tt>surface.abort</tt> to true. Currently, there are two reasons
43 * for aborting: a <tt>SizeChange</tt> or <tt>PosChange</tt> was
44 * triggered in the prerender phase (which ran scripts which modified
45 * the boxtree's composition, requiring another prerender pass), or
46 * else the user resized the surface. In either case, the
47 * [pre]rendering process is halted as soon as possible and
48 * re-started from the beginning.
51 * <p>Why are these done as seperate passes over the box tree?</p>
53 * <ol><li> Sometimes we need to make several trips through
54 * <tt>prerender()</tt?, as a result of <tt>SizeChange</tt>
55 * or <tt>PosChange</tt>. Calling <tt>prerender()</tt> is
56 * cheap; calling <tt>render()</tt> is expensive.
58 * <li> Even if no <tt>SizeChange</tt> or <tt>PosChange</tt> traps are
59 * triggered, updates to the size and position of boxes in
60 * the prerender phase can cause additional regions to be
61 * added to the dirty list. If the prerender and render
62 * passes were integrated, this might cause some screen
63 * regions to be painted twice (or more) in a single pass,
64 * which hurts performance.
68 * A box's <tt>_cmin_*</tt> variables hold the minimum possible
69 * dimensions of this box, taking into account the size of its
70 * children (and their children). The cmin variables must be kept in
71 * sync with its other geometric properties and the geometric
72 * properties of its children at all times -- they are not
73 * periodically recomputed during the [pre]rendering process, as size
74 * and pos are. If any data changes which might invalidate the cmin,
75 * the method <tt>sync_cmin_to_children()</tt> must be invoked
80 * A note on coordinates: the Box class represents regions
81 * internally as x,y,w,h tuples, even though the DoubleBuffer class
82 * uses x1,y1,x2,y2 tuples.
85 public final class Box extends JSObject {
88 // Static Data //////////////////////////////////////////////////////////////
90 /** a pool of one-element Object[]'s */
91 private static Queue singleObjects = new Queue(100);
93 /** caches images, keyed on resource name or url */
94 public static Hash pictureCache = new Hash();
96 /** cache of border objects */
97 static Hash bordercache = new Hash();
99 /** stores image names, keyed on image object */
100 static Hash imageToNameMap = new Hash();
102 /** the empty object, used for get-traps */
103 private static Object[] emptyobj = new Object[] { };
106 // Instance Data: Templates ////////////////////////////////////////////////////////
108 /** the unresolved name of the first template applied to this node [ignoring preapply's], or null if this template was specified anonymously */
109 String templatename = null;
111 /** the importlist which was used to resolve <tt>templatename</tt>, or null if this template was specified anonymously */
112 String[] importlist = Template.defaultImportList;
114 /** the template instance that resulted from resolving <tt>templatename</tt> using <tt>importlist</tt>, or the anonymous template applied */
115 Template template = null;
118 // Instance Data: Geometry ////////////////////////////////////////////////////////
120 /** The number of elements in the geom array */
121 public static final int NUMINTS = 10;
123 /** The maximum <i>defined</i> width and height of this box */
124 public static final int dmax = 0;
125 private short _dmax_0 = 0;
126 private short _dmax_1 = 0;
127 public final short dmax(int axis) { return axis == 0 ? _dmax_0 : _dmax_1; }
129 /** The minimum <i>defined</i> width and height of this box */
130 public static final int dmin = 1;
131 private short _dmin_0 = 0;
132 private short _dmin_1 = 0;
133 public final short dmin(int axis) { return axis == 0 ? _dmin_0 : _dmin_1; }
135 /** The minimum <i>calculated</i> width and height of this box -- unlike dmin, this takes childrens' sizes into account */
136 public static final int cmin = 2;
137 private short _cmin_0 = 0;
138 private short _cmin_1 = 0;
139 public final short cmin(int axis) { return axis == 0 ? _cmin_0 : _cmin_1; }
141 /** The position of this box, relitave to the parent */
142 public static final int abs = 3;
143 private short _abs_0 = 0;
144 private short _abs_1 = 0;
145 public final short abs(int axis) { return axis == 0 ? _abs_0 : _abs_1; }
147 /** The absolute position of this box (ie relitave to the root); set by the parent */
148 public static final int pos = 4;
149 private short _pos_0 = 0;
150 private short _pos_1 = 0;
151 public final short pos(int axis) { return axis == 0 ? _pos_0 : _pos_1; }
153 /** The actual size of this box; set by the parent. */
154 public static final int size = 5;
157 public final short size(int axis) { return axis == 0 ? _size_0 : _size_1; }
159 /** The old actual absolute position of this box (ie relitave to the root) */
160 public static final int oldpos = 6;
161 private short _oldpos_0 = 0;
162 private short _oldpos_1 = 0;
163 public final short oldpos(int axis) { return axis == 0 ? _oldpos_0 : _oldpos_1; }
165 /** The old actual size of this box */
166 public static final int oldsize = 7;
167 private short _oldsize_0 = 0;
168 private short _oldsize_1 = 0;
169 public final short oldsize(int axis) { return axis == 0 ? _oldsize_0 : _oldsize_1; }
171 /** The padding along each edge for this box */
172 public static final int pad = 8;
173 private short _pad_0 = 0;
174 private short _pad_1 = 0;
175 public final short pad(int axis) { return axis == 0 ? _pad_0 : _pad_1; }
177 /** The dimensions of the text in this box */
178 public static final int textdim = 9;
179 private short _textdim_0 = 0;
180 private short _textdim_1 = 0;
181 public final short textdim(int axis) { return axis == 0 ? _textdim_0 : _textdim_1; }
184 // Instance Data /////////////////////////////////////////////////////////////////
186 /** This box's mouseinside property, as defined in the reference */
187 boolean mouseinside = false;
189 /** If redirect is enabled, this holds the Box redirected to */
192 /** the Box's font -- you must call textupdate() after changing this */
193 String font = Platform.getDefaultFont();
195 /** The surface for us to render on; null if none; INVARIANT: surface == getParent().surface */
196 Surface surface = null;
198 /** Our alignment: top/left == -1, center == 0, bottom/right == +1 */
201 /** Our background image; to set this, use setImage() */
202 public Picture image;
204 /** The flex for this box */
207 /** The orientation, horizontal == 0, vertical == 1 */
210 /** The opposite of the orientation */
213 /** The id of this Box */
214 public String id = "";
216 /** The text of this Box -- you must call textupdate() after changing this */
219 /** The color of the text in this Box in 00RRGGBB form -- default is black */
220 int textcolor = 0xFF000000;
222 /** The background color of this box in AARRGGBB form -- default is clear; alpha is all-or-nothing */
223 int color = 0x00000000;
225 /** Holds four "strip images" -- 0=top, 1=bottom, 2=left, 3=right, 4=all */
226 Picture[] border = null;
228 /** true iff the box's background image should be tiled */
229 boolean tile = false;
231 /** True iff the Box is invisible */
232 public boolean invisible = false;
234 /** If true, the Box will force its own size to the natural size of its background image */
235 boolean sizetoimage = false;
237 /** If true, the box will shrink to the smallest vertical size possible */
238 boolean vshrink = false;
240 /** If true, the box will shrink to the smallest horizontal size possible */
241 boolean hshrink = false;
243 /** If true, the box will be positioned absolutely */
244 boolean absolute = false;
246 /** True iff the Box must be run through the prerender() pipeline before render()ing;<br>
247 * INVARIANT: if (needs_prerender) then getParent().needs_prerender. **/
248 boolean needs_prerender = true;
250 /** The cursor for this Box -- only meaningful on the root Box */
251 public String cursor = null;
253 /** Any traps placed on this Box */
254 public Hash traps = null;
257 // Instance Data: IndexOf ////////////////////////////////////////////////////////////
259 /** The indexof() Function; created lazily */
260 public Function indexof = null;
261 public Function indexof() {
262 if (indexof == null) indexof = new IndexOf();
266 /** a trivial private class to serve as the box.indexof function object */
267 private class IndexOf extends JSObject implements Function {
268 public IndexOf() { this.setSeal(true); }
269 public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
270 public Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException {
271 if (args == null || args.length != 1 || args[0] == null || !(args[0] instanceof Box)) return new Integer(-1);
272 Box b = (Box)args[0];
273 if (b.getParent() != Box.this) {
274 if (redirect == null || redirect == Box.this) return new Integer(-1);
275 return Box.this.redirect.indexof().call(cx, scope, thisObj, args);
277 return new Integer(b.getIndexInParent());
282 // Methods which enforce/preserve invariants ////////////////////////////////////////////
284 /** This method MUST be used to change geometry values -- it ensures that certain invariants are preserved. */
285 public final void set(int which, int axis, int newvalue) { set(which, axis, (short)newvalue); }
286 public final void set(int which, int axis, short newvalue) {
288 // if this Box is the root of the Surface, notify the Surface of size changes
289 if (getParent() == null && surface != null && which == size)
290 surface._setSize(axis == 0 ? newvalue : size(0), axis == 1 ? newvalue : size(1));
293 case dmin: if (dmin(axis) == newvalue) return; if (axis == 0) _dmin_0 = newvalue; else _dmin_1 = newvalue; break;
294 case dmax: if (dmax(axis) == newvalue) return; if (axis == 0) _dmax_0 = newvalue; else _dmax_1 = newvalue; break;
295 case cmin: if (cmin(axis) == newvalue) return; if (axis == 0) _cmin_0 = newvalue; else _cmin_1 = newvalue; break;
296 case abs: if (abs(axis) == newvalue) return; if (axis == 0) _abs_0 = newvalue; else _abs_1 = newvalue; break;
297 case pos: if (pos(axis) == newvalue) return; if (axis == 0) _pos_0 = newvalue; else _pos_1 = newvalue; break;
298 case size: if (size(axis) == newvalue) return; if (axis == 0) _size_0 = newvalue; else _size_1 = newvalue; break;
299 case oldpos: if (oldpos(axis) == newvalue) return; if (axis == 0) _oldpos_0 = newvalue; else _oldpos_1 = newvalue; break;
300 case oldsize: if (oldsize(axis) == newvalue) return; if (axis == 0) _oldsize_0 = newvalue; else _oldsize_1 = newvalue; break;
301 case pad: if (pad(axis) == newvalue) return; if (axis == 0) _pad_0 = newvalue; else _pad_1 = newvalue; break;
302 case textdim: if (textdim(axis) == newvalue) return; if (axis == 0) _textdim_0 = newvalue; else _textdim_1 = newvalue; break;
306 // size must always agree with dmin/dmax
307 if (which == dmin) set(size, axis, max(size(axis), newvalue));
308 if (which == dmax) set(size, axis, min(size(axis), newvalue));
310 // keep obedience to shrink directives
311 if (which == cmin || which == textdim || which == pad || which == dmin)
312 if ((hshrink && axis == 0) || (vshrink && axis == 1))
313 set(dmax, axis, max(cmin(axis), (textdim(axis) + 2 * pad(axis)), dmin(axis)));
315 // keep cmin in line with dmin/dmax/textdim
316 if (which == dmax || which == dmin || which == textdim || which == pad || which == cmin)
319 min(cmin(axis), dmax(axis)),
321 min(dmax(axis), textdim(axis) + 2 * pad(axis))
325 // if the pad changes, update cmin
326 if (which == pad) sync_cmin_to_children();
328 // needed in the shrink case, since dmin may have been the deciding factor in calculating cmin
329 if ((vshrink || hshrink) && which == dmin) sync_cmin_to_children();
331 // if the cmin changes, we need to be re-prerendered
332 if (which == cmin) mark_for_prerender();
334 // if the absolute position of a box changes, its parent needs to be re-prerendered (to update the child's position)
335 if (which == abs && getParent() != null) getParent().mark_for_prerender();
337 // if our cmin changes, then our parent's needs to be recalculated
338 if (getParent() != null && which == cmin) {
339 mark_for_prerender();
340 getParent().sync_cmin_to_children();
345 /** Marks this node and all its ancestors so that they will be prerender()ed */
346 public final void mark_for_prerender() {
347 if (needs_prerender) return;
348 needs_prerender = true;
349 if (getParent() != null) getParent().mark_for_prerender();
352 /** Ensures that cmin is in sync with the cmin's of our children. This should be called whenever a child is added or
353 * removed, as well as when our pad is changed. */
354 final void sync_cmin_to_children() {
355 short co = (short)(2 * pad(o));
356 short cxo = (short)(2 * pad(xo));
358 for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
359 if (bt.invisible || bt.absolute) continue;
361 cxo = (short)max(bt.cmin(xo) + 2 * pad(xo), cxo);
368 /** must be called after changes to <tt>image</tt> or <tt>border</tt> if sizetoimage is true */
369 public void syncSizeToImage() {
370 set(dmax, 0, (image == null ? 0 : image.getWidth()) + (border == null ? 0 : border[2].getWidth()) * 2);
371 set(dmax, 1, (image == null ? 0 : image.getHeight()) + (border == null ? 0 : border[0].getHeight()) * 2);
372 set(dmin, 0, (image == null ? 0 : image.getWidth()) + (border == null ? 0 : border[2].getWidth()) * 2);
373 set(dmin, 1, (image == null ? 0 : image.getHeight()) + (border == null ? 0 : border[0].getHeight()) * 2);
376 /** This must be called when font or text is changed */
378 if (text.equals("")) {
382 XWF xwf = XWF.getXWF(font);
384 set(textdim, 0, Platform.stringWidth(font, text));
385 set(textdim, 1, (Platform.getMaxAscent(font) + Platform.getMaxDescent(font)));
387 set(textdim, 0, xwf.stringWidth(text));
388 set(textdim, 1, (xwf.getMaxAscent() + xwf.getMaxDescent()));
394 // Instance Methods /////////////////////////////////////////////////////////////////////
396 /** Changes the Surface that this Box draws on. */
397 protected void setSurface(Surface newSurface) {
398 if (surface == newSurface) return;
400 if ((is_trapped("KeyPressed") || is_trapped("KeyReleased")) && surface != null)
401 surface.keywatchers.removeElement(this);
402 surface = newSurface;
403 if ((is_trapped("KeyPressed") || is_trapped("KeyReleased")) && surface != null)
404 surface.keywatchers.addElement(this);
405 for(Box i = getChild(0); i != null; i = i.nextSibling()) i.setSurface(surface);
406 if (numChildren() == 0) mark_for_prerender();
409 /** loads the image described by string str, possibly blocking for a network load */
410 private static ImageDecoder getImage(String str) {
411 ImageDecoder ret = null;
412 boolean ispng = false;
414 if (str.indexOf(':') == -1) {
416 byte[] b = Resources.getResource(Resources.resolve(s + ".png", null));
417 if (b == null) return null;
418 return PNG.decode(new ByteArrayInputStream(b), str);
421 Thread thread = Thread.currentThread();
422 if (!(thread instanceof ThreadMessage)) {
423 if (Log.on) Log.log(Box.class, "HTTP images can not be loaded from the foreground thread");
426 ThreadMessage mythread = (ThreadMessage)thread;
427 mythread.setPriority(Thread.MIN_PRIORITY);
428 mythread.done.release();
430 if (str.endsWith(".png")) ret = PNG.decode(Platform.urlToInputStream(new URL(str)), str);
431 else ret = GIF.decode(Platform.urlToInputStream(new URL(str)), str);
434 } catch (IOException e) {
435 if (Log.on) Log.log(Box.class, "error while trying to load an image from " + str);
436 if (Log.on) Log.log(Box.class, e);
440 MessageQueue.add(mythread);
441 mythread.setPriority(Thread.NORM_PRIORITY);
447 /** gets an Image using getImage(), adds it to the cache, and creates a Picture from it */
448 public static Picture getPicture(String os) {
450 ret = (Picture)pictureCache.get(os);
451 if (ret != null) return ret;
452 ImageDecoder id = getImage(os);
453 if (id == null) return null;
454 ret = Platform.createPicture(id);
455 pictureCache.put(os, ret);
456 imageToNameMap.put(ret, os);
460 /** Sets the image; argument should be a fully qualified s name or an URL */
461 void setImage(String s) {
462 if ((s == null && image == null) || (s != null && image != null && s.equals(imageToNameMap.get(image)))) return;
463 if (s == null || s.equals("")) {
465 if (sizetoimage) syncSizeToImage();
468 image = getPicture(s);
470 if (Log.on) Log.log(Box.class, "unable to load image " + s + " at " +
471 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
474 if (sizetoimage) syncSizeToImage();
479 /** Sets the border; argument should be a fully qualified resource name or an URL */
480 void setBorder(String s) {
481 if ((s == null && border == null) || (s != null && border != null && s.equals(imageToNameMap.get(border)))) return;
482 if (s == null || s.equals("")) {
484 if (sizetoimage) syncSizeToImage();
488 border = (Picture[])bordercache.get(s);
489 if (border == null) {
490 ImageDecoder id = getImage(s);
492 if (Log.on) Log.log(this, "unable to load border image " + s + " at " +
493 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
496 int[] data = id.getData();
497 int w = id.getWidth();
498 int h = id.getHeight();
502 int[][] dat = new int[4][];
503 dat[0] = new int[100 * vpad];
504 dat[1] = new int[100 * vpad];
505 dat[2] = new int[100 * hpad];
506 dat[3] = new int[100 * hpad];
508 for(int i=0; i<100; i++) {
509 for(int j=0; j<vpad; j++) {
510 dat[0][i + j * 100] = data[hpad + j * w];
511 dat[1][i + (vpad - j - 1) * 100] = data[hpad + (h - j - 1) * w];
513 for(int j=0; j<hpad; j++) {
514 dat[2][j + i * hpad] = data[j + vpad * w];
515 dat[3][hpad - j - 1 + i * hpad] = data[w - j - 1 + vpad * w];
519 border = new Picture[5];
520 border[0] = Platform.createPicture(dat[0], 100, vpad);
521 border[1] = Platform.createPicture(dat[1], 100, vpad);
522 border[2] = Platform.createPicture(dat[2], hpad, 100);
523 border[3] = Platform.createPicture(dat[3], hpad, 100);
524 border[4] = (Picture)pictureCache.get(s);
525 if (border[4] == null) {
526 border[4] = Platform.createPicture(data, w, h);
527 pictureCache.put(s, border[4]);
528 imageToNameMap.put(border[4], s);
530 bordercache.put(s, border);
532 if (sizetoimage) syncSizeToImage();
537 /** returns true if the property has a trap on it */
538 boolean is_trapped(String property) {
542 Object gc = traps.get(property);
543 return (gc != null &&
544 !(gc instanceof org.mozilla.javascript.Undefined) &&
545 gc != org.mozilla.javascript.Scriptable.NOT_FOUND);
549 /** Adds the node's current actual geometry to the Surface's dirty list */
551 dirty(pos(0), pos(1), size(0), size(1));
554 /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
555 public final void dirty(int x, int y, int w, int h) {
556 for(Box cur = this; cur != null; cur = cur.getParent()) {
557 w = min(x + w, cur.pos(0) + cur.size(0)) - max(x, cur.pos(0));
558 h = min(y + h, cur.pos(1) + cur.size(1)) - max(y, cur.pos(1));
559 x = max(x, cur.pos(0));
560 y = max(y, cur.pos(1));
561 if (w <= 0 || h <= 0) return;
563 if (surface != null) surface.dirty(x, y, w, h);
567 * Given an old and new mouse position, this will update <tt>mouseinside</tt> and check
568 * to see if this node requires any Enter, Leave, or Move notifications.
570 * @param forceleave set to true by the box's parent if the mouse is inside an older
571 * sibling, which is covering up this box.
573 void Move(int oldmousex, int oldmousey, int mousex, int mousey) { Move(oldmousex, oldmousey, mousex, mousey, false); }
574 void Move(int oldmousex, int oldmousey, int mousex, int mousey, boolean forceleave) {
576 boolean wasinside = mouseinside;
577 boolean isinside = !invisible && inside(mousex, mousey) && !forceleave;
578 mouseinside = isinside;
580 if (!wasinside && !isinside) return;
582 if (!wasinside && isinside && is_trapped("Enter")) put("Enter", null, this);
583 else if (wasinside && !isinside && is_trapped("Leave")) put("Leave", null, this);
584 else if (wasinside && isinside && (mousex != oldmousex || mousey != oldmousey) && is_trapped("Move")) put("Move", null, this);
586 if (isinside && cursor != null && surface != null) surface.cursor = cursor;
588 // if the mouse has moved into our padding region, it is considered 'outside' all our children
589 if (!(mousex >= pos(0) + pad(0) && mousey >= pos(1) + pad(1) &&
590 mousex < pos(0) + size(0) - pad(0) && mousey < pos(1) + size(1) + pad(1))) forceleave = true;
592 for(Box b = getChild(numChildren() - 1); b != null; b = b.prevSibling()) {
593 b.Move(oldmousex, oldmousey, mousex, mousey, forceleave);
594 if (b.inside(mousex, mousey)) forceleave = true;
598 /** creates a new box from an anonymous template; <tt>ids</tt> is passed through to Template.apply() */
599 Box(Template anonymous, Vec pboxes, Vec ptemplates) {
601 set(dmax, 0, Short.MAX_VALUE);
602 set(dmax, 1, Short.MAX_VALUE);
603 template = anonymous;
604 template.apply(this, pboxes, ptemplates);
609 /** creates a new box from an unresolved templatename and an importlist; use "box" for an untemplatized box */
610 public Box(String templatename, String[] importlist) {
612 set(dmax, 0, Short.MAX_VALUE);
613 set(dmax, 1, Short.MAX_VALUE);
614 this.importlist = importlist;
615 template = "box".equals(templatename) ? null : Template.getTemplate(templatename, importlist);
616 this.templatename = templatename;
617 if (template != null) {
618 template.apply(this, null, null);
619 if (redirect == this && !"self".equals(template.redirect)) redirect = null;
624 // Prerendering Pipeline ///////////////////////////////////////////////////////////////
626 /** Checks if the Box's size has changed, dirties it if necessary, and makes sure childrens' sizes are up to date */
629 if (getParent() == null) {
634 if (pos(0) != oldpos(0) || pos(1) != oldpos(1) || size(0) != oldsize(0) || size(1) != oldsize(1)) {
635 needs_prerender = true;
636 check_geometry_changes();
639 if (!needs_prerender) return;
640 needs_prerender = false;
641 if (numChildren() == 0) return;
643 int sumchildren = sizeChildren();
644 positionChildren(pos(o) + pad(o) + max(0, size(o) - 2 * pad(o) - sumchildren) / 2);
646 for(Box b = getChild(0); b != null; b = b.nextSibling()) {
649 mark_for_prerender();
655 /** if the size or position of a box has changed, dirty() the appropriate regions and possibly send Enter/Leave/SizeChange/PosChange */
656 private void check_geometry_changes() {
658 // FASTPATH: if we haven't moved position (just changed size), and we're not a stretched image:
659 if (oldpos(0) == pos(0) && oldpos(1) == pos(1) && (image == null || tile)) {
661 int bw = border == null ? 0 : border[2].getWidth();
662 int bh = border == null ? 0 : border[0].getHeight();
664 // dirty only the *change* in the area we cover, both on ourselves and on our parent
665 for(Box cur = this; cur != null && (cur == this || cur == this.getParent()); cur = cur.getParent()) {
666 cur.dirty(pos(0) + min(oldsize(0) - bw, size(0) - bw),
668 Math.abs(oldsize(0) - size(0)) + bw,
669 max(oldsize(1), size(1)));
671 pos(1) + min(oldsize(1) - bh, size(1) - bh),
672 max(oldsize(0), size(0)),
673 Math.abs(oldsize(1) - size(1)) + bh);
676 // SLOWPATH: dirty ourselves, as well as our former position on our parent
679 if (getParent() != null) getParent().dirty(oldpos(0), oldpos(1), oldsize(0), oldsize(1));
683 boolean sizechange = false;
684 boolean poschange = false;
685 if ((oldsize(0) != size(0) || oldsize(1) != size(1)) && is_trapped("SizeChange")) sizechange = true;
686 if ((oldpos(0) != pos(0) || oldpos(1) != pos(1)) && is_trapped("PosChange")) poschange = true;
688 set(oldsize, 0, size(0));
689 set(oldsize, 1, size(1));
690 set(oldpos, 0, pos(0));
691 set(oldpos, 1, pos(1));
693 if (sizechange || poschange)
694 if (surface.sizePosChangesSinceLastRender++ > 500) {
695 if (Log.on) Log.log(this, "Warning, more than 500 SizeChange/PosChange traps triggered since last complete render");
697 Trap t = sizechange ? Trap.getTrap(this, "SizeChange") : Trap.getTrap(this, "PosChange");
698 InterpretedFunction f = (InterpretedFunction)t.f;
699 if (Log.on) Log.log(this, "Current trap is at " + f.getSourceName() + ":" + f.getLineNumbers()[0]);
700 } catch (Throwable t) { }
703 if (sizechange) put("SizeChange", null, Boolean.TRUE);
704 if (poschange) put("PosChange", null, Boolean.TRUE);
705 if (sizechange || poschange) {
706 surface.abort = true;
712 /** sets our childrens' sizes */
715 // Set sizes along minor axis, as well as sizes for absolute-positioned children
716 for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
717 if (bt.invisible) continue;
719 bt.set(size, o, max(bt.cmin(o), min(size(o) - bt.abs(o) - pad(o), bt.dmax(o))));
720 bt.set(size, xo, max(bt.cmin(xo), min(size(xo) - bt.abs(xo) - pad(xo), bt.dmax(xo))));
721 } else if (xo == 0 && bt.hshrink || xo == 1 && bt.vshrink) {
722 bt.set(size, xo, bt.cmin(xo));
724 bt.set(size, xo, bound(bt.cmin(xo), size(xo) - 2 * pad(xo), bt.dmax(xo)));
728 // the ideal size of our children, along our own major axis
729 int goal = (o == 0 && hshrink) || (o == 1 && vshrink) ? cmin(o) - 2 * pad(o) : size(o) - 2 * pad(o);
731 // the current sum of the sizes of all children
734 // each box is set to bound(box.cmin, box.flex * factor, box.dmax)
737 // Algorithm: we set the sizes of all boxes to bound(cmin, flex * factor, dmax) for some global value
738 // 'factor'. We figure out what 'factor' should be by starting at zero, and slowly increasing
739 // it. After each pass, 'factor' is set to the smaller of two values: ((goal - total) /
740 // remaining_flex) or the next largest value of factor which will cause some box to exceed its
741 // cmin or dmax (thereby changing remaining_flex).
746 // the sum of the flexes of all boxes which are not pegged at either cmin or dmax
747 int remaining_flex = 0;
749 // this is the next largest value of factor at which some box exceeds its cmin/dmax
750 int nextjoint = Integer.MAX_VALUE;
752 for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
753 if (bt.absolute || bt.invisible) continue;
755 bt.set(size, o, bound(bt.cmin(o), factor * bt.flex, bt.dmax(o)));
758 if (factor * bt.flex < bt.cmin(o) && bt.size(o) == bt.cmin(o)) {
759 nextjoint = min(nextjoint, divide_round_up(bt.cmin(o), bt.flex));
761 } else if (bt.size(o) < bt.dmax(o)) {
762 remaining_flex += bt.flex;
763 nextjoint = min(nextjoint, divide_round_up(bt.dmax(o), bt.flex));
768 if (remaining_flex == 0) {
769 if (nextjoint <= factor) break;
772 factor = min((goal - total + factor * remaining_flex) / remaining_flex, nextjoint);
775 if (goal - total <= remaining_flex) break;
778 // arbitrarily distribute out any leftovers resulting from rounding errors
780 while(goal > total && total != last) {
782 for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
783 int newsize = bound(bt.cmin(o), bt.size(o) + 1, bt.dmax(o));
784 total += newsize - bt.size(o);
785 bt.set(size, o, newsize);
792 /** positions this Box's children; cur is the starting position along this' major axis */
793 void positionChildren(int cur) {
794 for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
795 if (bt.invisible) continue;
797 bt.set(pos, 0, pos(0) + bt.abs(0));
798 bt.set(pos, 1, pos(1) + bt.abs(1));
800 bt.set(pos, xo, pos(xo) + pad(xo) + max(0, ((size(xo) - 2 * pad(xo) - bt.size(xo)) * (bt.align + 1)) / 2));
802 bt.set(abs, 0, bt.pos(0) - pos(0));
803 bt.set(abs, 1, bt.pos(1) - pos(1));
810 // Rendering Pipeline /////////////////////////////////////////////////////////////////////
812 /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
813 void render(int xIn, int yIn, int wIn, int hIn, DoubleBuffer buf) {
814 if (surface.abort || invisible) return;
816 // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
817 int x = max(xIn, getParent() == null ? 0 : pos(0));
818 int y = max(yIn, getParent() == null ? 0 : pos(1));
819 int w = min(xIn + wIn, (getParent() == null ? 0 : pos(0)) + size(0)) - x;
820 int h = min(yIn + hIn, (getParent() == null ? 0 : pos(1)) + size(1)) - y;
821 if (w <= 0 || h <= 0) return;
823 if (border != null) renderBorder(x, y, w, h, buf);
825 if ((color & 0xFF000000) != 0x00000000 || getParent() == null) {
826 int bw = border == null ? 0 : border[2].getWidth();
827 int bh = border == null ? 0 : border[0].getHeight();
828 buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
829 buf.fillRect(max(x, pos(0) + bw),
831 min(x + w, pos(0) + size(0) - bw),
832 min(y + h, pos(1) + size(1) - bh),
833 (color & 0xFF000000) != 0 ? color : SpecialBoxProperty.lightGray);
837 if (tile) renderTiledImage(x, y, w, h, buf);
838 else renderStretchedImage(x, y, w, h, buf);
841 if (text != null && !text.equals("")) renderText(x, y, w, h, buf);
843 // now subtract the pad region from the clip region before proceeding
844 int x2 = max(x, pos(0) + pad(0));
845 int y2 = max(y, pos(1) + pad(1));
846 int w2 = min(x + w, pos(0) + size(0) - pad(0)) - x2;
847 int h2 = min(y + h, pos(1) + size(1) - pad(1)) - y2;
849 for(Box b = getChild(0); b != null; b = b.nextSibling())
850 b.render(x2, y2, w2, h2, buf);
853 private void renderBorder(int x, int y, int w, int h, DoubleBuffer buf) {
854 int bw = border[4].getWidth();
855 int bh = border[4].getHeight();
856 buf.setClip(x, y, w + x, h + y);
858 if ((color & 0xFF000000) != 0xFF000000) {
860 // if the color is null, we have to be very careful about drawing the corners
861 //if (Log.verbose) Log.log(this, "WARNING: (color == null && border != null) on box with border " + imageToNameMap.get(border[4]));
864 buf.drawPicture(border[4],
865 pos(0), pos(1), pos(0) + bw / 2, pos(1) + bh / 2,
866 0, 0, bw / 2, bh / 2);
868 // upper right corner
869 buf.drawPicture(border[4],
870 pos(0) + size(0) - bw / 2, pos(1), pos(0) + size(0), pos(1) + bh / 2,
871 bw - bw / 2, 0, bw, bh / 2);
874 buf.drawPicture(border[4],
875 pos(0), pos(1) + size(1) - bh / 2, pos(0) + bw / 2, pos(1) + size(1),
876 0, bh - bh / 2, bw / 2, bh);
878 // lower right corner
879 buf.drawPicture(border[4],
880 pos(0) + size(0) - bw / 2, pos(1) + size(1) - bh / 2, pos(0) + size(0), pos(1) + size(1),
881 bw - bw / 2, bh - bh / 2, bw, bh);
884 buf.drawPicture(border[4], pos(0), pos(1)); // upper left corner
885 buf.drawPicture(border[4], pos(0) + size(0) - bw, pos(1)); // upper right corner
886 buf.drawPicture(border[4], pos(0), pos(1) + size(1) - bh); // lower left corner
887 buf.drawPicture(border[4], pos(0) + size(0) - bw, pos(1) + size(1) - bh); // lower right corner
891 // top and bottom edges
892 buf.setClip(max(x, pos(0) + bw / 2), y, min(x + w, pos(0) + size(0) - bw / 2), h + y);
893 for(int i = max(x, pos(0) + bw / 2); i + 100 < min(x + w, pos(0) + size(0) - bw / 2); i += 100) {
894 buf.drawPicture(border[0], i, pos(1));
895 buf.drawPicture(border[1], i, pos(1) + size(1) - bh / 2);
897 buf.drawPicture(border[0], min(x + w, pos(0) + size(0) - bw / 2) - 100, pos(1));
898 buf.drawPicture(border[1], min(x + w, pos(0) + size(0) - bw / 2) - 100, pos(1) + size(1) - bh / 2);
900 // left and right edges
901 buf.setClip(x, max(y, pos(1) + bh / 2), w + x, min(y + h, pos(1) + size(1) - bh / 2));
902 for(int i = max(y, pos(1) + bh / 2); i + 100 < min(y + h, pos(1) + size(1) - bh / 2); i += 100) {
903 buf.drawPicture(border[2], pos(0), i);
904 buf.drawPicture(border[3], pos(0) + size(0) - bw / 2, i);
906 buf.drawPicture(border[2], pos(0), min(y + h, pos(1) + size(1) - bh / 2) - 100);
907 buf.drawPicture(border[3], pos(0) + size(0) - bw / 2, min(y + h, pos(1) + size(1) - bh / 2) - 100);
909 buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
912 void renderStretchedImage(int x, int y, int w, int h, DoubleBuffer buf) {
913 buf.setClip(x, y, w + x, h + y);
914 int bw = border == null ? 0 : border[4].getHeight();
915 int bh = border == null ? 0 : border[4].getWidth();
916 buf.drawPicture(image,
919 pos(0) + size(0) - bw / 2,
920 pos(1) + size(1) - bh / 2,
921 0, 0, image.getWidth(), image.getHeight());
922 buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
925 void renderTiledImage(int x, int y, int w, int h, DoubleBuffer buf) {
926 int iw = image.getWidth();
927 int ih = image.getHeight();
928 int bh = border == null ? 0 : border[4].getWidth();
929 int bw = border == null ? 0 : border[4].getHeight();
931 for(int i=(x - pos(0) - bw)/iw; i <= (x + w - pos(0) - bw)/iw; i++) {
932 for(int j=(y - pos(1) - bh)/ih; j<= (y + h - pos(1) - bh)/ih; j++) {
934 int dx1 = max(i * iw + pos(0), x);
935 int dy1 = max(j * ih + pos(1), y);
936 int dx2 = min((i+1) * iw + pos(0), x + w);
937 int dy2 = min((j+1) * ih + pos(1), y + h);
939 int sx1 = dx1 - (i*iw) - pos(0);
940 int sy1 = dy1 - (j*ih) - pos(1);
941 int sx2 = dx2 - (i*iw) - pos(0);
942 int sy2 = dy2 - (j*ih) - pos(1);
944 if (dx2 - dx1 > 0 && dy2 - dy1 > 0 && sx2 - sx1 > 0 && sy2 - sy1 > 0)
945 buf.drawPicture(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
951 void renderText(int x, int y, int w, int h, DoubleBuffer buf) {
953 if ((textcolor & 0xFF000000) == 0x00000000) return;
954 buf.setClip(x, y, w + x, h + y);
956 XWF xwf = XWF.getXWF(font);
958 xwf.drawString(buf, text,
960 pos(1) + pad(1) + xwf.getMaxAscent() - 1,
963 buf.drawString(font, text,
965 pos(1) + pad(1) + Platform.getMaxAscent(font) - 1,
969 buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
971 int i=0; while(i<font.length() && !Character.isDigit(font.charAt(i))) i++;
973 if (font.lastIndexOf('d') > i) {
974 for(int j = pos(0) + pad(0); j < pos(0) + pad(0) + textdim(0); j += 2)
975 buf.fillRect(j, pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font) : xwf.getMaxAscent()) + 2,
976 j + 1, pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font) : xwf.getMaxAscent()) + 2 + 1,
979 } else if (font.lastIndexOf('u') > i) {
980 buf.fillRect(pos(0) + pad(0),
981 pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font) : xwf.getMaxAscent()) + 2,
982 pos(0) + pad(0) + textdim(0),
983 pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font) : xwf.getMaxAscent()) + 2 + 1,
990 // Methods to implement org.mozilla.javascript.Scriptable //////////////////////////////////////
992 /** Returns the i_th child */
993 public Object get(int i, Scriptable start) {
994 if (redirect == null) return null;
995 if (redirect != this) return redirect.get(i, start);
996 return i >= numChildren() ? null : getChild(i);
1000 * Inserts value as child i; calls remove() if necessary.
1001 * This method handles "reinserting" one of your children properly.
1002 * INVARIANT: after completion, getChild(min(i, numChildren())) == newnode
1003 * WARNING: O(n) runtime, unless i == numChildren()
1005 public void put(int i, Scriptable start, Object value) {
1006 if (value == null) {
1007 if (i >= 0 && i < numChildren()) getChild(i).remove();
1010 if (value instanceof RootProxy) {
1011 if (Log.on) Log.log(this, "attempt to reparent a box via its proxy object at " +
1012 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
1014 } else if (!(value instanceof Box)) {
1015 if (Log.on) Log.log(this, "attempt to set a numerical property on a box to anything other than a box at " +
1016 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
1019 Box newnode = (Box)value;
1020 if (redirect == null) {
1021 if (Log.on) Log.log(this, "attempt to add a child to a node with a null redirect at " +
1022 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
1024 } else if (redirect != this) redirect.put(i, null, newnode);
1026 if (numKids > 15 && children == null) convert_to_array();
1027 if (newnode.parent != null) newnode.remove();
1028 newnode.parent = this;
1030 if (children == null) {
1031 if (firstKid == null) {
1033 newnode.prevSibling = newnode;
1034 newnode.nextSibling = newnode;
1035 } else if (i >= numKids) {
1036 newnode.prevSibling = firstKid.prevSibling;
1037 newnode.nextSibling = firstKid;
1038 firstKid.prevSibling.nextSibling = newnode;
1039 firstKid.prevSibling = newnode;
1042 for(int j=0; j<i; j++) cur = cur.nextSibling;
1043 newnode.prevSibling = cur.prevSibling;
1044 newnode.nextSibling = cur;
1045 cur.prevSibling.nextSibling = newnode;
1046 cur.prevSibling = newnode;
1047 if (i == 0) firstKid = newnode;
1052 if (i >= children.size()) {
1053 newnode.indexInParent = children.size();
1054 children.addElement(newnode);
1056 children.insertElementAt(newnode, i);
1057 for(int j=i; j<children.size(); j++)
1058 getChild(j).indexInParent = j;
1061 newnode.setSurface(surface);
1063 // need both of these in case child was already uncalc'ed
1064 newnode.mark_for_prerender();
1065 mark_for_prerender();
1068 sync_cmin_to_children();
1071 // note that JavaScript box[0] will invoke put(int i), not put(String s)
1072 put("0", null, newnode);
1075 public Object get(String name, Scriptable start) { return get(name, start, false); }
1076 public Object get(String name, Scriptable start, boolean ignoretraps) {
1078 if (name == null || name.equals("")) return null;
1080 // hack since Rhino needs to be able to grab these functions to create new objects
1081 if (name.equals("Object")) return JSObject.defaultObjects.get("Object", null);
1082 if (name.equals("Array")) return JSObject.defaultObjects.get("Array", null);
1083 if (name.equals("Function")) return JSObject.defaultObjects.get("Function", null);
1084 if (name.equals("TypeError")) return JSObject.defaultObjects.get("TypeError", null);
1085 if (name.equals("ConversionError")) return JSObject.defaultObjects.get("ConversionError", null);
1087 // See if we're reading back the function value of a trap
1088 if (name.charAt(0) == '_') {
1089 if (name.charAt(1) == '_') name = name.substring(2);
1090 else name = name.substring(1);
1091 Trap t = Trap.getTrap(this, name);
1092 return t == null ? null : t.f;
1095 // See if we're triggering a trap
1096 Trap t = traps == null || ignoretraps ? null : (Trap)traps.get(name);
1097 if (t != null && t.isreadtrap) return t.perform(emptyobj);
1099 // Check for a special handler
1100 SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
1101 if (gph != null) return gph.get(this);
1103 return super.get(name, start);
1106 /** indicate that we don't want JSObject trying to handle these */
1107 public boolean has(String name, Scriptable start) {
1108 if (name.equals("")) return false;
1109 if (traps != null && traps.get(name) != null) return true;
1110 if (name.charAt(0) == '_') return true;
1111 if (SpecialBoxProperty.specialBoxProperties.get(name) != null) return true;
1112 if (name.equals("Function") || name.equals("Array") || name.equals("Object") ||
1113 name.equals("TypeError") || name.equals("ConversionError")) return true;
1114 return super.has(name, start);
1117 public void put(String name, Scriptable start, Object value) { put(name, start, value, false, null); }
1118 public void put(String name, Scriptable start, Object value, boolean ignoretraps) { put(name, start, value, ignoretraps, null); }
1122 * @param ignoretraps if set, no traps will be triggered (set when 'cascade' reaches the bottom of the trap stack)
1123 * @param rp if this put is being performed via a root proxy, rp is the root proxy.
1125 public void put(String name, Scriptable start, Object value, boolean ignoretraps, RootProxy rp) {
1126 if (name == null) return;
1127 if (name.startsWith("xwt_")) {
1128 if (Log.on) Log.log(this, "attempt to set reserved property " + name + " at " +
1129 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
1133 if (!ignoretraps && traps != null) {
1134 Trap t = (Trap)traps.get(name);
1136 Object[] arg = (Object[])singleObjects.remove(false);
1137 if (arg == null) arg = new Object[] { value };
1138 else arg[0] = value;
1141 singleObjects.append(arg);
1146 // don't want to really cascade down to the box on this one
1147 if (name.equals("0")) return;
1149 SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
1151 gph.put(name, this, value);
1155 if (name.charAt(0) == '_') {
1156 if (value != null && !(value instanceof Function)) {
1157 if (Log.on) Log.log(this, "attempt to put a non-function value to " + name + " at " +
1158 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
1159 } else if (name.charAt(1) == '_') {
1160 name = name.substring(2).intern();
1161 Trap t = Trap.getTrap(this, name);
1162 if (t != null) t.delete();
1163 if (value != null) Trap.addTrap(this, name, ((Function)value), true, rp);
1165 name = name.substring(1).intern();
1166 Trap t = Trap.getTrap(this, name);
1167 if (t != null) t.delete();
1168 if (value != null) Trap.addTrap(this, name, ((Function)value), false, rp);
1174 // traps always cascade to the global property, not the local one
1175 putGlobally(name, start, value);
1177 super.put(name, start, value);
1180 // a bit of a hack, since titlebar is the only 'special' property stored in JSObject
1181 if (getParent() == null && surface != null) {
1182 if (name.equals("titlebar")) surface.setTitleBarText(value.toString());
1183 if (name.equals("icon")) {
1184 Picture pic = Box.getPicture(value.toString());
1185 if (pic != null) surface.setIcon(pic);
1186 else if (Log.on) Log.log(this, "unable to load icon " + value);
1191 /** the <tt>delete</tt> keyword is not valid in XWT scripts */
1192 public void delete(int i) { }
1195 // Tree Manipulation /////////////////////////////////////////////////////////////////////
1197 /** The parent of this node */
1198 private Box parent = null;
1200 // Variables used in Vector mode */
1201 /** INVARIANT: if (parent != null) parent.children.elementAt(indexInParent) == this */
1202 private int indexInParent;
1203 private Vec children = null;
1205 // Variables used in linked-list mode
1206 private int numKids = 0;
1207 private Box nextSibling = null;
1208 private Box prevSibling = null;
1209 private Box firstKid = null;
1211 // when we get more than 15 children, we switch to array-mode
1212 private void convert_to_array() {
1213 children = new Vec(numKids);
1216 children.addElement(cur);
1217 cur.indexInParent = children.size() - 1;
1218 cur = cur.nextSibling;
1219 } while (cur != firstKid);
1222 /** remove this node from its parent; INVARIANT: whenever the parent of a node is changed, remove() gets called. */
1223 public void remove() {
1224 if (parent == null) {
1225 if (surface != null) surface.dispose();
1228 Box oldparent = getParent();
1229 if (oldparent == null) return;
1230 mark_for_prerender();
1232 mouseinside = false;
1234 if (parent.children != null) {
1235 parent.children.removeElementAt(indexInParent);
1236 for(int j=indexInParent; j<parent.children.size(); j++)
1237 (parent.getChild(j)).indexInParent = j;
1240 if (parent.firstKid == this) {
1241 if (nextSibling == this) parent.firstKid = null;
1242 else parent.firstKid = nextSibling;
1245 prevSibling.nextSibling = nextSibling;
1246 nextSibling.prevSibling = prevSibling;
1252 if (oldparent != null) oldparent.sync_cmin_to_children();
1255 // note that JavaScript box[0] will invoke put(int i), not put(String s)
1256 if (oldparent != null) oldparent.put("0", null, this);
1259 /** returns our next sibling (parent[ourindex + 1]) */
1260 public final Box nextSibling() {
1261 if (parent == null) return null;
1262 if (parent.children == null) {
1263 if (nextSibling == parent.firstKid) return null;
1266 if (indexInParent >= parent.children.size() - 1) return null;
1267 return (Box)parent.children.elementAt(indexInParent + 1);
1271 /** returns our next sibling (parent[ourindex + 1]) */
1272 public final Box prevSibling() {
1273 if (parent == null) return null;
1274 if (parent.children == null) {
1275 if (this == parent.firstKid) return null;
1278 if (indexInParent == 0) return null;
1279 return (Box)parent.children.elementAt(indexInParent - 1);
1283 /** Returns the parent of this node */
1284 public Box getParent() { return parent; }
1286 /** Returns ith child */
1287 public Box getChild(int i) {
1288 if (children == null) {
1289 if (firstKid == null) return null;
1290 if (i >= numKids) return null;
1291 if (i == numKids - 1) return firstKid.prevSibling;
1293 for(int j=0; j<i; j++) cur = cur.nextSibling;
1296 if (i >= children.size() || i < 0) return null;
1297 return (Box)children.elementAt(i);
1301 /** Returns the number of children */
1302 public int numChildren() {
1303 if (children == null) {
1304 if (firstKid == null) return 0;
1306 for(Box cur = firstKid.nextSibling; cur != firstKid; i++) cur = cur.nextSibling;
1309 return children.size();
1313 /** Returns our index in our parent */
1314 public int getIndexInParent() {
1315 if (parent == null) return 0;
1316 if (parent.children == null) {
1318 for(Box cur = this; cur != parent.firstKid; i++) cur = cur.prevSibling;
1321 return indexInParent;
1325 /** returns the root of the surface that this box belongs to */
1326 public final Box getRoot() {
1327 if (getParent() == null && surface != null) return this;
1328 if (getParent() == null) return null;
1329 return getParent().getRoot();
1333 // Root Proxy ///////////////////////////////////////////////////////////////////////////////
1335 RootProxy myproxy = null;
1336 public Scriptable getRootProxy() {
1337 if (myproxy == null) myproxy = new RootProxy(this);
1341 private static class RootProxy implements Scriptable {
1344 RootProxy(Box b) { this.box = b; }
1346 public void delete(String name) { box.delete(name); }
1347 public Scriptable getParentScope() { return box.getParentScope(); }
1348 public void setParentScope(Scriptable p) { box.setParentScope(p); }
1349 public boolean hasInstance(Scriptable value) { return box.hasInstance(value); }
1350 public Scriptable getPrototype() { return box.getPrototype(); }
1351 public void setPrototype(Scriptable p) { box.setPrototype(p); }
1352 public void delete(int i) { box.delete(i); }
1353 public String getClassName() { return box.getClassName(); }
1354 public Object getDefaultValue(Class hint) { return box.getDefaultValue(hint); }
1356 public void put(int i, Scriptable start, Object value) { if (value != null) box.put(i, start, value); }
1357 public Object get(String name, Scriptable start) { return box.get(name, start); }
1358 public Object get(int i, Scriptable start) { return null; }
1360 public void put(String name, Scriptable start, Object value) { box.put(name, start, value, false, this); }
1361 public boolean has(String name, Scriptable start) { return box.has(name, start); }
1362 public boolean has(int i, Scriptable start) { return box.has(i, start); }
1363 public Object[] getIds() { return box.getIds(); }
1368 // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
1370 /** helper, included in this class so it can be inlined */
1371 static final int min(int a, int b) {
1376 /** helper, included in this class so it can be inlined */
1377 static final double min(double a, double b) {
1382 /** helper, included in this class so it can be inlined */
1383 static final int max(int a, int b) {
1388 /** helper, included in this class so it can be inlined */
1389 static final int min(int a, int b, int c) {
1390 if (a<=b && a<=c) return a;
1391 else if (b<=c && b<=a) return b;
1395 /** helper, included in this class so it can be inlined */
1396 static final int max(int a, int b, int c) {
1397 if (a>=b && a>=c) return a;
1398 else if (b>=c && b>=a) return b;
1402 /** helper, included in this class so it can be inlined */
1403 static final int bound(int a, int b, int c) {
1404 if (c < b) return c;
1405 if (a > b) return a;
1409 /** returns numerator/denominator, but rounds <i>up</i> instead of down */
1410 static final int divide_round_up(int numerator, int denominator) {
1411 int ret = numerator / denominator;
1412 if (ret * denominator < numerator) return ret + 1;
1416 /** Simple helper function to determine if the point x,y falls within this node's actual current geometry */
1417 boolean inside(int x, int y) {
1418 if (invisible) return false;
1419 return (x >= pos(0) && y >= pos(1) && x < pos(0) + size(0) && y < pos(1) + size(1));
1422 /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface
1424 * IMPORTANT: this method gets called from the event-queueing thread, since we need to determine which box is
1425 * underneath the mouse as early as possible. Because of this, we have to do some extra checks, as the
1426 * Box tree may be in flux.
1428 Box whoIs(int x, int y) {
1429 if (invisible) return null;
1430 if (!inside(x,y)) return getParent() == null ? this : null;
1432 // We do this because whoIs is unsynchronized (for
1433 // speed), yet is sometimes called while the structure of the
1435 for(int i=numChildren() - 1; i>=0; i--) {
1437 Box child = getChild(i);
1438 if (child == null) continue;
1440 Box bt = child.whoIs(x,y);
1441 if (bt != null) return bt;