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