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