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