JAL-2429 Additional fix to ColumnSelection when hidden cols start at 0
[jalview.git] / src / jalview / datamodel / ColumnSelection.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 jalview.util.Comparison;
24 import jalview.util.ShiftList;
25 import jalview.viewmodel.annotationfilter.AnnotationFilterParameter;
26 import jalview.viewmodel.annotationfilter.AnnotationFilterParameter.SearchableAnnotationField;
27
28 import java.util.ArrayList;
29 import java.util.BitSet;
30 import java.util.Collections;
31 import java.util.List;
32 import java.util.Vector;
33
34 /**
35  * Data class holding the selected columns and hidden column ranges for a view.
36  * Ranges are base 1.
37  */
38 public class ColumnSelection
39 {
40   /**
41    * A class to hold an efficient representation of selected columns
42    */
43   private class IntList
44   {
45     /*
46      * list of selected columns (ordered by selection order, not column order)
47      */
48     private List<Integer> order;
49
50     /*
51      * an unmodifiable view of the selected columns list
52      */
53     private List<Integer> _uorder;
54
55     /**
56      * bitfield for column selection - allows quick lookup
57      */
58     private BitSet selected;
59
60     /**
61      * Constructor
62      */
63     IntList()
64     {
65       order = new ArrayList<Integer>();
66       _uorder = Collections.unmodifiableList(order);
67       selected = new BitSet();
68     }
69
70     /**
71      * Copy constructor
72      * 
73      * @param other
74      */
75     IntList(IntList other)
76     {
77       this();
78       if (other != null)
79       {
80         int j = other.size();
81         for (int i = 0; i < j; i++)
82         {
83           add(other.elementAt(i));
84         }
85       }
86     }
87
88     /**
89      * adds a new column i to the selection - only if i is not already selected
90      * 
91      * @param i
92      */
93     void add(int i)
94     {
95       if (!selected.get(i))
96       {
97         order.add(Integer.valueOf(i));
98         selected.set(i);
99       }
100     }
101
102     void clear()
103     {
104       order.clear();
105       selected.clear();
106     }
107
108     void remove(int col)
109     {
110
111       Integer colInt = new Integer(col);
112
113       if (selected.get(col))
114       {
115         // if this ever changes to List.remove(), ensure Integer not int
116         // argument
117         // as List.remove(int i) removes the i'th item which is wrong
118         order.remove(colInt);
119         selected.clear(col);
120       }
121     }
122
123     boolean contains(Integer colInt)
124     {
125       return selected.get(colInt);
126     }
127
128     boolean isEmpty()
129     {
130       return order.isEmpty();
131     }
132
133     /**
134      * Returns a read-only view of the selected columns list
135      * 
136      * @return
137      */
138     List<Integer> getList()
139     {
140       return _uorder;
141     }
142
143     int size()
144     {
145       return order.size();
146     }
147
148     /**
149      * gets the column that was selected first, second or i'th
150      * 
151      * @param i
152      * @return
153      */
154     int elementAt(int i)
155     {
156       return order.get(i);
157     }
158
159     protected boolean pruneColumnList(final List<int[]> shifts)
160     {
161       int s = 0, t = shifts.size();
162       int[] sr = shifts.get(s++);
163       boolean pruned = false;
164       int i = 0, j = order.size();
165       while (i < j && s <= t)
166       {
167         int c = order.get(i++).intValue();
168         if (sr[0] <= c)
169         {
170           if (sr[1] + sr[0] >= c)
171           { // sr[1] -ve means inseriton.
172             order.remove(--i);
173             selected.clear(c);
174             j--;
175           }
176           else
177           {
178             if (s < t)
179             {
180               sr = shifts.get(s);
181             }
182             s++;
183           }
184         }
185       }
186       return pruned;
187     }
188
189     /**
190      * shift every selected column at or above start by change
191      * 
192      * @param start
193      *          - leftmost column to be shifted
194      * @param change
195      *          - delta for shift
196      */
197     void compensateForEdits(int start, int change)
198     {
199       BitSet mask = new BitSet();
200       for (int i = 0; i < order.size(); i++)
201       {
202         int temp = order.get(i);
203
204         if (temp >= start)
205         {
206           // clear shifted bits and update List of selected columns
207           selected.clear(temp);
208           mask.set(temp - change);
209           order.set(i, new Integer(temp - change));
210         }
211       }
212       // lastly update the bitfield all at once
213       selected.or(mask);
214     }
215
216     boolean isSelected(int column)
217     {
218       return selected.get(column);
219     }
220
221     int getMaxColumn()
222     {
223       return selected.length() - 1;
224     }
225
226     int getMinColumn()
227     {
228       return selected.get(0) ? 0 : selected.nextSetBit(0);
229     }
230
231     /**
232      * @return a series of selection intervals along the range
233      */
234     List<int[]> getRanges()
235     {
236       List<int[]> rlist = new ArrayList<int[]>();
237       if (selected.isEmpty())
238       {
239         return rlist;
240       }
241       int next = selected.nextSetBit(0), clear = -1;
242       while (next != -1)
243       {
244         clear = selected.nextClearBit(next);
245         rlist.add(new int[] { next, clear - 1 });
246         next = selected.nextSetBit(clear);
247       }
248       return rlist;
249     }
250
251     @Override
252     public int hashCode()
253     {
254       // TODO Auto-generated method stub
255       return selected.hashCode();
256     }
257
258     @Override
259     public boolean equals(Object obj)
260     {
261       if (obj instanceof IntList)
262       {
263         return ((IntList) obj).selected.equals(selected);
264       }
265       return false;
266     }
267   }
268
269   IntList selection = new IntList();
270
271   /*
272    * list of hidden column [start, end] ranges; the list is maintained in
273    * ascending start column order
274    */
275   Vector<int[]> hiddenColumns;
276
277   /**
278    * Add a column to the selection
279    * 
280    * @param col
281    *          index of column
282    */
283   public void addElement(int col)
284   {
285     selection.add(col);
286   }
287
288   /**
289    * clears column selection
290    */
291   public void clear()
292   {
293     selection.clear();
294   }
295
296   /**
297    * Removes value 'col' from the selection (not the col'th item)
298    * 
299    * @param col
300    *          index of column to be removed
301    */
302   public void removeElement(int col)
303   {
304     selection.remove(col);
305   }
306
307   /**
308    * removes a range of columns from the selection
309    * 
310    * @param start
311    *          int - first column in range to be removed
312    * @param end
313    *          int - last col
314    */
315   public void removeElements(int start, int end)
316   {
317     Integer colInt;
318     for (int i = start; i < end; i++)
319     {
320       colInt = new Integer(i);
321       if (selection.contains(colInt))
322       {
323         selection.remove(colInt);
324       }
325     }
326   }
327
328   /**
329    * Returns a read-only view of the (possibly empty) list of selected columns
330    * <p>
331    * The list contains no duplicates but is not necessarily ordered. It also may
332    * include columns hidden from the current view. To modify (for example sort)
333    * the list, you should first make a copy.
334    * <p>
335    * The list is not thread-safe: iterating over it could result in
336    * ConcurrentModificationException if it is modified by another thread.
337    */
338   public List<Integer> getSelected()
339   {
340     return selection.getList();
341   }
342
343   /**
344    * @return list of int arrays containing start and end column position for
345    *         runs of selected columns ordered from right to left.
346    */
347   public List<int[]> getSelectedRanges()
348   {
349     return selection.getRanges();
350   }
351
352   /**
353    * 
354    * @param col
355    *          index to search for in column selection
356    * 
357    * @return true if col is selected
358    */
359   public boolean contains(int col)
360   {
361     return (col > -1) ? selection.isSelected(col) : false;
362   }
363
364   /**
365    * Answers true if no columns are selected, else false
366    */
367   public boolean isEmpty()
368   {
369     return selection == null || selection.isEmpty();
370   }
371
372   /**
373    * rightmost selected column
374    * 
375    * @return rightmost column in alignment that is selected
376    */
377   public int getMax()
378   {
379     if (selection.isEmpty())
380     {
381       return -1;
382     }
383     return selection.getMaxColumn();
384   }
385
386   /**
387    * Leftmost column in selection
388    * 
389    * @return column index of leftmost column in selection
390    */
391   public int getMin()
392   {
393     if (selection.isEmpty())
394     {
395       return 1000000000;
396     }
397     return selection.getMinColumn();
398   }
399
400   /**
401    * propagate shift in alignment columns to column selection
402    * 
403    * @param start
404    *          beginning of edit
405    * @param left
406    *          shift in edit (+ve for removal, or -ve for inserts)
407    */
408   public List<int[]> compensateForEdit(int start, int change)
409   {
410     List<int[]> deletedHiddenColumns = null;
411     selection.compensateForEdits(start, change);
412
413     if (hiddenColumns != null)
414     {
415       deletedHiddenColumns = new ArrayList<int[]>();
416       int hSize = hiddenColumns.size();
417       for (int i = 0; i < hSize; i++)
418       {
419         int[] region = hiddenColumns.elementAt(i);
420         if (region[0] > start && start + change > region[1])
421         {
422           deletedHiddenColumns.add(region);
423
424           hiddenColumns.removeElementAt(i);
425           i--;
426           hSize--;
427           continue;
428         }
429
430         if (region[0] > start)
431         {
432           region[0] -= change;
433           region[1] -= change;
434         }
435
436         if (region[0] < 0)
437         {
438           region[0] = 0;
439         }
440
441       }
442
443       this.revealHiddenColumns(0);
444     }
445
446     return deletedHiddenColumns;
447   }
448
449   /**
450    * propagate shift in alignment columns to column selection special version of
451    * compensateForEdit - allowing for edits within hidden regions
452    * 
453    * @param start
454    *          beginning of edit
455    * @param left
456    *          shift in edit (+ve for removal, or -ve for inserts)
457    */
458   private void compensateForDelEdits(int start, int change)
459   {
460
461     selection.compensateForEdits(start, change);
462
463     if (hiddenColumns != null)
464     {
465       for (int i = 0; i < hiddenColumns.size(); i++)
466       {
467         int[] region = hiddenColumns.elementAt(i);
468         if (region[0] >= start)
469         {
470           region[0] -= change;
471         }
472         if (region[1] >= start)
473         {
474           region[1] -= change;
475         }
476         if (region[1] < region[0])
477         {
478           hiddenColumns.removeElementAt(i--);
479         }
480
481         if (region[0] < 0)
482         {
483           region[0] = 0;
484         }
485         if (region[1] < 0)
486         {
487           region[1] = 0;
488         }
489       }
490     }
491   }
492
493   /**
494    * Adjust hidden column boundaries based on a series of column additions or
495    * deletions in visible regions.
496    * 
497    * @param shiftrecord
498    * @return
499    */
500   public ShiftList compensateForEdits(ShiftList shiftrecord)
501   {
502     if (shiftrecord != null)
503     {
504       final List<int[]> shifts = shiftrecord.getShifts();
505       if (shifts != null && shifts.size() > 0)
506       {
507         int shifted = 0;
508         for (int i = 0, j = shifts.size(); i < j; i++)
509         {
510           int[] sh = shifts.get(i);
511           // compensateForEdit(shifted+sh[0], sh[1]);
512           compensateForDelEdits(shifted + sh[0], sh[1]);
513           shifted -= sh[1];
514         }
515       }
516       return shiftrecord.getInverse();
517     }
518     return null;
519   }
520
521   /**
522    * removes intersection of position,length ranges in deletions from the
523    * start,end regions marked in intervals.
524    * 
525    * @param shifts
526    * @param intervals
527    * @return
528    */
529   private boolean pruneIntervalVector(final List<int[]> shifts,
530           Vector<int[]> intervals)
531   {
532     boolean pruned = false;
533     int i = 0, j = intervals.size() - 1, s = 0, t = shifts.size() - 1;
534     int hr[] = intervals.elementAt(i);
535     int sr[] = shifts.get(s);
536     while (i <= j && s <= t)
537     {
538       boolean trailinghn = hr[1] >= sr[0];
539       if (!trailinghn)
540       {
541         if (i < j)
542         {
543           hr = intervals.elementAt(++i);
544         }
545         else
546         {
547           i++;
548         }
549         continue;
550       }
551       int endshift = sr[0] + sr[1]; // deletion ranges - -ve means an insert
552       if (endshift < hr[0] || endshift < sr[0])
553       { // leadinghc disjoint or not a deletion
554         if (s < t)
555         {
556           sr = shifts.get(++s);
557         }
558         else
559         {
560           s++;
561         }
562         continue;
563       }
564       boolean leadinghn = hr[0] >= sr[0];
565       boolean leadinghc = hr[0] < endshift;
566       boolean trailinghc = hr[1] < endshift;
567       if (leadinghn)
568       {
569         if (trailinghc)
570         { // deleted hidden region.
571           intervals.removeElementAt(i);
572           pruned = true;
573           j--;
574           if (i <= j)
575           {
576             hr = intervals.elementAt(i);
577           }
578           continue;
579         }
580         if (leadinghc)
581         {
582           hr[0] = endshift; // clip c terminal region
583           leadinghn = !leadinghn;
584           pruned = true;
585         }
586       }
587       if (!leadinghn)
588       {
589         if (trailinghc)
590         {
591           if (trailinghn)
592           {
593             hr[1] = sr[0] - 1;
594             pruned = true;
595           }
596         }
597         else
598         {
599           // sr contained in hr
600           if (s < t)
601           {
602             sr = shifts.get(++s);
603           }
604           else
605           {
606             s++;
607           }
608           continue;
609         }
610       }
611     }
612     return pruned; // true if any interval was removed or modified by
613     // operations.
614   }
615
616   /**
617    * remove any hiddenColumns or selected columns and shift remaining based on a
618    * series of position, range deletions.
619    * 
620    * @param deletions
621    */
622   public void pruneDeletions(ShiftList deletions)
623   {
624     if (deletions != null)
625     {
626       final List<int[]> shifts = deletions.getShifts();
627       if (shifts != null && shifts.size() > 0)
628       {
629         // delete any intervals intersecting.
630         if (hiddenColumns != null)
631         {
632           pruneIntervalVector(shifts, hiddenColumns);
633           if (hiddenColumns != null && hiddenColumns.size() == 0)
634           {
635             hiddenColumns = null;
636           }
637         }
638         if (selection != null && selection.size() > 0)
639         {
640           selection.pruneColumnList(shifts);
641           if (selection != null && selection.size() == 0)
642           {
643             selection = null;
644           }
645         }
646         // and shift the rest.
647         this.compensateForEdits(deletions);
648       }
649     }
650   }
651
652   /**
653    * This Method is used to return all the HiddenColumn regions
654    * 
655    * @return empty list or List of hidden column intervals
656    */
657   public List<int[]> getHiddenColumns()
658   {
659     return hiddenColumns == null ? Collections.<int[]> emptyList()
660             : hiddenColumns;
661   }
662
663   /**
664    * Return absolute column index for a visible column index
665    * 
666    * @param column
667    *          int column index in alignment view (count from zero)
668    * @return alignment column index for column
669    */
670   public int adjustForHiddenColumns(int column)
671   {
672     int result = column;
673     if (hiddenColumns != null)
674     {
675       for (int i = 0; i < hiddenColumns.size(); i++)
676       {
677         int[] region = hiddenColumns.elementAt(i);
678         if (result >= region[0])
679         {
680           result += region[1] - region[0] + 1;
681         }
682       }
683     }
684     return result;
685   }
686
687   /**
688    * Use this method to find out where a column will appear in the visible
689    * alignment when hidden columns exist. If the column is not visible, then the
690    * left-most visible column will always be returned.
691    * 
692    * @param hiddenColumn
693    *          the column index in the full alignment including hidden columns
694    * @return the position of the column in the visible alignment
695    */
696   public int findColumnPosition(int hiddenColumn)
697   {
698     int result = hiddenColumn;
699     if (hiddenColumns != null)
700     {
701       int index = 0;
702       int[] region;
703       do
704       {
705         region = hiddenColumns.elementAt(index++);
706         if (hiddenColumn > region[1])
707         {
708           result -= region[1] + 1 - region[0];
709         }
710       } while ((hiddenColumn > region[1]) && (index < hiddenColumns.size()));
711
712       if (hiddenColumn >= region[0] && hiddenColumn <= region[1])
713        {
714          // Here the hidden column is within a region, so
715          // we want to return the position of region[0]-1, adjusted for any
716          // earlier hidden columns.
717          // Calculate the difference between the actual hidden col position
718          // and region[0]-1, and then subtract from result to convert result from
719          // the adjusted hiddenColumn value to the adjusted region[0]-1 value
720
721         // However, if the region begins at 0 we cannot return region[0]-1
722         // so return region[1] + 1 instead, adjusted for earlier hidden columns,
723         // by calculating the difference between region[1]+1 and the actual
724         // hidden
725         // column, and then adding to result to convert result from the adjusted
726         // hiddenColumn value to the adjusted region[1]+1 value
727         if (region[0] == 0)
728         {
729           return result + (region[1] + 1 - hiddenColumn);
730         }
731         else
732         {
733           return result - (hiddenColumn - region[0] + 1);
734         }
735       }
736     }
737     return result; // return the shifted position after removing hidden columns.
738   }
739
740   /**
741    * Use this method to determine where the next hiddenRegion starts
742    * 
743    * @param hiddenRegion
744    *          index of hidden region (counts from 0)
745    * @return column number in visible view
746    */
747   public int findHiddenRegionPosition(int hiddenRegion)
748   {
749     int result = 0;
750     if (hiddenColumns != null)
751     {
752       int index = 0;
753       int gaps = 0;
754       do
755       {
756         int[] region = hiddenColumns.elementAt(index);
757         if (hiddenRegion == 0)
758         {
759           return region[0];
760         }
761
762         gaps += region[1] + 1 - region[0];
763         result = region[1] + 1;
764         index++;
765       } while (index <= hiddenRegion);
766
767       result -= gaps;
768     }
769
770     return result;
771   }
772
773   /**
774    * THis method returns the rightmost limit of a region of an alignment with
775    * hidden columns. In otherwords, the next hidden column.
776    * 
777    * @param index
778    *          int
779    */
780   public int getHiddenBoundaryRight(int alPos)
781   {
782     if (hiddenColumns != null)
783     {
784       int index = 0;
785       do
786       {
787         int[] region = hiddenColumns.elementAt(index);
788         if (alPos < region[0])
789         {
790           return region[0];
791         }
792
793         index++;
794       } while (index < hiddenColumns.size());
795     }
796
797     return alPos;
798
799   }
800
801   /**
802    * This method returns the leftmost limit of a region of an alignment with
803    * hidden columns. In otherwords, the previous hidden column.
804    * 
805    * @param index
806    *          int
807    */
808   public int getHiddenBoundaryLeft(int alPos)
809   {
810     if (hiddenColumns != null)
811     {
812       int index = hiddenColumns.size() - 1;
813       do
814       {
815         int[] region = hiddenColumns.elementAt(index);
816         if (alPos > region[1])
817         {
818           return region[1];
819         }
820
821         index--;
822       } while (index > -1);
823     }
824
825     return alPos;
826
827   }
828
829   public void hideSelectedColumns()
830   {
831     synchronized (selection)
832     {
833       for (int[] selregions : selection.getRanges())
834       {
835         hideColumns(selregions[0], selregions[1]);
836       }
837       selection.clear();
838     }
839
840   }
841
842   /**
843    * Adds the specified column range to the hidden columns
844    * 
845    * @param start
846    * @param end
847    */
848   public void hideColumns(int start, int end)
849   {
850     if (hiddenColumns == null)
851     {
852       hiddenColumns = new Vector<int[]>();
853     }
854
855     /*
856      * traverse existing hidden ranges and insert / amend / append as
857      * appropriate
858      */
859     for (int i = 0; i < hiddenColumns.size(); i++)
860     {
861       int[] region = hiddenColumns.elementAt(i);
862
863       if (end < region[0] - 1)
864       {
865         /*
866          * insert discontiguous preceding range
867          */
868         hiddenColumns.insertElementAt(new int[] { start, end }, i);
869         return;
870       }
871
872       if (end <= region[1])
873       {
874         /*
875          * new range overlaps existing, or is contiguous preceding it - adjust
876          * start column
877          */
878         region[0] = Math.min(region[0], start);
879         return;
880       }
881
882       if (start <= region[1] + 1)
883       {
884         /*
885          * new range overlaps existing, or is contiguous following it - adjust
886          * start and end columns
887          */
888         region[0] = Math.min(region[0], start);
889         region[1] = Math.max(region[1], end);
890
891         /*
892          * also update or remove any subsequent ranges 
893          * that are overlapped
894          */
895         while (i < hiddenColumns.size() - 1)
896         {
897           int[] nextRegion = hiddenColumns.get(i + 1);
898           if (nextRegion[0] > end + 1)
899           {
900             /*
901              * gap to next hidden range - no more to update
902              */
903             break;
904           }
905           region[1] = Math.max(nextRegion[1], end);
906           hiddenColumns.remove(i + 1);
907         }
908         return;
909       }
910     }
911
912     /*
913      * remaining case is that the new range follows everything else
914      */
915     hiddenColumns.addElement(new int[] { start, end });
916   }
917
918   /**
919    * Hides the specified column and any adjacent selected columns
920    * 
921    * @param res
922    *          int
923    */
924   public void hideColumns(int col)
925   {
926     /*
927      * deselect column (whether selected or not!)
928      */
929     removeElement(col);
930
931     /*
932      * find adjacent selected columns
933      */
934     int min = col - 1, max = col + 1;
935     while (contains(min))
936     {
937       removeElement(min);
938       min--;
939     }
940
941     while (contains(max))
942     {
943       removeElement(max);
944       max++;
945     }
946
947     /*
948      * min, max are now the closest unselected columns
949      */
950     min++;
951     max--;
952     if (min > max)
953     {
954       min = max;
955     }
956
957     hideColumns(min, max);
958   }
959
960   /**
961    * Unhides, and adds to the selection list, all hidden columns
962    */
963   public void revealAllHiddenColumns()
964   {
965     if (hiddenColumns != null)
966     {
967       for (int i = 0; i < hiddenColumns.size(); i++)
968       {
969         int[] region = hiddenColumns.elementAt(i);
970         for (int j = region[0]; j < region[1] + 1; j++)
971         {
972           addElement(j);
973         }
974       }
975     }
976
977     hiddenColumns = null;
978   }
979
980   /**
981    * Reveals, and marks as selected, the hidden column range with the given
982    * start column
983    * 
984    * @param start
985    */
986   public void revealHiddenColumns(int start)
987   {
988     for (int i = 0; i < hiddenColumns.size(); i++)
989     {
990       int[] region = hiddenColumns.elementAt(i);
991       if (start == region[0])
992       {
993         for (int j = region[0]; j < region[1] + 1; j++)
994         {
995           addElement(j);
996         }
997
998         hiddenColumns.removeElement(region);
999         break;
1000       }
1001     }
1002     if (hiddenColumns.size() == 0)
1003     {
1004       hiddenColumns = null;
1005     }
1006   }
1007
1008   public boolean isVisible(int column)
1009   {
1010     if (hiddenColumns != null)
1011     {
1012       for (int[] region : hiddenColumns)
1013       {
1014         if (column >= region[0] && column <= region[1])
1015         {
1016           return false;
1017         }
1018       }
1019     }
1020
1021     return true;
1022   }
1023
1024   /**
1025    * Copy constructor
1026    * 
1027    * @param copy
1028    */
1029   public ColumnSelection(ColumnSelection copy)
1030   {
1031     if (copy != null)
1032     {
1033       selection = new IntList(copy.selection);
1034       if (copy.hiddenColumns != null)
1035       {
1036         hiddenColumns = new Vector<int[]>(copy.hiddenColumns.size());
1037         for (int i = 0, j = copy.hiddenColumns.size(); i < j; i++)
1038         {
1039           int[] rh, cp;
1040           rh = copy.hiddenColumns.elementAt(i);
1041           if (rh != null)
1042           {
1043             cp = new int[rh.length];
1044             System.arraycopy(rh, 0, cp, 0, rh.length);
1045             hiddenColumns.addElement(cp);
1046           }
1047         }
1048       }
1049     }
1050   }
1051
1052   /**
1053    * ColumnSelection
1054    */
1055   public ColumnSelection()
1056   {
1057   }
1058
1059   public String[] getVisibleSequenceStrings(int start, int end,
1060           SequenceI[] seqs)
1061   {
1062     int i, iSize = seqs.length;
1063     String selections[] = new String[iSize];
1064     if (hiddenColumns != null && hiddenColumns.size() > 0)
1065     {
1066       for (i = 0; i < iSize; i++)
1067       {
1068         StringBuffer visibleSeq = new StringBuffer();
1069         List<int[]> regions = getHiddenColumns();
1070
1071         int blockStart = start, blockEnd = end;
1072         int[] region;
1073         int hideStart, hideEnd;
1074
1075         for (int j = 0; j < regions.size(); j++)
1076         {
1077           region = regions.get(j);
1078           hideStart = region[0];
1079           hideEnd = region[1];
1080
1081           if (hideStart < start)
1082           {
1083             continue;
1084           }
1085
1086           blockStart = Math.min(blockStart, hideEnd + 1);
1087           blockEnd = Math.min(blockEnd, hideStart);
1088
1089           if (blockStart > blockEnd)
1090           {
1091             break;
1092           }
1093
1094           visibleSeq.append(seqs[i].getSequence(blockStart, blockEnd));
1095
1096           blockStart = hideEnd + 1;
1097           blockEnd = end;
1098         }
1099
1100         if (end > blockStart)
1101         {
1102           visibleSeq.append(seqs[i].getSequence(blockStart, end));
1103         }
1104
1105         selections[i] = visibleSeq.toString();
1106       }
1107     }
1108     else
1109     {
1110       for (i = 0; i < iSize; i++)
1111       {
1112         selections[i] = seqs[i].getSequenceAsString(start, end);
1113       }
1114     }
1115
1116     return selections;
1117   }
1118
1119   /**
1120    * return all visible segments between the given start and end boundaries
1121    * 
1122    * @param start
1123    *          (first column inclusive from 0)
1124    * @param end
1125    *          (last column - not inclusive)
1126    * @return int[] {i_start, i_end, ..} where intervals lie in
1127    *         start<=i_start<=i_end<end
1128    */
1129   public int[] getVisibleContigs(int start, int end)
1130   {
1131     if (hiddenColumns != null && hiddenColumns.size() > 0)
1132     {
1133       List<int[]> visiblecontigs = new ArrayList<int[]>();
1134       List<int[]> regions = getHiddenColumns();
1135
1136       int vstart = start;
1137       int[] region;
1138       int hideStart, hideEnd;
1139
1140       for (int j = 0; vstart < end && j < regions.size(); j++)
1141       {
1142         region = regions.get(j);
1143         hideStart = region[0];
1144         hideEnd = region[1];
1145
1146         if (hideEnd < vstart)
1147         {
1148           continue;
1149         }
1150         if (hideStart > vstart)
1151         {
1152           visiblecontigs.add(new int[] { vstart, hideStart - 1 });
1153         }
1154         vstart = hideEnd + 1;
1155       }
1156
1157       if (vstart < end)
1158       {
1159         visiblecontigs.add(new int[] { vstart, end - 1 });
1160       }
1161       int[] vcontigs = new int[visiblecontigs.size() * 2];
1162       for (int i = 0, j = visiblecontigs.size(); i < j; i++)
1163       {
1164         int[] vc = visiblecontigs.get(i);
1165         visiblecontigs.set(i, null);
1166         vcontigs[i * 2] = vc[0];
1167         vcontigs[i * 2 + 1] = vc[1];
1168       }
1169       visiblecontigs.clear();
1170       return vcontigs;
1171     }
1172     else
1173     {
1174       return new int[] { start, end - 1 };
1175     }
1176   }
1177
1178   /**
1179    * Locate the first and last position visible for this sequence. if seq isn't
1180    * visible then return the position of the left and right of the hidden
1181    * boundary region, and the corresponding alignment column indices for the
1182    * extent of the sequence
1183    * 
1184    * @param seq
1185    * @return int[] { visible start, visible end, first seqpos, last seqpos,
1186    *         alignment index for seq start, alignment index for seq end }
1187    */
1188   public int[] locateVisibleBoundsOfSequence(SequenceI seq)
1189   {
1190     int fpos = seq.getStart(), lpos = seq.getEnd();
1191     int start = 0;
1192
1193     if (hiddenColumns == null || hiddenColumns.size() == 0)
1194     {
1195       int ifpos = seq.findIndex(fpos) - 1, ilpos = seq.findIndex(lpos) - 1;
1196       return new int[] { ifpos, ilpos, fpos, lpos, ifpos, ilpos };
1197     }
1198
1199     // Simply walk along the sequence whilst watching for hidden column
1200     // boundaries
1201     List<int[]> regions = getHiddenColumns();
1202     int spos = fpos, lastvispos = -1, rcount = 0, hideStart = seq
1203             .getLength(), hideEnd = -1;
1204     int visPrev = 0, visNext = 0, firstP = -1, lastP = -1;
1205     boolean foundStart = false;
1206     for (int p = 0, pLen = seq.getLength(); spos <= seq.getEnd()
1207             && p < pLen; p++)
1208     {
1209       if (!Comparison.isGap(seq.getCharAt(p)))
1210       {
1211         // keep track of first/last column
1212         // containing sequence data regardless of visibility
1213         if (firstP == -1)
1214         {
1215           firstP = p;
1216         }
1217         lastP = p;
1218         // update hidden region start/end
1219         while (hideEnd < p && rcount < regions.size())
1220         {
1221           int[] region = regions.get(rcount++);
1222           visPrev = visNext;
1223           visNext += region[0] - visPrev;
1224           hideStart = region[0];
1225           hideEnd = region[1];
1226         }
1227         if (hideEnd < p)
1228         {
1229           hideStart = seq.getLength();
1230         }
1231         // update visible boundary for sequence
1232         if (p < hideStart)
1233         {
1234           if (!foundStart)
1235           {
1236             fpos = spos;
1237             start = p;
1238             foundStart = true;
1239           }
1240           lastvispos = p;
1241           lpos = spos;
1242         }
1243         // look for next sequence position
1244         spos++;
1245       }
1246     }
1247     if (foundStart)
1248     {
1249       return new int[] { findColumnPosition(start),
1250           findColumnPosition(lastvispos), fpos, lpos, firstP, lastP };
1251     }
1252     // otherwise, sequence was completely hidden
1253     return new int[] { visPrev, visNext, 0, 0, firstP, lastP };
1254   }
1255
1256   /**
1257    * delete any columns in alignmentAnnotation that are hidden (including
1258    * sequence associated annotation).
1259    * 
1260    * @param alignmentAnnotation
1261    */
1262   public void makeVisibleAnnotation(AlignmentAnnotation alignmentAnnotation)
1263   {
1264     makeVisibleAnnotation(-1, -1, alignmentAnnotation);
1265   }
1266
1267   /**
1268    * delete any columns in alignmentAnnotation that are hidden (including
1269    * sequence associated annotation).
1270    * 
1271    * @param start
1272    *          remove any annotation to the right of this column
1273    * @param end
1274    *          remove any annotation to the left of this column
1275    * @param alignmentAnnotation
1276    *          the annotation to operate on
1277    */
1278   public void makeVisibleAnnotation(int start, int end,
1279           AlignmentAnnotation alignmentAnnotation)
1280   {
1281     if (alignmentAnnotation.annotations == null)
1282     {
1283       return;
1284     }
1285     if (start == end && end == -1)
1286     {
1287       start = 0;
1288       end = alignmentAnnotation.annotations.length;
1289     }
1290     if (hiddenColumns != null && hiddenColumns.size() > 0)
1291     {
1292       // then mangle the alignmentAnnotation annotation array
1293       Vector<Annotation[]> annels = new Vector<Annotation[]>();
1294       Annotation[] els = null;
1295       List<int[]> regions = getHiddenColumns();
1296       int blockStart = start, blockEnd = end;
1297       int[] region;
1298       int hideStart, hideEnd, w = 0;
1299
1300       for (int j = 0; j < regions.size(); j++)
1301       {
1302         region = regions.get(j);
1303         hideStart = region[0];
1304         hideEnd = region[1];
1305
1306         if (hideStart < start)
1307         {
1308           continue;
1309         }
1310
1311         blockStart = Math.min(blockStart, hideEnd + 1);
1312         blockEnd = Math.min(blockEnd, hideStart);
1313
1314         if (blockStart > blockEnd)
1315         {
1316           break;
1317         }
1318
1319         annels.addElement(els = new Annotation[blockEnd - blockStart]);
1320         System.arraycopy(alignmentAnnotation.annotations, blockStart, els,
1321                 0, els.length);
1322         w += els.length;
1323         blockStart = hideEnd + 1;
1324         blockEnd = end;
1325       }
1326
1327       if (end > blockStart)
1328       {
1329         annels.addElement(els = new Annotation[end - blockStart + 1]);
1330         if ((els.length + blockStart) <= alignmentAnnotation.annotations.length)
1331         {
1332           // copy just the visible segment of the annotation row
1333           System.arraycopy(alignmentAnnotation.annotations, blockStart,
1334                   els, 0, els.length);
1335         }
1336         else
1337         {
1338           // copy to the end of the annotation row
1339           System.arraycopy(alignmentAnnotation.annotations, blockStart,
1340                   els, 0,
1341                   (alignmentAnnotation.annotations.length - blockStart));
1342         }
1343         w += els.length;
1344       }
1345       if (w == 0)
1346       {
1347         return;
1348       }
1349
1350       alignmentAnnotation.annotations = new Annotation[w];
1351       w = 0;
1352
1353       for (Annotation[] chnk : annels)
1354       {
1355         System.arraycopy(chnk, 0, alignmentAnnotation.annotations, w,
1356                 chnk.length);
1357         w += chnk.length;
1358       }
1359     }
1360     else
1361     {
1362       alignmentAnnotation.restrict(start, end);
1363     }
1364   }
1365
1366   /**
1367    * Invert the column selection from first to end-1. leaves hiddenColumns
1368    * untouched (and unselected)
1369    * 
1370    * @param first
1371    * @param end
1372    */
1373   public void invertColumnSelection(int first, int width)
1374   {
1375     boolean hasHidden = hiddenColumns != null && hiddenColumns.size() > 0;
1376     for (int i = first; i < width; i++)
1377     {
1378       if (contains(i))
1379       {
1380         removeElement(i);
1381       }
1382       else
1383       {
1384         if (!hasHidden || isVisible(i))
1385         {
1386           addElement(i);
1387         }
1388       }
1389     }
1390   }
1391
1392   /**
1393    * add in any unselected columns from the given column selection, excluding
1394    * any that are hidden.
1395    * 
1396    * @param colsel
1397    */
1398   public void addElementsFrom(ColumnSelection colsel)
1399   {
1400     if (colsel != null && !colsel.isEmpty())
1401     {
1402       for (Integer col : colsel.getSelected())
1403       {
1404         if (hiddenColumns != null && isVisible(col.intValue()))
1405         {
1406           selection.add(col);
1407         }
1408       }
1409     }
1410   }
1411
1412   /**
1413    * set the selected columns the given column selection, excluding any columns
1414    * that are hidden.
1415    * 
1416    * @param colsel
1417    */
1418   public void setElementsFrom(ColumnSelection colsel)
1419   {
1420     selection = new IntList();
1421     if (colsel.selection != null && colsel.selection.size() > 0)
1422     {
1423       if (hiddenColumns != null && hiddenColumns.size() > 0)
1424       {
1425         // only select visible columns in this columns selection
1426         addElementsFrom(colsel);
1427       }
1428       else
1429       {
1430         // add everything regardless
1431         for (Integer col : colsel.getSelected())
1432         {
1433           addElement(col);
1434         }
1435       }
1436     }
1437   }
1438
1439   /**
1440    * Add gaps into the sequences aligned to profileseq under the given
1441    * AlignmentView
1442    * 
1443    * @param profileseq
1444    * @param al
1445    *          - alignment to have gaps inserted into it
1446    * @param input
1447    *          - alignment view where sequence corresponding to profileseq is
1448    *          first entry
1449    * @return new Column selection for new alignment view, with insertions into
1450    *         profileseq marked as hidden.
1451    */
1452   public static ColumnSelection propagateInsertions(SequenceI profileseq,
1453           AlignmentI al, AlignmentView input)
1454   {
1455     int profsqpos = 0;
1456
1457     // return propagateInsertions(profileseq, al, )
1458     char gc = al.getGapCharacter();
1459     Object[] alandcolsel = input.getAlignmentAndColumnSelection(gc);
1460     ColumnSelection nview = (ColumnSelection) alandcolsel[1];
1461     SequenceI origseq = ((SequenceI[]) alandcolsel[0])[profsqpos];
1462     nview.propagateInsertions(profileseq, al, origseq);
1463     return nview;
1464   }
1465
1466   /**
1467    * 
1468    * @param profileseq
1469    *          - sequence in al which corresponds to origseq
1470    * @param al
1471    *          - alignment which is to have gaps inserted into it
1472    * @param origseq
1473    *          - sequence corresponding to profileseq which defines gap map for
1474    *          modifying al
1475    */
1476   public void propagateInsertions(SequenceI profileseq, AlignmentI al,
1477           SequenceI origseq)
1478   {
1479     char gc = al.getGapCharacter();
1480     // recover mapping between sequence's non-gap positions and positions
1481     // mapping to view.
1482     pruneDeletions(ShiftList.parseMap(origseq.gapMap()));
1483     int[] viscontigs = getVisibleContigs(0, profileseq.getLength());
1484     int spos = 0;
1485     int offset = 0;
1486     // input.pruneDeletions(ShiftList.parseMap(((SequenceI[])
1487     // alandcolsel[0])[0].gapMap()))
1488     // add profile to visible contigs
1489     for (int v = 0; v < viscontigs.length; v += 2)
1490     {
1491       if (viscontigs[v] > spos)
1492       {
1493         StringBuffer sb = new StringBuffer();
1494         for (int s = 0, ns = viscontigs[v] - spos; s < ns; s++)
1495         {
1496           sb.append(gc);
1497         }
1498         for (int s = 0, ns = al.getHeight(); s < ns; s++)
1499         {
1500           SequenceI sqobj = al.getSequenceAt(s);
1501           if (sqobj != profileseq)
1502           {
1503             String sq = al.getSequenceAt(s).getSequenceAsString();
1504             if (sq.length() <= spos + offset)
1505             {
1506               // pad sequence
1507               int diff = spos + offset - sq.length() - 1;
1508               if (diff > 0)
1509               {
1510                 // pad gaps
1511                 sq = sq + sb;
1512                 while ((diff = spos + offset - sq.length() - 1) > 0)
1513                 {
1514                   // sq = sq
1515                   // + ((diff >= sb.length()) ? sb.toString() : sb
1516                   // .substring(0, diff));
1517                   if (diff >= sb.length())
1518                   {
1519                     sq += sb.toString();
1520                   }
1521                   else
1522                   {
1523                     char[] buf = new char[diff];
1524                     sb.getChars(0, diff, buf, 0);
1525                     sq += buf.toString();
1526                   }
1527                 }
1528               }
1529               sq += sb.toString();
1530             }
1531             else
1532             {
1533               al.getSequenceAt(s).setSequence(
1534                       sq.substring(0, spos + offset) + sb.toString()
1535                               + sq.substring(spos + offset));
1536             }
1537           }
1538         }
1539         // offset+=sb.length();
1540       }
1541       spos = viscontigs[v + 1] + 1;
1542     }
1543     if ((offset + spos) < profileseq.getLength())
1544     {
1545       // pad the final region with gaps.
1546       StringBuffer sb = new StringBuffer();
1547       for (int s = 0, ns = profileseq.getLength() - spos - offset; s < ns; s++)
1548       {
1549         sb.append(gc);
1550       }
1551       for (int s = 0, ns = al.getHeight(); s < ns; s++)
1552       {
1553         SequenceI sqobj = al.getSequenceAt(s);
1554         if (sqobj == profileseq)
1555         {
1556           continue;
1557         }
1558         String sq = sqobj.getSequenceAsString();
1559         // pad sequence
1560         int diff = origseq.getLength() - sq.length();
1561         while (diff > 0)
1562         {
1563           // sq = sq
1564           // + ((diff >= sb.length()) ? sb.toString() : sb
1565           // .substring(0, diff));
1566           if (diff >= sb.length())
1567           {
1568             sq += sb.toString();
1569           }
1570           else
1571           {
1572             char[] buf = new char[diff];
1573             sb.getChars(0, diff, buf, 0);
1574             sq += buf.toString();
1575           }
1576           diff = origseq.getLength() - sq.length();
1577         }
1578       }
1579     }
1580   }
1581
1582   /**
1583    * 
1584    * @return true if there are columns marked
1585    */
1586   public boolean hasSelectedColumns()
1587   {
1588     return (selection != null && selection.size() > 0);
1589   }
1590
1591   /**
1592    * 
1593    * @return true if there are columns hidden
1594    */
1595   public boolean hasHiddenColumns()
1596   {
1597     return hiddenColumns != null && hiddenColumns.size() > 0;
1598   }
1599
1600   /**
1601    * 
1602    * @return true if there are more than one set of columns hidden
1603    */
1604   public boolean hasManyHiddenColumns()
1605   {
1606     return hiddenColumns != null && hiddenColumns.size() > 1;
1607   }
1608
1609   /**
1610    * mark the columns corresponding to gap characters as hidden in the column
1611    * selection
1612    * 
1613    * @param sr
1614    */
1615   public void hideInsertionsFor(SequenceI sr)
1616   {
1617     List<int[]> inserts = sr.getInsertions();
1618     for (int[] r : inserts)
1619     {
1620       hideColumns(r[0], r[1]);
1621     }
1622   }
1623
1624   public boolean filterAnnotations(Annotation[] annotations,
1625           AnnotationFilterParameter filterParams)
1626   {
1627     // JBPNote - this method needs to be refactored to become independent of
1628     // viewmodel package
1629     this.revealAllHiddenColumns();
1630     this.clear();
1631     int count = 0;
1632     do
1633     {
1634       if (annotations[count] != null)
1635       {
1636
1637         boolean itemMatched = false;
1638
1639         if (filterParams.getThresholdType() == AnnotationFilterParameter.ThresholdType.ABOVE_THRESHOLD
1640                 && annotations[count].value >= filterParams
1641                         .getThresholdValue())
1642         {
1643           itemMatched = true;
1644         }
1645         if (filterParams.getThresholdType() == AnnotationFilterParameter.ThresholdType.BELOW_THRESHOLD
1646                 && annotations[count].value <= filterParams
1647                         .getThresholdValue())
1648         {
1649           itemMatched = true;
1650         }
1651
1652         if (filterParams.isFilterAlphaHelix()
1653                 && annotations[count].secondaryStructure == 'H')
1654         {
1655           itemMatched = true;
1656         }
1657
1658         if (filterParams.isFilterBetaSheet()
1659                 && annotations[count].secondaryStructure == 'E')
1660         {
1661           itemMatched = true;
1662         }
1663
1664         if (filterParams.isFilterTurn()
1665                 && annotations[count].secondaryStructure == 'S')
1666         {
1667           itemMatched = true;
1668         }
1669
1670         String regexSearchString = filterParams.getRegexString();
1671         if (regexSearchString != null
1672                 && !filterParams.getRegexSearchFields().isEmpty())
1673         {
1674           List<SearchableAnnotationField> fields = filterParams
1675                   .getRegexSearchFields();
1676           try
1677           {
1678             if (fields.contains(SearchableAnnotationField.DISPLAY_STRING)
1679                     && annotations[count].displayCharacter
1680                             .matches(regexSearchString))
1681             {
1682               itemMatched = true;
1683             }
1684           } catch (java.util.regex.PatternSyntaxException pse)
1685           {
1686             if (annotations[count].displayCharacter
1687                     .equals(regexSearchString))
1688             {
1689               itemMatched = true;
1690             }
1691           }
1692           if (fields.contains(SearchableAnnotationField.DESCRIPTION)
1693                   && annotations[count].description != null
1694                   && annotations[count].description
1695                           .matches(regexSearchString))
1696           {
1697             itemMatched = true;
1698           }
1699         }
1700
1701         if (itemMatched)
1702         {
1703           this.addElement(count);
1704         }
1705       }
1706       count++;
1707     } while (count < annotations.length);
1708     return false;
1709   }
1710
1711   /**
1712    * Returns a hashCode built from selected columns and hidden column ranges
1713    */
1714   @Override
1715   public int hashCode()
1716   {
1717     int hashCode = selection.hashCode();
1718     if (hiddenColumns != null)
1719     {
1720       for (int[] hidden : hiddenColumns)
1721       {
1722         hashCode = 31 * hashCode + hidden[0];
1723         hashCode = 31 * hashCode + hidden[1];
1724       }
1725     }
1726     return hashCode;
1727   }
1728
1729   /**
1730    * Answers true if comparing to a ColumnSelection with the same selected
1731    * columns and hidden columns, else false
1732    */
1733   @Override
1734   public boolean equals(Object obj)
1735   {
1736     if (!(obj instanceof ColumnSelection))
1737     {
1738       return false;
1739     }
1740     ColumnSelection that = (ColumnSelection) obj;
1741
1742     /*
1743      * check columns selected are either both null, or match
1744      */
1745     if (this.selection == null)
1746     {
1747       if (that.selection != null)
1748       {
1749         return false;
1750       }
1751     }
1752     if (!this.selection.equals(that.selection))
1753     {
1754       return false;
1755     }
1756
1757     /*
1758      * check hidden columns are either both null, or match
1759      */
1760     if (this.hiddenColumns == null)
1761     {
1762       return (that.hiddenColumns == null);
1763     }
1764     if (that.hiddenColumns == null
1765             || that.hiddenColumns.size() != this.hiddenColumns.size())
1766     {
1767       return false;
1768     }
1769     int i = 0;
1770     for (int[] thisRange : hiddenColumns)
1771     {
1772       int[] thatRange = that.hiddenColumns.get(i++);
1773       if (thisRange[0] != thatRange[0] || thisRange[1] != thatRange[1])
1774       {
1775         return false;
1776       }
1777     }
1778     return true;
1779   }
1780
1781   /**
1782    * Updates the column selection depending on the parameters, and returns true
1783    * if any change was made to the selection
1784    * 
1785    * @param markedColumns
1786    *          a set identifying marked columns (base 0)
1787    * @param startCol
1788    *          the first column of the range to operate over (base 0)
1789    * @param endCol
1790    *          the last column of the range to operate over (base 0)
1791    * @param invert
1792    *          if true, deselect marked columns and select unmarked
1793    * @param extendCurrent
1794    *          if true, extend rather than replacing the current column selection
1795    * @param toggle
1796    *          if true, toggle the selection state of marked columns
1797    * 
1798    * @return
1799    */
1800   public boolean markColumns(BitSet markedColumns, int startCol,
1801           int endCol, boolean invert, boolean extendCurrent, boolean toggle)
1802   {
1803     boolean changed = false;
1804     if (!extendCurrent && !toggle)
1805     {
1806       changed = !this.isEmpty();
1807       clear();
1808     }
1809     if (invert)
1810     {
1811       // invert only in the currently selected sequence region
1812       int i = markedColumns.nextClearBit(startCol);
1813       int ibs = markedColumns.nextSetBit(startCol);
1814       while (i >= startCol && i <= endCol)
1815       {
1816         if (ibs < 0 || i < ibs)
1817         {
1818           changed = true;
1819           if (toggle && contains(i))
1820           {
1821             removeElement(i++);
1822           }
1823           else
1824           {
1825             addElement(i++);
1826           }
1827         }
1828         else
1829         {
1830           i = markedColumns.nextClearBit(ibs);
1831           ibs = markedColumns.nextSetBit(i);
1832         }
1833       }
1834     }
1835     else
1836     {
1837       int i = markedColumns.nextSetBit(startCol);
1838       while (i >= startCol && i <= endCol)
1839       {
1840         changed = true;
1841         if (toggle && contains(i))
1842         {
1843           removeElement(i);
1844         }
1845         else
1846         {
1847           addElement(i);
1848         }
1849         i = markedColumns.nextSetBit(i + 1);
1850       }
1851     }
1852     return changed;
1853   }
1854
1855   /**
1856    * Adjusts column selections, and the given selection group, to match the
1857    * range of a stretch (e.g. mouse drag) operation
1858    * <p>
1859    * Method refactored from ScalePanel.mouseDragged
1860    * 
1861    * @param res
1862    *          current column position, adjusted for hidden columns
1863    * @param sg
1864    *          current selection group
1865    * @param min
1866    *          start position of the stretch group
1867    * @param max
1868    *          end position of the stretch group
1869    */
1870   public void stretchGroup(int res, SequenceGroup sg, int min, int max)
1871   {
1872     if (!contains(res))
1873     {
1874       addElement(res);
1875     }
1876
1877     if (res > sg.getStartRes())
1878     {
1879       // expand selection group to the right
1880       sg.setEndRes(res);
1881     }
1882     if (res < sg.getStartRes())
1883     {
1884       // expand selection group to the left
1885       sg.setStartRes(res);
1886     }
1887
1888     /*
1889      * expand or shrink column selection to match the
1890      * range of the drag operation
1891      */
1892     for (int col = min; col <= max; col++)
1893     {
1894       if (col < sg.getStartRes() || col > sg.getEndRes())
1895       {
1896         // shrinking drag - remove from selection
1897         removeElement(col);
1898       }
1899       else
1900       {
1901         // expanding drag - add to selection
1902         addElement(col);
1903       }
1904     }
1905   }
1906 }