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