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