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