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