2002/04/28 06:14:39
[org.ibex.core.git] / src / org / xwt / Box.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.io.*;
5 import java.net.*;
6 import java.util.*;
7 import org.xwt.util.*;
8 import org.mozilla.javascript.*;
9
10 /**
11  *  <p>
12  *  Encapsulates the data for a single XWT box as well as all layout
13  *  rendering logic.
14  *  </p>
15  *
16  *  <p>
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.
20  *  </p>
21  *
22  *  <p>The rendering process consists of two phases:</p>
23  *
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.
31  *
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.
38  *  </ol>
39  *
40  *  <p>
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.
49  *  </p>
50  *
51  *  <p>Why are these done as seperate passes over the box tree?</p>
52  * 
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.
57  *
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.
65  *  </ol>
66  *
67  *  <p>
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
76  *  immediately.
77  *  </p>
78  *
79  *  <p>
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.
83  * </p>
84  */
85 public final class Box extends JSObject {
86
87
88     // Static Data //////////////////////////////////////////////////////////////
89
90     /** a pool of one-element Object[]'s */
91     private static Queue singleObjects = new Queue(100);
92
93     /** caches images, keyed on resource name or url */
94     public static Hash pictureCache = new Hash();
95
96     /** cache of border objects */
97     static Hash bordercache = new Hash();
98
99     /** stores image names, keyed on image object */
100     static Hash imageToNameMap = new Hash();
101
102     /** the empty object, used for get-traps */
103     private static Object[] emptyobj = new Object[] { };
104
105
106     // Instance Data: Templates ////////////////////////////////////////////////////////
107
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;
110
111     /** the importlist which was used to resolve <tt>templatename</tt>, or null if this template was specified anonymously */
112     String[] importlist = Template.defaultImportList;
113
114     /** the template instance that resulted from resolving <tt>templatename</tt> using <tt>importlist</tt>, or the anonymous template applied */
115     Template template = null;
116
117
118     // Instance Data: Geometry ////////////////////////////////////////////////////////
119
120     /** The number of elements in the geom array */
121     public static final int NUMINTS = 10;
122
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; }
128
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; }
134     
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; }
140
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; }
146
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; }
152
153     /** The actual size of this box; set by the parent. */
154     public static final int size = 5;     
155     short _size_0 = 0;
156     short _size_1 = 0;
157     public final short size(int axis) { return axis == 0 ? _size_0 : _size_1; }
158
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; }
164
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; }
170
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; }
176
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; }
182
183
184     // Instance Data /////////////////////////////////////////////////////////////////
185
186     /** This box's mouseinside property, as defined in the reference */
187     boolean mouseinside = false;
188
189     /** If redirect is enabled, this holds the Box redirected to */
190     Box redirect = this;
191
192     /** the Box's font -- you must call textupdate() after changing this */
193     String font = Platform.getDefaultFont();
194
195     /** The surface for us to render on; null if none; INVARIANT: surface == getParent().surface */
196     Surface surface = null;
197
198     /** Our alignment: top/left == -1, center == 0, bottom/right == +1 */
199     byte align = 0;
200
201     /** Our background image; to set this, use setImage() */
202     public Picture image;
203
204     /** The flex for this box */
205     int flex = 1;
206
207     /** The orientation, horizontal == 0, vertical == 1 */
208     byte o = 0;
209
210     /** The opposite of the orientation */
211     byte xo = 1;
212
213     /** The id of this Box */
214     public String id = "";
215
216     /** The text of this Box -- you must call textupdate() after changing this */
217     String text = "";
218
219     /** The color of the text in this Box in 00RRGGBB form -- default is black */
220     int textcolor = 0xFF000000;
221
222     /** The background color of this box in AARRGGBB form -- default is clear; alpha is all-or-nothing */
223     int color = 0x00000000;
224
225     /** Holds four "strip images" -- 0=top, 1=bottom, 2=left, 3=right, 4=all */
226     Picture[] border = null;
227         
228     /** true iff the box's background image should be tiled */
229     boolean tile = false;
230
231     /** True iff the Box is invisible */
232     public boolean invisible = false;
233
234     /** If true, the Box will force its own size to the natural size of its background image */
235     boolean sizetoimage = false;
236
237     /** If true, the box will shrink to the smallest vertical size possible */
238     boolean vshrink = false;
239
240     /** If true, the box will shrink to the smallest horizontal size possible */
241     boolean hshrink = false;
242
243     /** If true, the box will be positioned absolutely */
244     boolean absolute = false;
245
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;
249
250     /** The cursor for this Box -- only meaningful on the root Box */
251     public String cursor = null;
252
253     /** Any traps placed on this Box */
254     public Hash traps = null;
255
256
257     // Instance Data: IndexOf  ////////////////////////////////////////////////////////////
258
259     /** The indexof() Function; created lazily */
260     public Function indexof = null;
261     public Function indexof() {
262         if (indexof == null) indexof = new IndexOf();
263         return indexof;
264     }
265
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);
276             }
277             return new Integer(b.getIndexInParent());
278         }
279     }
280
281
282     // Methods which enforce/preserve invariants ////////////////////////////////////////////
283
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) {
287
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));
291
292         switch(which) {
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;
303         default: return;
304         }
305
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));
309
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)));
314
315         // keep cmin in line with dmin/dmax/textdim
316         if (which == dmax || which == dmin || which == textdim || which == pad || which == cmin)
317             set(cmin, axis,
318                 max(
319                     min(cmin(axis), dmax(axis)),
320                     dmin(axis),
321                     min(dmax(axis), textdim(axis) + 2 * pad(axis))
322                     )
323                 );
324         
325         // if the pad changes, update cmin
326         if (which == pad) sync_cmin_to_children();
327
328         // if the cmin changes, we need to be re-prerendered
329         if (which == cmin) mark_for_prerender(); 
330
331         // if the absolute position of a box changes, its parent needs to be re-prerendered (to update the child's position)
332         if (which == abs && getParent() != null) getParent().mark_for_prerender();
333
334         // if our cmin changes, then our parent's needs to be recalculated
335         if (getParent() != null && which == cmin) {
336             mark_for_prerender();
337             getParent().sync_cmin_to_children();
338         }
339
340     }
341
342     /** Marks this node and all its ancestors so that they will be prerender()ed */
343     public final void mark_for_prerender() {
344         if (needs_prerender) return;
345         needs_prerender = true;
346         if (getParent() != null) getParent().mark_for_prerender();
347     }
348
349     /** Ensures that cmin is in sync with the cmin's of our children. This should be called whenever a child is added or
350      *  removed, as well as when our pad is changed. */
351     final void sync_cmin_to_children() {
352         short co = (short)(2 * pad(o));
353         short cxo = (short)(2 * pad(xo));
354         
355         for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
356             if (bt.invisible || bt.absolute) continue;
357             co += bt.cmin(o);
358             cxo = (short)max(bt.cmin(xo) + 2 * pad(xo), cxo);
359         }
360         
361         set(cmin, o, co);
362         set(cmin, xo, cxo);
363     }
364
365     /** must be called after changes to <tt>image</tt> or <tt>border</tt> if sizetoimage is true */
366     public void syncSizeToImage() {
367         set(dmax, 0, (image == null ? 0 : image.getWidth()) + (border == null ? 0 : border[2].getWidth()) * 2);
368         set(dmax, 1, (image == null ? 0 : image.getHeight()) + (border == null ? 0 : border[0].getHeight()) * 2);
369         set(dmin, 0, (image == null ? 0 : image.getWidth()) + (border == null ? 0 : border[2].getWidth()) * 2);
370         set(dmin, 1, (image == null ? 0 : image.getHeight()) + (border == null ? 0 : border[0].getHeight()) * 2);
371     }
372
373     /** This must be called when font or text is changed */
374     void textupdate() {
375         if (text.equals("")) {
376             set(textdim, 0, 0);
377             set(textdim, 1, 0);
378         } else {
379             XWF xwf = XWF.getXWF(font);
380             if (xwf == null) {
381                 set(textdim, 0, Platform.stringWidth(font, text));
382                 set(textdim, 1, (Platform.getMaxAscent(font) + Platform.getMaxDescent(font)));
383             } else {
384                 set(textdim, 0, xwf.stringWidth(text));
385                 set(textdim, 1, (xwf.getMaxAscent() + xwf.getMaxDescent()));
386             }
387         }
388     }
389
390
391     // Instance Methods /////////////////////////////////////////////////////////////////////
392
393     /** Changes the Surface that this Box draws on. */    
394     protected void setSurface(Surface newSurface) {
395         if (surface == newSurface) return;
396         mouseinside = false;
397         if ((is_trapped("KeyPressed") || is_trapped("KeyReleased")) && surface != null)
398             surface.keywatchers.removeElement(this);
399         surface = newSurface;
400         if ((is_trapped("KeyPressed") || is_trapped("KeyReleased")) && surface != null)
401             surface.keywatchers.addElement(this);
402         for(Box i = getChild(0); i != null; i = i.nextSibling()) i.setSurface(surface);
403         if (numChildren() == 0) mark_for_prerender();
404     }
405
406     /** loads the image described by string str, possibly blocking for a network load */
407     private static ImageDecoder getImage(String str) {
408         ImageDecoder ret = null;
409         boolean ispng = false;
410
411         if (str.indexOf(':') == -1) {
412             String s = str;
413             byte[] b = Resources.getResource(Resources.resolve(s + ".png", null));
414             if (b == null) return null;
415             return PNG.decode(new ByteArrayInputStream(b), str);
416             
417         } else {
418             Thread thread = Thread.currentThread();
419             if (!(thread instanceof ThreadMessage)) {
420                 if (Log.on) Log.log(Box.class, "HTTP images can not be loaded from the foreground thread");
421                 return null;
422             }
423             ThreadMessage mythread = (ThreadMessage)thread;
424             mythread.setPriority(Thread.MIN_PRIORITY);
425             mythread.done.release();
426             try {
427                 if (str.endsWith(".png")) ret = PNG.decode(Platform.urlToInputStream(new URL(str)), str);
428                 else ret = GIF.decode(Platform.urlToInputStream(new URL(str)), str);
429                 return ret;
430
431             } catch (IOException e) {
432                 if (Log.on) Log.log(Box.class, "error while trying to load an image from " + str);
433                 if (Log.on) Log.log(Box.class, e);
434                 return null;
435
436             } finally {
437                 MessageQueue.add(mythread);
438                 mythread.setPriority(Thread.NORM_PRIORITY);
439                 mythread.go.block();
440             }
441         }
442     }
443
444     /** gets an Image using getImage(), adds it to the cache, and creates a Picture from it */
445     public static Picture getPicture(String os) {
446         Picture ret = null;
447         ret = (Picture)pictureCache.get(os);
448         if (ret != null) return ret;
449         ImageDecoder id = getImage(os);
450         if (id == null) return null;
451         ret = Platform.createPicture(id);
452         pictureCache.put(os, ret);
453         imageToNameMap.put(ret, os);
454         return ret;
455     }
456
457     /** Sets the image; argument should be a fully qualified s name or an URL */
458     void setImage(String s) {
459         if ((s == null && image == null) || (s != null && image != null && s.equals(imageToNameMap.get(image)))) return;
460         if (s == null || s.equals("")) {
461             image = null;
462             if (sizetoimage) syncSizeToImage();
463             dirty();
464         } else {
465             image = getPicture(s);
466             if (image == null) {
467                 if (Log.on) Log.log(Box.class, "unable to load image " + s + " at " +
468                                     Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
469                 return;
470             }
471             if (sizetoimage) syncSizeToImage();
472             dirty();
473         }
474     }
475     
476     /** Sets the border; argument should be a fully qualified resource name or an URL */
477     void setBorder(String s) {
478         if ((s == null && border == null) || (s != null && border != null && s.equals(imageToNameMap.get(border)))) return;
479         if (s == null || s.equals("")) {
480             border = null;
481             if (sizetoimage) syncSizeToImage();
482             dirty();
483
484         } else {
485             border = (Picture[])bordercache.get(s);
486             if (border == null) {
487                 ImageDecoder id = getImage(s);
488                 if (id == null) {
489                     if (Log.on) Log.log(this, "unable to load border image " + s + " at " +
490                                     Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
491                     return;
492                 }
493                 int[] data = id.getData();
494                 int w = id.getWidth();
495                 int h = id.getHeight();
496                 int hpad = w / 2;
497                 int vpad = h / 2;
498
499                 int[][] dat = new int[4][];
500                 dat[0] = new int[100 * vpad];
501                 dat[1] = new int[100 * vpad];
502                 dat[2] = new int[100 * hpad];
503                 dat[3] = new int[100 * hpad];
504
505                 for(int i=0; i<100; i++) {
506                     for(int j=0; j<vpad; j++) {
507                         dat[0][i + j * 100] = data[hpad + j * w];
508                         dat[1][i + (vpad - j - 1) * 100] = data[hpad + (h - j - 1) * w];
509                     }
510                     for(int j=0; j<hpad; j++) {
511                         dat[2][j + i * hpad] = data[j + vpad * w];
512                         dat[3][hpad - j - 1 + i * hpad] = data[w - j - 1 + vpad * w];
513                     }
514                 }
515
516                 border = new Picture[5];
517                 border[0] = Platform.createPicture(dat[0], 100, vpad);
518                 border[1] = Platform.createPicture(dat[1], 100, vpad);
519                 border[2] = Platform.createPicture(dat[2], hpad, 100);
520                 border[3] = Platform.createPicture(dat[3], hpad, 100);
521                 border[4] = (Picture)pictureCache.get(s);
522                 if (border[4] == null) {
523                     border[4] = Platform.createPicture(data, w, h);
524                     pictureCache.put(s, border[4]);
525                     imageToNameMap.put(border[4], s);
526                 }
527                 bordercache.put(s, border);
528             }
529             if (sizetoimage) syncSizeToImage();
530             dirty();
531         }
532     }
533
534     /** returns true if the property has a trap on it */
535     boolean is_trapped(String property) {
536         if (traps == null) {
537             return false;
538         } else {
539             Object gc = traps.get(property);
540             return (gc != null &&
541                     !(gc instanceof org.mozilla.javascript.Undefined) &&
542                     gc != org.mozilla.javascript.Scriptable.NOT_FOUND);
543         }
544     }
545     
546     /** Adds the node's current actual geometry to the Surface's dirty list */
547     void dirty() {
548         dirty(pos(0), pos(1), size(0), size(1));
549     }
550
551     /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
552     final void dirty(int x, int y, int w, int h) {
553         for(Box cur = this; cur != null; cur = cur.getParent()) {
554             w = min(x + w, cur.pos(0) + cur.size(0)) - max(x, cur.pos(0));
555             h = min(y + h, cur.pos(1) + cur.size(1)) - max(y, cur.pos(1));
556             x = max(x, cur.pos(0));
557             y = max(y, cur.pos(1));
558             if (w <= 0 || h <= 0) return;
559         }
560         if (surface != null) surface.dirty(x, y, w, h);
561     }
562
563     /**
564      *  Given an old and new mouse position, this will update <tt>mouseinside</tt> and check
565      *  to see if this node requires any Enter, Leave, or Move notifications.
566      *
567      *  @param forceleave set to true by the box's parent if the mouse is inside an older
568      *                    sibling, which is covering up this box.
569      */
570     void Move(int oldmousex, int oldmousey, int mousex, int mousey) { Move(oldmousex, oldmousey, mousex, mousey, false); }
571     void Move(int oldmousex, int oldmousey, int mousex, int mousey, boolean forceleave) {
572
573         boolean wasinside = mouseinside;
574         boolean isinside = !invisible && inside(mousex, mousey) && !forceleave;
575         mouseinside = isinside;
576
577         if (!wasinside && !isinside) return;
578         
579         if (!wasinside && isinside && is_trapped("Enter")) put("Enter", null, this);
580         else if (wasinside && !isinside && is_trapped("Leave")) put("Leave", null, this);
581         else if (wasinside && isinside && (mousex != oldmousex || mousey != oldmousey) && is_trapped("Move")) put("Move", null, this);
582
583         if (isinside && cursor != null && surface != null) surface.cursor = cursor;
584
585         // if the mouse has moved into our padding region, it is considered 'outside' all our children
586         if (!(mousex >= pos(0) + pad(0) && mousey >= pos(1) + pad(1) &&
587               mousex < pos(0) + size(0) - pad(0) && mousey < pos(1) + size(1) + pad(1))) forceleave = true;
588
589         for(Box b = getChild(numChildren() - 1); b != null; b = b.prevSibling()) {
590             b.Move(oldmousex, oldmousey, mousex, mousey, forceleave);
591             if (b.inside(mousex, mousey)) forceleave = true;
592         }
593     }
594
595     /** creates a new box from an anonymous template; <tt>ids</tt> is passed through to Template.apply() */
596     Box(Template anonymous, Vec pboxes, Vec ptemplates) {
597         super(true);
598         set(dmax, 0, Short.MAX_VALUE);
599         set(dmax, 1, Short.MAX_VALUE);
600         template = anonymous;
601         template.apply(this, pboxes, ptemplates);
602         templatename = null;
603         importlist = null;
604     }
605
606     /** creates a new box from an unresolved templatename and an importlist; use "box" for an untemplatized box */
607     public Box(String templatename, String[] importlist) {
608         super(true);
609         set(dmax, 0, Short.MAX_VALUE);
610         set(dmax, 1, Short.MAX_VALUE);
611         this.importlist = importlist;
612         template = "box".equals(templatename) ? null : Template.getTemplate(templatename, importlist);
613         this.templatename = templatename;
614         if (template != null) {
615             template.apply(this, null, null);
616             if (redirect == this && !"self".equals(template.redirect)) redirect = null;
617         }
618     }
619     
620
621     // Prerendering Pipeline ///////////////////////////////////////////////////////////////
622
623     /** Checks if the Box's size has changed, dirties it if necessary, and makes sure childrens' sizes are up to date */
624     void prerender() {
625
626         if (getParent() == null) {
627             set(pos, 0, 0);
628             set(pos, 1, 0);
629         }
630
631         if (pos(0) != oldpos(0) || pos(1) != oldpos(1) || size(0) != oldsize(0) || size(1) != oldsize(1)) {
632             needs_prerender = true;
633             check_geometry_changes();
634         }
635
636         if (!needs_prerender) return; 
637         needs_prerender = false;
638         if (numChildren() == 0) return;
639
640         int sumchildren = sizeChildren();
641         positionChildren(pos(o) + pad(o) + max(0, size(o) - 2 * pad(o) - sumchildren) / 2);
642
643         for(Box b = getChild(0); b != null; b = b.nextSibling()) {
644             b.prerender();
645             if (surface.abort) {
646                 mark_for_prerender();
647                 return;
648             }
649         }
650     }
651
652     /** if the size or position of a box has changed, dirty() the appropriate regions and possibly send Enter/Leave/SizeChange/PosChange */
653     private void check_geometry_changes() {
654
655         // FASTPATH: if we haven't moved position (just changed size), and we're not a stretched image:
656         if (oldpos(0) == pos(0) && oldpos(1) == pos(1) && (image == null || tile)) {
657             
658             int bw = border == null ? 0 : border[2].getWidth();
659             int bh = border == null ? 0 : border[0].getHeight();
660             
661             // dirty only the *change* in the area we cover, both on ourselves and on our parent
662             for(Box cur = this; cur != null && (cur == this || cur == this.getParent()); cur = cur.getParent()) {
663                 cur.dirty(pos(0) + min(oldsize(0) - bw, size(0) - bw),
664                           pos(1),
665                           Math.abs(oldsize(0) - size(0)) + bw,
666                           max(oldsize(1), size(1)));
667                 cur.dirty(pos(0),
668                           pos(1) + min(oldsize(1) - bh, size(1) - bh),
669                           max(oldsize(0), size(0)),
670                           Math.abs(oldsize(1) - size(1)) + bh);
671             }
672             
673         // SLOWPATH: dirty ourselves, as well as our former position on our parent
674         } else {
675             dirty();
676             if (getParent() != null) getParent().dirty(oldpos(0), oldpos(1), oldsize(0), oldsize(1));
677             
678         }
679         
680         boolean sizechange = false;
681         boolean poschange = false;
682         if ((oldsize(0) != size(0) || oldsize(1) != size(1)) && is_trapped("SizeChange")) sizechange = true;
683         if ((oldpos(0) != pos(0) || oldpos(1) != pos(1)) && is_trapped("PosChange")) poschange = true;
684         
685         set(oldsize, 0, size(0));
686         set(oldsize, 1, size(1));
687         set(oldpos, 0, pos(0));
688         set(oldpos, 1, pos(1));
689
690         if (sizechange || poschange)
691             if (surface.sizePosChangesSinceLastRender++ > 500) {
692                 if (Log.on) Log.log(this, "Warning, more than 500 SizeChange/PosChange traps triggered since last complete render");
693                 try {
694                     Trap t = sizechange ? Trap.getTrap(this, "SizeChange") : Trap.getTrap(this, "PosChange");
695                     InterpretedFunction f = (InterpretedFunction)t.f;
696                     if (Log.on) Log.log(this, "Current trap is at " + f.getSourceName() + ":" + f.getLineNumbers()[0]);
697                 } catch (Throwable t) { }
698             }
699
700         if (sizechange) put("SizeChange", null, Boolean.TRUE);
701         if (poschange) put("PosChange", null, Boolean.TRUE);
702         if (sizechange || poschange) {
703             surface.abort = true;
704             return;
705         }
706     }
707     
708
709     /** sets our childrens' sizes */
710     int sizeChildren() {
711
712         // Set sizes along minor axis, as well as sizes for absolute-positioned children
713         for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
714             if (bt.invisible) continue;
715             if (bt.absolute) {
716                 bt.set(size, o, max(bt.cmin(o), min(size(o) - bt.abs(o) - pad(o), bt.dmax(o))));
717                 bt.set(size, xo, max(bt.cmin(xo), min(size(xo) - bt.abs(xo) - pad(xo), bt.dmax(xo))));
718             } else if (xo == 0 && bt.hshrink || xo == 1 && bt.vshrink) {
719                 bt.set(size, xo, bt.cmin(xo));
720             } else {
721                 bt.set(size, xo, bound(bt.cmin(xo), size(xo) - 2 * pad(xo), bt.dmax(xo)));
722             }
723         }
724
725         // the ideal size of our children, along our own major axis
726         int goal = (o == 0 && hshrink) || (o == 1 && vshrink) ? cmin(o) - 2 * pad(o) : size(o) - 2 * pad(o);
727
728         // the current sum of the sizes of all children
729         int total = 0;
730
731         // each box is set to bound(box.cmin, box.flex * factor, box.dmax)
732         int factor = 0;
733
734         // Algorithm: we set the sizes of all boxes to bound(cmin, flex * factor, dmax) for some global value
735         //            'factor'. We figure out what 'factor' should be by starting at zero, and slowly increasing
736         //            it. After each pass, 'factor' is set to the smaller of two values: ((goal - total) /
737         //            remaining_flex) or the next largest value of factor which will cause some box to exceed its
738         //            cmin or dmax (thereby changing remaining_flex).
739
740         while(true) {
741             total = 0;
742
743             // the sum of the flexes of all boxes which are not pegged at either cmin or dmax
744             int remaining_flex = 0;
745
746             // this is the next largest value of factor at which some box exceeds its cmin/dmax
747             int nextjoint = Integer.MAX_VALUE;
748             
749             for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
750                 if (bt.absolute || bt.invisible) continue;
751
752                 bt.set(size, o, bound(bt.cmin(o), factor * bt.flex, bt.dmax(o)));
753                 total += bt.size(o);
754
755                 if (factor * bt.flex < bt.cmin(o) && bt.size(o) == bt.cmin(o)) {
756                     nextjoint = min(nextjoint, divide_round_up(bt.cmin(o), bt.flex));
757
758                 } else if (bt.size(o) < bt.dmax(o)) {
759                     remaining_flex += bt.flex;
760                     nextjoint = min(nextjoint, divide_round_up(bt.dmax(o), bt.flex));
761
762                 }
763             }
764
765             if (remaining_flex == 0) {
766                 if (nextjoint <= factor) break;
767                 factor = nextjoint;
768             } else {
769                 factor = min((goal - total + factor * remaining_flex) / remaining_flex, nextjoint);
770             }
771
772             if (goal - total <= remaining_flex) break;
773         }
774
775         // arbitrarily distribute out any leftovers resulting from rounding errors
776         int last = 0;
777         while(goal > total && total != last) {
778             last = total;
779             for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
780                 int newsize = bound(bt.cmin(o), bt.size(o) + 1, bt.dmax(o));
781                 total += newsize - bt.size(o);
782                 bt.set(size, o, newsize);
783             }
784         }
785
786         return total;
787     }
788     
789     /** positions this Box's children; cur is the starting position along this' major axis */
790     void positionChildren(int cur) {
791         for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
792             if (bt.invisible) continue;
793             if (bt.absolute) {
794                 bt.set(pos, 0, pos(0) + bt.abs(0));
795                 bt.set(pos, 1, pos(1) + bt.abs(1));
796             } else {
797                 bt.set(pos, xo, pos(xo) + pad(xo) + max(0, ((size(xo) - 2 * pad(xo) - bt.size(xo)) * (bt.align + 1)) / 2));
798                 bt.set(pos, o, cur);
799                 bt.set(abs, 0, bt.pos(0) - pos(0));
800                 bt.set(abs, 1, bt.pos(1) - pos(1));
801                 cur += bt.size(o);
802             }
803         }
804     }
805
806
807     // Rendering Pipeline /////////////////////////////////////////////////////////////////////
808
809     /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
810     void render(int xIn, int yIn, int wIn, int hIn, DoubleBuffer buf) {
811         if (surface.abort || invisible) return;
812
813         // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
814         int x = max(xIn, getParent() == null ? 0 : pos(0));
815         int y = max(yIn, getParent() == null ? 0 : pos(1));
816         int w = min(xIn + wIn, (getParent() == null ? 0 : pos(0)) + size(0)) - x;
817         int h = min(yIn + hIn, (getParent() == null ? 0 : pos(1)) + size(1)) - y;
818         if (w <= 0 || h <= 0) return;
819
820         if (border != null) renderBorder(x, y, w, h, buf);
821
822         if ((color & 0xFF000000) != 0x00000000 || getParent() == null) {
823             int bw = border == null ? 0 : border[2].getWidth();
824             int bh = border == null ? 0 : border[0].getHeight();
825             buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
826             buf.fillRect(max(x, pos(0) + bw),
827                          max(y, pos(1) + bh),
828                          min(x + w, pos(0) + size(0) - bw),
829                          min(y + h, pos(1) + size(1) - bh),
830                          (color & 0xFF000000) != 0 ? color : SpecialBoxProperty.lightGray);
831         }
832
833         if (image != null) {
834             if (tile) renderTiledImage(x, y, w, h, buf);
835             else renderStretchedImage(x, y, w, h, buf);
836         }
837
838         if (text != null && !text.equals("")) renderText(x, y, w, h, buf);
839
840         // now subtract the pad region from the clip region before proceeding
841         int x2 = max(x, pos(0) + pad(0));
842         int y2 = max(y, pos(1) + pad(1));
843         int w2 = min(x + w, pos(0) + size(0) - pad(0)) - x2;
844         int h2 = min(y + h, pos(1) + size(1) - pad(1)) - y2;
845
846         for(Box b = getChild(0); b != null; b = b.nextSibling())
847             b.render(x2, y2, w2, h2, buf);   
848     }
849
850     private void renderBorder(int x, int y, int w, int h, DoubleBuffer buf) {
851         int bw = border[4].getWidth();
852         int bh = border[4].getHeight();
853         buf.setClip(x, y, w + x, h + y);
854
855         if ((color & 0xFF000000) != 0xFF000000) {
856
857             // if the color is null, we have to be very careful about drawing the corners
858             if (Log.verbose) Log.log(this, "WARNING: (color == null && border != null) on box with border " + imageToNameMap.get(border[4]));
859
860             // upper left corner
861             buf.drawPicture(border[4],
862                             pos(0), pos(1), pos(0) + bw / 2, pos(1) + bh / 2,
863                             0, 0, bw / 2, bh / 2);
864             
865             // upper right corner
866             buf.drawPicture(border[4],
867                             pos(0) + size(0) - bw / 2, pos(1), pos(0) + size(0), pos(1) + bh / 2,
868                             bw - bw / 2, 0, bw, bh / 2);
869
870             // lower left corner
871             buf.drawPicture(border[4],
872                             pos(0), pos(1) + size(1) - bh / 2, pos(0) + bw / 2, pos(1) + size(1),
873                             0, bh - bh / 2, bw / 2, bh);
874
875             // lower right corner
876             buf.drawPicture(border[4],
877                             pos(0) + size(0) - bw / 2, pos(1) + size(1) - bh / 2, pos(0) + size(0), pos(1) + size(1),
878                             bw - bw / 2, bh - bh / 2, bw, bh);
879
880         } else {
881             buf.drawPicture(border[4], pos(0), pos(1));                                // upper left corner
882             buf.drawPicture(border[4], pos(0) + size(0) - bw, pos(1));                 // upper right corner
883             buf.drawPicture(border[4], pos(0), pos(1) + size(1) - bh);                 // lower left corner
884             buf.drawPicture(border[4], pos(0) + size(0) - bw, pos(1) + size(1) - bh);  // lower right corner                                     
885
886         }
887
888         // top and bottom edges
889         buf.setClip(max(x, pos(0) + bw / 2), y, min(x + w, pos(0) + size(0) - bw / 2), h + y);
890         for(int i = max(x, pos(0) + bw / 2); i + 100 < min(x + w, pos(0) + size(0) - bw / 2); i += 100) {
891             buf.drawPicture(border[0], i, pos(1));
892             buf.drawPicture(border[1], i, pos(1) + size(1) - bh / 2);
893         }
894         buf.drawPicture(border[0], min(x + w, pos(0) + size(0) - bw / 2) - 100, pos(1));
895         buf.drawPicture(border[1], min(x + w, pos(0) + size(0) - bw / 2) - 100, pos(1) + size(1) - bh / 2);
896
897         // left and right edges
898         buf.setClip(x, max(y, pos(1) + bh / 2), w + x, min(y + h, pos(1) + size(1) - bh / 2));
899         for(int i = max(y, pos(1) + bh / 2); i + 100 < min(y + h, pos(1) + size(1) - bh / 2); i += 100) {
900             buf.drawPicture(border[2], pos(0), i);
901             buf.drawPicture(border[3], pos(0) + size(0) - bw / 2, i);
902         }
903         buf.drawPicture(border[2], pos(0), min(y + h, pos(1) + size(1) - bh / 2) - 100);
904         buf.drawPicture(border[3], pos(0) + size(0) - bw / 2, min(y + h, pos(1) + size(1) - bh / 2) - 100);
905
906         buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
907     }
908
909     void renderStretchedImage(int x, int y, int w, int h, DoubleBuffer buf) {
910         buf.setClip(x, y, w + x, h + y);
911         int bw = border == null ? 0 : border[4].getHeight();
912         int bh = border == null ? 0 : border[4].getWidth();
913         buf.drawPicture(image,
914                         pos(0) + bw / 2,
915                         pos(1) + bh / 2,
916                         pos(0) + size(0) - bw / 2,
917                         pos(1) + size(1) - bh / 2,
918                         0, 0, image.getWidth(), image.getHeight());
919         buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
920     }
921
922     void renderTiledImage(int x, int y, int w, int h, DoubleBuffer buf) {
923         int iw = image.getWidth();
924         int ih = image.getHeight();
925         int bh = border == null ? 0 : border[4].getWidth();
926         int bw = border == null ? 0 : border[4].getHeight();
927
928         for(int i=(x - pos(0) - bw)/iw; i <= (x + w - pos(0) - bw)/iw; i++) {
929             for(int j=(y - pos(1) - bh)/ih; j<= (y + h - pos(1) - bh)/ih; j++) {
930                 
931                 int dx1 = max(i * iw + pos(0), x);
932                 int dy1 = max(j * ih + pos(1), y);
933                 int dx2 = min((i+1) * iw + pos(0), x + w);
934                 int dy2 = min((j+1) * ih + pos(1), y + h);
935                 
936                 int sx1 = dx1 - (i*iw) - pos(0);
937                 int sy1 = dy1 - (j*ih) - pos(1);
938                 int sx2 = dx2 - (i*iw) - pos(0);
939                 int sy2 = dy2 - (j*ih) - pos(1);
940
941                 if (dx2 - dx1 > 0 && dy2 - dy1 > 0 && sx2 - sx1 > 0 && sy2 - sy1 > 0)
942                     buf.drawPicture(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
943             }
944         }
945
946     }
947
948     void renderText(int x, int y, int w, int h, DoubleBuffer buf) {
949
950         if ((textcolor & 0xFF000000) == 0x00000000) return;
951         buf.setClip(x, y, w + x, h + y);
952
953         XWF xwf = XWF.getXWF(font);
954         if (xwf != null) {
955             xwf.drawString(buf, text,
956                            pos(0) + pad(0),
957                            pos(1) + pad(1) + xwf.getMaxAscent() - 1,
958                            textcolor);
959         } else {
960             buf.drawString(font, text,
961                            pos(0) + pad(0),
962                            pos(1) + pad(1) + Platform.getMaxAscent(font) - 1,
963                            textcolor);
964         }
965
966         buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
967         
968         int i=0; while(i<font.length() && !Character.isDigit(font.charAt(i))) i++;
969
970         if (font.lastIndexOf('d') > i) {
971             for(int j = pos(0) + pad(0); j < pos(0) + pad(0) + textdim(0); j += 2)
972                 buf.fillRect(j, pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font) : xwf.getMaxAscent()) + 3,
973                              j + 1, pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font) : xwf.getMaxAscent()) + 3 + 1,
974                              textcolor);
975
976         } else if (font.lastIndexOf('u') > i) {
977             buf.fillRect(pos(0) + pad(0),
978                         pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font) : xwf.getMaxAscent()) + 3,
979                         pos(0) + pad(0) + textdim(0),
980                         pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font) : xwf.getMaxAscent()) + 3 + 1,
981                         textcolor);
982         }
983
984     }
985
986
987     // Methods to implement org.mozilla.javascript.Scriptable //////////////////////////////////////
988
989     /** Returns the i_th child */
990     public Object get(int i, Scriptable start) {
991         if (redirect == null) return null;
992         if (redirect != this) return redirect.get(i, start);
993         return i >= numChildren() ? null : getChild(i);
994     }
995
996     /**
997      *  Inserts value as child i; calls remove() if necessary.
998      *  This method handles "reinserting" one of your children properly.
999      *  INVARIANT: after completion, getChild(min(i, numChildren())) == newnode
1000      *  WARNING: O(n) runtime, unless i == numChildren()
1001      */
1002     public void put(int i, Scriptable start, Object value) {
1003         if (value == null) {
1004             if (i > 0 && i < numChildren()) getChild(i).remove();
1005             return;
1006         }
1007         if (value instanceof RootProxy) {
1008             if (Log.on) Log.log(this, "attempt to reparent a box via its proxy object at " +
1009                                 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
1010             return;
1011         } else if (!(value instanceof Box)) {
1012             if (Log.on) Log.log(this, "attempt to set a numerical property on a box to anything other than a box at " +
1013                                 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
1014             return;
1015         }
1016         Box newnode = (Box)value;
1017         if (redirect == null) {
1018             if (Log.on) Log.log(this, "attempt to add a child to a node with a null redirect at " + 
1019                                 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
1020             return;
1021         } else if (redirect != this) redirect.put(i, null, newnode);
1022         else {
1023             if (numKids > 15 && children == null) convert_to_array();
1024             if (newnode.parent != null) newnode.remove();
1025             newnode.parent = this;
1026             
1027             if (children == null) {
1028                 if (firstKid == null) {
1029                     firstKid = newnode;
1030                     newnode.prevSibling = newnode;
1031                     newnode.nextSibling = newnode;
1032                 } else if (i >= numKids) {
1033                     newnode.prevSibling = firstKid.prevSibling;
1034                     newnode.nextSibling = firstKid;
1035                     firstKid.prevSibling.nextSibling = newnode;
1036                     firstKid.prevSibling = newnode;
1037                 } else {
1038                     Box cur = firstKid;
1039                     for(int j=0; j<i; j++) cur = cur.nextSibling;
1040                     newnode.prevSibling = cur.prevSibling;
1041                     newnode.nextSibling = cur;
1042                     cur.prevSibling.nextSibling = newnode;
1043                     cur.prevSibling = newnode;
1044                     if (i == 0) firstKid = newnode;
1045                 }
1046                 numKids++;
1047                 
1048             } else {
1049                 if (i >= children.size()) {
1050                     newnode.indexInParent = children.size();
1051                     children.addElement(newnode);
1052                 } else {
1053                     children.insertElementAt(newnode, i);
1054                     for(int j=i; j<children.size(); j++)
1055                         getChild(j).indexInParent = j;
1056                 }
1057             }
1058             newnode.setSurface(surface);
1059
1060             // need both of these in case child was already uncalc'ed
1061             newnode.mark_for_prerender();
1062             mark_for_prerender(); 
1063
1064             newnode.dirty();
1065             sync_cmin_to_children();
1066         }
1067
1068         // note that JavaScript box[0] will invoke put(int i), not put(String s)
1069         put("0", null, newnode);
1070     }
1071     
1072     public Object get(String name, Scriptable start) { return get(name, start, false); }
1073     public Object get(String name, Scriptable start, boolean ignoretraps) {
1074
1075         if (name == null || name.equals("")) return null;
1076
1077         // hack since Rhino needs to be able to grab these functions to create new objects
1078         if (name.equals("Object")) return JSObject.defaultObjects.get("Object", null);
1079         if (name.equals("Array")) return JSObject.defaultObjects.get("Array", null);
1080         if (name.equals("Function")) return JSObject.defaultObjects.get("Function", null);
1081         if (name.equals("TypeError")) return JSObject.defaultObjects.get("TypeError", null);
1082
1083         // See if we're reading back the function value of a trap
1084         if (name.charAt(0) == '_') {
1085             if (name.charAt(1) == '_') name = name.substring(2);
1086             else name = name.substring(1);
1087             Trap t = Trap.getTrap(this, name);
1088             return t == null ? null : t.f;
1089         }
1090         
1091         // See if we're triggering a trap
1092         Trap t = traps == null || ignoretraps ? null : (Trap)traps.get(name);
1093         if (t != null && t.isreadtrap) return t.perform(emptyobj);
1094
1095         // Check for a special handler
1096         SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
1097         if (gph != null) return gph.get(this);
1098
1099         return super.get(name, start);
1100     }
1101
1102     /** indicate that we don't want JSObject trying to handle these */
1103     public boolean has(String name, Scriptable start) {
1104         if (name.equals("")) return false;
1105         if (traps != null && traps.get(name) != null) return true;
1106         if (name.charAt(0) == '_') return true;
1107         if (SpecialBoxProperty.specialBoxProperties.get(name) != null) return true;
1108         if (name.equals("Function") || name.equals("Array") || name.equals("Object") || name.equals("TypeError")) return true;
1109         return super.has(name, start);
1110     }
1111
1112     public void put(String name, Scriptable start, Object value) { put(name, start, value, false, null); }
1113     public void put(String name, Scriptable start, Object value, boolean ignoretraps) { put(name, start, value, ignoretraps, null); }
1114
1115     /**
1116      *  Scriptable.put()
1117      *  @param ignoretraps if set, no traps will be triggered (set when 'cascade' reaches the bottom of the trap stack)
1118      *  @param rp if this put is being performed via a root proxy, rp is the root proxy.
1119      */
1120     public void put(String name, Scriptable start, Object value, boolean ignoretraps, RootProxy rp) {
1121         if (name == null) return;
1122         if (name.startsWith("xwt_")) {
1123             if (Log.on) Log.log(this, "attempt to set reserved property " + name + " at " +
1124                                 Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
1125             return;
1126         }
1127
1128         if (!ignoretraps && traps != null) {
1129             Trap t = (Trap)traps.get(name);
1130             if (t != null) {
1131                 Object[] arg = (Object[])singleObjects.remove(false);
1132                 if (arg == null) arg = new Object[] { value };
1133                 else arg[0] = value;
1134                 t.perform(arg);
1135                 arg[0] = null;
1136                 singleObjects.append(arg);
1137                 return;
1138             }
1139         }
1140
1141         // don't want to really cascade down to the box on this one
1142         if (name.equals("0")) return;
1143
1144         SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
1145         if (gph != null) {
1146             gph.put(name, this, value);
1147             return;
1148         }
1149
1150         if (name.charAt(0) == '_') {
1151             if (value != null && !(value instanceof Function)) {
1152                 if (Log.on) Log.log(this, "attempt to put a non-function value to " + name + " at " + 
1153                                     Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine);
1154             } else if (name.charAt(1) == '_') {
1155                 name = name.substring(2).intern();
1156                 Trap t = Trap.getTrap(this, name);
1157                 if (t != null) t.delete();
1158                 if (value != null) Trap.addTrap(this, name, ((Function)value), true, rp);
1159             } else {
1160                 name = name.substring(1).intern();
1161                 Trap t = Trap.getTrap(this, name);
1162                 if (t != null) t.delete();
1163                 if (value != null) Trap.addTrap(this, name, ((Function)value), false, rp);
1164             }
1165             return;
1166         }
1167
1168         if (ignoretraps) {
1169             // traps always cascade to the global property, not the local one
1170             putGlobally(name, start, value);
1171         } else {
1172             super.put(name, start, value);
1173         }
1174
1175         // a bit of a hack, since titlebar is the only 'special' property stored in JSObject
1176         if (getParent() == null && surface != null) {
1177             if (name.equals("titlebar")) surface.setTitleBarText(value.toString());
1178             if (name.equals("icon")) {
1179                 Picture pic = Box.getPicture(value.toString());
1180                 if (pic != null) surface.setIcon(pic);
1181                 else if (Log.on) Log.log(this, "unable to load icon " + value);
1182             }
1183         }
1184     }
1185
1186     /** the <tt>delete</tt> keyword is not valid in XWT scripts */
1187     public void delete(int i) { }
1188
1189
1190     // Tree Manipulation /////////////////////////////////////////////////////////////////////
1191
1192     /** The parent of this node */
1193     private Box parent = null;
1194     
1195     // Variables used in Vector mode */
1196     /** INVARIANT: if (parent != null) parent.children.elementAt(indexInParent) == this */
1197     private int indexInParent;
1198     private Vec children = null;
1199
1200     // Variables used in linked-list mode
1201     private int numKids = 0;
1202     private Box nextSibling = null;
1203     private Box prevSibling = null;
1204     private Box firstKid = null;
1205     
1206     // when we get more than 15 children, we switch to array-mode
1207     private void convert_to_array() {
1208         children = new Vec(numKids);
1209         Box cur = firstKid;
1210         do {
1211             children.addElement(cur);
1212             cur.indexInParent = children.size() - 1;
1213             cur = cur.nextSibling;
1214         } while (cur != firstKid);
1215     }
1216     
1217     /** remove this node from its parent; INVARIANT: whenever the parent of a node is changed, remove() gets called. */
1218     public void remove() {
1219         if (parent == null) {
1220             if (surface != null) surface.dispose();
1221             return;
1222         }
1223         Box oldparent = getParent();
1224         if (oldparent == null) return;
1225         mark_for_prerender();
1226         dirty();
1227         mouseinside = false;
1228
1229         if (parent.children != null) {
1230             parent.children.removeElementAt(indexInParent);
1231             for(int j=indexInParent; j<parent.children.size(); j++)
1232                 (parent.getChild(j)).indexInParent = j;
1233
1234         } else {
1235             if (parent.firstKid == this) {
1236                 if (nextSibling == this) parent.firstKid = null;
1237                 else parent.firstKid = nextSibling;
1238             }
1239             parent.numKids--;
1240             prevSibling.nextSibling = nextSibling;
1241             nextSibling.prevSibling = prevSibling;
1242             prevSibling = null;
1243             nextSibling = null;
1244         }
1245         parent = null;
1246
1247         if (oldparent != null) oldparent.sync_cmin_to_children();
1248         setSurface(null);
1249
1250         // note that JavaScript box[0] will invoke put(int i), not put(String s)
1251         if (oldparent != null) oldparent.put("0", null, this);
1252     }
1253
1254     /** returns our next sibling (parent[ourindex + 1]) */
1255     public final Box nextSibling() {
1256         if (parent == null) return null;
1257         if (parent.children == null) {
1258             if (nextSibling == parent.firstKid) return null;
1259             return nextSibling;
1260         } else {
1261             if (indexInParent >= parent.children.size() - 1) return null;
1262             return (Box)parent.children.elementAt(indexInParent + 1);
1263         }
1264     }
1265     
1266     /** returns our next sibling (parent[ourindex + 1]) */
1267     public final Box prevSibling() {
1268         if (parent == null) return null;
1269         if (parent.children == null) {
1270             if (this == parent.firstKid) return null;
1271             return prevSibling;
1272         } else {
1273             if (indexInParent == 0) return null;
1274             return (Box)parent.children.elementAt(indexInParent - 1);
1275         }
1276     }
1277     
1278     /** Returns the parent of this node */
1279     public Box getParent() { return parent; }
1280     
1281     /** Returns ith child */
1282     public Box getChild(int i) {
1283         if (children == null) {
1284             if (firstKid == null) return null;
1285             if (i >= numKids) return null;
1286             if (i == numKids - 1) return firstKid.prevSibling;
1287             Box cur = firstKid;
1288             for(int j=0; j<i; j++) cur = cur.nextSibling;
1289             return cur;
1290         } else {
1291             if (i >= children.size() || i < 0) return null;
1292             return (Box)children.elementAt(i);
1293         }
1294     }
1295     
1296     /** Returns the number of children */
1297     public int numChildren() {
1298         if (children == null) {
1299             if (firstKid == null) return 0;
1300             int i=1;
1301             for(Box cur = firstKid.nextSibling; cur != firstKid; i++) cur = cur.nextSibling;
1302             return i;
1303         } else {
1304             return children.size();
1305         }
1306     }
1307     
1308     /** Returns our index in our parent */
1309     public int getIndexInParent() {
1310         if (parent == null) return 0;
1311         if (parent.children == null) {
1312             int i = 0;
1313             for(Box cur = this; cur != parent.firstKid; i++) cur = cur.prevSibling;
1314             return i;
1315         } else {
1316             return indexInParent;
1317         }
1318     }
1319
1320     /** returns the root of the surface that this box belongs to */
1321     public final Box getRoot() {
1322         if (getParent() == null && surface != null) return this;
1323         if (getParent() == null) return null;
1324         return getParent().getRoot();
1325     }
1326
1327
1328     // Root Proxy ///////////////////////////////////////////////////////////////////////////////
1329
1330     RootProxy myproxy = null;
1331     public Scriptable getRootProxy() {
1332         if (myproxy == null) myproxy = new RootProxy(this);
1333         return myproxy;
1334     }
1335
1336     private static class RootProxy implements Scriptable {
1337
1338         Box box;
1339         RootProxy(Box b) { this.box = b; }
1340
1341         public void delete(String name) { box.delete(name); }
1342         public Scriptable getParentScope() { return box.getParentScope(); }
1343         public void setParentScope(Scriptable p) { box.setParentScope(p); }
1344         public boolean hasInstance(Scriptable value) { return box.hasInstance(value); }
1345         public Scriptable getPrototype() { return box.getPrototype(); }
1346         public void setPrototype(Scriptable p) { box.setPrototype(p); }
1347         public void delete(int i) { box.delete(i); }
1348         public String getClassName() { return box.getClassName(); }
1349         public Object getDefaultValue(Class hint) { return box.getDefaultValue(hint); }
1350
1351         public void put(int i, Scriptable start, Object value) { if (value != null) box.put(i, start, value); }
1352         public Object get(String name, Scriptable start) { return box.get(name, start); }
1353         public Object get(int i, Scriptable start) { return null; }
1354
1355         public void put(String name, Scriptable start, Object value) { box.put(name, start, value, false, this); }
1356         public boolean has(String name, Scriptable start) { return box.has(name, start); }
1357         public boolean has(int i, Scriptable start) { return box.has(i, start); }
1358         public Object[] getIds() { return box.getIds(); }
1359
1360     }
1361
1362
1363     // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
1364
1365     /** helper, included in this class so it can be inlined */
1366     static final int min(int a, int b) {
1367         if (a<b) return a;
1368         else return b;
1369     }
1370     
1371     /** helper, included in this class so it can be inlined */
1372     static final double min(double a, double b) {
1373         if (a<b) return a;
1374         else return b;
1375     }
1376     
1377     /** helper, included in this class so it can be inlined */
1378     static final int max(int a, int b) {
1379         if (a>b) return a;
1380         else return b;
1381     }
1382     
1383     /** helper, included in this class so it can be inlined */
1384     static final int min(int a, int b, int c) {
1385         if (a<=b && a<=c) return a;
1386         else if (b<=c && b<=a) return b;
1387         else return c;
1388     }
1389     
1390     /** helper, included in this class so it can be inlined */
1391     static final int max(int a, int b, int c) {
1392         if (a>=b && a>=c) return a;
1393         else if (b>=c && b>=a) return b;
1394         else return c;
1395     }
1396     
1397     /** helper, included in this class so it can be inlined */
1398     static final int bound(int a, int b, int c) {
1399         if (c < b) return c;
1400         if (a > b) return a;
1401         return b;
1402     }
1403
1404     /** returns numerator/denominator, but rounds <i>up</i> instead of down */
1405     static final int divide_round_up(int numerator, int denominator) {
1406         int ret = numerator / denominator;
1407         if (ret * denominator < numerator) return ret + 1;
1408         return ret;
1409     }
1410
1411     /** Simple helper function to determine if the point x,y falls within this node's actual current geometry */
1412     boolean inside(int x, int y) {
1413         if (invisible) return false;
1414         return (x >= pos(0) && y >= pos(1) && x < pos(0) + size(0) && y < pos(1) + size(1));
1415     }
1416     
1417     /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface
1418      *
1419      *  IMPORTANT: this method gets called from the event-queueing thread, since we need to determine which box is
1420      *             underneath the mouse as early as possible. Because of this, we have to do some extra checks, as the
1421      *             Box tree may be in flux.
1422      */
1423     Box whoIs(int x, int y) {
1424         if (invisible) return null;
1425         if (!inside(x,y)) return getParent() == null ? this : null;
1426
1427         // We do this because whoIs is unsynchronized (for
1428         // speed), yet is sometimes called while the structure of the
1429         // Box is in flux.
1430         for(int i=numChildren() - 1; i>=0; i--) {
1431
1432             Box child = getChild(i);
1433             if (child == null) continue;
1434
1435             Box bt = child.whoIs(x,y);
1436             if (bt != null) return bt;
1437         }
1438         return this;
1439     }
1440     
1441 }
1442
1443
1444