JAL-2759 Rationalising hidden cols cursor, and sorting out coverage
[jalview.git] / src / jalview / datamodel / HiddenColumns.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.datamodel;
22
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.BitSet;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.concurrent.locks.ReentrantReadWriteLock;
29
30 /**
31  * This class manages the collection of hidden columns associated with an
32  * alignment. To iterate over the collection, or over visible columns/regions,
33  * use an iterator obtained from one of:
34  * 
35  * - getBoundedIterator: iterates over the hidden regions, within some bounds,
36  * returning *absolute* positions
37  * 
38  * - getBoundedStartIterator: iterates over the start positions of hidden
39  * regions, within some bounds, returning *visible* positions
40  * 
41  * - getVisContigsIterator: iterates over visible regions in a range, returning
42  * *absolute* positions
43  * 
44  * - getVisibleColsIterator: iterates over the visible *columns*
45  * 
46  * For performance reasons, provide bounds where possible. Note that column
47  * numbering begins at 0 throughout this class.
48  * 
49  * @author kmourao
50  */
51
52 /* Implementation notes:
53  * 
54  * Methods which change the hiddenColumns collection should use a writeLock to
55  * prevent other threads accessing the hiddenColumns collection while changes
56  * are being made. They should also reset the hidden columns cursor, and either
57  * update the hidden columns count, or set it to 0 (so that it will later be
58  * updated when needed).
59  * 
60  * 
61  * Methods which only need read access to the hidden columns collection should
62  * use a readLock to prevent other threads changing the hidden columns
63  * collection while it is in use.
64  */
65 public class HiddenColumns
66 {
67   private static final int HASH_MULTIPLIER = 31;
68
69   private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
70
71   /*
72    * Cursor which tracks the last used hidden columns region, and the number 
73    * of hidden columns up to (but not including) that region.
74    */
75   private HiddenColumnsCursor cursor = new HiddenColumnsCursor();
76
77   /*
78    * cache of the number of hidden columns: must be kept up to date by methods 
79    * which add or remove hidden columns
80    */
81   private int numColumns = 0;
82
83   /*
84    * list of hidden column [start, end] ranges; the list is maintained in
85    * ascending start column order
86    */
87   private List<int[]> hiddenColumns = new ArrayList<>();
88
89   /**
90    * Constructor
91    */
92   public HiddenColumns()
93   {
94   }
95
96   /**
97    * Copy constructor
98    * 
99    * @param copy
100    *          the HiddenColumns object to copy from
101    */
102   public HiddenColumns(HiddenColumns copy)
103   {
104     this(copy, Integer.MIN_VALUE, Integer.MAX_VALUE, 0);
105   }
106
107   /**
108    * Copy constructor within bounds and with offset. Copies hidden column
109    * regions fully contained between start and end, and offsets positions by
110    * subtracting offset.
111    * 
112    * @param copy
113    *          HiddenColumns instance to copy from
114    * @param start
115    *          lower bound to copy from
116    * @param end
117    *          upper bound to copy to
118    * @param offset
119    *          offset to subtract from each region boundary position
120    * 
121    */
122   public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
123   {
124     try
125     {
126       LOCK.writeLock().lock();
127       if (copy != null)
128       {
129         numColumns = 0;
130         Iterator<int[]> it = copy.getBoundedIterator(start, end);
131         while (it.hasNext())
132         {
133           int[] region = it.next();
134           // still need to check boundaries because iterator returns
135           // all overlapping regions and we need contained regions
136           if (region[0] >= start && region[1] <= end)
137           {
138             hiddenColumns.add(
139                     new int[]
140             { region[0] - offset, region[1] - offset });
141             numColumns += region[1] - region[0] + 1;
142           }
143         }
144         cursor = new HiddenColumnsCursor(hiddenColumns);
145       }
146     } finally
147     {
148       LOCK.writeLock().unlock();
149     }
150   }
151
152   /**
153    * Adds the specified column range to the hidden columns collection
154    * 
155    * @param start
156    *          start of range to add (absolute position in alignment)
157    * @param end
158    *          end of range to add (absolute position in alignment)
159    */
160   public void hideColumns(int start, int end)
161   {
162     try
163     {
164       LOCK.writeLock().lock();
165
166       int previndex = 0;
167       int prevHiddenCount = 0;
168       int regionindex = 0;
169       if (!hiddenColumns.isEmpty())
170       {
171         // set up cursor reset values
172         HiddenCursorPosition cursorPos = cursor.findRegionForColumn(start, false);
173         regionindex = cursorPos.getRegionIndex();
174
175         if (regionindex > 0)
176         {
177           // get previous index and hidden count for updating the cursor later
178           previndex = regionindex - 1;
179           int[] prevRegion = hiddenColumns.get(previndex);
180           prevHiddenCount = cursorPos.getHiddenSoFar()
181                   - (prevRegion[1] - prevRegion[0] + 1);
182         }
183       }
184
185       // new range follows everything else; check first to avoid looping over
186       // whole hiddenColumns collection
187       if (hiddenColumns.isEmpty()
188               || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
189       {
190         hiddenColumns.add(new int[] { start, end });
191         numColumns += end - start + 1;
192       }
193       else
194       {
195         /*
196          * traverse existing hidden ranges and insert / amend / append as
197          * appropriate
198          */
199         boolean added = false;
200         if (regionindex > 0)
201         {
202           added = insertRangeAtRegion(regionindex - 1, start, end);
203         }
204         if (!added && regionindex < hiddenColumns.size())
205         {
206           insertRangeAtRegion(regionindex, start, end);
207         }
208       }
209
210       // reset the cursor to just before our insertion point: this saves
211       // a lot of reprocessing in large alignments
212       cursor = new HiddenColumnsCursor(hiddenColumns, previndex,
213               prevHiddenCount);
214     } finally
215     {
216       LOCK.writeLock().unlock();
217     }
218   }
219
220   /**
221    * Insert [start, range] at the region at index i in hiddenColumns, if
222    * feasible
223    * 
224    * @param i
225    *          index to insert at
226    * @param start
227    *          start of range to insert
228    * @param end
229    *          end of range to insert
230    * @return true if range was successfully inserted
231    */
232   private boolean insertRangeAtRegion(int i, int start, int end)
233   {
234     boolean added = false;
235
236     int[] region = hiddenColumns.get(i);
237     if (end < region[0] - 1)
238     {
239       /*
240        * insert discontiguous preceding range
241        */
242       hiddenColumns.add(i, new int[] { start, end });
243       numColumns += end - start + 1;
244       added = true;
245     }
246     else if (end <= region[1])
247     {
248       /*
249        * new range overlaps existing, or is contiguous preceding it - adjust
250        * start column
251        */
252       int oldstart = region[0];
253       region[0] = Math.min(region[0], start);
254       numColumns += oldstart - region[0]; // new columns are between old and
255                                               // adjusted starts
256       added = true;
257     }
258     else if (start <= region[1] + 1)
259     {
260       /*
261        * new range overlaps existing, or is contiguous following it - adjust
262        * start and end columns
263        */
264       insertRangeAtOverlap(i, start, end, region);
265       added = true;
266     }
267     return added;
268   }
269
270   /**
271    * Insert a range whose start position overlaps an existing region and/or is
272    * contiguous to the right of the region
273    * 
274    * @param i
275    *          index to insert at
276    * @param start
277    *          start of range to insert
278    * @param end
279    *          end of range to insert
280    * @param region
281    *          the overlapped/continued region
282    */
283   private void insertRangeAtOverlap(int i, int start, int end, int[] region)
284   {
285     int oldstart = region[0];
286     int oldend = region[1];
287     region[0] = Math.min(region[0], start);
288     region[1] = Math.max(region[1], end);
289
290     numColumns += oldstart - region[0];
291
292     /*
293      * also update or remove any subsequent ranges 
294      * that are overlapped
295      */
296     int endi = i;
297     while (endi < hiddenColumns.size() - 1)
298     {
299       int[] nextRegion = hiddenColumns.get(endi + 1);
300       if (nextRegion[0] > end + 1)
301       {
302         /*
303          * gap to next hidden range - no more to update
304          */
305         break;
306       }
307       numColumns -= nextRegion[1] - nextRegion[0] + 1;
308       region[1] = Math.max(nextRegion[1], end);
309       endi++;
310     }
311     numColumns += region[1] - oldend;
312     hiddenColumns.subList(i + 1, endi + 1).clear();
313   }
314
315   /**
316    * hide a list of ranges
317    * 
318    * @param ranges
319    */
320   public void hideList(List<int[]> ranges)
321   {
322     try
323     {
324       LOCK.writeLock().lock();
325       for (int[] r : ranges)
326       {
327         hideColumns(r[0], r[1]);
328       }
329       cursor = new HiddenColumnsCursor(hiddenColumns);
330
331     } finally
332     {
333       LOCK.writeLock().unlock();
334     }
335   }
336
337   /**
338    * Unhides, and adds to the selection list, all hidden columns
339    */
340   public void revealAllHiddenColumns(ColumnSelection sel)
341   {
342     try
343     {
344       LOCK.writeLock().lock();
345
346       for (int[] region : hiddenColumns)
347       {
348         for (int j = region[0]; j < region[1] + 1; j++)
349         {
350           sel.addElement(j);
351         }
352       }
353       hiddenColumns.clear();
354       cursor = new HiddenColumnsCursor(hiddenColumns);
355       numColumns = 0;
356
357     } finally
358     {
359       LOCK.writeLock().unlock();
360     }
361   }
362
363   /**
364    * Reveals, and marks as selected, the hidden column range with the given
365    * start column
366    * 
367    * @param start
368    *          the start column to look for
369    * @param sel
370    *          the column selection to add the hidden column range to
371    */
372   public void revealHiddenColumns(int start, ColumnSelection sel)
373   {
374     try
375     {
376       LOCK.writeLock().lock();
377
378       if (!hiddenColumns.isEmpty())
379       {
380         int regionIndex = cursor.findRegionForColumn(start, false)
381                 .getRegionIndex();
382
383         if (regionIndex != -1 && regionIndex != hiddenColumns.size())
384         {
385           // regionIndex is the region which either contains start
386           // or lies to the right of start
387           int[] region = hiddenColumns.get(regionIndex);
388           if (start == region[0])
389           {
390             for (int j = region[0]; j < region[1] + 1; j++)
391             {
392               sel.addElement(j);
393             }
394             int colsToRemove = region[1] - region[0] + 1;
395             hiddenColumns.remove(regionIndex);
396             numColumns -= colsToRemove;
397
398             cursor.updateForDeletedRegion(hiddenColumns, colsToRemove);
399           }
400         }
401       }
402     } finally
403     {
404       LOCK.writeLock().unlock();
405     }
406   }
407
408   /**
409    * Output regions data as a string. String is in the format:
410    * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
411    * 
412    * @param delimiter
413    *          string to delimit regions
414    * @param betweenstring
415    *          to put between start and end region values
416    * @return regions formatted according to delimiter and between strings
417    */
418   public String regionsToString(String delimiter, String between)
419   {
420     try
421     {
422       LOCK.readLock().lock();
423       StringBuilder regionBuilder = new StringBuilder();
424
425       boolean first = true;
426       for (int[] range : hiddenColumns)
427       {
428         if (!first)
429         {
430           regionBuilder.append(delimiter);
431         }
432         else
433         {
434           first = false;
435         }
436         regionBuilder.append(range[0]).append(between).append(range[1]);
437
438       }
439
440       return regionBuilder.toString();
441     } finally
442     {
443       LOCK.readLock().unlock();
444     }
445   }
446
447   /**
448    * Find the number of hidden columns
449    * 
450    * @return number of hidden columns
451    */
452   public int getSize()
453   {
454     return numColumns;
455   }
456
457   /**
458    * Get the number of distinct hidden regions
459    * 
460    * @return number of regions
461    */
462   public int getNumberOfRegions()
463   {
464     try
465     {
466       LOCK.readLock().lock();
467       return hiddenColumns.size();
468     } finally
469     {
470       LOCK.readLock().unlock();
471     }
472   }
473
474   @Override
475   public boolean equals(Object obj)
476   {
477     try
478     {
479       LOCK.readLock().lock();
480
481       if (!(obj instanceof HiddenColumns))
482       {
483         return false;
484       }
485       HiddenColumns that = (HiddenColumns) obj;
486
487       /*
488        * check hidden columns are either both null, or match
489        */
490
491       if (that.hiddenColumns.size() != this.hiddenColumns.size())
492       {
493         return false;
494       }
495
496       Iterator<int[]> it = this.iterator();
497       Iterator<int[]> thatit = that.iterator();
498       while (it.hasNext())
499       {
500         if (!(Arrays.equals(it.next(), thatit.next())))
501         {
502           return false;
503         }
504       }
505       return true;
506
507     } finally
508     {
509       LOCK.readLock().unlock();
510     }
511   }
512
513   /**
514    * Return absolute column index for a visible column index
515    * 
516    * @param column
517    *          int column index in alignment view (count from zero)
518    * @return alignment column index for column
519    */
520   public int visibleToAbsoluteColumn(int column)
521   {
522     try
523     {
524       LOCK.readLock().lock();
525       int result = column;
526
527       if (!hiddenColumns.isEmpty())
528       {
529         result += cursor.findRegionForColumn(column, true)
530                 .getHiddenSoFar();
531       }
532
533       return result;
534     } finally
535     {
536       LOCK.readLock().unlock();
537     }
538   }
539
540   /**
541    * Use this method to find out where a column will appear in the visible
542    * alignment when hidden columns exist. If the column is not visible, then the
543    * index of the next visible column on the left will be returned (or 0 if
544    * there is no visible column on the left)
545    * 
546    * @param hiddenColumn
547    *          the column index in the full alignment including hidden columns
548    * @return the position of the column in the visible alignment
549    */
550   public int absoluteToVisibleColumn(int hiddenColumn)
551   {
552     try
553     {
554       LOCK.readLock().lock();
555       int result = hiddenColumn;
556
557       if (!hiddenColumns.isEmpty())
558       {
559         HiddenCursorPosition cursorPos = cursor
560                 .findRegionForColumn(hiddenColumn, false);
561         int index = cursorPos.getRegionIndex();
562         int hiddenBeforeCol = cursorPos.getHiddenSoFar();
563     
564         // just subtract hidden cols count - this works fine if column is
565         // visible
566         result = hiddenColumn - hiddenBeforeCol;
567     
568         // now check in case column is hidden - it will be in the returned
569         // hidden region
570         if (index < hiddenColumns.size())
571         {
572           int[] region = hiddenColumns.get(index);
573           if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
574           {
575             // actually col is hidden, return region[0]-1
576             // unless region[0]==0 in which case return 0
577             if (region[0] == 0)
578             {
579               result = 0;
580             }
581             else
582             {
583               result = region[0] - 1 - hiddenBeforeCol;
584             }
585           }
586         }
587       }
588
589       return result; // return the shifted position after removing hidden
590                      // columns.
591     } finally
592     {
593       LOCK.readLock().unlock();
594     }
595   }
596
597   /**
598    * Find the visible column which is a given visible number of columns to the
599    * left (negative visibleDistance) or right (positive visibleDistance) of
600    * startColumn. If startColumn is not visible, we use the visible column at
601    * the left boundary of the hidden region containing startColumn.
602    * 
603    * @param visibleDistance
604    *          the number of visible columns to offset by (left offset = negative
605    *          value; right offset = positive value)
606    * @param startColumn
607    *          the position of the column to start from (absolute position)
608    * @return the position of the column which is <visibleDistance> away
609    *         (absolute position)
610    */
611   public int offsetByVisibleColumns(int visibleDistance, int startColumn)
612   {
613     try
614     {
615       LOCK.readLock().lock();
616       int start = absoluteToVisibleColumn(startColumn);
617       return visibleToAbsoluteColumn(start + visibleDistance);
618
619     } finally
620     {
621       LOCK.readLock().unlock();
622     }
623   }
624
625   /**
626    * This method returns the rightmost limit of a region of an alignment with
627    * hidden columns. In otherwords, the next hidden column.
628    * 
629    * @param alPos
630    *          the absolute (visible) alignmentPosition to find the next hidden
631    *          column for
632    * @return the index of the next hidden column, or alPos if there is no next
633    *         hidden column
634    */
635   public int getNextHiddenBoundary(boolean left, int alPos)
636   {
637     try
638     {
639       LOCK.readLock().lock();
640       if (!hiddenColumns.isEmpty())
641       {
642         int index = cursor.findRegionForColumn(alPos, false)
643                 .getRegionIndex();
644
645         if (left && index > 0)
646         {
647           int[] region = hiddenColumns.get(index - 1);
648           return region[1];
649         }
650         else if (!left && index < hiddenColumns.size())
651         {
652           int[] region = hiddenColumns.get(index);
653           if (alPos < region[0])
654           {
655             return region[0];
656           }
657           else if ((alPos <= region[1])
658                   && (index + 1 < hiddenColumns.size()))
659           {
660             // alPos is within a hidden region, return the next one
661             // if there is one
662             region = hiddenColumns.get(index + 1);
663             return region[0];
664           }
665         }
666       }
667       return alPos;
668     } finally
669     {
670       LOCK.readLock().unlock();
671     }
672   }
673
674   /**
675    * Answers if a column in the alignment is visible
676    * 
677    * @param column
678    *          absolute position of column in the alignment
679    * @return true if column is visible
680    */
681   public boolean isVisible(int column)
682   {
683     try
684     {
685       LOCK.readLock().lock();
686
687       int regionindex = cursor.findRegionForColumn(column, false)
688               .getRegionIndex();
689       if (regionindex > -1 && regionindex < hiddenColumns.size())
690       {
691         int[] region = hiddenColumns.get(regionindex);
692         // already know that column <= region[1] as cursor returns containing
693         // region or region to right
694         if (column >= region[0])
695         {
696           return false;
697         }
698       }
699       return true;
700
701     } finally
702     {
703       LOCK.readLock().unlock();
704     }
705   }
706
707   /**
708    * 
709    * @return true if there are columns hidden
710    */
711   public boolean hasHiddenColumns()
712   {
713     try
714     {
715       LOCK.readLock().lock();
716
717       // we don't use getSize()>0 here because it has to iterate over
718       // the full hiddenColumns collection and so will be much slower
719       return (!hiddenColumns.isEmpty());
720     } finally
721     {
722       LOCK.readLock().unlock();
723     }
724   }
725
726   /**
727    * 
728    * @return true if there is more than one hidden column region
729    */
730   public boolean hasMultiHiddenColumnRegions()
731   {
732     try
733     {
734       LOCK.readLock().lock();
735       return !hiddenColumns.isEmpty() && hiddenColumns.size() > 1;
736     } finally
737     {
738       LOCK.readLock().unlock();
739     }
740   }
741
742
743   /**
744    * Returns a hashCode built from hidden column ranges
745    */
746   @Override
747   public int hashCode()
748   {
749     try
750     {
751       LOCK.readLock().lock();
752       int hashCode = 1;
753
754       for (int[] hidden : hiddenColumns)
755       {
756         hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
757         hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
758       }
759       return hashCode;
760     } finally
761     {
762       LOCK.readLock().unlock();
763     }
764   }
765
766   /**
767    * Hide columns corresponding to the marked bits
768    * 
769    * @param inserts
770    *          - columns mapped to bits starting from zero
771    */
772   public void hideColumns(BitSet inserts)
773   {
774     try
775     {
776       LOCK.writeLock().lock();
777       for (int firstSet = inserts
778               .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
779                       .nextSetBit(lastSet))
780       {
781         lastSet = inserts.nextClearBit(firstSet);
782         hideColumns(firstSet, lastSet - 1);
783       }
784       cursor = new HiddenColumnsCursor(hiddenColumns);
785     } finally
786     {
787       LOCK.writeLock().unlock();
788     }
789   }
790
791   /**
792    * Hide columns corresponding to the marked bits, within the range
793    * [start,end]. Entries in tohide which are outside [start,end] are ignored.
794    * 
795    * @param tohide
796    *          columns mapped to bits starting from zero
797    * @param start
798    *          start of range to hide columns within
799    * @param end
800    *          end of range to hide columns within
801    */
802   public void hideColumns(BitSet tohide, int start, int end)
803   {
804     clearHiddenColumnsInRange(start, end);
805
806     // make sure only bits between start and end are set
807     if (!tohide.isEmpty())
808     {
809       tohide.clear(0, start);
810       tohide.clear(Math.min(end + 1, tohide.length() + 1),
811               tohide.length() + 1);
812     }
813
814     hideColumns(tohide);
815   }
816
817   /**
818    * Make all columns in the range [start,end] visible
819    * 
820    * @param start
821    *          start of range to show columns
822    * @param end
823    *          end of range to show columns
824    */
825   private void clearHiddenColumnsInRange(int start, int end)
826   {
827     try
828     {
829       LOCK.writeLock().lock();
830       
831       if (!hiddenColumns.isEmpty())
832       {
833         HiddenCursorPosition pos = cursor.findRegionForColumn(start, false);
834         int index = pos.getRegionIndex();
835
836         if (index != -1 && index != hiddenColumns.size())
837         {
838           // regionIndex is the region which either contains start
839           // or lies to the right of start
840           int[] region = hiddenColumns.get(index);
841           if (region[0] < start && region[1] >= start)
842           {
843             // region contains start, truncate so that it ends just before start
844             numColumns -= region[1] - start + 1;
845             region[1] = start - 1;
846             index++;
847           }
848
849           int endi = index;
850           while (endi < hiddenColumns.size())
851           {
852             region = hiddenColumns.get(endi);
853
854             if (region[1] > end)
855             {
856               if (region[0] <= end)
857               {
858                 // region contains end, truncate so it starts just after end
859                 numColumns -= end - region[0] + 1;
860                 region[0] = end + 1;
861               }
862               break;
863             }
864
865             numColumns -= region[1] - region[0] + 1;
866             endi++;
867           }
868           hiddenColumns.subList(index, endi).clear();
869
870         }
871
872         cursor = new HiddenColumnsCursor(hiddenColumns);
873       }
874     } finally
875     {
876       LOCK.writeLock().unlock();
877     }
878   }
879
880   /**
881    * 
882    * @param updates
883    *          BitSet where hidden columns will be marked
884    */
885   protected void andNot(BitSet updates)
886   {
887     try
888     {
889       LOCK.writeLock().lock();
890
891       BitSet hiddenBitSet = new BitSet();
892       for (int[] range : hiddenColumns)
893       {
894         hiddenBitSet.set(range[0], range[1] + 1);
895       }
896       hiddenBitSet.andNot(updates);
897       hiddenColumns.clear();
898       hideColumns(hiddenBitSet);
899     } finally
900     {
901       LOCK.writeLock().unlock();
902     }
903   }
904
905   /**
906    * Calculate the visible start and end index of an alignment.
907    * 
908    * @param width
909    *          full alignment width
910    * @return integer array where: int[0] = startIndex, and int[1] = endIndex
911    */
912   public int[] getVisibleStartAndEndIndex(int width)
913   {
914     try
915     {
916       LOCK.readLock().lock();
917
918       int firstVisible = 0;
919       int lastVisible = width - 1;
920
921       if (!hiddenColumns.isEmpty())
922       {
923         // first visible col with index 0, convert to absolute index
924         firstVisible = visibleToAbsoluteColumn(0);
925
926         // last visible column is either immediately to left of
927         // last hidden region, or is just the last column in the alignment
928         int[] lastregion = hiddenColumns.get(hiddenColumns.size() - 1);
929         if (lastregion[1] == width - 1)
930         {
931           // last region is at very end of alignment
932           // last visible column immediately precedes it
933           lastVisible = lastregion[0] - 1;
934         }
935       }
936       return new int[] { firstVisible, lastVisible };
937
938     } finally
939     {
940       LOCK.readLock().unlock();
941     }
942   }
943
944   /**
945    * Finds the hidden region (if any) which starts or ends at res
946    * 
947    * @param res
948    *          visible residue position, unadjusted for hidden columns
949    * @return region as [start,end] or null if no matching region is found. If
950    *         res is adjacent to two regions, returns the left region.
951    */
952   public int[] getRegionWithEdgeAtRes(int res)
953   {
954     try
955     {
956       LOCK.readLock().lock();
957       int adjres = visibleToAbsoluteColumn(res);
958
959       int[] reveal = null;
960
961       if (!hiddenColumns.isEmpty())
962       {
963         // look for a region ending just before adjres
964         int regionindex = cursor.findRegionForColumn(adjres - 1, false)
965                 .getRegionIndex();
966         if (regionindex < hiddenColumns.size()
967                 && hiddenColumns.get(regionindex)[1] == adjres - 1)
968         {
969           reveal = hiddenColumns.get(regionindex);
970         }
971         // check if the region ends just after adjres
972         else if (regionindex < hiddenColumns.size()
973                 && hiddenColumns.get(regionindex)[0] == adjres + 1)
974         {
975           reveal = hiddenColumns.get(regionindex);
976         }
977       }
978       return reveal;
979
980     } finally
981     {
982       LOCK.readLock().unlock();
983     }
984   }
985
986   /**
987    * Return an iterator over the hidden regions
988    */
989   public Iterator<int[]> iterator()
990   {
991     try
992     {
993       LOCK.readLock().lock();
994       return new HiddenColsIterator(hiddenColumns);
995     } finally
996     {
997       LOCK.readLock().unlock();
998     }
999   }
1000
1001   /**
1002    * Return a bounded iterator over the hidden regions
1003    * 
1004    * @param start
1005    *          position to start from (inclusive, absolute column position)
1006    * @param end
1007    *          position to end at (inclusive, absolute column position)
1008    * @return
1009    */
1010   public Iterator<int[]> getBoundedIterator(int start, int end)
1011   {
1012     try
1013     {
1014       LOCK.readLock().lock();
1015       return new HiddenColsIterator(start, end, hiddenColumns);
1016     } finally
1017     {
1018       LOCK.readLock().unlock();
1019     }
1020   }
1021
1022   /**
1023    * Return a bounded iterator over the *visible* start positions of hidden
1024    * regions
1025    * 
1026    * @param start
1027    *          position to start from (inclusive, visible column position)
1028    * @param end
1029    *          position to end at (inclusive, visible column position)
1030    */
1031   public Iterator<Integer> getBoundedStartIterator(int start, int end)
1032   {
1033     try
1034     {
1035       LOCK.readLock().lock();
1036
1037       // get absolute position of column in alignment
1038       int absoluteStart = visibleToAbsoluteColumn(start);
1039
1040       // Get cursor position and supply it to the iterator:
1041       // Since we want visible region start, we look for a cursor for the
1042       // (absoluteStart-1), then if absoluteStart is the start of a visible
1043       // region we'll get the cursor pointing to the region before, which is
1044       // what we want
1045       HiddenCursorPosition pos = cursor
1046               .findRegionForColumn(absoluteStart - 1, false);
1047
1048       return new BoundedStartRegionIterator(pos, start, end,
1049               hiddenColumns);
1050     } finally
1051     {
1052       LOCK.readLock().unlock();
1053     }
1054   }
1055
1056   /**
1057    * Return an iterator over visible *columns* (not regions) between the given
1058    * start and end boundaries
1059    * 
1060    * @param start
1061    *          first column (inclusive)
1062    * @param end
1063    *          last column (inclusive)
1064    */
1065   public Iterator<Integer> getVisibleColsIterator(int start, int end)
1066   {
1067     try
1068     {
1069       LOCK.readLock().lock();
1070       return new VisibleColsIterator(start, end, hiddenColumns);
1071     } finally
1072     {
1073       LOCK.readLock().unlock();
1074     }
1075   }
1076
1077   /**
1078    * return an iterator over visible segments between the given start and end
1079    * boundaries
1080    * 
1081    * @param start
1082    *          first column, inclusive from 0
1083    * @param end
1084    *          last column - not inclusive
1085    * @param useVisibleCoords
1086    *          if true, start and end are visible column positions, not absolute
1087    *          positions*
1088    */
1089   public VisibleContigsIterator getVisContigsIterator(int start,
1090           int end,
1091           boolean useVisibleCoords)
1092   {
1093     int adjstart = start;
1094     int adjend = end;
1095     if (useVisibleCoords)
1096     {
1097       adjstart = visibleToAbsoluteColumn(start);
1098       adjend = visibleToAbsoluteColumn(end);
1099     }
1100
1101     try
1102     {
1103       LOCK.readLock().lock();
1104       return new VisibleContigsIterator(adjstart, adjend, hiddenColumns);
1105     } finally
1106     {
1107       LOCK.readLock().unlock();
1108     }
1109   }
1110 }