2003/12/22 04:50:08
[org.ibex.core.git] / src / org / xwt / Box.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 // FEATURE: reflow before allowing js to read from width/height 
5 // FEATURE: fastpath for rows=1/cols=1
6 // FEATURE: mark to reflow starting with a certain child
7 // FEATURE: separate mark_for_reflow and mark_for_resize
8 // FEATURE: make all methods final
9 // FEATURE: use a linked list for the "frontier" when packing
10 // FEATURE:    or else have a way to mark a column "same as last one"?
11 // FEATURE: reintroduce surface.abort
12
13 import java.io.*;
14 import java.net.*;
15 import java.util.*;
16 import org.xwt.js.*;
17 import org.xwt.util.*;
18 import org.xwt.translators.*;
19
20 /**
21  *  <p>
22  *  Encapsulates the data for a single XWT box as well as all layout
23  *  rendering logic.
24  *  </p>
25  *
26  *  <p>The rendering process consists of four phases; each requires
27  *     one DFS pass over the tree</p>
28  *  <ol><li> <b>repacking</b>: children of a box are packed into columns
29  *           and rows according to their colspan/rowspan attributes and
30  *           ordering.
31  *  <ol><li> <b>reconstraining</b>: Minimum and maximum sizes of columns are computed.
32  *      <li> <b>resizing</b>: width/height and x/y positions of children
33  *           are assigned, and PosChange/SizeChanges are triggered.
34  *      <li> <b>repainting</b>: children draw their content onto the PixelBuffer.
35  *  </ol>
36  *
37  *  The first three passes together are called the <i>reflow</i> phase.
38  *  Reflowing is done in a seperate pass since PosChanges and
39  *  SizeChanges trigger an Surface.abort; if rendering were done in the same
40  *  pass, rendering work done prior to the Surface.abort would be wasted.
41  */
42 public final class Box extends JSScope implements Scheduler.Task {
43
44     // Macros //////////////////////////////////////////////////////////////////////
45
46     //#define LENGTH int
47     //#define MARK_REPACK for(Box b2 = this; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK);
48     //#define MARK_REPACK_b for(Box b2 = b; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK);
49     //#define MARK_REPACK_parent for(Box b2 = parent; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK);
50     //#define MARK_REFLOW for(Box b2 = this; b2 != null && !b2.test(REFLOW); b2 = b2.parent) b2.set(REFLOW);
51     //#define MARK_REFLOW_b for(Box b2 = b; b2 != null && !b2.test(REFLOW); b2 = b2.parent) b2.set(REFLOW);
52     //#define MARK_RESIZE for(Box b2 = this; b2 != null && !b2.test(RESIZE); b2 = b2.parent) b2.set(RESIZE);
53     //#define MARK_RESIZE_b for(Box b2 = b; b2 != null && !b2.test(RESIZE); b2 = b2.parent) b2.set(RESIZE);
54     //#define CHECKSET_SHORT(prop) short nu = (short)toInt(value); if (nu == prop) break; prop = nu;
55     //#define CHECKSET_INT(prop) int nu = toInt(value); if (nu == prop) break; prop = nu;
56     //#define CHECKSET_FLAG(flag) boolean nu = toBoolean(value); if (nu == test(flag)) break; if (nu) set(flag); else clear(flag);
57     //#define CHECKSET_BOOLEAN(prop) boolean nu = toBoolean(value); if (nu == prop) break; prop = nu;
58     //#define CHECKSET_STRING(prop) if ((value==null&&prop==null)||(value!=null&&value.equals(prop))) break; prop=(String)value;
59
60     void mark_for_repack() { MARK_REPACK; }
61
62     protected Box() { super(null); }
63
64     static Hash boxToCursor = new Hash(500, 3);
65     public static final int MAX_LENGTH = Integer.MAX_VALUE;
66     static final Font DEFAULT_FONT;
67    
68     static {
69         Font f = null;
70         try { f = Font.getFont((Res)Main.builtin.get("fonts/vera/Vera.ttf"), 10); }
71         catch(JSExn e) { Log.log(Box.class, "should never happen: "+e); }
72         DEFAULT_FONT = f;
73     }
74
75     // FIXME update these
76     // box properties can not be trapped
77     static final String[] props = new String[] {
78         "fill", "stroke", "image", "tile", "fixedaspect", "text", "path", "font",
79         "shrink", "hshrink", "vshrink", "x", "y", "width", "height", "cols", "rows",
80         "colspan", "rowspan", "align", "visible", "absolute", "globalx", "globaly",
81         "minwidth", "maxwidth", "minheight", "maxheight",
82         "numchildren", "redirect", "cursor", "mousex", "mousey", "xwt", "static",
83         "mouseinside", "root", "thisbox", "indexof"
84     };
85
86     // FIXME update these
87     // events can have write traps, but not read traps
88     static final String[] events = new String[] {
89         "Press1", "Press2", "Press3",
90         "Release1", "Release2", "Release3",
91         "Click1", "Click2", "Click3",
92         "DoubleClick1", "DoubleClick2", "DoubleClick3",
93         "Enter", "Leave", "Move", 
94         "KeyPressed", "KeyReleased", "PosChange", "SizeChange",
95         "childadded", "childremoved",
96         "Focused", "Maximized", "Minimized", "Close",
97         "icon", "titlebar", "toback", "tofront"
98     };
99
100     // Flags //////////////////////////////////////////////////////////////////////
101
102     static final int MOUSEINSIDE  = 0x00000001;
103     static final int VISIBLE      = 0x00000002;
104     static final int PACKED       = 0x00000004;
105     static final int HSHRINK      = 0x00000008;
106     static final int VSHRINK      = 0x00000010;
107     static final int BLACK        = 0x00000020;  // for red-black code
108
109     static final int FIXED        = 0x00000040;
110     static final boolean ROWS     = true;
111     static final boolean COLS     = false;
112
113     static final int ISROOT       = 0x00000080;
114     static final int REPACK       = 0x00000100;
115     static final int REFLOW       = 0x00000200;
116     static final int RESIZE       = 0x00000400;
117     static final int RECONSTRAIN  = 0x00000800;
118     static final int ALIGN_TOP    = 0x00001000;
119     static final int ALIGN_BOTTOM = 0x00002000;
120     static final int ALIGN_LEFT   = 0x00004000;
121     static final int ALIGN_RIGHT  = 0x00008000;
122     static final int ALIGNS       = 0x0000f000;
123     static final int CURSOR       = 0x00010000;  // if true, this box has a cursor in the cursor hash; FEATURE: GC issues?
124     static final int NOCLIP       = 0x00020000;
125     static final int STOP_UPWARD_PROPAGATION    = 0x00040000;
126
127
128     // Instance Data //////////////////////////////////////////////////////////////////////
129
130     Box parent = null;
131     Box redirect = this;
132     int flags = VISIBLE | PACKED | REPACK | REFLOW | RESIZE | FIXED /* ROWS */ | STOP_UPWARD_PROPAGATION;
133
134     private String text = null;
135     private Font font = DEFAULT_FONT; 
136     private Picture texture = null;
137     private short strokewidth = 1;
138     private int fillcolor = 0x00000000;
139     private int strokecolor = 0xFF000000;
140
141     private int aspect = 0;
142
143     // specified directly by user
144     public LENGTH minwidth = 0;
145     public LENGTH maxwidth = MAX_LENGTH;
146     public LENGTH minheight = 0;
147     public LENGTH maxheight = MAX_LENGTH;
148     private short rows = 1;
149     private short cols = 0;
150     private short rowspan = 1;
151     private short colspan = 1;
152
153     // computed during reflow
154     private short row = 0;
155     private short col = 0;
156     public LENGTH x = 0;
157     public LENGTH y = 0;
158     public LENGTH width = 0;
159     public LENGTH height = 0;
160     private LENGTH contentwidth = 0;      // == max(minwidth, textwidth, sum(child.contentwidth))
161     private LENGTH contentheight = 0;
162
163     /*
164     private VectorGraphics.VectorPath path = null;
165     private VectorGraphics.Affine transform = null;
166     private VectorGraphics.RasterPath rpath = null;
167     private VectorGraphics.Affine rtransform = null;
168     */
169
170     // Instance Methods /////////////////////////////////////////////////////////////////////
171
172
173     /** invoked when a resource needed to render ourselves finishes loading */
174     public void perform() throws JSExn {
175         // as external events have occured, check the state of box
176         if (texture != null) {
177            if (texture.isLoaded) { minwidth = texture.width; minheight = texture.height; }
178            else { Res res = texture.res; texture = null; throw new JSExn("image not found: "+res); }
179         }
180
181         MARK_REPACK;
182         MARK_REFLOW;
183         MARK_RESIZE;
184         dirty();
185     }
186
187     public Box getRoot() { return parent == null ? this : parent.getRoot(); }
188     public Surface getSurface() { return Surface.fromBox(getRoot()); }
189
190     // FEATURE: use cx2/cy2 format
191     /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
192     public void dirty() { dirty(0, 0, width, height); }
193     public void dirty(int x, int y, int w, int h) {
194         for(Box cur = this; cur != null; cur = cur.parent) {
195             if (!cur.test(NOCLIP)) {
196                 w = min(x + w, cur.width) - max(x, 0);
197                 h = min(y + h, cur.height) - max(y, 0);
198                 x = max(x, 0);
199                 y = max(y, 0);
200             }
201             if (w <= 0 || h <= 0) return;
202             if (cur.parent == null && cur.getSurface() != null) cur.getSurface().dirty(x, y, w, h);
203             x += cur.x;
204             y += cur.y;
205         }
206     }
207
208
209     // Reflow ////////////////////////////////////////////////////////////////////////////////////////
210
211     // static stuff so we don't have to keep reallocating
212     private static int[] numRowsInCol = new int[65535];
213     private static LENGTH[] colWidth = new LENGTH[65535];
214     private static LENGTH[] colMaxWidth = new LENGTH[65535];
215     private static LENGTH[] rowHeight = new LENGTH[65535];
216     private static LENGTH[] rowMaxHeight = new LENGTH[65535];
217     static { for(int i=0; i<rowMaxHeight.length; i++) { rowMaxHeight[i] = MAX_LENGTH; colMaxWidth[i] = MAX_LENGTH; } }
218
219     Box nextPackedSibling() { Box b = nextSibling(); return b == null || (b.test(PACKED | VISIBLE)) ? b : b.nextPackedSibling(); }
220     Box firstPackedChild() { Box b = getChild(0); return b == null || (b.test(PACKED | VISIBLE)) ? b : b.nextPackedSibling(); }
221
222     /** pack the boxes into rows and columns; also computes contentwidth */
223     void repack() {
224         for(Box child = getChild(0); child != null; child = child.nextSibling()) child.repack();
225
226         //#repeat COLS/ROWS rows/cols cols/rows col/row row/col colspan/rowspan rowspan/colspan 
227         if (test(FIXED) == COLS) {
228             short r = 0;
229             for(Box child = firstPackedChild(); child != null; r++) {
230                 for(short c=0, numclear=0; child != null && c < cols; c++) {
231                     if (numRowsInCol[c] > r) { numclear = 0; continue; }
232                     if (c != 0 && c + min(cols, child.colspan) - numclear > cols) break;
233                     if (++numclear < min(cols, child.colspan)) continue;
234                     for(int i=c - numclear + 1; i <= c; i++) numRowsInCol[i] += child.rowspan;
235                     child.col = (short)(c - numclear + 1); child.row = r;
236                     rows = (short)max(rows, child.row + child.rowspan);
237                     child = child.nextPackedSibling();
238                     numclear = 0;
239                 }
240             }
241             for(int i=0; i<cols; i++) numRowsInCol[i] = 0;
242         }
243         //#end
244
245         //#repeat contentwidth/contentheight colWidth/rowHeight colspan/rowspan col/row cols/rows minwidth/minheight \
246         //        textwidth/textheight maxwidth/maxheight
247         contentwidth = 0;
248         for(Box child = firstPackedChild(); child != null; child = child.nextPackedSibling())
249             colWidth[child.col] = max(colWidth[child.col], child.contentwidth / child.colspan);
250         for(int i=0; i<cols; i++) { contentwidth += colWidth[i]; colWidth[i] = 0; }
251         contentwidth = bound(minwidth, max(font == null || text == null ? 0 : font.textwidth(text), contentwidth), maxwidth);
252         //#end               
253     }
254     
255     void resize(LENGTH x, LENGTH y, LENGTH width, LENGTH height) {
256         // FEATURE reimplement, but we're destroying this
257         // FIXME: uncommenting this breaks; see http://bugs.xwt.org/show_bug.cgi?id=345
258         if (x != this.x || y != this.y || width != this.width || height != this.height) {
259             boolean sizechange = (this.width != width || this.height != height) && getTrap("SizeChange") != null;
260             boolean poschange = (this.x != x || this.y != y) && getTrap("PosChange") != null;
261             do {
262                 if (texture == null && (text == null || text.equals(""))) {
263                     if ((fillcolor & 0xff000000) == 0) break;
264                     // FEATURE: more optimizations here
265                     if (this.x == x && this.y == y) {
266                         Box who = (parent == null ? this : parent);
267                         who.dirty(min(this.x+this.width,x+width), y, Math.abs(width-this.width), max(this.height, height));
268                         who.dirty(x, min(this.y+this.height,y+height), max(this.width, width), Math.abs(height-this.height));
269                         break;
270                     }
271                 }
272                 (parent == null ? this : parent).dirty(this.x, this.y, this.width, this.height);
273                 this.width = width; this.height = height; this.x = x; this.y = y;
274                 dirty();
275             } while (false);
276             this.width = width; this.height = height; this.x = x; this.y = y;
277             if (sizechange) putAndTriggerTrapsAndCatchExceptions("SizeChange", T);
278             if (poschange)  putAndTriggerTrapsAndCatchExceptions("PosChange", T);
279         }
280     }
281
282     void resize_children() {
283
284         //#repeat col/row colspan/rowspan contentwidth/contentheight x/y width/height colMaxWidth/rowMaxHeight colWidth/rowHeight \
285         //        HSHRINK/VSHRINK maxwidth/maxheight cols/rows minwidth/minheight colWidth/rowHeight x_slack/y_slack
286         // PHASE 1: compute column min/max sizes
287         int x_slack = width;
288         for(int i=0; i<cols; i++) x_slack -= colWidth[i];
289         for(Box child = firstPackedChild(); child != null; child = child.nextPackedSibling())
290             for(int i=child.col; i < child.col + child.colspan; i++) {
291                 x_slack += colWidth[i];
292                 colWidth[i] = max(colWidth[i], child.contentwidth / child.colspan);
293                 x_slack -= colWidth[i];
294                 colMaxWidth[i] = min(colMaxWidth[i], child.test(HSHRINK) ? child.contentwidth : child.maxwidth) / child.colspan;
295             }
296         
297         // PHASE 2: hand out slack
298         for(int startslack = 0; x_slack > 0 && cols > 0 && startslack != x_slack;) {
299             int increment = max(1, x_slack / cols);
300             startslack = x_slack;
301             for(short col=0; col < cols; col++) {
302                 int diff = min(colMaxWidth[col], colWidth[col] + increment) - colWidth[col];
303                 x_slack -= diff;
304                 colWidth[col] += diff;
305             }
306         }   
307         //#end
308
309         // Phase 3: assign childrens' actual sizes
310         for(Box child = getChild(0); child != null; child = child.nextSibling()) {
311             if (!child.test(VISIBLE)) continue;
312             int child_width, child_height, child_x, child_y;
313             if (!child.test(PACKED)) {
314                 child_x = child.x;
315                 child_y = child.y;
316                 child_width = child.test(HSHRINK) ? child.contentwidth : min(child.maxwidth, width - child.x);
317                 child_height = child.test(VSHRINK) ? child.contentheight : min(child.maxheight, height - child.y);
318                 child_width = max(child.minwidth, child_width);
319                 child_height = max(child.minheight, child_height);
320             } else {
321                 int unbounded;
322                 //#repeat col/row colspan/rowspan contentwidth/contentheight width/height colMaxWidth/rowMaxHeight \
323                 //        child_x/child_y x/y HSHRINK/VSHRINK maxwidth/maxheight cols/rows minwidth/minheight x_slack/y_slack \
324                 //        colWidth/rowHeight child_width/child_height ALIGN_RIGHT/ALIGN_BOTTOM ALIGN_LEFT/ALIGN_TOP
325                 unbounded = 0;
326                 for(int i = child.col; i < child.col + child.colspan; i++) unbounded += colWidth[i];
327                 child_width = min(unbounded, child.test(HSHRINK) ? child.contentwidth : child.maxwidth);
328                 child_x = test(ALIGN_RIGHT) ? x_slack : test(ALIGN_LEFT) ? 0 : x_slack / 2;
329                 for(int i=0; i < child.col; i++) child_x += colWidth[i];
330                 if (child_width > unbounded) child_x -= (child_width - unbounded) / 2;
331                 //#end
332             }
333             child.resize(child_x, child_y, child_width, child_height);
334         }
335
336         // cleanup
337         for(int i=0; i<cols; i++) { colWidth[i] = 0; colMaxWidth[i] = MAX_LENGTH; }
338         for(int i=0; i<rows; i++) { rowHeight[i] = 0; rowMaxHeight[i] = MAX_LENGTH; }
339
340         for(Box child = getChild(0); child != null; child = child.nextSibling())
341             if (test(VISIBLE))
342                 child.resize_children();
343     }
344
345
346
347     // Rendering Pipeline /////////////////////////////////////////////////////////////////////
348
349     /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
350     void render(int parentx, int parenty, int cx1, int cy1, int cx2, int cy2, PixelBuffer buf, VectorGraphics.Affine a) {
351         if (!test(VISIBLE)) return;
352         int globalx = parentx + (parent == null ? 0 : x);
353         int globaly = parenty + (parent == null ? 0 : y);
354
355         // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
356         if (!test(NOCLIP)) {
357             cx1 = max(cx1, parent == null ? 0 : globalx);
358             cy1 = max(cy1, parent == null ? 0 : globaly);
359             cx2 = min(cx2, globalx + width);
360             cy2 = min(cy2, globaly + height);
361             if (cx2 <= cx1 || cy2 <= cy1) return;
362         }
363
364         if ((fillcolor & 0xFF000000) != 0x00000000)
365             buf.fillTrapezoid(cx1, cx2, cy1, cx1, cx2, cy2, fillcolor);
366
367         // FIXME: do aspect in here
368         if (texture != null && texture.isLoaded)
369             for(int x = globalx; x < cx2; x += texture.width)
370                 for(int y = globaly; y < cy2; y += texture.height)
371                     buf.drawPicture(texture, x, y, cx1, cy1, cx2, cy2);
372
373         if (text != null && !text.equals("") && font != null)
374             if (font.rasterizeGlyphs(text, buf, strokecolor, globalx, globaly, cx1, cy1, cx2, cy2, null) == -1)
375                 font.rasterizeGlyphs(text, buf, strokecolor, globalx, globaly, cx1, cy1, cx2, cy2, this);
376
377         for(Box b = getChild(0); b != null; b = b.nextSibling())
378             b.render(globalx, globaly, cx1, cy1, cx2, cy2, buf, null);
379     }
380     
381     
382     // Methods to implement org.xwt.js.JS //////////////////////////////////////
383
384     public int globalToLocalX(int x) { return parent == null ? x : parent.globalToLocalX(x - this.x); }
385     public int globalToLocalY(int y) { return parent == null ? y : parent.globalToLocalY(y - this.y); }
386     public int localToGlobalX(int x) { return parent == null ? x : parent.globalToLocalX(x + this.x); }
387     public int localToGlobalY(int y) { return parent == null ? y : parent.globalToLocalY(y + this.y); }
388     
389     public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
390         if (nargs != 1 || !"indexof".equals(method)) return super.callMethod(method, a0, a1, a2, rest, nargs);
391         Box b = (Box)a0;
392         if (b.parent != this)
393             return (redirect == null || redirect == this) ?
394                 N(-1) :
395                 redirect.callMethod(method, a0, a1, a2, rest, nargs);
396         return N(b.getIndexInParent());
397     }
398
399     public Enumeration keys() { throw new Error("you cannot apply for..in to a " + this.getClass().getName()); }
400
401     protected boolean isTrappable(Object key, boolean isRead) {
402         if (key == null) return false;
403         else if (key instanceof String) {
404             // not allowed to trap box properties, and no read traps on events
405             String name = (String)key;
406             for (int i=0; i < props.length; i++) if (name.equals(props[i])) return false; 
407             if (isRead) for (int i=0; i < events.length; i++) if (name.equals(events[i])) return false; 
408         }
409
410         return true;
411     }
412
413     public Object get(Object name) throws JSExn {
414         if (name instanceof Number)
415             return redirect == null ? null : redirect == this ? getChild(toInt(name)) : redirect.get(name);
416
417         //#switch(name)
418         case "indexof": return METHOD;
419         case "text": return text;
420         case "path": throw new JSExn("cannot read from the path property");
421         case "fill": return colorToString(fillcolor);
422         case "strokecolor": return colorToString(strokecolor);
423         case "textcolor": return colorToString(strokecolor);
424         case "font": return font == null ? null : font.res;
425         case "fontsize": return font == null ? N(10) : N(font.pointsize);
426         case "strokewidth": return N(strokewidth);
427         case "align": return alignToString();
428         case "thisbox": return this;
429         case "shrink": return B(test(HSHRINK) || test(VSHRINK));
430         case "hshrink": return B(test(HSHRINK));
431         case "vshrink": return B(test(VSHRINK));
432         case "aspect": return N(aspect);
433         case "x": return (parent == null || !test(VISIBLE)) ? N(0) : N(x);
434         case "y": return (parent == null || !test(VISIBLE)) ? N(0) : N(y);
435         case "width": return N(width);
436         case "height": return N(height);
437         case "cols": return test(FIXED) == COLS ? N(cols) : N(0);
438         case "rows": return test(FIXED) == ROWS ? N(rows) : N(0);
439         case "colspan": return N(colspan);
440         case "rowspan": return N(rowspan);
441         case "noclip": return B(test(NOCLIP));
442         case "visible": return B(test(VISIBLE) && (parent == null || (parent.get("visible") == T)));
443         case "packed": return B(test(PACKED));
444         case "globalx": return N(localToGlobalX(0));
445         case "globaly": return N(localToGlobalY(0));
446         case "cursor": return test(CURSOR) ? boxToCursor.get(this) : null;
447         case "mouse":
448             if (getSurface() == null) return null;
449             if (getSurface()._mousex == Integer.MAX_VALUE)
450                 throw new JSExn("you cannot read from the box.mouse property in background thread context");
451             return new Mouse();
452         case "numchildren": return redirect == null ? N(0) : redirect == this ? N(treeSize()) : redirect.get("numchildren");
453         case "minwidth": return N(minwidth);
454         case "maxwidth": return N(maxwidth);
455         case "minheight": return N(minheight);
456         case "maxheight": return N(maxheight);
457         case "redirect": return redirect == null ? null : redirect == this ? T : redirect.get("redirect");
458         case "Minimized": if (parent == null && getSurface() != null) return B(getSurface().minimized);
459         default: return super.get(name);
460         //#end
461         throw new Error("unreachable"); // unreachable
462     }
463
464     private class Mouse extends JS {
465         public Object get(Object key) {
466             //#switch(key)
467             case "x": return N(globalToLocalX(getSurface()._mousex));
468             case "y": return N(globalToLocalY(getSurface()._mousey));
469
470             // this might not get recomputed if we change mousex/mousey...
471             case "inside": return B(MOUSEINSIDE);
472             //#end
473             return null;
474         }
475     }
476
477     void setMaxWidth(Object value) { do { CHECKSET_INT(maxwidth); MARK_RESIZE; } while(false); }
478     void setMaxHeight(Object value) { do { CHECKSET_INT(maxheight); MARK_RESIZE; } while(false); }
479
480     public void put(Object name, Object value) throws JSExn {
481         if (name instanceof Number) { put(toInt(name), value); return; }
482         //#switch(name)
483         case "text": CHECKSET_STRING(text); MARK_RESIZE; dirty();
484         case "strokecolor": value = N(stringToColor((String)value)); CHECKSET_INT(strokecolor); MARK_RESIZE; dirty();
485         case "textcolor": value = N(stringToColor((String)value)); CHECKSET_INT(strokecolor); MARK_RESIZE; dirty();
486         case "text": CHECKSET_STRING(text); MARK_RESIZE; dirty();
487         case "strokewidth": CHECKSET_SHORT(strokewidth); dirty();
488         case "shrink": put("hshrink", value); put("vshrink", value);
489         case "hshrink": CHECKSET_FLAG(HSHRINK); MARK_RESIZE;
490         case "vshrink": CHECKSET_FLAG(VSHRINK); MARK_RESIZE;
491         case "width": put("maxwidth", value); put("minwidth", value); MARK_RESIZE;
492         case "height": put("maxheight", value); put("minheight", value); MARK_RESIZE;
493         case "maxwidth": setMaxWidth(value);
494         case "minwidth": CHECKSET_INT(minwidth); MARK_RESIZE;
495         case "maxheight": setMaxHeight(value);
496         case "minheight": CHECKSET_INT(minheight); MARK_RESIZE;
497         case "colspan": CHECKSET_SHORT(colspan); MARK_REPACK_parent;
498         case "rowspan": CHECKSET_SHORT(rowspan); MARK_REPACK_parent;
499         case "rows": CHECKSET_SHORT(rows); if (rows==0){set(FIXED, COLS);if(cols==0)cols=1;} else set(FIXED, ROWS); MARK_REPACK;
500         case "cols": CHECKSET_SHORT(cols); if (cols==0){set(FIXED, ROWS);if(rows==0)rows=1;} else set(FIXED, COLS); MARK_REPACK;
501         case "noclip": CHECKSET_FLAG(NOCLIP); if (parent == null) dirty(); else parent.dirty();
502         case "visible": CHECKSET_FLAG(VISIBLE); dirty(); MARK_RESIZE; dirty();
503         case "packed": CHECKSET_FLAG(PACKED); MARK_REPACK_parent;
504         case "aspect": CHECKSET_INT(aspect); dirty();
505         case "globalx": put("x", N(globalToLocalX(toInt(value))));
506         case "globaly": put("y", N(globalToLocalY(toInt(value))));
507         case "align": clear(ALIGNS); setAlign(value == null ? "center" : value); MARK_RESIZE;
508         case "cursor": setCursor(value);
509         case "fill": setFill(value);
510         case "mouse":
511             int mousex = toInt(((JS)value).get("x"));
512             int mousey = toInt(((JS)value).get("y"));
513             getSurface()._mousex = localToGlobalX(mousex);
514             getSurface()._mousey = localToGlobalY(mousey);
515         case "Minimized": if (parent == null && getSurface() != null) getSurface().minimized = toBoolean(value);  // FEATURE
516         case "Maximized": if (parent == null && getSurface() != null) getSurface().maximized = toBoolean(value);  // FEATURE
517         case "Close": if (parent == null && getSurface() != null) getSurface().dispose(true);
518         case "toback": if (parent == null && getSurface() != null && toBoolean(value)) { getSurface().toBack(); }
519         case "tofront": if (parent == null && getSurface() != null && toBoolean(value)) { getSurface().toFront(); }
520         case "redirect": if (redirect == this) redirect = (Box)value; else Log.log(this, "redirect can only be set once");
521         case "font": font = value == null ? null : Font.getFont((Res)value, font == null ? 10 : font.pointsize); MARK_RESIZE; dirty();
522         case "fontsize": font = Font.getFont(font == null ? null : font.res, toInt(value)); MARK_RESIZE; dirty();
523         case "x": if (parent==null && Surface.fromBox(this)!=null) { CHECKSET_INT(x); } else { if (test(PACKED) && parent != null) return; CHECKSET_INT(x); dirty(); MARK_RESIZE; dirty(); }
524         case "y": if (parent==null && Surface.fromBox(this)!=null) { CHECKSET_INT(y); } else { if (test(PACKED) && parent != null) return; CHECKSET_INT(y); dirty(); MARK_RESIZE; dirty(); }
525
526         case "Press1":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
527         case "Press2":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
528         case "Press3":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
529         case "Release1":      if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
530         case "Release2":      if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
531         case "Release3":      if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
532         case "Click1":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
533         case "Click2":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
534         case "Click3":        if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
535         case "DoubleClick1":  if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
536         case "DoubleClick2":  if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
537         case "DoubleClick3":  if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
538         case "KeyPressed":    if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
539         case "KeyReleased":   if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
540         case "Move":          if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
541         case "Enter":         if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
542         case "Leave":         if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.put(name, value);
543
544         case "_Move":         propagateDownward(name, value, false);
545         case "_Press1":       propagateDownward(name, value, false);
546         case "_Press2":       propagateDownward(name, value, false);
547         case "_Press3":       propagateDownward(name, value, false);
548         case "_Release1":     propagateDownward(name, value, false);
549         case "_Release2":     propagateDownward(name, value, false);
550         case "_Release3":     propagateDownward(name, value, false);
551         case "_Click1":       propagateDownward(name, value, false);
552         case "_Click2":       propagateDownward(name, value, false);
553         case "_Click3":       propagateDownward(name, value, false);
554         case "_DoubleClick1": propagateDownward(name, value, false);
555         case "_DoubleClick2": propagateDownward(name, value, false);
556         case "_DoubleClick3": propagateDownward(name, value, false);
557         case "_KeyPressed":   propagateDownward(name, value, false);
558         case "_KeyReleased":  propagateDownward(name, value, false);
559
560         case "PosChange":     return;
561         case "SizeChange":    return;
562         case "childadded":    return;
563         case "childremoved":  return;
564
565         case "thisbox":       if (value == null) removeSelf();
566
567         default:              super.put(name, value);
568         //#end
569     }
570
571     private String alignToString() {
572         switch(flags & ALIGNS) {
573             case (ALIGN_TOP | ALIGN_LEFT): return "topleft";
574             case (ALIGN_BOTTOM | ALIGN_LEFT): return "bottomleft";
575             case (ALIGN_TOP | ALIGN_RIGHT): return "topright";
576             case (ALIGN_BOTTOM | ALIGN_RIGHT): return "bottomright";
577             case ALIGN_TOP: return "top";
578             case ALIGN_BOTTOM: return "bottom";
579             case ALIGN_LEFT: return "left";
580             case ALIGN_RIGHT: return "right";
581             case 0: return "center";
582             default: throw new Error("invalid alignment flags: " + (flags & ALIGNS));
583         }
584     }
585
586     private void setAlign(Object value) {
587         //#switch(value)
588         case "center": clear(ALIGNS);
589         case "topleft": set(ALIGN_TOP | ALIGN_LEFT);
590         case "bottomleft": set(ALIGN_BOTTOM | ALIGN_LEFT);
591         case "topright": set(ALIGN_TOP | ALIGN_RIGHT);
592         case "bottomright": set(ALIGN_BOTTOM | ALIGN_RIGHT);
593         case "top": set(ALIGN_TOP);
594         case "bottom": set(ALIGN_BOTTOM);
595         case "left": set(ALIGN_LEFT);
596         case "right": set(ALIGN_RIGHT);
597         default: Log.logJS("invalid alignment \"" + value + "\"");
598         //#end
599     }
600     
601     private void setCursor(Object value) {
602         if (value == null) { clear(CURSOR); boxToCursor.remove(this); return; }
603         if (value.equals(boxToCursor.get(this))) return;
604         set(CURSOR);
605         boxToCursor.put(this, value);
606         Surface surface = getSurface();
607         String tempcursor = surface.cursor;
608         // FIXME
609         //Move(surface.mousex, surface.mousey, surface.mousex, surface.mousey);
610         if (surface.cursor != tempcursor) surface.syncCursor();
611     }
612
613     private void setFill(Object value) {
614         if (value == null) return;
615         if (value instanceof String) {
616             // FIXME check double set
617             int newfillcolor = stringToColor((String)value);
618             if (newfillcolor == fillcolor) return;
619             fillcolor = newfillcolor;
620             dirty();
621             return;
622         }
623         if (!(value instanceof Res)) return;
624
625         texture = Picture.load((Res)value, this);
626     }
627
628     /**
629      *  Handles events which propagate down the box tree.  If obscured
630      *  is set, then we merely check for Enter/Leave.
631      */
632     private void propagateDownward(Object name_, Object value, boolean obscured) {
633
634         String name = (String)name_;
635         if (getSurface() == null) return;
636         int x = globalToLocalX(getSurface()._mousex);
637         int y = globalToLocalY(getSurface()._mousey);
638         boolean wasinside = test(MOUSEINSIDE);
639         boolean isinside = test(VISIBLE) && inside(x, y) && !obscured;
640         if (!wasinside && isinside) { set(MOUSEINSIDE);   putAndTriggerTrapsAndCatchExceptions("Enter", T); }
641         if (wasinside && !isinside) { clear(MOUSEINSIDE); putAndTriggerTrapsAndCatchExceptions("Leave", T); }
642
643         boolean found = false;
644         if (wasinside || isinside)
645             for(Box child = getChild(treeSize() - 1); child != null; child = child.prevSibling()) {
646                 boolean save_stop = child.test(STOP_UPWARD_PROPAGATION);
647                 if (obscured || !child.inside(x - child.x, y - child.y)) {
648                     child.propagateDownward(name, value, true);
649                 } else try {
650                     found = true;
651                     child.clear(STOP_UPWARD_PROPAGATION);
652                     child.putAndTriggerTrapsAndCatchExceptions(name, value);
653                 } finally {
654                     if (save_stop) child.set(STOP_UPWARD_PROPAGATION); else child.clear(STOP_UPWARD_PROPAGATION);
655                 }
656                 if (child.inside(x - child.x, y - child.y))
657                     if (name.equals("_Move")) obscured = true;
658                     else break;
659             }
660
661         if (!obscured && !found)
662             if (!name.equals("_Move") || wasinside) putAndTriggerTrapsAndCatchExceptions(name.substring(1), value);
663     }
664
665     private static int stringToColor(String s) {
666         // FIXME support three-char strings by doubling digits
667         if (s == null) return 0x00000000;
668         else if (SVG.colors.get(s) != null) return 0xFF000000 | toInt(SVG.colors.get(s));
669         else if (s.length() > 0 && s.charAt(0) == '#') try {
670             // FEATURE  alpha
671             return 0xFF000000 |
672                 (Integer.parseInt(s.substring(1, 3), 16) << 16) |
673                 (Integer.parseInt(s.substring(3, 5), 16) << 8) |
674                 Integer.parseInt(s.substring(5, 7), 16);
675         } catch (NumberFormatException e) {
676             Log.log(Box.class, "invalid color " + s);
677             return 0;
678         }
679         else return 0; // FEATURE: error?
680     }
681
682     private static String colorToString(int argb) {
683         if ((argb & 0xFF000000) == 0) return null;
684         String red = Integer.toHexString((argb & 0x00FF0000) >> 16);
685         String green = Integer.toHexString((argb & 0x0000FF00) >> 8);
686         String blue = Integer.toHexString(argb & 0x000000FF);
687         if (red.length() < 2) red = "0" + red;
688         if (blue.length() < 2) blue = "0" + blue;
689         if (green.length() < 2) green = "0" + green;
690         return "#" + red + green + blue;
691     }
692
693     /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface */
694     public static Box whoIs(Box cur, int x, int y) {
695
696         if (cur.parent != null) throw new Error("whoIs may only be invoked on the root box of a surface");
697         int globalx = 0;
698         int globaly = 0;
699
700         // WARNING: this method is called from the event-queueing thread -- it may run concurrently with
701         // ANY part of XWT, and is UNSYNCHRONIZED for performance reasons.  BE CAREFUL HERE.
702
703         if (!cur.test(VISIBLE)) return null;
704         if (!cur.inside(x - globalx, y - globaly)) return cur.parent == null ? cur : null;
705         OUTER: while(true) {
706             for(int i=cur.treeSize() - 1; i>=0; i--) {
707                 Box child = cur.getChild(i);
708                 if (child == null) continue;        // since this method is unsynchronized, we have to double-check
709                 globalx += child.x;
710                 globaly += child.y;
711                 if (child.test(VISIBLE) && child.inside(x - globalx, y - globaly)) { cur = child; continue OUTER; }
712                 globalx -= child.x;
713                 globaly -= child.y;
714             }
715             break;
716         }
717         return cur;
718     }
719
720
721     // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
722
723     static short min(short a, short b) { if (a<b) return a; else return b; }
724     static int min(int a, int b) { if (a<b) return a; else return b; }
725     static float min(float a, float b) { if (a<b) return a; else return b; }
726
727     static short max(short a, short b) { if (a>b) return a; else return b; }
728     static int max(int a, int b) { if (a>b) return a; else return b; }
729     static float max(float a, float b) { if (a>b) return a; else return b; }
730
731     static 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; }
732     static 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; }
733     static int bound(int a, int b, int c) { if (c < b) return c; if (a > b) return a; return b; }
734     final boolean inside(int x, int y) { return test(VISIBLE) && x >= 0 && y >= 0 && x < width && y < height; }
735
736     void set(int mask) { flags |= mask; }
737     void set(int mask, boolean setclear) { if (setclear) set(mask); else clear(mask); }
738     void clear(int mask) { flags &= ~mask; }
739     boolean test(int mask) { return ((flags & mask) == mask); }
740     
741
742     // Tree Handling //////////////////////////////////////////////////////////////////////
743
744     public final int getIndexInParent() { return parent == null ? 0 : parent.indexNode(this); }
745     public final Box nextSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) + 1); }
746     public final Box prevSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) - 1); }
747     public final Box getChild(int i) {
748         if (i < 0) return null;
749         if (i >= treeSize()) return null;
750         return (Box)getNode(i);
751     }
752
753     // Tree Manipulation /////////////////////////////////////////////////////////////////////
754
755     void removeSelf() {
756         if (parent != null) { parent.removeChild(parent.indexNode(this)); return; }
757         Surface surface = Surface.fromBox(this); 
758         if (surface != null) surface.dispose(true);
759     }
760
761     /** remove the i^th child */
762     public void removeChild(int i) {
763         Box b = getChild(i);
764         MARK_REFLOW_b;
765         b.dirty();
766         b.clear(MOUSEINSIDE);
767         deleteNode(i);
768         b.parent = null;
769         MARK_REFLOW;
770         putAndTriggerTrapsAndCatchExceptions("childremoved", b);
771     }
772     
773     public void put(int i, Object value) throws JSExn {
774         if (i < 0) return;
775             
776         if (value != null && !(value instanceof Box)) {
777             if (Log.on) Log.logJS(this, "attempt to set a numerical property on a box to a non-box");
778             return;
779         }
780
781         if (redirect == null) {
782             if (value == null) putAndTriggerTrapsAndCatchExceptions("childremoved", getChild(i));
783             else Log.logJS(this, "attempt to add/remove children to/from a node with a null redirect");
784
785         } else if (redirect != this) {
786             if (value != null) putAndTriggerTrapsAndCatchExceptions("childadded", value);
787             redirect.put(i, value);
788             if (value == null) {
789                 Box b = (Box)redirect.get(new Integer(i));
790                 if (b != null) putAndTriggerTrapsAndCatchExceptions("childremoved", b);
791             }
792
793         } else if (value == null) {
794             if (i < 0 || i > treeSize()) return;
795             Box b = getChild(i);
796             removeChild(i);
797             putAndTriggerTrapsAndCatchExceptions("childremoved", b);
798
799         } else {
800             Box b = (Box)value;
801
802             // check if box being moved is currently target of a redirect
803             for(Box cur = b.parent; cur != null; cur = cur.parent)
804                 if (cur.redirect == b) {
805                     if (Log.on) Log.logJS(this, "attempt to move a box that is the target of a redirect");
806                     return;
807                 }
808
809             // check for recursive ancestor violation
810             for(Box cur = this; cur != null; cur = cur.parent)
811                 if (cur == b) {
812                     if (Log.on) Log.logJS(this, "attempt to make a node a parent of its own ancestor");
813                     if (Log.on) Log.log(this, "box == " + this + "  ancestor == " + b);
814                     return;
815                 }
816
817             if (b.parent != null) b.parent.removeChild(b.parent.indexNode(b));
818             insertNode(i, b);
819             b.parent = this;
820             
821             // need both of these in case child was already uncalc'ed
822             MARK_REFLOW_b;
823             MARK_REFLOW;
824             
825             b.dirty(); 
826             putAndTriggerTrapsAndCatchExceptions("childadded", b);
827         }
828     }
829
830     void putAndTriggerTrapsAndCatchExceptions(Object name, Object val) {
831         try {
832             putAndTriggerTraps(name, val);
833         } catch (Exception e) {
834             Log.logJS("caught exception while putting to trap \""+name+"\"");
835             Log.logJS(e);
836         }
837     }
838
839 }
840
841
842
843
844
845
846         /*
847         offset_x = 0;
848         if (path != null) {
849             if (rpath == null) rpath = path.realize(transform == null ? VectorGraphics.Affine.identity() : transform);
850             if ((flags & HSHRINK) != 0) contentwidth = max(contentwidth, rpath.boundingBoxWidth());
851             if ((flags & VSHRINK) != 0) contentheight = max(contentheight, rpath.boundingBoxHeight());
852             // FIXME: separate offset_x needed for the path
853         }
854         // #repeat x1/y1 x2/y2 x3/y3 x4/y4 contentwidth/contentheight left/top right/bottom
855         int x1 = transform == null ? 0 : (int)transform.multiply_px(0, 0);
856         int x2 = transform == null ? 0 : (int)transform.multiply_px(contentwidth, 0);
857         int x3 = transform == null ? contentwidth : (int)transform.multiply_px(contentwidth, contentheight);
858         int x4 = transform == null ? contentwidth : (int)transform.multiply_px(0, contentheight);
859         int left = min(min(x1, x2), min(x3, x4));
860         int right = max(max(x1, x2), max(x3, x4));
861         contentwidth = max(contentwidth, right - left);
862         offset_x = -1 * left;
863         // #end
864         */
865
866
867                     /*
868         if (path != null) {
869             if (rtransform == null) rpath = null;
870             else if (!rtransform.equalsIgnoringTranslation(a)) rpath = null;
871             else {
872                 rpath.translate((int)(a.e - rtransform.e), (int)(a.f - rtransform.f));
873                 rtransform = a.copy();
874             }
875             if (rpath == null) rpath = path.realize((rtransform = a) == null ? VectorGraphics.Affine.identity() : a);
876             if ((strokecolor & 0xff000000) != 0) rpath.stroke(buf, 1, strokecolor);
877             if ((fillcolor & 0xff000000) != 0) rpath.fill(buf, new VectorGraphics.SingleColorPaint(fillcolor));
878         }
879 */
880
881
882 /*
883             VectorGraphics.Affine a2 = VectorGraphics.Affine.translate(b.x, b.y);
884             if (transform != null) a2.multiply(transform);
885             a2.multiply(VectorGraphics.Affine.translate(offset_x, offset_y));
886             a2.multiply(a);
887 */