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