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