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