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