JAL-2591 updated HiddenColumns::findHiddenRegionPositions + test
[jalview.git] / src / jalview / datamodel / HiddenColumns.java
index f6102d4..1e1a58b 100644 (file)
@@ -1,14 +1,20 @@
 package jalview.datamodel;
 
 import jalview.util.Comparison;
+import jalview.util.ShiftList;
 
 import java.util.ArrayList;
+import java.util.BitSet;
 import java.util.Collections;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Vector;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
 
-public class HiddenColumns
+public class HiddenColumns implements Iterable<int[]>
 {
+  private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
+  
   /*
    * list of hidden column [start, end] ranges; the list is maintained in
    * ascending start column order
@@ -33,15 +39,23 @@ public class HiddenColumns
    */
   public int getSize()
   {
-    int size = 0;
-    if (hasHidden())
+    try
     {
-      for (int[] range : hiddenColumns)
+      lock.readLock().lock();
+      int size = 0;
+      if (hasHidden())
       {
-        size += range[1] - range[0] + 1;
+        for (int[] range : hiddenColumns)
+        {
+          size += range[1] - range[0] + 1;
+        }
       }
+      return size;
+    }
+    finally
+    {
+      lock.readLock().unlock();
     }
-    return size;
   }
 
   /**
@@ -51,40 +65,56 @@ public class HiddenColumns
    */
   public boolean hasHidden()
   {
-    return (hiddenColumns != null) && (!hiddenColumns.isEmpty());
+    try
+    {
+      lock.readLock().lock();
+      return (hiddenColumns != null) && (!hiddenColumns.isEmpty());
+    } finally
+    {
+      lock.readLock().unlock();
+    }
+
   }
 
   @Override
   public boolean equals(Object obj)
   {
-    if (!(obj instanceof HiddenColumns))
+    try
     {
-      return false;
-    }
-    HiddenColumns that = (HiddenColumns) obj;
+      lock.readLock().lock();
 
-    /*
-     * check hidden columns are either both null, or match
-     */
-    if (this.hiddenColumns == null)
-    {
-      return (that.hiddenColumns == null);
-    }
-    if (that.hiddenColumns == null
-            || that.hiddenColumns.size() != this.hiddenColumns.size())
-    {
-      return false;
-    }
-    int i = 0;
-    for (int[] thisRange : hiddenColumns)
-    {
-      int[] thatRange = that.hiddenColumns.get(i++);
-      if (thisRange[0] != thatRange[0] || thisRange[1] != thatRange[1])
+      if (!(obj instanceof HiddenColumns))
+      {
+        return false;
+      }
+      HiddenColumns that = (HiddenColumns) obj;
+
+      /*
+       * check hidden columns are either both null, or match
+       */
+      if (this.hiddenColumns == null)
+      {
+        return (that.hiddenColumns == null);
+      }
+      if (that.hiddenColumns == null
+              || that.hiddenColumns.size() != this.hiddenColumns.size())
       {
         return false;
       }
+      int i = 0;
+      for (int[] thisRange : hiddenColumns)
+      {
+        int[] thatRange = that.hiddenColumns.get(i++);
+        if (thisRange[0] != thatRange[0] || thisRange[1] != thatRange[1])
+        {
+          return false;
+        }
+      }
+      return true;
+    } finally
+    {
+      lock.readLock().unlock();
     }
-    return true;
   }
 
   /**
@@ -96,19 +126,26 @@ public class HiddenColumns
    */
   public int adjustForHiddenColumns(int column)
   {
-    int result = column;
-    if (hiddenColumns != null)
+    try
     {
-      for (int i = 0; i < hiddenColumns.size(); i++)
+      lock.readLock().lock();
+      int result = column;
+      if (hiddenColumns != null)
       {
-        int[] region = hiddenColumns.elementAt(i);
-        if (result >= region[0])
+        for (int i = 0; i < hiddenColumns.size(); i++)
         {
-          result += region[1] - region[0] + 1;
+          int[] region = hiddenColumns.elementAt(i);
+          if (result >= region[0])
+          {
+            result += region[1] - region[0] + 1;
+          }
         }
       }
+      return result;
+    } finally
+    {
+      lock.readLock().unlock();
     }
-    return result;
   }
 
   /**
@@ -122,42 +159,52 @@ public class HiddenColumns
    */
   public int findColumnPosition(int hiddenColumn)
   {
-    int result = hiddenColumn;
-    if (hiddenColumns != null)
+    try
     {
-      int index = 0;
-      int[] region;
-      do
+      lock.readLock().lock();
+      int result = hiddenColumn;
+      if (hiddenColumns != null)
       {
-        region = hiddenColumns.elementAt(index++);
-        if (hiddenColumn > region[1])
+        int index = 0;
+        int[] region;
+        do
         {
-          result -= region[1] + 1 - region[0];
-        }
-      } while ((hiddenColumn > region[1]) && (index < hiddenColumns.size()));
+          region = hiddenColumns.elementAt(index++);
+          if (hiddenColumn > region[1])
+          {
+            result -= region[1] + 1 - region[0];
+          }
+        } while ((hiddenColumn > region[1])
+                && (index < hiddenColumns.size()));
 
-      if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
-      {
-        // Here the hidden column is within a region, so
-        // we want to return the position of region[0]-1, adjusted for any
-        // earlier hidden columns.
-        // Calculate the difference between the actual hidden col position
-        // and region[0]-1, and then subtract from result to convert result from
-        // the adjusted hiddenColumn value to the adjusted region[0]-1 value
-
-        // However, if the region begins at 0 we cannot return region[0]-1
-        // just return 0
-        if (region[0] == 0)
+        if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
         {
-          return 0;
-        }
-        else
-        {
-          return result - (hiddenColumn - region[0] + 1);
+          // Here the hidden column is within a region, so
+          // we want to return the position of region[0]-1, adjusted for any
+          // earlier hidden columns.
+          // Calculate the difference between the actual hidden col position
+          // and region[0]-1, and then subtract from result to convert result
+          // from
+          // the adjusted hiddenColumn value to the adjusted region[0]-1 value
+
+          // However, if the region begins at 0 we cannot return region[0]-1
+          // just return 0
+          if (region[0] == 0)
+          {
+            return 0;
+          }
+          else
+          {
+            return result - (hiddenColumn - region[0] + 1);
+          }
         }
       }
+      return result; // return the shifted position after removing hidden
+                     // columns.
+    } finally
+    {
+      lock.readLock().unlock();
     }
-    return result; // return the shifted position after removing hidden columns.
   }
 
   /**
@@ -173,6 +220,10 @@ public class HiddenColumns
    */
   public int subtractVisibleColumns(int visibleDistance, int startColumn)
   {
+    try
+    {
+
+      lock.readLock().lock();
     int distance = visibleDistance;
 
     // in case startColumn is in a hidden region, move it to the left
@@ -214,40 +265,54 @@ public class HiddenColumns
       return nextstart - distance;
     }
     return start - distance;
+    } finally
+    {
+      lock.readLock().unlock();
+    }
 
   }
 
   /**
-   * Use this method to determine where the next hiddenRegion starts
+   * Use this method to determine the set of hiddenRegion start positions
    * 
-   * @param hiddenRegion
-   *          index of hidden region (counts from 0)
-   * @return column number in visible view
+   * @return list of column number in visible view where hidden regions start
    */
