JAL-2629 tidy unit tests, constants etc
[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.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   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     hconservation = null;
1025     hcomplementConsensus = null;
1026     gapcounts = null;
1027     calculator = null;
1028     residueShading = null; // may hold a reference to Consensus
1029     changeSupport = null;
1030     ranges = null;
1031     currentTree = null;
1032     selectionGroup = null;
1033     setAlignment(null);
1034   }
1035
1036   @Override
1037   public boolean isClosed()
1038   {
1039     // TODO: check that this isClosed is only true after panel is closed, not
1040     // before it is fully constructed.
1041     return alignment == null;
1042   }
1043
1044   @Override
1045   public AlignCalcManagerI getCalcManager()
1046   {
1047     return calculator;
1048   }
1049
1050   /**
1051    * should conservation rows be shown for groups
1052    */
1053   protected boolean showGroupConservation = false;
1054
1055   /**
1056    * should consensus rows be shown for groups
1057    */
1058   protected boolean showGroupConsensus = false;
1059
1060   /**
1061    * should consensus profile be rendered by default
1062    */
1063   protected boolean showSequenceLogo = false;
1064
1065   /**
1066    * should consensus profile be rendered normalised to row height
1067    */
1068   protected boolean normaliseSequenceLogo = false;
1069
1070   /**
1071    * should consensus histograms be rendered by default
1072    */
1073   protected boolean showConsensusHistogram = true;
1074
1075   /**
1076    * should hmm profile be rendered by default
1077    */
1078   protected boolean showHMMSequenceLogo = false;
1079
1080   /**
1081    * should hmm profile be rendered normalised to row height
1082    */
1083   protected boolean normaliseHMMSequenceLogo = false;
1084
1085   /**
1086    * should information histograms be rendered by default
1087    */
1088   protected boolean showInformationHistogram = true;
1089
1090   /**
1091    * @return the showConsensusProfile
1092    */
1093   @Override
1094   public boolean isShowSequenceLogo()
1095   {
1096     return showSequenceLogo;
1097   }
1098
1099   /**
1100    * @return the showInformationProfile
1101    */
1102   @Override
1103   public boolean isShowHMMSequenceLogo()
1104   {
1105     return showHMMSequenceLogo;
1106   }
1107
1108   /**
1109    * @param showSequenceLogo
1110    *          the new value
1111    */
1112   public void setShowSequenceLogo(boolean showSequenceLogo)
1113   {
1114     if (showSequenceLogo != this.showSequenceLogo)
1115     {
1116       // TODO: decouple settings setting from calculation when refactoring
1117       // annotation update method from alignframe to viewport
1118       this.showSequenceLogo = showSequenceLogo;
1119       calculator.updateAnnotationFor(ConsensusThread.class);
1120       calculator.updateAnnotationFor(ComplementConsensusThread.class);
1121       calculator.updateAnnotationFor(StrucConsensusThread.class);
1122     }
1123     this.showSequenceLogo = showSequenceLogo;
1124   }
1125
1126   public void setShowHMMSequenceLogo(boolean showHMMSequenceLogo)
1127   {
1128     if (showHMMSequenceLogo != this.showHMMSequenceLogo)
1129     {
1130       this.showHMMSequenceLogo = showHMMSequenceLogo;
1131       calculator.updateAnnotationFor(InformationThread.class);
1132     }
1133     this.showHMMSequenceLogo = showHMMSequenceLogo;
1134   }
1135
1136   /**
1137    * @param showConsensusHistogram
1138    *          the showConsensusHistogram to set
1139    */
1140   public void setShowConsensusHistogram(boolean showConsensusHistogram)
1141   {
1142     this.showConsensusHistogram = showConsensusHistogram;
1143   }
1144
1145   /**
1146    * @param showInformationHistogram
1147    *          the showInformationHistogram to set
1148    */
1149   public void setShowInformationHistogram(boolean showInformationHistogram)
1150   {
1151     this.showInformationHistogram = showInformationHistogram;
1152   }
1153
1154   /**
1155    * @return the showGroupConservation
1156    */
1157   public boolean isShowGroupConservation()
1158   {
1159     return showGroupConservation;
1160   }
1161
1162   /**
1163    * @param showGroupConservation
1164    *          the showGroupConservation to set
1165    */
1166   public void setShowGroupConservation(boolean showGroupConservation)
1167   {
1168     this.showGroupConservation = showGroupConservation;
1169   }
1170
1171   /**
1172    * @return the showGroupConsensus
1173    */
1174   public boolean isShowGroupConsensus()
1175   {
1176     return showGroupConsensus;
1177   }
1178
1179   /**
1180    * @param showGroupConsensus
1181    *          the showGroupConsensus to set
1182    */
1183   public void setShowGroupConsensus(boolean showGroupConsensus)
1184   {
1185     this.showGroupConsensus = showGroupConsensus;
1186   }
1187
1188   /**
1189    * 
1190    * @return flag to indicate if the consensus histogram should be rendered by
1191    *         default
1192    */
1193   @Override
1194   public boolean isShowConsensusHistogram()
1195   {
1196     return this.showConsensusHistogram;
1197   }
1198
1199   /**
1200    * 
1201    * @return flag to indicate if the information content histogram should be
1202    *         rendered by default
1203    */
1204   @Override
1205   public boolean isShowInformationHistogram()
1206   {
1207     return this.showInformationHistogram;
1208   }
1209
1210   /**
1211    * when set, updateAlignment will always ensure sequences are of equal length
1212    */
1213   private boolean padGaps = false;
1214
1215   /**
1216    * when set, alignment should be reordered according to a newly opened tree
1217    */
1218   public boolean sortByTree = false;
1219
1220   /**
1221    * 
1222    * 
1223    * @return null or the currently selected sequence region
1224    */
1225   @Override
1226   public SequenceGroup getSelectionGroup()
1227   {
1228     return selectionGroup;
1229   }
1230
1231   /**
1232    * Set the selection group for this window. Also sets the current alignment as
1233    * the context for the group, if it does not already have one.
1234    * 
1235    * @param sg
1236    *          - group holding references to sequences in this alignment view
1237    * 
1238    */
1239   @Override
1240   public void setSelectionGroup(SequenceGroup sg)
1241   {
1242     selectionGroup = sg;
1243     if (sg != null && sg.getContext() == null)
1244     {
1245       sg.setContext(alignment);
1246     }
1247   }
1248
1249   public void setHiddenColumns(HiddenColumns hidden)
1250   {
1251     this.alignment.setHiddenColumns(hidden);
1252   }
1253
1254   @Override
1255   public ColumnSelection getColumnSelection()
1256   {
1257     return colSel;
1258   }
1259
1260   @Override
1261   public void setColumnSelection(ColumnSelection colSel)
1262   {
1263     this.colSel = colSel;
1264     if (colSel != null)
1265     {
1266       updateHiddenColumns();
1267     }
1268     isColSelChanged(true);
1269   }
1270
1271   /**
1272    * 
1273    * @return
1274    */
1275   @Override
1276   public Map<SequenceI, SequenceCollectionI> getHiddenRepSequences()
1277   {
1278     return hiddenRepSequences;
1279   }
1280
1281   @Override
1282   public void setHiddenRepSequences(
1283           Map<SequenceI, SequenceCollectionI> hiddenRepSequences)
1284   {
1285     this.hiddenRepSequences = hiddenRepSequences;
1286   }
1287
1288   @Override
1289   public boolean hasSelectedColumns()
1290   {
1291     ColumnSelection columnSelection = getColumnSelection();
1292     return columnSelection != null && columnSelection.hasSelectedColumns();
1293   }
1294
1295   @Override
1296   public boolean hasHiddenColumns()
1297   {
1298     return alignment.getHiddenColumns() != null
1299             && alignment.getHiddenColumns().hasHiddenColumns();
1300   }
1301
1302   public void updateHiddenColumns()
1303   {
1304     // this method doesn't really do anything now. But - it could, since a
1305     // column Selection could be in the process of modification
1306     // hasHiddenColumns = colSel.hasHiddenColumns();
1307   }
1308
1309   @Override
1310   public boolean hasHiddenRows()
1311   {
1312     return alignment.getHiddenSequences().getSize() > 0;
1313   }
1314
1315   protected SequenceGroup selectionGroup;
1316
1317   public void setSequenceSetId(String newid)
1318   {
1319     if (sequenceSetID != null)
1320     {
1321       System.err.println(
1322               "Warning - overwriting a sequenceSetId for a viewport!");
1323     }
1324     sequenceSetID = new String(newid);
1325   }
1326
1327   @Override
1328   public String getSequenceSetId()
1329   {
1330     if (sequenceSetID == null)
1331     {
1332       sequenceSetID = alignment.hashCode() + "";
1333     }
1334
1335     return sequenceSetID;
1336   }
1337
1338   /**
1339    * unique viewId for synchronizing state (e.g. with stored Jalview Project)
1340    * 
1341    */
1342   protected String viewId = null;
1343
1344   @Override
1345   public String getViewId()
1346   {
1347     if (viewId == null)
1348     {
1349       viewId = this.getSequenceSetId() + "." + this.hashCode() + "";
1350     }
1351     return viewId;
1352   }
1353
1354   public void setIgnoreGapsConsensus(boolean b, AlignmentViewPanel ap)
1355   {
1356     ignoreGapsInConsensusCalculation = b;
1357     if (ap != null)
1358     {
1359       updateConsensus(ap);
1360       if (residueShading != null)
1361       {
1362         residueShading.setThreshold(residueShading.getThreshold(),
1363                 ignoreGapsInConsensusCalculation);
1364       }
1365     }
1366
1367   }
1368
1369   public void setIgnoreBelowBackground(boolean b, AlignmentViewPanel ap)
1370   {
1371     ignoreBelowBackGroundFrequencyCalculation = b;
1372     if (ap != null)
1373     {
1374       updateInformation(ap);
1375     }
1376
1377   }
1378
1379   public void setInfoLetterHeight(boolean b, AlignmentViewPanel ap)
1380   {
1381     infoLetterHeight = b;
1382     if (ap != null)
1383     {
1384       updateInformation(ap);
1385     }
1386
1387   }
1388
1389   private long sgrouphash = -1, colselhash = -1;
1390
1391   /**
1392    * checks current SelectionGroup against record of last hash value, and
1393    * updates record.
1394    * 
1395    * @param b
1396    *          update the record of last hash value
1397    * 
1398    * @return true if SelectionGroup changed since last call (when b is true)
1399    */
1400   public boolean isSelectionGroupChanged(boolean b)
1401   {
1402     int hc = (selectionGroup == null || selectionGroup.getSize() == 0) ? -1
1403             : selectionGroup.hashCode();
1404     if (hc != -1 && hc != sgrouphash)
1405     {
1406       if (b)
1407       {
1408         sgrouphash = hc;
1409       }
1410       return true;
1411     }
1412     return false;
1413   }
1414
1415   /**
1416    * checks current colsel against record of last hash value, and optionally
1417    * updates record.
1418    * 
1419    * @param b
1420    *          update the record of last hash value
1421    * @return true if colsel changed since last call (when b is true)
1422    */
1423   public boolean isColSelChanged(boolean b)
1424   {
1425     int hc = (colSel == null || colSel.isEmpty()) ? -1 : colSel.hashCode();
1426     if (hc != -1 && hc != colselhash)
1427     {
1428       if (b)
1429       {
1430         colselhash = hc;
1431       }
1432       return true;
1433     }
1434     return false;
1435   }
1436
1437   @Override
1438   public boolean isIgnoreGapsConsensus()
1439   {
1440     return ignoreGapsInConsensusCalculation;
1441   }
1442
1443   @Override
1444   public boolean isIgnoreBelowBackground()
1445   {
1446     return ignoreBelowBackGroundFrequencyCalculation;
1447   }
1448
1449   @Override
1450   public boolean isInfoLetterHeight()
1451   {
1452     return infoLetterHeight;
1453   }
1454
1455   // property change stuff
1456   // JBPNote Prolly only need this in the applet version.
1457   private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
1458           this);
1459
1460   protected boolean showConservation = true;
1461
1462   protected boolean showQuality = true;
1463
1464   protected boolean showConsensus = true;
1465
1466   protected boolean showOccupancy = true;
1467
1468   private Map<SequenceI, Color> sequenceColours = new HashMap<>();
1469
1470   protected SequenceAnnotationOrder sortAnnotationsBy = null;
1471
1472   protected boolean showAutocalculatedAbove;
1473
1474   /**
1475    * when set, view will scroll to show the highlighted position
1476    */
1477   private boolean followHighlight = true;
1478
1479   /**
1480    * Property change listener for changes in alignment
1481    * 
1482    * @param listener
1483    *          DOCUMENT ME!
1484    */
1485   public void addPropertyChangeListener(
1486           java.beans.PropertyChangeListener listener)
1487   {
1488     changeSupport.addPropertyChangeListener(listener);
1489   }
1490
1491   /**
1492    * DOCUMENT ME!
1493    * 
1494    * @param listener
1495    *          DOCUMENT ME!
1496    */
1497   public void removePropertyChangeListener(
1498           java.beans.PropertyChangeListener listener)
1499   {
1500     if (changeSupport != null)
1501     {
1502       changeSupport.removePropertyChangeListener(listener);
1503     }
1504   }
1505
1506   /**
1507    * Property change listener for changes in alignment
1508    * 
1509    * @param prop
1510    *          DOCUMENT ME!
1511    * @param oldvalue
1512    *          DOCUMENT ME!
1513    * @param newvalue
1514    *          DOCUMENT ME!
1515    */
1516   public void firePropertyChange(String prop, Object oldvalue,
1517           Object newvalue)
1518   {
1519     changeSupport.firePropertyChange(prop, oldvalue, newvalue);
1520   }
1521
1522   // common hide/show column stuff
1523
1524   public void hideSelectedColumns()
1525   {
1526     if (colSel.isEmpty())
1527     {
1528       return;
1529     }
1530
1531     colSel.hideSelectedColumns(alignment);
1532     setSelectionGroup(null);
1533     isColSelChanged(true);
1534   }
1535
1536   public void hideColumns(int start, int end)
1537   {
1538     if (start == end)
1539     {
1540       colSel.hideSelectedColumns(start, alignment.getHiddenColumns());
1541     }
1542     else
1543     {
1544       alignment.getHiddenColumns().hideColumns(start, end);
1545     }
1546     isColSelChanged(true);
1547   }
1548
1549   public void showColumn(int col)
1550   {
1551     alignment.getHiddenColumns().revealHiddenColumns(col, colSel);
1552     isColSelChanged(true);
1553   }
1554
1555   public void showAllHiddenColumns()
1556   {
1557     alignment.getHiddenColumns().revealAllHiddenColumns(colSel);
1558     isColSelChanged(true);
1559   }
1560
1561   // common hide/show seq stuff
1562   public void showAllHiddenSeqs()
1563   {
1564     int startSeq = ranges.getStartSeq();
1565     int endSeq = ranges.getEndSeq();
1566
1567     if (alignment.getHiddenSequences().getSize() > 0)
1568     {
1569       if (selectionGroup == null)
1570       {
1571         selectionGroup = new SequenceGroup();
1572         selectionGroup.setEndRes(alignment.getWidth() - 1);
1573       }
1574       List<SequenceI> tmp = alignment.getHiddenSequences()
1575               .showAll(hiddenRepSequences);
1576       for (SequenceI seq : tmp)
1577       {
1578         selectionGroup.addSequence(seq, false);
1579         setSequenceAnnotationsVisible(seq, true);
1580       }
1581
1582       hiddenRepSequences = null;
1583
1584       ranges.setStartEndSeq(startSeq, endSeq + tmp.size());
1585
1586       firePropertyChange("alignment", null, alignment.getSequences());
1587       // used to set hasHiddenRows/hiddenRepSequences here, after the property
1588       // changed event
1589       sendSelection();
1590     }
1591   }
1592
1593   public void showSequence(int index)
1594   {
1595     int startSeq = ranges.getStartSeq();
1596     int endSeq = ranges.getEndSeq();
1597
1598     List<SequenceI> tmp = alignment.getHiddenSequences().showSequence(index,
1599             hiddenRepSequences);
1600     if (tmp.size() > 0)
1601     {
1602       if (selectionGroup == null)
1603       {
1604         selectionGroup = new SequenceGroup();
1605         selectionGroup.setEndRes(alignment.getWidth() - 1);
1606       }
1607
1608       for (SequenceI seq : tmp)
1609       {
1610         selectionGroup.addSequence(seq, false);
1611         setSequenceAnnotationsVisible(seq, true);
1612       }
1613
1614       ranges.setStartEndSeq(startSeq, endSeq + tmp.size());
1615
1616       firePropertyChange("alignment", null, alignment.getSequences());
1617       sendSelection();
1618     }
1619   }
1620
1621   public void hideAllSelectedSeqs()
1622   {
1623     if (selectionGroup == null || selectionGroup.getSize() < 1)
1624     {
1625       return;
1626     }
1627
1628     SequenceI[] seqs = selectionGroup.getSequencesInOrder(alignment);
1629
1630     hideSequence(seqs);
1631
1632     setSelectionGroup(null);
1633   }
1634
1635   public void hideSequence(SequenceI[] seq)
1636   {
1637     /*
1638      * cache offset to first visible sequence
1639      */
1640     int startSeq = ranges.getStartSeq();
1641
1642     if (seq != null)
1643     {
1644       for (int i = 0; i < seq.length; i++)
1645       {
1646         alignment.getHiddenSequences().hideSequence(seq[i]);
1647         setSequenceAnnotationsVisible(seq[i], false);
1648       }
1649       ranges.setStartSeq(startSeq);
1650       firePropertyChange("alignment", null, alignment.getSequences());
1651     }
1652   }
1653
1654   /**
1655    * Hides the specified sequence, or the sequences it represents
1656    * 
1657    * @param sequence
1658    *          the sequence to hide, or keep as representative
1659    * @param representGroup
1660    *          if true, hide the current selection group except for the
1661    *          representative sequence
1662    */
1663   public void hideSequences(SequenceI sequence, boolean representGroup)
1664   {
1665     if (selectionGroup == null || selectionGroup.getSize() < 1)
1666     {
1667       hideSequence(new SequenceI[] { sequence });
1668       return;
1669     }
1670
1671     if (representGroup)
1672     {
1673       hideRepSequences(sequence, selectionGroup);
1674       setSelectionGroup(null);
1675       return;
1676     }
1677
1678     int gsize = selectionGroup.getSize();
1679     SequenceI[] hseqs = selectionGroup.getSequences()
1680             .toArray(new SequenceI[gsize]);
1681
1682     hideSequence(hseqs);
1683     setSelectionGroup(null);
1684     sendSelection();
1685   }
1686
1687   /**
1688    * Set visibility for any annotations for the given sequence.
1689    * 
1690    * @param sequenceI
1691    */
1692   protected void setSequenceAnnotationsVisible(SequenceI sequenceI,
1693           boolean visible)
1694   {
1695     AlignmentAnnotation[] anns = alignment.getAlignmentAnnotation();
1696     if (anns != null)
1697     {
1698       for (AlignmentAnnotation ann : anns)
1699       {
1700         if (ann.sequenceRef == sequenceI)
1701         {
1702           ann.visible = visible;
1703         }
1704       }
1705     }
1706   }
1707
1708   public void hideRepSequences(SequenceI repSequence, SequenceGroup sg)
1709   {
1710     int sSize = sg.getSize();
1711     if (sSize < 2)
1712     {
1713       return;
1714     }
1715
1716     if (hiddenRepSequences == null)
1717     {
1718       hiddenRepSequences = new Hashtable<>();
1719     }
1720
1721     hiddenRepSequences.put(repSequence, sg);
1722
1723     // Hide all sequences except the repSequence
1724     SequenceI[] seqs = new SequenceI[sSize - 1];
1725     int index = 0;
1726     for (int i = 0; i < sSize; i++)
1727     {
1728       if (sg.getSequenceAt(i) != repSequence)
1729       {
1730         if (index == sSize - 1)
1731         {
1732           return;
1733         }
1734
1735         seqs[index++] = sg.getSequenceAt(i);
1736       }
1737     }
1738     sg.setSeqrep(repSequence); // note: not done in 2.7applet
1739     sg.setHidereps(true); // note: not done in 2.7applet
1740     hideSequence(seqs);
1741
1742   }
1743
1744   /**
1745    * 
1746    * @return null or the current reference sequence
1747    */
1748   public SequenceI getReferenceSeq()
1749   {
1750     return alignment.getSeqrep();
1751   }
1752
1753   /**
1754    * @param seq
1755    * @return true iff seq is the reference for the alignment
1756    */
1757   public boolean isReferenceSeq(SequenceI seq)
1758   {
1759     return alignment.getSeqrep() == seq;
1760   }
1761
1762   /**
1763    * 
1764    * @param seq
1765    * @return true if there are sequences represented by this sequence that are
1766    *         currently hidden
1767    */
1768   public boolean isHiddenRepSequence(SequenceI seq)
1769   {
1770     return (hiddenRepSequences != null
1771             && hiddenRepSequences.containsKey(seq));
1772   }
1773
1774   /**
1775    * 
1776    * @param seq
1777    * @return null or a sequence group containing the sequences that seq
1778    *         represents
1779    */
1780   public SequenceGroup getRepresentedSequences(SequenceI seq)
1781   {
1782     return (SequenceGroup) (hiddenRepSequences == null ? null
1783             : hiddenRepSequences.get(seq));
1784   }
1785
1786   @Override
1787   public int adjustForHiddenSeqs(int alignmentIndex)
1788   {
1789     return alignment.getHiddenSequences()
1790             .adjustForHiddenSeqs(alignmentIndex);
1791   }
1792
1793   @Override
1794   public void invertColumnSelection()
1795   {
1796     colSel.invertColumnSelection(0, alignment.getWidth(), alignment);
1797   }
1798
1799   @Override
1800   public SequenceI[] getSelectionAsNewSequence()
1801   {
1802     SequenceI[] sequences;
1803     // JBPNote: Need to test jalviewLite.getSelectedSequencesAsAlignmentFrom -
1804     // this was the only caller in the applet for this method
1805     // JBPNote: in applet, this method returned references to the alignment
1806     // sequences, and it did not honour the presence/absence of annotation
1807     // attached to the alignment (probably!)
1808     if (selectionGroup == null || selectionGroup.getSize() == 0)
1809     {
1810       sequences = alignment.getSequencesArray();
1811       AlignmentAnnotation[] annots = alignment.getAlignmentAnnotation();
1812       for (int i = 0; i < sequences.length; i++)
1813       {
1814         // construct new sequence with subset of visible annotation
1815         sequences[i] = new Sequence(sequences[i], annots);
1816       }
1817     }
1818     else
1819     {
1820       sequences = selectionGroup.getSelectionAsNewSequences(alignment);
1821     }
1822
1823     return sequences;
1824   }
1825
1826   @Override
1827   public SequenceI[] getSequenceSelection()
1828   {
1829     SequenceI[] sequences = null;
1830     if (selectionGroup != null)
1831     {
1832       sequences = selectionGroup.getSequencesInOrder(alignment);
1833     }
1834     if (sequences == null)
1835     {
1836       sequences = alignment.getSequencesArray();
1837     }
1838     return sequences;
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();
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())
2169     {
2170       if (!seq.hasHMMAnnotation())
2171       {
2172         AlignmentAnnotation info = new AlignmentAnnotation(seq.getName(),
2173                 MessageManager.getString("label.information_description"),
2174                 new Annotation[1], 0f, 6.52f,
2175                 AlignmentAnnotation.BAR_GRAPH);
2176         info.hasText = true;
2177         info.autoCalculated = true;
2178         info.hasText = true;
2179         info.autoCalculated = false;
2180         info.sequenceRef = seq;
2181         info.setCalcId(InformationThread.HMM_CALC_ID);
2182         this.information.add(info);
2183         hinformation.add(new Profiles(new ProfileI[1]));
2184         alignment.addAnnotation(info);
2185         seq.updateHMMMapping();
2186         seq.setHasInfo(true);
2187         seq.addAlignmentAnnotation(info);
2188       }
2189     }
2190   }
2191
2192   // these should be extracted from the view model - style and settings for
2193   // derived annotation
2194   private void initGapCounts()
2195   {
2196     if (showOccupancy)
2197     {
2198       gapcounts = new AlignmentAnnotation("Occupancy",
2199               MessageManager.getString("label.occupancy_descr"),
2200               new Annotation[1], 0f, alignment.getHeight(),
2201               AlignmentAnnotation.BAR_GRAPH);
2202       gapcounts.hasText = true;
2203       gapcounts.autoCalculated = true;
2204       gapcounts.scaleColLabel = true;
2205       gapcounts.graph = AlignmentAnnotation.BAR_GRAPH;
2206
2207       alignment.addAnnotation(gapcounts);
2208     }
2209   }
2210
2211   private void initConservation()
2212   {
2213     if (showConservation)
2214     {
2215       if (conservation == null)
2216       {
2217         conservation = new AlignmentAnnotation("Conservation",
2218                 MessageManager.formatMessage("label.conservation_descr",
2219                         getConsPercGaps()),
2220                 new Annotation[1], 0f, 11f, AlignmentAnnotation.BAR_GRAPH);
2221         conservation.hasText = true;
2222         conservation.autoCalculated = true;
2223         alignment.addAnnotation(conservation);
2224       }
2225     }
2226   }
2227
2228   private void initQuality()
2229   {
2230     if (showQuality)
2231     {
2232       if (quality == null)
2233       {
2234         quality = new AlignmentAnnotation("Quality",
2235                 MessageManager.getString("label.quality_descr"),
2236                 new Annotation[1], 0f, 11f, AlignmentAnnotation.BAR_GRAPH);
2237         quality.hasText = true;
2238         quality.autoCalculated = true;
2239         alignment.addAnnotation(quality);
2240       }
2241     }
2242   }
2243
2244   private void initRNAStructure()
2245   {
2246     if (alignment.hasRNAStructure() && strucConsensus == null)
2247     {
2248       strucConsensus = new AlignmentAnnotation("StrucConsensus",
2249               MessageManager.getString("label.strucconsensus_descr"),
2250               new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH);
2251       strucConsensus.hasText = true;
2252       strucConsensus.autoCalculated = true;
2253
2254       if (showConsensus)
2255       {
2256         alignment.addAnnotation(strucConsensus);
2257       }
2258     }
2259   }
2260
2261   /*
2262    * (non-Javadoc)
2263    * 
2264    * @see jalview.api.AlignViewportI#calcPanelHeight()
2265    */
2266   @Override
2267   public int calcPanelHeight()
2268   {
2269     // setHeight of panels
2270     AlignmentAnnotation[] anns = getAlignment().getAlignmentAnnotation();
2271     int height = 0;
2272     int charHeight = getCharHeight();
2273     if (anns != null)
2274     {
2275       BitSet graphgrp = new BitSet();
2276       for (AlignmentAnnotation aa : anns)
2277       {
2278         if (aa == null)
2279         {
2280           System.err.println("Null annotation row: ignoring.");
2281           continue;
2282         }
2283         if (!aa.visible)
2284         {
2285           continue;
2286         }
2287         if (aa.graphGroup > -1)
2288         {
2289           if (graphgrp.get(aa.graphGroup))
2290           {
2291             continue;
2292           }
2293           else
2294           {
2295             graphgrp.set(aa.graphGroup);
2296           }
2297         }
2298         aa.height = 0;
2299
2300         if (aa.hasText)
2301         {
2302           aa.height += charHeight;
2303         }
2304
2305         if (aa.hasIcons)
2306         {
2307           aa.height += 16;
2308         }
2309
2310         if (aa.graph > 0)
2311         {
2312           aa.height += aa.graphHeight;
2313         }
2314
2315         if (aa.height == 0)
2316         {
2317           aa.height = 20;
2318         }
2319
2320         height += aa.height;
2321       }
2322     }
2323     if (height == 0)
2324     {
2325       // set minimum
2326       height = 20;
2327     }
2328     return height;
2329   }
2330
2331   @Override
2332   public void updateGroupAnnotationSettings(boolean applyGlobalSettings,
2333           boolean preserveNewGroupSettings)
2334   {
2335     boolean updateCalcs = false;
2336     boolean conv = isShowGroupConservation();
2337     boolean cons = isShowGroupConsensus();
2338     boolean showprf = isShowSequenceLogo();
2339     boolean showConsHist = isShowConsensusHistogram();
2340     boolean normLogo = isNormaliseSequenceLogo();
2341     boolean showHMMPrf = isShowHMMSequenceLogo();
2342     boolean showInfoHist = isShowInformationHistogram();
2343     boolean normHMMLogo = isNormaliseHMMSequenceLogo();
2344
2345     /**
2346      * TODO reorder the annotation rows according to group/sequence ordering on
2347      * alignment
2348      */
2349     boolean sortg = true;
2350
2351     // remove old automatic annotation
2352     // add any new annotation
2353
2354     // intersect alignment annotation with alignment groups
2355
2356     AlignmentAnnotation[] aan = alignment.getAlignmentAnnotation();
2357     List<SequenceGroup> oldrfs = new ArrayList<>();
2358     if (aan != null)
2359     {
2360       for (int an = 0; an < aan.length; an++)
2361       {
2362         if (aan[an].autoCalculated && aan[an].groupRef != null)
2363         {
2364           oldrfs.add(aan[an].groupRef);
2365           alignment.deleteAnnotation(aan[an], false);
2366         }
2367       }
2368     }
2369     if (alignment.getGroups() != null)
2370     {
2371       for (SequenceGroup sg : alignment.getGroups())
2372       {
2373         updateCalcs = false;
2374         if (applyGlobalSettings
2375                 || (!preserveNewGroupSettings && !oldrfs.contains(sg)))
2376         {
2377           // set defaults for this group's conservation/consensus
2378           sg.setshowSequenceLogo(showprf);
2379           sg.setShowConsensusHistogram(showConsHist);
2380           sg.setNormaliseSequenceLogo(normLogo);
2381           sg.setshowHMMSequenceLogo(showHMMPrf);
2382           sg.setShowInformationHistogram(showInfoHist);
2383           sg.setNormaliseHMMSequenceLogo(normHMMLogo);
2384         }
2385         if (conv)
2386         {
2387           updateCalcs = true;
2388           alignment.addAnnotation(sg.getConservationRow(), 0);
2389         }
2390         if (cons)
2391         {
2392           updateCalcs = true;
2393           alignment.addAnnotation(sg.getConsensus(), 0);
2394         }
2395         // refresh the annotation rows
2396         if (updateCalcs)
2397         {
2398           sg.recalcConservation();
2399         }
2400       }
2401     }
2402     oldrfs.clear();
2403   }
2404
2405   @Override
2406   public boolean isDisplayReferenceSeq()
2407   {
2408     return alignment.hasSeqrep() && viewStyle.isDisplayReferenceSeq();
2409   }
2410
2411   @Override
2412   public void setDisplayReferenceSeq(boolean displayReferenceSeq)
2413   {
2414     viewStyle.setDisplayReferenceSeq(displayReferenceSeq);
2415   }
2416
2417   @Override
2418   public boolean isColourByReferenceSeq()
2419   {
2420     return alignment.hasSeqrep() && viewStyle.isColourByReferenceSeq();
2421   }
2422
2423   @Override
2424   public Color getSequenceColour(SequenceI seq)
2425   {
2426     Color sqc = sequenceColours.get(seq);
2427     return (sqc == null ? Color.white : sqc);
2428   }
2429
2430   @Override
2431   public void setSequenceColour(SequenceI seq, Color col)
2432   {
2433     if (col == null)
2434     {
2435       sequenceColours.remove(seq);
2436     }
2437     else
2438     {
2439       sequenceColours.put(seq, col);
2440     }
2441   }
2442
2443   @Override
2444   public void updateSequenceIdColours()
2445   {
2446     for (SequenceGroup sg : alignment.getGroups())
2447     {
2448       if (sg.idColour != null)
2449       {
2450         for (SequenceI s : sg.getSequences(getHiddenRepSequences()))
2451         {
2452           sequenceColours.put(s, sg.idColour);
2453         }
2454       }
2455     }
2456   }
2457
2458   @Override
2459   public void clearSequenceColours()
2460   {
2461     sequenceColours.clear();
2462   };
2463
2464   @Override
2465   public AlignViewportI getCodingComplement()
2466   {
2467     return this.codingComplement;
2468   }
2469
2470   /**
2471    * Set this as the (cDna/protein) complement of the given viewport. Also
2472    * ensures the reverse relationship is set on the given viewport.
2473    */
2474   @Override
2475   public void setCodingComplement(AlignViewportI av)
2476   {
2477     if (this == av)
2478     {
2479       System.err.println("Ignoring recursive setCodingComplement request");
2480     }
2481     else
2482     {
2483       this.codingComplement = av;
2484       // avoid infinite recursion!
2485       if (av.getCodingComplement() != this)
2486       {
2487         av.setCodingComplement(this);
2488       }
2489     }
2490   }
2491
2492   @Override
2493   public boolean isNucleotide()
2494   {
2495     return getAlignment() == null ? false : getAlignment().isNucleotide();
2496   }
2497
2498   @Override
2499   public FeaturesDisplayedI getFeaturesDisplayed()
2500   {
2501     return featuresDisplayed;
2502   }
2503
2504   @Override
2505   public void setFeaturesDisplayed(FeaturesDisplayedI featuresDisplayedI)
2506   {
2507     featuresDisplayed = featuresDisplayedI;
2508   }
2509
2510   @Override
2511   public boolean areFeaturesDisplayed()
2512   {
2513     return featuresDisplayed != null
2514             && featuresDisplayed.getRegisteredFeaturesCount() > 0;
2515   }
2516
2517   /**
2518    * set the flag
2519    * 
2520    * @param b
2521    *          features are displayed if true
2522    */
2523   @Override
2524   public void setShowSequenceFeatures(boolean b)
2525   {
2526     viewStyle.setShowSequenceFeatures(b);
2527   }
2528
2529   @Override
2530   public boolean isShowSequenceFeatures()
2531   {
2532     return viewStyle.isShowSequenceFeatures();
2533   }
2534
2535   @Override
2536   public void setShowSequenceFeaturesHeight(boolean selected)
2537   {
2538     viewStyle.setShowSequenceFeaturesHeight(selected);
2539   }
2540
2541   @Override
2542   public boolean isShowSequenceFeaturesHeight()
2543   {
2544     return viewStyle.isShowSequenceFeaturesHeight();
2545   }
2546
2547   @Override
2548   public void setShowAnnotation(boolean b)
2549   {
2550     viewStyle.setShowAnnotation(b);
2551   }
2552
2553   @Override
2554   public boolean isShowAnnotation()
2555   {
2556     return viewStyle.isShowAnnotation();
2557   }
2558
2559   @Override
2560   public boolean isRightAlignIds()
2561   {
2562     return viewStyle.isRightAlignIds();
2563   }
2564
2565   @Override
2566   public void setRightAlignIds(boolean rightAlignIds)
2567   {
2568     viewStyle.setRightAlignIds(rightAlignIds);
2569   }
2570
2571   @Override
2572   public boolean getConservationSelected()
2573   {
2574     return viewStyle.getConservationSelected();
2575   }
2576
2577   @Override
2578   public void setShowBoxes(boolean state)
2579   {
2580     viewStyle.setShowBoxes(state);
2581   }
2582
2583   /**
2584    * @return
2585    * @see jalview.api.ViewStyleI#getTextColour()
2586    */
2587   @Override
2588   public Color getTextColour()
2589   {
2590     return viewStyle.getTextColour();
2591   }
2592
2593   /**
2594    * @return
2595    * @see jalview.api.ViewStyleI#getTextColour2()
2596    */
2597   @Override
2598   public Color getTextColour2()
2599   {
2600     return viewStyle.getTextColour2();
2601   }
2602
2603   /**
2604    * @return
2605    * @see jalview.api.ViewStyleI#getThresholdTextColour()
2606    */
2607   @Override
2608   public int getThresholdTextColour()
2609   {
2610     return viewStyle.getThresholdTextColour();
2611   }
2612
2613   /**
2614    * @return
2615    * @see jalview.api.ViewStyleI#isConservationColourSelected()
2616    */
2617   @Override
2618   public boolean isConservationColourSelected()
2619   {
2620     return viewStyle.isConservationColourSelected();
2621   }
2622
2623   /**
2624    * @return
2625    * @see jalview.api.ViewStyleI#isRenderGaps()
2626    */
2627   @Override
2628   public boolean isRenderGaps()
2629   {
2630     return viewStyle.isRenderGaps();
2631   }
2632
2633   /**
2634    * @return
2635    * @see jalview.api.ViewStyleI#isShowColourText()
2636    */
2637   @Override
2638   public boolean isShowColourText()
2639   {
2640     return viewStyle.isShowColourText();
2641   }
2642
2643   /**
2644    * @param conservationColourSelected
2645    * @see jalview.api.ViewStyleI#setConservationColourSelected(boolean)
2646    */
2647   @Override
2648   public void setConservationColourSelected(
2649           boolean conservationColourSelected)
2650   {
2651     viewStyle.setConservationColourSelected(conservationColourSelected);
2652   }
2653
2654   /**
2655    * @param showColourText
2656    * @see jalview.api.ViewStyleI#setShowColourText(boolean)
2657    */
2658   @Override
2659   public void setShowColourText(boolean showColourText)
2660   {
2661     viewStyle.setShowColourText(showColourText);
2662   }
2663
2664   /**
2665    * @param textColour
2666    * @see jalview.api.ViewStyleI#setTextColour(java.awt.Color)
2667    */
2668   @Override
2669   public void setTextColour(Color textColour)
2670   {
2671     viewStyle.setTextColour(textColour);
2672   }
2673
2674   /**
2675    * @param thresholdTextColour
2676    * @see jalview.api.ViewStyleI#setThresholdTextColour(int)
2677    */
2678   @Override
2679   public void setThresholdTextColour(int thresholdTextColour)
2680   {
2681     viewStyle.setThresholdTextColour(thresholdTextColour);
2682   }
2683
2684   /**
2685    * @param textColour2
2686    * @see jalview.api.ViewStyleI#setTextColour2(java.awt.Color)
2687    */
2688   @Override
2689   public void setTextColour2(Color textColour2)
2690   {
2691     viewStyle.setTextColour2(textColour2);
2692   }
2693
2694   @Override
2695   public ViewStyleI getViewStyle()
2696   {
2697     return new ViewStyle(viewStyle);
2698   }
2699
2700   @Override
2701   public void setViewStyle(ViewStyleI settingsForView)
2702   {
2703     viewStyle = new ViewStyle(settingsForView);
2704     if (residueShading != null)
2705     {
2706       residueShading.setConservationApplied(
2707               settingsForView.isConservationColourSelected());
2708     }
2709   }
2710
2711   @Override
2712   public boolean sameStyle(ViewStyleI them)
2713   {
2714     return viewStyle.sameStyle(them);
2715   }
2716
2717   /**
2718    * @return
2719    * @see jalview.api.ViewStyleI#getIdWidth()
2720    */
2721   @Override
2722   public int getIdWidth()
2723   {
2724     return viewStyle.getIdWidth();
2725   }
2726
2727   /**
2728    * @param i
2729    * @see jalview.api.ViewStyleI#setIdWidth(int)
2730    */
2731   @Override
2732   public void setIdWidth(int i)
2733   {
2734     viewStyle.setIdWidth(i);
2735   }
2736
2737   /**
2738    * @return
2739    * @see jalview.api.ViewStyleI#isCentreColumnLabels()
2740    */
2741   @Override
2742   public boolean isCentreColumnLabels()
2743   {
2744     return viewStyle.isCentreColumnLabels();
2745   }
2746
2747   /**
2748    * @param centreColumnLabels
2749    * @see jalview.api.ViewStyleI#setCentreColumnLabels(boolean)
2750    */
2751   @Override
2752   public void setCentreColumnLabels(boolean centreColumnLabels)
2753   {
2754     viewStyle.setCentreColumnLabels(centreColumnLabels);
2755   }
2756
2757   /**
2758    * @param showdbrefs
2759    * @see jalview.api.ViewStyleI#setShowDBRefs(boolean)
2760    */
2761   @Override
2762   public void setShowDBRefs(boolean showdbrefs)
2763   {
2764     viewStyle.setShowDBRefs(showdbrefs);
2765   }
2766
2767   /**
2768    * @return
2769    * @see jalview.api.ViewStyleI#isShowDBRefs()
2770    */
2771   @Override
2772   public boolean isShowDBRefs()
2773   {
2774     return viewStyle.isShowDBRefs();
2775   }
2776
2777   /**
2778    * @return
2779    * @see jalview.api.ViewStyleI#isShowNPFeats()
2780    */
2781   @Override
2782   public boolean isShowNPFeats()
2783   {
2784     return viewStyle.isShowNPFeats();
2785   }
2786
2787   /**
2788    * @param shownpfeats
2789    * @see jalview.api.ViewStyleI#setShowNPFeats(boolean)
2790    */
2791   @Override
2792   public void setShowNPFeats(boolean shownpfeats)
2793   {
2794     viewStyle.setShowNPFeats(shownpfeats);
2795   }
2796
2797   public abstract StructureSelectionManager getStructureSelectionManager();
2798
2799   /**
2800    * Add one command to the command history list.
2801    * 
2802    * @param command
2803    */
2804   public void addToHistoryList(CommandI command)
2805   {
2806     if (this.historyList != null)
2807     {
2808       this.historyList.push(command);
2809       broadcastCommand(command, false);
2810     }
2811   }
2812
2813   protected void broadcastCommand(CommandI command, boolean undo)
2814   {
2815     getStructureSelectionManager().commandPerformed(command, undo,
2816             getVamsasSource());
2817   }
2818
2819   /**
2820    * Add one command to the command redo list.
2821    * 
2822    * @param command
2823    */
2824   public void addToRedoList(CommandI command)
2825   {
2826     if (this.redoList != null)
2827     {
2828       this.redoList.push(command);
2829     }
2830     broadcastCommand(command, true);
2831   }
2832
2833   /**
2834    * Clear the command redo list.
2835    */
2836   public void clearRedoList()
2837   {
2838     if (this.redoList != null)
2839     {
2840       this.redoList.clear();
2841     }
2842   }
2843
2844   public void setHistoryList(Deque<CommandI> list)
2845   {
2846     this.historyList = list;
2847   }
2848
2849   public Deque<CommandI> getHistoryList()
2850   {
2851     return this.historyList;
2852   }
2853
2854   public void setRedoList(Deque<CommandI> list)
2855   {
2856     this.redoList = list;
2857   }
2858
2859   public Deque<CommandI> getRedoList()
2860   {
2861     return this.redoList;
2862   }
2863
2864   @Override
2865   public VamsasSource getVamsasSource()
2866   {
2867     return this;
2868   }
2869
2870   public SequenceAnnotationOrder getSortAnnotationsBy()
2871   {
2872     return sortAnnotationsBy;
2873   }
2874
2875   public void setSortAnnotationsBy(
2876           SequenceAnnotationOrder sortAnnotationsBy)
2877   {
2878     this.sortAnnotationsBy = sortAnnotationsBy;
2879   }
2880
2881   public boolean isShowAutocalculatedAbove()
2882   {
2883     return showAutocalculatedAbove;
2884   }
2885
2886   public void setShowAutocalculatedAbove(boolean showAutocalculatedAbove)
2887   {
2888     this.showAutocalculatedAbove = showAutocalculatedAbove;
2889   }
2890
2891   @Override
2892   public boolean isScaleProteinAsCdna()
2893   {
2894     return viewStyle.isScaleProteinAsCdna();
2895   }
2896
2897   @Override
2898   public void setScaleProteinAsCdna(boolean b)
2899   {
2900     viewStyle.setScaleProteinAsCdna(b);
2901   }
2902
2903   @Override
2904   public boolean isProteinFontAsCdna()
2905   {
2906     return viewStyle.isProteinFontAsCdna();
2907   }
2908
2909   @Override
2910   public void setProteinFontAsCdna(boolean b)
2911   {
2912     viewStyle.setProteinFontAsCdna(b);
2913   }
2914
2915   /**
2916    * @return true if view should scroll to show the highlighted region of a
2917    *         sequence
2918    * @return
2919    */
2920   @Override
2921   public final boolean isFollowHighlight()
2922   {
2923     return followHighlight;
2924   }
2925
2926   @Override
2927   public final void setFollowHighlight(boolean b)
2928   {
2929     this.followHighlight = b;
2930   }
2931
2932   @Override
2933   public ViewportRanges getRanges()
2934   {
2935     return ranges;
2936   }
2937
2938   /**
2939    * Helper method to populate the SearchResults with the location in the
2940    * complementary alignment to scroll to, in order to match this one.
2941    * 
2942    * @param sr
2943    *          the SearchResults to add to
2944    * @return the offset (below top of visible region) of the matched sequence
2945    */
2946   protected int findComplementScrollTarget(SearchResultsI sr)
2947   {
2948     final AlignViewportI complement = getCodingComplement();
2949     if (complement == null || !complement.isFollowHighlight())
2950     {
2951       return 0;
2952     }
2953     boolean iAmProtein = !getAlignment().isNucleotide();
2954     AlignmentI proteinAlignment = iAmProtein ? getAlignment()
2955             : complement.getAlignment();
2956     if (proteinAlignment == null)
2957     {
2958       return 0;
2959     }
2960     final List<AlignedCodonFrame> mappings = proteinAlignment
2961             .getCodonFrames();
2962
2963     /*
2964      * Heuristic: find the first mapped sequence (if any) with a non-gapped
2965      * residue in the middle column of the visible region. Scroll the
2966      * complementary alignment to line up the corresponding residue.
2967      */
2968     int seqOffset = 0;
2969     SequenceI sequence = null;
2970
2971     /*
2972      * locate 'middle' column (true middle if an odd number visible, left of
2973      * middle if an even number visible)
2974      */
2975     int middleColumn = ranges.getStartRes()
2976             + (ranges.getEndRes() - ranges.getStartRes()) / 2;
2977     final HiddenSequences hiddenSequences = getAlignment()
2978             .getHiddenSequences();
2979
2980     /*
2981      * searching to the bottom of the alignment gives smoother scrolling across
2982      * all gapped visible regions
2983      */
2984     int lastSeq = alignment.getHeight() - 1;
2985     List<AlignedCodonFrame> seqMappings = null;
2986     for (int seqNo = ranges
2987             .getStartSeq(); seqNo < lastSeq; seqNo++, seqOffset++)
2988     {
2989       sequence = getAlignment().getSequenceAt(seqNo);
2990       if (hiddenSequences != null && hiddenSequences.isHidden(sequence))
2991       {
2992         continue;
2993       }
2994       if (Comparison.isGap(sequence.getCharAt(middleColumn)))
2995       {
2996         continue;
2997       }
2998       seqMappings = MappingUtils.findMappingsForSequenceAndOthers(sequence,
2999               mappings,
3000               getCodingComplement().getAlignment().getSequences());
3001       if (!seqMappings.isEmpty())
3002       {
3003         break;
3004       }
3005     }
3006
3007     if (sequence == null || seqMappings == null || seqMappings.isEmpty())
3008     {
3009       /*
3010        * No ungapped mapped sequence in middle column - do nothing
3011        */
3012       return 0;
3013     }
3014     MappingUtils.addSearchResults(sr, sequence,
3015             sequence.findPosition(middleColumn), seqMappings);
3016     return seqOffset;
3017   }
3018
3019   /**
3020    * synthesize a column selection if none exists so it covers the given
3021    * selection group. if wholewidth is false, no column selection is made if the
3022    * selection group covers the whole alignment width.
3023    * 
3024    * @param sg
3025    * @param wholewidth
3026    */
3027   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
3028   {
3029     int sgs, sge;
3030     if (sg != null && (sgs = sg.getStartRes()) >= 0
3031             && sg.getStartRes() <= (sge = sg.getEndRes())
3032             && !this.hasSelectedColumns())
3033     {
3034       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
3035       {
3036         // do nothing
3037         return;
3038       }
3039       if (colSel == null)
3040       {
3041         colSel = new ColumnSelection();
3042       }
3043       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
3044       {
3045         colSel.addElement(cspos);
3046       }
3047     }
3048   }
3049
3050   /**
3051    * hold status of current selection group - defined on alignment or not.
3052    */
3053   private boolean selectionIsDefinedGroup = false;
3054
3055   @Override
3056   public boolean isSelectionDefinedGroup()
3057   {
3058     if (selectionGroup == null)
3059     {
3060       return false;
3061     }
3062     if (isSelectionGroupChanged(true))
3063     {
3064       selectionIsDefinedGroup = false;
3065       List<SequenceGroup> gps = alignment.getGroups();
3066       if (gps == null || gps.size() == 0)
3067       {
3068         selectionIsDefinedGroup = false;
3069       }
3070       else
3071       {
3072         selectionIsDefinedGroup = gps.contains(selectionGroup);
3073       }
3074     }
3075     return selectionGroup.isDefined() || selectionIsDefinedGroup;
3076   }
3077
3078   /**
3079    * null, or currently highlighted results on this view
3080    */
3081   private SearchResultsI searchResults = null;
3082
3083   protected TreeModel currentTree = 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   @Override
3158   public void setCurrentTree(TreeModel tree)
3159   {
3160     currentTree = tree;
3161   }
3162
3163   @Override
3164   public TreeModel getCurrentTree()
3165   {
3166     return currentTree;
3167   }
3168 }