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