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