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