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