JAL-2418 source formatting
[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.viewmodel.annotationfilter.AnnotationFilterParameter;
24 import jalview.viewmodel.annotationfilter.AnnotationFilterParameter.SearchableAnnotationField;
25
26 import java.util.ArrayList;
27 import java.util.BitSet;
28 import java.util.Collections;
29 import java.util.List;
30
31 /**
32  * Data class holding the selected columns and hidden column ranges for a view.
33  * Ranges are base 1.
34  */
35 public class ColumnSelection
36 {
37   /**
38    * A class to hold an efficient representation of selected columns
39    */
40   private class IntList
41   {
42     /*
43      * list of selected columns (ordered by selection order, not column order)
44      */
45     private List<Integer> order;
46
47     /*
48      * an unmodifiable view of the selected columns list
49      */
50     private List<Integer> _uorder;
51
52     /**
53      * bitfield for column selection - allows quick lookup
54      */
55     private BitSet selected;
56
57     /**
58      * Constructor
59      */
60     IntList()
61     {
62       order = new ArrayList<Integer>();
63       _uorder = Collections.unmodifiableList(order);
64       selected = new BitSet();
65     }
66
67     /**
68      * Copy constructor
69      * 
70      * @param other
71      */
72     IntList(IntList other)
73     {
74       this();
75       if (other != null)
76       {
77         int j = other.size();
78         for (int i = 0; i < j; i++)
79         {
80           add(other.elementAt(i));
81         }
82       }
83     }
84
85     /**
86      * adds a new column i to the selection - only if i is not already selected
87      * 
88      * @param i
89      */
90     void add(int i)
91     {
92       if (!selected.get(i))
93       {
94         order.add(Integer.valueOf(i));
95         selected.set(i);
96       }
97     }
98
99     void clear()
100     {
101       order.clear();
102       selected.clear();
103     }
104
105     void remove(int col)
106     {
107
108       Integer colInt = new Integer(col);
109
110       if (selected.get(col))
111       {
112         // if this ever changes to List.remove(), ensure Integer not int
113         // argument
114         // as List.remove(int i) removes the i'th item which is wrong
115         order.remove(colInt);
116         selected.clear(col);
117       }
118     }
119
120     boolean contains(Integer colInt)
121     {
122       return selected.get(colInt);
123     }
124
125     boolean isEmpty()
126     {
127       return order.isEmpty();
128     }
129
130     /**
131      * Returns a read-only view of the selected columns list
132      * 
133      * @return
134      */
135     List<Integer> getList()
136     {
137       return _uorder;
138     }
139
140     int size()
141     {
142       return order.size();
143     }
144
145     /**
146      * gets the column that was selected first, second or i'th
147      * 
148      * @param i
149      * @return
150      */
151     int elementAt(int i)
152     {
153       return order.get(i);
154     }
155
156     protected boolean pruneColumnList(final List<int[]> shifts)
157     {
158       int s = 0, t = shifts.size();
159       int[] sr = shifts.get(s++);
160       boolean pruned = false;
161       int i = 0, j = order.size();
162       while (i < j && s <= t)
163       {
164         int c = order.get(i++).intValue();
165         if (sr[0] <= c)
166         {
167           if (sr[1] + sr[0] >= c)
168           { // sr[1] -ve means inseriton.
169             order.remove(--i);
170             selected.clear(c);
171             j--;
172           }
173           else
174           {
175             if (s < t)
176             {
177               sr = shifts.get(s);
178             }
179             s++;
180           }
181         }
182       }
183       return pruned;
184     }
185
186     /**
187      * shift every selected column at or above start by change
188      * 
189      * @param start
190      *          - leftmost column to be shifted
191      * @param change
192      *          - delta for shift
193      */
194     void compensateForEdits(int start, int change)
195     {
196       BitSet mask = new BitSet();
197       for (int i = 0; i < order.size(); i++)
198       {
199         int temp = order.get(i);
200
201         if (temp >= start)
202         {
203           // clear shifted bits and update List of selected columns
204           selected.clear(temp);
205           mask.set(temp - change);
206           order.set(i, new Integer(temp - change));
207         }
208       }
209       // lastly update the bitfield all at once
210       selected.or(mask);
211     }
212
213     boolean isSelected(int column)
214     {
215       return selected.get(column);
216     }
217
218     int getMaxColumn()
219     {
220       return selected.length() - 1;
221     }
222
223     int getMinColumn()
224     {
225       return selected.get(0) ? 0 : selected.nextSetBit(0);
226     }
227
228     /**
229      * @return a series of selection intervals along the range
230      */
231     List<int[]> getRanges()
232     {
233       List<int[]> rlist = new ArrayList<int[]>();
234       if (selected.isEmpty())
235       {
236         return rlist;
237       }
238       int next = selected.nextSetBit(0), clear = -1;
239       while (next != -1)
240       {
241         clear = selected.nextClearBit(next);
242         rlist.add(new int[] { next, clear - 1 });
243         next = selected.nextSetBit(clear);
244       }
245       return rlist;
246     }
247
248     @Override
249     public int hashCode()
250     {
251       // TODO Auto-generated method stub
252       return selected.hashCode();
253     }
254
255     @Override
256     public boolean equals(Object obj)
257     {
258       if (obj instanceof IntList)
259       {
260         return ((IntList) obj).selected.equals(selected);
261       }
262       return false;
263     }
264   }
265
266   IntList selection = new IntList();
267
268   /**
269    * Add a column to the selection
270    * 
271    * @param col
272    *          index of column
273    */
274   public void addElement(int col)
275   {
276     selection.add(col);
277   }
278
279   /**
280    * clears column selection
281    */
282   public void clear()
283   {
284     selection.clear();
285   }
286
287   /**
288    * Removes value 'col' from the selection (not the col'th item)
289    * 
290    * @param col
291    *          index of column to be removed
292    */
293   public void removeElement(int col)
294   {
295     selection.remove(col);
296   }
297
298   /**
299    * removes a range of columns from the selection
300    * 
301    * @param start
302    *          int - first column in range to be removed
303    * @param end
304    *          int - last col
305    */
306   public void removeElements(int start, int end)
307   {
308     Integer colInt;
309     for (int i = start; i < end; i++)
310     {
311       colInt = new Integer(i);
312       if (selection.contains(colInt))
313       {
314         selection.remove(colInt);
315       }
316     }
317   }
318
319   /**
320    * Returns a read-only view of the (possibly empty) list of selected columns
321    * <p>
322    * The list contains no duplicates but is not necessarily ordered. It also may
323    * include columns hidden from the current view. To modify (for example sort)
324    * the list, you should first make a copy.
325    * <p>
326    * The list is not thread-safe: iterating over it could result in
327    * ConcurrentModificationException if it is modified by another thread.
328    */
329   public List<Integer> getSelected()
330   {
331     return selection.getList();
332   }
333
334   /**
335    * @return list of int arrays containing start and end column position for
336    *         runs of selected columns ordered from right to left.
337    */
338   public List<int[]> getSelectedRanges()
339   {
340     return selection.getRanges();
341   }
342
343   /**
344    * 
345    * @param col
346    *          index to search for in column selection
347    * 
348    * @return true if col is selected
349    */
350   public boolean contains(int col)
351   {
352     return (col > -1) ? selection.isSelected(col) : false;
353   }
354
355   /**
356    * Answers true if no columns are selected, else false
357    */
358   public boolean isEmpty()
359   {
360     return selection == null || selection.isEmpty();
361   }
362
363   /**
364    * rightmost selected column
365    * 
366    * @return rightmost column in alignment that is selected
367    */
368   public int getMax()
369   {
370     if (selection.isEmpty())
371     {
372       return -1;
373     }
374     return selection.getMaxColumn();
375   }
376
377   /**
378    * Leftmost column in selection
379    * 
380    * @return column index of leftmost column in selection
381    */
382   public int getMin()
383   {
384     if (selection.isEmpty())
385     {
386       return 1000000000;
387     }
388     return selection.getMinColumn();
389   }
390
391   public void hideSelectedColumns(AlignmentI al)
392   {
393     synchronized (selection)
394     {
395       for (int[] selregions : selection.getRanges())
396       {
397         al.getHiddenColumns().hideColumns(selregions[0], selregions[1]);
398       }
399       selection.clear();
400     }
401
402   }
403
404   /**
405    * Hides the specified column and any adjacent selected columns
406    * 
407    * @param res
408    *          int
409    */
410   public void hideSelectedColumns(int col, HiddenColumns hidden)
411   {
412     /*
413      * deselect column (whether selected or not!)
414      */
415     removeElement(col);
416
417     /*
418      * find adjacent selected columns
419      */
420     int min = col - 1, max = col + 1;
421     while (contains(min))
422     {
423       removeElement(min);
424       min--;
425     }
426
427     while (contains(max))
428     {
429       removeElement(max);
430       max++;
431     }
432
433     /*
434      * min, max are now the closest unselected columns
435      */
436     min++;
437     max--;
438     if (min > max)
439     {
440       min = max;
441     }
442
443     hidden.hideColumns(min, max);
444   }
445
446   /**
447    * Copy constructor
448    * 
449    * @param copy
450    */
451   public ColumnSelection(ColumnSelection copy)
452   {
453     if (copy != null)
454     {
455       selection = new IntList(copy.selection);
456     }
457   }
458
459   /**
460    * ColumnSelection
461    */
462   public ColumnSelection()
463   {
464   }
465
466   /**
467    * Invert the column selection from first to end-1. leaves hiddenColumns
468    * untouched (and unselected)
469    * 
470    * @param first
471    * @param end
472    */
473   public void invertColumnSelection(int first, int width, AlignmentI al)
474   {
475     boolean hasHidden = al.getHiddenColumns().hasHiddenColumns();
476     for (int i = first; i < width; i++)
477     {
478       if (contains(i))
479       {
480         removeElement(i);
481       }
482       else
483       {
484         if (!hasHidden || al.getHiddenColumns().isVisible(i))
485         {
486           addElement(i);
487         }
488       }
489     }
490   }
491
492   /**
493    * set the selected columns to the given column selection, excluding any
494    * columns that are hidden.
495    * 
496    * @param colsel
497    */
498   public void setElementsFrom(ColumnSelection colsel,
499           HiddenColumns hiddenColumns)
500   {
501     selection = new IntList();
502     if (colsel.selection != null && colsel.selection.size() > 0)
503     {
504       if (hiddenColumns.hasHiddenColumns())
505       {
506         // only select visible columns in this columns selection
507         for (Integer col : colsel.getSelected())
508         {
509           if (hiddenColumns != null
510                   && hiddenColumns.isVisible(col.intValue()))
511           {
512             selection.add(col);
513           }
514         }
515       }
516       else
517       {
518         // add everything regardless
519         for (Integer col : colsel.getSelected())
520         {
521           addElement(col);
522         }
523       }
524     }
525   }
526
527   /**
528    * 
529    * @return true if there are columns marked
530    */
531   public boolean hasSelectedColumns()
532   {
533     return (selection != null && selection.size() > 0);
534   }
535
536   public boolean filterAnnotations(Annotation[] annotations,
537           AnnotationFilterParameter filterParams)
538   {
539     // JBPNote - this method needs to be refactored to become independent of
540     // viewmodel package
541     this.clear();
542     int count = 0;
543     do
544     {
545       if (annotations[count] != null)
546       {
547
548         boolean itemMatched = false;
549
550         if (filterParams
551                 .getThresholdType() == AnnotationFilterParameter.ThresholdType.ABOVE_THRESHOLD
552                 && annotations[count].value >= filterParams
553                         .getThresholdValue())
554         {
555           itemMatched = true;
556         }
557         if (filterParams
558                 .getThresholdType() == AnnotationFilterParameter.ThresholdType.BELOW_THRESHOLD
559                 && annotations[count].value <= filterParams
560                         .getThresholdValue())
561         {
562           itemMatched = true;
563         }
564
565         if (filterParams.isFilterAlphaHelix()
566                 && annotations[count].secondaryStructure == 'H')
567         {
568           itemMatched = true;
569         }
570
571         if (filterParams.isFilterBetaSheet()
572                 && annotations[count].secondaryStructure == 'E')
573         {
574           itemMatched = true;
575         }
576
577         if (filterParams.isFilterTurn()
578                 && annotations[count].secondaryStructure == 'S')
579         {
580           itemMatched = true;
581         }
582
583         String regexSearchString = filterParams.getRegexString();
584         if (regexSearchString != null
585                 && !filterParams.getRegexSearchFields().isEmpty())
586         {
587           List<SearchableAnnotationField> fields = filterParams
588                   .getRegexSearchFields();
589           try
590           {
591             if (fields.contains(SearchableAnnotationField.DISPLAY_STRING)
592                     && annotations[count].displayCharacter
593                             .matches(regexSearchString))
594             {
595               itemMatched = true;
596             }
597           } catch (java.util.regex.PatternSyntaxException pse)
598           {
599             if (annotations[count].displayCharacter
600                     .equals(regexSearchString))
601             {
602               itemMatched = true;
603             }
604           }
605           if (fields.contains(SearchableAnnotationField.DESCRIPTION)
606                   && annotations[count].description != null
607                   && annotations[count].description
608                           .matches(regexSearchString))
609           {
610             itemMatched = true;
611           }
612         }
613
614         if (itemMatched)
615         {
616           this.addElement(count);
617         }
618       }
619       count++;
620     } while (count < annotations.length);
621     return false;
622   }
623
624   /**
625    * Returns a hashCode built from selected columns ranges
626    */
627   @Override
628   public int hashCode()
629   {
630     return selection.hashCode();
631   }
632
633   /**
634    * Answers true if comparing to a ColumnSelection with the same selected
635    * columns and hidden columns, else false
636    */
637   @Override
638   public boolean equals(Object obj)
639   {
640     if (!(obj instanceof ColumnSelection))
641     {
642       return false;
643     }
644     ColumnSelection that = (ColumnSelection) obj;
645
646     /*
647      * check columns selected are either both null, or match
648      */
649     if (this.selection == null)
650     {
651       if (that.selection != null)
652       {
653         return false;
654       }
655     }
656     if (!this.selection.equals(that.selection))
657     {
658       return false;
659     }
660
661     return true;
662   }
663
664   /**
665    * Updates the column selection depending on the parameters, and returns true
666    * if any change was made to the selection
667    * 
668    * @param markedColumns
669    *          a set identifying marked columns (base 0)
670    * @param startCol
671    *          the first column of the range to operate over (base 0)
672    * @param endCol
673    *          the last column of the range to operate over (base 0)
674    * @param invert
675    *          if true, deselect marked columns and select unmarked
676    * @param extendCurrent
677    *          if true, extend rather than replacing the current column selection
678    * @param toggle
679    *          if true, toggle the selection state of marked columns
680    * 
681    * @return
682    */
683   public boolean markColumns(BitSet markedColumns, int startCol, int endCol,
684           boolean invert, boolean extendCurrent, boolean toggle)
685   {
686     boolean changed = false;
687     if (!extendCurrent && !toggle)
688     {
689       changed = !this.isEmpty();
690       clear();
691     }
692     if (invert)
693     {
694       // invert only in the currently selected sequence region
695       int i = markedColumns.nextClearBit(startCol);
696       int ibs = markedColumns.nextSetBit(startCol);
697       while (i >= startCol && i <= endCol)
698       {
699         if (ibs < 0 || i < ibs)
700         {
701           changed = true;
702           if (toggle && contains(i))
703           {
704             removeElement(i++);
705           }
706           else
707           {
708             addElement(i++);
709           }
710         }
711         else
712         {
713           i = markedColumns.nextClearBit(ibs);
714           ibs = markedColumns.nextSetBit(i);
715         }
716       }
717     }
718     else
719     {
720       int i = markedColumns.nextSetBit(startCol);
721       while (i >= startCol && i <= endCol)
722       {
723         changed = true;
724         if (toggle && contains(i))
725         {
726           removeElement(i);
727         }
728         else
729         {
730           addElement(i);
731         }
732         i = markedColumns.nextSetBit(i + 1);
733       }
734     }
735     return changed;
736   }
737
738   /**
739    * Adjusts column selections, and the given selection group, to match the
740    * range of a stretch (e.g. mouse drag) operation
741    * <p>
742    * Method refactored from ScalePanel.mouseDragged
743    * 
744    * @param res
745    *          current column position, adjusted for hidden columns
746    * @param sg
747    *          current selection group
748    * @param min
749    *          start position of the stretch group
750    * @param max
751    *          end position of the stretch group
752    */
753   public void stretchGroup(int res, SequenceGroup sg, int min, int max)
754   {
755     if (!contains(res))
756     {
757       addElement(res);
758     }
759
760     if (res > sg.getStartRes())
761     {
762       // expand selection group to the right
763       sg.setEndRes(res);
764     }
765     if (res < sg.getStartRes())
766     {
767       // expand selection group to the left
768       sg.setStartRes(res);
769     }
770
771     /*
772      * expand or shrink column selection to match the
773      * range of the drag operation
774      */
775     for (int col = min; col <= max; col++)
776     {
777       if (col < sg.getStartRes() || col > sg.getEndRes())
778       {
779         // shrinking drag - remove from selection
780         removeElement(col);
781       }
782       else
783       {
784         // expanding drag - add to selection
785         addElement(col);
786       }
787     }
788   }
789 }