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