-  public int findHiddenRegionPosition(int hiddenRegion)
+  public List<Integer> findHiddenRegionPositions()
   {
-    int result = 0;
-    if (hiddenColumns != null)
+    try
     {
-      int index = 0;
-      int gaps = 0;
-      do
+      lock.readLock().lock();
+      List<Integer> positions = new ArrayList<>(
+              hiddenColumns.size());
+
+      positions.add(hiddenColumns.elementAt(0)[0]);
+      for (int i = 1; i < hiddenColumns.size(); ++i)
       {
-        int[] region = hiddenColumns.elementAt(index);
-        if (hiddenRegion == 0)
+
+        int result = 0;
+        if (hiddenColumns != null)
         {
-          return region[0];
-        }
+          int index = 0;
+          int gaps = 0;
+          do
+          {
+            int[] region = hiddenColumns.elementAt(index);
+            gaps += region[1] + 1 - region[0];
+            result = region[1] + 1;
+            index++;
+          } while (index <= i);
 
-        gaps += region[1] + 1 - region[0];
-        result = region[1] + 1;
-        index++;
-      } while (index <= hiddenRegion);
+          result -= gaps;
+        }
+        positions.add(result);
+      }
 
-      result -= gaps;
+      return positions;
+    }
+    finally
+    {
+      lock.readLock().unlock();
     }
-
-    return result;
   }
 
   /**
@@ -259,22 +324,29 @@ public class HiddenColumns
    */
   public int getHiddenBoundaryRight(int alPos)
   {
-    if (hiddenColumns != null)
+    try
     {
-      int index = 0;
-      do
+      lock.readLock().lock();
+      if (hiddenColumns != null)
       {
-        int[] region = hiddenColumns.elementAt(index);
-        if (alPos < region[0])
+        int index = 0;
+        do
         {
-          return region[0];
-        }
+          int[] region = hiddenColumns.elementAt(index);
+          if (alPos < region[0])
+          {
+            return region[0];
+          }
 
-        index++;
-      } while (index < hiddenColumns.size());
-    }
+          index++;
+        } while (index < hiddenColumns.size());
+      }
 
-    return alPos;
+      return alPos;
+    } finally
+    {
+      lock.readLock().unlock();
+    }
 
   }
 
@@ -287,6 +359,10 @@ public class HiddenColumns
    */
   public int getHiddenBoundaryLeft(int alPos)
   {
+    try
+    {
+      lock.readLock().lock();
+
     if (hiddenColumns != null)
     {
       int index = hiddenColumns.size() - 1;
@@ -303,7 +379,10 @@ public class HiddenColumns
     }
 
     return alPos;
-
+    } finally
+    {
+      lock.readLock().unlock();
+    }
   }
 
   /**
@@ -316,6 +395,10 @@ public class HiddenColumns
    */
   private int getHiddenIndexLeft(int pos)
   {
+    try
+    {
+
+      lock.readLock().lock();
     if (hiddenColumns != null)
     {
       int index = hiddenColumns.size() - 1;
@@ -332,6 +415,10 @@ public class HiddenColumns
     }
 
     return -1;
+    } finally
+    {
+      lock.readLock().unlock();
+    }
 
   }
 
