JAL-2759 Converted getHiddenBoundaryLeft/Right to use cursor
[jalview.git] / src / jalview / datamodel / RegionsIterator.java
1 package jalview.datamodel;
2
3 import java.util.Iterator;
4 import java.util.List;
5
6 /**
7  * A local iterator which iterates over hidden column regions in a range.
8  * Intended for use ONLY within the HiddenColumns class, because it works
9  * directly with the hiddenColumns collection without locking (callers should
10  * lock hiddenColumns).
11  */
12 public class RegionsIterator implements Iterator<int[]>
13 {
14   // start position to iterate from
15   private int start;
16
17   // end position to iterate to
18   private int end;
19
20   // current index in hiddenColumns
21   private int currentPosition = 0;
22
23   // current column in hiddenColumns
24   private int[] nextRegion = null;
25
26   private int[] currentRegion = null;
27
28   private int removedIndex = -1;
29
30   private final List<int[]> hiddenColumns;
31
32   // Constructor with bounds
33   RegionsIterator(int lowerBound, int upperBound, List<int[]> hiddenCols,
34           HiddenColumnsCursor cursor)
35   {
36     start = lowerBound;
37     end = upperBound;
38     hiddenColumns = hiddenCols;
39
40     if (hiddenColumns != null)
41     {
42       currentPosition = cursor.findRegionForColumn(start);
43
44       if (currentPosition < hiddenColumns.size())
45       {
46         nextRegion = hiddenColumns.get(currentPosition);
47       }
48     }
49   }
50
51   @Override
52   public boolean hasNext()
53   {
54     return (hiddenColumns != null) && (nextRegion != null)
55             && (nextRegion[0] <= end);
56   }
57
58   @Override
59   public int[] next()
60   {
61     currentRegion = nextRegion;
62     currentPosition++;
63     if (currentPosition < hiddenColumns.size())
64     {
65       nextRegion = hiddenColumns.get(currentPosition);
66     }
67     else
68     {
69       nextRegion = null;
70     }
71     return currentRegion;
72   }
73
74   @Override
75   public void remove()
76   {
77     if ((currentRegion != null) && (removedIndex != currentPosition))
78     {
79       currentPosition--;
80       hiddenColumns.subList(currentPosition, currentPosition + 1).clear();
81       removedIndex = currentPosition;
82     }
83     else
84     {
85       // already removed element last returned by next()
86       // or next() has not yet been called
87       throw new IllegalStateException();
88     }
89   }
90
91 }