X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=src%2Forg%2Fxwt%2FBox.java;h=c4f34e599ae38e2032334d9cf47884ac1bb29159;hb=9c2602143956cd39ecf5ef4c9eb31f5f56b5bd66;hp=c1dfd86ac3c771fe307f320ff5055ae9c0f7515d;hpb=a5b4833ce4307242eb20dd96df36d847322bf29e;p=org.ibex.core.git diff --git a/src/org/xwt/Box.java b/src/org/xwt/Box.java index c1dfd86..c4f34e5 100644 --- a/src/org/xwt/Box.java +++ b/src/org/xwt/Box.java @@ -1,11 +1,21 @@ // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL] package org.xwt; +// FEATURE: reflow before allowing js to read from width/height +// FEATURE: fastpath for rows=1/cols=1 +// FEATURE: mark to reflow starting with a certain child +// FEATURE: separate mark_for_reflow and mark_for_resize +// FEATURE: make all methods final +// FEATURE: use a linked list for the "frontier" when packing +// FEATURE: or else have a way to mark a column "same as last one"? +// FEATURE: reintroduce surface.abort + import java.io.*; import java.net.*; import java.util.*; +import org.xwt.js.*; import org.xwt.util.*; -import org.mozilla.javascript.*; +import org.xwt.translators.*; /** *

@@ -13,1437 +23,894 @@ import org.mozilla.javascript.*; * rendering logic. *

* - *

- * 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. - *

- * - *

The rendering process consists of two phases:

- * - *
  1. Prerendering pipeline: 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, needs_prerender will be false, and the box - * and its descendants will be skipped. - * - *
  2. Rendering pipeline: 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. - *
- * - *

- * Either of these two phases may abort at any time by setting - * surface.abort to true. Currently, there are two reasons - * for aborting: a SizeChange or PosChange 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. - *

- * - *

Why are these done as seperate passes over the box tree?

