custom simplex solver (post-experimental)
[org.ibex.core.git] / src / org / ibex / Box.java
index 7f636ba..6d74e69 100644 (file)
@@ -58,7 +58,7 @@ public final class Box extends JSScope implements Scheduler.Task {
 
     protected Box() { super(null); }
 
-    static Hash boxToCursor = new Hash(500, 3);
+    static Hash boxToCursor = new Hash(500, 3);               // FIXME memory leak
     public static final int MAX_LENGTH = Integer.MAX_VALUE;
     static final Font DEFAULT_FONT;
    
@@ -85,11 +85,9 @@ public final class Box extends JSScope implements Scheduler.Task {
         "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"
+        "Enter", "Leave", "Move", "ChildChange",
+        "KeyPressed", "KeyReleased", "SizeChange",
+        "Focused", "Maximized", "Minimized", "Close"
     };
 
     // Flags //////////////////////////////////////////////////////////////////////
@@ -118,13 +116,14 @@ public final class Box extends JSScope implements Scheduler.Task {
     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;
+    static final int MOVED         = 0x00080000;
 
 
     // Instance Data //////////////////////////////////////////////////////////////////////
 
     Box parent = null;
     Box redirect = this;
-    int flags = VISIBLE | PACKED | REPACK | REFLOW | RESIZE | FIXED /* ROWS */ | STOP_UPWARD_PROPAGATION | CLIP;
+    int flags = VISIBLE | PACKED | REPACK | REFLOW | RESIZE | FIXED /* ROWS */ | STOP_UPWARD_PROPAGATION | CLIP | MOVED;
 
     private String text = null;
     private Font font = DEFAULT_FONT; 
@@ -170,19 +169,9 @@ public final class Box extends JSScope implements Scheduler.Task {
 
     /** invoked when a resource needed to render ourselves finishes loading */
     public void perform() throws JSExn {
-
-        // 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 { JS res = texture.stream; texture = null; throw new JSExn("image not found: "+res.unclone()); }
-        } else {
-            Log.warn(Box.class, "perform() called with null texture");
-        }
-        MARK_REPACK;
-        MARK_REFLOW;
-        MARK_RESIZE;
-        dirty();
+        if (texture == null) { Log.warn(Box.class, "perform() called with null texture"); return; }
+        if (texture.isLoaded) { setMinWidth(max(texture.width, maxwidth)); setMinHeight(max(texture.height, maxheight)); }
+        else { JS res = texture.stream; texture = null; throw new JSExn("image not found: "+res.unclone()); }
     }
 
     // FEATURE: use cx2/cy2 format
@@ -207,20 +196,18 @@ public final class Box extends JSScope implements Scheduler.Task {
 
     // Reflow ////////////////////////////////////////////////////////////////////////////////////////
 
-    // worst case runtime = O(numboxes * numboxes_in_widest_row)
-    
-    private static Box[] frontier = new Box[65535];  // FIXME: GC hazard
-
-    /** pack the boxes into rows and columns; also computes contentwidth */
+    private static Box[] frontier = new Box[65535];
+    /** pack the boxes into rows and columns, compute contentwidth */
     void pack() {
         for(Box child = getChild(0); child != null; child = child.nextSibling()) child.pack();
         int frontier_size = 0; contentwidth = 0; contentheight = 0;
         //#repeat COLS/ROWS rows/cols cols/rows col/row row/col colspan/rowspan rowspan/colspan \
         //        contentheight/contentwidth contentwidth/contentheight
-        if (treeSize() > 0 && test(FIXED) == COLS) {
+        if (test(FIXED) == COLS) {
             rows = 0;
             for(Box child = getChild(0); child != null; child = child.nextSibling()) {
                 if (!child.test(PACKED) || !child.test(VISIBLE)) continue;
+                if (cols == 1) { child.row = rows; rows += child.rowspan; child.col = 0; continue; }
                 child.col = (short)(frontier_size <= 0 ? 0 : (frontier[frontier_size-1].col + frontier[frontier_size-1].colspan));
                 child.row = (short)(frontier_size <= 0 ? 0 : frontier[frontier_size-1].row);
                 if (child.col + min(cols,child.colspan) > cols) { child.col = 0; child.row++; }
@@ -238,39 +225,37 @@ public final class Box extends JSScope implements Scheduler.Task {
                     } else break;
                 frontier[frontier_size++] = child;
             }
-            for(int i=0; i<frontier_size; i++){rows=(short)max(rows, frontier[i].row + frontier[i].rowspan); frontier[i] = null; }
+            for(int i=0; i<frontier_size; i++){ rows=(short)max(rows, frontier[i].row + frontier[i].rowspan); frontier[i] = null; }
         }
         //#end
         solve(true);
         //#repeat contentwidth/contentheight contentheight/contentwidth minwidth/minheight row/col col/row \
         //        textwidth/textheight maxwidth/maxheight cols/rows rows/cols colspan/rowspan rowspan/colspan
         contentwidth = bound(minwidth,
-                             max(contentwidth,
-                                 font == null || text == null ? 0 : font.textwidth(text)),
+                             max(contentwidth, font == null || text == null ? 0 : font.textwidth(text)),
                              maxwidth);
         //#end
     }
     
     void resize(LENGTH x, LENGTH y, LENGTH width, LENGTH height) {
-        if (x != this.x || y != this.y || width != this.width || height != this.height) {
-            boolean sizechange = (this.width != width || this.height != height) && getTrap("SizeChange") != null;
-            do {
-                int thisx = parent == null ? 0 : this.x;
-                int thisy = parent == null ? 0 : this.y;
-                // we can't reenable this until we track surface-relative sizes; imagine clear surface with nonclear children
-                if (false /*texture == null && (text == null || text.equals(""))*/) {
-                    if ((fillcolor & 0xff000000) == 0) break;
-                    if (this.x == x && this.y == y) {
-                        Box who = (parent == null ? this : parent);
-                        who.dirty(thisx+min(this.width,width), thisy, Math.abs(width-this.width), max(this.height, height));
-                        who.dirty(thisx, thisy+min(this.height,height), min(this.width, width), Math.abs(height-this.height));
-                        break;
-                    }
+        if (x == this.x && y == this.y && width == this.width && height == this.height) return;
+        boolean sizechange = (this.width != width || this.height != height) && getTrap("SizeChange") != null;
+        try {
+            int thisx = parent == null ? 0 : this.x;
+            int thisy = parent == null ? 0 : this.y;
+            if (this.x != x || this.y != y) set(MOVED);
+            if (texture == null && (text == null || text.equals("")) && !test(MOVED)) {
+                if ((fillcolor & 0xff000000) != 0) {
+                    Box who = (parent == null ? this : parent);
+                    who.dirty(thisx+min(this.width,width), thisy, Math.abs(width-this.width), max(this.height, height));
+                    who.dirty(thisx, thisy+min(this.height,height), min(this.width, width), Math.abs(height-this.height));
                 }
-                (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);
+                //return;
+            }
+            (parent == null ? this : parent).dirty(thisx, thisy, this.width, this.height);
+            this.width = width; this.height = height; this.x = x; this.y = y;
+            dirty();
+        } finally {
             this.width = width; this.height = height; this.x = x; this.y = y;
             if (sizechange) putAndTriggerTrapsAndCatchExceptions("SizeChange", T);
         }
@@ -307,84 +292,72 @@ public final class Box extends JSScope implements Scheduler.Task {
     }
     //#end
 
+    private static float[] sizes = new float[65535];
+    private static float[] sizes_v = new float[65535];
     void solve(boolean findMinimum) {
         int numkids = 0; for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling()) numkids++;
         //#repeat col/row colspan/rowspan contentwidth/contentheight width/height HSHRINK/VSHRINK numregions/numregions_v \
         //        maxwidth/maxheight cols/rows minwidth/minheight lp_h/lp lp_h/lp easy_width/easy_height regions/regions_v \
-        //        computeRegions/computeRegions_v
-        if (numkids > 0) do {
-            computeRegions();
-            int nc = numregions * 3 + numkids * 2 + 3;
-            if (coeff == null || nc+1>coeff.length) coeff = new float[nc+1];
-            lp_h.init(nc);
-
-            for(int i=0; i<coeff.length; i++) coeff[i] = (float)0.0;
-            if (!findMinimum) {
-                coeff[numregions*2+numkids] = (float)10000.0;           // priority 1: sum of columns no greater than parent
-                for(int i=numregions*2; i<numregions*2+numkids; i++) coeff[i] = (float)100.0;  // priority 2: honor maxwidths
-                for(int i=numregions; i<numregions*2; i++) coeff[i] = (float)(0.1);            // priority 3: equalize columns
+        //        computeRegions/computeRegions_v targetColumnSize/targetRowSize sizes/sizes_v
+        if (numkids == 0) {
+            if (findMinimum) contentwidth = 0;
+            else targetColumnSize = 0;
+        } else if (cols == 1) {
+            if (findMinimum) {
+                contentwidth = 0;
+                for(Box c = firstPackedChild(); c != null; c = c.nextPackedSibling())
+                    contentwidth = max(contentwidth, c.contentwidth);
             } else {
-                coeff[numregions*2+numkids] = (float)1.0;
+                targetColumnSize = width;
             }
-            lp_h.setObjective(coeff, false);
-
-            // priority 1: sum of columns as close to parent's width as possible
-            for(int i=0; i<coeff.length; i++) coeff[i] = (i<numregions) ? (float)(regions[i+1] - regions[i]) : (float)0.0;
-            coeff[numregions*2+numkids] = (float)-1.0;
-            if (!findMinimum) lp_h.add_constraint(coeff, Simplex.LE, (float)width);
-            else              lp_h.add_constraint(coeff, Simplex.LE, (float)0);
-
-            int childnum = 0;
-            for(Box child = firstPackedChild(); child != null; child = child.nextPackedSibling()) {
-
-                // invariant: honor minwidths
-                for(int i=0; i<coeff.length; i++) coeff[i] = (float)0.0;
-                for(int r=0; r<numregions; r++)
-                    if (regions[r] >= child.col && regions[r+1] <= min(child.col+child.colspan,cols))
-                        coeff[r] = (float)(regions[r+1] - regions[r]);
-                lp_h.add_constraint(coeff, Simplex.GE, (float)child.contentwidth);
-                if (!findMinimum) {
-                    // priority 2: honor maxwidths
-                    int child_maxwidth = child.test(HSHRINK) ? min(child.maxwidth, child.contentwidth) : child.maxwidth;
-                    if (child_maxwidth < Integer.MAX_VALUE) {
-                        for(int i=0; i<coeff.length; i++) coeff[i] = (float)0.0;
-                        for(int r=0; r<numregions; r++)
-                            if (regions[r] >= child.col && regions[r+1] <= min(child.col+child.colspan,cols))
-                                coeff[r] = (float)(regions[r+1] - regions[r]);
-                        coeff[numregions*2+childnum] = (float)-1.0;
-                        lp_h.add_constraint(coeff, Simplex.LE, (float)child_maxwidth);
+        } else if (cols > 1) do {
+            computeRegions();
+            int target = findMinimum ? 0 : Math.max(width, contentwidth);
+            // priority 0: (inviolable) honor minwidths
+            // priority 1: sum of columns no greater than parent
+            // priority 2: honor maxwidths
+            // priority 3: equalize columns
+            float targetColumnSize = target == 0 ? 0 : this.targetColumnSize;
+            float last_columnsize = 0;
+            float last_total = 0;
+            float total;
+            boolean first = true;
+            while(true) {
+                total = (float)0.0;
+                for(int r=0; r<numregions; r++) total += (sizes[r] = (float)(targetColumnSize * (regions[r+1]-regions[r])));
+                int minregion = 0;
+                for(Box child = firstPackedChild(); child != null; child = child.nextPackedSibling())
+                    for(int r=(child.col==0?0:minregion); r<numregions; r++) {
+                        if (regions[r+1] < child.col) continue;
+                        if (regions[r] >= min(child.col+child.colspan,cols)) { minregion = r; break; }
+                        total -= sizes[r];
+                        if (sizes[r] <= (float)(targetColumnSize*(regions[r+1]-regions[r])))
+                            if ((child.colspan * targetColumnSize) > (child.maxwidth + (float)0.5))
+                                sizes[r] = (float)Math.min(sizes[r], (regions[r+1]-regions[r])*(child.maxwidth/child.colspan));
+                        if ((child.colspan * targetColumnSize) < (child.contentwidth - (float)0.5))
+                            sizes[r] = (float)Math.max(sizes[r], (regions[r+1]-regions[r])*(child.contentwidth/child.colspan));
+                        total += sizes[r];
                     }
+                float save = targetColumnSize;
+                if (Math.abs(total - target) <= (float)1.0) break;
+                if (!first) {
+                    if (Math.abs(total - last_total) <= (float)1.0) break;
+                } else {
+                    last_columnsize = ((total - target) / (float)cols) + targetColumnSize;
                 }
-                childnum++;
-            }
-
-            if (!findMinimum) {
-                // priority 3: equalize columns
-                float avg = ((float)width)/((float)numregions);
-                for(int r=0; r<numregions; r++) {
-                    float weight = (float)(regions[r+1] - regions[r]);
-                    for(int k=0; k<coeff.length; k++) coeff[k] = (float)(k==r?weight:k==(numregions+r)?-1.0:0.0);
-                    lp_h.add_constraint(coeff, Simplex.LE, avg * weight);
-                    for(int k=0; k<coeff.length; k++) coeff[k] = (float)(k==r?weight:k==(numregions+r)?1.0:0.0);
-                    lp_h.add_constraint(coeff, Simplex.GE, avg * weight);
-                }
+                if (total < target)      targetColumnSize += Math.abs((last_columnsize - targetColumnSize) / (float)1.1);
+                else if (total > target) targetColumnSize -= Math.abs((last_columnsize - targetColumnSize) / (float)1.1);
+                last_columnsize = save;
+                last_total = total;
+                first = false;
             }
-
-            try { switch(lp_h.solve()) {
-                case Simplex.UNBOUNDED: Log.warn(this, "simplex claims unboundedness; this should never happen"); break;
-                case Simplex.INFEASIBLE: Log.debug(this, "simplex claims infeasibility; this should never happen"); break;
-                case Simplex.MILP_FAIL: Log.warn(this, "simplex claims MILP_FAIL; this should never happen"); break;
-                case Simplex.RUNNING: Log.warn(this, "simplex still RUNNING; this should never happen"); break;
-                case Simplex.FAILURE: Log.warn(this, "simplex claims FAILURE; this should never happen"); break;
-            } } catch (Error e) {
-                Log.warn(this, "got an Error in simplex solver; not sure why this happens");
-                return;
-            }
-
-            if (findMinimum) contentwidth = Math.round(lp_h.solution[lp_h.rows + (2*numregions + numkids + 1)]);
+            if (findMinimum) contentwidth = Math.round(total);
+            else this.targetColumnSize = targetColumnSize;
         } while(false);
         //#end
     }
+    private float targetColumnSize = (float)0.0;
+    private float targetRowSize = (float)0.0;
 
     void place() {
         solve(false);
@@ -405,26 +378,26 @@ public final class Box extends JSScope implements Scheduler.Task {
                 //#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 \
                 //        child_width/child_height ALIGN_RIGHT/ALIGN_BOTTOM ALIGN_LEFT/ALIGN_TOP lp_h/lp \
-                //        numregions/numregions_v regions/regions_v
-                child_width = 0;
+                //        numregions/numregions_v regions/regions_v targetColumnSize/targetRowSize sizes/sizes_v
                 child_x = 0;
                 if (cols == 1) {
-                    child_x = 0;
                     child_width = width;
                 } else {
-                    for(int r=0; r<numregions; r++)
-                        if (regions[r] >= child.col && regions[r+1] <= min(child.col+child.colspan,cols))
-                            child_width += Math.round(lp_h.solution[lp_h.rows+r+1] * (regions[r+1] - regions[r]));
-                        else if (regions[r+1] <= child.col)
-                            child_x += Math.round(lp_h.solution[lp_h.rows+r+1] * (regions[r+1] - regions[r]));
+                    child_width = 0;
+                    for(int r=0; r<numregions; r++) {
+                        if (regions[r] < child.col) child_x += Math.round(sizes[r]);
+                        else if (regions[r] < child.col+child.colspan) child_width += Math.round(sizes[r]);
+                    }
                 }
                 diff = (child_width - (child.test(HSHRINK) ? child.contentwidth : min(child_width, child.maxwidth)));
                 child_x += (child.test(ALIGN_RIGHT) ? diff : child.test(ALIGN_LEFT) ? 0 : diff / 2);
                 child_width -= diff;
                 //#end
             }
+            if (test(MOVED)) child.set(MOVED);
             child.resize(child_x, child_y, child_width, child_height);
         }
+        clear(MOVED);
 
         for(Box child = getChild(0); child != null; child = child.nextSibling())
             if (child.test(VISIBLE) && child.treeSize() > 0)
@@ -578,6 +551,14 @@ public final class Box extends JSScope implements Scheduler.Task {
         }
     }
 
+    public void setMinWidth(int minwidth) {
+        if (this.minwidth == minwidth) return;
+        MARK_RESIZE; MARK_REFLOW; MARK_REPACK; this.minwidth = minwidth;
+    }
+    public void setMinHeight(int minheight) {
+        if (this.minheight == minheight) return;
+        MARK_RESIZE; MARK_REFLOW; MARK_REPACK; this.minheight = minheight;
+    }
     public void setMaxWidth(Object value) {
         do { CHECKSET_INT(maxwidth); MARK_RESIZE; } while(false);
         if (parent == null && getSurface() != null) getSurface().pendingWidth = maxwidth; 
@@ -702,10 +683,8 @@ public final class Box extends JSScope implements Scheduler.Task {
         case "_HScroll":      propagateDownward(name, value, false);
         case "_VScroll":      propagateDownward(name, value, false);
 
-        case "PosChange":     return;
         case "SizeChange":    return;
-        case "childadded":    return;
-        case "childremoved":  return;
+        case "ChildChange":    return;
         case "Enter":         return;
         case "Leave":         return;
 
@@ -944,7 +923,7 @@ public final class Box extends JSScope implements Scheduler.Task {
         deleteNode(i);
         b.parent = null;
         MARK_REFLOW;
-        putAndTriggerTrapsAndCatchExceptions("childremoved", b);
+        putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
     }
     
     public void put(int i, Object value) throws JSExn {
@@ -956,22 +935,22 @@ public final class Box extends JSScope implements Scheduler.Task {
         }
 
         if (redirect == null) {
-            if (value == null) putAndTriggerTrapsAndCatchExceptions("childremoved", getChild(i));
+            if (value == null) putAndTriggerTrapsAndCatchExceptions("ChildChange", getChild(i));
             else JS.warn("attempt to add/remove children to/from a node with a null redirect");
 
         } else if (redirect != this) {
-            if (value != null) putAndTriggerTrapsAndCatchExceptions("childadded", value);
+            if (value != null) putAndTriggerTrapsAndCatchExceptions("ChildChange", value);
             redirect.put(i, value);
             if (value == null) {
                 Box b = (Box)redirect.get(new Integer(i));
-                if (b != null) putAndTriggerTrapsAndCatchExceptions("childremoved", b);
+                if (b != null) putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
             }
 
         } else if (value == null) {
             if (i < 0 || i > treeSize()) return;
             Box b = getChild(i);
             removeChild(i);
-            putAndTriggerTrapsAndCatchExceptions("childremoved", b);
+            putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
 
         } else {
             Box b = (Box)value;
@@ -1000,7 +979,7 @@ public final class Box extends JSScope implements Scheduler.Task {
             MARK_REFLOW;
             
             b.dirty(); 
-            putAndTriggerTrapsAndCatchExceptions("childadded", b);
+            putAndTriggerTrapsAndCatchExceptions("ChildChange", b);
         }
     }