@@ -343,9 +430,28 @@ public class HiddenColumns
    */
   public void hideColumns(int start, int end)
   {
+    hideColumns(start, end, false);
+  }
+
+  /**
+   * Adds the specified column range to the hidden columns
+   * 
+   * @param start
+   * @param end
+   */
+  private void hideColumns(int start, int end, boolean alreadyLocked)
+  {
+    try
+    {
+
+      if (!alreadyLocked)
+      {
+        lock.writeLock().lock();
+      }
+
     if (hiddenColumns == null)
     {
-      hiddenColumns = new Vector<int[]>();
+      hiddenColumns = new Vector<>();
     }
 
     /*
@@ -409,10 +515,21 @@ public class HiddenColumns
      * remaining case is that the new range follows everything else
      */
     hiddenColumns.addElement(new int[] { start, end });
+    } finally
+    {
+      if (!alreadyLocked)
+      {
+        lock.writeLock().unlock();
+      }
+    }
   }
 
   public boolean isVisible(int column)
   {
+    try
+    {
+      lock.readLock().lock();
+
     if (hiddenColumns != null)
     {
       for (int[] region : hiddenColumns)
@@ -425,6 +542,10 @@ public class HiddenColumns
     }
 
     return true;
+    } finally
+    {
+      lock.readLock().unlock();
+    }
   }
 
   /**
@@ -441,24 +562,80 @@ public class HiddenColumns
    */
   public HiddenColumns(HiddenColumns copy)
   {
-    if (copy != null)
+    try
     {
-      if (copy.hiddenColumns != null)
+
+      lock.readLock().lock();
+      if (copy != null)
       {
-        hiddenColumns = new Vector<int[]>(copy.hiddenColumns.size());
-        for (int i = 0, j = copy.hiddenColumns.size(); i < j; i++)
+        if (copy.hiddenColumns != null)
         {
-          int[] rh, cp;
-          rh = copy.hiddenColumns.elementAt(i);
-          if (rh != null)
-          {
-            cp = new int[rh.length];
-            System.arraycopy(rh, 0, cp, 0, rh.length);
-            hiddenColumns.addElement(cp);
-          }
+          hiddenColumns = copy.copyHiddenRegions();
         }
       }
     }
+    finally
+    {
+      lock.readLock().unlock();
+    }
+  }
+
+  private Vector<int[]> copyHiddenRegions()
+  {
+    Vector<int[]> copy = new Vector<>(hiddenColumns.size());
+    for (int i = 0, j = hiddenColumns.size(); i < j; i++)
+    {
+      int[] rh, cp;
+      rh = hiddenColumns.elementAt(i);
+      if (rh != null)
+      {
+        cp = new int[rh.length];
+        System.arraycopy(rh, 0, cp, 0, rh.length);
+        copy.addElement(cp);
+      }
+    }
+    return copy;
+  }
+
+  private ArrayList<int[]> copyHiddenRegionsToArrayList()
+  {
+    ArrayList<int[]> copy = new ArrayList<>(hiddenColumns.size());
+    for (int i = 0, j = hiddenColumns.size(); i < j; i++)
+    {
+      int[] rh, cp;
+      rh = hiddenColumns.elementAt(i);
+      if (rh != null)
+      {
+        cp = new int[rh.length];
+        System.arraycopy(rh, 0, cp, 0, rh.length);
+        copy.add(cp);
+      }
+    }
+    return copy;
+  }
+
+  public void getHiddenColumnsCopy(Vector<int[]> copy)
+  {
+    try
+    {
+      lock.readLock().lock();
+      copy = copyHiddenRegions();
+    } finally
+    {
+      lock.readLock().unlock();
+    }
+  }
+
+  public void getHiddenColumnsCopy(ArrayList<int[]> copy)
+  {
+    try
+    {
+      lock.readLock().lock();
+      copy = copyHiddenRegionsToArrayList();
+    } finally
+    {
+      lock.readLock().unlock();
+    }
   }
 
   /**
@@ -472,42 +649,49 @@ public class HiddenColumns
   public List<int[]> compensateForEdit(int start, int change,
           ColumnSelection sel)
   {
-    List<int[]> deletedHiddenColumns = null;
-
-    if (hiddenColumns != null)
+    try
     {
-      deletedHiddenColumns = new ArrayList<int[]>();
-      int hSize = hiddenColumns.size();
-      for (int i = 0; i < hSize; i++)
+      lock.writeLock().lock();
+      List<int[]> deletedHiddenColumns = null;
+
+      if (hiddenColumns != null)
       {
-        int[] region = hiddenColumns.elementAt(i);
-        if (region[0] > start && start + change > region[1])
+        deletedHiddenColumns = new ArrayList<>();
+        int hSize = hiddenColumns.size();
+        for (int i = 0; i < hSize; i++)
         {
-          deletedHiddenColumns.add(region);
+          int[] region = hiddenColumns.elementAt(i);
+          if (region[0] > start && start + change > region[1])
+          {
+            deletedHiddenColumns.add(region);
 
-          hiddenColumns.removeElementAt(i);
-          i--;
-          hSize--;
-          continue;
-        }
+            hiddenColumns.removeElementAt(i);
+            i--;
+            hSize--;
+            continue;
+          }
 
-        if (region[0] > start)
-        {
-          region[0] -= change;
-          region[1] -= change;
-        }
+          if (region[0] > start)
+          {
+            region[0] -= change;
+            region[1] -= change;
+          }
+
+          if (region[0] < 0)
+          {
+            region[0] = 0;
+          }
 
-        if (region[0] < 0)
-        {
-          region[0] = 0;
         }
 
+        this.revealHiddenColumns(0, sel);
       }
 
-      this.revealHiddenColumns(0, sel);
+      return deletedHiddenColumns;
+    } finally
+    {
+      lock.writeLock().unlock();
     }
-
-    return deletedHiddenColumns;
   }
 
   /**
@@ -521,34 +705,42 @@ public class HiddenColumns
    */
   public void compensateForDelEdits(int start, int change)
   {
-    if (hiddenColumns != null)
+    try
     {
-      for (int i = 0; i < hiddenColumns.size(); i++)
+      lock.writeLock().lock();
+      if (hiddenColumns != null)
       {
-        int[] region = hiddenColumns.elementAt(i);
-        if (region[0] >= start)
-        {
-          region[0] -= change;
-        }
-        if (region[1] >= start)
+        for (int i = 0; i < hiddenColumns.size(); i++)
         {
-          region[1] -= change;
-        }
-        if (region[1] < region[0])
-        {
-          hiddenColumns.removeElementAt(i--);
-        }
+          int[] region = hiddenColumns.elementAt(i);
+          if (region[0] >= start)
+          {
+            region[0] -= change;
+          }
+          if (region[1] >= start)
+          {
+            region[1] -= change;
+          }
+          if (region[1] < region[0])
+          {
+            hiddenColumns.removeElementAt(i--);
+          }
 
-        if (region[0] < 0)
-        {
-          region[0] = 0;
-        }
-        if (region[1] < 0)
-        {
-          region[1] = 0;
+          if (region[0] < 0)
+          {
+            region[0] = 0;
+          }
+          if (region[1] < 0)
+          {
+            region[1] = 0;
+          }
         }
       }
     }
+    finally
+    {
+      lock.writeLock().unlock();
+    }
   }
 
   /**
@@ -563,111 +755,127 @@ public class HiddenColumns
    */
   public int[] getVisibleContigs(int start, int end)
   {
-    if (hiddenColumns != null && hiddenColumns.size() > 0)
+    try
     {
-      List<int[]> visiblecontigs = new ArrayList<int[]>();
-      List<int[]> regions = getHiddenRegions();
+      lock.readLock().lock();
+      if (hiddenColumns != null && hiddenColumns.size() > 0)
+      {
+        List<int[]> visiblecontigs = new ArrayList<>();
+        List<int[]> regions = getHiddenRegions();
 
-      int vstart = start;
-      int[] region;
-      int hideStart, hideEnd;
+        int vstart = start;
+        int[] region;
+        int hideStart, hideEnd;
 
-      for (int j = 0; vstart < end && j < regions.size(); j++)
-      {
-        region = regions.get(j);
-        hideStart = region[0];
-        hideEnd = region[1];
+        for (int j = 0; vstart < end && j < regions.size(); j++)
+        {
+          region = regions.get(j);
+          hideStart = region[0];
+          hideEnd = region[1];
+
+          if (hideEnd < vstart)
+          {
+            continue;
+          }
+          if (hideStart > vstart)
+          {
+            visiblecontigs.add(new int[] { vstart, hideStart - 1 });
+          }
+          vstart = hideEnd + 1;
+        }
 
-        if (hideEnd < vstart)
+        if (vstart < end)
         {
-          continue;
+          visiblecontigs.add(new int[] { vstart, end - 1 });
         }
-        if (hideStart > vstart)
+        int[] vcontigs = new int[visiblecontigs.size() * 2];
+        for (int i = 0, j = visiblecontigs.size(); i < j; i++)
         {
-          visiblecontigs.add(new int[] { vstart, hideStart - 1 });
+          int[] vc = visiblecontigs.get(i);
+          visiblecontigs.set(i, null);
+          vcontigs[i * 2] = vc[0];
+          vcontigs[i * 2 + 1] = vc[1];
         }
-        vstart = hideEnd + 1;
+        visiblecontigs.clear();
+        return vcontigs;
       }
-
-      if (vstart < end)
-      {
-        visiblecontigs.add(new int[] { vstart, end - 1 });
-      }
-      int[] vcontigs = new int[visiblecontigs.size() * 2];
-      for (int i = 0, j = visiblecontigs.size(); i < j; i++)
+      else
       {
-        int[] vc = visiblecontigs.get(i);
-        visiblecontigs.set(i, null);
-        vcontigs[i * 2] = vc[0];
-        vcontigs[i * 2 + 1] = vc[1];
+        return new int[] { start, end - 1 };
       }
-      visiblecontigs.clear();
-      return vcontigs;
     }
-    else
+    finally
     {
-      return new int[] { start, end - 1 };
+      lock.readLock().unlock();
     }
   }
 
   public String[] getVisibleSequenceStrings(int start, int end,
           SequenceI[] seqs)
   {
-    int i, iSize = seqs.length;
-    String selections[] = new String[iSize];
-    if (hiddenColumns != null && hiddenColumns.size() > 0)
+    try
     {
-      for (i = 0; i < iSize; i++)
+      lock.readLock().lock();
+      int i, iSize = seqs.length;
+      String selections[] = new String[iSize];
+      if (hiddenColumns != null && hiddenColumns.size() > 0)
       {
-        StringBuffer visibleSeq = new StringBuffer();
-        List<int[]> regions = getHiddenRegions();
-
-        int blockStart = start, blockEnd = end;
-        int[] region;
-        int hideStart, hideEnd;
-
-        for (int j = 0; j < regions.size(); j++)
+        for (i = 0; i < iSize; i++)
         {
-          region = regions.get(j);
-          hideStart = region[0];
-          hideEnd = region[1];
+          StringBuffer visibleSeq = new StringBuffer();
+          List<int[]> regions = getHiddenRegions();
 
-          if (hideStart < start)
+          int blockStart = start, blockEnd = end;
+          int[] region;
+          int hideStart, hideEnd;
+
+          for (int j = 0; j < regions.size(); j++)
           {
-            continue;
-          }
+            region = regions.get(j);
+            hideStart = region[0];
+            hideEnd = region[1];
 
-          blockStart = Math.min(blockStart, hideEnd + 1);
-          blockEnd = Math.min(blockEnd, hideStart);
+            if (hideStart < start)
+            {
+              continue;
+            }
 
-          if (blockStart > blockEnd)
-          {
-            break;
+            blockStart = Math.min(blockStart, hideEnd + 1);
+            blockEnd = Math.min(blockEnd, hideStart);
+
+            if (blockStart > blockEnd)
+            {
+              break;
+            }
+
+            visibleSeq.append(seqs[i].getSequence(blockStart, blockEnd));
+
+            blockStart = hideEnd + 1;
+            blockEnd = end;
           }
 
-          visibleSeq.append(seqs[i].getSequence(blockStart, blockEnd));
+          if (end > blockStart)
+          {
+            visibleSeq.append(seqs[i].getSequence(blockStart, end));
+          }
 
-          blockStart = hideEnd + 1;
-          blockEnd = end;
+          selections[i] = visibleSeq.toString();
         }
-
-        if (end > blockStart)
+      }
+      else
+      {
+        for (i = 0; i < iSize; i++)
         {
-          visibleSeq.append(seqs[i].getSequence(blockStart, end));
+          selections[i] = seqs[i].getSequenceAsString(start, end);
         }
-
-        selections[i] = visibleSeq.toString();
       }
+
+      return selections;
     }
-    else
+    finally
     {
-      for (i = 0; i < iSize; i++)
-      {
-        selections[i] = seqs[i].getSequenceAsString(start, end);
-      }
+      lock.readLock().unlock();
     }
-
-    return selections;
   }
 
   /**
@@ -682,70 +890,79 @@ public class HiddenColumns
    */
   public int[] locateVisibleBoundsOfSequence(SequenceI seq)
   {
-    int fpos = seq.getStart(), lpos = seq.getEnd();
-    int start = 0;
-
-    if (hiddenColumns == null || hiddenColumns.size() == 0)
+    try
     {
-      int ifpos = seq.findIndex(fpos) - 1, ilpos = seq.findIndex(lpos) - 1;
-      return new int[] { ifpos, ilpos, fpos, lpos, ifpos, ilpos };
-    }
+      lock.readLock().lock();
+      int fpos = seq.getStart(), lpos = seq.getEnd();
+      int start = 0;
 
-    // Simply walk along the sequence whilst watching for hidden column
-    // boundaries
-    List<int[]> regions = getHiddenRegions();
-    int spos = fpos, lastvispos = -1, rcount = 0, hideStart = seq
-            .getLength(), hideEnd = -1;
-    int visPrev = 0, visNext = 0, firstP = -1, lastP = -1;
-    boolean foundStart = false;
-    for (int p = 0, pLen = seq.getLength(); spos <= seq.getEnd()
-            && p < pLen; p++)
-    {
-      if (!Comparison.isGap(seq.getCharAt(p)))
+      if (hiddenColumns == null || hiddenColumns.size() == 0)
       {
-        // keep track of first/last column
-        // containing sequence data regardless of visibility
-        if (firstP == -1)
-        {
-          firstP = p;
-        }
-        lastP = p;
-        // update hidden region start/end
-        while (hideEnd < p && rcount < regions.size())
-        {
-          int[] region = regions.get(rcount++);
-          visPrev = visNext;
-          visNext += region[0] - visPrev;
-          hideStart = region[0];
-          hideEnd = region[1];
-        }
-        if (hideEnd < p)
-        {
-          hideStart = seq.getLength();
-        }
-        // update visible boundary for sequence
-        if (p < hideStart)
+        int ifpos = seq.findIndex(fpos) - 1,
+                ilpos = seq.findIndex(lpos) - 1;
+        return new int[] { ifpos, ilpos, fpos, lpos, ifpos, ilpos };
+      }
+
+      // Simply walk along the sequence whilst watching for hidden column
+      // boundaries
+      List<int[]> regions = getHiddenRegions();
+      int spos = fpos, lastvispos = -1, rcount = 0,
+              hideStart = seq.getLength(), hideEnd = -1;
+      int visPrev = 0, visNext = 0, firstP = -1, lastP = -1;
+      boolean foundStart = false;
+      for (int p = 0, pLen = seq.getLength(); spos <= seq.getEnd()
+              && p < pLen; p++)
+      {
+        if (!Comparison.isGap(seq.getCharAt(p)))
         {
-          if (!foundStart)
+          // keep track of first/last column
+          // containing sequence data regardless of visibility
+          if (firstP == -1)
+          {
+            firstP = p;
+          }
+          lastP = p;
+          // update hidden region start/end
+          while (hideEnd < p && rcount < regions.size())
           {
-            fpos = spos;
-            start = p;
-            foundStart = true;
+            int[] region = regions.get(rcount++);
+            visPrev = visNext;
+            visNext += region[0] - visPrev;
+            hideStart = region[0];
+            hideEnd = region[1];
           }
-          lastvispos = p;
-          lpos = spos;
+          if (hideEnd < p)
+          {
+            hideStart = seq.getLength();
+          }
+          // update visible boundary for sequence
+          if (p < hideStart)
+          {
+            if (!foundStart)
+            {
+              fpos = spos;
+              start = p;
+              foundStart = true;
+            }
+            lastvispos = p;
+            lpos = spos;
+          }
+          // look for next sequence position
+          spos++;
         }
-        // look for next sequence position
-        spos++;
       }
+      if (foundStart)
+      {
+        return new int[] { findColumnPosition(start),
+            findColumnPosition(lastvispos), fpos, lpos, firstP, lastP };
+      }
+      // otherwise, sequence was completely hidden
+      return new int[] { visPrev, visNext, 0, 0, firstP, lastP };
     }
-    if (foundStart)
+    finally
     {
-      return new int[] { findColumnPosition(start),
-          findColumnPosition(lastvispos), fpos, lpos, firstP, lastP };
+      lock.readLock().unlock();
     }
-    // otherwise, sequence was completely hidden
-    return new int[] { visPrev, visNext, 0, 0, firstP, lastP };
   }
 
   /**
@@ -773,88 +990,97 @@ public class HiddenColumns
   public void makeVisibleAnnotation(int start, int end,
           AlignmentAnnotation alignmentAnnotation)
   {
-    if (alignmentAnnotation.annotations == null)
-    {
-      return;
-    }
-    if (start == end && end == -1)
-    {
-      start = 0;
-      end = alignmentAnnotation.annotations.length;
-    }
-    if (hiddenColumns != null && hiddenColumns.size() > 0)
+    try
     {
-      // then mangle the alignmentAnnotation annotation array
-      Vector<Annotation[]> annels = new Vector<Annotation[]>();
-      Annotation[] els = null;
-      List<int[]> regions = getHiddenRegions();
-      int blockStart = start, blockEnd = end;
-      int[] region;
-      int hideStart, hideEnd, w = 0;
-
-      for (int j = 0; j < regions.size(); j++)
+      lock.readLock().lock();
+      if (alignmentAnnotation.annotations == null)
+      {
+        return;
+      }
+      if (start == end && end == -1)
+      {
+        start = 0;
+        end = alignmentAnnotation.annotations.length;
+      }
+      if (hiddenColumns != null && hiddenColumns.size() > 0)
       {
-        region = regions.get(j);
-        hideStart = region[0];
-        hideEnd = region[1];
+        // then mangle the alignmentAnnotation annotation array
+        Vector<Annotation[]> annels = new Vector<>();
+        Annotation[] els = null;
+        List<int[]> regions = getHiddenRegions();
+        int blockStart = start, blockEnd = end;
+        int[] region;
+        int hideStart, hideEnd, w = 0;
 
-        if (hideStart < start)
+        for (int j = 0; j < regions.size(); j++)
         {
-          continue;
-        }
+          region = regions.get(j);
+          hideStart = region[0];
+          hideEnd = region[1];
 
-        blockStart = Math.min(blockStart, hideEnd + 1);
-        blockEnd = Math.min(blockEnd, hideStart);
+          if (hideStart < start)
+          {
+            continue;
+          }
 
-        if (blockStart > blockEnd)
-        {
-          break;
-        }
+          blockStart = Math.min(blockStart, hideEnd + 1);
+          blockEnd = Math.min(blockEnd, hideStart);
 
-        annels.addElement(els = new Annotation[blockEnd - blockStart]);
-        System.arraycopy(alignmentAnnotation.annotations, blockStart, els,
-                0, els.length);
-        w += els.length;
-        blockStart = hideEnd + 1;
-        blockEnd = end;
-      }
+          if (blockStart > blockEnd)
+          {
+            break;
+          }
 
-      if (end > blockStart)
-      {
-        annels.addElement(els = new Annotation[end - blockStart + 1]);
-        if ((els.length + blockStart) <= alignmentAnnotation.annotations.length)
+          annels.addElement(els = new Annotation[blockEnd - blockStart]);
+          System.arraycopy(alignmentAnnotation.annotations, blockStart, els,
+                  0, els.length);
+          w += els.length;
+          blockStart = hideEnd + 1;
+          blockEnd = end;
+        }
+
+        if (end > blockStart)
         {
-          // copy just the visible segment of the annotation row
-          System.arraycopy(alignmentAnnotation.annotations, blockStart,
-                  els, 0, els.length);
+          annels.addElement(els = new Annotation[end - blockStart + 1]);
+          if ((els.length
+                  + blockStart) <= alignmentAnnotation.annotations.length)
+          {
+            // copy just the visible segment of the annotation row
+            System.arraycopy(alignmentAnnotation.annotations, blockStart,
+                    els, 0, els.length);
+          }
+          else
+          {
+            // copy to the end of the annotation row
+            System.arraycopy(alignmentAnnotation.annotations, blockStart,
+                    els, 0,
+                    (alignmentAnnotation.annotations.length - blockStart));
+          }
+          w += els.length;
         }
-        else
+        if (w == 0)
         {
-          // copy to the end of the annotation row
-          System.arraycopy(alignmentAnnotation.annotations, blockStart,
-                  els, 0,
-                  (alignmentAnnotation.annotations.length - blockStart));
+          return;
         }
-        w += els.length;
-      }
-      if (w == 0)
-      {
-        return;
-      }
 
-      alignmentAnnotation.annotations = new Annotation[w];
-      w = 0;
+        alignmentAnnotation.annotations = new Annotation[w];
+        w = 0;
 
-      for (Annotation[] chnk : annels)
+        for (Annotation[] chnk : annels)
+        {
+          System.arraycopy(chnk, 0, alignmentAnnotation.annotations, w,
+                  chnk.length);
+          w += chnk.length;
+        }
+      }
+      else
       {
-        System.arraycopy(chnk, 0, alignmentAnnotation.annotations, w,
-                chnk.length);
-        w += chnk.length;
+        alignmentAnnotation.restrict(start, end);
       }
     }
-    else
+    finally
     {
-      alignmentAnnotation.restrict(start, end);
+      lock.readLock().unlock();
     }
   }
 
@@ -864,7 +1090,14 @@ public class HiddenColumns
    */
   public boolean hasHiddenColumns()
   {
-    return hiddenColumns != null && hiddenColumns.size() > 0;
+    try
+    {
+      lock.readLock().lock();
+      return hiddenColumns != null && hiddenColumns.size() > 0;
+    } finally
+    {
+      lock.readLock().unlock();
+    }
   }
 
   /**
@@ -873,7 +1106,14 @@ public class HiddenColumns
    */
   public boolean hasManyHiddenColumns()
   {
-    return hiddenColumns != null && hiddenColumns.size() > 1;
+    try
+    {
+      lock.readLock().lock();
+      return hiddenColumns != null && hiddenColumns.size() > 1;
+    } finally
+    {
+      lock.readLock().unlock();
+    }
   }
 
   /**
@@ -884,10 +1124,17 @@ public class HiddenColumns
    */
   public void hideInsertionsFor(SequenceI sr)
   {
-    List<int[]> inserts = sr.getInsertions();
-    for (int[] r : inserts)
+    try
+    {
+      lock.writeLock().lock();
+      List<int[]> inserts = sr.getInsertions();
+      for (int[] r : inserts)
+      {
+        hideColumns(r[0], r[1], true);
+      }
+    } finally
     {
-      hideColumns(r[0], r[1]);
+      lock.writeLock().unlock();
     }
   }
 
@@ -896,19 +1143,27 @@ public class HiddenColumns
    */
   public void revealAllHiddenColumns(ColumnSelection sel)
   {
-    if (hiddenColumns != null)
+    try
     {
-      for (int i = 0; i < hiddenColumns.size(); i++)
+      lock.writeLock().lock();
+      if (hiddenColumns != null)
       {
-        int[] region = hiddenColumns.elementAt(i);
-        for (int j = region[0]; j < region[1] + 1; j++)
+        for (int i = 0; i < hiddenColumns.size(); i++)
         {
-          sel.addElement(j);
+          int[] region = hiddenColumns.elementAt(i);
+          for (int j = region[0]; j < region[1] + 1; j++)
+          {
+            sel.addElement(j);
+          }
         }
       }
-    }
 
-    hiddenColumns = null;
+      hiddenColumns = null;
+    }
+    finally
+    {
+      lock.writeLock().unlock();
+    }
   }
 
   /**
@@ -919,23 +1174,31 @@ public class HiddenColumns
    */
   public void revealHiddenColumns(int start, ColumnSelection sel)
   {
-    for (int i = 0; i < hiddenColumns.size(); i++)
+    try
     {
-      int[] region = hiddenColumns.elementAt(i);
-      if (start == region[0])
+      lock.writeLock().lock();
+      for (int i = 0; i < hiddenColumns.size(); i++)
       {
-        for (int j = region[0]; j < region[1] + 1; j++)
+        int[] region = hiddenColumns.elementAt(i);
+        if (start == region[0])
         {
-          sel.addElement(j);
-        }
+          for (int j = region[0]; j < region[1] + 1; j++)
+          {
+            sel.addElement(j);
+          }
 
-        hiddenColumns.removeElement(region);
-        break;
+          hiddenColumns.removeElement(region);
+          break;
+        }
+      }
+      if (hiddenColumns.size() == 0)
+      {
+        hiddenColumns = null;
       }
     }
