+++ /dev/null
-// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
-package org.xwt;
-
-import java.io.*;
-import java.net.*;
-import java.util.*;
-import org.xwt.js.*;
-import org.xwt.util.*;
-
-/**
- * <p>
- * Encapsulates the data for a single XWT box as well as all layout
- * rendering logic.
- * </p>
- *
- * <p>
- * This is the real meat of XWT. Part of its monolithic design is for
- * performance reasons: deep inheritance heirarchies are slow, and
- * neither javago nor GCJ can inline across class boundaries.
- * </p>
- *
- * <p>The rendering process consists of two phases:</p>
- *
- * <ol><li> <b>Prerendering pipeline</b>: a set of methods that
- * traverse the tree (DFS, postorder) immediately before
- * rendering. These methods calculate the appropriate size
- * and position for all boxes. If no changes requiring a
- * re-prerender have been made to a box or any of its
- * descendants, <tt>needs_prerender</tt> will be false, and the box
- * and its descendants will be skipped.
- *
- * <li> <b>Rendering pipeline</b>: a second set of methods that
- * traverses the tree (DFS, preorder) and renders each Box
- * onto the associated Surface. The render() method takes a
- * region (x,y,w,h) as an argument, and will only render
- * onto pixels within that region. Boxes which lie
- * completely outside that region will be skipped.
- * </ol>
- *
- * <p>
- * Either of these two phases may <i>abort</i> at any time by setting
- * <tt>surface.abort</tt> to true. Currently, there are two reasons
- * for aborting: a <tt>SizeChange</tt> or <tt>PosChange</tt> was
- * triggered in the prerender phase (which ran scripts which modified
- * the boxtree's composition, requiring another prerender pass), or
- * else the user resized the surface. In either case, the
- * [pre]rendering process is halted as soon as possible and
- * re-started from the beginning.
- * </p>
- *
- * <p>Why are these done as seperate passes over the box tree?</p>
- *
- * <ol><li> Sometimes we need to make several trips through
- * <tt>prerender()</tt?, as a result of <tt>SizeChange</tt>
- * or <tt>PosChange</tt>. Calling <tt>prerender()</tt> is
- * cheap; calling <tt>render()</tt> is expensive.
- *
- * <li> Even if no <tt>SizeChange</tt> or <tt>PosChange</tt> traps are
- * triggered, updates to the size and position of boxes in
- * the prerender phase can cause additional regions to be
- * added to the dirty list. If the prerender and render
- * passes were integrated, this might cause some screen
- * regions to be painted twice (or more) in a single pass,
- * which hurts performance.
- * </ol>
- *
- * <p>
- * A box's <tt>_cmin_*</tt> variables hold the minimum possible
- * dimensions of this box, taking into account the size of its
- * children (and their children). The cmin variables must be kept in
- * sync with its other geometric properties and the geometric
- * properties of its children at all times -- they are not
- * periodically recomputed during the [pre]rendering process, as size
- * and pos are. If any data changes which might invalidate the cmin,
- * the method <tt>sync_cmin_to_children()</tt> must be invoked
- * immediately.
- * </p>
- *
- * <p>
- * A note on coordinates: the Box class represents regions
- * internally as x,y,w,h tuples, even though the DoubleBuffer class
- * uses x1,y1,x2,y2 tuples.
- * </p>
- */
-public final class Box extends JS.Scope {
-
-
- // Static Data //////////////////////////////////////////////////////////////
-
- /** a pool of one-element Object[]'s */
- private static Queue singleObjects = new Queue(100);
-
- /** caches images, keyed on resource name or url */
- public static Hash pictureCache = new Hash();
-
- /** cache of border objects */
- static Hash bordercache = new Hash();
-
- /** stores image names, keyed on image object */
- static Hash imageToNameMap = new Hash();
-
- /** the empty object, used for get-traps */
- private static JS.Array emptyobj = new JS.Array();
-
-
- // Instance Data: Templates ////////////////////////////////////////////////////////
-
- /** the unresolved name of the first template applied to this node [ignoring preapply's], or null if this template was specified anonymously */
- String templatename = null;
-
- /** the importlist which was used to resolve <tt>templatename</tt>, or null if this template was specified anonymously */
- String[] importlist = Template.defaultImportList;
-
- /** the template instance that resulted from resolving <tt>templatename</tt> using <tt>importlist</tt>, or the anonymous template applied */
- Template template = null;
-
-
- // Instance Data: Geometry ////////////////////////////////////////////////////////
-
- /** The number of elements in the geom array */
- public static final int NUMINTS = 10;
-
- /** The maximum <i>defined</i> width and height of this box */
- public static final int dmax = 0;
- private int _dmax_0 = 0;
- private int _dmax_1 = 0;
- public final int dmax(int axis) { return axis == 0 ? _dmax_0 : _dmax_1; }
-
- /** The minimum <i>defined</i> width and height of this box */
- public static final int dmin = 1;
- private int _dmin_0 = 0;
- private int _dmin_1 = 0;
- public final int dmin(int axis) { return axis == 0 ? _dmin_0 : _dmin_1; }
-
- /** The minimum <i>calculated</i> width and height of this box -- unlike dmin, this takes childrens' sizes into account */
- public static final int cmin = 2;
- private int _cmin_0 = 0;
- private int _cmin_1 = 0;
- public final int cmin(int axis) { return axis == 0 ? _cmin_0 : _cmin_1; }
-
- /** The position of this box, relitave to the parent */
- public static final int abs = 3;
- private int _abs_0 = 0;
- private int _abs_1 = 0;
- public final int abs(int axis) { return axis == 0 ? _abs_0 : _abs_1; }
-
- /** The absolute position of this box (ie relitave to the root); set by the parent */
- public static final int pos = 4;
- private int _pos_0 = 0;
- private int _pos_1 = 0;
- public final int pos(int axis) { return axis == 0 ? _pos_0 : _pos_1; }
-
- /** The actual size of this box; set by the parent. */
- public static final int size = 5;
- int _size_0 = 0;
- int _size_1 = 0;
- public final int size(int axis) { return axis == 0 ? _size_0 : _size_1; }
-
- /** The old actual absolute position of this box (ie relitave to the root) */
- public static final int oldpos = 6;
- private int _oldpos_0 = 0;
- private int _oldpos_1 = 0;
- public final int oldpos(int axis) { return axis == 0 ? _oldpos_0 : _oldpos_1; }
-
- /** The old actual size of this box */
- public static final int oldsize = 7;
- private int _oldsize_0 = 0;
- private int _oldsize_1 = 0;
- public final int oldsize(int axis) { return axis == 0 ? _oldsize_0 : _oldsize_1; }
-
- /** The padding along each edge for this box */
- public static final int pad = 8;
- private int _pad_0 = 0;
- private int _pad_1 = 0;
- public final int pad(int axis) { return axis == 0 ? _pad_0 : _pad_1; }
-
- /** The dimensions of the text in this box */
- public static final int textdim = 9;
- private int _textdim_0 = 0;
- private int _textdim_1 = 0;
- public final int textdim(int axis) { return axis == 0 ? _textdim_0 : _textdim_1; }
-
-
- // Instance Data /////////////////////////////////////////////////////////////////
-
- /** This box's mouseinside property, as defined in the reference */
- boolean mouseinside = false;
-
- /** If redirect is enabled, this holds the Box redirected to */
- Box redirect = this;
-
- /** the Box's font, null inherits from parent -- you must call textupdate() after changing this */
- String font = null;
-
- /** if font == null, this might be a cached copy of the inherited ancestor font */
- String cachedFont = null;
-
- /** The surface for us to render on; null if none; INVARIANT: surface == getParent().surface */
- Surface surface = null;
-
- /** Our alignment: top/left == -1, center == 0, bottom/right == +1 */
- byte align = 0;
-
- /** Our background image; to set this, use setImage() */
- public Picture image;
-
- /** The flex for this box */
- int flex = 1;
-
- /** The orientation, horizontal == 0, vertical == 1 */
- byte o = 0;
-
- /** The opposite of the orientation */
- byte xo = 1;
-
- /** The id of this Box */
- public String id = "";
-
- /** The text of this Box -- you must call textupdate() after changing this */
- String text = "";
-
- /** The color of the text in this Box in 00RRGGBB form -- default is black */
- int textcolor = 0xFF000000;
-
- /** The background color of this box in AARRGGBB form -- default is clear; alpha is all-or-nothing */
- int color = 0x00000000;
-
- /** Holds four "strip images" -- 0=top, 1=bottom, 2=left, 3=right, 4=all */
- Picture[] border = null;
-
- /** true iff the box's background image should be tiled */
- boolean tile = false;
-
- /** True iff the Box is invisible */
- public boolean invisible = false;
-
- /** If true, the Box will force its own size to the natural size of its background image */
- boolean sizetoimage = false;
-
- /** If true and tile is false, the background of this image will never be stretched */
- boolean fixedaspect = false;
-
- /** If true, the box will shrink to the smallest vertical size possible */
- boolean vshrink = false;
-
- /** If true, the box will shrink to the smallest horizontal size possible */
- boolean hshrink = false;
-
- /** If true, the box will be positioned absolutely */
- boolean absolute = false;
-
- /** True iff the Box must be run through the prerender() pipeline before render()ing;<br>
- * INVARIANT: if (needs_prerender) then getParent().needs_prerender. **/
- boolean needs_prerender = true;
-
- /** The cursor for this Box -- only meaningful on the root Box */
- public String cursor = null;
-
- /** Any traps placed on this Box */
- public Hash traps = null;
-
-
- // Instance Data: IndexOf ////////////////////////////////////////////////////////////
-
- /** The indexof() Function; created lazily */
- public JS.Callable indexof = null;
- public JS.Callable indexof() { if (indexof == null) indexof = new IndexOf(); return indexof; }
-
- /** a trivial private class to serve as the box.indexof function object */
- private class IndexOf extends JS.Callable {
- public IndexOf() { this.setSeal(true); }
- public Object call(JS.Array args) throws JS.Exn {
- if (args.length() != 1 || args.elementAt(0) == null || !(args.elementAt(0) instanceof Box)) return new Integer(-1);
- Box b = (Box)args.elementAt(0);
- if (b.getParent() != Box.this) {
- if (redirect == null || redirect == Box.this) return new Integer(-1);
- return Box.this.redirect.indexof().call(args);
- }
- return new Integer(b.getIndexInParent());
- }
- }
-
-
- // Methods which enforce/preserve invariants ////////////////////////////////////////////
-
- /** This method MUST be used to change geometry values -- it ensures that certain invariants are preserved. */
- public final void set(int which, int axis, int newvalue) {
-
- // if this Box is the root of the Surface, notify the Surface of size changes
- if (getParent() == null && surface != null && which == size)
- surface._setSize(axis == 0 ? newvalue : size(0), axis == 1 ? newvalue : size(1));
-
- if (getParent() == null && surface != null && (which == dmin || which == dmax))
- surface.setLimits(dmin(0), dmin(1), dmax(0), dmax(1));
-
- switch(which) {
- case dmin: if (dmin(axis) == newvalue) return; if (axis == 0) _dmin_0 = newvalue; else _dmin_1 = newvalue; break;
- case dmax: if (dmax(axis) == newvalue) return; if (axis == 0) _dmax_0 = newvalue; else _dmax_1 = newvalue; break;
- case cmin: if (cmin(axis) == newvalue) return; if (axis == 0) _cmin_0 = newvalue; else _cmin_1 = newvalue; break;
- case abs: if (abs(axis) == newvalue) return; if (axis == 0) _abs_0 = newvalue; else _abs_1 = newvalue; break;
- case pos: if (pos(axis) == newvalue) return; if (axis == 0) _pos_0 = newvalue; else _pos_1 = newvalue; break;
- case size: if (size(axis) == newvalue) return; if (axis == 0) _size_0 = newvalue; else _size_1 = newvalue; break;
- case oldpos: if (oldpos(axis) == newvalue) return; if (axis == 0) _oldpos_0 = newvalue; else _oldpos_1 = newvalue; break;
- case oldsize: if (oldsize(axis) == newvalue) return; if (axis == 0) _oldsize_0 = newvalue; else _oldsize_1 = newvalue; break;
- case pad: if (pad(axis) == newvalue) return; if (axis == 0) _pad_0 = newvalue; else _pad_1 = newvalue; break;
- case textdim: if (textdim(axis) == newvalue) return; if (axis == 0) _textdim_0 = newvalue; else _textdim_1 = newvalue; break;
- default: return;
- }
-
- // size must always agree with dmin/dmax
- if (which == dmin) set(size, axis, max(size(axis), newvalue));
- if (which == dmax) set(size, axis, min(size(axis), newvalue));
-
- // keep cmin in line with dmin/dmax/textdim
- if (which == dmax || which == dmin || which == textdim || which == pad || which == cmin)
- set(cmin, axis,
- max(
- min(dmax(axis), cmin(axis)),
- dmin(axis),
- min(dmax(axis), textdim(axis) + 2 * pad(axis))
- )
- );
-
- // if the pad changes, update cmin
- if (which == pad) sync_cmin_to_children();
-
- // needed in the shrink case, since dmin may have been the deciding factor in calculating cmin
- if ((vshrink || hshrink) && (which == dmin || which == textdim || which == pad)) sync_cmin_to_children();
-
- // if the cmin changes, we need to be re-prerendered
- if (which == cmin) mark_for_prerender();
-
- // if the absolute position of a box changes, its parent needs to be re-prerendered (to update the child's position)
- if (which == abs && getParent() != null) getParent().mark_for_prerender();
-
- // if our cmin changes, then our parent's needs to be recalculated
- if (getParent() != null && which == cmin) {
- mark_for_prerender();
- getParent().sync_cmin_to_children();
- }
-
- }
-
- /** Marks this node and all its ancestors so that they will be prerender()ed */
- public final void mark_for_prerender() {
- if (needs_prerender) return;
- needs_prerender = true;
- if (getParent() != null) getParent().mark_for_prerender();
- }
-
- /** Ensures that cmin is in sync with the cmin's of our children. This should be called whenever a child is added or
- * removed, as well as when our pad is changed. */
- final void sync_cmin_to_children() {
- int co = (int)(2 * pad(o));
- int cxo = (int)(2 * pad(xo));
-
- for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
- if (bt.invisible || bt.absolute) continue;
- co += bt.cmin(o);
- cxo = (int)max(bt.cmin(xo) + 2 * pad(xo), cxo);
- }
-
- set(cmin, o, co);
- set(cmin, xo, cxo);
- }
-
- /** must be called after changes to <tt>image</tt> or <tt>border</tt> if sizetoimage is true */
- public void syncSizeToImage() {
- set(dmax, 0, (image == null ? 0 : image.getWidth()) + (border == null ? 0 : border[2].getWidth()) * 2);
- set(dmax, 1, (image == null ? 0 : image.getHeight()) + (border == null ? 0 : border[0].getHeight()) * 2);
- set(dmin, 0, (image == null ? 0 : image.getWidth()) + (border == null ? 0 : border[2].getWidth()) * 2);
- set(dmin, 1, (image == null ? 0 : image.getHeight()) + (border == null ? 0 : border[0].getHeight()) * 2);
- }
-
- /** returns the actual font that should be used to render this box */
- private String font() {
- if (font != null) return font;
- if (font == null && cachedFont != null) return cachedFont;
- if (getParent() != null) return cachedFont = getParent().font();
- return cachedFont = Platform.getDefaultFont();
- }
-
- /** this must be called when a box's font changes */
- void fontChanged() {
- textupdate();
- for(Box b = getChild(0); b != null; b = b.nextSibling())
- if (b.font == null) {
- b.cachedFont = font();
- b.fontChanged();
- }
- }
-
- /** This must be called when font or text is changed */
- void textupdate() {
- if (text.equals("")) {
- set(textdim, 0, 0);
- set(textdim, 1, 0);
- } else {
- XWF xwf = XWF.getXWF(font());
- if (xwf == null) {
- set(textdim, 0, Platform.stringWidth(font(), text));
- set(textdim, 1, (Platform.getMaxAscent(font()) + Platform.getMaxDescent(font())));
- } else {
- set(textdim, 0, xwf.stringWidth(text));
- set(textdim, 1, (xwf.getMaxAscent() + xwf.getMaxDescent()));
- }
- }
- }
-
-
- // Instance Methods /////////////////////////////////////////////////////////////////////
-
- /** Changes the Surface that this Box draws on. */
- protected void setSurface(Surface newSurface) {
- if (surface == newSurface) return;
- mouseinside = false;
- if ((is_trapped("KeyPressed") || is_trapped("KeyReleased")) && surface != null)
- surface.keywatchers.removeElement(this);
- surface = newSurface;
- if ((is_trapped("KeyPressed") || is_trapped("KeyReleased")) && surface != null)
- surface.keywatchers.addElement(this);
- for(Box i = getChild(0); i != null; i = i.nextSibling()) i.setSurface(surface);
- if (numChildren() == 0) mark_for_prerender();
- }
-
- /** loads the image described by string str, possibly blocking for a network load */
- static ImageDecoder getImage(String str, final JS.Callable callback) {
-
- if (str.indexOf(':') == -1) {
- String s = str;
- byte[] b = Resources.getResource(Resources.resolve(s + ".png", null));
- if (b != null) return PNG.decode(new ByteArrayInputStream(b), str);
- b = Resources.getResource(Resources.resolve(s + ".jpeg", null));
- if (b != null) return Platform.decodeJPEG(new ByteArrayInputStream(b), str);
- return null;
-
- } else {
- java.lang.Thread thread = java.lang.Thread.currentThread();
- if (!(thread instanceof ThreadMessage)) {
- if (Log.on) Log.log(Box.class, "HTTP images can not be loaded from the foreground thread");
- return null;
- }
- // FIXME: use primitives here
- ThreadMessage mythread = (ThreadMessage)thread;
- mythread.setPriority(java.lang.Thread.MIN_PRIORITY);
- mythread.done.release();
- try {
- HTTP http = new HTTP(str);
- final HTTP.HTTPInputStream in = http.GET();
- final int contentLength = in.getContentLength();
- InputStream is = new FilterInputStream(in) {
- int bytesDownloaded = 0;
- boolean clear = true;
- public int read() throws IOException {
- bytesDownloaded++;
- return super.read();
- }
- public int read(byte[] b, int off, int len) throws IOException {
- int ret = super.read(b, off, len);
- if (ret != -1) bytesDownloaded += ret;
- if (clear && callback != null) {
- clear = false;
- ThreadMessage.newthread(new JS.Callable() {
- public Object call(JS.Array args_) throws JS.Exn {
- try {
- JS.Array args = new JS.Array();
- args.addElement(new Double(bytesDownloaded));
- args.addElement(new Double(contentLength));
- callback.call(args);
- } finally {
- clear = true;
- }
- return null;
- }
- });
- }
- return ret;
- }
- };
-
- if (str.endsWith(".gif")) return GIF.decode(is, str);
- else if (str.endsWith(".jpeg") || str.endsWith(".jpg")) return Platform.decodeJPEG(is, str);
- else return PNG.decode(is, str);
-
- } catch (IOException e) {
- if (Log.on) Log.log(Box.class, "error while trying to load an image from " + str);
- if (Log.on) Log.log(Box.class, e);
- return null;
-
- } finally {
- MessageQueue.add(mythread);
- mythread.setPriority(java.lang.Thread.NORM_PRIORITY);
- mythread.go.block();
- }
- }
- }
-
- /** gets an Image using getImage(), adds it to the cache, and creates a Picture from it */
- public static Picture getPicture(String os) {
- Picture ret = null;
- ret = (Picture)pictureCache.get(os);
- if (ret != null) return ret;
- ImageDecoder id = getImage(os, null);
- if (id == null) return null;
- ret = Platform.createPicture(id);
- pictureCache.put(os, ret);
- imageToNameMap.put(ret, os);
- return ret;
- }
-
- /** Sets the image; argument should be a fully qualified s name or an URL */
- void setImage(String s) {
- if ((s == null && image == null) || (s != null && image != null && s.equals(imageToNameMap.get(image)))) return;
- if (s == null || s.equals("")) {
- image = null;
- if (sizetoimage) syncSizeToImage();
- dirty();
- } else {
- image = getPicture(s);
- if (image == null) {
- if (Log.on) Log.logJS(Box.class, "unable to load image " + s);
- return;
- }
- if (sizetoimage) syncSizeToImage();
- dirty();
- }
- }
-
- /** Sets the border; argument should be a fully qualified resource name or an URL */
- void setBorder(String s) {
- if ((s == null && border == null) || (s != null && border != null && s.equals(imageToNameMap.get(border)))) return;
- if (s == null || s.equals("")) {
- border = null;
- if (sizetoimage) syncSizeToImage();
- dirty();
-
- } else {
- border = (Picture[])bordercache.get(s);
- if (border == null) {
- ImageDecoder id = getImage(s, null);
- if (id == null) {
- if (Log.on) Log.logJS(this, "unable to load border image " + s);
- return;
- }
- int[] data = id.getData();
- int w = id.getWidth();
- int h = id.getHeight();
- int hpad = w / 2;
- int vpad = h / 2;
-
- int[][] dat = new int[4][];
- dat[0] = new int[100 * vpad];
- dat[1] = new int[100 * vpad];
- dat[2] = new int[100 * hpad];
- dat[3] = new int[100 * hpad];
-
- for(int i=0; i<100; i++) {
- for(int j=0; j<vpad; j++) {
- dat[0][i + j * 100] = data[hpad + j * w];
- dat[1][i + (vpad - j - 1) * 100] = data[hpad + (h - j - 1) * w];
- }
- for(int j=0; j<hpad; j++) {
- dat[2][j + i * hpad] = data[j + vpad * w];
- dat[3][hpad - j - 1 + i * hpad] = data[w - j - 1 + vpad * w];
- }
- }
-
- border = new Picture[5];
- border[0] = Platform.createPicture(dat[0], 100, vpad);
- border[1] = Platform.createPicture(dat[1], 100, vpad);
- border[2] = Platform.createPicture(dat[2], hpad, 100);
- border[3] = Platform.createPicture(dat[3], hpad, 100);
- border[4] = (Picture)pictureCache.get(s);
- if (border[4] == null) {
- border[4] = Platform.createPicture(data, w, h);
- pictureCache.put(s, border[4]);
- imageToNameMap.put(border[4], s);
- }
- bordercache.put(s, border);
- }
- if (sizetoimage) syncSizeToImage();
- dirty();
- }
- }
-
- /** returns true if the property has a trap on it */
- boolean is_trapped(String property) { return traps != null && traps.get(property) != null; }
-
- /** Adds the node's current actual geometry to the Surface's dirty list */
- void dirty() { dirty(pos(0), pos(1), size(0), size(1)); }
-
- /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
- public final void dirty(int x, int y, int w, int h) {
- for(Box cur = this; cur != null; cur = cur.getParent()) {
- w = min(x + w, cur.pos(0) + cur.size(0)) - max(x, cur.pos(0));
- h = min(y + h, cur.pos(1) + cur.size(1)) - max(y, cur.pos(1));
- x = max(x, cur.pos(0));
- y = max(y, cur.pos(1));
- if (w <= 0 || h <= 0) return;
- }
- if (surface != null) surface.dirty(x, y, w, h);
- }
-
- /**
- * Given an old and new mouse position, this will update <tt>mouseinside</tt> and check
- * to see if this node requires any Enter, Leave, or Move notifications.
- *
- * @param forceleave set to true by the box's parent if the mouse is inside an older
- * sibling, which is covering up this box.
- */
- void Move(int oldmousex, int oldmousey, int mousex, int mousey) { Move(oldmousex, oldmousey, mousex, mousey, false); }
- void Move(int oldmousex, int oldmousey, int mousex, int mousey, boolean forceleave) {
-
- boolean wasinside = mouseinside;
- boolean isinside = !invisible && inside(mousex, mousey) && !forceleave;
- mouseinside = isinside;
-
- if (!wasinside && !isinside) return;
-
- if (!wasinside && isinside && is_trapped("Enter")) put("Enter", this);
- else if (wasinside && !isinside && is_trapped("Leave")) put("Leave", this);
- else if (wasinside && isinside && (mousex != oldmousex || mousey != oldmousey) && is_trapped("Move")) put("Move", this);
-
- if (isinside && cursor != null && surface != null) surface.cursor = cursor;
-
- // if the mouse has moved into our padding region, it is considered 'outside' all our children
- if (!(mousex >= pos(0) + pad(0) && mousey >= pos(1) + pad(1) &&
- mousex < pos(0) + size(0) - pad(0) && mousey < pos(1) + size(1) + pad(1))) forceleave = true;
-
- for(Box b = getChild(numChildren() - 1); b != null; b = b.prevSibling()) {
- b.Move(oldmousex, oldmousey, mousex, mousey, forceleave);
- if (b.inside(mousex, mousey)) forceleave = true;
- }
- }
-
- /** creates a new box from an anonymous template; <tt>ids</tt> is passed through to Template.apply() */
- Box(Template anonymous, Vec pboxes, Vec ptemplates, JS.Callable callback, int numerator, int denominator) {
- super(null);
- set(dmax, 0, Integer.MAX_VALUE);
- set(dmax, 1, Integer.MAX_VALUE);
- template = anonymous;
- template.apply(this, pboxes, ptemplates, callback, numerator, denominator);
- templatename = null;
- importlist = null;
- }
-
- /** creates a new box from an unresolved templatename and an importlist; use "box" for an untemplatized box */
- public Box(String templatename, String[] importlist) { this(templatename, importlist, null); }
- public Box(String templatename, String[] importlist, JS.Callable callback) {
- super(null);
- set(dmax, 0, Integer.MAX_VALUE);
- set(dmax, 1, Integer.MAX_VALUE);
- this.importlist = importlist;
- if (!"box".equals(templatename)) {
- template = Template.getTemplate(templatename, importlist);
- if (template == null)
- if (Log.on) Log.log(this, "couldn't find template \"" + templatename + "\"");
- }
- if (template != null) {
- this.templatename = templatename;
- template.apply(this, null, null, callback, 0, template.numUnits());
- if (redirect == this && !"self".equals(template.redirect)) redirect = null;
- }
- }
-
-
- // Prerendering Pipeline ///////////////////////////////////////////////////////////////
-
- /** Checks if the Box's size has changed, dirties it if necessary, and makes sure childrens' sizes are up to date */
- void prerender() {
-
- if (invisible) return;
-
- if (getParent() == null) {
- set(pos, 0, 0);
- set(pos, 1, 0);
- }
-
- if (pos(0) != oldpos(0) || pos(1) != oldpos(1) || size(0) != oldsize(0) || size(1) != oldsize(1)) {
- needs_prerender = true;
- check_geometry_changes();
- }
-
- if (!needs_prerender) return;
- needs_prerender = false;
- if (numChildren() == 0) return;
-
- int sumchildren = sizeChildren();
- positionChildren(pos(o) + pad(o) + max(0, size(o) - 2 * pad(o) - sumchildren) / 2);
-
- for(Box b = getChild(0); b != null; b = b.nextSibling()) {
- b.prerender();
- if (surface.abort) {
- mark_for_prerender();
- return;
- }
- }
- }
-
- /** if the size or position of a box has changed, dirty() the appropriate regions and possibly send Enter/Leave/SizeChange/PosChange */
- private void check_geometry_changes() {
-
- // FASTPATH: if we haven't moved position (just changed size), and we're not a stretched image:
- if (oldpos(0) == pos(0) && oldpos(1) == pos(1) && (image == null || tile)) {
-
- // we use the max(border, pad) since because of the pad we might be revealing an abs-pos child
- int bw = max(border == null ? 0 : border[2].getWidth(), pad(0));
- int bh = max(border == null ? 0 : border[0].getHeight(), pad(1));
-
- // dirty only the *change* in the area we cover, both on ourselves and on our parent
- for(Box cur = this; cur != null && (cur == this || cur == this.getParent()); cur = cur.getParent()) {
- cur.dirty(pos(0) + min(oldsize(0) - bw, size(0) - bw),
- pos(1),
- java.lang.Math.abs(oldsize(0) - size(0)) + bw,
- max(oldsize(1), size(1)));
- cur.dirty(pos(0),
- pos(1) + min(oldsize(1) - bh, size(1) - bh),
- max(oldsize(0), size(0)),
- java.lang.Math.abs(oldsize(1) - size(1)) + bh);
- }
-
- // SLOWPATH: dirty ourselves, as well as our former position on our parent
- } else {
- dirty();
- if (getParent() != null) getParent().dirty(oldpos(0), oldpos(1), oldsize(0), oldsize(1));
-
- }
-
- boolean sizechange = false;
- boolean poschange = false;
- if ((oldsize(0) != size(0) || oldsize(1) != size(1)) && is_trapped("SizeChange")) sizechange = true;
- if ((oldpos(0) != pos(0) || oldpos(1) != pos(1)) && is_trapped("PosChange")) poschange = true;
-
- set(oldsize, 0, size(0));
- set(oldsize, 1, size(1));
- set(oldpos, 0, pos(0));
- set(oldpos, 1, pos(1));
-
- if (!sizechange && !poschange) return;
-
- if (++surface.sizePosChangesSinceLastRender >= 500) {
- if (surface.sizePosChangesSinceLastRender == 500) {
- if (Log.on) Log.logJS(this, "Warning, more than 500 SizeChange/PosChange traps triggered since last complete render");
- /*
- try {
- Trap t = sizechange ? Trap.getTrap(this, "SizeChange") : Trap.getTrap(this, "PosChange");
- InterpretedJS.Callable f = (InterpretedJS.Callable)t.f;
- if (Log.on) Log.log(this, "Current trap is at " + f.getSourceName() + ":" + f.getLineNumbers()[0]);
- } catch (Throwable t) { }
- */
- }
- } else {
- if (sizechange) put("SizeChange", Boolean.TRUE);
- if (poschange) put("PosChange", Boolean.TRUE);
- if (sizechange || poschange) {
- surface.abort = true;
- return;
- }
- }
- }
-
-
- /** sets our childrens' sizes */
- int sizeChildren() {
-
- // Set sizes along minor axis, as well as sizes for absolute-positioned children
- for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
- if (bt.invisible) continue;
- if (bt.absolute) {
- bt.set(size, 0, bt.hshrink ? bt.cmin(0) : max(bt.cmin(0), min(size(0) - bt.abs(0) - pad(0), bt.dmax(0))));
- bt.set(size, 1, bt.vshrink ? bt.cmin(1) : max(bt.cmin(1), min(size(1) - bt.abs(1) - pad(1), bt.dmax(1))));
- } else if (xo == 0 && bt.hshrink || xo == 1 && bt.vshrink) {
- bt.set(size, xo, bt.cmin(xo));
- } else {
- bt.set(size, xo, bound(bt.cmin(xo), size(xo) - 2 * pad(xo), bt.dmax(xo)));
- }
- }
-
- // the ideal size of our children, along our own major axis
- int goal = (o == 0 && hshrink) || (o == 1 && vshrink) ? cmin(o) - 2 * pad(o) : size(o) - 2 * pad(o);
-
- // the current sum of the sizes of all children
- int total = 0;
-
- // each box is set to bound(box.cmin, box.flex * factor, box.dmax)
- int factor = 0;
-
- // Algorithm: we set the sizes of all boxes to bound(cmin, flex * factor, dmax) for some global value
- // 'factor'. We figure out what 'factor' should be by starting at zero, and slowly increasing
- // it. After each pass, 'factor' is set to the smaller of two values: ((goal - total) /
- // remaining_flex) or the next largest value of factor which will cause some box to exceed its
- // cmin or dmax (thereby changing remaining_flex).
-
- while(true) {
- total = 0;
-
- // the sum of the flexes of all boxes which are not pegged at either cmin or dmax
- int remaining_flex = 0;
-
- // this is the next largest value of factor at which some box exceeds its cmin/dmax
- int nextjoint = Integer.MAX_VALUE;
-
- for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
- if (bt.absolute || bt.invisible) continue;
-
- int btmax = (o == 0 && bt.hshrink) || (o == 1 && bt.vshrink) ? bt.cmin(o) : bt.dmax(o);
- bt.set(size, o, bound(bt.cmin(o), factor * bt.flex, btmax));
- total += bt.size(o);
-
- if (factor * bt.flex < bt.cmin(o) && bt.size(o) == bt.cmin(o)) {
- nextjoint = min(nextjoint, divide_round_up(bt.cmin(o), bt.flex));
-
- } else if (bt.size(o) < btmax) {
- remaining_flex += bt.flex;
- nextjoint = min(nextjoint, divide_round_up(btmax, bt.flex));
-
- }
- }
-
- if (remaining_flex == 0) {
- if (nextjoint <= factor) break;
- factor = nextjoint;
- } else {
- factor = min((goal - total + factor * remaining_flex) / remaining_flex, nextjoint);
- }
-
- if (goal - total <= remaining_flex) break;
- }
-
- // arbitrarily distribute out any leftovers resulting from rounding errors
- int last = 0;
- while(goal != total && total != last) {
- last = total;
- for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
- int btmax = (o == 0 && bt.hshrink) || (o == 1 && bt.vshrink) ? bt.cmin(o) : bt.dmax(o);
- int newsize = bound(bt.cmin(o), bt.size(o) + (goal > total ? 1 : -1), btmax);
- total += newsize - bt.size(o);
- bt.set(size, o, newsize);
- }
- }
-
- return total;
- }
-
- /** positions this Box's children; cur is the starting position along this' major axis */
- void positionChildren(int cur) {
- for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) {
- if (bt.invisible) continue;
- if (bt.absolute) {
- bt.set(pos, 0, pos(0) + bt.abs(0));
- bt.set(pos, 1, pos(1) + bt.abs(1));
- } else {
- bt.set(pos, xo, pos(xo) + pad(xo) + max(0, ((size(xo) - 2 * pad(xo) - bt.size(xo)) * (bt.align + 1)) / 2));
- bt.set(pos, o, cur);
- bt.set(abs, 0, bt.pos(0) - pos(0));
- bt.set(abs, 1, bt.pos(1) - pos(1));
- cur += bt.size(o);
- }
- }
- }
-
-
- // Rendering Pipeline /////////////////////////////////////////////////////////////////////
-
- /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
- void render(int xIn, int yIn, int wIn, int hIn, DoubleBuffer buf) {
- if (surface.abort || invisible) return;
-
- // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
- int x = max(xIn, getParent() == null ? 0 : pos(0));
- int y = max(yIn, getParent() == null ? 0 : pos(1));
- int w = min(xIn + wIn, (getParent() == null ? 0 : pos(0)) + size(0)) - x;
- int h = min(yIn + hIn, (getParent() == null ? 0 : pos(1)) + size(1)) - y;
- if (w <= 0 || h <= 0) return;
-
- if (border != null) renderBorder(x, y, w, h, buf);
- if ((color & 0xFF000000) != 0x00000000 || getParent() == null) {
- int bw = border == null ? 0 : border[2].getWidth();
- int bh = border == null ? 0 : border[0].getHeight();
- int x1 = max(x, pos(0) + bw);
- int y1 = max(y, pos(1) + bh);
- int x2 = min(x + w, pos(0) + size(0) - bw);
- int y2 = min(y + h, pos(1) + size(1) - bh);
- if (y2 - y1 > 0 && x2 - x1 > 0)
- buf.fillRect(x1,y1,x2,y2,(color & 0xFF000000) != 0 ? color : SpecialBoxProperty.lightGray);
- }
-
- if (image != null) {
- if (tile) renderTiledImage(x, y, w, h, buf);
- else renderStretchedImage(x, y, w, h, buf);
- }
-
- if (text != null && !text.equals("")) renderText(x, y, w, h, buf);
-
- // now subtract the pad region from the clip region before proceeding
- int x2 = max(x, pos(0) + pad(0));
- int y2 = max(y, pos(1) + pad(1));
- int w2 = min(x + w, pos(0) + size(0) - pad(0)) - x2;
- int h2 = min(y + h, pos(1) + size(1) - pad(1)) - y2;
-
- for(Box b = getChild(0); b != null; b = b.nextSibling())
- b.render(x2, y2, w2, h2, buf);
- }
-
- private void renderBorder(int x, int y, int w, int h, DoubleBuffer buf) {
- int bw = border[4].getWidth();
- int bh = border[4].getHeight();
- buf.setClip(x, y, w + x, h + y);
-
- if ((color & 0xFF000000) != 0xFF000000) {
- // if the color is null, we have to be very careful about drawing the corners
- //if (Log.verbose) Log.log(this, "WARNING: (color == null && border != null) on box with border " + imageToNameMap.get(border[4]));
-
- // upper left corner
- buf.drawPicture(border[4],
- pos(0), pos(1), pos(0) + bw / 2, pos(1) + bh / 2,
- 0, 0, bw / 2, bh / 2);
-
- // upper right corner
- buf.drawPicture(border[4],
- pos(0) + size(0) - bw / 2, pos(1), pos(0) + size(0), pos(1) + bh / 2,
- bw - bw / 2, 0, bw, bh / 2);
-
- // lower left corner
- buf.drawPicture(border[4],
- pos(0), pos(1) + size(1) - bh / 2, pos(0) + bw / 2, pos(1) + size(1),
- 0, bh - bh / 2, bw / 2, bh);
-
- // lower right corner
- buf.drawPicture(border[4],
- pos(0) + size(0) - bw / 2, pos(1) + size(1) - bh / 2, pos(0) + size(0), pos(1) + size(1),
- bw - bw / 2, bh - bh / 2, bw, bh);
-
- } else {
- buf.drawPicture(border[4], pos(0), pos(1)); // upper left corner
- buf.drawPicture(border[4], pos(0) + size(0) - bw, pos(1)); // upper right corner
- buf.drawPicture(border[4], pos(0), pos(1) + size(1) - bh); // lower left corner
- buf.drawPicture(border[4], pos(0) + size(0) - bw, pos(1) + size(1) - bh); // lower right corner
-
- }
-
- // top and bottom edges
- buf.setClip(max(x, pos(0) + bw / 2), y, min(x + w, pos(0) + size(0) - bw / 2), h + y);
- for(int i = max(x, pos(0) + bw / 2); i + 100 < min(x + w, pos(0) + size(0) - bw / 2); i += 100) {
- buf.drawPicture(border[0], i, pos(1));
- buf.drawPicture(border[1], i, pos(1) + size(1) - bh / 2);
- }
- buf.drawPicture(border[0], min(x + w, pos(0) + size(0) - bw / 2) - 100, pos(1));
- buf.drawPicture(border[1], min(x + w, pos(0) + size(0) - bw / 2) - 100, pos(1) + size(1) - bh / 2);
-
- // left and right edges
- buf.setClip(x, max(y, pos(1) + bh / 2), w + x, min(y + h, pos(1) + size(1) - bh / 2));
- for(int i = max(y, pos(1) + bh / 2); i + 100 < min(y + h, pos(1) + size(1) - bh / 2); i += 100) {
- buf.drawPicture(border[2], pos(0), i);
- buf.drawPicture(border[3], pos(0) + size(0) - bw / 2, i);
- }
- buf.drawPicture(border[2], pos(0), min(y + h, pos(1) + size(1) - bh / 2) - 100);
- buf.drawPicture(border[3], pos(0) + size(0) - bw / 2, min(y + h, pos(1) + size(1) - bh / 2) - 100);
-
- buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
- }
-
- void renderStretchedImage(int x, int y, int w, int h, DoubleBuffer buf) {
- buf.setClip(x, y, w + x, h + y);
- int bw = border == null ? 0 : border[4].getHeight();
- int bh = border == null ? 0 : border[4].getWidth();
-
- int width = pos(0) + size(0) - bw / 2 - pos(0) + bw / 2;
- int height = pos(1) + size(1) - bh / 2 - pos(1) + bh / 2;
-
- if (fixedaspect) {
- int hstretch = width / image.getWidth();
- if (hstretch == 0) hstretch = -1 * image.getWidth() / width;
- int vstretch = height / image.getHeight();
- if (vstretch == 0) vstretch = -1 * image.getHeight() / height;
-
- if (hstretch < vstretch) {
- height = image.getHeight() * width / image.getWidth();
- } else {
- width = image.getWidth() * height / image.getHeight();
- }
- }
-
- buf.drawPicture(image,
- pos(0) + bw / 2,
- pos(1) + bh / 2,
- pos(0) + bw / 2 + width,
- pos(1) + bh / 2 + height,
- 0, 0, image.getWidth(), image.getHeight());
- buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
- }
-
- void renderTiledImage(int x, int y, int w, int h, DoubleBuffer buf) {
- int iw = image.getWidth();
- int ih = image.getHeight();
- int bh = border == null ? 0 : border[4].getWidth();
- int bw = border == null ? 0 : border[4].getHeight();
-
- for(int i=(x - pos(0) - bw)/iw; i <= (x + w - pos(0) - bw)/iw; i++) {
- for(int j=(y - pos(1) - bh)/ih; j<= (y + h - pos(1) - bh)/ih; j++) {
-
- int dx1 = max(i * iw + pos(0), x);
- int dy1 = max(j * ih + pos(1), y);
- int dx2 = min((i+1) * iw + pos(0), x + w);
- int dy2 = min((j+1) * ih + pos(1), y + h);
-
- int sx1 = dx1 - (i*iw) - pos(0);
- int sy1 = dy1 - (j*ih) - pos(1);
- int sx2 = dx2 - (i*iw) - pos(0);
- int sy2 = dy2 - (j*ih) - pos(1);
-
- if (dx2 - dx1 > 0 && dy2 - dy1 > 0 && sx2 - sx1 > 0 && sy2 - sy1 > 0)
- buf.drawPicture(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
- }
- }
-
- }
-
- void renderText(int x, int y, int w, int h, DoubleBuffer buf) {
-
- if ((textcolor & 0xFF000000) == 0x00000000) return;
- buf.setClip(x, y, w + x, h + y);
-
- XWF xwf = XWF.getXWF(font());
- if (xwf != null) {
- xwf.drawString(buf, text,
- pos(0) + pad(0),
- pos(1) + pad(1) + xwf.getMaxAscent() - 1,
- textcolor);
- } else {
- buf.drawString(font(), text,
- pos(0) + pad(0),
- pos(1) + pad(1) + Platform.getMaxAscent(font()) - 1,
- textcolor);
- }
-
- buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
-
- int i=0; while(i<font().length() && !Character.isDigit(font().charAt(i))) i++;
-
- if (font().lastIndexOf('d') > i) {
- for(int j = pos(0) + pad(0); j < pos(0) + pad(0) + textdim(0); j += 2)
- buf.fillRect(j, pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2,
- j + 1, pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2 + 1,
- textcolor);
-
- } else if (font().lastIndexOf('u') > i) {
- buf.fillRect(pos(0) + pad(0),
- pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2,
- pos(0) + pad(0) + textdim(0),
- pos(1) + pad(1) + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2 + 1,
- textcolor);
- }
-
- }
-
-
- // Methods to implement org.mozilla.javascript.Scriptable //////////////////////////////////////
-
- /** Returns the i_th child */
- public Object get(int i) {
- if (redirect == null) return null;
- if (redirect != this) return redirect.get(i);
- return i >= numChildren() || i < 0 ? null : getChild(i);
- }
-
- /**
- * Inserts value as child i; calls remove() if necessary.
- * This method handles "reinserting" one of your children properly.
- * INVARIANT: after completion, getChild(min(i, numChildren())) == newnode
- * WARNING: O(n) runtime, unless i == numChildren()
- */
- public void put(int i, Object value) {
- if (i < 0) return;
-
- if (value != null && !(value instanceof Box)) {
- if (Log.on) Log.logJS(this, "attempt to set a numerical property on a box to anything other than a box");
- } else if (redirect == null) {
- if (Log.on) Log.logJS(this, "attempt to add/remove children to/from a node with a null redirect");
- } else if (redirect != this) {
- Box b = value == null ? (Box)redirect.get(i) : (Box)value;
- redirect.put(i, value);
- put("0", b);
-
- } else if (value == null) {
- if (i >= 0 && i < numChildren()) {
- Box b = getChild(i);
- b.remove();
- put("0", b);
- }
-
- } else if (value instanceof RootProxy) {
- if (Log.on) Log.logJS(this, "attempt to reparent a box via its proxy object");
-
- } else {
- Box newnode = (Box)value;
-
- // check if box being moved is currently target of a redirect
- for(Box cur = newnode.getParent(); cur != null; cur = cur.getParent())
- if (cur.redirect == newnode) {
- if (Log.on) Log.logJS(this, "attempt to move a box that is the target of a redirect");
- return;
- }
-
- // check for recursive ancestor violation
- for(Box cur = this; cur != null; cur = cur.getParent())
- if (cur == newnode) {
- if (Log.on) Log.logJS(this, "attempt to make a node a parent of its own ancestor");
- if (Log.on) Log.log(this, "box == " + this + " ancestor == " + newnode);
- return;
- }
-
- if (numKids > 15 && children == null) convert_to_array();
- newnode.remove();
- newnode.parent = this;
-
- if (children == null) {
- if (firstKid == null) {
- firstKid = newnode;
- newnode.prevSibling = newnode;
- newnode.nextSibling = newnode;
- } else if (i >= numKids) {
- newnode.prevSibling = firstKid.prevSibling;
- newnode.nextSibling = firstKid;
- firstKid.prevSibling.nextSibling = newnode;
- firstKid.prevSibling = newnode;
- } else {
- Box cur = firstKid;
- for(int j=0; j<i; j++) cur = cur.nextSibling;
- newnode.prevSibling = cur.prevSibling;
- newnode.nextSibling = cur;
- cur.prevSibling.nextSibling = newnode;
- cur.prevSibling = newnode;
- if (i == 0) firstKid = newnode;
- }
- numKids++;
-
- } else {
- if (i >= children.size()) {
- newnode.indexInParent = children.size();
- children.addElement(newnode);
- } else {
- children.insertElementAt(newnode, i);
- for(int j=i; j<children.size(); j++)
- getChild(j).indexInParent = j;
- }
- }
- newnode.setSurface(surface);
-
- // need both of these in case child was already uncalc'ed
- newnode.mark_for_prerender();
- mark_for_prerender();
-
- newnode.dirty();
- sync_cmin_to_children();
-
- // note that JavaScript box[0] will invoke put(int i), not put(String s)
- put("0", newnode);
- }
- }
-
- public Object get(Object name) { return get(name, false); }
- public Object get(Object name_, boolean ignoretraps) {
- if (name_ instanceof Number) return get(((Number)name_).intValue());
-
- if (!(name_ instanceof String)) return null;
- String name = (String)name_;
- if (name.equals("")) return null;
-
- // See if we're reading back the function value of a trap
- if (name.charAt(0) == '_') {
- if (name.charAt(1) == '_') name = name.substring(2);
- else name = name.substring(1);
- Trap t = Trap.getTrap(this, name);
- return t == null ? null : t.f;
- }
-
- // See if we're triggering a trap
- Trap t = traps == null || ignoretraps ? null : (Trap)traps.get(name);
- if (t != null && t.isreadtrap) return t.perform(emptyobj);
-
- // Check for a special handler
- SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
- if (gph != null) return gph.get(this);
-
- Object ret = super.get(name);
- if (name.startsWith("$") && ret == null)
- if (Log.on) Log.logJS(this, "WARNING: attempt to access " + name + ", but no child with id=\"" + name.substring(1) + "\" found");
- return ret;
- }
-
- public Object[] keys() {
- Object[] ret = new Object[numChildren()];
- for(int i=0; i<ret.length; i++) ret[i] = new Integer(i);
- return ret;
- }
-
- /**
- * Scriptable.put()
- * @param ignoretraps if set, no traps will be triggered (set when 'cascade' reaches the bottom of the trap stack)
- * @param rp if this put is being performed via a root proxy, rp is the root proxy.
- */
- public void put(Object name, Object value) { put(name, value, false, null); }
- public void put(Object name, Object value, boolean ignoretraps) { put(name, value, ignoretraps, null); }
- public void put(Object name_, Object value, boolean ignoretraps, RootProxy rp) {
- if (name_ instanceof Number) { put(((Number)name_).intValue(), value); return; }
- if (!(name_ instanceof String)) { super.put(name_,value); return; }
- String name = name_.toString();
- if (name == null) return; // FIXME, shouldn't be necessary
- if (name.startsWith("xwt_")) {
- if (Log.on) Log.logJS(this, "attempt to set reserved property " + name);
- return;
- }
-
- if (!ignoretraps && traps != null) {
- Trap t = (Trap)traps.get(name);
- if (t != null) {
- JS.Array arg = new JS.Array();
- arg.addElement(value);
- t.perform(arg);
- arg.setElementAt(null, 0);
- return;
- }
- }
-
- // don't want to really cascade down to the box on this one
- if (name.equals("0")) return;
-
- SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
- if (gph != null) {
- gph.put(name, this, value);
- return;
- }
-
- if (name.charAt(0) == '_') {
- if (value != null && !(value instanceof JS.Callable)) {
- if (Log.on) Log.logJS(this, "attempt to put a non function value (" + value + ") to " + name);
- } else if (value != null && !(value instanceof JS.CompiledFunction)) {
- if (Log.on) Log.logJS(this, "attempt to put a non-compiled function value (" + value + ") to " + name);
- } else if (name.charAt(1) == '_') {
- name = name.substring(2).intern();
- Trap t = Trap.getTrap(this, name);
- if (t != null) t.delete();
- if (value != null) Trap.addTrap(this, name, ((JS.CompiledFunction)value), true, rp);
- } else {
- name = name.substring(1).intern();
- Trap t = Trap.getTrap(this, name);
- if (t != null) t.delete();
- if (value != null) Trap.addTrap(this, name, ((JS.CompiledFunction)value), false, rp);
- }
- return;
- }
-
- super.put(name, value);
-
- // a bit of a hack, since titlebar is the only 'special' property stored in JSObject
- if (getParent() == null && surface != null) {
- if (name.equals("titlebar")) surface.setTitleBarText(value.toString());
- if (name.equals("icon")) {
- Picture pic = Box.getPicture(value.toString());
- if (pic != null) surface.setIcon(pic);
- else if (Log.on) Log.log(this, "unable to load icon " + value);
- }
- }
- }
-
-
- // Tree Manipulation /////////////////////////////////////////////////////////////////////
-
- /** The parent of this node */
- private Box parent = null;
-
- // Variables used in Vector mode */
- /** INVARIANT: if (parent != null) parent.children.elementAt(indexInParent) == this */
- private int indexInParent;
- private Vec children = null;
-
- // Variables used in linked-list mode
- private int numKids = 0;
- private Box nextSibling = null;
- private Box prevSibling = null;
- private Box firstKid = null;
-
- // when we get more than 15 children, we switch to array-mode
- private void convert_to_array() {
- children = new Vec(numKids);
- Box cur = firstKid;
- do {
- children.addElement(cur);
- cur.indexInParent = children.size() - 1;
- cur = cur.nextSibling;
- } while (cur != firstKid);
- }
-
- /** remove this node from its parent; INVARIANT: whenever the parent of a node is changed, remove() gets called. */
- public void remove() {
- cachedFont = null;
- if (parent == null) {
- if (surface != null) surface.dispose(true);
- return;
- }
- Box oldparent = getParent();
- if (oldparent == null) return;
- mark_for_prerender();
- dirty();
- mouseinside = false;
-
- if (parent.children != null) {
- parent.children.removeElementAt(indexInParent);
- for(int j=indexInParent; j<parent.children.size(); j++)
- (parent.getChild(j)).indexInParent = j;
-
- } else {
- if (parent.firstKid == this) {
- if (nextSibling == this) parent.firstKid = null;
- else parent.firstKid = nextSibling;
- }
- parent.numKids--;
- prevSibling.nextSibling = nextSibling;
- nextSibling.prevSibling = prevSibling;
- prevSibling = null;
- nextSibling = null;
- }
- parent = null;
-
- if (oldparent != null) oldparent.sync_cmin_to_children();
- setSurface(null);
-
- // note that JavaScript box[0] will invoke put(int i), not put(String s)
- if (oldparent != null) oldparent.put("0", this);
- }
-
- /** returns our next sibling (parent[ourindex + 1]) */
- public final Box nextSibling() {
- if (parent == null) return null;
- if (parent.children == null) {
- if (nextSibling == parent.firstKid) return null;
- return nextSibling;
- } else {
- if (indexInParent >= parent.children.size() - 1) return null;
- return (Box)parent.children.elementAt(indexInParent + 1);
- }
- }
-
- /** returns our next sibling (parent[ourindex + 1]) */
- public final Box prevSibling() {
- if (parent == null) return null;
- if (parent.children == null) {
- if (this == parent.firstKid) return null;
- return prevSibling;
- } else {
- if (indexInParent == 0) return null;
- return (Box)parent.children.elementAt(indexInParent - 1);
- }
- }
-
- /** Returns the parent of this node */
- public Box getParent() { return parent; }
-
- /** Returns ith child */
- public Box getChild(int i) {
- if (children == null) {
- if (firstKid == null) return null;
- if (i >= numKids) return null;
- if (i == numKids - 1) return firstKid.prevSibling;
- Box cur = firstKid;
- for(int j=0; j<i; j++) cur = cur.nextSibling;
- return cur;
- } else {
- if (i >= children.size() || i < 0) return null;
- return (Box)children.elementAt(i);
- }
- }
-
- /** Returns the number of children */
- public int numChildren() {
- if (children == null) {
- if (firstKid == null) return 0;
- int i=1;
- for(Box cur = firstKid.nextSibling; cur != firstKid; i++) cur = cur.nextSibling;
- return i;
- } else {
- return children.size();
- }
- }
-
- /** Returns our index in our parent */
- public int getIndexInParent() {
- if (parent == null) return 0;
- if (parent.children == null) {
- int i = 0;
- for(Box cur = this; cur != parent.firstKid; i++) cur = cur.prevSibling;
- return i;
- } else {
- return indexInParent;
- }
- }
-
- /** returns the root of the surface that this box belongs to */
- public final Box getRoot() {
- if (getParent() == null && surface != null) return this;
- if (getParent() == null) return null;
- return getParent().getRoot();
- }
-
-
- // Root Proxy ///////////////////////////////////////////////////////////////////////////////
-
- RootProxy myproxy = null;
- public JS getRootProxy() {
- if (myproxy == null) myproxy = new RootProxy(this);
- return myproxy;
- }
-
- private static class RootProxy extends JS {
- Box box;
- RootProxy(Box b) { this.box = b; }
- public Object get(Object name) { return box.get(name); }
- public void put(Object name, Object value) { box.put(name, value, false, this); }
- public Object[] keys() { return box.keys(); }
- public Object callMethod(Object method, JS.Array args, boolean justChecking) {
- return box.callMethod(method,args,justChecking);
- }
- }
-
-
- // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
-
- /** helper, included in this class so it can be inlined */
- static final int min(int a, int b) {
- if (a<b) return a;
- else return b;
- }
-
- /** helper, included in this class so it can be inlined */
- static final double min(double a, double b) {
- if (a<b) return a;
- else return b;
- }
-
- /** helper, included in this class so it can be inlined */
- static final int max(int a, int b) {
- if (a>b) return a;
- else return b;
- }
-
- /** helper, included in this class so it can be inlined */
- static final int min(int a, int b, int c) {
- if (a<=b && a<=c) return a;
- else if (b<=c && b<=a) return b;
- else return c;
- }
-
- /** helper, included in this class so it can be inlined */
- static final int max(int a, int b, int c) {
- if (a>=b && a>=c) return a;
- else if (b>=c && b>=a) return b;
- else return c;
- }
-
- /** helper, included in this class so it can be inlined */
- static final int bound(int a, int b, int c) {
- if (c < b) return c;
- if (a > b) return a;
- return b;
- }
-
- /** returns numerator/denominator, but rounds <i>up</i> instead of down */
- static final int divide_round_up(int numerator, int denominator) {
-
- // cope with bozos who use flex==0.0
- if (denominator == 0) return Integer.MAX_VALUE;
-
- int ret = numerator / denominator;
- if (ret * denominator < numerator) return ret + 1;
- return ret;
- }
-
- /** Simple helper function to determine if the point x,y falls within this node's actual current geometry */
- boolean inside(int x, int y) {
- if (invisible) return false;
- return (x >= pos(0) && y >= pos(1) && x < pos(0) + size(0) && y < pos(1) + size(1));
- }
-
- /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface
- *
- * IMPORTANT: this method gets called from the event-queueing thread, since we need to determine which box is
- * underneath the mouse as early as possible. Because of this, we have to do some extra checks, as the
- * Box tree may be in flux.
- */
- Box whoIs(int x, int y) {
- if (invisible) return null;
- if (!inside(x,y)) return getParent() == null ? this : null;
-
- // We do this because whoIs is unsynchronized (for
- // speed), yet is sometimes called while the structure of the
- // Box is in flux.
- for(int i=numChildren() - 1; i>=0; i--) {
-
- Box child = getChild(i);
- if (child == null) continue;
-
- Box bt = child.whoIs(x,y);
- if (bt != null) return bt;
- }
- return this;
- }
-
- // This is the name returned by typeof() by JS
- public String typeName() {
- return "box";
- }
-
-}
-
-
--- /dev/null
+// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
+package org.xwt;
+
+// **** This file must be preprocessed before compilation ****
+
+// FIXME: align
+// FIXME use bitfields
+// FIXME fixedaspect
+// FIXME: reflow before allowing js to read from width/height
+// FIXME: due to font inheritance, we must dirty and mark all null-font descendents of a node if its font changes
+// FEATURE: fastpath for rows=1/cols=1
+// FEATURE: reflow starting with a certain child
+// FEATURE: separate mark_for_reflow and mark_for_resize
+
+import java.io.*;
+import java.net.*;
+import java.util.*;
+import org.xwt.js.*;
+import org.xwt.util.*;
+
+/**
+ * <p>
+ * Encapsulates the data for a single XWT box as well as all layout
+ * rendering logic.
+ * </p>
+ *
+ * <p>
+ * This is the real meat of XWT. Part of its monolithic design is for
+ * performance reasons: deep inheritance heirarchies are slow, and
+ * neither javago nor GCJ can inline across class boundaries.
+ * </p>
+ *
+ * <p>The rendering process consists of three phases; each requires
+ * one DFS pass over the tree</p>
+ *
+ * <ol><li> <b>repacking</b>: children of a box are packed into columns
+ * and rows according to their colspan/rowspan attributes and
+ * ordering. Minimum and maximum sizes of columns are computed.
+ *
+ * <li> <b>resizing</b>: width/height and x/y positions of children
+ * are assigned. If a PosChange or SizeChange is triggered,
+ * <tt>abort</tt> will be set and the resizing process will
+ * abort.
+ *
+ * <li> <b>repainting</b>: children draw their content onto the
+ * buffer.
+ * </ol>
+ *
+ * The first two passes together are called the <i>reflow</i> phase.
+ *
+ * Reflowing is done in a seperate pass since PosChanges and
+ * SizeChanges trigger an abort; if rendering were done in the same
+ * pass, rendering work done prior to the abort would be wasted.
+ *
+ * Repacking is seperate from resizing since a box's size depends on
+ * both the box's parent's size (so the traversal must be preorder)
+ * contentwidths of siblings both before and after the box, which in
+ * turn depend on all descendents of the siblings. FIXME
+ *
+ * A note on coordinates: the Box class represents regions
+ * internally as x,y,w,h tuples, even though the DoubleBuffer class
+ * uses x1,y1,x2,y2 tuples.
+ */
+public final class Box extends JS.Scope {
+
+ public Box() { super(null); }
+
+
+ // Misc instance data ////////////////////////////////////////////////////////////////
+
+ public static boolean abort = false;
+ private static int sizePosChangesSinceLastRender = 0;
+
+
+ // Misc instance data ////////////////////////////////////////////////////////////////
+
+ boolean needs_reflow = true;
+ //#define MARK_FOR_REFLOW_this for(Box b2 = this; b2 != null && !b2.needs_reflow; b2 = b2.parent) b2.needs_reflow = true;
+ //#define MARK_FOR_REFLOW_b for(Box b2 = b; b2 != null && !b2.needs_reflow; b2 = b2.parent) b2.needs_reflow = true;
+ //#define MARK_FOR_REFLOW_b_parent for(Box b2 = b.parent; b2 != null && !b2.needs_reflow; b2 = b2.parent) b2.needs_reflow = true;
+
+ private boolean mouseinside = false;
+ Box redirect = this;
+ Surface surface = null; // null on all non-root boxen
+ Hash traps = null;
+
+
+ // Geometry ////////////////////////////////////////////////////////////////////////////
+
+ // xwt can be compiled with 16-bit lengths to save memory on small devices
+ //#define LENGTH int
+ //#define MAX_LENGTH Integer.MAX_VALUE
+ //#define MIN_LENGTH Integer.MIN_VALUE
+
+ // always correct (set directly by user)
+ LENGTH minwidth = 0;
+ LENGTH minheight = 0;
+ LENGTH maxwidth = MAX_LENGTH;
+ LENGTH maxheight = MAX_LENGTH;
+ private LENGTH hpad = 0;
+ private LENGTH vpad = 0;
+ private String text = null;
+ private String font = null;
+ private LENGTH textwidth = 0;
+ private LENGTH textheight = 0;
+
+ // FIXME: use shorts
+ private int rows = 1;
+ private int cols = 0;
+ private int rowspan = 1;
+ private int colspan = 1;
+
+ // computed during reflow
+ LENGTH x = 0;
+ LENGTH y = 0;
+ LENGTH width = 0;
+ LENGTH height = 0;
+ private int row = 0; // FIXME short
+ private int col = 0; // FIXME short
+ private LENGTH contentwidth = 0; // == max(minwidth, textwidth, sum(child.contentwidth) + pad)
+ private LENGTH contentheight = 0;
+
+
+ // Rendering Properties ///////////////////////////////////////////////////////////
+
+ //private SVG.VP path = null;
+ //private SVG.Paint fill = null;
+ //private SVG.Paint stroke = null;
+
+ private Picture image; // will disappear
+ private int fillcolor = 0x00000000; // will become SVG.Paint
+ private int strokecolor = 0xFF000000; // will become SVG.Paint
+
+ private String cursor = null; // the cursor for this box
+
+ //FIXME make private
+ public boolean invisible = false; // true iff the Box is invisible
+ private boolean absolute = false; // If true, the box will be positioned absolutely
+ private boolean vshrink = false; // If true, the box will shrink to the smallest vertical size possible
+ private boolean hshrink = false; // If true, the box will shrink to the smallest horizontal size possible
+ private boolean tile = false; // FIXME: drop this?
+
+ // Instance Methods /////////////////////////////////////////////////////////////////////
+
+ // FIXME: rethink
+ /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */
+ public final void dirty() { dirty(x, y, width, height); }
+ public final void dirty(int x, int y, int w, int h) {
+ for(Box cur = this; cur != null; cur = cur.parent) {
+ w = min(x + w, this.x + this.width) - max(x, this.x);
+ h = min(y + h, this.y + this.height) - max(y, this.y);
+ x = max(x, this.x);
+ y = max(y, this.y);
+ if (w <= 0 || h <= 0) return;
+ if (cur.parent == null && cur.surface != null) cur.surface.dirty(x, y, w, h);
+ }
+ }
+
+ /**
+ * Given an old and new mouse position, this will update <tt>mouseinside</tt> and check
+ * to see if this node requires any Enter, Leave, or Move notifications.
+ *
+ * @param forceleave set to true by the box's parent if the mouse is inside an older
+ * sibling, which is covering up this box.
+ */
+ void Move(int oldmousex, int oldmousey, int mousex, int mousey) { Move(oldmousex, oldmousey, mousex, mousey, false); }
+ void Move(int oldmousex, int oldmousey, int mousex, int mousey, boolean forceleave) {
+
+ boolean wasinside = mouseinside;
+ boolean isinside = !invisible && inside(mousex, mousey) && !forceleave;
+ mouseinside = isinside;
+
+ if (!wasinside && !isinside) return;
+
+ if (traps == null) { }
+ else if (!wasinside && isinside && traps.get("Enter") != null) put("Enter", this);
+ else if (wasinside && !isinside && traps.get("Leave") != null) put("Leave", this);
+ else if (wasinside && isinside && (mousex != oldmousex || mousey != oldmousey) && traps.get("Move") != null) put("Move", this);
+
+ if (isinside && cursor != null) getRoot().cursor = cursor;
+
+ // if the mouse has moved into our padding region, it is considered 'outside' all our children
+ if (!(mousex >= x + hpad && mousey >= y + vpad &&
+ mousex < x + width - hpad && mousey < y + height + vpad)) forceleave = true;
+
+ for(Box b = getChild(numChildren() - 1); b != null; b = b.prevSibling()) {
+ b.Move(oldmousex, oldmousey, mousex, mousey, forceleave);
+ if (b.inside(mousex, mousey)) forceleave = true;
+ }
+ }
+
+
+ // Reflow ////////////////////////////////////////////////////////////////////////////////////////
+
+ void reflow() {
+ repack();
+ if (abort) return;
+ resize(x, y, width, height);
+ }
+
+ /** Checks if the Box's size has changed, dirties it if necessary, and makes sure childrens' sizes are up to date */
+ void repack() {
+ if (!needs_reflow || numChildren() == 0) return;
+
+ // --- Phase 0 ----------------------------------------------------------------------
+ // recurse
+ for(Box child = getChild(0); child != null; child = child.nextSibling()) {
+ child.reflow();
+ if (abort) { MARK_FOR_REFLOW_this; return; }
+ }
+
+ // --- Phase 1 ----------------------------------------------------------------------
+ // assign children to their row/column positions (assuming constrained columns)
+ //#repeat x/y y/x width/height col/row row/col cols/rows colspan/rowspan colWidth/rowHeight numRowsInCol/numColsInRow INNER/INNER2 maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight OUTER/OUTER2 INNER/INNER2
+ if (rows == 0) {
+ int[] numRowsInCol = new int[cols]; // the number of cells occupied in each column
+ Box child = getChild(0);
+ for(child = child.nextSibling(); child != null && (child.absolute || child.invisible); child = child.nextSibling());
+ OUTER: for(int row=0; child != null; row++) {
+ for(int col=0; child != null && col < cols;) {
+ INNER: while(true) { // scan across the row, looking for an unoccupied gap at least as wide as the child
+ while(col < cols && numRowsInCol[col] > row) col++;
+ for(int i=col; i < cols && i < col + child.colspan; i++)
+ if (numRowsInCol[col] > row) { col = i + 1; continue INNER; }
+ break;
+ }
+ if (col + child.colspan >= cols) break;
+ for(int i=col; i < col + child.colspan; i++) numRowsInCol[i] += child.rowspan;
+ child.col = col;
+ col += child.colspan;
+ for(child = child.nextSibling(); child != null && (child.absolute || child.invisible); child = child.nextSibling());
+ }
+ }
+ }
+ //#end
+
+ // --- Phase 2 ----------------------------------------------------------------------
+ // compute the min/max sizes of the columns and rows and set our contentwidth
+ //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight
+ contentwidth = 0;
+ LENGTH[] colWidth = new LENGTH[cols];
+ for(Box child = getChild(0); child != null; child = child.nextSibling())
+ colWidth[child.col] = max(colWidth[child.col], child.contentwidth / child.colspan);
+ for(int col=0; col<cols; col++) contentwidth += colWidth[col];
+ contentwidth = max(textwidth, contentwidth);
+ contentwidth = bound(minwidth, contentwidth, maxwidth);
+ //#end
+ }
+
+
+ void resize(LENGTH x, LENGTH y, LENGTH width, LENGTH height) {
+
+ // --- Phase 1 ----------------------------------------------------------------------
+ // run PosChange/SizeChange, dirty as needed
+ if (x != this.x || y != this.y || width != this.width || height != this.height) {
+ parent.dirty(this.x, this.y, this.width, this.height);
+ dirty(x, y, width, height);
+ boolean sizechange = false, poschange = false;
+ if (traps != null && (this.width != width || this.height != height) && traps.get("SizeChange") != null) sizechange = true;
+ if (traps != null && (this.x != x || this.y != y) && traps.get("PosChange") != null) poschange = true;
+ this.width = width; this.height = height; this.x = x; this.y = y;
+ if (sizechange || poschange)
+ if (sizePosChangesSinceLastRender == 500) {
+ if (Log.on) Log.logJS(this, "Warning, more than 500 SizeChange/PosChange traps triggered since last complete render");
+ } else {
+ sizePosChangesSinceLastRender++;
+ if (sizechange) put("SizeChange", Boolean.TRUE);
+ if (poschange) put("PosChange", Boolean.TRUE);
+ abort = true;
+ return;
+ }
+ needs_reflow = true;
+ }
+
+ // --- short circuit ----------------------------------------------------------------
+ if (!needs_reflow) return;
+ needs_reflow = false;
+
+
+ // --- Phase 2 ----------------------------------------------------------------------
+ // compute the min/max sizes of the columns and rows and set initial width/height to minimums
+
+ //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight
+ LENGTH[] colWidth = new LENGTH[cols];
+ LENGTH[] colMaxWidth = new LENGTH[cols];
+ //#end
+
+ for(Box child = getChild(0); child != null; child = child.nextSibling()) {
+ //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight hshrink/vshrink
+ colWidth[child.col] = max(colWidth[child.col], child.contentwidth / child.colspan);
+ colMaxWidth[child.col] = min(colMaxWidth[child.col], (child.hshrink ? child.minwidth : child.maxwidth) / child.colspan);
+ //#end
+ }
+
+
+ // --- Phase 3 ----------------------------------------------------------------------
+ // hand out the slack
+ int slack;
+ //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight
+ slack = width;
+ for(int i=0; i<cols; i++) slack -= colWidth[i];
+ while(slack > 0) {
+ // FEATURE: inefficient
+ int startslack = slack;
+ int increment = max(1, slack / cols);
+ for(int col=0; col < cols && slack > 0; col++) {
+ slack += colWidth[col];
+ colWidth[col] = min(colMaxWidth[col], colWidth[col] + increment);
+ slack -= colWidth[col];
+ }
+ if (slack == startslack) break;
+ }
+ //#end
+
+
+ // --- Phase 4 ----------------------------------------------------------------------
+ // assign children's new sizes and positions and recurse
+ for(Box child = getChild(0); child != null; child = child.nextSibling()) {
+ int diff;
+
+ //#repeat x/y y/x width/height col/row cols/rows colspan/rowspan colWidth/rowHeight maxwidth/maxheight minwidth/minheight contentwidth/contentheight colMaxWidth/rowMaxHeight hshrink/vshrink
+ child.width = 0; for(int i=child.col; i<child.colspan; i++) child.width += colWidth[i];
+ diff = bound(child.contentwidth, child.width, child.hshrink ? child.contentwidth : child.maxwidth) - child.width;
+ child.x = 0; for(int i=0; i<child.col; i++) child.x += colWidth[i];
+ if (diff < 0) child.x += -1 * (diff / 2);
+ //#end
+
+ child.resize(child.x, child.y, child.width, child.height);
+ }
+ }
+
+
+
+
+ // Rendering Pipeline /////////////////////////////////////////////////////////////////////
+
+ /** Renders self and children within the specified region. All rendering operations are clipped to xIn,yIn,wIn,hIn */
+ void render(int xIn, int yIn, int wIn, int hIn, DoubleBuffer buf) {
+ if (abort || invisible) return;
+
+ // intersect the x,y,w,h rendering window with ourselves; quit if it's empty
+ int x = max(xIn, parent == null ? 0 : this.x);
+ int y = max(yIn, parent == null ? 0 : this.y);
+ int w = min(xIn + wIn, (parent == null ? 0 : this.x) + width) - x;
+ int h = min(yIn + hIn, (parent == null ? 0 : this.y) + height) - y;
+ if (w <= 0 || h <= 0) return;
+
+ if ((fillcolor & 0xFF000000) != 0x00000000 || parent == null)
+ buf.fillRect(x, y, x + w, y + h, (fillcolor & 0xFF000000) != 0 ? fillcolor : 0xFF777777);
+
+ if (image != null)
+ if (tile) renderTiledImage(x, y, w, h, buf);
+ else renderStretchedImage(x, y, w, h, buf);
+
+ if (text != null && !text.equals("")) renderText(x, y, w, h, buf);
+
+ // now subtract the pad region from the clip region before proceeding
+ int x2 = max(x, x + hpad);
+ int y2 = max(y, y + vpad);
+ int w2 = min(x + w, x + width - hpad) - x2;
+ int h2 = min(y + h, y + height - vpad) - y2;
+
+ for(Box b = getChild(0); b != null; b = b.nextSibling()) b.render(x2, y2, w2, h2, buf);
+ }
+
+ void renderStretchedImage(int x, int y, int w, int h, DoubleBuffer buf) {
+ buf.setClip(x, y, w + x, h + y);
+
+ int width = x + this.width - x;
+ int height = y + this.height - y;
+
+ /*
+ if (fixedaspect) {
+ int hstretch = width / image.getWidth();
+ if (hstretch == 0) hstretch = -1 * image.getWidth() / width;
+ int vstretch = height / image.getHeight();
+ if (vstretch == 0) vstretch = -1 * image.getHeight() / height;
+ if (hstretch < vstretch) height = image.getHeight() * width / image.getWidth();
+ else width = image.getWidth() * height / image.getHeight();
+ }
+ */
+
+ buf.drawPicture(image, x, y, x + width, y + height, 0, 0, image.getWidth(), image.getHeight());
+ buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
+ }
+
+ void renderTiledImage(int x, int y, int w, int h, DoubleBuffer buf) {
+ int iw = image.getWidth();
+ int ih = image.getHeight();
+
+ for(int i=(x - x)/iw; i <= (x + w - x)/iw; i++) {
+ for(int j=(y - y)/ih; j<= (y + h - y)/ih; j++) {
+
+ int dx1 = max(i * iw + x, x);
+ int dy1 = max(j * ih + y, y);
+ int dx2 = min((i+1) * iw + x, x + w);
+ int dy2 = min((j+1) * ih + y, y + h);
+
+ int sx1 = dx1 - (i*iw) - x;
+ int sy1 = dy1 - (j*ih) - y;
+ int sx2 = dx2 - (i*iw) - x;
+ int sy2 = dy2 - (j*ih) - y;
+
+ if (dx2 - dx1 > 0 && dy2 - dy1 > 0 && sx2 - sx1 > 0 && sy2 - sy1 > 0)
+ buf.drawPicture(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2);
+ }
+ }
+ }
+
+ void renderText(int x, int y, int w, int h, DoubleBuffer buf) {
+ /*
+ if ((textcolor & 0xFF000000) == 0x00000000) return;
+ buf.setClip(x, y, w + x, h + y);
+
+ buf.drawString(font(), text, x + hpad, y + vpad + Platform.getMaxAscent(font()) - 1, textcolor);
+ buf.setClip(0, 0, buf.getWidth(), buf.getHeight());
+ int i=0; while(i<font().length() && !Character.isDigit(font().charAt(i))) i++;
+
+ if (font().lastIndexOf('d') > i) {
+ for(int j = x + hpad; j < x + hpad + textdim(0); j += 2)
+ buf.fillRect(j, y + vpad + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2,
+ j + 1, y + vpad + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2 + 1,
+ textcolor);
+
+ } else if (font().lastIndexOf('u') > i) {
+ buf.fillRect(x + hpad,
+ y + vpad + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2,
+ x + hpad + textdim(0),
+ y + vpad + (xwf == null ? Platform.getMaxAscent(font()) : xwf.getMaxAscent()) + 2 + 1,
+ textcolor);
+ }
+ */
+ }
+
+
+ // Methods to implement org.xwt.js.JS //////////////////////////////////////
+
+ public Object callMethod(Object method, JS.Array args, boolean checkOnly) throws JS.Exn {
+ if ("indexof".equals(method)) {
+ if (checkOnly) return Boolean.TRUE;
+ if (args.length() != 1 || args.elementAt(0) == null || !(args.elementAt(0) instanceof Box)) return new Integer(-1);
+ Box b = (Box)args.elementAt(0);
+ if (b.parent != Box.this) {
+ if (redirect == null || redirect == Box.this) return new Integer(-1);
+ return redirect.callMethod(method, args, checkOnly);
+ }
+ return new Integer(b.getIndexInParent());
+
+ } else if ("apply".equals(method)) {
+ if (checkOnly) return Boolean.TRUE;
+ if (args.elementAt(0) instanceof String) {
+ String templatename = (String)args.elementAt(0);
+ Template t = Template.getTemplate(templatename, null);
+ if (t == null) {
+ if (Log.on) Log.logJS(this, "template " + templatename + " not found");
+ } else {
+ if (ThreadMessage.suspendThread()) try {
+ JS.Callable callback = args.length() < 2 ? null : (Callable)args.elementAt(1);
+ t.apply(this, null, null, callback, 0, t.numUnits());
+ } finally {
+ ThreadMessage.resumeThread();
+ }
+ }
+ } else if (args.elementAt(0) instanceof JS && !(args.elementAt(0) instanceof Box)) {
+ JS s = (JS)args.elementAt(0);
+ Object[] keys = s.keys();
+ for(int j=0; j<keys.length; j++) put(keys[j].toString(), s.get(keys[j]));
+ }
+ return this;
+ }
+ return null;
+ }
+
+ /** Returns the i_th child */
+ public Object get(int i) {
+ if (redirect == null) return null;
+ if (redirect != this) return redirect.get(i);
+ return i >= numChildren() || i < 0 ? null : getChild(i);
+ }
+
+ /**
+ * Inserts value as child i; calls remove() if necessary.
+ * This method handles "reinserting" one of your children properly.
+ * INVARIANT: after completion, getChild(min(i, numChildren())) == newnode
+ * WARNING: O(n) runtime, unless i == numChildren()
+ */
+ public void put(int i, Object value) {
+ if (i < 0) return;
+
+ if (value != null && !(value instanceof Box)) {
+ if (Log.on) Log.logJS(this, "attempt to set a numerical property on a box to anything other than a box");
+ } else if (redirect == null) {
+ if (Log.on) Log.logJS(this, "attempt to add/remove children to/from a node with a null redirect");
+ } else if (redirect != this) {
+ Box b = value == null ? (Box)redirect.get(i) : (Box)value;
+ redirect.put(i, value);
+ put("0", b);
+ } else if (value == null) {
+ if (i >= 0 && i < numChildren()) {
+ Box b = getChild(i);
+ b.remove();
+ put("0", b);
+ }
+ } else if (value instanceof RootProxy) {
+ if (Log.on) Log.logJS(this, "attempt to reparent a box via its proxy object");
+ } else {
+ Box newnode = (Box)value;
+
+ // check if box being moved is currently target of a redirect
+ for(Box cur = newnode.parent; cur != null; cur = cur.parent)
+ if (cur.redirect == newnode) {
+ if (Log.on) Log.logJS(this, "attempt to move a box that is the target of a redirect");
+ return;
+ }
+
+ // check for recursive ancestor violation
+ for(Box cur = this; cur != null; cur = cur.parent)
+ if (cur == newnode) {
+ if (Log.on) Log.logJS(this, "attempt to make a node a parent of its own ancestor");
+ if (Log.on) Log.log(this, "box == " + this + " ancestor == " + newnode);
+ return;
+ }
+
+ if (numKids > 15 && children == null) convert_to_array();
+ newnode.remove();
+ newnode.parent = this;
+
+ if (children == null) {
+ if (firstKid == null) {
+ firstKid = newnode;
+ newnode.prevSibling = newnode;
+ newnode.nextSibling = newnode;
+ } else if (i >= numKids) {
+ newnode.prevSibling = firstKid.prevSibling;
+ newnode.nextSibling = firstKid;
+ firstKid.prevSibling.nextSibling = newnode;
+ firstKid.prevSibling = newnode;
+ } else {
+ Box cur = firstKid;
+ for(int j=0; j<i; j++) cur = cur.nextSibling;
+ newnode.prevSibling = cur.prevSibling;
+ newnode.nextSibling = cur;
+ cur.prevSibling.nextSibling = newnode;
+ cur.prevSibling = newnode;
+ if (i == 0) firstKid = newnode;
+ }
+ numKids++;
+
+ } else {
+ if (i >= children.size()) {
+ newnode.indexInParent = children.size();
+ children.addElement(newnode);
+ } else {
+ children.insertElementAt(newnode, i);
+ for(int j=i; j<children.size(); j++)
+ getChild(j).indexInParent = j;
+ }
+ }
+
+ // need both of these in case child was already uncalc'ed
+ Box b = newnode;
+ MARK_FOR_REFLOW_b;
+ MARK_FOR_REFLOW_this;
+
+ newnode.dirty();
+
+ // note that JavaScript box[0] will invoke put(int i), not put(String s)
+ put("0", newnode);
+ }
+ }
+
+ public Object get(Object name) { return get(name, false); }
+ public Object get(Object name_, boolean ignoretraps) {
+ if (name_ instanceof Number) return get(((Number)name_).intValue());
+
+ if (!(name_ instanceof String)) return null;
+ String name = (String)name_;
+ if (name.equals("")) return null;
+
+ // See if we're reading back the function value of a trap
+ if (name.charAt(0) == '_') {
+ if (name.charAt(1) == '_') name = name.substring(2);
+ else name = name.substring(1);
+ Trap t = Trap.getTrap(this, name);
+ return t == null ? null : t.f;
+ }
+
+ // See if we're triggering a trap
+ Trap t = traps == null || ignoretraps ? null : (Trap)traps.get(name);
+ if (t != null && t.isreadtrap) return t.perform(Trap.emptyargs);
+
+ // Check for a special handler
+ SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
+ if (gph != null) return gph.get(this);
+
+ Object ret = super.get(name);
+ if (name.startsWith("$") && ret == null)
+ if (Log.on) Log.logJS(this, "WARNING: attempt to access " + name + ", but no child with id=\"" + name.substring(1) + "\" found");
+ return ret;
+ }
+
+ public Object[] keys() {
+ Object[] ret = new Object[numChildren()];
+ for(int i=0; i<ret.length; i++) ret[i] = new Integer(i);
+ return ret;
+ }
+
+ /**
+ * Scriptable.put()
+ * @param ignoretraps if set, no traps will be triggered (set when 'cascade' reaches the bottom of the trap stack)
+ * @param rp if this put is being performed via a root proxy, rp is the root proxy.
+ */
+ public void put(Object name, Object value) { put(name, value, false, null); }
+ public void put(Object name, Object value, boolean ignoretraps) { put(name, value, ignoretraps, null); }
+ public void put(Object name_, Object value, boolean ignoretraps, RootProxy rp) {
+ if (name_ instanceof Number) { put(((Number)name_).intValue(), value); return; }
+ if (!(name_ instanceof String)) { super.put(name_,value); return; }
+ String name = name_.toString();
+ if (!ignoretraps && traps != null) {
+ Trap t = (Trap)traps.get(name);
+ if (t != null) {
+ JS.Array arg = new JS.Array();
+ arg.addElement(value);
+ t.perform(arg);
+ arg.setElementAt(null, 0);
+ return;
+ }
+ }
+
+ // don't want to really cascade down to the box on this one
+ if (name.equals("0")) return;
+
+ SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name);
+ if (gph != null) { gph.put(name, this, value); return; }
+
+ if (name.charAt(0) == '_') {
+ if (value != null && !(value instanceof JS.Callable)) {
+ if (Log.on) Log.logJS(this, "attempt to put a non function value (" + value + ") to " + name);
+ } else if (value != null && !(value instanceof JS.CompiledFunction)) {
+ if (Log.on) Log.logJS(this, "attempt to put a non-compiled function value (" + value + ") to " + name);
+ } else if (name.charAt(1) == '_') {
+ name = name.substring(2).intern();
+ Trap t = Trap.getTrap(this, name);
+ if (t != null) t.delete();
+ if (value != null) Trap.addTrap(this, name, ((JS.CompiledFunction)value), true, rp);
+ } else {
+ name = name.substring(1).intern();
+ Trap t = Trap.getTrap(this, name);
+ if (t != null) t.delete();
+ if (value != null) Trap.addTrap(this, name, ((JS.CompiledFunction)value), false, rp);
+ }
+ return;
+ }
+
+ super.put(name, value);
+ }
+
+
+ // Tree Manipulation /////////////////////////////////////////////////////////////////////
+
+ /** The parent of this node */
+ private Box parent = null;
+
+ // Variables used in Vector mode */
+ /** INVARIANT: if (parent != null) parent.children.elementAt(indexInParent) == this */
+ private int indexInParent;
+ private Vec children = null;
+
+ // Variables used in linked-list mode
+ private int numKids = 0;
+ private Box nextSibling = null;
+ private Box prevSibling = null;
+ private Box firstKid = null;
+
+ // when we get more than 15 children, we switch to array-mode
+ private void convert_to_array() {
+ children = new Vec(numKids);
+ Box cur = firstKid;
+ do {
+ children.addElement(cur);
+ cur.indexInParent = children.size() - 1;
+ cur = cur.nextSibling;
+ } while (cur != firstKid);
+ }
+
+ /** remove this node from its parent; INVARIANT: whenever the parent of a node is changed, remove() gets called. */
+ public void remove() {
+ if (parent == null) {
+ if (surface != null) surface.dispose(true);
+ return;
+ }
+ Box oldparent = parent;
+ if (oldparent == null) return;
+ MARK_FOR_REFLOW_this;
+ dirty();
+ mouseinside = false;
+
+ if (parent.children != null) {
+ parent.children.removeElementAt(indexInParent);
+ for(int j=indexInParent; j<parent.children.size(); j++)
+ (parent.getChild(j)).indexInParent = j;
+
+ } else {
+ if (parent.firstKid == this) {
+ if (nextSibling == this) parent.firstKid = null;
+ else parent.firstKid = nextSibling;
+ }
+ parent.numKids--;
+ prevSibling.nextSibling = nextSibling;
+ nextSibling.prevSibling = prevSibling;
+ prevSibling = null;
+ nextSibling = null;
+ }
+ parent = null;
+
+ if (oldparent != null) { Box b = oldparent; MARK_FOR_REFLOW_b; }
+
+ // note that JavaScript box[0] will invoke put(int i), not put(String s)
+ if (oldparent != null) oldparent.put("0", this);
+ }
+
+ /** returns our next sibling (parent[ourindex + 1]) */
+ public final Box nextSibling() {
+ if (parent == null) return null;
+ if (parent.children == null) {
+ if (nextSibling == parent.firstKid) return null;
+ return nextSibling;
+ } else {
+ if (indexInParent >= parent.children.size() - 1) return null;
+ return (Box)parent.children.elementAt(indexInParent + 1);
+ }
+ }
+
+ /** returns our next sibling (parent[ourindex + 1]) */
+ public final Box prevSibling() {
+ if (parent == null) return null;
+ if (parent.children == null) {
+ if (this == parent.firstKid) return null;
+ return prevSibling;
+ } else {
+ if (indexInParent == 0) return null;
+ return (Box)parent.children.elementAt(indexInParent - 1);
+ }
+ }
+
+ /** Returns the parent of this node */
+ public Box getParent() { return parent; }
+
+ /** Returns ith child */
+ public Box getChild(int i) {
+ if (children == null) {
+ if (firstKid == null) return null;
+ if (i >= numKids) return null;
+ if (i == numKids - 1) return firstKid.prevSibling;
+ Box cur = firstKid;
+ for(int j=0; j<i; j++) cur = cur.nextSibling;
+ return cur;
+ } else {
+ if (i >= children.size() || i < 0) return null;
+ return (Box)children.elementAt(i);
+ }
+ }
+
+ /** Returns the number of children */
+ public int numChildren() {
+ if (children == null) {
+ if (firstKid == null) return 0;
+ int i=1;
+ for(Box cur = firstKid.nextSibling; cur != firstKid; i++) cur = cur.nextSibling;
+ return i;
+ } else {
+ return children.size();
+ }
+ }
+
+ /** Returns our index in our parent */
+ public int getIndexInParent() {
+ if (parent == null) return 0;
+ if (parent.children == null) {
+ int i = 0;
+ for(Box cur = this; cur != parent.firstKid; i++) cur = cur.prevSibling;
+ return i;
+ } else {
+ return indexInParent;
+ }
+ }
+
+ /** returns the root of the surface that this box belongs to */
+ public final Box getRoot() {
+ if (parent == null && surface != null) return this;
+ if (parent == null) return null;
+ return parent.getRoot();
+ }
+
+
+ // Root Proxy ///////////////////////////////////////////////////////////////////////////////
+
+ // FEATURE: use xwt.graft() here
+ RootProxy myproxy = null;
+ public JS getRootProxy() {
+ if (myproxy == null) myproxy = new RootProxy(this);
+ return myproxy;
+ }
+
+ private static class RootProxy extends JS {
+ Box box;
+ RootProxy(Box b) { this.box = b; }
+ public Object get(Object name) { return box.get(name); }
+ public void put(Object name, Object value) { box.put(name, value, false, this); }
+ public Object[] keys() { return box.keys(); }
+ public Object callMethod(Object method, JS.Array args, boolean justChecking) { return box.callMethod(method,args,justChecking); }
+ }
+
+
+ // Trivial Helper Methods (should be inlined) /////////////////////////////////////////
+
+ static final int min(int a, int b) { if (a<b) return a; else return b; }
+ static final double min(double a, double b) { if (a<b) return a; else return b; }
+ static final int max(int a, int b) { if (a>b) return a; else return b; }
+ static final int min(int a, int b, int c) { if (a<=b && a<=c) return a; else if (b<=c && b<=a) return b; else return c; }
+ static final int max(int a, int b, int c) { if (a>=b && a>=c) return a; else if (b>=c && b>=a) return b; else return c; }
+ static final int bound(int a, int b, int c) { if (c < b) return c; if (a > b) return a; return b; }
+ final boolean inside(int x, int y) { return (!invisible && x >= this.x && y >= this.y && x < this.x + width && y < this.y + height); }
+
+ /** figures out what box in this subtree of the Box owns the pixel at x,y relitave to the Surface */
+ public static Box whoIs(Box cur, int x, int y) {
+
+ // WARNING: this method is called from the event-queueing
+ // thread -- it may run concurrently with ANY part of XWT, and
+ // is UNSYNCHRONIZED for performance reasons. BE CAREFUL
+ // HERE.
+
+ if (cur.invisible) return null;
+ if (!cur.inside(x,y)) return cur.parent == null ? cur : null;
+ OUTER: while(true) {
+ for(int i=cur.numChildren() - 1; i>=0; i--) {
+ Box child = cur.getChild(i);
+ if (child == null) continue; // since this method is unsynchronized, we have to double-check
+ if (!child.invisible && child.inside(x,y)) { cur = child; continue OUTER; }
+ }
+ break;
+ }
+ return cur;
+ }
+
+ /**
+ * A helper class for properties of Box which require special
+ * handling.
+ *
+ * To avoid excessive use of String.equals(), the Box.get() and
+ * Box.put() methods employ a Hash keyed on property names that
+ * require special handling. The value stored in the Hash is an
+ * instance of an anonymous subclass of SpecialBoxProperty, which knows
+ * how to handle get()s and put()s for that property name. There
+ * should be one anonymous subclass of SpecialBoxProperty for each
+ * specially-handled property on Box.
+ */
+ static class SpecialBoxProperty {
+
+ SpecialBoxProperty() { }
+
+ /** stores instances of SpecialBoxProperty; keyed on property name */
+ static Hash specialBoxProperties = new Hash(200, 3);
+
+ /** this method defines the behavior when the property is get()ed from b */
+ Object get(Box b) { return null; }
+
+ /** this method defines the behavior when the property is put() to b */
+ void put(Box b, Object value) { }
+
+ /** this method defines the behavior when the property is put() to b, allows a single SpecialBoxProperty to serve multiple properties */
+ void put(String name, Box b, Object value) { put(b, value); }
+
+ static {
+ //#repeat fillcolor/strokecolor
+ specialBoxProperties.put("fillcolor", new SpecialBoxProperty() {
+ public Object get(Box b) {
+ if ((b.fillcolor & 0xFF000000) == 0) return null;
+ String red = Integer.toHexString((b.fillcolor & 0x00FF0000) >> 16);
+ String green = Integer.toHexString((b.fillcolor & 0x0000FF00) >> 8);
+ String blue = Integer.toHexString(b.fillcolor & 0x000000FF);
+ if (red.length() < 2) red = "0" + red;
+ if (blue.length() < 2) blue = "0" + blue;
+ if (green.length() < 2) green = "0" + green;
+ return "#" + red + green + blue;
+ }
+ public void put(Box b, Object value) {
+ int newcolor = b.fillcolor;
+ String s = value == null ? null : value.toString();
+ if (value == null) newcolor = 0x00000000;
+ else if (s.length() > 0 && s.charAt(0) == '#')
+ try {
+ newcolor = 0xFF000000 |
+ (Integer.parseInt(s.substring(1, 3), 16) << 16) |
+ (Integer.parseInt(s.substring(3, 5), 16) << 8) |
+ Integer.parseInt(s.substring(5, 7), 16);
+ } catch (NumberFormatException e) {
+ Log.log(this, "invalid color " + s);
+ return;
+ }
+ // FIXME put named colors back in
+ }
+ });
+ //#end
+
+ specialBoxProperties.put("text", new SpecialBoxProperty() {
+ public Object get(Box b) { return b.text; }
+ public void put(Box b, Object value) {
+ String t = value == null ? "null" : value.toString();
+ if (t.equals(b.text)) return;
+ // FIXME text is broken
+ } });
+ specialBoxProperties.put("font", new SpecialBoxProperty() {
+ public Object get(Box b) { return b.font; }
+ public void put(Box b, Object value) {
+ b.font = value == null ? null : value.toString();
+ //b.fontChanged();
+ b.dirty();
+ } });
+
+ specialBoxProperties.put("thisbox", new SpecialBoxProperty() {
+ public Object get(Box b) { return b; }
+ public void put(Box b, Object value) {
+ if (value == null) b.remove();
+ else if (value.equals("window") || value.equals("frame")) Platform.createSurface(b, value.equals("frame"), true);
+ else if (Log.on) Log.log(this, "put invalid value to 'thisbox' property: " + value);
+ }
+ });
+
+ specialBoxProperties.put("orient", new SpecialBoxProperty() {
+ public Object get(Box b) {
+ if (b.redirect == null) return "horizontal";
+ else if (b.redirect != b) return get(b.redirect);
+ else if (b.cols == 1) return "vertical";
+ else if (b.rows == 1) return "horizontal";
+ else return "grid";
+ }
+ public void put(Box b, Object value) {
+ if (value == null) return;
+ if (b.redirect == null) return;
+ if (b.redirect != b) { put(b.redirect, value); return; }
+ if (value.equals("vertical")) {
+ if (b.rows == 0) return;
+ b.rows = 0; b.cols = 1;
+ } else if (value.equals("horizontal")) {
+ if (b.cols == 0) return;
+ b.cols = 0; b.rows = 1;
+ } else if (Log.on)
+ Log.log(this, "invalid value put to orient property: " + value);
+ MARK_FOR_REFLOW_b;
+ } });
+
+ specialBoxProperties.put("static", new SpecialBoxProperty() {
+ public Object get(Box b) {
+ String cfsn =
+ JS.Thread.fromJavaThread(java.lang.Thread.currentThread()).getCurrentCompiledFunction().getSourceName();
+ for(int i=0; i<cfsn.length() - 1; i++)
+ if (cfsn.charAt(i) == '.' && (cfsn.charAt(i+1) == '_' || Character.isDigit(cfsn.charAt(i+1)))) {
+ cfsn = cfsn.substring(0, i);
+ break;
+ }
+ return Static.getStatic(cfsn);
+ }
+ });
+
+ specialBoxProperties.put("shrink", new SpecialBoxProperty() {
+ public Object get(Box b) { return (b.vshrink && b.hshrink) ? Boolean.TRUE : Boolean.FALSE; }
+ public void put(Box b, Object value) { b.put("hshrink", value); b.put("vshrink", value); }
+ });
+
+ //#repeat hshrink/vshrink
+ specialBoxProperties.put("hshrink", new SpecialBoxProperty() {
+ public Object get(Box b) { return new Boolean(b.hshrink); }
+ public void put(Box b, Object value) {
+ boolean newshrink = stob(value);
+ if (b.hshrink == newshrink) return;
+ b.hshrink = newshrink;
+ MARK_FOR_REFLOW_b;
+ }
+ });
+ //#end
+
+ //#repeat x/y
+ specialBoxProperties.put("x", new SpecialBoxProperty() {
+ public Object get(Box b) {
+ if (b.surface == null) return new Integer(0);
+ if (b.invisible) return new Integer(0);
+ return new Integer(b.x);
+ }
+ public void put(Box b, Object value) {
+ b.x = stoi(value);
+ if (b.parent == null && b.surface != null) {
+ // FIXME this gets hosed by the #repeat
+ //b.surface.setLocation(b.x, b.y);
+ b.surface.centerSurfaceOnRender = false;
+ }
+ }
+ });
+ //#end
+
+ //#repeat width/height minwidth/minheight maxwidth/maxheight
+ specialBoxProperties.put("width", new SpecialBoxProperty() {
+ public Object get(Box b) { return new Integer(b.width); }
+ public void put(Box b, Object value) {
+ b.width = stoi(value);
+ if (b.parent == null && b.surface != null) {
+ // FIXME this gets hosed...
+ //b.surface.setSize(max(Surface.scarPicture.getWidth(), b.width),
+ //max(Surface.scarPicture.getHeight(), b.height));
+ MARK_FOR_REFLOW_b;
+ } else {
+ b.minwidth = b.minheight = b.width;
+ MARK_FOR_REFLOW_b;
+ }
+ } });
+ //#end
+
+ //#repeat cols/rows rows/cols
+ specialBoxProperties.put("cols", new SpecialBoxProperty() {
+ public Object get(Box b) { return new Double(b.cols); }
+ public void put(Box b, Object value) {
+ b.cols = stoi(value);
+ if (b.cols == 0 && b.rows == 0) b.rows = 1;
+ if (b.cols != 0 && b.rows != 0) b.rows = 0;
+ MARK_FOR_REFLOW_b;
+ } });
+ //#end
+
+ //#repeat colspan/rowspan
+ specialBoxProperties.put("colspan", new SpecialBoxProperty() {
+ public Object get(Box b) { return new Double(b.colspan); }
+ public void put(Box b, Object value) { b.colspan = stoi(value); MARK_FOR_REFLOW_b; }
+ });
+ //#end
+
+ specialBoxProperties.put("tile", new SpecialBoxProperty() {
+ public Object get(Box b) { return b.tile ? Boolean.TRUE : Boolean.FALSE; }
+ public void put(Box b, Object value) {
+ boolean newtile = stob(value);
+ if (newtile == b.tile) return;
+ b.tile = newtile;
+ b.dirty();
+ } });
+
+ specialBoxProperties.put("invisible", new SpecialBoxProperty() {
+ public Object get(Box b) {
+ for (Box cur = b; cur != null; cur = cur.parent) { if (cur.invisible) return Boolean.TRUE; }
+ return Boolean.FALSE;
+ }
+ public void put(Box b, Object value) {
+ boolean newinvisible = stob(value);
+ if (newinvisible == b.invisible) return;
+ b.invisible = newinvisible;
+ if (b.parent == null) {
+ if (b.surface != null) b.surface.setInvisible(newinvisible);
+ } else {
+ b.dirty();
+ MARK_FOR_REFLOW_b_parent;
+ b.parent.dirty(b.x, b.y, b.width, b.height);
+ }
+ }});
+
+ specialBoxProperties.put("absolute", new SpecialBoxProperty() {
+ public Object get(Box b) { return b.absolute ? Boolean.TRUE : Boolean.FALSE; }
+ public void put(Box b, Object value) {
+ boolean newabsolute = stob(value);
+ if (newabsolute == b.absolute) return;
+ b.absolute = newabsolute;
+ if (b.parent != null) MARK_FOR_REFLOW_b_parent;
+ } });
+
+ specialBoxProperties.put("image", new SpecialBoxProperty() {
+ public Object get(Box b) { return b.image == null ? null : ImageDecoder.imageToNameMap.get(b.image); }
+ public void put(Box b, Object value) {
+ if ((value == null && b.image == null) ||
+ (value != null && b.image != null && value.equals(ImageDecoder.imageToNameMap.get(b.image)))) return;
+ String s = value == null ? null : value.toString();
+ if (s == null || s.equals("")) b.image = null;
+ else {
+ if ((b.image = ImageDecoder.getPicture(s)) == null) {
+ if (Log.on) Log.logJS(Box.class, "unable to load image " + s);
+ } else {
+ b.minwidth = b.maxwidth = b.image.getWidth();
+ b.minheight = b.maxheight = b.image.getHeight();
+ }
+ }
+ b.dirty();
+ }
+ });
+
+ //#repeat globalx/globaly x/y
+ specialBoxProperties.put("globalx", new SpecialBoxProperty() {
+ public Object get(Box b) { return new Integer(b.parent == null || b.surface == null ? 0 : b.x); }
+ public void put(Box b, Object value) {
+ if (b.surface == null || b.parent == null) return;
+ b.put("x", new Integer(stoi(value) - stoi(get(b.parent))));
+ }
+ });
+ //#end
+
+ specialBoxProperties.put("cursor", new SpecialBoxProperty() {
+ public Object get(Box b) { return b.cursor; }
+ public void put(Box b, Object value) {
+ b.cursor = (String)value;
+ if (b.surface == null) return;
+
+ // see if we need to update the surface cursor
+ Surface surface = b.getRoot().surface;
+ String tempcursor = surface.cursor;
+ b.Move(surface.mousex, surface.mousey, surface.mousex, surface.mousey);
+ if (surface.cursor != tempcursor) surface.syncCursor();
+ }
+ });
+
+ //#repeat mousex/mousey x/y
+ specialBoxProperties.put("mousex", new SpecialBoxProperty() {
+ public Object get(Box b) { return new Integer(b.getRoot().surface == null ? 0 : b.getRoot().surface.mousex - b.x); }
+ });
+ //#end
+
+ specialBoxProperties.put("xwt", new SpecialBoxProperty() {
+ public Object get(Box b) { return XWT.singleton; }
+ });
+
+ specialBoxProperties.put("mouseinside", new SpecialBoxProperty() {
+ public Object get(Box b) { return b.mouseinside ? Boolean.TRUE : Boolean.FALSE; }
+ });
+
+ specialBoxProperties.put("numchildren", new SpecialBoxProperty() {
+ public Object get(Box b) {
+ if (b.redirect == null) return new Integer(0);
+ if (b.redirect != b) return get(b.redirect);
+ return new Integer(b.numChildren());
+ } });
+
+ SpecialBoxProperty mouseEventHandler = new SpecialBoxProperty() {
+ public void put(String name, Box b, Object value) {
+ Surface surface = b.getRoot().surface;
+ if (surface == null) return;
+ for(Box c = b.prevSibling(); c != null; c = c.prevSibling()) {
+ Box siblingChild = whoIs(c, surface.mousex, surface.mousey);
+ if (siblingChild != null) {
+ siblingChild.put(name, value);
+ return;
+ }
+ }
+ if (b.parent != null) b.parent.put(name, value);
+ }};
+
+ specialBoxProperties.put("Press1", mouseEventHandler);
+ specialBoxProperties.put("Press2", mouseEventHandler);
+ specialBoxProperties.put("Press3", mouseEventHandler);
+ specialBoxProperties.put("Release1", mouseEventHandler);
+ specialBoxProperties.put("Release2", mouseEventHandler);
+ specialBoxProperties.put("Release3", mouseEventHandler);
+ specialBoxProperties.put("Click1", mouseEventHandler);
+ specialBoxProperties.put("Click2", mouseEventHandler);
+ specialBoxProperties.put("Click3", mouseEventHandler);
+ specialBoxProperties.put("DoubleClick1", mouseEventHandler);
+ specialBoxProperties.put("DoubleClick2", mouseEventHandler);
+ specialBoxProperties.put("DoubleClick3", mouseEventHandler);
+
+ specialBoxProperties.put("root", new SpecialBoxProperty() {
+ public Object get(Box b) {
+ if (b.getRoot() == null) return null;
+ else if (b.parent == null) return b;
+ else return b.getRoot().getRootProxy();
+ } });
+
+ specialBoxProperties.put("Minimized", new SpecialBoxProperty() {
+ public Object get(Box b) {
+ if (b.parent == null && b.surface != null) return b.surface.minimized ? Boolean.TRUE : Boolean.FALSE;
+ else return null;
+ }
+ public void put(Box b, Object value) {
+ if (b.surface == null) return;
+ boolean val = stob(value);
+ if (b.parent == null && b.surface.minimized != val) b.surface.setMinimized(val);
+ }
+ });
+
+ specialBoxProperties.put("Maximized", new SpecialBoxProperty() {
+ public Object get(Box b) {
+ if (b.parent == null && b.surface != null) return b.surface.maximized ? Boolean.TRUE : Boolean.FALSE;
+ else return null;
+ }
+ public void put(Box b, Object value) {
+ if (b.surface == null) return;
+ boolean val = stob(value);
+ if (b.parent == null && b.surface.maximized != val) b.surface.setMaximized(val);
+ }
+ });
+
+ specialBoxProperties.put("toback", new SpecialBoxProperty() {
+ public void put(Box b, Object value) {
+ if (b.parent == null && stob(value) && b.surface != null) b.surface.toBack();
+ }
+ });
+
+ specialBoxProperties.put("tofront", new SpecialBoxProperty() {
+ public void put(Box b, Object value) {
+ if (b.parent == null && stob(value) && b.surface != null) b.surface.toFront();
+ }
+ });
+
+ //#repeat hscar/vscar
+ specialBoxProperties.put("hscar", new SpecialBoxProperty() {
+ public void put(Box b, Object value) {
+ if (b.parent == null && b.surface != null) {
+ b.surface.hscar = stoi(value);
+ b.surface.dirty(0, 0, b.surface.width, b.surface.height);
+ b.surface.Refresh();
+ }
+ }
+ });
+ //#end
+
+ specialBoxProperties.put("Close", new SpecialBoxProperty() {
+ public void put(Box b, Object value) {
+ if (b.parent == null && b.surface != null) b.surface.dispose(true);
+ }
+ });
+
+ // these are all do-nothings; just to prevent space from getting taken up in the params Hash.
+ specialBoxProperties.put("KeyPressed", new SpecialBoxProperty()); // FIXME should cascade
+ specialBoxProperties.put("KeyReleased", new SpecialBoxProperty()); // FIXME should cascade
+ specialBoxProperties.put("PosChange", new SpecialBoxProperty());
+ specialBoxProperties.put("SizeChange", new SpecialBoxProperty());
+
+ //#repeat hpad/vpad
+ specialBoxProperties.put("hpad", new SpecialBoxProperty() {
+ public Object get(Box b) {
+ if (b.redirect == null) return new Integer(0);
+ if (b.redirect != b) return get(b.redirect);
+ return new Integer(b.hpad);
+ }
+ public void put(Box b, Object value) {
+ if (b.redirect == null) return;
+ if (b.redirect != b) { put(b.redirect, value); return; }
+ int newval = stoi(value);
+ if (newval == b.hpad) return;
+ b.hpad = newval;
+ MARK_FOR_REFLOW_b;
+ }
+ });
+ //#end
+
+ //#repeat minwidth/minheight maxwidth/maxheight
+ specialBoxProperties.put("minwidth", new SpecialBoxProperty() {
+ public Object get(Box b) { return new Integer(b.minwidth); }
+ public void put(Box b, Object value) {
+ if (stoi(value) == b.minwidth) return;
+ b.minwidth = stoi(value);
+ MARK_FOR_REFLOW_b;
+ }
+ });
+ specialBoxProperties.put("maxwidth", new SpecialBoxProperty() {
+ public Object get(Box b) { return new Integer(b.maxwidth); }
+ public void put(Box b, Object value) {
+ if (stoi(value) == b.maxwidth) return;
+ b.maxwidth = stoi(value);
+ MARK_FOR_REFLOW_b;
+ }
+ });
+ //#end
+
+ specialBoxProperties.put("redirect", new SpecialBoxProperty() {
+ public void put(Box b, Object value) { }
+ public Object get(Box b) {
+ if (b.redirect == null) return null;
+ if (b.redirect == b) return Boolean.TRUE;
+ return get(b.redirect);
+ }
+ });
+
+ /*
+ // FIXME: need to be able to read this back
+ specialBoxProperties.put("titlebar", new SpecialBoxProperty() {
+ public void put(Box b, Object value) { surface.setTitleBarText(value.toString()); }
+ public Object get(Box b) { return b.ti; }
+ });
+
+ // FIXME: need to be able to read this back
+ specialBoxProperties.put("icon", new SpecialBoxProperty() {
+ public void put(Box b, Object value) {
+ Picture pic = Box.getPicture(value.toString());
+ if (pic != null) surface.setIcon(pic);
+ else if (Log.on) Log.log(this, "unable to load icon " + value);
+ }
+ public Object get(Box b) { return b.id; }
+ });
+ */
+ }
+
+
+ /** helper that converts a String to a boolean according to JavaScript coercion rules */
+ public static boolean stob(Object o) {
+ if (o == null) return false;
+ return Boolean.TRUE.equals(o) || "true".equals(o);
+ }
+
+
+ }
+ /** helper that converts a String to an int according to JavaScript coercion rules */
+ public static int stoi(Object o) {
+ if (o == null) return 0;
+ if (o instanceof Integer) return ((Integer)o).intValue();
+
+ String s;
+ if (!(o instanceof String)) s = o.toString();
+ else s = (String)o;
+
+ try { return Integer.parseInt(s.indexOf('.') == -1 ? s : s.substring(0, s.indexOf('.'))); }
+ catch (NumberFormatException e) { return 0; }
+ }
+}
+
+
+