5c7a24266219c49396a3adc8116ab09f65398c24
[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
546         if (value != null && !(value instanceof Box)) {
547             if (Log.on) Log.logJS(this, "attempt to set a numerical property on a box to anything other than a box");
548         } else if (redirect == null) {
549             if (Log.on) Log.logJS(this, "attempt to add/remove children to/from a node with a null redirect");
550             put("0", (Box)value);
551         } else if (redirect != this) {
552             Box b = value == null ? (Box)redirect.get(i) : (Box)value;
553             redirect.put(i, value);
554             put("0", b);
555         } else if (value == null) {
556             if (i >= 0 && i < numChildren()) {
557                 Box b = getChild(i);
558                 b.remove();
559                 put("0", b);
560             }
561         } else {
562             Box newnode = (Box)value;
563
564             // check if box being moved is currently target of a redirect
565             for(Box cur = newnode.parent; cur != null; cur = cur.parent)
566                 if (cur.redirect == newnode) {
567                     if (Log.on) Log.logJS(this, "attempt to move a box that is the target of a redirect");
568                     return;
569                 }
570
571             // check for recursive ancestor violation
572             for(Box cur = this; cur != null; cur = cur.parent)
573                 if (cur == newnode) {
574                     if (Log.on) Log.logJS(this, "attempt to make a node a parent of its own ancestor");
575                     if (Log.on) Log.log(this, "box == " + this + "  ancestor == " + newnode);
576                     return;
577                 }
578
579             if (numKids > 15 && children == null) convert_to_array();
580             newnode.remove();
581             newnode.parent = this;
582             
583             if (children == null) {
584                 if (firstKid == null) {
585                     firstKid = newnode;
586                     newnode.prevSibling = newnode;
587                     newnode.nextSibling = newnode;
588                 } else if (i >= numKids) {
589                     newnode.prevSibling = firstKid.prevSibling;
590                     newnode.nextSibling = firstKid;
591                     firstKid.prevSibling.nextSibling = newnode;
592                     firstKid.prevSibling = newnode;
593                 } else {
594                     Box cur = firstKid;
595                     for(int j=0; j<i; j++) cur = cur.nextSibling;
596                     newnode.prevSibling = cur.prevSibling;
597                     newnode.nextSibling = cur;
598                     cur.prevSibling.nextSibling = newnode;
599                     cur.prevSibling = newnode;
600                     if (i == 0) firstKid = newnode;
601                 }
602                 numKids++;
603                 
604             } else {
605                 if (i >= children.size()) {
606                     newnode.indexInParent = children.size();
607                     children.addElement(newnode);
608                 } else {
609                     children.insertElementAt(newnode, i);
610                     for(int j=i; j<children.size(); j++)
611                         getChild(j).indexInParent = j;
612                 }
613             }
614             
615             // need both of these in case child was already uncalc'ed
616             Box b = newnode; 
617             MARK_FOR_REFLOW_b;
618             MARK_FOR_REFLOW_this;
619             
620             newnode.dirty();
621
622             // note that JavaScript box[0] will invoke put(int i), not put(String s)
623             put("0", newnode);
624         }
625     }
626     
627     public Object get(Object key, Object key2) { return super.get(key, key2); }
628     public void put(Object key, Object key2, Object val) { super.put(key, key2, val); }
629
630     public Object get_(Object name) { return super.get(name); }
631     public Object get(Object name) { return get(name, false); }
632     public Object get(Object name_, boolean ignoretraps) {
633         if (name_ instanceof Number) return get(((Number)name_).intValue());
634
635         if (!(name_ instanceof String)) return null;
636         String name = (String)name_;
637         if (name.equals("")) return null;
638
639         // See if we're triggering a trap
640         Trap t = ignoretraps ? (Trap)null : (Trap)get(name, Trap.class);
641         if (t != null) return t.perform();
642
643         // Check for a special handler
644         SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
645         if (gph != null) return gph.get(this);
646
647         Object ret = super.get(name);
648         if (name.startsWith("$") && ret == null)
649             if (Log.on) Log.logJS(this, "WARNING: attempt to access " + name + ", but no child with id=\"" +
650                                   name.substring(1) + "\" found");
651         return ret;
652     }
653
654     public Object[] keys() {
655         Object[] ret = new Object[numChildren()];
656         for(int i=0; i<ret.length; i++) ret[i] = new Integer(i);
657         return ret;
658     }
659
660     public void addTrap(Object name, Object value) { Trap.addTrap(this, name, ((JS.CompiledFunction)value)); }
661     public void delTrap(Object name, Object value) { Trap.delTrap(this, name, ((JS.CompiledFunction)value)); }
662
663
664     /**
665      *  Scriptable.put()
666      *  @param ignoretraps if set, no traps will be triggered (set when 'cascade' reaches the bottom of the trap stack)
667      *  @param rp if this put is being performed via a root proxy, rp is the root proxy.
668      */
669     public void put_(Object name, Object value) { super.put(name, value); }
670     public void put(Object name, Object value) { put(name, value, false); }
671     public void put(Object name_, Object value, boolean ignoretraps) {
672         if (name_ instanceof Number) { put(((Number)name_).intValue(), value); return; }
673         if (!(name_ instanceof String)) { super.put(name_,value); return; }
674         String name = name_.toString();
675         if (!ignoretraps) {
676             Trap t = (Trap)get(name, Trap.class);
677             if (t != null) {
678                 t.perform(value);
679                 return;
680             }
681         }
682
683         // don't want to really cascade down to the box on this one
684         if (name.equals("0")) return;
685
686         SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
687         if (gph != null) { gph.put(name, this, value); return; }
688
689         super.put(name, value);
690     }
691
692
693     // Tree Manipulation /////////////////////////////////////////////////////////////////////
694
695     /** The parent of this node */
696     private Box parent = null;
697     
698     // Variables used in Vector mode */
699     /** INVARIANT: if (parent != null) parent.children.elementAt(indexInParent) == this */
700     private int indexInParent;
701     private Vec children = null;
702
703     // Variables used in linked-list mode
704     private int numKids = 0;
705     private Box nextSibling = null;
706     private Box prevSibling = null;
707     private Box firstKid = null;
708     
709     // when we get more than 15 children, we switch to array-mode
710     private void convert_to_array() {
711         children = new Vec(numKids);
712         Box cur = firstKid;
713         do {
714             children.addElement(cur);
715             cur.indexInParent = children.size() - 1;
716             cur = cur.nextSibling;
717         } while (cur != firstKid);
718     }
719     
720     /** remove this node from its parent; INVARIANT: whenever the parent of a node is changed, remove() gets called. */
721     public void remove() {
722         if (parent == null) {
723             if (surface != null) surface.dispose(true);
724             return;
725         }
726         Box oldparent = parent;
727         if (oldparent == null) return;
728         MARK_FOR_REFLOW_this;
729         dirty();
730         flags &= ~MOUSEINSIDE_FLAG;
731
732         if (parent.children != null) {
733             parent.children.removeElementAt(indexInParent);
734             for(int j=indexInParent; j<parent.children.size(); j++)
735                 (parent.getChild(j)).indexInParent = j;
736
737         } else {
738             if (parent.firstKid == this) {
739                 if (nextSibling == this) parent.firstKid = null;
740                 else parent.firstKid = nextSibling;
741             }
742             parent.numKids--;
743             prevSibling.nextSibling = nextSibling;
744             nextSibling.prevSibling = prevSibling;
745             prevSibling = null;
746             nextSibling = null;
747         }
748         parent = null;
749
750         if (oldparent != null) { Box b = oldparent; MARK_FOR_REFLOW_b; }
751
752         // note that JavaScript box[0] will invoke put(int i), not put(String s)
753         if (oldparent != null) oldparent.put("0", this);
754     }
755
756     /** returns our next sibling (parent[ourindex + 1]) */
757     public final Box nextSibling() {
758         if (parent == null) return null;
759         if (parent.children == null) {
760             if (nextSibling == parent.firstKid) return null;
761             return nextSibling;
762         } else {
763             if (indexInParent >= parent.children.size() - 1) return null;
764             return (Box)parent.children.elementAt(indexInParent + 1);
765         }
766     }
767     
768     /** returns our next sibling (parent[ourindex + 1]) */
769     public final Box prevSibling() {
770         if (parent == null) return null;
771         if (parent.children == null) {
772             if (this == parent.firstKid) return null;
773             return prevSibling;
774         } else {
775             if (indexInParent == 0) return null;
776             return (Box)parent.children.elementAt(indexInParent - 1);
777         }
778     }
779     
780     /** Returns the parent of this node */
781     public Box getParent() { return parent; }
782     
783     /** Returns ith child */
784     public Box getChild(int i) {
785         if (children == null) {
786             if (firstKid == null) return null;
787             if (i >= numKids) return null;
788             if (i == numKids - 1) return firstKid.prevSibling;
789             Box cur = firstKid;
790             for(int j=0; j<i; j++) cur = cur.nextSibling;
791             return cur;
792         } else {
793             if (i >= children.size() || i < 0) return null;
794             return (Box)children.elementAt(i);
795         }
796     }
797     
798     /** Returns the number of children */
799     public int numChildren() {
800         if (children == null) {
801             if (firstKid == null) return 0;
802             int i=1;
803             for(Box cur = firstKid.nextSibling; cur != firstKid; i++) cur = cur.nextSibling;
804             return i;
805         } else {
806             return children.size();
807         }
808     }
809     
810     /** Returns our index in our parent */
811     public int getIndexInParent() {
812         if (parent == null) return 0;
813         if (parent.children == null) {
814             int i = 0;
815             for(Box cur = this; cur != parent.firstKid; i++) cur = cur.prevSibling;
816             return i;
817         } else {
818             return indexInParent;
819         }
820     }
821
822     /** returns the root of the surface that this box belongs to */
823     public final Box getRoot() {
824         if (parent == null && surface != null) return this;
825         if (parent == null) return null;
826         return parent.getRoot();
827     }
828
829
830     // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
831
832     static final int min(int a, int b) { if (a<b) return a; else return b; }
833     static final float min(float a, float b) { if (a<b) return a; else return b; }
834     static final double min(double a, double b) { if (a<b) return a; else return b; }
835     static final int max(int a, int b) { if (a>b) return a; else return b; }
836     static final float max(float a, float b) { if (a>b) return a; else return b; }
837     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; }
838     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; }
839     static final int bound(int a, int b, int c) { if (c < b) return c; if (a > b) return a; return b; }
840     final boolean inside(int x, int y) { return (!((flags & INVISIBLE_FLAG) != 0) && x >= 0 && y >= 0 && x < width && y < height); }
841     
842     /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface */
843     public static Box whoIs(Box cur, int x, int y) {
844
845         if (cur.parent != null) throw new Error("whoIs may only be invoked on the root box of a surface");
846         int globalx = 0;
847         int globaly = 0;
848
849         // WARNING: this method is called from the event-queueing
850         // thread -- it may run concurrently with ANY part of XWT, and
851         // is UNSYNCHRONIZED for performance reasons.  BE CAREFUL
852         // HERE.
853
854         if ((cur.flags & INVISIBLE_FLAG) != 0) return null;
855         if (!cur.inside(x - globalx, y - globaly)) return cur.parent == null ? cur : null;
856         OUTER: while(true) {
857             for(int i=cur.numChildren() - 1; i>=0; i--) {
858                 Box child = cur.getChild(i);
859                 if (child == null) continue;        // since this method is unsynchronized, we have to double-check
860                 globalx += child.x;
861                 globaly += child.y;
862                 if (!((child.flags & INVISIBLE_FLAG) != 0) && child.inside(x - globalx, y - globaly)) { cur = child; continue OUTER; }
863                 globalx -= child.x;
864                 globaly -= child.y;
865             }
866             break;
867         }
868         return cur;
869     }
870
871     /** 
872      *  A helper class for properties of Box which require special
873      *  handling.
874      *
875      *  To avoid excessive use of String.equals(), the Box.get() and
876      *  Box.put() methods employ a Hash keyed on property names that
877      *  require special handling. The value stored in the Hash is an
878      *  instance of an anonymous subclass of SpecialBoxProperty, which knows
879      *  how to handle get()s and put()s for that property name. There
880      *  should be one anonymous subclass of SpecialBoxProperty for each
881      *  specially-handled property on Box.
882      */
883     static class SpecialBoxProperty {
884
885         SpecialBoxProperty() { }
886
887         /** stores instances of SpecialBoxProperty; keyed on property name */
888         static Hash specialBoxProperties = new Hash(200, 3);
889
890         /** this method defines the behavior when the property is get()ed from b */
891         Object get(Box b) { return null; }
892
893         /** this method defines the behavior when the property is put() to b */
894         void put(Box b, Object value) { }
895
896         /** this method defines the behavior when the property is put() to b, allows a single SpecialBoxProperty to serve multiple properties */
897         void put(String name, Box b, Object value) { put(b, value); }
898
899         static {
900             specialBoxProperties.put("fill", new ColorBoxProperty() {
901                     public int getColor(Box b) { return b.fillcolor; }
902                     public void putColor(Box b, int argb) { b.fillcolor = argb; }
903                 });
904             specialBoxProperties.put("textcolor", new ColorBoxProperty() {
905                     public int getColor(Box b) { return b.textcolor; }
906                     public void putColor(Box b, int argb) { b.textcolor = argb; }
907                 });
908             specialBoxProperties.put("strokecolor", new ColorBoxProperty() {
909                     public int getColor(Box b) { return b.strokecolor; }
910                     public void putColor(Box b, int argb) { b.strokecolor = argb; }
911                 });
912
913             specialBoxProperties.put("text", new SpecialBoxProperty() {
914                     public Object get(Box b) { return b.text; }
915                     public void put(Box b, Object value) {
916                         String t = value == null ? "null" : value.toString();
917                         if (t.equals(b.text)) return;
918                         b.text = t;
919                         if (t == null) {
920                             if (b.textwidth != 0 || b.textheight != 0) MARK_FOR_REFLOW_b;
921                             b.textwidth = b.textheight = 0;
922                         } else {
923                             try {
924                                 MARK_FOR_REFLOW_b;
925                                 b.textwidth = 0;
926                                 for(int i=0; i<b.text.length(); i++) {
927                                     Glyph g = Glyph.getGlyph(b.font, b.fontsize, b.text.charAt(i));
928                                     b.textwidth += g.advance;
929                                     b.textheight = g.max_ascent + g.max_descent;
930                                 }
931                             } catch (Exception e) {
932                                 Log.log(this, e);
933                             }
934                         }
935                         b.dirty();
936                     } });
937
938             specialBoxProperties.put("path", new SpecialBoxProperty() {
939                     public Object get(Box b) { throw new JS.Exn("cannot read from the path property"); }
940                     public void put(Box b, Object value) {
941                         String t = value == null ? "null" : value.toString();
942                         b.path = value == null ? null : VectorGraphics.parseVectorPath(value.toString());
943                         MARK_FOR_REFLOW_b;
944                         b.dirty();
945                     } });
946
947             specialBoxProperties.put("transform", new SpecialBoxProperty() {
948                     public void put(Box b, Object value) {
949                         String t = value.toString().trim();
950                         b.transform = VectorGraphics.Affine.identity();
951                         while (t.length() > 0) {
952                             if (t.startsWith("skewX(")) {
953                                 // FIXME
954                                 
955                             } else if (t.startsWith("shear(")) {
956                                 // FIXME: nonstandard; remove this
957                                 b.transform.multiply(VectorGraphics.Affine.shear(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(')')))));
958                                 
959                             } else if (t.startsWith("skewY(")) {
960                                 // FIXME
961                                 
962                             } else if (t.startsWith("rotate(")) {
963                                 String sub = t.substring(t.indexOf('(') + 1, t.indexOf(')'));
964                                 if (sub.indexOf(',') != -1) {
965                                     float angle = Float.parseFloat(sub.substring(0, sub.indexOf(',')));
966                                     sub = sub.substring(sub.indexOf(',') + 1);
967                                     float cx = Float.parseFloat(sub.substring(0, sub.indexOf(',')));
968                                     sub = sub.substring(sub.indexOf(',') + 1);
969                                     float cy = Float.parseFloat(sub);
970                                     b.transform.multiply(VectorGraphics.Affine.translate(cx, cy));
971                                     b.transform.multiply(VectorGraphics.Affine.rotate(angle));
972                                     b.transform.multiply(VectorGraphics.Affine.translate(-1 * cx, -1 * cy));
973                                 } else {
974                                     b.transform.multiply(VectorGraphics.Affine.rotate(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(')')))));
975                                 }
976                                 
977                             } else if (t.startsWith("translate(")) {
978                                 String sub = t.substring(t.indexOf('(') + 1, t.indexOf(')'));
979                                 if (sub.indexOf(',') > -1) {
980                                     b.transform.multiply(VectorGraphics.Affine.translate(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(','))),
981                                                                                          Float.parseFloat(t.substring(t.indexOf(',') + 1, t.indexOf(')')))));
982                                 } else {
983                                     b.transform.multiply(VectorGraphics.Affine.translate(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(','))), 0));
984                                 }
985                                 
986                             } else if (t.startsWith("flip(")) {
987                                 String which = t.substring(t.indexOf('(') + 1, t.indexOf(')'));
988                                 b.transform.multiply(VectorGraphics.Affine.flip(which.equals("horizontal"), which.equals("vertical")));
989                                 
990                             } else if (t.startsWith("scale(")) {
991                                 String sub = t.substring(t.indexOf('(') + 1, t.indexOf(')'));
992                                 if (sub.indexOf(',') > -1) {
993                                     b.transform.multiply(VectorGraphics.Affine.scale(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(','))),
994                                                                                      Float.parseFloat(t.substring(t.indexOf(',') + 1, t.indexOf(')')))));
995                                 } else {
996                                     b.transform.multiply(VectorGraphics.Affine.scale(Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(','))),
997                                                                                      Float.parseFloat(t.substring(t.indexOf('(') + 1, t.indexOf(',')))));
998                                 }
999                                 
1000                             } else if (t.startsWith("matrix(")) {
1001                                 // FIXME: is this mapped right?
1002                                 float d[] = new float[6];
1003                                 StringTokenizer st = new StringTokenizer(t, ",", false);
1004                                 for(int i=0; i<6; i++)
1005                                     d[i] = Float.parseFloat(st.nextToken());
1006                                 b.transform.multiply(new VectorGraphics.Affine(d[0], d[1], d[2], d[3], d[4], d[5]));
1007                             }
1008                             t = t.substring(t.indexOf(')') + 1).trim();
1009                         }
1010                         MARK_FOR_REFLOW_b;
1011                         b.dirty();
1012                     }
1013                     public Object get(Box b) { return b.transform.toString(); }
1014                 });
1015             
1016             specialBoxProperties.put("font", new SpecialBoxProperty() {
1017                     public Object get(Box b) { return b.font; }
1018                     public void put(Box b, Object value) {
1019                         // FIXME: translate value into a resource if it is a string
1020                         b.font = value == null ? null : (Res)value;
1021                         MARK_FOR_REFLOW_b;
1022                         b.flags |= FONT_CHANGED_FLAG;
1023                         b.dirty();
1024                     } });
1025         
1026             specialBoxProperties.put("fontsize", new SpecialBoxProperty() {
1027                     public Object get(Box b) { return b.font; }
1028                     public void put(Box b, Object value) {
1029                         if (b.fontsize == stoi(value)) return;
1030                         b.fontsize = stoi(value);
1031                         MARK_FOR_REFLOW_b;
1032                         b.flags |= FONT_CHANGED_FLAG;
1033                         b.dirty();
1034                     } });
1035         
1036             specialBoxProperties.put("strokewidth", new SpecialBoxProperty() {
1037                     public Object get(Box b) { return new Integer(b.strokewidth); }
1038                     public void put(Box b, Object value) {
1039                         if (b.strokewidth == stoi(value)) return;
1040                         b.strokewidth = stoi(value);
1041                         b.dirty();
1042                     } });
1043         
1044             specialBoxProperties.put("thisbox", new SpecialBoxProperty() {
1045                     public Object get(Box b) { return b; }
1046                     public void put(Box b, Object value) {
1047                         if (value == null) b.remove();
1048                         else if (value.equals("window") || value.equals("frame")) Platform.createSurface(b, value.equals("frame"), true);
1049                         else if (Log.on) Log.log(this, "put invalid value to 'thisbox' property: " + value);
1050                     }
1051                 });
1052
1053             specialBoxProperties.put("orient", new SpecialBoxProperty() {
1054                     public Object get(Box b) {
1055                         Log.log(this, "warning: the orient property is deprecated");
1056                         if (b.redirect == null) return "horizontal";
1057                         else if (b.redirect != b) return get(b.redirect);
1058                         else if (b.cols == 1) return "vertical";
1059                         else if (b.rows == 1) return "horizontal";
1060                         else return "grid";
1061                     }
1062                     public void put(Box b, Object value) {
1063                         Log.log(this, "warning: the orient property is deprecated");
1064                         if (value == null) return;
1065                         if (b.redirect == null) return;
1066                         if (b.redirect != b) { put(b.redirect, value); return; }
1067                         if (value.equals("vertical")) {
1068                             if (b.rows == 0) return;
1069                             b.rows = 0; b.cols = 1;
1070                         } else if (value.equals("horizontal")) {
1071                             if (b.cols == 0) return;
1072                             b.cols = 0; b.rows = 1;
1073                         } else if (Log.on)
1074                             Log.log(this, "invalid value put to orient property: " + value);
1075                         MARK_FOR_REFLOW_b;
1076                     } });
1077
1078             specialBoxProperties.put("shrink", new SpecialBoxProperty() {
1079                     public Object get(Box b) { return (((b.flags & HSHRINK_FLAG) != 0) || ((b.flags & VSHRINK_FLAG) != 0)) ? Boolean.TRUE : Boolean.FALSE; }
1080                     public void put(Box b, Object value) { b.put("hshrink", value); b.put("vshrink", value); }
1081                 });
1082         
1083             //#repeat hshrink/vshrink HSHRINK_FLAG/VSHRINK_FLAG
1084             specialBoxProperties.put("hshrink", new SpecialBoxProperty() {
1085                     public Object get(Box b) { return new Boolean((b.flags & HSHRINK_FLAG) != 0); }
1086                     public void put(Box b, Object value) {
1087                         boolean newshrink = stob(value);
1088                         if (((b.flags & HSHRINK_FLAG) != 0) == newshrink) return;
1089                         if (newshrink) b.flags |= HSHRINK_FLAG; else b.flags &= ~HSHRINK_FLAG;
1090                         MARK_FOR_REFLOW_b;
1091                     }
1092                 });
1093             //#end
1094         
1095             //#repeat x/y
1096             specialBoxProperties.put("x", new SpecialBoxProperty() {
1097                     public Object get(Box b) {
1098                         if (b.surface == null) return new Integer(0);
1099                         if ((b.flags & INVISIBLE_FLAG) != 0) return new Integer(0);
1100                         return new Integer(b.x);
1101                     }
1102                     public void put(Box b, Object value) {
1103                         if (!((b.flags & NOTPACKED_FLAG) != 0)) return;
1104                         int x = stoi(value);
1105                         if (x == b.x) return;
1106                         b.dirty();
1107                         b.x = x;
1108                         if (b.parent == null && b.surface != null) b.surface.setLocation();
1109                         MARK_FOR_REFLOW_b;
1110                         b.dirty();
1111                     }
1112                 });
1113             //#end
1114         
1115             //#repeat width/height minwidth/minheight maxwidth/maxheight
1116             specialBoxProperties.put("width", new SpecialBoxProperty() {
1117                     public Object get(Box b) { return new Integer(b.width); }
1118                     public void put(Box b, Object value) {
1119                         b.width = stoi(value);
1120                         if (b.parent == null && b.surface != null) {
1121                             b.surface.setSize();
1122                             MARK_FOR_REFLOW_b;
1123                         } else {
1124                             if (b.minwidth == b.width && b.maxwidth == b.width) return;
1125                             b.minwidth = b.maxwidth = b.width;
1126                             MARK_FOR_REFLOW_b;
1127                         }
1128                     } });
1129             //#end
1130
1131             //#repeat cols/rows rows/cols
1132             specialBoxProperties.put("cols", new SpecialBoxProperty() {
1133                     public Object get(Box b) { return new Double(b.cols); }
1134                     public void put(Box b, Object value) {
1135                         if (b.cols == stoi(value)) return;
1136                         b.cols = stoi(value);
1137                         if (b.cols == 0 && b.rows == 0) b.rows = 1;
1138                         if (b.cols != 0 && b.rows != 0) b.rows = 0;
1139                         MARK_FOR_REFLOW_b;
1140                     } });
1141             //#end
1142         
1143             //#repeat colspan/rowspan
1144             specialBoxProperties.put("colspan", new SpecialBoxProperty() {
1145                     public Object get(Box b) { return new Double(b.colspan); }
1146                     public void put(Box b, Object value) {
1147                         if (b.colspan == stoi(value)) return;
1148                         b.colspan = stoi(value);
1149                         MARK_FOR_REFLOW_b;
1150                     }
1151                 });
1152             //#end
1153         
1154             specialBoxProperties.put("tile", new SpecialBoxProperty() {
1155                     public Object get(Box b) { return ((b.flags & TILE_FLAG) != 0) ? Boolean.TRUE : Boolean.FALSE; }
1156                     public void put(Box b, Object value) {
1157                         if (((b.flags & TILE_FLAG) != 0) == stob(value)) return;
1158                         if (stob(value)) b.flags |= TILE_FLAG; else b.flags &= ~TILE_FLAG;
1159                         b.dirty();
1160                     } });
1161         
1162             specialBoxProperties.put("noclip", new SpecialBoxProperty() {
1163                     public Object get(Box b) { return ((b.flags & NOCLIP_FLAG) != 0) ? Boolean.TRUE : Boolean.FALSE; }
1164                     public void put(Box b, Object value) {
1165                         if (((b.flags & NOCLIP_FLAG) != 0) == stob(value)) return;
1166                         if (stob(value)) b.flags |= NOCLIP_FLAG; else b.flags &= ~NOCLIP_FLAG;
1167                         MARK_FOR_REFLOW_b;
1168                         b.dirty();
1169                     } });
1170         
1171             specialBoxProperties.put("visible", new SpecialBoxProperty() {
1172                     public Object get(Box b) {
1173                         for (Box cur = b; cur != null; cur = cur.parent) {
1174                             if ((cur.flags & INVISIBLE_FLAG) != 0) return Boolean.FALSE; }
1175                         return Boolean.TRUE;
1176                     }
1177                     public void put(Box b, Object value) {
1178                         if (!stob(value) == ((b.flags & INVISIBLE_FLAG) != 0)) return;
1179                         if (!stob(value)) b.flags |= INVISIBLE_FLAG; else b.flags &= ~INVISIBLE_FLAG;
1180                         if (b.parent == null) {
1181                             if (b.surface != null) b.surface.setInvisible((b.flags & INVISIBLE_FLAG) != 0);
1182                         } else {
1183                             b.dirty();
1184                             MARK_FOR_REFLOW_b_parent;
1185                             b.parent.dirty(b.x, b.y, b.width, b.height);
1186                         }
1187                     }});
1188         
1189             specialBoxProperties.put("packed", new SpecialBoxProperty() {
1190                     public Object get(Box b) { return ((b.flags & NOTPACKED_FLAG) != 0) ? Boolean.TRUE : Boolean.FALSE; }
1191                     public void put(Box b, Object value) {
1192                         if (stob(value) == ((b.flags & NOTPACKED_FLAG) == 0)) return;
1193                         if (!stob(value)) b.flags |= NOTPACKED_FLAG; else b.flags &= ~NOTPACKED_FLAG;
1194                         if ((b.flags & NOTPACKED_FLAG) != 0) { b.x = 0; b.y = 0; }
1195                         if (b.parent != null) MARK_FOR_REFLOW_b_parent;
1196                     } });
1197         
1198             specialBoxProperties.put("image", new SpecialBoxProperty() {
1199                     /* FIXME
1200                     public Object get(Box b) { return b.image == null ? null : ImageDecoder.imageToNameMap.get(b.image); }
1201                     */
1202                     public void put(Box b, Object value) {
1203                         //if (image != null) System.out.println("hit");
1204                         if (value == null) {
1205                             b.image = null;
1206                         } else if (value instanceof Res) {
1207                             b.image = Picture.fromRes((Res)value);
1208                         } else {
1209                             // FIXME
1210                         }
1211                         b.minwidth = min(b.maxwidth, max(b.minwidth, b.image == null ? 0 : b.image.getWidth()));
1212                         b.minheight = min(b.maxheight, max(b.minheight, b.image == null ? 0 : b.image.getHeight()));
1213                         MARK_FOR_REFLOW_b;
1214                         b.dirty();
1215                     }
1216                 });
1217
1218             //#repeat globalx/globaly x/y
1219             specialBoxProperties.put("globalx", new SpecialBoxProperty() {
1220                     public Object get(Box b) { return new Integer(b.parent == null || b.surface == null ? 0 : b.x); }
1221                     public void put(Box b, Object value) {
1222                         if (b.surface == null || b.parent == null) return;
1223                         b.put("x", new Integer(stoi(value) - stoi(get(b.parent))));
1224                         MARK_FOR_REFLOW_b;
1225                     }
1226                 });
1227             //#end
1228         
1229             specialBoxProperties.put("cursor", new SpecialBoxProperty() {
1230                     public Object get(Box b) { return b.cursor; } 
1231                     public void put(Box b, Object value) {
1232                         b.cursor = (String)value;
1233                         if (b.surface == null) return;
1234
1235                         // see if we need to update the surface cursor
1236                         Surface surface = b.getRoot().surface;
1237                         String tempcursor = surface.cursor;
1238                         b.Move(surface.mousex, surface.mousey, surface.mousex, surface.mousey);
1239                         if (surface.cursor != tempcursor) surface.syncCursor();
1240                     } 
1241                 });
1242         
1243             //#repeat mousex/mousey x/y
1244             specialBoxProperties.put("mousex", new SpecialBoxProperty() {
1245                     public Object get(Box b) {
1246                         Surface surface = b.getRoot().surface;
1247                         if (surface == null) return new Integer(0);
1248                         int mousex = surface.mousex;
1249                         for(Box cur = b; cur != null && cur.parent != null; cur = cur.parent) mousex -= cur.x;
1250                         return new Integer(mousex);
1251                     }
1252                 });
1253             //#end
1254         
1255             specialBoxProperties.put("mouseinside", new SpecialBoxProperty() {
1256                     public Object get(Box b) {
1257                         return ((b.flags & MOUSEINSIDE_FLAG) != 0) ? Boolean.TRUE : Boolean.FALSE; }
1258                 });
1259         
1260             specialBoxProperties.put("numchildren", new SpecialBoxProperty() {
1261                     public Object get(Box b) {
1262                         if (b.redirect == null) return new Integer(0);
1263                         if (b.redirect != b) return get(b.redirect);
1264                         return new Integer(b.numChildren());
1265                     } });
1266         
1267             SpecialBoxProperty mouseEventHandler = new SpecialBoxProperty() {
1268                     public void put(String name, Box b, Object value) {
1269                         Surface surface = b.getRoot().surface;
1270                         if (surface == null) return;
1271                         int mousex = surface.mousex;
1272                         int mousey = surface.mousey;
1273                         for(Box c = b.parent; c != null && c.parent != null; c = c.parent) {
1274                             mousex -= c.x;
1275                             mousey -= c.y;
1276                         }
1277                         for(Box c = b.prevSibling(); c != null; c = c.prevSibling()) {
1278                             if (c.inside(mousex - c.x, mousey - c.y)) {
1279                                 c.put(name, value);
1280                                 return;
1281                             }
1282                         }
1283                         if (b.parent != null) b.parent.put(name, value);
1284                     }};
1285
1286             specialBoxProperties.put("Press1", mouseEventHandler);
1287             specialBoxProperties.put("Press2", mouseEventHandler);
1288             specialBoxProperties.put("Press3", mouseEventHandler);
1289             specialBoxProperties.put("Release1", mouseEventHandler);
1290             specialBoxProperties.put("Release2", mouseEventHandler);
1291             specialBoxProperties.put("Release3", mouseEventHandler);
1292             specialBoxProperties.put("Click1", mouseEventHandler);
1293             specialBoxProperties.put("Click2", mouseEventHandler);
1294             specialBoxProperties.put("Click3", mouseEventHandler);
1295             specialBoxProperties.put("DoubleClick1", mouseEventHandler);
1296             specialBoxProperties.put("DoubleClick2", mouseEventHandler);
1297             specialBoxProperties.put("DoubleClick3", mouseEventHandler);
1298
1299             specialBoxProperties.put("root", new SpecialBoxProperty() {
1300                     public void put(Box b, Object value) {
1301                         if (stob(value)) b.flags |= ISROOT_FLAG;
1302                         else b.flags &= ~ISROOT_FLAG;
1303                     }
1304                     public Object get(Box b) {
1305                         if (b.parent == null || ((b.flags & ISROOT_FLAG) != 0)) return b;
1306                         else return get(b.parent);
1307                     } });
1308
1309             specialBoxProperties.put("Minimized", new SpecialBoxProperty() {
1310                     public Object get(Box b) {
1311                         if (b.parent == null && b.surface != null) return b.surface.minimized ? Boolean.TRUE : Boolean.FALSE;
1312                         else return null;
1313                     }
1314                     public void put(Box b, Object value) {
1315                         if (b.surface == null) return;
1316                         boolean val = stob(value);
1317                         if (b.parent == null && b.surface.minimized != val) b.surface.setMinimized(val);
1318                     }
1319                 });
1320
1321             specialBoxProperties.put("Maximized", new SpecialBoxProperty() {
1322                     public Object get(Box b) {
1323                         if (b.parent == null && b.surface != null) return b.surface.maximized ? 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.maximized != val) b.surface.setMaximized(val);
1330                     }
1331                 });
1332
1333             specialBoxProperties.put("toback", new SpecialBoxProperty() {
1334                     public void put(Box b, Object value) {
1335                         if (b.parent == null && stob(value) && b.surface != null) b.surface.toBack();
1336                     }
1337                 });
1338
1339             specialBoxProperties.put("tofront", new SpecialBoxProperty() {
1340                     public void put(Box b, Object value) {
1341                         if (b.parent == null && stob(value) && b.surface != null) b.surface.toFront();
1342                     }
1343                 });
1344
1345             specialBoxProperties.put("Close", new SpecialBoxProperty() {
1346                     public void put(Box b, Object value) {
1347                         if (b.parent == null && b.surface != null) b.surface.dispose(true);
1348                     }
1349                 });
1350
1351             // these are all do-nothings; just to prevent space from getting taken up in the params Hash.
1352             specialBoxProperties.put("KeyPressed", new SpecialBoxProperty());
1353             specialBoxProperties.put("KeyReleased", new SpecialBoxProperty());
1354             specialBoxProperties.put("PosChange", new SpecialBoxProperty());
1355             specialBoxProperties.put("SizeChange", new SpecialBoxProperty());
1356
1357             //#repeat minwidth/minheight maxwidth/maxheight
1358             specialBoxProperties.put("minwidth", new SpecialBoxProperty() {
1359                     public Object get(Box b) { return new Integer(b.minwidth); }
1360                     public void put(Box b, Object value) {
1361                         if (stoi(value) == b.minwidth) return;
1362                         b.minwidth = stoi(value);
1363                         MARK_FOR_REFLOW_b;
1364                     }
1365                 });
1366             specialBoxProperties.put("maxwidth", new SpecialBoxProperty() {
1367                     public Object get(Box b) { return new Integer(b.maxwidth); }
1368                     public void put(Box b, Object value) {
1369                         if (stoi(value) == b.maxwidth) return;
1370                         b.maxwidth = stoi(value);
1371                         MARK_FOR_REFLOW_b;
1372                     }
1373                 });
1374             //#end
1375
1376             specialBoxProperties.put("redirect", new SpecialBoxProperty() {
1377                     public void put(Box b, Object value) {
1378                         if (b.redirect != b) Log.log(this, "cannot change the redirect of a box once it is set");
1379                         else if (value == null) b.redirect = null;
1380                         else {
1381                             Box b2 = (Box)value;
1382                             while(b2 != b && b2 != null) b2 = b2.parent;
1383                             if (b2 == null) Log.log(this, "a box's redirect must be one of its descendants");
1384                             b.redirect = (Box)value;
1385                         }
1386                     }
1387                     public Object get(Box b) {
1388                         if (b.redirect == null) return null;
1389                         if (b.redirect == b) return Boolean.TRUE;
1390                         return get(b.redirect);
1391                     }
1392                 });
1393
1394             // FEATURE: this still isn't totally harmonious; when you createSurface, these aren't checked
1395             specialBoxProperties.put("titlebar", new SpecialBoxProperty() {
1396                     public void put(Box b, Object value) {
1397                         if (b.surface != null) b.surface.setTitleBarText(value.toString());
1398                         b.put_("titlebar", value);
1399                     }
1400                     public Object get(Box b) { return b.get_("titlebar"); }
1401                 });
1402
1403             specialBoxProperties.put("icon", new SpecialBoxProperty() {
1404                     // FIXME
1405                     /*
1406                     public void put(Box b, Object value) {
1407                         b.put_("icon", value);
1408                         if (b.surface == null) return;
1409                         Picture pic = ImageDecoder.getPicture(value.toString());
1410                         if (pic != null) b.surface.setIcon(pic);
1411                         else if (Log.on) Log.log(this, "unable to load icon " + value);
1412                     }
1413                     public Object get(Box b) { return b.get_("icon"); }
1414                     */
1415                 });
1416         }
1417
1418         private static abstract class ColorBoxProperty extends SpecialBoxProperty {
1419             public abstract int getColor(Box b);
1420             public abstract void putColor(Box b, int argb);
1421             public Object get(Box b) {
1422                 if ((getColor(b) & 0xFF000000) == 0) return null;
1423                 String red = Integer.toHexString((getColor(b) & 0x00FF0000) >> 16);
1424                 String green = Integer.toHexString((getColor(b) & 0x0000FF00) >> 8);
1425                 String blue = Integer.toHexString(getColor(b) & 0x000000FF);
1426                 if (red.length() < 2) red = "0" + red;
1427                 if (blue.length() < 2) blue = "0" + blue;
1428                 if (green.length() < 2) green = "0" + green;
1429                 return "#" + red + green + blue;
1430             }
1431             public void put(Box b, Object value) {
1432                 int newcolor = getColor(b);
1433                 String s = value == null ? null : value.toString();
1434                 if (value == null) newcolor = 0x00000000;
1435                 else if (s.length() > 0 && s.charAt(0) == '#')
1436                     try {
1437                         newcolor = 0xFF000000 |
1438                             (Integer.parseInt(s.substring(1, 3), 16) << 16) |
1439                             (Integer.parseInt(s.substring(3, 5), 16) << 8) |
1440                             Integer.parseInt(s.substring(5, 7), 16);
1441                     } catch (NumberFormatException e) {
1442                         Log.log(this, "invalid color " + s);
1443                         return;
1444                     }
1445                 else if (org.xwt.translators.SVG.colors.get(s) != null)
1446                     newcolor = 0xFF000000 | ((Integer)org.xwt.translators.SVG.colors.get(s)).intValue();
1447                 if (newcolor == getColor(b)) return;
1448                 putColor(b, newcolor);
1449                 b.dirty();
1450             }
1451         }
1452     }
1453
1454     /** helper that converts a String to a boolean according to JavaScript coercion rules */
1455     public static boolean stob(Object o) {
1456         if (o == null) return false;
1457         return Boolean.TRUE.equals(o) || "true".equals(o);
1458     }
1459
1460     /** helper that converts a String to an int according to JavaScript coercion rules */
1461     public static int stoi(Object o) {
1462         if (o == null) return 0;
1463         if (o instanceof Integer) return ((Integer)o).intValue();
1464         
1465         String s;
1466         if (!(o instanceof String)) s = o.toString();
1467         else s = (String)o;
1468         
1469         try { return Integer.parseInt(s.indexOf('.') == -1 ? s : s.substring(0, s.indexOf('.'))); }
1470         catch (NumberFormatException e) { return 0; }
1471     }
1472 }
1473         
1474
1475