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