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