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