70f16d95a8c0fd0daa344434b2aac3d049ea586c
[jalview.git] / src / jalview / viewmodel / AlignmentViewport.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.viewmodel;
22
23 import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
24 import jalview.analysis.Conservation;
25 import jalview.api.AlignCalcManagerI;
26 import jalview.api.AlignViewportI;
27 import jalview.api.AlignmentViewPanel;
28 import jalview.api.FeaturesDisplayedI;
29 import jalview.api.ViewStyleI;
30 import jalview.commands.CommandI;
31 import jalview.datamodel.AlignedCodonFrame;
32 import jalview.datamodel.AlignmentAnnotation;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.AlignmentView;
35 import jalview.datamodel.Annotation;
36 import jalview.datamodel.CigarArray;
37 import jalview.datamodel.ColumnSelection;
38 import jalview.datamodel.HiddenColumns;
39 import jalview.datamodel.HiddenSequences;
40 import jalview.datamodel.ProfilesI;
41 import jalview.datamodel.SearchResultsI;
42 import jalview.datamodel.Sequence;
43 import jalview.datamodel.SequenceCollectionI;
44 import jalview.datamodel.SequenceGroup;
45 import jalview.datamodel.SequenceI;
46 import jalview.renderer.ResidueShader;
47 import jalview.renderer.ResidueShaderI;
48 import jalview.schemes.ColourSchemeI;
49 import jalview.structure.CommandListener;
50 import jalview.structure.StructureSelectionManager;
51 import jalview.structure.VamsasSource;
52 import jalview.util.Comparison;
53 import jalview.util.MapList;
54 import jalview.util.MappingUtils;
55 import jalview.util.MessageManager;
56 import jalview.viewmodel.styles.ViewStyle;
57 import jalview.workers.AlignCalcManager;
58 import jalview.workers.ComplementConsensusThread;
59 import jalview.workers.ConsensusThread;
60 import jalview.workers.StrucConsensusThread;
61
62 import java.awt.Color;
63 import java.beans.PropertyChangeSupport;
64 import java.util.ArrayDeque;
65 import java.util.ArrayList;
66 import java.util.BitSet;
67 import java.util.Deque;
68 import java.util.HashMap;
69 import java.util.Hashtable;
70 import java.util.List;
71 import java.util.Map;
72
73 /**
74  * base class holding visualization and analysis attributes and common logic for
75  * an active alignment view displayed in the GUI
76  * 
77  * @author jimp
78  * 
79  */
80 public abstract class AlignmentViewport implements AlignViewportI,
81         CommandListener, VamsasSource
82 {
83   final protected ViewportRanges ranges;
84
85   protected ViewStyleI viewStyle = new ViewStyle();
86
87   /**
88    * A viewport that hosts the cDna view of this (protein), or vice versa (if
89    * set).
90    */
91   AlignViewportI codingComplement = null;
92
93   FeaturesDisplayedI featuresDisplayed = null;
94
95   protected Deque<CommandI> historyList = new ArrayDeque<>();
96
97   protected Deque<CommandI> redoList = new ArrayDeque<>();
98
99   /**
100    * alignment displayed in the viewport. Please use get/setter
101    */
102   protected AlignmentI alignment;
103
104   public AlignmentViewport(AlignmentI al)
105   {
106     setAlignment(al);
107     ranges = new ViewportRanges(al);
108   }
109
110   /**
111    * @param name
112    * @see jalview.api.ViewStyleI#setFontName(java.lang.String)
113    */
114   @Override
115   public void setFontName(String name)
116   {
117     viewStyle.setFontName(name);
118   }
119
120   /**
121    * @param style
122    * @see jalview.api.ViewStyleI#setFontStyle(int)
123    */
124   @Override
125   public void setFontStyle(int style)
126   {
127     viewStyle.setFontStyle(style);
128   }
129
130   /**
131    * @param size
132    * @see jalview.api.ViewStyleI#setFontSize(int)
133    */
134   @Override
135   public void setFontSize(int size)
136   {
137     viewStyle.setFontSize(size);
138   }
139
140   /**
141    * @return
142    * @see jalview.api.ViewStyleI#getFontStyle()
143    */
144   @Override
145   public int getFontStyle()
146   {
147     return viewStyle.getFontStyle();
148   }
149
150   /**
151    * @return
152    * @see jalview.api.ViewStyleI#getFontName()
153    */
154   @Override
155   public String getFontName()
156   {
157     return viewStyle.getFontName();
158   }
159
160   /**
161    * @return
162    * @see jalview.api.ViewStyleI#getFontSize()
163    */
164   @Override
165   public int getFontSize()
166   {
167     return viewStyle.getFontSize();
168   }
169
170   /**
171    * @param upperCasebold
172    * @see jalview.api.ViewStyleI#setUpperCasebold(boolean)
173    */
174   @Override
175   public void setUpperCasebold(boolean upperCasebold)
176   {
177     viewStyle.setUpperCasebold(upperCasebold);
178   }
179
180   /**
181    * @return
182    * @see jalview.api.ViewStyleI#isUpperCasebold()
183    */
184   @Override
185   public boolean isUpperCasebold()
186   {
187     return viewStyle.isUpperCasebold();
188   }
189
190   /**
191    * @return
192    * @see jalview.api.ViewStyleI#isSeqNameItalics()
193    */
194   @Override
195   public boolean isSeqNameItalics()
196   {
197     return viewStyle.isSeqNameItalics();
198   }
199
200   /**
201    * @param colourByReferenceSeq
202    * @see jalview.api.ViewStyleI#setColourByReferenceSeq(boolean)
203    */
204   @Override
205   public void setColourByReferenceSeq(boolean colourByReferenceSeq)
206   {
207     viewStyle.setColourByReferenceSeq(colourByReferenceSeq);
208   }
209
210   /**
211    * @param b
212    * @see jalview.api.ViewStyleI#setColourAppliesToAllGroups(boolean)
213    */
214   @Override
215   public void setColourAppliesToAllGroups(boolean b)
216   {
217     viewStyle.setColourAppliesToAllGroups(b);
218   }
219
220   /**
221    * @return
222    * @see jalview.api.ViewStyleI#getColourAppliesToAllGroups()
223    */
224   @Override
225   public boolean getColourAppliesToAllGroups()
226   {
227     return viewStyle.getColourAppliesToAllGroups();
228   }
229
230   /**
231    * @return
232    * @see jalview.api.ViewStyleI#getAbovePIDThreshold()
233    */
234   @Override
235   public boolean getAbovePIDThreshold()
236   {
237     return viewStyle.getAbovePIDThreshold();
238   }
239
240   /**
241    * @param inc
242    * @see jalview.api.ViewStyleI#setIncrement(int)
243    */
244   @Override
245   public void setIncrement(int inc)
246   {
247     viewStyle.setIncrement(inc);
248   }
249
250   /**
251    * @return
252    * @see jalview.api.ViewStyleI#getIncrement()
253    */
254   @Override
255   public int getIncrement()
256   {
257     return viewStyle.getIncrement();
258   }
259
260   /**
261    * @param b
262    * @see jalview.api.ViewStyleI#setConservationSelected(boolean)
263    */
264   @Override
265   public void setConservationSelected(boolean b)
266   {
267     viewStyle.setConservationSelected(b);
268   }
269
270   /**
271    * @param show
272    * @see jalview.api.ViewStyleI#setShowHiddenMarkers(boolean)
273    */
274   @Override
275   public void setShowHiddenMarkers(boolean show)
276   {
277     viewStyle.setShowHiddenMarkers(show);
278   }
279
280   /**
281    * @return
282    * @see jalview.api.ViewStyleI#getShowHiddenMarkers()
283    */
284   @Override
285   public boolean getShowHiddenMarkers()
286   {
287     return viewStyle.getShowHiddenMarkers();
288   }
289
290   /**
291    * @param b
292    * @see jalview.api.ViewStyleI#setScaleRightWrapped(boolean)
293    */
294   @Override
295   public void setScaleRightWrapped(boolean b)
296   {
297     viewStyle.setScaleRightWrapped(b);
298   }
299
300   /**
301    * @param b
302    * @see jalview.api.ViewStyleI#setScaleLeftWrapped(boolean)
303    */
304   @Override
305   public void setScaleLeftWrapped(boolean b)
306   {
307     viewStyle.setScaleLeftWrapped(b);
308   }
309
310   /**
311    * @param b
312    * @see jalview.api.ViewStyleI#setScaleAboveWrapped(boolean)
313    */
314   @Override
315   public void setScaleAboveWrapped(boolean b)
316   {
317     viewStyle.setScaleAboveWrapped(b);
318   }
319
320   /**
321    * @return
322    * @see jalview.api.ViewStyleI#getScaleLeftWrapped()
323    */
324   @Override
325   public boolean getScaleLeftWrapped()
326   {
327     return viewStyle.getScaleLeftWrapped();
328   }
329
330   /**
331    * @return
332    * @see jalview.api.ViewStyleI#getScaleAboveWrapped()
333    */
334   @Override
335   public boolean getScaleAboveWrapped()
336   {
337     return viewStyle.getScaleAboveWrapped();
338   }
339
340   /**
341    * @return
342    * @see jalview.api.ViewStyleI#getScaleRightWrapped()
343    */
344   @Override
345   public boolean getScaleRightWrapped()
346   {
347     return viewStyle.getScaleRightWrapped();
348   }
349
350   /**
351    * @param b
352    * @see jalview.api.ViewStyleI#setAbovePIDThreshold(boolean)
353    */
354   @Override
355   public void setAbovePIDThreshold(boolean b)
356   {
357     viewStyle.setAbovePIDThreshold(b);
358   }
359
360   /**
361    * @param thresh
362    * @see jalview.api.ViewStyleI#setThreshold(int)
363    */
364   @Override
365   public void setThreshold(int thresh)
366   {
367     viewStyle.setThreshold(thresh);
368   }
369
370   /**
371    * @return
372    * @see jalview.api.ViewStyleI#getThreshold()
373    */
374   @Override
375   public int getThreshold()
376   {
377     return viewStyle.getThreshold();
378   }
379
380   /**
381    * @return
382    * @see jalview.api.ViewStyleI#getShowJVSuffix()
383    */
384   @Override
385   public boolean getShowJVSuffix()
386   {
387     return viewStyle.getShowJVSuffix();
388   }
389
390   /**
391    * @param b
392    * @see jalview.api.ViewStyleI#setShowJVSuffix(boolean)
393    */
394   @Override
395   public void setShowJVSuffix(boolean b)
396   {
397     viewStyle.setShowJVSuffix(b);
398   }
399
400   /**
401    * @param state
402    * @see jalview.api.ViewStyleI#setWrapAlignment(boolean)
403    */
404   @Override
405   public void setWrapAlignment(boolean state)
406   {
407     viewStyle.setWrapAlignment(state);
408     ranges.setWrappedMode(state);
409   }
410
411   /**
412    * @param state
413    * @see jalview.api.ViewStyleI#setShowText(boolean)
414    */
415   @Override
416   public void setShowText(boolean state)
417   {
418     viewStyle.setShowText(state);
419   }
420
421   /**
422    * @param state
423    * @see jalview.api.ViewStyleI#setRenderGaps(boolean)
424    */
425   @Override
426   public void setRenderGaps(boolean state)
427   {
428     viewStyle.setRenderGaps(state);
429   }
430
431   /**
432    * @return
433    * @see jalview.api.ViewStyleI#getColourText()
434    */
435   @Override
436   public boolean getColourText()
437   {
438     return viewStyle.getColourText();
439   }
440
441   /**
442    * @param state
443    * @see jalview.api.ViewStyleI#setColourText(boolean)
444    */
445   @Override
446   public void setColourText(boolean state)
447   {
448     viewStyle.setColourText(state);
449   }
450
451   /**
452    * @return
453    * @see jalview.api.ViewStyleI#getWrapAlignment()
454    */
455   @Override
456   public boolean getWrapAlignment()
457   {
458     return viewStyle.getWrapAlignment();
459   }
460
461   /**
462    * @return
463    * @see jalview.api.ViewStyleI#getShowText()
464    */
465   @Override
466   public boolean getShowText()
467   {
468     return viewStyle.getShowText();
469   }
470
471   /**
472    * @return
473    * @see jalview.api.ViewStyleI#getWrappedWidth()
474    */
475   @Override
476   public int getWrappedWidth()
477   {
478     return viewStyle.getWrappedWidth();
479   }
480
481   /**
482    * @param w
483    * @see jalview.api.ViewStyleI#setWrappedWidth(int)
484    */
485   @Override
486   public void setWrappedWidth(int w)
487   {
488     viewStyle.setWrappedWidth(w);
489   }
490
491   /**
492    * @return
493    * @see jalview.api.ViewStyleI#getCharHeight()
494    */
495   @Override
496   public int getCharHeight()
497   {
498     return viewStyle.getCharHeight();
499   }
500
501   /**
502    * @param h
503    * @see jalview.api.ViewStyleI#setCharHeight(int)
504    */
505   @Override
506   public void setCharHeight(int h)
507   {
508     viewStyle.setCharHeight(h);
509   }
510
511   /**
512    * @return
513    * @see jalview.api.ViewStyleI#getCharWidth()
514    */
515   @Override
516   public int getCharWidth()
517   {
518     return viewStyle.getCharWidth();
519   }
520
521   /**
522    * @param w
523    * @see jalview.api.ViewStyleI#setCharWidth(int)
524    */
525   @Override
526   public void setCharWidth(int w)
527   {
528     viewStyle.setCharWidth(w);
529   }
530
531   /**
532    * @return
533    * @see jalview.api.ViewStyleI#getShowBoxes()
534    */
535   @Override
536   public boolean getShowBoxes()
537   {
538     return viewStyle.getShowBoxes();
539   }
540
541   /**
542    * @return
543    * @see jalview.api.ViewStyleI#getShowUnconserved()
544    */
545   @Override
546   public boolean getShowUnconserved()
547   {
548     return viewStyle.getShowUnconserved();
549   }
550
551   /**
552    * @param showunconserved
553    * @see jalview.api.ViewStyleI#setShowUnconserved(boolean)
554    */
555   @Override
556   public void setShowUnconserved(boolean showunconserved)
557   {
558     viewStyle.setShowUnconserved(showunconserved);
559   }
560
561   /**
562    * @param default1
563    * @see jalview.api.ViewStyleI#setSeqNameItalics(boolean)
564    */
565   @Override
566   public void setSeqNameItalics(boolean default1)
567   {
568     viewStyle.setSeqNameItalics(default1);
569   }
570
571
572
573   @Override
574   public AlignmentI getAlignment()
575   {
576     return alignment;
577   }
578
579   @Override
580   public char getGapCharacter()
581   {
582     return alignment.getGapCharacter();
583   }
584
585   protected String sequenceSetID;
586
587   /**
588    * probably unused indicator that view is of a dataset rather than an
589    * alignment
590    */
591   protected boolean isDataset = false;
592
593   public void setDataset(boolean b)
594   {
595     isDataset = b;
596   }
597
598   public boolean isDataset()
599   {
600     return isDataset;
601   }
602
603   private Map<SequenceI, SequenceCollectionI> hiddenRepSequences;
604
605   protected ColumnSelection colSel = new ColumnSelection();
606
607   public boolean autoCalculateConsensus = true;
608
609   protected boolean autoCalculateStrucConsensus = true;
610
611   protected boolean ignoreGapsInConsensusCalculation = false;
612
613   protected ResidueShaderI residueShading = new ResidueShader();
614
615   @Override
616   public void setGlobalColourScheme(ColourSchemeI cs)
617   {
618     // TODO: logic refactored from AlignFrame changeColour -
619     // TODO: autorecalc stuff should be changed to rely on the worker system
620     // check to see if we should implement a changeColour(cs) method rather than
621     // put the logic in here
622     // - means that caller decides if they want to just modify state and defer
623     // calculation till later or to do all calculations in thread.
624     // via changecolour
625
626     /*
627      * only instantiate alignment colouring once, thereafter update it;
628      * this means that any conservation or PID threshold settings
629      * persist when the alignment colour scheme is changed
630      */
631     if (residueShading == null)
632     {
633       residueShading = new ResidueShader(viewStyle);
634     }
635     residueShading.setColourScheme(cs);
636
637     // TODO: do threshold and increment belong in ViewStyle or ResidueShader?
638     // ...problem: groups need these, but do not currently have a ViewStyle
639
640     if (cs != null)
641     {
642       if (getConservationSelected())
643       {
644         int retry = 0;
645         synchronized (this)
646         {
647           while (isCalcInProgress() && retry < 10)
648           {
649             try
650             {
651               wait(50);
652               retry++;
653             } catch (InterruptedException e)
654             {
655             }
656           }
657         }
658         residueShading.setConservation(hconservation);
659       }
660       residueShading.alignmentChanged(alignment, hiddenRepSequences);
661     }
662
663     /*
664      * if 'apply colour to all groups' is selected... do so
665      * (but don't transfer any colour threshold settings to groups)
666      */
667     if (getColourAppliesToAllGroups())
668     {
669       for (SequenceGroup sg : getAlignment().getGroups())
670       {
671         /*
672          * retain any colour thresholds per group while
673          * changing choice of colour scheme (JAL-2386)
674          */
675         sg.setColourScheme(cs);
676         if (cs != null)
677         {
678           sg.getGroupColourScheme()
679                   .alignmentChanged(sg, hiddenRepSequences);
680         }
681       }
682     }
683   }
684
685   @Override
686   public ColourSchemeI getGlobalColourScheme()
687   {
688     return residueShading == null ? null : residueShading
689             .getColourScheme();
690   }
691
692   @Override
693   public ResidueShaderI getResidueShading()
694   {
695     return residueShading;
696   }
697
698   protected AlignmentAnnotation consensus;
699
700   protected AlignmentAnnotation complementConsensus;
701
702   protected AlignmentAnnotation gapcounts;
703
704   protected AlignmentAnnotation strucConsensus;
705
706   protected AlignmentAnnotation conservation;
707
708   protected AlignmentAnnotation quality;
709
710   protected AlignmentAnnotation[] groupConsensus;
711
712   protected AlignmentAnnotation[] groupConservation;
713
714   /**
715    * results of alignment consensus analysis for visible portion of view
716    */
717   protected ProfilesI hconsensus = null;
718
719   /**
720    * results of cDNA complement consensus visible portion of view
721    */
722   protected Hashtable[] hcomplementConsensus = null;
723
724   /**
725    * results of secondary structure base pair consensus for visible portion of
726    * view
727    */
728   protected Hashtable[] hStrucConsensus = null;
729
730   protected Conservation hconservation = null;
731
732   @Override
733   public void setConservation(Conservation cons)
734   {
735     hconservation = cons;
736   }
737
738   /**
739    * percentage gaps allowed in a column before all amino acid properties should
740    * be considered unconserved
741    */
742   int ConsPercGaps = 25; // JBPNote : This should be a scalable property!
743
744   @Override
745   public int getConsPercGaps()
746   {
747     return ConsPercGaps;
748   }
749
750   @Override
751   public void setSequenceConsensusHash(ProfilesI hconsensus)
752   {
753     this.hconsensus = hconsensus;
754   }
755
756   @Override
757   public void setComplementConsensusHash(Hashtable[] hconsensus)
758   {
759     this.hcomplementConsensus = hconsensus;
760   }
761
762   @Override
763   public ProfilesI getSequenceConsensusHash()
764   {
765     return hconsensus;
766   }
767
768   @Override
769   public Hashtable[] getComplementConsensusHash()
770   {
771     return hcomplementConsensus;
772   }
773
774   @Override
775   public Hashtable[] getRnaStructureConsensusHash()
776   {
777     return hStrucConsensus;
778   }
779
780   @Override
781   public void setRnaStructureConsensusHash(Hashtable[] hStrucConsensus)
782   {
783     this.hStrucConsensus = hStrucConsensus;
784
785   }
786
787   @Override
788   public AlignmentAnnotation getAlignmentQualityAnnot()
789   {
790     return quality;
791   }
792
793   @Override
794   public AlignmentAnnotation getAlignmentConservationAnnotation()
795   {
796     return conservation;
797   }
798
799   @Override
800   public AlignmentAnnotation getAlignmentConsensusAnnotation()
801   {
802     return consensus;
803   }
804
805   @Override
806   public AlignmentAnnotation getAlignmentGapAnnotation()
807   {
808     return gapcounts;
809   }
810
811   @Override
812   public AlignmentAnnotation getComplementConsensusAnnotation()
813   {
814     return complementConsensus;
815   }
816
817   @Override
818   public AlignmentAnnotation getAlignmentStrucConsensusAnnotation()
819   {
820     return strucConsensus;
821   }
822
823   protected AlignCalcManagerI calculator = new AlignCalcManager();
824
825   /**
826    * trigger update of conservation annotation
827    */
828   public void updateConservation(final AlignmentViewPanel ap)
829   {
830     // see note in mantis : issue number 8585
831     if (alignment.isNucleotide()
832             || (conservation == null && quality == null)
833             || !autoCalculateConsensus)
834     {
835       return;
836     }
837     if (calculator
838             .getRegisteredWorkersOfClass(jalview.workers.ConservationThread.class) == null)
839     {
840       calculator.registerWorker(new jalview.workers.ConservationThread(
841               this, ap));
842     }
843   }
844
845   /**
846    * trigger update of consensus annotation
847    */
848   public void updateConsensus(final AlignmentViewPanel ap)
849   {
850     // see note in mantis : issue number 8585
851     if (consensus == null || !autoCalculateConsensus)
852     {
853       return;
854     }
855     if (calculator.getRegisteredWorkersOfClass(ConsensusThread.class) == null)
856     {
857       calculator.registerWorker(new ConsensusThread(this, ap));
858     }
859
860     /*
861      * A separate thread to compute cDNA consensus for a protein alignment
862      * which has mapping to cDNA
863      */
864     final AlignmentI al = this.getAlignment();
865     if (!al.isNucleotide() && al.getCodonFrames() != null
866             && !al.getCodonFrames().isEmpty())
867     {
868       /*
869        * fudge - check first for protein-to-nucleotide mappings
870        * (we don't want to do this for protein-to-protein)
871        */
872       boolean doConsensus = false;
873       for (AlignedCodonFrame mapping : al.getCodonFrames())
874       {
875         // TODO hold mapping type e.g. dna-to-protein in AlignedCodonFrame?
876         MapList[] mapLists = mapping.getdnaToProt();
877         // mapLists can be empty if project load has not finished resolving seqs
878         if (mapLists.length > 0 && mapLists[0].getFromRatio() == 3)
879         {
880           doConsensus = true;
881           break;
882         }
883       }
884       if (doConsensus)
885       {
886         if (calculator
887                 .getRegisteredWorkersOfClass(ComplementConsensusThread.class) == null)
888         {
889           calculator
890                   .registerWorker(new ComplementConsensusThread(this, ap));
891         }
892       }
893     }
894   }
895
896   // --------START Structure Conservation
897   public void updateStrucConsensus(final AlignmentViewPanel ap)
898   {
899     if (autoCalculateStrucConsensus && strucConsensus == null
900             && alignment.isNucleotide() && alignment.hasRNAStructure())
901     {
902       // secondary structure has been added - so init the consensus line
903       initRNAStructure();
904     }
905
906     // see note in mantis : issue number 8585
907     if (strucConsensus == null || !autoCalculateStrucConsensus)
908     {
909       return;
910     }
911     if (calculator.getRegisteredWorkersOfClass(StrucConsensusThread.class) == null)
912     {
913       calculator.registerWorker(new StrucConsensusThread(this, ap));
914     }
915   }
916
917   public boolean isCalcInProgress()
918   {
919     return calculator.isWorking();
920   }
921
922   @Override
923   public boolean isCalculationInProgress(
924           AlignmentAnnotation alignmentAnnotation)
925   {
926     if (!alignmentAnnotation.autoCalculated)
927     {
928       return false;
929     }
930     if (calculator.workingInvolvedWith(alignmentAnnotation))
931     {
932       // System.err.println("grey out ("+alignmentAnnotation.label+")");
933       return true;
934     }
935     return false;
936   }
937
938   public void setAlignment(AlignmentI align)
939   {
940     this.alignment = align;
941   }
942
943   /**
944    * Clean up references when this viewport is closed
945    */
946   @Override
947   public void dispose()
948   {
949     /*
950      * defensively null out references to large objects in case
951      * this object is not garbage collected (as if!)
952      */
953     consensus = null;
954     complementConsensus = null;
955     strucConsensus = null;
956     conservation = null;
957     quality = null;
958     groupConsensus = null;
959     groupConservation = null;
960     hconsensus = null;
961     hcomplementConsensus = null;
962     // colour scheme may hold reference to consensus
963     residueShading = null;
964     // TODO remove listeners from changeSupport?
965     changeSupport = null;
966     setAlignment(null);
967   }
968
969   @Override
970   public boolean isClosed()
971   {
972     // TODO: check that this isClosed is only true after panel is closed, not
973     // before it is fully constructed.
974     return alignment == null;
975   }
976
977   @Override
978   public AlignCalcManagerI getCalcManager()
979   {
980     return calculator;
981   }
982
983   /**
984    * should conservation rows be shown for groups
985    */
986   protected boolean showGroupConservation = false;
987
988   /**
989    * should consensus rows be shown for groups
990    */
991   protected boolean showGroupConsensus = false;
992
993   /**
994    * should consensus profile be rendered by default
995    */
996   protected boolean showSequenceLogo = false;
997
998   /**
999    * should consensus profile be rendered normalised to row height
1000    */
1001   protected boolean normaliseSequenceLogo = false;
1002
1003   /**
1004    * should consensus histograms be rendered by default
1005    */
1006   protected boolean showConsensusHistogram = true;
1007
1008   /**
1009    * @return the showConsensusProfile
1010    */
1011   @Override
1012   public boolean isShowSequenceLogo()
1013   {
1014     return showSequenceLogo;
1015   }
1016
1017   /**
1018    * @param showSequenceLogo
1019    *          the new value
1020    */
1021   public void setShowSequenceLogo(boolean showSequenceLogo)
1022   {
1023     if (showSequenceLogo != this.showSequenceLogo)
1024     {
1025       // TODO: decouple settings setting from calculation when refactoring
1026       // annotation update method from alignframe to viewport
1027       this.showSequenceLogo = showSequenceLogo;
1028       calculator.updateAnnotationFor(ConsensusThread.class);
1029       calculator.updateAnnotationFor(ComplementConsensusThread.class);
1030       calculator.updateAnnotationFor(StrucConsensusThread.class);
1031     }
1032     this.showSequenceLogo = showSequenceLogo;
1033   }
1034
1035   /**
1036    * @param showConsensusHistogram
1037    *          the showConsensusHistogram to set
1038    */
1039   public void setShowConsensusHistogram(boolean showConsensusHistogram)
1040   {
1041     this.showConsensusHistogram = showConsensusHistogram;
1042   }
1043
1044   /**
1045    * @return the showGroupConservation
1046    */
1047   public boolean isShowGroupConservation()
1048   {
1049     return showGroupConservation;
1050   }
1051
1052   /**
1053    * @param showGroupConservation
1054    *          the showGroupConservation to set
1055    */
1056   public void setShowGroupConservation(boolean showGroupConservation)
1057   {
1058     this.showGroupConservation = showGroupConservation;
1059   }
1060
1061   /**
1062    * @return the showGroupConsensus
1063    */
1064   public boolean isShowGroupConsensus()
1065   {
1066     return showGroupConsensus;
1067   }
1068
1069   /**
1070    * @param showGroupConsensus
1071    *          the showGroupConsensus to set
1072    */
1073   public void setShowGroupConsensus(boolean showGroupConsensus)
1074   {
1075     this.showGroupConsensus = showGroupConsensus;
1076   }
1077
1078   /**
1079    * 
1080    * @return flag to indicate if the consensus histogram should be rendered by
1081    *         default
1082    */
1083   @Override
1084   public boolean isShowConsensusHistogram()
1085   {
1086     return this.showConsensusHistogram;
1087   }
1088
1089   /**
1090    * when set, updateAlignment will always ensure sequences are of equal length
1091    */
1092   private boolean padGaps = false;
1093
1094   /**
1095    * when set, alignment should be reordered according to a newly opened tree
1096    */
1097   public boolean sortByTree = false;
1098
1099   /**
1100    * 
1101    * 
1102    * @return null or the currently selected sequence region
1103    */
1104   @Override
1105   public SequenceGroup getSelectionGroup()
1106   {
1107     return selectionGroup;
1108   }
1109
1110   /**
1111    * Set the selection group for this window. Also sets the current alignment as
1112    * the context for the group, if it does not already have one.
1113    * 
1114    * @param sg
1115    *          - group holding references to sequences in this alignment view
1116    * 
1117    */
1118   @Override
1119   public void setSelectionGroup(SequenceGroup sg)
1120   {
1121     selectionGroup = sg;
1122     if (sg != null && sg.getContext() == null)
1123     {
1124       sg.setContext(alignment);
1125     }
1126   }
1127
1128   public void setHiddenColumns(HiddenColumns hidden)
1129   {
1130     this.alignment.setHiddenColumns(hidden);
1131   }
1132
1133   @Override
1134   public ColumnSelection getColumnSelection()
1135   {
1136     return colSel;
1137   }
1138
1139   @Override
1140   public void setColumnSelection(ColumnSelection colSel)
1141   {
1142     this.colSel = colSel;
1143     if (colSel != null)
1144     {
1145       updateHiddenColumns();
1146     }
1147     isColSelChanged(true);
1148   }
1149
1150   /**
1151    * 
1152    * @return
1153    */
1154   @Override
1155   public Map<SequenceI, SequenceCollectionI> getHiddenRepSequences()
1156   {
1157     return hiddenRepSequences;
1158   }
1159
1160   @Override
1161   public void setHiddenRepSequences(
1162           Map<SequenceI, SequenceCollectionI> hiddenRepSequences)
1163   {
1164     this.hiddenRepSequences = hiddenRepSequences;
1165   }
1166
1167   @Override
1168   public boolean hasSelectedColumns()
1169   {
1170     ColumnSelection columnSelection = getColumnSelection();
1171     return columnSelection != null && columnSelection.hasSelectedColumns();
1172   }
1173
1174   @Override
1175   public boolean hasHiddenColumns()
1176   {
1177     return alignment.getHiddenColumns() != null
1178             && alignment.getHiddenColumns().hasHiddenColumns();
1179   }
1180
1181   public void updateHiddenColumns()
1182   {
1183     // this method doesn't really do anything now. But - it could, since a
1184     // column Selection could be in the process of modification
1185     // hasHiddenColumns = colSel.hasHiddenColumns();
1186   }
1187
1188   @Override
1189   public boolean hasHiddenRows()
1190   {
1191     return alignment.getHiddenSequences().getSize() > 0;
1192   }
1193
1194   protected SequenceGroup selectionGroup;
1195
1196   public void setSequenceSetId(String newid)
1197   {
1198     if (sequenceSetID != null)
1199     {
1200       System.err
1201               .println("Warning - overwriting a sequenceSetId for a viewport!");
1202     }
1203     sequenceSetID = new String(newid);
1204   }
1205
1206   @Override
1207   public String getSequenceSetId()
1208   {
1209     if (sequenceSetID == null)
1210     {
1211       sequenceSetID = alignment.hashCode() + "";
1212     }
1213
1214     return sequenceSetID;
1215   }
1216
1217   /**
1218    * unique viewId for synchronizing state (e.g. with stored Jalview Project)
1219    * 
1220    */
1221   protected String viewId = null;
1222
1223   @Override
1224   public String getViewId()
1225   {
1226     if (viewId == null)
1227     {
1228       viewId = this.getSequenceSetId() + "." + this.hashCode() + "";
1229     }
1230     return viewId;
1231   }
1232
1233   public void setIgnoreGapsConsensus(boolean b, AlignmentViewPanel ap)
1234   {
1235     ignoreGapsInConsensusCalculation = b;
1236     if (ap != null)
1237     {
1238       updateConsensus(ap);
1239       if (residueShading != null)
1240       {
1241         residueShading.setThreshold(residueShading.getThreshold(),
1242                 ignoreGapsInConsensusCalculation);
1243       }
1244     }
1245
1246   }
1247
1248   private long sgrouphash = -1, colselhash = -1;
1249
1250   /**
1251    * checks current SelectionGroup against record of last hash value, and
1252    * updates record.
1253    * 
1254    * @param b
1255    *          update the record of last hash value
1256    * 
1257    * @return true if SelectionGroup changed since last call (when b is true)
1258    */
1259   public boolean isSelectionGroupChanged(boolean b)
1260   {
1261     int hc = (selectionGroup == null || selectionGroup.getSize() == 0) ? -1
1262             : selectionGroup.hashCode();
1263     if (hc != -1 && hc != sgrouphash)
1264     {
1265       if (b)
1266       {
1267         sgrouphash = hc;
1268       }
1269       return true;
1270     }
1271     return false;
1272   }
1273
1274   /**
1275    * checks current colsel against record of last hash value, and optionally
1276    * updates record.
1277    * 
1278    * @param b
1279    *          update the record of last hash value
1280    * @return true if colsel changed since last call (when b is true)
1281    */
1282   public boolean isColSelChanged(boolean b)
1283   {
1284     int hc = (colSel == null || colSel.isEmpty()) ? -1 : colSel.hashCode();
1285     if (hc != -1 && hc != colselhash)
1286     {
1287       if (b)
1288       {
1289         colselhash = hc;
1290       }
1291       return true;
1292     }
1293     return false;
1294   }
1295
1296   @Override
1297   public boolean isIgnoreGapsConsensus()
1298   {
1299     return ignoreGapsInConsensusCalculation;
1300   }
1301
1302   // property change stuff
1303   // JBPNote Prolly only need this in the applet version.
1304   private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
1305           this);
1306
1307   protected boolean showConservation = true;
1308
1309   protected boolean showQuality = true;
1310
1311   protected boolean showConsensus = true;
1312
1313   protected boolean showOccupancy = true;
1314
1315   private Map<SequenceI, Color> sequenceColours = new HashMap<>();
1316
1317   protected SequenceAnnotationOrder sortAnnotationsBy = null;
1318
1319   protected boolean showAutocalculatedAbove;
1320
1321   /**
1322    * when set, view will scroll to show the highlighted position
1323    */
1324   private boolean followHighlight = true;
1325
1326   /**
1327    * Property change listener for changes in alignment
1328    * 
1329    * @param listener
1330    *          DOCUMENT ME!
1331    */
1332   public void addPropertyChangeListener(
1333           java.beans.PropertyChangeListener listener)
1334   {
1335     changeSupport.addPropertyChangeListener(listener);
1336   }
1337
1338   /**
1339    * DOCUMENT ME!
1340    * 
1341    * @param listener
1342    *          DOCUMENT ME!
1343    */
1344   public void removePropertyChangeListener(
1345           java.beans.PropertyChangeListener listener)
1346   {
1347     changeSupport.removePropertyChangeListener(listener);
1348   }
1349
1350   /**
1351    * Property change listener for changes in alignment
1352    * 
1353    * @param prop
1354    *          DOCUMENT ME!
1355    * @param oldvalue
1356    *          DOCUMENT ME!
1357    * @param newvalue
1358    *          DOCUMENT ME!
1359    */
1360   public void firePropertyChange(String prop, Object oldvalue,
1361           Object newvalue)
1362   {
1363     changeSupport.firePropertyChange(prop, oldvalue, newvalue);
1364   }
1365
1366   // common hide/show column stuff
1367
1368   public void hideSelectedColumns()
1369   {
1370     if (colSel.isEmpty())
1371     {
1372       return;
1373     }
1374
1375     colSel.hideSelectedColumns(alignment);
1376     setSelectionGroup(null);
1377     isColSelChanged(true);
1378   }
1379
1380   public void hideColumns(int start, int end)
1381   {
1382     if (start == end)
1383     {
1384       colSel.hideSelectedColumns(start, alignment.getHiddenColumns());
1385     }
1386     else
1387     {
1388       alignment.getHiddenColumns().hideColumns(start, end);
1389     }
1390     isColSelChanged(true);
1391   }
1392
1393   public void showColumn(int col)
1394   {
1395     alignment.getHiddenColumns().revealHiddenColumns(col, colSel);
1396     isColSelChanged(true);
1397   }
1398
1399   public void showAllHiddenColumns()
1400   {
1401     alignment.getHiddenColumns().revealAllHiddenColumns(colSel);
1402     isColSelChanged(true);
1403   }
1404
1405   // common hide/show seq stuff
1406   public void showAllHiddenSeqs()
1407   {
1408     int startSeq = ranges.getStartSeq();
1409     int endSeq = ranges.getEndSeq();
1410
1411     if (alignment.getHiddenSequences().getSize() > 0)
1412     {
1413       if (selectionGroup == null)
1414       {
1415         selectionGroup = new SequenceGroup();
1416         selectionGroup.setEndRes(alignment.getWidth() - 1);
1417       }
1418       List<SequenceI> tmp = alignment.getHiddenSequences().showAll(
1419               hiddenRepSequences);
1420       for (SequenceI seq : tmp)
1421       {
1422         selectionGroup.addSequence(seq, false);
1423         setSequenceAnnotationsVisible(seq, true);
1424       }
1425
1426       hiddenRepSequences = null;
1427
1428       ranges.setStartEndSeq(startSeq, endSeq + tmp.size());
1429
1430       firePropertyChange("alignment", null, alignment.getSequences());
1431       // used to set hasHiddenRows/hiddenRepSequences here, after the property
1432       // changed event
1433       sendSelection();
1434     }
1435   }
1436
1437   public void showSequence(int index)
1438   {
1439     int startSeq = ranges.getStartSeq();
1440     int endSeq = ranges.getEndSeq();
1441
1442     List<SequenceI> tmp = alignment.getHiddenSequences().showSequence(
1443             index, hiddenRepSequences);
1444     if (tmp.size() > 0)
1445     {
1446       if (selectionGroup == null)
1447       {
1448         selectionGroup = new SequenceGroup();
1449         selectionGroup.setEndRes(alignment.getWidth() - 1);
1450       }
1451
1452       for (SequenceI seq : tmp)
1453       {
1454         selectionGroup.addSequence(seq, false);
1455         setSequenceAnnotationsVisible(seq, true);
1456       }
1457
1458       ranges.setStartEndSeq(startSeq, endSeq + tmp.size());
1459
1460       firePropertyChange("alignment", null, alignment.getSequences());
1461       sendSelection();
1462     }
1463   }
1464
1465   public void hideAllSelectedSeqs()
1466   {
1467     if (selectionGroup == null || selectionGroup.getSize() < 1)
1468     {
1469       return;
1470     }
1471
1472     SequenceI[] seqs = selectionGroup.getSequencesInOrder(alignment);
1473
1474     hideSequence(seqs);
1475
1476     setSelectionGroup(null);
1477   }
1478
1479   public void hideSequence(SequenceI[] seq)
1480   {
1481     /*
1482      * cache offset to first visible sequence
1483      */
1484     int startSeq = ranges.getStartSeq();
1485
1486     if (seq != null)
1487     {
1488       for (int i = 0; i < seq.length; i++)
1489       {
1490         alignment.getHiddenSequences().hideSequence(seq[i]);
1491         setSequenceAnnotationsVisible(seq[i], false);
1492       }
1493       ranges.setStartSeq(startSeq);
1494       firePropertyChange("alignment", null, alignment.getSequences());
1495     }
1496   }
1497
1498   /**
1499    * Hides the specified sequence, or the sequences it represents
1500    * 
1501    * @param sequence
1502    *          the sequence to hide, or keep as representative
1503    * @param representGroup
1504    *          if true, hide the current selection group except for the
1505    *          representative sequence
1506    */
1507   public void hideSequences(SequenceI sequence, boolean representGroup)
1508   {
1509     if (selectionGroup == null || selectionGroup.getSize() < 1)
1510     {
1511       hideSequence(new SequenceI[] { sequence });
1512       return;
1513     }
1514
1515     if (representGroup)
1516     {
1517       hideRepSequences(sequence, selectionGroup);
1518       setSelectionGroup(null);
1519       return;
1520     }
1521
1522     int gsize = selectionGroup.getSize();
1523     SequenceI[] hseqs = selectionGroup.getSequences().toArray(
1524             new SequenceI[gsize]);
1525
1526     hideSequence(hseqs);
1527     setSelectionGroup(null);
1528     sendSelection();
1529   }
1530
1531   /**
1532    * Set visibility for any annotations for the given sequence.
1533    * 
1534    * @param sequenceI
1535    */
1536   protected void setSequenceAnnotationsVisible(SequenceI sequenceI,
1537           boolean visible)
1538   {
1539     AlignmentAnnotation[] anns = alignment.getAlignmentAnnotation();
1540     if (anns != null)
1541     {
1542       for (AlignmentAnnotation ann : anns)
1543       {
1544         if (ann.sequenceRef == sequenceI)
1545         {
1546           ann.visible = visible;
1547         }
1548       }
1549     }
1550   }
1551
1552   public void hideRepSequences(SequenceI repSequence, SequenceGroup sg)
1553   {
1554     int sSize = sg.getSize();
1555     if (sSize < 2)
1556     {
1557       return;
1558     }
1559
1560     if (hiddenRepSequences == null)
1561     {
1562       hiddenRepSequences = new Hashtable<>();
1563     }
1564
1565     hiddenRepSequences.put(repSequence, sg);
1566
1567     // Hide all sequences except the repSequence
1568     SequenceI[] seqs = new SequenceI[sSize - 1];
1569     int index = 0;
1570     for (int i = 0; i < sSize; i++)
1571     {
1572       if (sg.getSequenceAt(i) != repSequence)
1573       {
1574         if (index == sSize - 1)
1575         {
1576           return;
1577         }
1578
1579         seqs[index++] = sg.getSequenceAt(i);
1580       }
1581     }
1582     sg.setSeqrep(repSequence); // note: not done in 2.7applet
1583     sg.setHidereps(true); // note: not done in 2.7applet
1584     hideSequence(seqs);
1585
1586   }
1587
1588   /**
1589    * 
1590    * @return null or the current reference sequence
1591    */
1592   public SequenceI getReferenceSeq()
1593   {
1594     return alignment.getSeqrep();
1595   }
1596
1597   /**
1598    * @param seq
1599    * @return true iff seq is the reference for the alignment
1600    */
1601   public boolean isReferenceSeq(SequenceI seq)
1602   {
1603     return alignment.getSeqrep() == seq;
1604   }
1605
1606   /**
1607    * 
1608    * @param seq
1609    * @return true if there are sequences represented by this sequence that are
1610    *         currently hidden
1611    */
1612   public boolean isHiddenRepSequence(SequenceI seq)
1613   {
1614     return (hiddenRepSequences != null && hiddenRepSequences
1615             .containsKey(seq));
1616   }
1617
1618   /**
1619    * 
1620    * @param seq
1621    * @return null or a sequence group containing the sequences that seq
1622    *         represents
1623    */
1624   public SequenceGroup getRepresentedSequences(SequenceI seq)
1625   {
1626     return (SequenceGroup) (hiddenRepSequences == null ? null
1627             : hiddenRepSequences.get(seq));
1628   }
1629
1630   @Override
1631   public int adjustForHiddenSeqs(int alignmentIndex)
1632   {
1633     return alignment.getHiddenSequences().adjustForHiddenSeqs(
1634             alignmentIndex);
1635   }
1636
1637   @Override
1638   public void invertColumnSelection()
1639   {
1640     colSel.invertColumnSelection(0, alignment.getWidth(), alignment);
1641   }
1642
1643   @Override
1644   public SequenceI[] getSelectionAsNewSequence()
1645   {
1646     SequenceI[] sequences;
1647     // JBPNote: Need to test jalviewLite.getSelectedSequencesAsAlignmentFrom -
1648     // this was the only caller in the applet for this method
1649     // JBPNote: in applet, this method returned references to the alignment
1650     // sequences, and it did not honour the presence/absence of annotation
1651     // attached to the alignment (probably!)
1652     if (selectionGroup == null || selectionGroup.getSize() == 0)
1653     {
1654       sequences = alignment.getSequencesArray();
1655       AlignmentAnnotation[] annots = alignment.getAlignmentAnnotation();
1656       for (int i = 0; i < sequences.length; i++)
1657       {
1658         // construct new sequence with subset of visible annotation
1659         sequences[i] = new Sequence(sequences[i], annots);
1660       }
1661     }
1662     else
1663     {
1664       sequences = selectionGroup.getSelectionAsNewSequences(alignment);
1665     }
1666
1667     return sequences;
1668   }
1669
1670   @Override
1671   public SequenceI[] getSequenceSelection()
1672   {
1673     SequenceI[] sequences = null;
1674     if (selectionGroup != null)
1675     {
1676       sequences = selectionGroup.getSequencesInOrder(alignment);
1677     }
1678     if (sequences == null)
1679     {
1680       sequences = alignment.getSequencesArray();
1681     }
1682     return sequences;
1683   }
1684
1685   @Override
1686   public CigarArray getViewAsCigars(boolean selectedRegionOnly)
1687   {
1688     return new CigarArray(alignment, alignment.getHiddenColumns(),
1689             (selectedRegionOnly ? selectionGroup : null));
1690   }
1691
1692   @Override
1693   public jalview.datamodel.AlignmentView getAlignmentView(
1694           boolean selectedOnly)
1695   {
1696     return getAlignmentView(selectedOnly, false);
1697   }
1698
1699   @Override
1700   public jalview.datamodel.AlignmentView getAlignmentView(
1701           boolean selectedOnly, boolean markGroups)
1702   {
1703     return new AlignmentView(alignment, alignment.getHiddenColumns(),
1704             selectionGroup, alignment.getHiddenColumns() != null
1705                     && alignment.getHiddenColumns().hasHiddenColumns(),
1706             selectedOnly,
1707             markGroups);
1708   }
1709
1710   @Override
1711   public String[] getViewAsString(boolean selectedRegionOnly)
1712   {
1713     return getViewAsString(selectedRegionOnly, true);
1714   }
1715
1716   @Override
1717   public String[] getViewAsString(boolean selectedRegionOnly,
1718           boolean exportHiddenSeqs)
1719   {
1720     String[] selection = null;
1721     SequenceI[] seqs = null;
1722     int i, iSize;
1723     int start = 0, end = 0;
1724     if (selectedRegionOnly && selectionGroup != null)
1725     {
1726       iSize = selectionGroup.getSize();
1727       seqs = selectionGroup.getSequencesInOrder(alignment);
1728       start = selectionGroup.getStartRes();
1729       end = selectionGroup.getEndRes() + 1;
1730     }
1731     else
1732     {
1733       if (hasHiddenRows() && exportHiddenSeqs)
1734       {
1735         AlignmentI fullAlignment = alignment.getHiddenSequences()
1736                 .getFullAlignment();
1737         iSize = fullAlignment.getHeight();
1738         seqs = fullAlignment.getSequencesArray();
1739         end = fullAlignment.getWidth();
1740       }
1741       else
1742       {
1743         iSize = alignment.getHeight();
1744         seqs = alignment.getSequencesArray();
1745         end = alignment.getWidth();
1746       }
1747     }
1748
1749     selection = new String[iSize];
1750     if (alignment.getHiddenColumns() != null
1751             && alignment.getHiddenColumns().hasHiddenColumns())
1752     {
1753       selection = alignment.getHiddenColumns().getVisibleSequenceStrings(
1754               start, end, seqs);
1755     }
1756     else
1757     {
1758       for (i = 0; i < iSize; i++)
1759       {
1760         selection[i] = seqs[i].getSequenceAsString(start, end);
1761       }
1762
1763     }
1764     return selection;
1765   }
1766
1767   @Override
1768   public List<int[]> getVisibleRegionBoundaries(int min, int max)
1769   {
1770     ArrayList<int[]> regions = new ArrayList<>();
1771     int start = min;
1772     int end = max;
1773
1774     do
1775     {
1776       HiddenColumns hidden = alignment.getHiddenColumns();
1777       if (hidden != null && hidden.hasHiddenColumns())
1778       {
1779         if (start == 0)
1780         {
1781           start = hidden.adjustForHiddenColumns(start);
1782         }
1783
1784         end = hidden.getHiddenBoundaryRight(start);
1785         if (start == end)
1786         {
1787           end = max;
1788         }
1789         if (end > max)
1790         {
1791           end = max;
1792         }
1793       }
1794
1795       regions.add(new int[] { start, end });
1796
1797       if (hidden != null && hidden.hasHiddenColumns())
1798       {
1799         start = hidden.adjustForHiddenColumns(end);
1800         start = hidden.getHiddenBoundaryLeft(start) + 1;
1801       }
1802     } while (end < max);
1803
1804     int[][] startEnd = new int[regions.size()][2];
1805
1806     return regions;
1807   }
1808
1809   @Override
1810   public List<AlignmentAnnotation> getVisibleAlignmentAnnotation(
1811           boolean selectedOnly)
1812   {
1813     ArrayList<AlignmentAnnotation> ala = new ArrayList<>();
1814     AlignmentAnnotation[] aa;
1815     if ((aa = alignment.getAlignmentAnnotation()) != null)
1816     {
1817       for (AlignmentAnnotation annot : aa)
1818       {
1819         AlignmentAnnotation clone = new AlignmentAnnotation(annot);
1820         if (selectedOnly && selectionGroup != null)
1821         {
1822           alignment.getHiddenColumns().makeVisibleAnnotation(
1823                   selectionGroup.getStartRes(),
1824                   selectionGroup.getEndRes(), clone);
1825         }
1826         else
1827         {
1828           alignment.getHiddenColumns().makeVisibleAnnotation(clone);
1829         }
1830         ala.add(clone);
1831       }
1832     }
1833     return ala;
1834   }
1835
1836   @Override
1837   public boolean isPadGaps()
1838   {
1839     return padGaps;
1840   }
1841
1842   @Override
1843   public void setPadGaps(boolean padGaps)
1844   {
1845     this.padGaps = padGaps;
1846   }
1847
1848   /**
1849    * apply any post-edit constraints and trigger any calculations needed after
1850    * an edit has been performed on the alignment
1851    * 
1852    * @param ap
1853    */
1854   @Override
1855   public void alignmentChanged(AlignmentViewPanel ap)
1856   {
1857     if (isPadGaps())
1858     {
1859       alignment.padGaps();
1860     }
1861     if (autoCalculateConsensus)
1862     {
1863       updateConsensus(ap);
1864     }
1865     if (hconsensus != null && autoCalculateConsensus)
1866     {
1867       updateConservation(ap);
1868     }
1869     if (autoCalculateStrucConsensus)
1870     {
1871       updateStrucConsensus(ap);
1872     }
1873
1874     // Reset endRes of groups if beyond alignment width
1875     int alWidth = alignment.getWidth();
1876     List<SequenceGroup> groups = alignment.getGroups();
1877     if (groups != null)
1878     {
1879       for (SequenceGroup sg : groups)
1880       {
1881         if (sg.getEndRes() > alWidth)
1882         {
1883           sg.setEndRes(alWidth - 1);
1884         }
1885       }
1886     }
1887
1888     if (selectionGroup != null && selectionGroup.getEndRes() > alWidth)
1889     {
1890       selectionGroup.setEndRes(alWidth - 1);
1891     }
1892
1893     updateAllColourSchemes();
1894     calculator.restartWorkers();
1895     // alignment.adjustSequenceAnnotations();
1896   }
1897
1898   /**
1899    * reset scope and do calculations for all applied colourschemes on alignment
1900    */
1901   void updateAllColourSchemes()
1902   {
1903     ResidueShaderI rs = residueShading;
1904     if (rs != null)
1905     {
1906       rs.alignmentChanged(alignment, hiddenRepSequences);
1907
1908       rs.setConsensus(hconsensus);
1909       if (rs.conservationApplied())
1910       {
1911         rs.setConservation(Conservation.calculateConservation("All",
1912                 alignment.getSequences(), 0, alignment.getWidth(), false,
1913                 getConsPercGaps(), false));
1914       }
1915     }
1916
1917     for (SequenceGroup sg : alignment.getGroups())
1918     {
1919       if (sg.cs != null)
1920       {
1921         sg.cs.alignmentChanged(sg, hiddenRepSequences);
1922       }
1923       sg.recalcConservation();
1924     }
1925   }
1926
1927   protected void initAutoAnnotation()
1928   {
1929     // TODO: add menu option action that nulls or creates consensus object
1930     // depending on if the user wants to see the annotation or not in a
1931     // specific alignment
1932
1933     if (hconsensus == null && !isDataset)
1934     {
1935       if (!alignment.isNucleotide())
1936       {
1937         initConservation();
1938         initQuality();
1939       }
1940       else
1941       {
1942         initRNAStructure();
1943       }
1944       consensus = new AlignmentAnnotation("Consensus",
1945               MessageManager.getString("label.consensus_descr"),
1946               new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH);
1947       initConsensus(consensus);
1948       initGapCounts();
1949
1950       initComplementConsensus();
1951     }
1952   }
1953
1954   /**
1955    * If this is a protein alignment and there are mappings to cDNA, adds the
1956    * cDNA consensus annotation and returns true, else returns false.
1957    */
1958   public boolean initComplementConsensus()
1959   {
1960     if (!alignment.isNucleotide())
1961     {
1962       final List<AlignedCodonFrame> codonMappings = alignment
1963               .getCodonFrames();
1964       if (codonMappings != null && !codonMappings.isEmpty())
1965       {
1966         boolean doConsensus = false;
1967         for (AlignedCodonFrame mapping : codonMappings)
1968         {
1969           // TODO hold mapping type e.g. dna-to-protein in AlignedCodonFrame?
1970           MapList[] mapLists = mapping.getdnaToProt();
1971           // mapLists can be empty if project load has not finished resolving
1972           // seqs
1973           if (mapLists.length > 0 && mapLists[0].getFromRatio() == 3)
1974           {
1975             doConsensus = true;
1976             break;
1977           }
1978         }
1979         if (doConsensus)
1980         {
1981           complementConsensus = new AlignmentAnnotation("cDNA Consensus",
1982                   MessageManager
1983                           .getString("label.complement_consensus_descr"),
1984                   new Annotation[1], 0f, 100f,
1985                   AlignmentAnnotation.BAR_GRAPH);
1986           initConsensus(complementConsensus);
1987           return true;
1988         }
1989       }
1990     }
1991     return false;
1992   }
1993
1994   private void initConsensus(AlignmentAnnotation aa)
1995   {
1996     aa.hasText = true;
1997     aa.autoCalculated = true;
1998
1999     if (showConsensus)
2000     {
2001       alignment.addAnnotation(aa);
2002     }
2003   }
2004
2005   // these should be extracted from the view model - style and settings for
2006   // derived annotation
2007   private void initGapCounts()
2008   {
2009     if (showOccupancy)
2010     {
2011       gapcounts = new AlignmentAnnotation("Occupancy",
2012               MessageManager.getString("label.occupancy_descr"),
2013               new Annotation[1], 0f,
2014               alignment.getHeight(), AlignmentAnnotation.BAR_GRAPH);
2015       gapcounts.hasText = true;
2016       gapcounts.autoCalculated = true;
2017       gapcounts.scaleColLabel = true;
2018       gapcounts.graph = AlignmentAnnotation.BAR_GRAPH;
2019
2020       alignment.addAnnotation(gapcounts);
2021     }
2022   }
2023
2024   private void initConservation()
2025   {
2026     if (showConservation)
2027     {
2028       if (conservation == null)
2029       {
2030         conservation = new AlignmentAnnotation("Conservation",
2031                 MessageManager.formatMessage("label.conservation_descr",
2032                         getConsPercGaps()), new Annotation[1],
2033                 0f, 11f, AlignmentAnnotation.BAR_GRAPH);
2034         conservation.hasText = true;
2035         conservation.autoCalculated = true;
2036         alignment.addAnnotation(conservation);
2037       }
2038     }
2039   }
2040
2041   private void initQuality()
2042   {
2043     if (showQuality)
2044     {
2045       if (quality == null)
2046       {
2047         quality = new AlignmentAnnotation("Quality",
2048                 MessageManager.getString("label.quality_descr"),
2049                 new Annotation[1], 0f, 11f, AlignmentAnnotation.BAR_GRAPH);
2050         quality.hasText = true;
2051         quality.autoCalculated = true;
2052         alignment.addAnnotation(quality);
2053       }
2054     }
2055   }
2056
2057   private void initRNAStructure()
2058   {
2059     if (alignment.hasRNAStructure() && strucConsensus == null)
2060     {
2061       strucConsensus = new AlignmentAnnotation("StrucConsensus",
2062               MessageManager.getString("label.strucconsensus_descr"),
2063               new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH);
2064       strucConsensus.hasText = true;
2065       strucConsensus.autoCalculated = true;
2066
2067       if (showConsensus)
2068       {
2069         alignment.addAnnotation(strucConsensus);
2070       }
2071     }
2072   }
2073
2074   /*
2075    * (non-Javadoc)
2076    * 
2077    * @see jalview.api.AlignViewportI#calcPanelHeight()
2078    */
2079   @Override
2080   public int calcPanelHeight()
2081   {
2082     // setHeight of panels
2083     AlignmentAnnotation[] anns = getAlignment().getAlignmentAnnotation();
2084     int height = 0;
2085     int charHeight = getCharHeight();
2086     if (anns != null)
2087     {
2088       BitSet graphgrp = new BitSet();
2089       for (AlignmentAnnotation aa : anns)
2090       {
2091         if (aa == null)
2092         {
2093           System.err.println("Null annotation row: ignoring.");
2094           continue;
2095         }
2096         if (!aa.visible)
2097         {
2098           continue;
2099         }
2100         if (aa.graphGroup > -1)
2101         {
2102           if (graphgrp.get(aa.graphGroup))
2103           {
2104             continue;
2105           }
2106           else
2107           {
2108             graphgrp.set(aa.graphGroup);
2109           }
2110         }
2111         aa.height = 0;
2112
2113         if (aa.hasText)
2114         {
2115           aa.height += charHeight;
2116         }
2117
2118         if (aa.hasIcons)
2119         {
2120           aa.height += 16;
2121         }
2122
2123         if (aa.graph > 0)
2124         {
2125           aa.height += aa.graphHeight;
2126         }
2127
2128         if (aa.height == 0)
2129         {
2130           aa.height = 20;
2131         }
2132
2133         height += aa.height;
2134       }
2135     }
2136     if (height == 0)
2137     {
2138       // set minimum
2139       height = 20;
2140     }
2141     return height;
2142   }
2143
2144   @Override
2145   public void updateGroupAnnotationSettings(boolean applyGlobalSettings,
2146           boolean preserveNewGroupSettings)
2147   {
2148     boolean updateCalcs = false;
2149     boolean conv = isShowGroupConservation();
2150     boolean cons = isShowGroupConsensus();
2151     boolean showprf = isShowSequenceLogo();
2152     boolean showConsHist = isShowConsensusHistogram();
2153     boolean normLogo = isNormaliseSequenceLogo();
2154
2155     /**
2156      * TODO reorder the annotation rows according to group/sequence ordering on
2157      * alignment
2158      */
2159     boolean sortg = true;
2160
2161     // remove old automatic annotation
2162     // add any new annotation
2163
2164     // intersect alignment annotation with alignment groups
2165
2166     AlignmentAnnotation[] aan = alignment.getAlignmentAnnotation();
2167     List<SequenceGroup> oldrfs = new ArrayList<>();
2168     if (aan != null)
2169     {
2170       for (int an = 0; an < aan.length; an++)
2171       {
2172         if (aan[an].autoCalculated && aan[an].groupRef != null)
2173         {
2174           oldrfs.add(aan[an].groupRef);
2175           alignment.deleteAnnotation(aan[an], false);
2176         }
2177       }
2178     }
2179     if (alignment.getGroups() != null)
2180     {
2181       for (SequenceGroup sg : alignment.getGroups())
2182       {
2183         updateCalcs = false;
2184         if (applyGlobalSettings
2185                 || (!preserveNewGroupSettings && !oldrfs.contains(sg)))
2186         {
2187           // set defaults for this group's conservation/consensus
2188           sg.setshowSequenceLogo(showprf);
2189           sg.setShowConsensusHistogram(showConsHist);
2190           sg.setNormaliseSequenceLogo(normLogo);
2191         }
2192         if (conv)
2193         {
2194           updateCalcs = true;
2195           alignment.addAnnotation(sg.getConservationRow(), 0);
2196         }
2197         if (cons)
2198         {
2199           updateCalcs = true;
2200           alignment.addAnnotation(sg.getConsensus(), 0);
2201         }
2202         // refresh the annotation rows
2203         if (updateCalcs)
2204         {
2205           sg.recalcConservation();
2206         }
2207       }
2208     }
2209     oldrfs.clear();
2210   }
2211
2212   @Override
2213   public boolean isDisplayReferenceSeq()
2214   {
2215     return alignment.hasSeqrep() && viewStyle.isDisplayReferenceSeq();
2216   }
2217
2218   @Override
2219   public void setDisplayReferenceSeq(boolean displayReferenceSeq)
2220   {
2221     viewStyle.setDisplayReferenceSeq(displayReferenceSeq);
2222   }
2223
2224   @Override
2225   public boolean isColourByReferenceSeq()
2226   {
2227     return alignment.hasSeqrep() && viewStyle.isColourByReferenceSeq();
2228   }
2229
2230   @Override
2231   public Color getSequenceColour(SequenceI seq)
2232   {
2233     Color sqc = sequenceColours.get(seq);
2234     return (sqc == null ? Color.white : sqc);
2235   }
2236
2237   @Override
2238   public void setSequenceColour(SequenceI seq, Color col)
2239   {
2240     if (col == null)
2241     {
2242       sequenceColours.remove(seq);
2243     }
2244     else
2245     {
2246       sequenceColours.put(seq, col);
2247     }
2248   }
2249
2250   @Override
2251   public void updateSequenceIdColours()
2252   {
2253     for (SequenceGroup sg : alignment.getGroups())
2254     {
2255       if (sg.idColour != null)
2256       {
2257         for (SequenceI s : sg.getSequences(getHiddenRepSequences()))
2258         {
2259           sequenceColours.put(s, sg.idColour);
2260         }
2261       }
2262     }
2263   }
2264
2265   @Override
2266   public void clearSequenceColours()
2267   {
2268     sequenceColours.clear();
2269   };
2270
2271   @Override
2272   public AlignViewportI getCodingComplement()
2273   {
2274     return this.codingComplement;
2275   }
2276
2277   /**
2278    * Set this as the (cDna/protein) complement of the given viewport. Also
2279    * ensures the reverse relationship is set on the given viewport.
2280    */
2281   @Override
2282   public void setCodingComplement(AlignViewportI av)
2283   {
2284     if (this == av)
2285     {
2286       System.err.println("Ignoring recursive setCodingComplement request");
2287     }
2288     else
2289     {
2290       this.codingComplement = av;
2291       // avoid infinite recursion!
2292       if (av.getCodingComplement() != this)
2293       {
2294         av.setCodingComplement(this);
2295       }
2296     }
2297   }
2298
2299   @Override
2300   public boolean isNucleotide()
2301   {
2302     return getAlignment() == null ? false : getAlignment().isNucleotide();
2303   }
2304
2305   @Override
2306   public FeaturesDisplayedI getFeaturesDisplayed()
2307   {
2308     return featuresDisplayed;
2309   }
2310
2311   @Override
2312   public void setFeaturesDisplayed(FeaturesDisplayedI featuresDisplayedI)
2313   {
2314     featuresDisplayed = featuresDisplayedI;
2315   }
2316
2317   @Override
2318   public boolean areFeaturesDisplayed()
2319   {
2320     return featuresDisplayed != null
2321             && featuresDisplayed.getRegisteredFeaturesCount() > 0;
2322   }
2323
2324   /**
2325    * set the flag
2326    * 
2327    * @param b
2328    *          features are displayed if true
2329    */
2330   @Override
2331   public void setShowSequenceFeatures(boolean b)
2332   {
2333     viewStyle.setShowSequenceFeatures(b);
2334   }
2335
2336   @Override
2337   public boolean isShowSequenceFeatures()
2338   {
2339     return viewStyle.isShowSequenceFeatures();
2340   }
2341
2342   @Override
2343   public void setShowSequenceFeaturesHeight(boolean selected)
2344   {
2345     viewStyle.setShowSequenceFeaturesHeight(selected);
2346   }
2347
2348   @Override
2349   public boolean isShowSequenceFeaturesHeight()
2350   {
2351     return viewStyle.isShowSequenceFeaturesHeight();
2352   }
2353
2354   @Override
2355   public void setShowAnnotation(boolean b)
2356   {
2357     viewStyle.setShowAnnotation(b);
2358   }
2359
2360   @Override
2361   public boolean isShowAnnotation()
2362   {
2363     return viewStyle.isShowAnnotation();
2364   }
2365
2366   @Override
2367   public boolean isRightAlignIds()
2368   {
2369     return viewStyle.isRightAlignIds();
2370   }
2371
2372   @Override
2373   public void setRightAlignIds(boolean rightAlignIds)
2374   {
2375     viewStyle.setRightAlignIds(rightAlignIds);
2376   }
2377
2378   @Override
2379   public boolean getConservationSelected()
2380   {
2381     return viewStyle.getConservationSelected();
2382   }
2383
2384   @Override
2385   public void setShowBoxes(boolean state)
2386   {
2387     viewStyle.setShowBoxes(state);
2388   }
2389
2390   /**
2391    * @return
2392    * @see jalview.api.ViewStyleI#getTextColour()
2393    */
2394   @Override
2395   public Color getTextColour()
2396   {
2397     return viewStyle.getTextColour();
2398   }
2399
2400   /**
2401    * @return
2402    * @see jalview.api.ViewStyleI#getTextColour2()
2403    */
2404   @Override
2405   public Color getTextColour2()
2406   {
2407     return viewStyle.getTextColour2();
2408   }
2409
2410   /**
2411    * @return
2412    * @see jalview.api.ViewStyleI#getThresholdTextColour()
2413    */
2414   @Override
2415   public int getThresholdTextColour()
2416   {
2417     return viewStyle.getThresholdTextColour();
2418   }
2419
2420   /**
2421    * @return
2422    * @see jalview.api.ViewStyleI#isConservationColourSelected()
2423    */
2424   @Override
2425   public boolean isConservationColourSelected()
2426   {
2427     return viewStyle.isConservationColourSelected();
2428   }
2429
2430   /**
2431    * @return
2432    * @see jalview.api.ViewStyleI#isRenderGaps()
2433    */
2434   @Override
2435   public boolean isRenderGaps()
2436   {
2437     return viewStyle.isRenderGaps();
2438   }
2439
2440   /**
2441    * @return
2442    * @see jalview.api.ViewStyleI#isShowColourText()
2443    */
2444   @Override
2445   public boolean isShowColourText()
2446   {
2447     return viewStyle.isShowColourText();
2448   }
2449
2450   /**
2451    * @param conservationColourSelected
2452    * @see jalview.api.ViewStyleI#setConservationColourSelected(boolean)
2453    */
2454   @Override
2455   public void setConservationColourSelected(
2456           boolean conservationColourSelected)
2457   {
2458     viewStyle.setConservationColourSelected(conservationColourSelected);
2459   }
2460
2461   /**
2462    * @param showColourText
2463    * @see jalview.api.ViewStyleI#setShowColourText(boolean)
2464    */
2465   @Override
2466   public void setShowColourText(boolean showColourText)
2467   {
2468     viewStyle.setShowColourText(showColourText);
2469   }
2470
2471   /**
2472    * @param textColour
2473    * @see jalview.api.ViewStyleI#setTextColour(java.awt.Color)
2474    */
2475   @Override
2476   public void setTextColour(Color textColour)
2477   {
2478     viewStyle.setTextColour(textColour);
2479   }
2480
2481   /**
2482    * @param thresholdTextColour
2483    * @see jalview.api.ViewStyleI#setThresholdTextColour(int)
2484    */
2485   @Override
2486   public void setThresholdTextColour(int thresholdTextColour)
2487   {
2488     viewStyle.setThresholdTextColour(thresholdTextColour);
2489   }
2490
2491   /**
2492    * @param textColour2
2493    * @see jalview.api.ViewStyleI#setTextColour2(java.awt.Color)
2494    */
2495   @Override
2496   public void setTextColour2(Color textColour2)
2497   {
2498     viewStyle.setTextColour2(textColour2);
2499   }
2500
2501   @Override
2502   public ViewStyleI getViewStyle()
2503   {
2504     return new ViewStyle(viewStyle);
2505   }
2506
2507   @Override
2508   public void setViewStyle(ViewStyleI settingsForView)
2509   {
2510     viewStyle = new ViewStyle(settingsForView);
2511     if (residueShading != null)
2512     {
2513       residueShading.setConservationApplied(settingsForView
2514               .isConservationColourSelected());
2515     }
2516   }
2517
2518   @Override
2519   public boolean sameStyle(ViewStyleI them)
2520   {
2521     return viewStyle.sameStyle(them);
2522   }
2523
2524   /**
2525    * @return
2526    * @see jalview.api.ViewStyleI#getIdWidth()
2527    */
2528   @Override
2529   public int getIdWidth()
2530   {
2531     return viewStyle.getIdWidth();
2532   }
2533
2534   /**
2535    * @param i
2536    * @see jalview.api.ViewStyleI#setIdWidth(int)
2537    */
2538   @Override
2539   public void setIdWidth(int i)
2540   {
2541     viewStyle.setIdWidth(i);
2542   }
2543
2544   /**
2545    * @return
2546    * @see jalview.api.ViewStyleI#isCentreColumnLabels()
2547    */
2548   @Override
2549   public boolean isCentreColumnLabels()
2550   {
2551     return viewStyle.isCentreColumnLabels();
2552   }
2553
2554   /**
2555    * @param centreColumnLabels
2556    * @see jalview.api.ViewStyleI#setCentreColumnLabels(boolean)
2557    */
2558   @Override
2559   public void setCentreColumnLabels(boolean centreColumnLabels)
2560   {
2561     viewStyle.setCentreColumnLabels(centreColumnLabels);
2562   }
2563
2564   /**
2565    * @param showdbrefs
2566    * @see jalview.api.ViewStyleI#setShowDBRefs(boolean)
2567    */
2568   @Override
2569   public void setShowDBRefs(boolean showdbrefs)
2570   {
2571     viewStyle.setShowDBRefs(showdbrefs);
2572   }
2573
2574   /**
2575    * @return
2576    * @see jalview.api.ViewStyleI#isShowDBRefs()
2577    */
2578   @Override
2579   public boolean isShowDBRefs()
2580   {
2581     return viewStyle.isShowDBRefs();
2582   }
2583
2584   /**
2585    * @return
2586    * @see jalview.api.ViewStyleI#isShowNPFeats()
2587    */
2588   @Override
2589   public boolean isShowNPFeats()
2590   {
2591     return viewStyle.isShowNPFeats();
2592   }
2593
2594   /**
2595    * @param shownpfeats
2596    * @see jalview.api.ViewStyleI#setShowNPFeats(boolean)
2597    */
2598   @Override
2599   public void setShowNPFeats(boolean shownpfeats)
2600   {
2601     viewStyle.setShowNPFeats(shownpfeats);
2602   }
2603
2604   public abstract StructureSelectionManager getStructureSelectionManager();
2605
2606   /**
2607    * Add one command to the command history list.
2608    * 
2609    * @param command
2610    */
2611   public void addToHistoryList(CommandI command)
2612   {
2613     if (this.historyList != null)
2614     {
2615       this.historyList.push(command);
2616       broadcastCommand(command, false);
2617     }
2618   }
2619
2620   protected void broadcastCommand(CommandI command, boolean undo)
2621   {
2622     getStructureSelectionManager().commandPerformed(command, undo,
2623             getVamsasSource());
2624   }
2625
2626   /**
2627    * Add one command to the command redo list.
2628    * 
2629    * @param command
2630    */
2631   public void addToRedoList(CommandI command)
2632   {
2633     if (this.redoList != null)
2634     {
2635       this.redoList.push(command);
2636     }
2637     broadcastCommand(command, true);
2638   }
2639
2640   /**
2641    * Clear the command redo list.
2642    */
2643   public void clearRedoList()
2644   {
2645     if (this.redoList != null)
2646     {
2647       this.redoList.clear();
2648     }
2649   }
2650
2651   public void setHistoryList(Deque<CommandI> list)
2652   {
2653     this.historyList = list;
2654   }
2655
2656   public Deque<CommandI> getHistoryList()
2657   {
2658     return this.historyList;
2659   }
2660
2661   public void setRedoList(Deque<CommandI> list)
2662   {
2663     this.redoList = list;
2664   }
2665
2666   public Deque<CommandI> getRedoList()
2667   {
2668     return this.redoList;
2669   }
2670
2671   @Override
2672   public VamsasSource getVamsasSource()
2673   {
2674     return this;
2675   }
2676
2677   public SequenceAnnotationOrder getSortAnnotationsBy()
2678   {
2679     return sortAnnotationsBy;
2680   }
2681
2682   public void setSortAnnotationsBy(SequenceAnnotationOrder sortAnnotationsBy)
2683   {
2684     this.sortAnnotationsBy = sortAnnotationsBy;
2685   }
2686
2687   public boolean isShowAutocalculatedAbove()
2688   {
2689     return showAutocalculatedAbove;
2690   }
2691
2692   public void setShowAutocalculatedAbove(boolean showAutocalculatedAbove)
2693   {
2694     this.showAutocalculatedAbove = showAutocalculatedAbove;
2695   }
2696
2697   @Override
2698   public boolean isScaleProteinAsCdna()
2699   {
2700     return viewStyle.isScaleProteinAsCdna();
2701   }
2702
2703   @Override
2704   public void setScaleProteinAsCdna(boolean b)
2705   {
2706     viewStyle.setScaleProteinAsCdna(b);
2707   }
2708
2709   @Override
2710   public boolean isProteinFontAsCdna()
2711   {
2712     return viewStyle.isProteinFontAsCdna();
2713   }
2714
2715   @Override
2716   public void setProteinFontAsCdna(boolean b)
2717   {
2718     viewStyle.setProteinFontAsCdna(b);
2719   }
2720
2721   /**
2722    * @return true if view should scroll to show the highlighted region of a
2723    *         sequence
2724    * @return
2725    */
2726   @Override
2727   public final boolean isFollowHighlight()
2728   {
2729     return followHighlight;
2730   }
2731
2732   @Override
2733   public final void setFollowHighlight(boolean b)
2734   {
2735     this.followHighlight = b;
2736   }
2737
2738   @Override
2739   public ViewportRanges getRanges()
2740   {
2741     return ranges;
2742   }
2743
2744   /**
2745    * Helper method to populate the SearchResults with the location in the
2746    * complementary alignment to scroll to, in order to match this one.
2747    * 
2748    * @param sr
2749    *          the SearchResults to add to
2750    * @return the offset (below top of visible region) of the matched sequence
2751    */
2752   protected int findComplementScrollTarget(SearchResultsI sr)
2753   {
2754     final AlignViewportI complement = getCodingComplement();
2755     if (complement == null || !complement.isFollowHighlight())
2756     {
2757       return 0;
2758     }
2759     boolean iAmProtein = !getAlignment().isNucleotide();
2760     AlignmentI proteinAlignment = iAmProtein ? getAlignment() : complement
2761             .getAlignment();
2762     if (proteinAlignment == null)
2763     {
2764       return 0;
2765     }
2766     final List<AlignedCodonFrame> mappings = proteinAlignment
2767             .getCodonFrames();
2768
2769     /*
2770      * Heuristic: find the first mapped sequence (if any) with a non-gapped
2771      * residue in the middle column of the visible region. Scroll the
2772      * complementary alignment to line up the corresponding residue.
2773      */
2774     int seqOffset = 0;
2775     SequenceI sequence = null;
2776
2777     /*
2778      * locate 'middle' column (true middle if an odd number visible, left of
2779      * middle if an even number visible)
2780      */
2781     int middleColumn = ranges.getStartRes()
2782             + (ranges.getEndRes() - ranges.getStartRes()) / 2;
2783     final HiddenSequences hiddenSequences = getAlignment()
2784             .getHiddenSequences();
2785
2786     /*
2787      * searching to the bottom of the alignment gives smoother scrolling across
2788      * all gapped visible regions
2789      */
2790     int lastSeq = alignment.getHeight() - 1;
2791     List<AlignedCodonFrame> seqMappings = null;
2792     for (int seqNo = ranges.getStartSeq(); seqNo < lastSeq; seqNo++, seqOffset++)
2793     {
2794       sequence = getAlignment().getSequenceAt(seqNo);
2795       if (hiddenSequences != null && hiddenSequences.isHidden(sequence))
2796       {
2797         continue;
2798       }
2799       if (Comparison.isGap(sequence.getCharAt(middleColumn)))
2800       {
2801         continue;
2802       }
2803       seqMappings = MappingUtils
2804               .findMappingsForSequenceAndOthers(sequence, mappings,
2805                       getCodingComplement().getAlignment().getSequences());
2806       if (!seqMappings.isEmpty())
2807       {
2808         break;
2809       }
2810     }
2811
2812     if (sequence == null || seqMappings == null || seqMappings.isEmpty())
2813     {
2814       /*
2815        * No ungapped mapped sequence in middle column - do nothing
2816        */
2817       return 0;
2818     }
2819     MappingUtils.addSearchResults(sr, sequence,
2820             sequence.findPosition(middleColumn), seqMappings);
2821     return seqOffset;
2822   }
2823
2824   /**
2825    * synthesize a column selection if none exists so it covers the given
2826    * selection group. if wholewidth is false, no column selection is made if the
2827    * selection group covers the whole alignment width.
2828    * 
2829    * @param sg
2830    * @param wholewidth
2831    */
2832   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
2833   {
2834     int sgs, sge;
2835     if (sg != null && (sgs = sg.getStartRes()) >= 0
2836             && sg.getStartRes() <= (sge = sg.getEndRes())
2837             && !this.hasSelectedColumns())
2838     {
2839       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
2840       {
2841         // do nothing
2842         return;
2843       }
2844       if (colSel == null)
2845       {
2846         colSel = new ColumnSelection();
2847       }
2848       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
2849       {
2850         colSel.addElement(cspos);
2851       }
2852     }
2853   }
2854
2855   /**
2856    * hold status of current selection group - defined on alignment or not.
2857    */
2858   private boolean selectionIsDefinedGroup = false;
2859
2860   @Override
2861   public boolean isSelectionDefinedGroup()
2862   {
2863     if (selectionGroup == null)
2864     {
2865       return false;
2866     }
2867     if (isSelectionGroupChanged(true))
2868     {
2869       selectionIsDefinedGroup = false;
2870       List<SequenceGroup> gps = alignment.getGroups();
2871       if (gps == null || gps.size() == 0)
2872       {
2873         selectionIsDefinedGroup = false;
2874       }
2875       else
2876       {
2877         selectionIsDefinedGroup = gps.contains(selectionGroup);
2878       }
2879     }
2880     return selectionGroup.isDefined() || selectionIsDefinedGroup;
2881   }
2882
2883   /**
2884    * null, or currently highlighted results on this view
2885    */
2886   private SearchResultsI searchResults = null;
2887
2888   @Override
2889   public boolean hasSearchResults()
2890   {
2891     return searchResults != null;
2892   }
2893
2894   @Override
2895   public void setSearchResults(SearchResultsI results)
2896   {
2897     searchResults = results;
2898   }
2899
2900   @Override
2901   public SearchResultsI getSearchResults()
2902   {
2903     return searchResults;
2904   }
2905
2906   /**
2907    * get the consensus sequence as displayed under the PID consensus annotation
2908    * row.
2909    * 
2910    * @return consensus sequence as a new sequence object
2911    */
2912   public SequenceI getConsensusSeq()
2913   {
2914     if (consensus == null)
2915     {
2916       updateConsensus(null);
2917     }
2918     if (consensus == null)
2919     {
2920       return null;
2921     }
2922     StringBuffer seqs = new StringBuffer();
2923     for (int i = 0; i < consensus.annotations.length; i++)
2924     {
2925       Annotation annotation = consensus.annotations[i];
2926       if (annotation != null)
2927       {
2928         String description = annotation.description;
2929         if (description != null && description.startsWith("["))
2930         {
2931           // consensus is a tie - just pick the first one
2932           seqs.append(description.charAt(1));
2933         }
2934         else
2935         {
2936           seqs.append(annotation.displayCharacter);
2937         }
2938       }
2939     }
2940   
2941     SequenceI sq = new Sequence("Consensus", seqs.toString());
2942     sq.setDescription("Percentage Identity Consensus "
2943             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
2944     return sq;
2945   }
2946 }