2003/09/18 08:04:08
[org.ibex.core.git] / src / org / xwt / Box.java.pp
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 //     **** This file must be preprocessed before compilation ****
5
6 // RULE: coordinates on non-static methods are ALWAYS relative to the
7 // upper-left hand corner of <tt>this</tt>
8
9 // FIXME: font color, italicization, bolding, and underlining
10 // FIXME: align
11 // FIXME: fixed aspect
12 // FEATURE: reflow before allowing js to read from width/height 
13 // FEATURE: fastpath for rows=1/cols=1
14 // FEATURE: reflow starting with a certain child
15 // FEATURE: separate mark_for_reflow and mark_for_resize
16
17 import java.io.*;
18 import java.net.*;
19 import java.util.*;
20 import org.xwt.js.*;
21 import org.xwt.util.*;
22 import org.xwt.imp.*;
23
24 /**
25  *  <p>
26  *  Encapsulates the data for a single XWT box as well as all layout
27  *  rendering logic.
28  *  </p>
29  *
30  *  <p>
31  *  This is the real meat of XWT. Part of its monolithic design is for
32  *  performance reasons: deep inheritance heirarchies are slow, and
33  *  neither javago nor GCJ can inline across class boundaries.
34  *  </p>
35  *
36  *  <p>The rendering process consists of three phases; each requires
37  *     one DFS pass over the tree</p>
38  *
39  *  <ol><li> <b>repacking</b>: children of a box are packed into columns
40  *           and rows according to their colspan/rowspan attributes and
41  *           ordering.  Minimum and maximum sizes of columns are computed.
42  *
43  *      <li> <b>resizing</b>: width/height and x/y positions of children
44  *           are assigned.  If a PosChange or SizeChange is triggered,
45  *           <tt>Surface.abort</tt> will be set and the resizing process will
46  *           Surface.abort.
47  *
48  *      <li> <b>repainting</b>: children draw their content onto the
49  *           buffer.
50  *  </ol>
51  *
52  *  The first two passes together are called the <i>reflow</i> phase.
53  *
54  *  Reflowing is done in a seperate pass since PosChanges and
55  *  SizeChanges trigger an Surface.abort; if rendering were done in the same
56  *  pass, rendering work done prior to the Surface.abort would be wasted.
57  *
58  *  The two passes are repack and resize.  Together they are known as
59  *  reflow.  Repacking assigns boxes to the appropriate grid
60  *  coordinates within the parents and computes
61  *  contentwidth/contentheight.  Resize computes actual size and
62  *  position.
63  *
64  *  A note on coordinates: the Box class represents regions
65  *  internally as x,y,w,h tuples, even though the DoubleBuffer class
66  *  uses x1,y1,x2,y2 tuples.
67  */
68 public final class Box extends JS.Scope {
69
70     public Box() { super(null); }
71
72
73     // Misc instance data ////////////////////////////////////////////////////////////////
74
75     private static int sizePosChangesSinceLastRender = 0;
76
77
78     // Misc instance data ////////////////////////////////////////////////////////////////
79
80     boolean needs_reflow = true;         
81     //#define MARK_FOR_REFLOW_this for(Box b2 = this; b2 != null && !b2.needs_reflow; b2 = b2.parent) b2.needs_reflow = true;
82     //#define MARK_FOR_REFLOW_b for(Box b2 = b; b2 != null && !b2.needs_reflow; b2 = b2.parent) b2.needs_reflow = true;
83     //#define MARK_FOR_REFLOW_b_parent for(Box b2 = b.parent; b2 != null && !b2.needs_reflow; b2 = b2.parent) b2.needs_reflow = true;
84
85     Box redirect = this;
86     Surface surface = null;               // null on all non-root boxen
87
88     // FEATURE: combine this with the JSObject Hash
89     Hash traps = null;
90
91
92     // Flags ///////////////////////////////////////////////////////////////////////////////
93     static int MOUSEINSIDE_FLAG  = 0x00000001;
94     static int INVISIBLE_FLAG    = 0x00000002;
95     static int ABSOLUTE_FLAG     = 0x00000004;
96     static int HSHRINK_FLAG      = 0x00000010;
97     static int VSHRINK_FLAG      = 0x00000020;
98     static int TILE_FLAG         = 0x00000040;
99
100     /**
101      *  Set when the font changes, cleared during repack.  If set
102      *  during repack, all font==null children are marked for reflow
103      *  and given the font_changed_flag.  We use this flag to avoid
104      *  having to iterate over all descendents of a box when its font
105      *  changes.
106      */
107     static int FONT_CHANGED_FLAG = 0x00000100;
108
109     static int ALIGN_FLAG        = 0x00000000;
110     static int FIXEDASPECT_FLAG  = 0x00000000;
111     int flags = 0;
112
113
114     // Geometry ////////////////////////////////////////////////////////////////////////////
115
116     // xwt can be compiled with 16-bit lengths to save memory on small devices
117     //#define LENGTH int
118     //#define MAX_LENGTH Integer.MAX_VALUE
119     //#define MIN_LENGTH Integer.MIN_VALUE
120
121     // always correct (set directly by user)
122     LENGTH minwidth = 0;        
123     LENGTH minheight = 0;        
124     LENGTH maxwidth = MAX_LENGTH;
125     LENGTH maxheight = MAX_LENGTH;
126     private LENGTH hpad = 0;
127     private LENGTH vpad = 0;
128     private String text = null;
129     private String font = null;
130     private LENGTH textwidth = 0;
131     private LENGTH textheight = 0;
132
133     // FEATURE: use shorts
134     private int rows = 1;
135     private int cols = 0;
136     private int rowspan = 1;
137     private int colspan = 1;
138
139     // computed during reflow
140     LENGTH x = 0;
141     LENGTH y = 0;
142     public LENGTH width = 0;
143     public LENGTH height = 0;
144     private int row = 0;  // FEATURE use a short
145     private int col = 0;  // FEATURE use a short
146     private LENGTH contentwidth = 0;             // == max(minwidth, textwidth+pad, sum(child.contentwidth) + pad)
147     private LENGTH contentheight = 0;
148
149
150     // Rendering Properties ///////////////////////////////////////////////////////////
151
152     //private SVG.VP path = null;
153     //private SVG.Paint fill = null;
154     //private SVG.Paint stroke = null;
155
156     private Picture image;                       // will disappear
157     private int fillcolor = 0x00000000;          // will become SVG.Paint
158     private int strokecolor = 0xFF000000;        // will become SVG.Paint
159
160     private String cursor = null;                // the cursor for this box
161
162
163     // Instance Methods /////////////////////////////////////////////////////////////////////
164
165     /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
166     public final void dirty() { dirty(0, 0, width, height); }
167     public final void dirty(int x, int y, int w, int h) {
168         for(Box cur = this; cur != null; cur = cur.parent) {
169             w = min(x + w, cur.width) - max(x, 0);
170             h = min(y + h, cur.height) - max(y, 0);
171             x = max(x, 0);
172             y = max(y, 0);
173             if (w <= 0 || h <= 0) return;
174             if (cur.parent == null && cur.surface != null) cur.surface.dirty(x, y, w, h);
175             x += cur.x;
176             y += cur.y;
177         }
178     }
179
180     /**
181      *  Given an old and new mouse position, this will update <tt>mouseinside</tt> and check
182      *  to see if this node requires any Enter, Leave, or Move notifications.
183      *
184      *  @param forceleave set to true by the box's parent if the mouse is inside an older
185      *                    sibling, which is covering up this box.
186      */
187     void Move(int oldmousex, int oldmousey, int mousex, int mousey) { Move(oldmousex, oldmousey, mousex, mousey, false); }
188     void Move(int oldmousex, int oldmousey, int mousex, int mousey, boolean forceleave) {
189
190         boolean wasinside = (flags & MOUSEINSIDE_FLAG) != 0;
191         boolean isinside = !((flags & INVISIBLE_FLAG) != 0) && inside(mousex, mousey) && !forceleave;
192         if (isinside) flags |= MOUSEINSIDE_FLAG; else flags &= ~MOUSEINSIDE_FLAG;
193
194         if (!wasinside && !isinside) return;
195
196         if (traps == null) { }
197         else if (!wasinside && isinside && traps.get("Enter") != null) put("Enter", Boolean.TRUE);
198         else if (wasinside && !isinside && traps.get("Leave") != null) put("Leave", Boolean.TRUE);
199         else if (wasinside && isinside && (mousex != oldmousex || mousey != oldmousey) && traps.get("Move") != null) put("Move", Boolean.TRUE);
200
201         if (isinside && cursor != null) getRoot().cursor = cursor;
202
203         // if the mouse has moved into our padding region, it is considered 'outside' all our children
204         if (!(mousex >= hpad && mousey >= vpad && mousex < width - hpad && mousey < height + vpad)) forceleave = true;
205
206         for(Box b = getChild(numChildren() - 1); b != null; b = b.prevSibling()) {
207             b.Move(oldmousex - b.x, oldmousey - b.y, mousex - b.x, mousey - b.y, forceleave);
208             if (b.inside(mousex - b.x, mousey - b.y)) forceleave = true;
209         }
210     }
211
212
213     // Reflow ////////////////////////////////////////////////////////////////////////////////////////
214
215     void reflow() {
216         repack();
217         if (Surface.abort) return;
218         resize(x, y, width, height);
219     }
220
221     /** Checks if the Box's size has changed, dirties it if necessary, and makes sure childrens' sizes are up to date */
222     void repack() {
223         if (!needs_reflow) return;
224         if (numChildren() == 0) {
225             contentwidth = max(textwidth + 2 * hpad, minwidth);
226             contentheight = max(textheight + 2 * vpad, minheight);
227             return;
228         }
229
230         // --- Phase 0 ----------------------------------------------------------------------
231         // recurse
232         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
233             if (((flags & FONT_CHANGED_FLAG) != 0) && child.font == null) {
234                 child.flags |= FONT_CHANGED_FLAG;
235                 child.needs_reflow = true;
236             }
237             child.repack();
238             if (Surface.abort) { MARK_FOR_REFLOW_this; return; }
239         }
240         flags &= ~FONT_CHANGED_FLAG;
241
242         // --- Phase 1 ----------------------------------------------------------------------
243         // assign children to their row/column positions (assuming constrained columns)
244         if ((rows == 0 && cols == 0) || (rows != 0 && cols != 0)) throw new Error("rows == " + rows + "   cols == " + cols);
245         //#repeat x/y y/x width/height col/row row/col cols/rows rows/cols colspan/rowspan rowspan/colspan colWidth/rowHeight numRowsInCol/numColsInRow INNER/INNER2 maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight OUTER/OUTER2 INNER/INNER2
246         if (rows == 0) {
247             int[] numRowsInCol = new int[cols];           // the number of cells occupied in each column
248             Box child = getChild(0);
249             for(; child != null && (((child.flags & ABSOLUTE_FLAG) != 0) || ((child.flags & INVISIBLE_FLAG) != 0)); child = child.nextSibling());
250             OUTER: for(int row=0; child != null; row++) {
251                 for(int col=0; child != null && col < cols;) {
252                     INNER: while(true) {  // scan across the row, looking for an unoccupied gap at least as wide as the child
253                         while(col < cols && numRowsInCol[col] > row) col++;
254                         for(int i=col; i < cols && i < col + min(cols, child.colspan); i++)
255                             if (numRowsInCol[col] > row) { col = i + 1; continue INNER; }
256                         break;
257                     }
258                     if (col + min(cols, child.colspan) > cols) break;
259                     for(int i=col; i < col + min(cols, child.colspan); i++) numRowsInCol[i] += child.rowspan;
260                     child.col = col;
261                     child.row = row;
262                     col += min(cols, child.colspan);
263                     child = child.nextSibling();
264                     for(; child != null && (((child.flags & ABSOLUTE_FLAG) != 0) || ((child.flags & INVISIBLE_FLAG) != 0)); child = child.nextSibling());
265                 }
266             }
267         }
268         //#end
269
270         // --- Phase 2 ----------------------------------------------------------------------
271         // compute the min/max sizes of the columns and rows and set our contentwidth
272         //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight numCols/numRows hpad/vpad
273         contentwidth = 2 * hpad;
274         int numCols = cols;
275         if (numCols == 0)
276             for(Box child = getChild(0); child != null; child = child.nextSibling())
277                 numCols = max(numCols, child.col + child.colspan);
278         LENGTH[] colWidth = new LENGTH[numCols];
279         for(Box child = getChild(0); child != null; child = child.nextSibling())
280             if (!(((child.flags & ABSOLUTE_FLAG) != 0) || ((child.flags & INVISIBLE_FLAG) != 0)))
281                 colWidth[child.col] = max(colWidth[child.col], child.contentwidth / child.colspan);
282         for(int col=0; col<numCols; col++) contentwidth += colWidth[col];
283         contentwidth = max(textwidth + 2 * hpad, contentwidth);
284         contentwidth = bound(minwidth, contentwidth, maxwidth);
285         //#end
286     }
287
288
289     void resize(LENGTH x, LENGTH y, LENGTH width, LENGTH height) {
290
291         // --- Phase 1 ----------------------------------------------------------------------
292         // run PosChange/SizeChange, dirty as needed
293         if (x != this.x || y != this.y || width != this.width || height != this.height) {
294             (parent == null ? this : parent).dirty(this.x, this.y, this.width, this.height);
295             boolean sizechange = false, poschange = false;
296             if (traps != null && (this.width != width || this.height != height) && traps.get("SizeChange") != null) sizechange = true;
297             if (traps != null && (this.x != x || this.y != y) && traps.get("PosChange") != null) poschange = true;
298             this.width = width; this.height = height; this.x = x; this.y = y;
299             dirty();
300             if (sizechange || poschange)
301                 if (sizePosChangesSinceLastRender == 500) {
302                     if (Log.on) Log.logJS(this, "Warning, more than 500 SizeChange/PosChange traps triggered since last complete render");
303                 } else {
304                     sizePosChangesSinceLastRender++;
305                     if (sizechange) put("SizeChange", Boolean.TRUE);
306                     if (poschange) put("PosChange", Boolean.TRUE);
307                     Surface.abort = true;
308                     return;
309                 }
310             needs_reflow = true;
311         }
312
313         // --- short circuit ----------------------------------------------------------------
314         if (!needs_reflow) return;
315         needs_reflow = false;
316         if (numChildren() == 0) return;
317
318         // --- Phase 2 ----------------------------------------------------------------------
319         // compute the min/max sizes of the columns and rows and set initial width/height to minimums
320
321         //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight marginWidth/marginHeight numCols/numRows
322         int numCols = cols;
323         if (numCols == 0)
324             for(Box child = getChild(0); child != null; child = child.nextSibling())
325                 numCols = max(numCols, child.col + child.colspan);
326         LENGTH[] colWidth = new LENGTH[numCols];
327         LENGTH[] colMaxWidth = new LENGTH[numCols];
328         int marginWidth = width;
329         for(int i=0; i<colMaxWidth.length; i++) colMaxWidth[i] = -1;
330         //#end
331
332         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
333             if (((child.flags & ABSOLUTE_FLAG) != 0) || ((child.flags & INVISIBLE_FLAG) != 0)) continue;
334             //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight HSHRINK_FLAG/VSHRINK_FLAG numCols/numRows
335             colWidth[child.col] = max(colWidth[child.col], child.contentwidth / child.colspan);
336             for(int i=child.col; i<child.col+child.colspan && i<numCols; i++)
337                 colMaxWidth[i] = max(colMaxWidth[i], (((child.flags & HSHRINK_FLAG) != 0) ? child.contentwidth : child.maxwidth) / child.colspan);
338             //#end
339         }
340
341         //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight marginWidth/marginHeight
342         for(int i=0; i<colMaxWidth.length; i++) if (colMaxWidth[i] == -1) colMaxWidth[i] = MAX_LENGTH;
343
344         for(int i=0; i<colMaxWidth.length; i++) {
345             if (colMaxWidth[i] == MAX_LENGTH) { marginWidth = 0; break; }
346             marginWidth -= colMaxWidth[i];
347             if (marginWidth < 0) { marginWidth = 0; break; }
348         }
349         //#end
350       
351
352         // --- Phase 3 ----------------------------------------------------------------------
353         // hand out the slack
354         int slack;
355         //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight numCols/numRows
356         slack = width;
357         for(int i=0; i<numCols; i++) slack -= colWidth[i];
358         if (numChildren() > 0)
359             while(slack > 0) {  
360                 // FEATURE: inefficient
361                 int startslack = slack;
362                 int increment = max(1, slack / numCols);
363                 for(int col=0; col < numCols && slack > 0; col++) {
364                     slack += colWidth[col];
365                     colWidth[col] = min(colMaxWidth[col], colWidth[col] + increment);
366                     slack -= colWidth[col];
367                 }
368                 if (slack == startslack) break;
369             }   
370         //#end
371
372
373         // --- Phase 4 ----------------------------------------------------------------------
374         // assign children's new sizes and positions and recurse
375         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
376             if ((child.flags & INVISIBLE_FLAG) != 0) continue;
377             int child_x = 0, child_y = 0, child_width = 0, child_height = 0;
378             if ((child.flags & ABSOLUTE_FLAG) != 0) {
379                 child_x = child.x;
380                 child_y = child.y;
381                 child_width = ((child.flags & HSHRINK_FLAG) != 0) ? child.contentwidth : min(child.maxwidth, width - child.x - hpad);
382                 child_height = ((child.flags & VSHRINK_FLAG) != 0) ? child.contentheight : min(child.maxheight, height - child.y - vpad);
383             } else {
384                 int diff;
385                 //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight HSHRINK_FLAG/VSHRINK_FLAG marginWidth/marginHeight hpad/vpad child_x/child_y child_width/child_height
386                 child_width = 0; for(int i=child.col; i<child.col+child.colspan && i<colWidth.length; i++) child_width += colWidth[i];
387                 diff = bound(child.contentwidth, child_width, ((child.flags & HSHRINK_FLAG) != 0) ? child.contentwidth : child.maxwidth) - child_width;
388                 child_x = max(hpad, marginWidth / 2); for(int i=0; i<child.col; i++) child_x += colWidth[i];
389                 if (diff < 0) child_x += -1 * (diff / 2);
390                 child_width += diff;
391                 //#end
392             }
393             child.resize(child_x, child_y, child_width, child_height);
394         }
395     }
396
397
398
399
400     // Rendering Pipeline /////////////////////////////////////////////////////////////////////
401
402     /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
403     void render(int parentx, int parenty, int clipx, int clipy, int clipw, int cliph, DoubleBuffer buf) {
404         if (Surface.abort || (flags & INVISIBLE_FLAG) != 0) return;
405         int globalx = parentx + (parent == null ? 0 : x);
406         int globaly = parenty + (parent == null ? 0 : y);
407
408         // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
409         clipw = min(max(clipx, parent == null ? 0 : globalx) + clipw,
410                     (parent == null ? 0 : globalx) + width) - globalx;
411         cliph = min(max(clipy, parent == null ? 0 : globaly) + cliph,
412                     (parent == null ? 0 : globaly) + height) - globaly;
413         clipx = max(clipx, parent == null ? 0 : globalx);
414         clipy = max(clipy, parent == null ? 0 : globaly);
415         if (clipw <= 0 || cliph <= 0) return;
416
417         if ((fillcolor & 0xFF000000) != 0x00000000 || parent == null)
418             buf.fillRect(clipx, clipy, clipx + clipw, clipy + cliph,
419                          (fillcolor & 0xFF000000) != 0 ? fillcolor : 0xFF777777);
420
421         if (image != null)
422             if ((flags & TILE_FLAG) != 0) renderTiledImage(globalx, globaly, clipx, clipy, clipw, cliph, buf);
423             else renderStretchedImage(globalx, globaly, clipx, clipy, clipw, cliph, buf);
424
425         if (text != null && !text.equals(""))
426             renderText(x, y, clipx, clipy, clipw, cliph, buf);
427
428         // now subtract the pad region from the clip region before proceeding
429         clipw = min(max(clipx, globalx + hpad) + clipw, globalx + width - hpad) - clipx;
430         cliph = min(max(clipy, globaly + vpad) + cliph, globaly + height - vpad) - clipy;
431         clipx = max(clipx, globalx + hpad);
432         clipy = max(clipy, globaly + vpad);
433
434         for(Box b = getChild(0); b != null; b = b.nextSibling())
435             b.render(globalx, globaly, clipx, clipy, clipw, cliph, buf);   
436     }
437
438     void renderStretchedImage(int globalx, int globaly, int x, int y, int w, int h, DoubleBuffer buf) {
439         buf.setClip(x, y, w + x, h + y);
440         buf.drawPicture(image,
441                         globalx, globaly,
442                         globalx + width, globaly + height,
443                         0, 0, image.getWidth(), image.getHeight());
444         buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
445     }
446
447     void renderTiledImage(int globalx, int globaly, int x, int y, int w, int h, DoubleBuffer buf) {
448         int iw = image.getWidth();
449         int ih = image.getHeight();
450         for(int i=(x - x)/iw; i <= (x + w - x)/iw; i++) {
451             for(int j=(y - y)/ih; j<= (y + h - y)/ih; j++) {
452                 
453                 int dx1 = max(i * iw + x, x);
454                 int dy1 = max(j * ih + y, y);
455                 int dx2 = min((i+1) * iw + x, x + w);
456                 int dy2 = min((j+1) * ih + y, y + h);
457                 
458                 int sx1 = dx1 - (i*iw) - x;
459                 int sy1 = dy1 - (j*ih) - y;
460                 int sx2 = dx2 - (i*iw) - x;
461                 int sy2 = dy2 - (j*ih) - y;
462
463                 if (dx2 - dx1 > 0 && dy2 - dy1 > 0 && sx2 - sx1 > 0 && sy2 - sy1 > 0)
464                     buf.drawPicture(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
465             }
466         }
467     }
468
469     void renderText(int x, int y, int clipx, int clipy, int clipw, int cliph, DoubleBuffer buf) {
470         try {
471             ImageDecoder id = org.xwt.imp.Font.render(new FileInputStream("COMIC.TTF"), 24, text, false);
472             Picture p = Platform.createPicture(id);
473             // FIXME: clipping (don't use setClip)
474             buf.drawPicture(p,
475                             x + hpad, y + vpad,
476                             x + hpad + p.getWidth(), y + vpad + p.getHeight(),
477                             0, 0,
478                             p.getWidth(), p.getHeight());
479         } catch (Exception e) {
480             Log.log(this, e);
481         }
482     }
483
484
485     // Methods to implement org.xwt.js.JS //////////////////////////////////////
486
487     public Object callMethod(Object method, JS.Array args, boolean checkOnly) throws JS.Exn {
488         if ("indexof".equals(method)) {
489             if (checkOnly) return Boolean.TRUE;
490             if (args.length() != 1 || args.elementAt(0) == null || !(args.elementAt(0) instanceof Box)) return new Integer(-1);
491             Box b = (Box)args.elementAt(0);
492             if (b.parent != Box.this) {
493                 if (redirect == null || redirect == Box.this) return new Integer(-1);
494                 return redirect.callMethod(method, args, checkOnly);
495             }
496             return new Integer(b.getIndexInParent());
497
498         } else if ("apply".equals(method)) {
499             if (checkOnly) return Boolean.TRUE;
500             if (args.elementAt(0) instanceof String) {
501                 String templatename = (String)args.elementAt(0);
502                 Template t = Template.getTemplate(templatename, null);
503                 if (t == null) {
504                     if (Log.on) Log.logJS(this, "template " + templatename + " not found");
505                 } else {
506                     if (ThreadMessage.suspendThread()) try {
507                         JS.Callable callback = args.length() < 2 ? null : (Callable)args.elementAt(1);
508                         t.apply(this, null, null, callback, 0, t.numUnits());
509                     } finally {
510                         ThreadMessage.resumeThread();
511                     }
512                 }
513             } else if (args.elementAt(0) instanceof JS && !(args.elementAt(0) instanceof Box)) {
514                 JS s = (JS)args.elementAt(0);
515                 Object[] keys = s.keys();
516                 for(int j=0; j<keys.length; j++) put(keys[j].toString(), s.get(keys[j]));
517             }
518             return this;
519         }
520         return null;
521     }
522
523     /** Returns the i_th child */
524     public Object get(int i) {
525         if (redirect == null) return null;
526         if (redirect != this) return redirect.get(i);
527         return i >= numChildren() || i < 0 ? null : getChild(i);
528     }
529
530     /**
531      *  Inserts value as child i; calls remove() if necessary.
532      *  This method handles "reinserting" one of your children properly.
533      *  INVARIANT: after completion, getChild(min(i, numChildren())) == newnode
534      *  WARNING: O(n) runtime, unless i == numChildren()
535      */
536     public void put(int i, Object value) {
537         if (i < 0) return;
538
539         if (value != null && !(value instanceof Box)) {
540             if (Log.on) Log.logJS(this, "attempt to set a numerical property on a box to anything other than a box");
541         } else if (redirect == null) {
542             if (Log.on) Log.logJS(this, "attempt to add/remove children to/from a node with a null redirect");
543         } else if (redirect != this) {
544             Box b = value == null ? (Box)redirect.get(i) : (Box)value;
545             redirect.put(i, value);
546             put("0", b);
547         } else if (value == null) {
548             if (i >= 0 && i < numChildren()) {
549                 Box b = getChild(i);
550                 b.remove();
551                 put("0", b);
552             }
553         } else if (value instanceof RootProxy) {
554             if (Log.on) Log.logJS(this, "attempt to reparent a box via its proxy object");
555         } else {
556             Box newnode = (Box)value;
557
558             // check if box being moved is currently target of a redirect
559             for(Box cur = newnode.parent; cur != null; cur = cur.parent)
560                 if (cur.redirect == newnode) {
561                     if (Log.on) Log.logJS(this, "attempt to move a box that is the target of a redirect");
562                     return;
563                 }
564
565             // check for recursive ancestor violation
566             for(Box cur = this; cur != null; cur = cur.parent)
567                 if (cur == newnode) {
568                     if (Log.on) Log.logJS(this, "attempt to make a node a parent of its own ancestor");
569                     if (Log.on) Log.log(this, "box == " + this + "  ancestor == " + newnode);
570                     return;
571                 }
572
573             if (numKids > 15 && children == null) convert_to_array();
574             newnode.remove();
575             newnode.parent = this;
576             
577             if (children == null) {
578                 if (firstKid == null) {
579                     firstKid = newnode;
580                     newnode.prevSibling = newnode;
581                     newnode.nextSibling = newnode;
582                 } else if (i >= numKids) {
583                     newnode.prevSibling = firstKid.prevSibling;
584                     newnode.nextSibling = firstKid;
585                     firstKid.prevSibling.nextSibling = newnode;
586                     firstKid.prevSibling = newnode;
587                 } else {
588                     Box cur = firstKid;
589                     for(int j=0; j<i; j++) cur = cur.nextSibling;
590                     newnode.prevSibling = cur.prevSibling;
591                     newnode.nextSibling = cur;
592                     cur.prevSibling.nextSibling = newnode;
593                     cur.prevSibling = newnode;
594                     if (i == 0) firstKid = newnode;
595                 }
596                 numKids++;
597                 
598             } else {
599                 if (i >= children.size()) {
600                     newnode.indexInParent = children.size();
601                     children.addElement(newnode);
602                 } else {
603                     children.insertElementAt(newnode, i);
604                     for(int j=i; j<children.size(); j++)
605                         getChild(j).indexInParent = j;
606                 }
607             }
608             
609             // need both of these in case child was already uncalc'ed
610             Box b = newnode; 
611             MARK_FOR_REFLOW_b;
612             MARK_FOR_REFLOW_this;
613             
614             newnode.dirty();
615
616             // note that JavaScript box[0] will invoke put(int i), not put(String s)
617             put("0", newnode);
618         }
619     }
620     
621     public Object get_(Object name) { return super.get(name); }
622     public Object get(Object name) { return get(name, false); }
623     public Object get(Object name_, boolean ignoretraps) {
624         if (name_ instanceof Number) return get(((Number)name_).intValue());
625
626         if (!(name_ instanceof String)) return null;
627         String name = (String)name_;
628         if (name.equals("")) return null;
629
630         // See if we're reading back the function value of a trap
631         if (name.charAt(0) == '_') {
632             if (name.charAt(1) == '_') name = name.substring(2);
633             else name = name.substring(1);
634             Trap t = Trap.getTrap(this, name);
635             return t == null ? null : t.f;
636         }
637         
638         // See if we're triggering a trap
639         Trap t = traps == null || ignoretraps ? null : (Trap)traps.get(name);
640         if (t != null && t.isreadtrap) return t.perform(Trap.emptyargs);
641
642         // Check for a special handler
643         SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
644         if (gph != null) return gph.get(this);
645
646         Object ret = super.get(name);
647         if (name.startsWith("$") && ret == null)
648             if (Log.on) Log.logJS(this, "WARNING: attempt to access " + name + ", but no child with id=\"" + name.substring(1) + "\" found");
649         return ret;
650     }
651
652     public Object[] keys() {
653         Object[] ret = new Object[numChildren()];
654         for(int i=0; i<ret.length; i++) ret[i] = new Integer(i);
655         return ret;
656     }
657
658     /**
659      *  Scriptable.put()
660      *  @param ignoretraps if set, no traps will be triggered (set when 'cascade' reaches the bottom of the trap stack)
661      *  @param rp if this put is being performed via a root proxy, rp is the root proxy.
662      */
663     public void put_(Object name, Object value) { super.put(name, value); }
664     public void put(Object name, Object value) { put(name, value, false, null); }
665     public void put(Object name, Object value, boolean ignoretraps) { put(name, value, ignoretraps, null); }
666     public void put(Object name_, Object value, boolean ignoretraps, RootProxy rp) {
667         if (name_ instanceof Number) { put(((Number)name_).intValue(), value); return; }
668         if (!(name_ instanceof String)) { super.put(name_,value); return; }
669         String name = name_.toString();
670         if (!ignoretraps && traps != null) {
671             Trap t = (Trap)traps.get(name);
672             if (t != null) {
673                 JS.Array arg = new JS.Array();
674                 arg.addElement(value);
675                 t.perform(arg);
676                 arg.setElementAt(null, 0);
677                 return;
678             }
679         }
680
681         // don't want to really cascade down to the box on this one
682         if (name.equals("0")) return;
683
684         SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
685         if (gph != null) { gph.put(name, this, value); return; }
686
687         if (name.charAt(0) == '_') {
688             if (value != null && !(value instanceof JS.Callable)) {
689                 if (Log.on) Log.logJS(this, "attempt to put a non function value (" + value + ") to " + name);
690             } else if (value != null && !(value instanceof JS.CompiledFunction)) {
691                 if (Log.on) Log.logJS(this, "attempt to put a non-compiled function value (" + value + ") to " + name);
692             } else if (name.charAt(1) == '_') {
693                 name = name.substring(2).intern();
694                 Trap t = Trap.getTrap(this, name);
695                 if (t != null) t.delete();
696                 if (value != null) Trap.addTrap(this, name, ((JS.CompiledFunction)value), true, rp);
697             } else {
698                 name = name.substring(1).intern();
699                 Trap t = Trap.getTrap(this, name);
700                 if (t != null) t.delete();
701                 if (value != null) Trap.addTrap(this, name, ((JS.CompiledFunction)value), false, rp);
702             }
703             return;
704         }
705
706         super.put(name, value);
707     }
708
709
710     // Tree Manipulation /////////////////////////////////////////////////////////////////////
711
712     /** The parent of this node */
713     private Box parent = null;
714     
715     // Variables used in Vector mode */
716     /** INVARIANT: if (parent != null) parent.children.elementAt(indexInParent) == this */
717     private int indexInParent;
718     private Vec children = null;
719
720     // Variables used in linked-list mode
721     private int numKids = 0;
722     private Box nextSibling = null;
723     private Box prevSibling = null;
724     private Box firstKid = null;
725     
726     // when we get more than 15 children, we switch to array-mode
727     private void convert_to_array() {
728         children = new Vec(numKids);
729         Box cur = firstKid;
730         do {
731             children.addElement(cur);
732             cur.indexInParent = children.size() - 1;
733             cur = cur.nextSibling;
734         } while (cur != firstKid);
735     }
736     
737     /** remove this node from its parent; INVARIANT: whenever the parent of a node is changed, remove() gets called. */
738     public void remove() {
739         if (parent == null) {
740             if (surface != null) surface.dispose(true);
741             return;
742         }
743         Box oldparent = parent;
744         if (oldparent == null) return;
745         MARK_FOR_REFLOW_this;
746         dirty();
747         flags &= ~MOUSEINSIDE_FLAG;
748
749         if (parent.children != null) {
750             parent.children.removeElementAt(indexInParent);
751             for(int j=indexInParent; j<parent.children.size(); j++)
752                 (parent.getChild(j)).indexInParent = j;
753
754         } else {
755             if (parent.firstKid == this) {
756                 if (nextSibling == this) parent.firstKid = null;
757                 else parent.firstKid = nextSibling;
758             }
759             parent.numKids--;
760             prevSibling.nextSibling = nextSibling;
761             nextSibling.prevSibling = prevSibling;
762             prevSibling = null;
763             nextSibling = null;
764         }
765         parent = null;
766
767         if (oldparent != null) { Box b = oldparent; MARK_FOR_REFLOW_b; }
768
769         // note that JavaScript box[0] will invoke put(int i), not put(String s)
770         if (oldparent != null) oldparent.put("0", this);
771     }
772
773     /** returns our next sibling (parent[ourindex + 1]) */
774     public final Box nextSibling() {
775         if (parent == null) return null;
776         if (parent.children == null) {
777             if (nextSibling == parent.firstKid) return null;
778             return nextSibling;
779         } else {
780             if (indexInParent >= parent.children.size() - 1) return null;
781             return (Box)parent.children.elementAt(indexInParent + 1);
782         }
783     }
784     
785     /** returns our next sibling (parent[ourindex + 1]) */
786     public final Box prevSibling() {
787         if (parent == null) return null;
788         if (parent.children == null) {
789             if (this == parent.firstKid) return null;
790             return prevSibling;
791         } else {
792             if (indexInParent == 0) return null;
793             return (Box)parent.children.elementAt(indexInParent - 1);
794         }
795     }
796     
797     /** Returns the parent of this node */
798     public Box getParent() { return parent; }
799     
800     /** Returns ith child */
801     public Box getChild(int i) {
802         if (children == null) {
803             if (firstKid == null) return null;
804             if (i >= numKids) return null;
805             if (i == numKids - 1) return firstKid.prevSibling;
806             Box cur = firstKid;
807             for(int j=0; j<i; j++) cur = cur.nextSibling;
808             return cur;
809         } else {
810             if (i >= children.size() || i < 0) return null;
811             return (Box)children.elementAt(i);
812         }
813     }
814     
815     /** Returns the number of children */
816     public int numChildren() {
817         if (children == null) {
818             if (firstKid == null) return 0;
819             int i=1;
820             for(Box cur = firstKid.nextSibling; cur != firstKid; i++) cur = cur.nextSibling;
821             return i;
822         } else {
823             return children.size();
824         }
825     }
826     
827     /** Returns our index in our parent */
828     public int getIndexInParent() {
829         if (parent == null) return 0;
830         if (parent.children == null) {
831             int i = 0;
832             for(Box cur = this; cur != parent.firstKid; i++) cur = cur.prevSibling;
833             return i;
834         } else {
835             return indexInParent;
836         }
837     }
838
839     /** returns the root of the surface that this box belongs to */
840     public final Box getRoot() {
841         if (parent == null && surface != null) return this;
842         if (parent == null) return null;
843         return parent.getRoot();
844     }
845
846
847     // Root Proxy ///////////////////////////////////////////////////////////////////////////////
848
849     // FEATURE: use xwt.graft() here
850     RootProxy myproxy = null;
851     public JS getRootProxy() {
852         if (myproxy == null) myproxy = new RootProxy(this);
853         return myproxy;
854     }
855
856     private static class RootProxy extends JS {
857         Box box;
858         RootProxy(Box b) { this.box = b; }
859         public Object get(Object name) { return box.get(name); }
860         public void put(Object name, Object value) { box.put(name, value, false, this); }
861         public Object[] keys() { return box.keys(); }
862         public Object callMethod(Object method, JS.Array args, boolean justChecking) {
863             return ((Box)box).callMethod(method,args,justChecking);
864         }
865     }
866
867
868     // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
869
870     static final int min(int a, int b) { if (a<b) return a; else return b; }
871     static final double min(double a, double b) { if (a<b) return a; else return b; }
872     static final int max(int a, int b) { if (a>b) return a; else return b; }
873     static final int min(int a, int b, int c) { if (a<=b && a<=c) return a; else if (b<=c && b<=a) return b; else return c; }
874     static final int max(int a, int b, int c) { if (a>=b && a>=c) return a; else if (b>=c && b>=a) return b; else return c; }
875     static final int bound(int a, int b, int c) { if (c < b) return c; if (a > b) return a; return b; }
876     final boolean inside(int x, int y) { return (!((flags & INVISIBLE_FLAG) != 0) && x >= 0 && y >= 0 && x < width && y < height); }
877     
878     /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface */
879     public static Box whoIs(Box cur, int x, int y) {
880
881         if (cur.parent != null) throw new Error("whoIs may only be invoked on the root box of a surface");
882         int globalx = 0;
883         int globaly = 0;
884
885         // WARNING: this method is called from the event-queueing
886         // thread -- it may run concurrently with ANY part of XWT, and
887         // is UNSYNCHRONIZED for performance reasons.  BE CAREFUL
888         // HERE.
889
890         if ((cur.flags & INVISIBLE_FLAG) != 0) return null;
891         if (!cur.inside(x - globalx, y - globaly)) return cur.parent == null ? cur : null;
892         OUTER: while(true) {
893             for(int i=cur.numChildren() - 1; i>=0; i--) {
894                 Box child = cur.getChild(i);
895                 if (child == null) continue;        // since this method is unsynchronized, we have to double-check
896                 globalx += child.x;
897                 globaly += child.y;
898                 if (!((child.flags & INVISIBLE_FLAG) != 0) && child.inside(x - globalx, y - globaly)) { cur = child; continue OUTER; }
899                 globalx -= child.x;
900                 globaly -= child.y;
901             }
902             break;
903         }
904         return cur;
905     }
906
907     /** 
908      *  A helper class for properties of Box which require special
909      *  handling.
910      *
911      *  To avoid excessive use of String.equals(), the Box.get() and
912      *  Box.put() methods employ a Hash keyed on property names that
913      *  require special handling. The value stored in the Hash is an
914      *  instance of an anonymous subclass of SpecialBoxProperty, which knows
915      *  how to handle get()s and put()s for that property name. There
916      *  should be one anonymous subclass of SpecialBoxProperty for each
917      *  specially-handled property on Box.
918      */
919     static class SpecialBoxProperty {
920
921         SpecialBoxProperty() { }
922
923         /** stores instances of SpecialBoxProperty; keyed on property name */
924         static Hash specialBoxProperties = new Hash(200, 3);
925
926         /** this method defines the behavior when the property is get()ed from b */
927         Object get(Box b) { return null; }
928
929         /** this method defines the behavior when the property is put() to b */
930         void put(Box b, Object value) { }
931
932         /** this method defines the behavior when the property is put() to b, allows a single SpecialBoxProperty to serve multiple properties */
933         void put(String name, Box b, Object value) { put(b, value); }
934
935         static {
936             //#repeat fillcolor/strokecolor
937             specialBoxProperties.put("fillcolor", new SpecialBoxProperty() {
938                     public Object get(Box b) {
939                         if ((b.fillcolor & 0xFF000000) == 0) return null;
940                         String red = Integer.toHexString((b.fillcolor & 0x00FF0000) >> 16);
941                         String green = Integer.toHexString((b.fillcolor & 0x0000FF00) >> 8);
942                         String blue = Integer.toHexString(b.fillcolor & 0x000000FF);
943                         if (red.length() < 2) red = "0" + red;
944                         if (blue.length() < 2) blue = "0" + blue;
945                         if (green.length() < 2) green = "0" + green;
946                         return "#" + red + green + blue;
947                     }
948                     public void put(Box b, Object value) {
949                         int newcolor = b.fillcolor;
950                         String s = value == null ? null : value.toString();
951                         if (value == null) newcolor = 0x00000000;
952                         else if (s.length() > 0 && s.charAt(0) == '#')
953                             try {
954                                 newcolor = 0xFF000000 |
955                                     (Integer.parseInt(s.substring(1, 3), 16) << 16) |
956                                     (Integer.parseInt(s.substring(3, 5), 16) << 8) |
957                                     Integer.parseInt(s.substring(5, 7), 16);
958                             } catch (NumberFormatException e) {
959                                 Log.log(this, "invalid color " + s);
960                                 return;
961                             }
962                         else if (SVG.colors.get(s) != null)
963                             newcolor = 0xFF000000 | ((Integer)SVG.colors.get(s)).intValue();
964                         if (newcolor == b.fillcolor) return;
965                         b.fillcolor = newcolor;
966                         b.dirty();
967                     }
968                 });
969             //#end
970         
971             specialBoxProperties.put("color", new SpecialBoxProperty() {
972                     public Object get(Box b) { return b.get("fillcolor"); }
973                     public void put(Box b, Object value) { b.put("fillcolor", value); }
974                 });
975
976             specialBoxProperties.put("textcolor", new SpecialBoxProperty() {
977                     public Object get(Box b) { return b.get("strokecolor"); }
978                     public void put(Box b, Object value) { b.put("strokecolor", value); }
979                 });
980
981             specialBoxProperties.put("text", new SpecialBoxProperty() {
982                     public Object get(Box b) { return b.text; }
983                     public void put(Box b, Object value) {
984                         String t = value == null ? "null" : value.toString();
985                         if (t.equals(b.text)) return;
986                         b.text = t;
987                         if (t == null) {
988                             if (b.textwidth != 0 || b.textheight != 0) MARK_FOR_REFLOW_b;
989                             b.textwidth = b.textheight = 0;
990                         } else {
991                             try {
992                                 ImageDecoder id = org.xwt.imp.Font.render(new FileInputStream("COMIC.TTF"), 24, b.text, true);
993                                 if (id.getWidth() != b.textwidth || id.getHeight() != b.textheight) MARK_FOR_REFLOW_b;
994                                 b.textwidth = id.getWidth();
995                                 b.textheight = id.getHeight();
996                             } catch (Exception e) {
997                                 Log.log(this, e);
998                             }
999                         }
1000                         b.dirty();
1001                     } });
1002
1003             specialBoxProperties.put("font", new SpecialBoxProperty() {
1004                     public Object get(Box b) { return b.font; }
1005                     public void put(Box b, Object value) {
1006                         b.font = value == null ? null : value.toString();
1007                         // FIXME: translate value into a resource
1008                         MARK_FOR_REFLOW_b;
1009                         b.flags |= FONT_CHANGED_FLAG;
1010                         b.dirty();
1011                     } });
1012         
1013             specialBoxProperties.put("thisbox", new SpecialBoxProperty() {
1014                     public Object get(Box b) { return b; }
1015                     public void put(Box b, Object value) {
1016                         if (value == null) b.remove();
1017                         else if (value.equals("window") || value.equals("frame")) Platform.createSurface(b, value.equals("frame"), true);
1018                         else if (Log.on) Log.log(this, "put invalid value to 'thisbox' property: " + value);
1019                     }
1020                 });
1021
1022             specialBoxProperties.put("orient", new SpecialBoxProperty() {
1023                     public Object get(Box b) {
1024                         Log.log(this, "warning: the orient property is deprecated");
1025                         if (b.redirect == null) return "horizontal";
1026                         else if (b.redirect != b) return get(b.redirect);
1027                         else if (b.cols == 1) return "vertical";
1028                         else if (b.rows == 1) return "horizontal";
1029                         else return "grid";
1030                     }
1031                     public void put(Box b, Object value) {
1032                         Log.log(this, "warning: the orient property is deprecated");
1033                         if (value == null) return;
1034                         if (b.redirect == null) return;
1035                         if (b.redirect != b) { put(b.redirect, value); return; }
1036                         if (value.equals("vertical")) {
1037                             if (b.rows == 0) return;
1038                             b.rows = 0; b.cols = 1;
1039                         } else if (value.equals("horizontal")) {
1040                             if (b.cols == 0) return;
1041                             b.cols = 0; b.rows = 1;
1042                         } else if (Log.on)
1043                             Log.log(this, "invalid value put to orient property: " + value);
1044                         MARK_FOR_REFLOW_b;
1045                     } });
1046
1047             specialBoxProperties.put("static", new SpecialBoxProperty() {
1048                     public Object get(Box b) {
1049                         String cfsn =
1050                             JS.Thread.fromJavaThread(java.lang.Thread.currentThread()).getCurrentCompiledFunction().getSourceName();
1051                         for(int i=0; i<cfsn.length() - 1; i++)
1052                             if (cfsn.charAt(i) == '.' && (cfsn.charAt(i+1) == '_' || Character.isDigit(cfsn.charAt(i+1)))) {
1053                                 cfsn = cfsn.substring(0, i);
1054                                 break;
1055                             }
1056                         return Static.getStatic(cfsn);
1057                     }
1058                 });
1059
1060             specialBoxProperties.put("shrink", new SpecialBoxProperty() {
1061                     public Object get(Box b) { return (((b.flags & HSHRINK_FLAG) != 0) || ((b.flags & VSHRINK_FLAG) != 0)) ? Boolean.TRUE : Boolean.FALSE; }
1062                     public void put(Box b, Object value) { b.put("hshrink", value); b.put("vshrink", value); }
1063                 });
1064         
1065             //#repeat hshrink/vshrink HSHRINK_FLAG/VSHRINK_FLAG
1066             specialBoxProperties.put("hshrink", new SpecialBoxProperty() {
1067                     public Object get(Box b) { return new Boolean((b.flags & HSHRINK_FLAG) != 0); }
1068                     public void put(Box b, Object value) {
1069                         boolean newshrink = stob(value);
1070                         if (((b.flags & HSHRINK_FLAG) != 0) == newshrink) return;
1071                         if (newshrink) b.flags |= HSHRINK_FLAG; else b.flags &= ~HSHRINK_FLAG;
1072                         MARK_FOR_REFLOW_b;
1073                     }
1074                 });
1075             //#end
1076         
1077             //#repeat x/y
1078             specialBoxProperties.put("x", new SpecialBoxProperty() {
1079                     public Object get(Box b) {
1080                         if (b.surface == null) return new Integer(0);
1081                         if ((b.flags & INVISIBLE_FLAG) != 0) return new Integer(0);
1082                         return new Integer(b.x);
1083                     }
1084                     public void put(Box b, Object value) {
1085                         if (!((b.flags & ABSOLUTE_FLAG) != 0)) return;
1086                         int x = stoi(value);
1087                         if (x == b.x) return;
1088                         b.dirty();
1089                         b.x = x;
1090                         if (b.parent == null && b.surface != null) {
1091                             b.surface.setLocation();
1092                             b.surface.centerSurfaceOnRender = false;
1093                         }
1094                         MARK_FOR_REFLOW_b;
1095                         b.dirty();
1096                     }
1097                 });
1098             //#end
1099         
1100             //#repeat width/height minwidth/minheight maxwidth/maxheight
1101             specialBoxProperties.put("width", new SpecialBoxProperty() {
1102                     public Object get(Box b) { return new Integer(b.width); }
1103                     public void put(Box b, Object value) {
1104                         b.width = stoi(value);
1105                         if (b.parent == null && b.surface != null) {
1106                             b.surface.setSize();
1107                             MARK_FOR_REFLOW_b;
1108                         } else {
1109                             if (b.minwidth == b.width && b.maxwidth == b.width) return;
1110                             b.minwidth = b.maxwidth = b.width;
1111                             MARK_FOR_REFLOW_b;
1112                         }
1113                     } });
1114             //#end
1115
1116             //#repeat cols/rows rows/cols
1117             specialBoxProperties.put("cols", new SpecialBoxProperty() {
1118                     public Object get(Box b) { return new Double(b.cols); }
1119                     public void put(Box b, Object value) {
1120                         if (b.cols == stoi(value)) return;
1121                         b.cols = stoi(value);
1122                         if (b.cols == 0 && b.rows == 0) b.rows = 1;
1123                         if (b.cols != 0 && b.rows != 0) b.rows = 0;
1124                         MARK_FOR_REFLOW_b;
1125                     } });
1126             //#end
1127         
1128             //#repeat colspan/rowspan
1129             specialBoxProperties.put("colspan", new SpecialBoxProperty() {
1130                     public Object get(Box b) { return new Double(b.colspan); }
1131                     public void put(Box b, Object value) {
1132                         if (b.colspan == stoi(value)) return;
1133                         b.colspan = stoi(value);
1134                         MARK_FOR_REFLOW_b;
1135                     }
1136                 });
1137             //#end
1138         
1139             specialBoxProperties.put("tile", new SpecialBoxProperty() {
1140                     public Object get(Box b) { return ((b.flags & TILE_FLAG) != 0) ? Boolean.TRUE : Boolean.FALSE; }
1141                     public void put(Box b, Object value) {
1142                         if (((b.flags & TILE_FLAG) != 0) == stob(value)) return;
1143                         if (stob(value)) b.flags |= TILE_FLAG; else b.flags &= ~TILE_FLAG;
1144                         b.dirty();
1145                     } });
1146         
1147             specialBoxProperties.put("invisible", new SpecialBoxProperty() {
1148                     public Object get(Box b) {
1149                         for (Box cur = b; cur != null; cur = cur.parent) {
1150                             if ((cur.flags & INVISIBLE_FLAG) != 0) return Boolean.TRUE; }
1151                         return Boolean.FALSE;
1152                     }
1153                     public void put(Box b, Object value) {
1154                         if (stob(value) == ((b.flags & INVISIBLE_FLAG) != 0)) return;
1155                         if (stob(value)) b.flags |= INVISIBLE_FLAG; else b.flags &= ~INVISIBLE_FLAG;
1156                         if (b.parent == null) {
1157                             if (b.surface != null) b.surface.setInvisible((b.flags & INVISIBLE_FLAG) != 0);
1158                         } else {
1159                             b.dirty();
1160                             MARK_FOR_REFLOW_b_parent;
1161                             b.parent.dirty(b.x, b.y, b.width, b.height);
1162                         }
1163                     }});
1164         
1165             specialBoxProperties.put("absolute", new SpecialBoxProperty() {
1166                     public Object get(Box b) { return ((b.flags & ABSOLUTE_FLAG) != 0) ? Boolean.TRUE : Boolean.FALSE; }
1167                     public void put(Box b, Object value) {
1168                         if (stob(value) == ((b.flags & ABSOLUTE_FLAG) != 0)) return;
1169                         if (stob(value)) b.flags |= ABSOLUTE_FLAG; else b.flags &= ~ABSOLUTE_FLAG;
1170                         if ((b.flags & ABSOLUTE_FLAG) != 0) { b.x = 0; b.y = 0; }
1171                         if (b.parent != null) MARK_FOR_REFLOW_b_parent;
1172                     } });
1173         
1174             specialBoxProperties.put("image", new SpecialBoxProperty() {
1175                     public Object get(Box b) { return b.image == null ? null : ImageDecoder.imageToNameMap.get(b.image); }
1176                     public void put(Box b, Object value) {
1177                         if ((value == null && b.image == null) ||
1178                             (value != null && b.image != null && value.equals(ImageDecoder.imageToNameMap.get(b.image)))) return;
1179                         String s = value == null ? null : value.toString();
1180                         if (s == null || s.equals("")) b.image = null;
1181                         else {
1182                             if ((b.image = ImageDecoder.getPicture(s)) == null) {
1183                                 if (Log.on) Log.logJS(Box.class, "unable to load image " + s);
1184                             } else {
1185                                 b.minwidth = b.maxwidth = b.image.getWidth();
1186                                 b.minheight = b.maxheight = b.image.getHeight();
1187                                 MARK_FOR_REFLOW_b;
1188                             }
1189                         }
1190                         b.dirty();
1191                     }
1192                 });
1193
1194             //#repeat globalx/globaly x/y
1195             specialBoxProperties.put("globalx", new SpecialBoxProperty() {
1196                     public Object get(Box b) { return new Integer(b.parent == null || b.surface == null ? 0 : b.x); }
1197                     public void put(Box b, Object value) {
1198                         if (b.surface == null || b.parent == null) return;
1199                         b.put("x", new Integer(stoi(value) - stoi(get(b.parent))));
1200                         MARK_FOR_REFLOW_b;
1201                     }
1202                 });
1203             //#end
1204         
1205             specialBoxProperties.put("cursor", new SpecialBoxProperty() {
1206                     public Object get(Box b) { return b.cursor; } 
1207                     public void put(Box b, Object value) {
1208                         b.cursor = (String)value;
1209                         if (b.surface == null) return;
1210
1211                         // see if we need to update the surface cursor
1212                         Surface surface = b.getRoot().surface;
1213                         String tempcursor = surface.cursor;
1214                         b.Move(surface.mousex, surface.mousey, surface.mousex, surface.mousey);
1215                         if (surface.cursor != tempcursor) surface.syncCursor();
1216                     } 
1217                 });
1218         
1219             //#repeat mousex/mousey x/y
1220             specialBoxProperties.put("mousex", new SpecialBoxProperty() {
1221                     public Object get(Box b) {
1222                         Surface surface = b.getRoot().surface;
1223                         if (surface == null) return new Integer(0);
1224                         int mousex = surface.mousex;
1225                         for(Box cur = b; cur != null && cur.parent != null; cur = cur.parent) mousex -= cur.x;
1226                         return new Integer(mousex);
1227                     }
1228                 });
1229             //#end
1230         
1231             specialBoxProperties.put("xwt", new SpecialBoxProperty() {
1232                     public Object get(Box b) { return XWT.singleton; }
1233                 });
1234         
1235             specialBoxProperties.put("mouseinside", new SpecialBoxProperty() {
1236                     public Object get(Box b) {
1237                         return ((b.flags & MOUSEINSIDE_FLAG) != 0) ? Boolean.TRUE : Boolean.FALSE; }
1238                 });
1239         
1240             specialBoxProperties.put("numchildren", new SpecialBoxProperty() {
1241                     public Object get(Box b) {
1242                         if (b.redirect == null) return new Integer(0);
1243                         if (b.redirect != b) return get(b.redirect);
1244                         return new Integer(b.numChildren());
1245                     } });
1246         
1247             SpecialBoxProperty mouseEventHandler = new SpecialBoxProperty() {
1248                     public void put(String name, Box b, Object value) {
1249                         Surface surface = b.getRoot().surface;
1250                         if (surface == null) return;
1251                         int mousex = surface.mousex;
1252                         int mousey = surface.mousey;
1253                         for(Box c = b.parent; c != null && c.parent != null; c = c.parent) {
1254                             mousex -= c.x;
1255                             mousey -= c.y;
1256                         }
1257                         for(Box c = b.prevSibling(); c != null; c = c.prevSibling()) {
1258                             if (c.inside(mousex - c.x, mousey - c.y)) {
1259                                 c.put(name, value);
1260                                 return;
1261                             }
1262                         }
1263                         if (b.parent != null) b.parent.put(name, value);
1264                     }};
1265
1266             specialBoxProperties.put("Press1", mouseEventHandler);
1267             specialBoxProperties.put("Press2", mouseEventHandler);
1268             specialBoxProperties.put("Press3", mouseEventHandler);
1269             specialBoxProperties.put("Release1", mouseEventHandler);
1270             specialBoxProperties.put("Release2", mouseEventHandler);
1271             specialBoxProperties.put("Release3", mouseEventHandler);
1272             specialBoxProperties.put("Click1", mouseEventHandler);
1273             specialBoxProperties.put("Click2", mouseEventHandler);
1274             specialBoxProperties.put("Click3", mouseEventHandler);
1275             specialBoxProperties.put("DoubleClick1", mouseEventHandler);
1276             specialBoxProperties.put("DoubleClick2", mouseEventHandler);
1277             specialBoxProperties.put("DoubleClick3", mouseEventHandler);
1278
1279             specialBoxProperties.put("root", new SpecialBoxProperty() {
1280                     public Object get(Box b) {
1281                         if (b.getRoot() == null) return null;
1282                         else if (b.parent == null) return b;
1283                         else return b.getRoot().getRootProxy();
1284                     } });
1285
1286             specialBoxProperties.put("Minimized", new SpecialBoxProperty() {
1287                     public Object get(Box b) {
1288                         if (b.parent == null && b.surface != null) return b.surface.minimized ? Boolean.TRUE : Boolean.FALSE;
1289                         else return null;
1290                     }
1291                     public void put(Box b, Object value) {
1292                         if (b.surface == null) return;
1293                         boolean val = stob(value);
1294                         if (b.parent == null && b.surface.minimized != val) b.surface.setMinimized(val);
1295                     }
1296                 });
1297
1298             specialBoxProperties.put("Maximized", new SpecialBoxProperty() {
1299                     public Object get(Box b) {
1300                         if (b.parent == null && b.surface != null) return b.surface.maximized ? Boolean.TRUE : Boolean.FALSE;
1301                         else return null;
1302                     }
1303                     public void put(Box b, Object value) {
1304                         if (b.surface == null) return;
1305                         boolean val = stob(value);
1306                         if (b.parent == null && b.surface.maximized != val) b.surface.setMaximized(val);
1307                     }
1308                 });
1309
1310             specialBoxProperties.put("toback", new SpecialBoxProperty() {
1311                     public void put(Box b, Object value) {
1312                         if (b.parent == null && stob(value) && b.surface != null) b.surface.toBack();
1313                     }
1314                 });
1315
1316             specialBoxProperties.put("tofront", new SpecialBoxProperty() {
1317                     public void put(Box b, Object value) {
1318                         if (b.parent == null && stob(value) && b.surface != null) b.surface.toFront();
1319                     }
1320                 });
1321
1322             //#repeat hscar/vscar
1323             specialBoxProperties.put("hscar", new SpecialBoxProperty() {
1324                     public void put(Box b, Object value) {
1325                         if (b.parent == null && b.surface != null) {
1326                             b.surface.hscar = stoi(value);
1327                             b.surface.dirty(0, 0, b.width, b.height);
1328                             b.surface.Refresh();
1329                         }
1330                     }
1331                 });
1332             //#end
1333
1334             specialBoxProperties.put("Close", new SpecialBoxProperty() {
1335                     public void put(Box b, Object value) {
1336                         if (b.parent == null && b.surface != null) b.surface.dispose(true);
1337                     }
1338                 });
1339
1340             // these are all do-nothings; just to prevent space from getting taken up in the params Hash.
1341             specialBoxProperties.put("KeyPressed", new SpecialBoxProperty());
1342             specialBoxProperties.put("KeyReleased", new SpecialBoxProperty());
1343             specialBoxProperties.put("PosChange", new SpecialBoxProperty());
1344             specialBoxProperties.put("SizeChange", new SpecialBoxProperty());
1345
1346             //#repeat hpad/vpad 
1347             specialBoxProperties.put("hpad", new SpecialBoxProperty() {
1348                     public Object get(Box b) {
1349                         if (b.redirect == null) return new Integer(0);
1350                         if (b.redirect != b) return get(b.redirect);
1351                         return new Integer(b.hpad);
1352                     }
1353                     public void put(Box b, Object value) {
1354                         if (b.redirect == null) return;
1355                         if (b.redirect != b) { put(b.redirect, value); return; }
1356                         int newval = stoi(value);
1357                         if (newval == b.hpad) return;
1358                         b.hpad = newval;
1359                         MARK_FOR_REFLOW_b;
1360                     }
1361                 });
1362             //#end
1363
1364             //#repeat minwidth/minheight maxwidth/maxheight
1365             specialBoxProperties.put("minwidth", new SpecialBoxProperty() {
1366                     public Object get(Box b) { return new Integer(b.minwidth); }
1367                     public void put(Box b, Object value) {
1368                         if (stoi(value) == b.minwidth) return;
1369                         b.minwidth = stoi(value);
1370                         MARK_FOR_REFLOW_b;
1371                     }
1372                 });
1373             specialBoxProperties.put("maxwidth", new SpecialBoxProperty() {
1374                     public Object get(Box b) { return new Integer(b.maxwidth); }
1375                     public void put(Box b, Object value) {
1376                         if (stoi(value) == b.maxwidth) return;
1377                         b.maxwidth = stoi(value);
1378                         MARK_FOR_REFLOW_b;
1379                     }
1380                 });
1381             //#end
1382
1383             specialBoxProperties.put("redirect", new SpecialBoxProperty() {
1384                     public void put(Box b, Object value) { }
1385                     public Object get(Box b) {
1386                         if (b.redirect == null) return null;
1387                         if (b.redirect == b) return Boolean.TRUE;
1388                         return get(b.redirect);
1389                     }
1390                 });
1391
1392             // FEATURE: this still isn't totally harmonious; when you createSurface, these aren't checked
1393             specialBoxProperties.put("titlebar", new SpecialBoxProperty() {
1394                     public void put(Box b, Object value) {
1395                         if (b.surface != null) b.surface.setTitleBarText(value.toString());
1396                         b.put_("titlebar", value);
1397                     }
1398                     public Object get(Box b) { return b.get_("titlebar"); }
1399                 });
1400
1401             specialBoxProperties.put("icon", new SpecialBoxProperty() {
1402                     public void put(Box b, Object value) {
1403                         b.put_("icon", value);
1404                         if (b.surface == null) return;
1405                         Picture pic = ImageDecoder.getPicture(value.toString());
1406                         if (pic != null) b.surface.setIcon(pic);
1407                         else if (Log.on) Log.log(this, "unable to load icon " + value);
1408                     }
1409                     public Object get(Box b) { return b.get_("icon"); }
1410                 });
1411         }
1412     }
1413
1414     /** helper that converts a String to a boolean according to JavaScript coercion rules */
1415     public static boolean stob(Object o) {
1416         if (o == null) return false;
1417         return Boolean.TRUE.equals(o) || "true".equals(o);
1418     }
1419
1420     /** helper that converts a String to an int according to JavaScript coercion rules */
1421     public static int stoi(Object o) {
1422         if (o == null) return 0;
1423         if (o instanceof Integer) return ((Integer)o).intValue();
1424         
1425         String s;
1426         if (!(o instanceof String)) s = o.toString();
1427         else s = (String)o;
1428         
1429         try { return Integer.parseInt(s.indexOf('.') == -1 ? s : s.substring(0, s.indexOf('.'))); }
1430         catch (NumberFormatException e) { return 0; }
1431     }
1432 }
1433         
1434
1435