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