-    if (hiddenColumns.size() == 0)
+    finally
     {
-      hiddenColumns = null;
+      lock.writeLock().unlock();
     }
   }
 
@@ -1042,32 +1305,298 @@ public class HiddenColumns
    */
   public void pruneDeletions(List<int[]> shifts)
   {
-    // delete any intervals intersecting.
-    if (hiddenColumns != null)
+    try
     {
-      pruneIntervalVector(shifts, hiddenColumns);
-      if (hiddenColumns != null && hiddenColumns.size() == 0)
+      lock.writeLock().lock();
+      // delete any intervals intersecting.
+      if (hiddenColumns != null)
       {
-        hiddenColumns = null;
+        pruneIntervalVector(shifts, hiddenColumns);
+        if (hiddenColumns != null && hiddenColumns.size() == 0)
+        {
+          hiddenColumns = null;
+        }
       }
     }
+    finally
+    {
+      lock.writeLock().unlock();
+    }
   }
 
   /**
-   * Returns a hashCode built from selected columns and hidden column ranges
+   * Add gaps into the sequences aligned to profileseq under the given
+   * AlignmentView
+   * 
+   * @param profileseq
+   * @param al
+   *          - alignment to have gaps inserted into it
+   * @param input
+   *          - alignment view where sequence corresponding to profileseq is
+   *          first entry
+   * @return new HiddenColumns for new alignment view, with insertions into
+   *         profileseq marked as hidden.
    */
