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