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