-  public int hashCode(int hc)
+  public static HiddenColumns propagateInsertions(SequenceI profileseq,
+          AlignmentI al, AlignmentView input)
   {
-    int hashCode = hc;
-    if (hiddenColumns != null)
+    int profsqpos = 0;
+
+    char gc = al.getGapCharacter();
+    Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
+    HiddenColumns nview = (HiddenColumns) alandhidden[1];
+    SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
+    nview.propagateInsertions(profileseq, al, origseq);
+    return nview;
+  }
+
+  /**
+   * 
+   * @param profileseq
+   *          - sequence in al which corresponds to origseq
+   * @param al
+   *          - alignment which is to have gaps inserted into it
+   * @param origseq
+   *          - sequence corresponding to profileseq which defines gap map for
+   *          modifying al
+   */
+  private void propagateInsertions(SequenceI profileseq, AlignmentI al,
+          SequenceI origseq)
+  {
+    char gc = al.getGapCharacter();
+    // recover mapping between sequence's non-gap positions and positions
+    // mapping to view.
+    pruneDeletions(ShiftList.parseMap(origseq.gapMap()));
+    int[] viscontigs = al.getHiddenColumns().getVisibleContigs(0,
+            profileseq.getLength());
+    int spos = 0;
+    int offset = 0;
+
+    // add profile to visible contigs
+    for (int v = 0; v < viscontigs.length; v += 2)
+    {
+      if (viscontigs[v] > spos)
+      {
+        StringBuffer sb = new StringBuffer();
+        for (int s = 0, ns = viscontigs[v] - spos; s < ns; s++)
+        {
+          sb.append(gc);
+        }
+        for (int s = 0, ns = al.getHeight(); s < ns; s++)
+        {
+          SequenceI sqobj = al.getSequenceAt(s);
+          if (sqobj != profileseq)
+          {
+            String sq = al.getSequenceAt(s).getSequenceAsString();
+            if (sq.length() <= spos + offset)
+            {
+              // pad sequence
+              int diff = spos + offset - sq.length() - 1;
+              if (diff > 0)
+              {
+                // pad gaps
+                sq = sq + sb;
+                while ((diff = spos + offset - sq.length() - 1) > 0)
+                {
+                  // sq = sq
+                  // + ((diff >= sb.length()) ? sb.toString() : sb
+                  // .substring(0, diff));
+                  if (diff >= sb.length())
+                  {
+                    sq += sb.toString();
+                  }
+                  else
+                  {
+                    char[] buf = new char[diff];
+                    sb.getChars(0, diff, buf, 0);
+                    sq += buf.toString();
+                  }
+                }
+              }
+              sq += sb.toString();
+            }
+            else
+            {
+              al.getSequenceAt(s).setSequence(
+                      sq.substring(0, spos + offset) + sb.toString()
+                              + sq.substring(spos + offset));
+            }
+          }
+        }
+        // offset+=sb.length();
+      }
+      spos = viscontigs[v + 1] + 1;
+    }
+    if ((offset + spos) < profileseq.getLength())
+    {
+      // pad the final region with gaps.
+      StringBuffer sb = new StringBuffer();
+      for (int s = 0, ns = profileseq.getLength() - spos - offset; s < ns; s++)
+      {
+        sb.append(gc);
+      }
+      for (int s = 0, ns = al.getHeight(); s < ns; s++)
+      {
+        SequenceI sqobj = al.getSequenceAt(s);
+        if (sqobj == profileseq)
+        {
+          continue;
+        }
+        String sq = sqobj.getSequenceAsString();
+        // pad sequence
+        int diff = origseq.getLength() - sq.length();
+        while (diff > 0)
+        {
+          // sq = sq
+          // + ((diff >= sb.length()) ? sb.toString() : sb
+          // .substring(0, diff));
+          if (diff >= sb.length())
+          {
+            sq += sb.toString();
+          }
+          else
+          {
+            char[] buf = new char[diff];
+            sb.getChars(0, diff, buf, 0);
+            sq += buf.toString();
+          }
+          diff = origseq.getLength() - sq.length();
+        }
+      }
+    }
+  }
+
+  /**
+   * remove any hiddenColumns or selected columns and shift remaining based on a
+   * series of position, range deletions.
+   * 
+   * @param deletions
+   */
+  private void pruneDeletions(ShiftList deletions)
+  {
+    if (deletions != null)
+    {
+      final List<int[]> shifts = deletions.getShifts();
+      if (shifts != null && shifts.size() > 0)
+      {
+        pruneDeletions(shifts);
+
+        // and shift the rest.
+        this.compensateForEdits(deletions);
+      }
+    }
+  }
+
+  /**
+   * Adjust hidden column boundaries based on a series of column additions or
+   * deletions in visible regions.
+   * 
+   * @param shiftrecord
+   * @return
+   */
+  private ShiftList compensateForEdits(ShiftList shiftrecord)
+  {
+    if (shiftrecord != null)
     {
-      for (int[] hidden : hiddenColumns)
+      final List<int[]> shifts = shiftrecord.getShifts();
+      if (shifts != null && shifts.size() > 0)
       {
-        hashCode = 31 * hashCode + hidden[0];
-        hashCode = 31 * hashCode + hidden[1];
+        int shifted = 0;
+        for (int i = 0, j = shifts.size(); i < j; i++)
+        {
+          int[] sh = shifts.get(i);
+          compensateForDelEdits(shifted + sh[0], sh[1]);
+          shifted -= sh[1];
+        }
       }
+      return shiftrecord.getInverse();
+    }
+    return null;
+  }
+
+  /**
+   * Returns a hashCode built from hidden column ranges
+   */
+  @Override
+  public int hashCode()
+  {
+    try
+    {
+      lock.readLock().lock();
+      int hashCode = 1;
+      if (hiddenColumns != null)
+      {
+        for (int[] hidden : hiddenColumns)
+        {
+          hashCode = 31 * hashCode + hidden[0];
+          hashCode = 31 * hashCode + hidden[1];
+        }
+      }
+      return hashCode;
+    }
+    finally
+    {
+      lock.readLock().unlock();
+    }
+  }
+
+  /**
+   * Hide columns corresponding to the marked bits
+   * 
+   * @param inserts
+   *          - columns map to bits starting from zero
+   */
+  public void hideMarkedBits(BitSet inserts)
+  {
+    try
+    {
+      lock.writeLock().lock();
+      for (int firstSet = inserts
+              .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
+                      .nextSetBit(lastSet))
+      {
+        lastSet = inserts.nextClearBit(firstSet);
+        hideColumns(firstSet, lastSet - 1, true);
+      }
+    } finally
+    {
+      lock.writeLock().unlock();
+    }
+  }
+
+  /**
+   * 
+   * @param inserts
+   *          BitSet where hidden columns will be marked
+   */
+  public void markHiddenRegions(BitSet inserts)
+  {
+    try
+    {
+      lock.readLock().lock();
+      if (hiddenColumns == null)
+      {
+        return;
+      }
+      for (int[] range : hiddenColumns)
+      {
+        inserts.set(range[0], range[1] + 1);
+      }
+    }
+    finally
+    {
+      lock.readLock().unlock();
+    }
+  }
+
+  @Override
+  public Iterator<int[]> iterator()
+  {
+    if (hiddenColumns == null)
+    {
+      return Collections.<int[]> emptyList().iterator();
     }
-    return hashCode;
+    return hiddenColumns.iterator();
   }
 
 }