- * - *
  1. Sometimes we need to make several trips through - * prerender()SizeChange - * or PosChange. Calling prerender() is - * cheap; calling render() is expensive. - * - *
  2. Even if no SizeChange or PosChange 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. + *

    The rendering process consists of four phases; each requires + * one DFS pass over the tree

    + *
    1. repacking: children of a box are packed into columns + * and rows according to their colspan/rowspan attributes and + * ordering. + *
      1. reconstraining: Minimum and maximum sizes of columns are computed. + *
      2. resizing: width/height and x/y positions of children + * are assigned, and PosChange/SizeChanges are triggered. + *
      3. repainting: children draw their content onto the PixelBuffer. *
      * - *

      - * A box's _cmin_* 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 sync_cmin_to_children() must be invoked - * immediately. - *

      - * - *

      - * 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. - *

      + * The first three passes together are called the reflow phase. + * Reflowing is done in a seperate pass since PosChanges and + * SizeChanges trigger an Surface.abort; if rendering were done in the same + * pass, rendering work done prior to the Surface.abort would be wasted. */ -public final class Box extends JSObject { - - - // 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 Object[] emptyobj = new Object[] { }; - - - // 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 templatename, or null if this template was specified anonymously */ - String[] importlist = Template.defaultImportList; - - /** the template instance that resulted from resolving templatename using importlist, 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 defined width and height of this box */ - public static final int dmax = 0; - private short _dmax_0 = 0; - private short _dmax_1 = 0; - public final short dmax(int axis) { return axis == 0 ? _dmax_0 : _dmax_1; } - - /** The minimum defined width and height of this box */ - public static final int dmin = 1; - private short _dmin_0 = 0; - private short _dmin_1 = 0; - public final short dmin(int axis) { return axis == 0 ? _dmin_0 : _dmin_1; } - - /** The minimum calculated width and height of this box -- unlike dmin, this takes childrens' sizes into account */ - public static final int cmin = 2; - private short _cmin_0 = 0; - private short _cmin_1 = 0; - public final short 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 short _abs_0 = 0; - private short _abs_1 = 0; - public final short 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 short _pos_0 = 0; - private short _pos_1 = 0; - public final short 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; - short _size_0 = 0; - short _size_1 = 0; - public final short 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 short _oldpos_0 = 0; - private short _oldpos_1 = 0; - public final short oldpos(int axis) { return axis == 0 ? _oldpos_0 : _oldpos_1; } - - /** The old actual size of this box */ - public static final int oldsize = 7; - private short _oldsize_0 = 0; - private short _oldsize_1 = 0; - public final short 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 short _pad_0 = 0; - private short _pad_1 = 0; - public final short 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 short _textdim_0 = 0; - private short _textdim_1 = 0; - public final short 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 */ +public final class Box extends JSScope implements Scheduler.Task { + + // Macros ////////////////////////////////////////////////////////////////////// + + //#define LENGTH int + //#define MARK_REPACK for(Box b2 = this; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK); + //#define MARK_REPACK_b for(Box b2 = b; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK); + //#define MARK_REPACK_parent for(Box b2 = parent; b2 != null && !b2.test(REPACK); b2 = b2.parent) b2.set(REPACK); + //#define MARK_REFLOW for(Box b2 = this; b2 != null && !b2.test(REFLOW); b2 = b2.parent) b2.set(REFLOW); + //#define MARK_REFLOW_b for(Box b2 = b; b2 != null && !b2.test(REFLOW); b2 = b2.parent) b2.set(REFLOW); + //#define MARK_RESIZE for(Box b2 = this; b2 != null && !b2.test(RESIZE); b2 = b2.parent) b2.set(RESIZE); + //#define MARK_RESIZE_b for(Box b2 = b; b2 != null && !b2.test(RESIZE); b2 = b2.parent) b2.set(RESIZE); + //#define CHECKSET_SHORT(prop) short nu = (short)toInt(value); if (nu == prop) break; prop = nu; + //#define CHECKSET_INT(prop) int nu = toInt(value); if (nu == prop) break; prop = nu; + //#define CHECKSET_FLAG(flag) boolean nu = toBoolean(value); if (nu == test(flag)) break; if (nu) set(flag); else clear(flag); + //#define CHECKSET_BOOLEAN(prop) boolean nu = toBoolean(value); if (nu == prop) break; prop = nu; + //#define CHECKSET_STRING(prop) if ((value==null&&prop==null)||(value!=null&&value.equals(prop))) break; prop=(String)value; + + void mark_for_repack() { MARK_REPACK; } + + protected Box() { super(null); } + + static Hash boxToCursor = new Hash(500, 3); + public static final int MAX_LENGTH = Integer.MAX_VALUE; + static final Font DEFAULT_FONT; + + static { + Font f = null; + try { f = Font.getFont((Stream)Main.builtin.get("fonts/vera/Vera.ttf"), 10); } + catch(JSExn e) { Log.info(Box.class, "should never happen: "+e); } + DEFAULT_FONT = f; + } + + // FIXME update these + // box properties can not be trapped + static final String[] props = new String[] { + "shrink", "hshrink", "vshrink", "x", "y", "width", "height", "cols", "rows", + "colspan", "rowspan", "align", "visible", "packed", "globalx", "globaly", + "minwidth", "maxwidth", "minheight", "maxheight", "indexof", "thisbox", "clip", + "numchildren", "redirect", "cursor", "mouse" + }; + + // FIXME update these + // events can have write traps, but not read traps + static final String[] events = new String[] { + "Press1", "Press2", "Press3", + "Release1", "Release2", "Release3", + "Click1", "Click2", "Click3", + "DoubleClick1", "DoubleClick2", "DoubleClick3", + "Enter", "Leave", "Move", + "KeyPressed", "KeyReleased", "PosChange", "SizeChange", + "childadded", "childremoved", + "Focused", "Maximized", "Minimized", "Close", + "icon", "titlebar", "toback", "tofront" + }; + + // Flags ////////////////////////////////////////////////////////////////////// + + static final int MOUSEINSIDE = 0x00000001; + static final int VISIBLE = 0x00000002; + static final int PACKED = 0x00000004; + static final int HSHRINK = 0x00000008; + static final int VSHRINK = 0x00000010; + static final int BLACK = 0x00000020; // for red-black code + + static final int FIXED = 0x00000040; + static final boolean ROWS = true; + static final boolean COLS = false; + + static final int ISROOT = 0x00000080; + static final int REPACK = 0x00000100; + static final int REFLOW = 0x00000200; + static final int RESIZE = 0x00000400; + static final int RECONSTRAIN = 0x00000800; + static final int ALIGN_TOP = 0x00001000; + static final int ALIGN_BOTTOM = 0x00002000; + static final int ALIGN_LEFT = 0x00004000; + static final int ALIGN_RIGHT = 0x00008000; + static final int ALIGNS = 0x0000f000; + static final int CURSOR = 0x00010000; // if true, this box has a cursor in the cursor hash; FEATURE: GC issues? + static final int CLIP = 0x00020000; + static final int STOP_UPWARD_PROPAGATION = 0x00040000; + + + // Instance Data ////////////////////////////////////////////////////////////////////// + + Box parent = null; Box redirect = this; + int flags = VISIBLE | PACKED | REPACK | REFLOW | RESIZE | FIXED /* ROWS */ | STOP_UPWARD_PROPAGATION | CLIP; + + private String text = null; + private Font font = DEFAULT_FONT; + private Picture texture = null; + private short strokewidth = 1; + public int fillcolor = 0x00000000; + private int strokecolor = 0xFF000000; + + private int aspect = 0; + + // specified directly by user + public LENGTH minwidth = 0; + public LENGTH maxwidth = MAX_LENGTH; + public LENGTH minheight = 0; + public LENGTH maxheight = MAX_LENGTH; + private short rows = 1; + private short cols = 0; + private short rowspan = 1; + private short colspan = 1; + + // computed during reflow + private short row = 0; + private short col = 0; + public LENGTH x = 0; + public LENGTH y = 0; + public LENGTH width = 0; + public LENGTH height = 0; + private LENGTH contentwidth = 0; // == max(minwidth, textwidth, sum(child.contentwidth)) + private LENGTH contentheight = 0; + + /* + private VectorGraphics.VectorPath path = null; + private VectorGraphics.Affine transform = null; + private VectorGraphics.RasterPath rpath = null; + private VectorGraphics.Affine rtransform = null; + */ - /** the Box's font -- you must call textupdate() after changing this */ - String font = Platform.getDefaultFont(); - - /** 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, 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;
      - * 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 Function indexof = null; - public Function 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 JSObject implements Function { - public IndexOf() { this.setSeal(true); } - public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; } - public Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException { - if (args == null || args.length != 1 || args[0] == null || !(args[0] instanceof Box)) return new Integer(-1); - Box b = (Box)args[0]; - if (b.getParent() != Box.this) { - if (redirect == null || redirect == Box.this) return new Integer(-1); - return Box.this.redirect.indexof().call(cx, scope, thisObj, 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) { set(which, axis, (short)newvalue); } - public final void set(int which, int axis, short 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)); - - 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 obedience to shrink directives - if (which == cmin || which == textdim || which == pad || which == dmin) - if ((hshrink && axis == 0) || (vshrink && axis == 1)) - set(dmax, axis, max(cmin(axis), (textdim(axis) + 2 * pad(axis)), dmin(axis))); - - // keep cmin in line with dmin/dmax/textdim - if (which == dmax || which == dmin || which == textdim || which == pad || which == cmin) - set(cmin, axis, - max( - min(cmin(axis), dmax(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) 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(); - } + // Instance Methods ///////////////////////////////////////////////////////////////////// - /** 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() { - short co = (short)(2 * pad(o)); - short cxo = (short)(2 * pad(xo)); - - for(Box bt = getChild(0); bt != null; bt = bt.nextSibling()) { - if (bt.invisible || bt.absolute) continue; - co += bt.cmin(o); - cxo = (short)max(bt.cmin(xo) + 2 * pad(xo), cxo); - } - - set(cmin, o, co); - set(cmin, xo, cxo); - } - /** must be called after changes to image or border 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); - } + /** invoked when a resource needed to render ourselves finishes loading */ + public void perform() throws JSExn { - /** 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())); - } + // FIXME; we can't assume that just because we were performed the image is loaded. + // as external events have occured, check the state of box + if (texture != null) { + if (texture.isLoaded) { minwidth = min(texture.width, maxwidth); minheight = min(texture.height, maxheight); } + else { Stream res = texture.res; texture = null; throw new JSExn("image not found: "+res); } } - } - - - // 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(); + MARK_REPACK; + MARK_REFLOW; + MARK_RESIZE; + dirty(); } - /** loads the image described by string str, possibly blocking for a network load */ - private static ImageDecoder getImage(String str) { - ImageDecoder ret = null; - boolean ispng = false; + public Box getRoot() { return parent == null ? this : parent.getRoot(); } + public Surface getSurface() { return Surface.fromBox(getRoot()); } - if (str.indexOf(':') == -1) { - String s = str; - byte[] b = Resources.getResource(Resources.resolve(s + ".png", null)); - if (b == null) return null; - return PNG.decode(new ByteArrayInputStream(b), str); - - } else { - Thread thread = 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; + // FEATURE: use cx2/cy2 format + /** Adds the intersection of (x,y,w,h) and the node's current actual geometry to the Surface's dirty list */ + public void dirty() { dirty(0, 0, width, height); } + public void dirty(int x, int y, int w, int h) { + for(Box cur = this; cur != null; cur = cur.parent) { + // x and y have a different meaning on the root box + if (cur.parent != null && cur.test(CLIP)) { + w = min(x + w, cur.width) - max(x, 0); + h = min(y + h, cur.height) - max(y, 0); + x = max(x, 0); + y = max(y, 0); } - ThreadMessage mythread = (ThreadMessage)thread; - mythread.setPriority(Thread.MIN_PRIORITY); - mythread.done.release(); - try { - if (str.endsWith(".png")) ret = PNG.decode(Platform.urlToInputStream(new URL(str)), str); - else ret = GIF.decode(Platform.urlToInputStream(new URL(str)), str); - return ret; - - } 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(Thread.NORM_PRIORITY); - mythread.go.block(); + if (w <= 0 || h <= 0) return; + if (cur.parent == null && cur.getSurface() != null) cur.getSurface().dirty(x, y, w, h); + x += cur.x; + y += cur.y; + } + } + + + // Reflow //////////////////////////////////////////////////////////////////////////////////////// + + // static stuff so we don't have to keep reallocating + private static int[] numRowsInCol = new int[65535]; + private static LENGTH[] colWidth = new LENGTH[65535]; + private static LENGTH[] colMaxWidth = new LENGTH[65535]; + private static LENGTH[] rowHeight = new LENGTH[65535]; + private static LENGTH[] rowMaxHeight = new LENGTH[65535]; + static { for(int i=0; i r) { numclear = 0; continue; } + if (c != 0 && c + min(cols, child.colspan) - numclear > cols) break; + if (++numclear < min(cols, child.colspan)) continue; + for(int i=c - numclear + 1; i <= c; i++) numRowsInCol[i] += child.rowspan; + child.col = (short)(c - numclear + 1); child.row = r; + rows = (short)max(rows, child.row + child.rowspan); + child = child.nextPackedSibling(); + numclear = 0; + } } + for(int i=0; imouseinside 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", null, this); - else if (wasinside && !isinside && is_trapped("Leave")) put("Leave", null, this); - else if (wasinside && isinside && (mousex != oldmousex || mousey != oldmousey) && is_trapped("Move")) put("Move", null, 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; ids is passed through to Template.apply() */ - Box(Template anonymous, Vec pboxes, Vec ptemplates) { - super(true); - set(dmax, 0, Short.MAX_VALUE); - set(dmax, 1, Short.MAX_VALUE); - template = anonymous; - template.apply(this, pboxes, ptemplates); - 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) { - super(true); - set(dmax, 0, Short.MAX_VALUE); - set(dmax, 1, Short.MAX_VALUE); - this.importlist = importlist; - template = "box".equals(templatename) ? null : Template.getTemplate(templatename, importlist); - this.templatename = templatename; - if (template != null) { - template.apply(this, null, null); - 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 (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)) { - - int bw = border == null ? 0 : border[2].getWidth(); - int bh = border == null ? 0 : border[0].getHeight(); - - // 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), - 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)), - Math.abs(oldsize(1) - size(1)) + bh); + */ + (parent == null ? this : parent).dirty(thisx, thisy, this.width, this.height); + this.width = width; this.height = height; this.x = x; this.y = y; + dirty(); + } while (false); + this.width = width; this.height = height; this.x = x; this.y = y; + if (sizechange) putAndTriggerTrapsAndCatchExceptions("SizeChange", T); + if (poschange) putAndTriggerTrapsAndCatchExceptions("PosChange", T); + } + } + + void resize_children() { + + //#repeat col/row colspan/rowspan contentwidth/contentheight x/y width/height colMaxWidth/rowMaxHeight colWidth/rowHeight \ + // HSHRINK/VSHRINK maxwidth/maxheight cols/rows minwidth/minheight colWidth/rowHeight x_slack/y_slack + // PHASE 1: compute column min/max sizes + int x_slack = width; + for(int i=0; i 500) { - if (Log.on) Log.log(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"); - InterpretedFunction f = (InterpretedFunction)t.f; - if (Log.on) Log.log(this, "Current trap is at " + f.getSourceName() + ":" + f.getLineNumbers()[0]); - } catch (Throwable t) { } - } - - if (sizechange) put("SizeChange", null, Boolean.TRUE); - if (poschange) put("PosChange", null, 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, o, max(bt.cmin(o), min(size(o) - bt.abs(o) - pad(o), bt.dmax(o)))); - bt.set(size, xo, max(bt.cmin(xo), min(size(xo) - bt.abs(xo) - pad(xo), bt.dmax(xo)))); - } 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; - - bt.set(size, o, bound(bt.cmin(o), factor * bt.flex, bt.dmax(o))); - 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) < bt.dmax(o)) { - remaining_flex += bt.flex; - nextjoint = min(nextjoint, divide_round_up(bt.dmax(o), bt.flex)); - - } + // PHASE 2: hand out slack + for(int startslack = 0; x_slack > 0 && cols > 0 && startslack != x_slack;) { + int increment = max(1, x_slack / cols); + startslack = x_slack; + for(short col=0; col < cols; col++) { + // FIXME: double check this + int diff = min(min(colMaxWidth[col], colWidth[col] + increment) - colWidth[col], x_slack); + x_slack -= diff; + colWidth[col] += diff; } - - if (remaining_flex == 0) { - if (nextjoint <= factor) break; - factor = nextjoint; + } + //#end + + // Phase 3: assign childrens' actual sizes + for(Box child = getChild(0); child != null; child = child.nextSibling()) { + if (!child.test(VISIBLE)) continue; + int child_width, child_height, child_x, child_y; + if (!child.test(PACKED)) { + child_x = child.x; + child_y = child.y; + child_width = child.test(HSHRINK) ? child.contentwidth : min(child.maxwidth, width - child.x); + child_height = child.test(VSHRINK) ? child.contentheight : min(child.maxheight, height - child.y); + child_width = max(child.minwidth, child_width); + child_height = max(child.minheight, child_height); } else { - factor = min((goal - total + factor * remaining_flex) / remaining_flex, nextjoint); + int unbounded; + //#repeat col/row colspan/rowspan contentwidth/contentheight width/height colMaxWidth/rowMaxHeight \ + // child_x/child_y x/y HSHRINK/VSHRINK maxwidth/maxheight cols/rows minwidth/minheight x_slack/y_slack \ + // colWidth/rowHeight child_width/child_height ALIGN_RIGHT/ALIGN_BOTTOM ALIGN_LEFT/ALIGN_TOP + unbounded = 0; + for(int i = child.col; i < child.col + child.colspan; i++) unbounded += colWidth[i]; + child_width = min(unbounded, child.test(HSHRINK) ? child.contentwidth : child.maxwidth); + child_x = test(ALIGN_RIGHT) ? x_slack : test(ALIGN_LEFT) ? 0 : x_slack / 2; + for(int i=0; i < child.col; i++) child_x += colWidth[i]; + if (child_width > unbounded) child_x -= (child_width - unbounded) / 2; + //#end } - - if (goal - total <= remaining_flex) break; + child.resize(child_x, child_y, child_width, child_height); } - // 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 newsize = bound(bt.cmin(o), bt.size(o) + 1, bt.dmax(o)); - total += newsize - bt.size(o); - bt.set(size, o, newsize); - } - } + // cleanup + for(int i=0; i 0 && dy2 - dy1 > 0 && sx2 - sx1 > 0 && sy2 - sy1 > 0) - buf.drawPicture(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2); - } - } - + case "Press1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Press2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Press3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Release1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Release2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Release3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Click1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Click2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Click3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "DoubleClick1": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "DoubleClick2": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "DoubleClick3": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "KeyPressed": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "KeyReleased": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Move": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Enter": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + case "Leave": if (!test(STOP_UPWARD_PROPAGATION) && parent != null) parent.putAndTriggerTraps(name, value); + + case "_Move": propagateDownward(name, value, false); + case "_Press1": propagateDownward(name, value, false); + case "_Press2": propagateDownward(name, value, false); + case "_Press3": propagateDownward(name, value, false); + case "_Release1": propagateDownward(name, value, false); + case "_Release2": propagateDownward(name, value, false); + case "_Release3": propagateDownward(name, value, false); + case "_Click1": propagateDownward(name, value, false); + case "_Click2": propagateDownward(name, value, false); + case "_Click3": propagateDownward(name, value, false); + case "_DoubleClick1": propagateDownward(name, value, false); + case "_DoubleClick2": propagateDownward(name, value, false); + case "_DoubleClick3": propagateDownward(name, value, false); + case "_KeyPressed": propagateDownward(name, value, false); + case "_KeyReleased": propagateDownward(name, value, false); + + case "PosChange": return; + case "SizeChange": return; + case "childadded": return; + case "childremoved": return; + + case "thisbox": if (value == null) removeSelf(); + + default: super.put(name, value); + //#end + } + + private String alignToString() { + switch(flags & ALIGNS) { + case (ALIGN_TOP | ALIGN_LEFT): return "topleft"; + case (ALIGN_BOTTOM | ALIGN_LEFT): return "bottomleft"; + case (ALIGN_TOP | ALIGN_RIGHT): return "topright"; + case (ALIGN_BOTTOM | ALIGN_RIGHT): return "bottomright"; + case ALIGN_TOP: return "top"; + case ALIGN_BOTTOM: return "bottom"; + case ALIGN_LEFT: return "left"; + case ALIGN_RIGHT: return "right"; + case 0: return "center"; + default: throw new Error("invalid alignment flags: " + (flags & ALIGNS)); + } + } + + private void setAlign(Object value) { + //#switch(value) + case "center": clear(ALIGNS); + case "topleft": set(ALIGN_TOP | ALIGN_LEFT); + case "bottomleft": set(ALIGN_BOTTOM | ALIGN_LEFT); + case "topright": set(ALIGN_TOP | ALIGN_RIGHT); + case "bottomright": set(ALIGN_BOTTOM | ALIGN_RIGHT); + case "top": set(ALIGN_TOP); + case "bottom": set(ALIGN_BOTTOM); + case "left": set(ALIGN_LEFT); + case "right": set(ALIGN_RIGHT); + default: JS.log("invalid alignment \"" + value + "\""); + //#end } - - 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); + + private void setCursor(Object value) { + if (value == null) { clear(CURSOR); boxToCursor.remove(this); return; } + if (value.equals(boxToCursor.get(this))) return; + set(CURSOR); + boxToCursor.put(this, value); + Surface surface = getSurface(); + String tempcursor = surface.cursor; + // FIXME + //Move(surface.mousex, surface.mousey, surface.mousex, surface.mousey); + if (surface.cursor != tempcursor) surface.syncCursor(); + } + + private void setFill(Object value) throws JSExn { + if (value == null) { + // FIXME: Check this... does this make it transparent? + texture = null; + fillcolor = 0; + } else if (value instanceof String) { + // FIXME check double set + int newfillcolor = stringToColor((String)value); + if (newfillcolor == fillcolor) return; + fillcolor = newfillcolor; + } else if(value instanceof Stream) { + texture = Picture.load((Stream)value, this); } 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 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); + throw new JSExn("fill must be null, a String, or a stream"); } - - } - - - // Methods to implement org.mozilla.javascript.Scriptable ////////////////////////////////////// - - /** Returns the i_th child */ - public Object get(int i, Scriptable start) { - if (redirect == null) return null; - if (redirect != this) return redirect.get(i, start); - return i >= numChildren() ? null : getChild(i); + dirty(); } + // FIXME: mouse move/release still needs to propagate to boxen in which the mouse was pressed and is still held down /** - * 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() + * Handles events which propagate down the box tree. If obscured + * is set, then we merely check for Enter/Leave. */ - public void put(int i, Scriptable start, Object value) { - if (value == null) { - if (i > 0 && i < numChildren()) getChild(i).remove(); - return; - } - if (value instanceof RootProxy) { - if (Log.on) Log.log(this, "attempt to reparent a box via its proxy object at " + - Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine); - return; - } else if (!(value instanceof Box)) { - if (Log.on) Log.log(this, "attempt to set a numerical property on a box to anything other than a box at " + - Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine); - return; - } - Box newnode = (Box)value; - if (redirect == null) { - if (Log.on) Log.log(this, "attempt to add a child to a node with a null redirect at " + - Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine); - return; - } else if (redirect != this) redirect.put(i, null, newnode); - else { - if (numKids > 15 && children == null) convert_to_array(); - if (newnode.parent != null) 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= children.size()) { - newnode.indexInParent = children.size(); - children.addElement(newnode); - } else { - children.insertElementAt(newnode, i); - for(int j=i; j> 16); + String green = Integer.toHexString((argb & 0x0000FF00) >> 8); + String blue = Integer.toHexString(argb & 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; + } + + /** 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) { + + if (cur.parent != null) throw new Error("whoIs may only be invoked on the root box of a surface"); + int globalx = 0; + int globaly = 0; + + // 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.test(VISIBLE)) return null; + if (!cur.inside(x - globalx, y - globaly)) return cur.parent == null ? cur : null; + OUTER: while(true) { + for(int i=cur.treeSize() - 1; i>=0; i--) { + Box child = cur.getChild(i); + if (child == null) continue; // since this method is unsynchronized, we have to double-check + globalx += child.x; + globaly += child.y; + if (child.test(VISIBLE) && child.inside(x - globalx, y - globaly)) { cur = child; continue OUTER; } + globalx -= child.x; + globaly -= child.y; + } + break; } - - // 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); - - return super.get(name, start); + return cur; } - /** indicate that we don't want JSObject trying to handle these */ - public boolean has(String name, Scriptable start) { - if (name.equals("")) return false; - if (traps != null && traps.get(name) != null) return true; - if (name.charAt(0) == '_') return true; - if (SpecialBoxProperty.specialBoxProperties.get(name) != null) return true; - if (name.equals("Function") || name.equals("Array") || name.equals("Object") || - name.equals("TypeError") || name.equals("ConversionError")) return true; - return super.has(name, start); - } - - public void put(String name, Scriptable start, Object value) { put(name, start, value, false, null); } - public void put(String name, Scriptable start, Object value, boolean ignoretraps) { put(name, start, value, ignoretraps, null); } - /** - * 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(String name, Scriptable start, Object value, boolean ignoretraps, RootProxy rp) { - if (name == null) return; - if (name.startsWith("xwt_")) { - if (Log.on) Log.log(this, "attempt to set reserved property " + name + " at " + - Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine); - return; - } + // Trivial Helper Methods (should be inlined) ///////////////////////////////////////// - if (!ignoretraps && traps != null) { - Trap t = (Trap)traps.get(name); - if (t != null) { - Object[] arg = (Object[])singleObjects.remove(false); - if (arg == null) arg = new Object[] { value }; - else arg[0] = value; - t.perform(arg); - arg[0] = null; - singleObjects.append(arg); - return; - } - } + static short min(short a, short b) { if (ab) return a; else return b; } + static int max(int a, int b) { if (a>b) return a; else return b; } + static float max(float a, float b) { if (a>b) return a; else return b; } - SpecialBoxProperty gph = (SpecialBoxProperty)SpecialBoxProperty.specialBoxProperties.get(name); - if (gph != null) { - gph.put(name, this, value); - return; - } + static int min(int a, int b, int c) { if (a<=b && a<=c) return a; else if (b<=c && b<=a) return b; else return c; } + static int max(int a, int b, int c) { if (a>=b && a>=c) return a; else if (b>=c && b>=a) return b; else return c; } + static 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 test(VISIBLE) && x >= 0 && y >= 0 && x < width && y < height; } - if (name.charAt(0) == '_') { - if (value != null && !(value instanceof Function)) { - if (Log.on) Log.log(this, "attempt to put a non-function value to " + name + " at " + - Context.enter().interpreterSourceFile + ":" + Context.enter().interpreterLine); - } 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, ((Function)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, ((Function)value), false, rp); - } - return; - } + void set(int mask) { flags |= mask; } + void set(int mask, boolean setclear) { if (setclear) set(mask); else clear(mask); } + void clear(int mask) { flags &= ~mask; } + boolean test(int mask) { return ((flags & mask) == mask); } + - if (ignoretraps) { - // traps always cascade to the global property, not the local one - putGlobally(name, start, value); - } else { - super.put(name, start, value); - } + // Tree Handling ////////////////////////////////////////////////////////////////////// - // 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); - } - } + public final int getIndexInParent() { return parent == null ? 0 : parent.indexNode(this); } + public final Box nextSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) + 1); } + public final Box prevSibling() { return parent == null ? null : parent.getChild(parent.indexNode(this) - 1); } + public final Box getChild(int i) { + if (i < 0) return null; + if (i >= treeSize()) return null; + return (Box)getNode(i); } - /** the delete keyword is not valid in XWT scripts */ - public void delete(int i) { } - - // 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); + void removeSelf() { + if (parent != null) { parent.removeChild(parent.indexNode(this)); return; } + Surface surface = Surface.fromBox(this); + if (surface != null) surface.dispose(true); + } + + /** remove the i^th child */ + public void removeChild(int i) { + Box b = getChild(i); + MARK_REFLOW_b; + b.dirty(); + b.clear(MOUSEINSIDE); + deleteNode(i); + b.parent = null; + MARK_REFLOW; + putAndTriggerTrapsAndCatchExceptions("childremoved", b); } - /** 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(); + public void put(int i, Object value) throws JSExn { + if (i < 0) return; + + if (value != null && !(value instanceof Box)) { + if (Log.on) JS.log(this, "attempt to set a numerical property on a box to a non-box"); 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 treeSize()) return; + Box b = getChild(i); + removeChild(i); + putAndTriggerTrapsAndCatchExceptions("childremoved", b); - // note that JavaScript box[0] will invoke put(int i), not put(String s) - if (oldparent != null) oldparent.put("0", null, 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= 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(); - } + Box b = (Box)value; + // check if box being moved is currently target of a redirect + for(Box cur = b.parent; cur != null; cur = cur.parent) + if (cur.redirect == b) { + if (Log.on) JS.log(this, "attempt to move a box that is the target of a redirect"); + return; + } - // Root Proxy /////////////////////////////////////////////////////////////////////////////// + // check for recursive ancestor violation + for(Box cur = this; cur != null; cur = cur.parent) + if (cur == b) { + if (Log.on) JS.log(this, "attempt to make a node a parent of its own ancestor"); + if (Log.on) Log.info(this, "box == " + this + " ancestor == " + b); + return; + } - RootProxy myproxy = null; - public Scriptable getRootProxy() { - if (myproxy == null) myproxy = new RootProxy(this); - return myproxy; + if (b.parent != null) b.parent.removeChild(b.parent.indexNode(b)); + insertNode(i, b); + b.parent = this; + + // need both of these in case child was already uncalc'ed + MARK_REFLOW_b; + MARK_REFLOW; + + b.dirty(); + putAndTriggerTrapsAndCatchExceptions("childadded", b); + } } - private static class RootProxy implements Scriptable { - - Box box; - RootProxy(Box b) { this.box = b; } - - public void delete(String name) { box.delete(name); } - public Scriptable getParentScope() { return box.getParentScope(); } - public void setParentScope(Scriptable p) { box.setParentScope(p); } - public boolean hasInstance(Scriptable value) { return box.hasInstance(value); } - public Scriptable getPrototype() { return box.getPrototype(); } - public void setPrototype(Scriptable p) { box.setPrototype(p); } - public void delete(int i) { box.delete(i); } - public String getClassName() { return box.getClassName(); } - public Object getDefaultValue(Class hint) { return box.getDefaultValue(hint); } - - public void put(int i, Scriptable start, Object value) { if (value != null) box.put(i, start, value); } - public Object get(String name, Scriptable start) { return box.get(name, start); } - public Object get(int i, Scriptable start) { return null; } - - public void put(String name, Scriptable start, Object value) { box.put(name, start, value, false, this); } - public boolean has(String name, Scriptable start) { return box.has(name, start); } - public boolean has(int i, Scriptable start) { return box.has(i, start); } - public Object[] getIds() { return box.getIds(); } - + void putAndTriggerTrapsAndCatchExceptions(Object name, Object val) { + try { + putAndTriggerTraps(name, val); + } catch (JSExn e) { + JS.log("caught js exception while putting to trap \""+name+"\""); + JS.log(e); + } catch (Exception e) { + JS.log("caught exception while putting to trap \""+name+"\""); + JS.log(e); + } } +} - // 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 (ab) 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 up instead of down */ - static final int divide_round_up(int numerator, int denominator) { - 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; + /* + offset_x = 0; + if (path != null) { + if (rpath == null) rpath = path.realize(transform == null ? VectorGraphics.Affine.identity() : transform); + if ((flags & HSHRINK) != 0) contentwidth = max(contentwidth, rpath.boundingBoxWidth()); + if ((flags & VSHRINK) != 0) contentheight = max(contentheight, rpath.boundingBoxHeight()); + // FIXME: separate offset_x needed for the path } - return this; - } - -} + // #repeat x1/y1 x2/y2 x3/y3 x4/y4 contentwidth/contentheight left/top right/bottom + int x1 = transform == null ? 0 : (int)transform.multiply_px(0, 0); + int x2 = transform == null ? 0 : (int)transform.multiply_px(contentwidth, 0); + int x3 = transform == null ? contentwidth : (int)transform.multiply_px(contentwidth, contentheight); + int x4 = transform == null ? contentwidth : (int)transform.multiply_px(0, contentheight); + int left = min(min(x1, x2), min(x3, x4)); + int right = max(max(x1, x2), max(x3, x4)); + contentwidth = max(contentwidth, right - left); + offset_x = -1 * left; + // #end + */ + + /* + if (path != null) { + if (rtransform == null) rpath = null; + else if (!rtransform.equalsIgnoringTranslation(a)) rpath = null; + else { + rpath.translate((int)(a.e - rtransform.e), (int)(a.f - rtransform.f)); + rtransform = a.copy(); + } + if (rpath == null) rpath = path.realize((rtransform = a) == null ? VectorGraphics.Affine.identity() : a); + if ((strokecolor & 0xff000000) != 0) rpath.stroke(buf, 1, strokecolor); + if ((fillcolor & 0xff000000) != 0) rpath.fill(buf, new VectorGraphics.SingleColorPaint(fillcolor)); + } +*/ +/* + VectorGraphics.Affine a2 = VectorGraphics.Affine.translate(b.x, b.y); + if (transform != null) a2.multiply(transform); + a2.multiply(VectorGraphics.Affine.translate(offset_x, offset_y)); + a2.multiply(a); +*/