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