JAL-2050 JAL-1722 new getSelectedRange() method to quickly hide selected columns
[jalview.git] / src / jalview / datamodel / ColumnSelection.java
index 835d7e9..c23b772 100644 (file)
@@ -25,6 +25,7 @@ import jalview.viewmodel.annotationfilter.AnnotationFilterParameter;
 import jalview.viewmodel.annotationfilter.AnnotationFilterParameter.SearchableAnnotationField;
 
 import java.util.ArrayList;
+import java.util.BitSet;
 import java.util.Collections;
 import java.util.List;
 import java.util.Vector;
@@ -34,9 +35,182 @@ import java.util.Vector;
  */
 public class ColumnSelection
 {
-  Vector<Integer> selected = new Vector<Integer>();
+  private class IntList
+  {
+    /*
+     * list of selected columns (ordered by selection order, not column order)
+     */
+    private List<Integer> order = new ArrayList<Integer>();
+
+    /**
+     * bitfield for column selection - allows quick lookup
+     */
+    private BitSet selected = new BitSet();
+
+    /**
+     * adds a new column i to the selection - only if i is not already selected
+     * 
+     * @param i
+     */
+    public void add(int i)
+    {
+      if (!selected.get(i))
+      {
+        order.add(Integer.valueOf(i));
+        selected.set(i);
+      }
+    }
+
+    public void clear()
+    {
+      order.clear();
+      selected.clear();
+    }
+
+    public void remove(int col)
+    {
+
+      Integer colInt = new Integer(col);
+
+      if (selected.get(col))
+      {
+        // if this ever changes to List.remove(), ensure Integer not int
+        // argument
+        // as List.remove(int i) removes the i'th item which is wrong
+        order.remove(colInt);
+        selected.clear(col);
+      }
+    }
+
+    public boolean contains(Integer colInt)
+    {
+      return selected.get(colInt);
+    }
+
+    public boolean isEmpty()
+    {
+      return order.isEmpty();
+    }
+
+    public List<Integer> getList()
+    {
+      return order;
+    }
+
+    public int size()
+    {
+      return order.size();
+    }
+
+    /**
+     * gets the column that was selected first, second or i'th
+     * 
+     * @param i
+     * @return
+     */
+    public int elementAt(int i)
+    {
+      return order.get(i);
+    }
+
+    protected boolean pruneColumnList(final List<int[]> shifts)
+    {
+      int s = 0, t = shifts.size();
+      int[] sr = shifts.get(s++);
+      boolean pruned = false;
+      int i = 0, j = order.size();
+      while (i < j && s <= t)
+      {
+        int c = order.get(i++).intValue();
+        if (sr[0] <= c)
+        {
+          if (sr[1] + sr[0] >= c)
+          { // sr[1] -ve means inseriton.
+            order.remove(--i);
+            selected.clear(c);
+            j--;
+          }
+          else
+          {
+            if (s < t)
+            {
+              sr = shifts.get(s);
+            }
+            s++;
+          }
+        }
+      }
+      return pruned;
+    }
+
+    /**
+     * shift every selected column at or above start by change
+     * 
+     * @param start
+     *          - leftmost column to be shifted
+     * @param change
+     *          - delta for shift
+     */
+    public void compensateForEdits(int start, int change)
+    {
+      BitSet mask = new BitSet();
+      for (int i = 0; i < order.size(); i++)
+      {
+        int temp = order.get(i);
+
+        if (temp >= start)
+        {
+          // clear shifted bits and update List of selected columns
+          selected.clear(temp);
+          mask.set(temp - change);
+          order.set(i, new Integer(temp - change));
+        }
+      }
+      // lastly update the bitfield all at once
+      selected.or(mask);
+    }
+
+    public boolean isSelected(int column)
+    {
+      return selected.get(column);
+    }
 
-  // Vector of int [] {startCol, endCol}
+    public int getMaxColumn()
+    {
+      return selected.length() - 1;
+    }
+
+    public int getMinColumn()
+    {
+      return selected.get(0) ? 0 : selected.nextSetBit(0);
+    }
+
+    /**
+     * @return a series of selection intervals along the range
+     */
+    public List<int[]> getRanges()
+    {
+      List<int[]> rlist = new ArrayList<int[]>();
+      if (selected.isEmpty())
+      {
+        return rlist;
+      }
+      int next = selected.nextSetBit(0), clear = -1;
+      while (next != -1)
+      {
+        clear = selected.nextClearBit(next);
+        rlist.add(new int[] { next, clear - 1 });
+        next = selected.nextSetBit(clear);
+      }
+      return rlist;
+    }
+  }
+
+  IntList selected = new IntList();
+  /*
+   * list of hidden column [start, end] ranges; the list is maintained in
+   * ascending start column order
+   */
   Vector<int[]> hiddenColumns;
 
   /**
@@ -47,11 +221,7 @@ public class ColumnSelection
    */
   public void addElement(int col)
   {
-    Integer column = new Integer(col);
-    if (!selected.contains(column))
-    {
-      selected.addElement(column);
-    }
+    selected.add(col);
   }
 
   /**
@@ -59,7 +229,7 @@ public class ColumnSelection
    */
   public void clear()
   {
-    selected.removeAllElements();
+    selected.clear();
   }
 
   /**
@@ -70,14 +240,7 @@ public class ColumnSelection
    */
   public void removeElement(int col)
   {
-    Integer colInt = new Integer(col);
-
-    if (selected.contains(colInt))
-    {
-      // if this ever changes to List.remove(), ensure Integer not int argument
-      // as List.remove(int i) removes the i'th item which is wrong
-      selected.removeElement(colInt);
-    }
+    selected.remove(col);
   }
 
   /**
@@ -96,53 +259,48 @@ public class ColumnSelection
       colInt = new Integer(i);
       if (selected.contains(colInt))
       {
-        selected.removeElement(colInt);
+        selected.remove(colInt);
       }
     }
   }
 
   /**
-   * 
-   * @return Vector containing selected columns as Integers
+   * Returns a list of selected columns. The list contains no duplicates but is
+   * not necessarily ordered. It also may include columns hidden from the
+   * current view
    */
-  public Vector<Integer> getSelected()
+  public List<Integer> getSelected()
   {
-    return selected;
+    return selected.getList();
   }
 
   /**
-   * 
-   * @param col
-   *          index to search for in column selection
-   * 
-   * @return true if Integer(col) is in selection.
+   * @return list of int arrays containing start and end column position for
+   *         runs of selected columns ordered from right to left.
    */
-  public boolean contains(int col)
+  public List<int[]> getSelectedRanges()
   {
-    return selected.contains(new Integer(col));
+    return selected.getRanges();
   }
 
   /**
-   * Column number at position i in selection
    * 
-   * @param i
-   *          index into selected columns
+   * @param col
+   *          index to search for in column selection
    * 
-   * @return column number in alignment
+   * @return true if col is selected
    */
-  public int columnAt(int i)
+  public boolean contains(int col)
   {
-    return selected.elementAt(i).intValue();
+    return (col > -1) ? selected.isSelected(col) : false;
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @return DOCUMENT ME!
+   * Answers true if no columns are selected, else false
    */
-  public int size()
+  public boolean isEmpty()
   {
-    return selected.size();
+    return selected == null || selected.isEmpty();
   }
 
   /**
@@ -152,17 +310,11 @@ public class ColumnSelection
    */
   public int getMax()
   {
-    int max = -1;
-
-    for (int i = 0; i < selected.size(); i++)
+    if (selected.isEmpty())
     {
-      if (columnAt(i) > max)
-      {
-        max = columnAt(i);
-      }
+      return -1;
     }
-
-    return max;
+    return selected.getMaxColumn();
   }
 
   /**
@@ -172,17 +324,11 @@ public class ColumnSelection
    */
   public int getMin()
   {
-    int min = 1000000000;
-
-    for (int i = 0; i < selected.size(); i++)
+    if (selected.isEmpty())
     {
-      if (columnAt(i) < min)
-      {
-        min = columnAt(i);
-      }
+      return 1000000000;
     }
-
-    return min;
+    return selected.getMinColumn();
   }
 
   /**
@@ -196,16 +342,7 @@ public class ColumnSelection
   public List<int[]> compensateForEdit(int start, int change)
   {
     List<int[]> deletedHiddenColumns = null;
-    for (int i = 0; i < size(); i++)
-    {
-      int temp = columnAt(i);
-
-      if (temp >= start)
-      {
-        // if this ever changes to List.set(), swap parameter order!!
-        selected.setElementAt(new Integer(temp - change), i);
-      }
-    }
+    selected.compensateForEdits(start, change);
 
     if (hiddenColumns != null)
     {
@@ -254,16 +391,8 @@ public class ColumnSelection
    */
   private void compensateForDelEdits(int start, int change)
   {
-    for (int i = 0; i < size(); i++)
-    {
-      int temp = columnAt(i);
 
-      if (temp >= start)
-      {
-        // if this ever changes to List.set(), swap parameter order!!
-        selected.setElementAt(new Integer(temp - change), i);
-      }
-    }
+    selected.compensateForEdits(start, change);
 
     if (hiddenColumns != null)
     {
@@ -418,36 +547,6 @@ public class ColumnSelection
     // operations.
   }
 
-  private boolean pruneColumnList(final List<int[]> shifts,
-          Vector<Integer> list)
-  {
-    int s = 0, t = shifts.size();
-    int[] sr = shifts.get(s++);
-    boolean pruned = false;
-    int i = 0, j = list.size();
-    while (i < j && s <= t)
-    {
-      int c = list.elementAt(i++).intValue();
-      if (sr[0] <= c)
-      {
-        if (sr[1] + sr[0] >= c)
-        { // sr[1] -ve means inseriton.
-          list.removeElementAt(--i);
-          j--;
-        }
-        else
-        {
-          if (s < t)
-          {
-            sr = shifts.get(s);
-          }
-          s++;
-        }
-      }
-    }
-    return pruned;
-  }
-
   /**
    * remove any hiddenColumns or selected columns and shift remaining based on a
    * series of position, range deletions.
@@ -472,7 +571,7 @@ public class ColumnSelection
         }
         if (selected != null && selected.size() > 0)
         {
-          pruneColumnList(shifts, selected);
+          selected.pruneColumnList(shifts);
           if (selected != null && selected.size() == 0)
           {
             selected = null;
@@ -486,6 +585,7 @@ public class ColumnSelection
 
   /**
    * This Method is used to return all the HiddenColumn regions
+   * 
    * @return empty list or List of hidden column intervals
    */
   public List<int[]> getHiddenColumns()
@@ -552,6 +652,10 @@ public class ColumnSelection
 
   /**
    * Use this method to determine where the next hiddenRegion starts
+   * 
+   * @param hiddenRegion
+   *          index of hidden region (counts from 0)
+   * @return column number in visible view
    */
   public int findHiddenRegionPosition(int hiddenRegion)
   {
@@ -571,7 +675,7 @@ public class ColumnSelection
         gaps += region[1] + 1 - region[0];
         result = region[1] + 1;
         index++;
-      } while (index < hiddenRegion + 1);
+      } while (index <= hiddenRegion);
 
       result -= gaps;
     }
@@ -637,14 +741,22 @@ public class ColumnSelection
 
   public void hideSelectedColumns()
   {
-    while (size() > 0)
-    {
-      int column = getSelected().firstElement().intValue();
-      hideColumns(column);
+    synchronized (selected) {
+      for (int[] selregions:selected.getRanges())
+      {
+        hideColumns(selregions[0], selregions[1]);
+      }
+      selected.clear();
     }
 
   }
 
+  /**
+   * Adds the specified column range to the hidden columns
+   * 
+   * @param start
+   * @param end
+   */
   public void hideColumns(int start, int end)
   {
     if (hiddenColumns == null)
@@ -652,50 +764,68 @@ public class ColumnSelection
       hiddenColumns = new Vector<int[]>();
     }
 
-    boolean added = false;
-    boolean overlap = false;
-
+    /*
+     * traverse existing hidden ranges and insert / amend / append as
+     * appropriate
+     */
     for (int i = 0; i < hiddenColumns.size(); i++)
     {
       int[] region = hiddenColumns.elementAt(i);
-      if (start <= region[1] && end >= region[0])
+
+      if (end < region[0] - 1)
       {
-        hiddenColumns.removeElementAt(i);
-        overlap = true;
-        break;
+        /*
+         * insert discontiguous preceding range
+         */
+        hiddenColumns.insertElementAt(new int[] { start, end }, i);
+        return;
       }
-      else if (end < region[0] && start < region[0])
+
+      if (end <= region[1])
       {
-        hiddenColumns.insertElementAt(new int[]
-        { start, end }, i);
-        added = true;
-        break;
+        /*
+         * new range overlaps existing, or is contiguous preceding it - adjust
+         * start column
+         */
+        region[0] = Math.min(region[0], start);
+        return;
       }
-    }
 
-    if (overlap)
-    {
-      hideColumns(start, end);
-    }
-    else if (!added)
-    {
-      hiddenColumns.addElement(new int[]
-      { start, end });
+      if (start <= region[1] + 1)
+      {
+        /*
+         * new range overlaps existing, or is contiguous following it - adjust
+         * start and end columns
+         */
+        region[0] = Math.min(region[0], start);
+        region[1] = Math.max(region[1], end);
+        return;
+      }
     }
 
+    /*
+     * remaining case is that the new range follows everything else
+     */
+      hiddenColumns.addElement(new int[] { start, end });
   }
 
   /**
-   * This method will find a range of selected columns around the column
-   * specified
+   * Hides the specified column and any adjacent selected columns
    * 
    * @param res
    *          int
    */
   public void hideColumns(int col)
   {
-    // First find out range of columns to hide
-    int min = col, max = col + 1;
+    /*
+     * deselect column (whether selected or not!)
+     */
+    removeElement(col);
+
+    /*
+     * find adjacent selected columns
+     */
+    int min = col - 1, max = col + 1;
     while (contains(min))
     {
       removeElement(min);
@@ -708,6 +838,9 @@ public class ColumnSelection
       max++;
     }
 
+    /*
+     * min, max are now the closest unselected columns
+     */
     min++;
     max--;
     if (min > max)
@@ -718,6 +851,9 @@ public class ColumnSelection
     hideColumns(min, max);
   }
 
+  /**
+   * Unhides, and adds to the selection list, all hidden columns
+   */
   public void revealAllHiddenColumns()
   {
     if (hiddenColumns != null)
@@ -735,12 +871,18 @@ public class ColumnSelection
     hiddenColumns = null;
   }
 
-  public void revealHiddenColumns(int res)
+  /**
+   * Reveals, and marks as selected, the hidden column range with the given
+   * start column
+   * 
+   * @param start
+   */
+  public void revealHiddenColumns(int start)
   {
     for (int i = 0; i < hiddenColumns.size(); i++)
     {
       int[] region = hiddenColumns.elementAt(i);
-      if (res == region[0])
+      if (start == region[0])
       {
         for (int j = region[0]; j < region[1] + 1; j++)
         {
@@ -761,9 +903,8 @@ public class ColumnSelection
   {
     if (hiddenColumns != null)
     {
-      for (int i = 0; i < hiddenColumns.size(); i++)
+      for (int[] region : hiddenColumns)
       {
-        int[] region = hiddenColumns.elementAt(i);
         if (column >= region[0] && column <= region[1])
         {
           return false;
@@ -785,10 +926,10 @@ public class ColumnSelection
     {
       if (copy.selected != null)
       {
-        selected = new Vector<Integer>();
+        selected = new IntList();
         for (int i = 0, j = copy.selected.size(); i < j; i++)
         {
-          selected.addElement(copy.selected.elementAt(i));
+          selected.add(copy.selected.elementAt(i));
         }
       }
       if (copy.hiddenColumns != null)
@@ -909,16 +1050,14 @@ public class ColumnSelection
         }
         if (hideStart > vstart)
         {
-          visiblecontigs.add(new int[]
-          { vstart, hideStart - 1 });
+          visiblecontigs.add(new int[] { vstart, hideStart - 1 });
         }
         vstart = hideEnd + 1;
       }
 
       if (vstart < end)
       {
-        visiblecontigs.add(new int[]
-        { vstart, end - 1 });
+        visiblecontigs.add(new int[] { vstart, end - 1 });
       }
       int[] vcontigs = new int[visiblecontigs.size() * 2];
       for (int i = 0, j = visiblecontigs.size(); i < j; i++)
@@ -933,8 +1072,7 @@ public class ColumnSelection
     }
     else
     {
-      return new int[]
-      { start, end - 1 };
+      return new int[] { start, end - 1 };
     }
   }
 
@@ -975,7 +1113,7 @@ public class ColumnSelection
     if (hiddenColumns != null && hiddenColumns.size() > 0)
     {
       // then mangle the alignmentAnnotation annotation array
-      Vector<Annotation []> annels = new Vector<Annotation []>();
+      Vector<Annotation[]> annels = new Vector<Annotation[]>();
       Annotation[] els = null;
       List<int[]> regions = getHiddenColumns();
       int blockStart = start, blockEnd = end;
@@ -1035,7 +1173,7 @@ public class ColumnSelection
       alignmentAnnotation.annotations = new Annotation[w];
       w = 0;
 
-        for (Annotation [] chnk : annels)
+      for (Annotation[] chnk : annels)
       {
         System.arraycopy(chnk, 0, alignmentAnnotation.annotations, w,
                 chnk.length);
@@ -1082,16 +1220,13 @@ public class ColumnSelection
    */
   public void addElementsFrom(ColumnSelection colsel)
   {
-    if (colsel != null && colsel.size() > 0)
+    if (colsel != null && !colsel.isEmpty())
     {
       for (Integer col : colsel.getSelected())
       {
         if (hiddenColumns != null && isVisible(col.intValue()))
         {
-          if (!selected.contains(col))
-          {
-            selected.addElement(col);
-          }
+          selected.add(col);
         }
       }
     }
@@ -1105,7 +1240,7 @@ public class ColumnSelection
    */
   public void setElementsFrom(ColumnSelection colsel)
   {
-    selected = new Vector<Integer>();
+    selected = new IntList();
     if (colsel.selected != null && colsel.selected.size() > 0)
     {
       if (hiddenColumns != null && hiddenColumns.size() > 0)
@@ -1138,7 +1273,7 @@ public class ColumnSelection
    *         profileseq marked as hidden.
    */
   public static ColumnSelection propagateInsertions(SequenceI profileseq,
-          Alignment al, AlignmentView input)
+          AlignmentI al, AlignmentView input)
   {
     int profsqpos = 0;
 
@@ -1284,7 +1419,7 @@ public class ColumnSelection
   {
     return hiddenColumns != null && hiddenColumns.size() > 0;
   }
-  
+
   /**
    * 
    * @return true if there are more than one set of columns hidden
@@ -1308,7 +1443,7 @@ public class ColumnSelection
       hideColumns(r[0], r[1]);
     }
   }
-  
+
   public boolean filterAnnotations(Annotation[] annotations,
           AnnotationFilterParameter filterParams)
   {