Merge branch 'develop' into bug/JAL-4353_cannot_output_multiple_different_structure_i...
[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.styles.ViewStyle;
76 import jalview.workers.AlignCalcManager;
77 import jalview.workers.ComplementConsensusThread;
78 import jalview.workers.ConsensusThread;
79 import jalview.workers.StrucConsensusThread;
80
81 /**
82  * base class holding visualization and analysis attributes and common logic for
83  * an active alignment view displayed in the GUI
84  * 
85  * @author jimp
86  * 
87  */
88 public abstract class AlignmentViewport
89         implements AlignViewportI, CommandListener, VamsasSource
90 {
91   protected ViewportRanges ranges;
92
93   protected ViewStyleI viewStyle = new ViewStyle();
94
95   /**
96    * A viewport that hosts the cDna view of this (protein), or vice versa (if
97    * set).
98    */
99   AlignViewportI codingComplement = null;
100
101   FeaturesDisplayedI featuresDisplayed = null;
102
103   protected Deque<CommandI> historyList = new ArrayDeque<>();
104
105   protected Deque<CommandI> redoList = new ArrayDeque<>();
106
107   /**
108    * used to determine if quit should be confirmed
109    */
110   private boolean savedUpToDate = false;
111
112   /**
113    * alignment displayed in the viewport. Please use get/setter
114    */
115   protected AlignmentI alignment;
116
117   public AlignmentViewport(AlignmentI al)
118   {
119     setAlignment(al);
120     ranges = new ViewportRanges(al);
121   }
122
123   /**
124    * @param name
125    * @see jalview.api.ViewStyleI#setFontName(java.lang.String)
126    */
127   @Override
128   public void setFontName(String name)
129   {
130     viewStyle.setFontName(name);
131   }
132
133   /**
134    * @param style
135    * @see jalview.api.ViewStyleI#setFontStyle(int)
136    */
137   @Override
138   public void setFontStyle(int style)
139   {
140     viewStyle.setFontStyle(style);
141   }
142
143   /**
144    * @param size
145    * @see jalview.api.ViewStyleI#setFontSize(int)
146    */
147   @Override
148   public void setFontSize(int size)
149   {
150     viewStyle.setFontSize(size);
151   }
152
153   /**
154    * @return
155    * @see jalview.api.ViewStyleI#getFontStyle()
156    */
157   @Override
158   public int getFontStyle()
159   {
160     return viewStyle.getFontStyle();
161   }
162
163   /**
164    * @return
165    * @see jalview.api.ViewStyleI#getFontName()
166    */
167   @Override
168   public String getFontName()
169   {
170     return viewStyle.getFontName();
171   }
172
173   /**
174    * @return
175    * @see jalview.api.ViewStyleI#getFontSize()
176    */
177   @Override
178   public int getFontSize()
179   {
180     return viewStyle.getFontSize();
181   }
182
183   /**
184    * @param upperCasebold
185    * @see jalview.api.ViewStyleI#setUpperCasebold(boolean)
186    */
187   @Override
188   public void setUpperCasebold(boolean upperCasebold)
189   {
190     viewStyle.setUpperCasebold(upperCasebold);
191   }
192
193   /**
194    * @return
195    * @see jalview.api.ViewStyleI#isUpperCasebold()
196    */
197   @Override
198   public boolean isUpperCasebold()
199   {
200     return viewStyle.isUpperCasebold();
201   }
202
203   /**
204    * @return
205    * @see jalview.api.ViewStyleI#isSeqNameItalics()
206    */
207   @Override
208   public boolean isSeqNameItalics()
209   {
210     return viewStyle.isSeqNameItalics();
211   }
212
213   /**
214    * @param colourByReferenceSeq
215    * @see jalview.api.ViewStyleI#setColourByReferenceSeq(boolean)
216    */
217   @Override
218   public void setColourByReferenceSeq(boolean colourByReferenceSeq)
219   {
220     viewStyle.setColourByReferenceSeq(colourByReferenceSeq);
221   }
222
223   /**
224    * @param b
225    * @see jalview.api.ViewStyleI#setColourAppliesToAllGroups(boolean)
226    */
227   @Override
228   public void setColourAppliesToAllGroups(boolean b)
229   {
230     viewStyle.setColourAppliesToAllGroups(b);
231   }
232
233   /**
234    * @return
235    * @see jalview.api.ViewStyleI#getColourAppliesToAllGroups()
236    */
237   @Override
238   public boolean getColourAppliesToAllGroups()
239   {
240     return viewStyle.getColourAppliesToAllGroups();
241   }
242
243   /**
244    * @return
245    * @see jalview.api.ViewStyleI#getAbovePIDThreshold()
246    */
247   @Override
248   public boolean getAbovePIDThreshold()
249   {
250     return viewStyle.getAbovePIDThreshold();
251   }
252
253   /**
254    * @param inc
255    * @see jalview.api.ViewStyleI#setIncrement(int)
256    */
257   @Override
258   public void setIncrement(int inc)
259   {
260     viewStyle.setIncrement(inc);
261   }
262
263   /**
264    * @return
265    * @see jalview.api.ViewStyleI#getIncrement()
266    */
267   @Override
268   public int getIncrement()
269   {
270     return viewStyle.getIncrement();
271   }
272
273   /**
274    * @param b
275    * @see jalview.api.ViewStyleI#setConservationSelected(boolean)
276    */
277   @Override
278   public void setConservationSelected(boolean b)
279   {
280     viewStyle.setConservationSelected(b);
281   }
282
283   /**
284    * @param show
285    * @see jalview.api.ViewStyleI#setShowHiddenMarkers(boolean)
286    */
287   @Override
288   public void setShowHiddenMarkers(boolean show)
289   {
290     viewStyle.setShowHiddenMarkers(show);
291   }
292
293   /**
294    * @return
295    * @see jalview.api.ViewStyleI#getShowHiddenMarkers()
296    */
297   @Override
298   public boolean getShowHiddenMarkers()
299   {
300     return viewStyle.getShowHiddenMarkers();
301   }
302
303   /**
304    * @param b
305    * @see jalview.api.ViewStyleI#setScaleRightWrapped(boolean)
306    */
307   @Override
308   public void setScaleRightWrapped(boolean b)
309   {
310     viewStyle.setScaleRightWrapped(b);
311   }
312
313   /**
314    * @param b
315    * @see jalview.api.ViewStyleI#setScaleLeftWrapped(boolean)
316    */
317   @Override
318   public void setScaleLeftWrapped(boolean b)
319   {
320     viewStyle.setScaleLeftWrapped(b);
321   }
322
323   /**
324    * @param b
325    * @see jalview.api.ViewStyleI#setScaleAboveWrapped(boolean)
326    */
327   @Override
328   public void setScaleAboveWrapped(boolean b)
329   {
330     viewStyle.setScaleAboveWrapped(b);
331   }
332
333   /**
334    * @return
335    * @see jalview.api.ViewStyleI#getScaleLeftWrapped()
336    */
337   @Override
338   public boolean getScaleLeftWrapped()
339   {
340     return viewStyle.getScaleLeftWrapped();
341   }
342
343   /**
344    * @return
345    * @see jalview.api.ViewStyleI#getScaleAboveWrapped()
346    */
347   @Override
348   public boolean getScaleAboveWrapped()
349   {
350     return viewStyle.getScaleAboveWrapped();
351   }
352
353   /**
354    * @return
355    * @see jalview.api.ViewStyleI#getScaleRightWrapped()
356    */
357   @Override
358   public boolean getScaleRightWrapped()
359   {
360     return viewStyle.getScaleRightWrapped();
361   }
362
363   /**
364    * @param b
365    * @see jalview.api.ViewStyleI#setAbovePIDThreshold(boolean)
366    */
367   @Override
368   public void setAbovePIDThreshold(boolean b)
369   {
370     viewStyle.setAbovePIDThreshold(b);
371   }
372
373   /**
374    * @param thresh
375    * @see jalview.api.ViewStyleI#setThreshold(int)
376    */
377   @Override
378   public void setThreshold(int thresh)
379   {
380     viewStyle.setThreshold(thresh);
381   }
382
383   /**
384    * @return
385    * @see jalview.api.ViewStyleI#getThreshold()
386    */
387   @Override
388   public int getThreshold()
389   {
390     return viewStyle.getThreshold();
391   }
392
393   /**
394    * @return
395    * @see jalview.api.ViewStyleI#getShowJVSuffix()
396    */
397   @Override
398   public boolean getShowJVSuffix()
399   {
400     return viewStyle.getShowJVSuffix();
401   }
402
403   /**
404    * @param b
405    * @see jalview.api.ViewStyleI#setShowJVSuffix(boolean)
406    */
407   @Override
408   public void setShowJVSuffix(boolean b)
409   {
410     viewStyle.setShowJVSuffix(b);
411   }
412
413   /**
414    * @param state
415    * @see jalview.api.ViewStyleI#setWrapAlignment(boolean)
416    */
417   @Override
418   public void setWrapAlignment(boolean state)
419   {
420     viewStyle.setWrapAlignment(state);
421     ranges.setWrappedMode(state);
422   }
423
424   /**
425    * @param state
426    * @see jalview.api.ViewStyleI#setShowText(boolean)
427    */
428   @Override
429   public void setShowText(boolean state)
430   {
431     viewStyle.setShowText(state);
432   }
433
434   /**
435    * @param state
436    * @see jalview.api.ViewStyleI#setRenderGaps(boolean)
437    */
438   @Override
439   public void setRenderGaps(boolean state)
440   {
441     viewStyle.setRenderGaps(state);
442   }
443
444   /**
445    * @return
446    * @see jalview.api.ViewStyleI#getColourText()
447    */
448   @Override
449   public boolean getColourText()
450   {
451     return viewStyle.getColourText();
452   }
453
454   /**
455    * @param state
456    * @see jalview.api.ViewStyleI#setColourText(boolean)
457    */
458   @Override
459   public void setColourText(boolean state)
460   {
461     viewStyle.setColourText(state);
462   }
463
464   /**
465    * @return
466    * @see jalview.api.ViewStyleI#getWrapAlignment()
467    */
468   @Override
469   public boolean getWrapAlignment()
470   {
471     return viewStyle.getWrapAlignment();
472   }
473
474   /**
475    * @return
476    * @see jalview.api.ViewStyleI#getShowText()
477    */
478   @Override
479   public boolean getShowText()
480   {
481     return viewStyle.getShowText();
482   }
483
484   /**
485    * @return
486    * @see jalview.api.ViewStyleI#getWrappedWidth()
487    */
488   @Override
489   public int getWrappedWidth()
490   {
491     return viewStyle.getWrappedWidth();
492   }
493
494   /**
495    * @param w
496    * @see jalview.api.ViewStyleI#setWrappedWidth(int)
497    */
498   @Override
499   public void setWrappedWidth(int w)
500   {
501     viewStyle.setWrappedWidth(w);
502   }
503
504   /**
505    * @return
506    * @see jalview.api.ViewStyleI#getCharHeight()
507    */
508   @Override
509   public int getCharHeight()
510   {
511     return viewStyle.getCharHeight();
512   }
513
514   /**
515    * @param h
516    * @see jalview.api.ViewStyleI#setCharHeight(int)
517    */
518   @Override
519   public void setCharHeight(int h)
520   {
521     viewStyle.setCharHeight(h);
522   }
523
524   /**
525    * @return
526    * @see jalview.api.ViewStyleI#getCharWidth()
527    */
528   @Override
529   public int getCharWidth()
530   {
531     return viewStyle.getCharWidth();
532   }
533
534   /**
535    * @param w
536    * @see jalview.api.ViewStyleI#setCharWidth(int)
537    */
538   @Override
539   public void setCharWidth(int w)
540   {
541     viewStyle.setCharWidth(w);
542   }
543
544   /**
545    * @return
546    * @see jalview.api.ViewStyleI#getShowBoxes()
547    */
548   @Override
549   public boolean getShowBoxes()
550   {
551     return viewStyle.getShowBoxes();
552   }
553
554   /**
555    * @return
556    * @see jalview.api.ViewStyleI#getShowUnconserved()
557    */
558   @Override
559   public boolean getShowUnconserved()
560   {
561     return viewStyle.getShowUnconserved();
562   }
563
564   /**
565    * @param showunconserved
566    * @see jalview.api.ViewStyleI#setShowUnconserved(boolean)
567    */
568   @Override
569   public void setShowUnconserved(boolean showunconserved)
570   {
571     viewStyle.setShowUnconserved(showunconserved);
572   }
573
574   /**
575    * @param default1
576    * @see jalview.api.ViewStyleI#setSeqNameItalics(boolean)
577    */
578   @Override
579   public void setSeqNameItalics(boolean default1)
580   {
581     viewStyle.setSeqNameItalics(default1);
582   }
583
584   @Override
585   public AlignmentI getAlignment()
586   {
587     return alignment;
588   }
589
590   @Override
591   public char getGapCharacter()
592   {
593     return alignment.getGapCharacter();
594   }
595
596   protected String sequenceSetID;
597
598   /**
599    * probably unused indicator that view is of a dataset rather than an
600    * alignment
601    */
602   protected boolean isDataset = false;
603
604   public void setDataset(boolean b)
605   {
606     isDataset = b;
607   }
608
609   public boolean isDataset()
610   {
611     return isDataset;
612   }
613
614   private Map<SequenceI, SequenceCollectionI> hiddenRepSequences;
615
616   protected ColumnSelection colSel = new ColumnSelection();
617
618   public boolean autoCalculateConsensus = true;
619
620   protected boolean autoCalculateStrucConsensus = true;
621
622   protected boolean ignoreGapsInConsensusCalculation = false;
623
624   protected ResidueShaderI residueShading = new ResidueShader();
625
626   @Override
627   public void setGlobalColourScheme(ColourSchemeI cs)
628   {
629     // TODO: logic refactored from AlignFrame changeColour -
630     // TODO: autorecalc stuff should be changed to rely on the worker system
631     // check to see if we should implement a changeColour(cs) method rather than
632     // put the logic in here
633     // - means that caller decides if they want to just modify state and defer
634     // calculation till later or to do all calculations in thread.
635     // via changecolour
636
637     /*
638      * only instantiate alignment colouring once, thereafter update it;
639      * this means that any conservation or PID threshold settings
640      * persist when the alignment colour scheme is changed
641      */
642     if (residueShading == null)
643     {
644       residueShading = new ResidueShader(viewStyle);
645     }
646     residueShading.setColourScheme(cs);
647
648     // TODO: do threshold and increment belong in ViewStyle or ResidueShader?
649     // ...problem: groups need these, but do not currently have a ViewStyle
650
651     if (cs != null)
652     {
653       if (getConservationSelected())
654       {
655         residueShading.setConservation(hconservation);
656       }
657       /*
658        * reset conservation flag in case just set to false if
659        * Conservation was null (calculation still in progress)
660        */
661       residueShading.setConservationApplied(getConservationSelected());
662       residueShading.alignmentChanged(alignment, hiddenRepSequences);
663     }
664
665     /*
666      * if 'apply colour to all groups' is selected... do so
667      * (but don't transfer any colour threshold settings to groups)
668      */
669     if (getColourAppliesToAllGroups())
670     {
671       for (SequenceGroup sg : getAlignment().getGroups())
672       {
673         /*
674          * retain any colour thresholds per group while
675          * changing choice of colour scheme (JAL-2386)
676          */
677         sg.setColourScheme(cs == null ? null : cs.getInstance(this, sg));
678         if (cs != null)
679         {
680           sg.getGroupColourScheme().alignmentChanged(sg,
681                   hiddenRepSequences);
682         }
683       }
684     }
685   }
686
687   @Override
688   public ColourSchemeI getGlobalColourScheme()
689   {
690     return residueShading == null ? null : residueShading.getColourScheme();
691   }
692
693   @Override
694   public ResidueShaderI getResidueShading()
695   {
696     return residueShading;
697   }
698
699   protected AlignmentAnnotation consensus;
700
701   protected AlignmentAnnotation complementConsensus;
702
703   protected AlignmentAnnotation gapcounts;
704
705   protected AlignmentAnnotation strucConsensus;
706
707   protected AlignmentAnnotation conservation;
708
709   protected AlignmentAnnotation quality;
710
711   protected AlignmentAnnotation[] groupConsensus;
712
713   protected AlignmentAnnotation[] groupConservation;
714
715   /**
716    * results of alignment consensus analysis for visible portion of view
717    */
718   protected ProfilesI hconsensus = null;
719
720   /**
721    * results of cDNA complement consensus visible portion of view
722    */
723   protected Hashtable<String, Object>[] hcomplementConsensus = null;
724
725   /**
726    * results of secondary structure base pair consensus for visible portion of
727    * view
728    */
729   protected Hashtable<String, Object>[] hStrucConsensus = null;
730
731   protected Conservation hconservation = null;
732
733   @Override
734   public void setConservation(Conservation cons)
735   {
736     hconservation = cons;
737   }
738
739   /**
740    * percentage gaps allowed in a column before all amino acid properties should
741    * be considered unconserved
742    */
743   int ConsPercGaps = 25; // JBPNote : This should be a scalable property!
744
745   @Override
746   public int getConsPercGaps()
747   {
748     return ConsPercGaps;
749   }
750
751   @Override
752   public void setSequenceConsensusHash(ProfilesI hconsensus)
753   {
754     this.hconsensus = hconsensus;
755   }
756
757   @Override
758   public void setComplementConsensusHash(
759           Hashtable<String, Object>[] hconsensus)
760   {
761     this.hcomplementConsensus = hconsensus;
762   }
763
764   @Override
765   public ProfilesI getSequenceConsensusHash()
766   {
767     return hconsensus;
768   }
769
770   @Override
771   public Hashtable<String, Object>[] getComplementConsensusHash()
772   {
773     return hcomplementConsensus;
774   }
775
776   @Override
777   public Hashtable<String, Object>[] getRnaStructureConsensusHash()
778   {
779     return hStrucConsensus;
780   }
781
782   @Override
783   public void setRnaStructureConsensusHash(
784           Hashtable<String, Object>[] hStrucConsensus)
785   {
786     this.hStrucConsensus = hStrucConsensus;
787
788   }
789
790   @Override
791   public AlignmentAnnotation getAlignmentQualityAnnot()
792   {
793     return quality;
794   }
795
796   @Override
797   public AlignmentAnnotation getAlignmentConservationAnnotation()
798   {
799     return conservation;
800   }
801
802   @Override
803   public AlignmentAnnotation getAlignmentConsensusAnnotation()
804   {
805     return consensus;
806   }
807
808   @Override
809   public AlignmentAnnotation getAlignmentGapAnnotation()
810   {
811     return gapcounts;
812   }
813
814   @Override
815   public AlignmentAnnotation getComplementConsensusAnnotation()
816   {
817     return complementConsensus;
818   }
819
820   @Override
821   public AlignmentAnnotation getAlignmentStrucConsensusAnnotation()
822   {
823     return strucConsensus;
824   }
825
826   protected AlignCalcManagerI calculator = new AlignCalcManager();
827
828   /**
829    * trigger update of conservation annotation
830    */
831   public void updateConservation(final AlignmentViewPanel ap)
832   {
833     // see note in mantis : issue number 8585
834     if (alignment.isNucleotide()
835             || (conservation == null && quality == null)
836             || !autoCalculateConsensus)
837     {
838       return;
839     }
840     if (calculator.getRegisteredWorkersOfClass(
841             jalview.workers.ConservationThread.class) == null)
842     {
843       calculator.registerWorker(
844               new jalview.workers.ConservationThread(this, ap));
845     }
846   }
847
848   /**
849    * trigger update of consensus annotation
850    */
851   public void updateConsensus(final AlignmentViewPanel ap)
852   {
853     // see note in mantis : issue number 8585
854     if (consensus == null || !autoCalculateConsensus)
855     {
856       return;
857     }
858     if (calculator
859             .getRegisteredWorkersOfClass(ConsensusThread.class) == null)
860     {
861       calculator.registerWorker(new ConsensusThread(this, ap));
862     }
863
864     /*
865      * A separate thread to compute cDNA consensus for a protein alignment
866      * which has mapping to cDNA
867      */
868     final AlignmentI al = this.getAlignment();
869     if (!al.isNucleotide() && al.getCodonFrames() != null
870             && !al.getCodonFrames().isEmpty())
871     {
872       /*
873        * fudge - check first for protein-to-nucleotide mappings
874        * (we don't want to do this for protein-to-protein)
875        */
876       boolean doConsensus = false;
877       for (AlignedCodonFrame mapping : al.getCodonFrames())
878       {
879         // TODO hold mapping type e.g. dna-to-protein in AlignedCodonFrame?
880         MapList[] mapLists = mapping.getdnaToProt();
881         // mapLists can be empty if project load has not finished resolving seqs
882         if (mapLists.length > 0 && mapLists[0].getFromRatio() == 3)
883         {
884           doConsensus = true;
885           break;
886         }
887       }
888       if (doConsensus)
889       {
890         if (calculator.getRegisteredWorkersOfClass(
891                 ComplementConsensusThread.class) == null)
892         {
893           calculator
894                   .registerWorker(new ComplementConsensusThread(this, ap));
895         }
896       }
897     }
898   }
899
900   // --------START Structure Conservation
901   public void updateStrucConsensus(final AlignmentViewPanel ap)
902   {
903     if (autoCalculateStrucConsensus && strucConsensus == null
904             && alignment.isNucleotide() && alignment.hasRNAStructure())
905     {
906       // secondary structure has been added - so init the consensus line
907       initRNAStructure();
908     }
909
910     // see note in mantis : issue number 8585
911     if (strucConsensus == null || !autoCalculateStrucConsensus)
912     {
913       return;
914     }
915     if (calculator.getRegisteredWorkersOfClass(
916             StrucConsensusThread.class) == null)
917     {
918       calculator.registerWorker(new StrucConsensusThread(this, ap));
919     }
920   }
921
922   public boolean isCalcInProgress()
923   {
924     return calculator.isWorking();
925   }
926
927   @Override
928   public boolean isCalculationInProgress(
929           AlignmentAnnotation alignmentAnnotation)
930   {
931     if (!alignmentAnnotation.autoCalculated)
932     {
933       return false;
934     }
935     if (calculator.workingInvolvedWith(alignmentAnnotation))
936     {
937       // jalview.bin.Console.errPrintln("grey out
938       // ("+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
2298               .errPrintln("Ignoring recursive setCodingComplement request");
2299     }
2300     else
2301     {
2302       this.codingComplement = av;
2303       // avoid infinite recursion!
2304       if (av.getCodingComplement() != this)
2305       {
2306         av.setCodingComplement(this);
2307       }
2308     }
2309   }
2310
2311   @Override
2312   public boolean isNucleotide()
2313   {
2314     return getAlignment() == null ? false : getAlignment().isNucleotide();
2315   }
2316
2317   @Override
2318   public FeaturesDisplayedI getFeaturesDisplayed()
2319   {
2320     return featuresDisplayed;
2321   }
2322
2323   @Override
2324   public void setFeaturesDisplayed(FeaturesDisplayedI featuresDisplayedI)
2325   {
2326     featuresDisplayed = featuresDisplayedI;
2327   }
2328
2329   @Override
2330   public boolean areFeaturesDisplayed()
2331   {
2332     return featuresDisplayed != null
2333             && featuresDisplayed.getRegisteredFeaturesCount() > 0;
2334   }
2335
2336   /**
2337    * set the flag
2338    * 
2339    * @param b
2340    *          features are displayed if true
2341    */
2342   @Override
2343   public void setShowSequenceFeatures(boolean b)
2344   {
2345     viewStyle.setShowSequenceFeatures(b);
2346   }
2347
2348   @Override
2349   public boolean isShowSequenceFeatures()
2350   {
2351     return viewStyle.isShowSequenceFeatures();
2352   }
2353
2354   @Override
2355   public void setShowSequenceFeaturesHeight(boolean selected)
2356   {
2357     viewStyle.setShowSequenceFeaturesHeight(selected);
2358   }
2359
2360   @Override
2361   public boolean isShowSequenceFeaturesHeight()
2362   {
2363     return viewStyle.isShowSequenceFeaturesHeight();
2364   }
2365
2366   @Override
2367   public void setShowAnnotation(boolean b)
2368   {
2369     viewStyle.setShowAnnotation(b);
2370   }
2371
2372   @Override
2373   public boolean isShowAnnotation()
2374   {
2375     return viewStyle.isShowAnnotation();
2376   }
2377
2378   @Override
2379   public boolean isRightAlignIds()
2380   {
2381     return viewStyle.isRightAlignIds();
2382   }
2383
2384   @Override
2385   public void setRightAlignIds(boolean rightAlignIds)
2386   {
2387     viewStyle.setRightAlignIds(rightAlignIds);
2388   }
2389
2390   @Override
2391   public boolean getConservationSelected()
2392   {
2393     return viewStyle.getConservationSelected();
2394   }
2395
2396   @Override
2397   public void setShowBoxes(boolean state)
2398   {
2399     viewStyle.setShowBoxes(state);
2400   }
2401
2402   /**
2403    * @return
2404    * @see jalview.api.ViewStyleI#getTextColour()
2405    */
2406   @Override
2407   public Color getTextColour()
2408   {
2409     return viewStyle.getTextColour();
2410   }
2411
2412   /**
2413    * @return
2414    * @see jalview.api.ViewStyleI#getTextColour2()
2415    */
2416   @Override
2417   public Color getTextColour2()
2418   {
2419     return viewStyle.getTextColour2();
2420   }
2421
2422   /**
2423    * @return
2424    * @see jalview.api.ViewStyleI#getThresholdTextColour()
2425    */
2426   @Override
2427   public int getThresholdTextColour()
2428   {
2429     return viewStyle.getThresholdTextColour();
2430   }
2431
2432   /**
2433    * @return
2434    * @see jalview.api.ViewStyleI#isConservationColourSelected()
2435    */
2436   @Override
2437   public boolean isConservationColourSelected()
2438   {
2439     return viewStyle.isConservationColourSelected();
2440   }
2441
2442   /**
2443    * @return
2444    * @see jalview.api.ViewStyleI#isRenderGaps()
2445    */
2446   @Override
2447   public boolean isRenderGaps()
2448   {
2449     return viewStyle.isRenderGaps();
2450   }
2451
2452   /**
2453    * @return
2454    * @see jalview.api.ViewStyleI#isShowColourText()
2455    */
2456   @Override
2457   public boolean isShowColourText()
2458   {
2459     return viewStyle.isShowColourText();
2460   }
2461
2462   /**
2463    * @param conservationColourSelected
2464    * @see jalview.api.ViewStyleI#setConservationColourSelected(boolean)
2465    */
2466   @Override
2467   public void setConservationColourSelected(
2468           boolean conservationColourSelected)
2469   {
2470     viewStyle.setConservationColourSelected(conservationColourSelected);
2471   }
2472
2473   /**
2474    * @param showColourText
2475    * @see jalview.api.ViewStyleI#setShowColourText(boolean)
2476    */
2477   @Override
2478   public void setShowColourText(boolean showColourText)
2479   {
2480     viewStyle.setShowColourText(showColourText);
2481   }
2482
2483   /**
2484    * @param textColour
2485    * @see jalview.api.ViewStyleI#setTextColour(java.awt.Color)
2486    */
2487   @Override
2488   public void setTextColour(Color textColour)
2489   {
2490     viewStyle.setTextColour(textColour);
2491   }
2492
2493   /**
2494    * @param thresholdTextColour
2495    * @see jalview.api.ViewStyleI#setThresholdTextColour(int)
2496    */
2497   @Override
2498   public void setThresholdTextColour(int thresholdTextColour)
2499   {
2500     viewStyle.setThresholdTextColour(thresholdTextColour);
2501   }
2502
2503   /**
2504    * @param textColour2
2505    * @see jalview.api.ViewStyleI#setTextColour2(java.awt.Color)
2506    */
2507   @Override
2508   public void setTextColour2(Color textColour2)
2509   {
2510     viewStyle.setTextColour2(textColour2);
2511   }
2512
2513   @Override
2514   public ViewStyleI getViewStyle()
2515   {
2516     return new ViewStyle(viewStyle);
2517   }
2518
2519   @Override
2520   public void setViewStyle(ViewStyleI settingsForView)
2521   {
2522     viewStyle = new ViewStyle(settingsForView);
2523     if (residueShading != null)
2524     {
2525       residueShading.setConservationApplied(
2526               settingsForView.isConservationColourSelected());
2527     }
2528   }
2529
2530   @Override
2531   public boolean sameStyle(ViewStyleI them)
2532   {
2533     return viewStyle.sameStyle(them);
2534   }
2535
2536   /**
2537    * @return
2538    * @see jalview.api.ViewStyleI#getIdWidth()
2539    */
2540   @Override
2541   public int getIdWidth()
2542   {
2543     return viewStyle.getIdWidth();
2544   }
2545
2546   /**
2547    * @param i
2548    * @see jalview.api.ViewStyleI#setIdWidth(int)
2549    */
2550   @Override
2551   public void setIdWidth(int i)
2552   {
2553     viewStyle.setIdWidth(i);
2554   }
2555
2556   /**
2557    * @return
2558    * @see jalview.api.ViewStyleI#isCentreColumnLabels()
2559    */
2560   @Override
2561   public boolean isCentreColumnLabels()
2562   {
2563     return viewStyle.isCentreColumnLabels();
2564   }
2565
2566   /**
2567    * @param centreColumnLabels
2568    * @see jalview.api.ViewStyleI#setCentreColumnLabels(boolean)
2569    */
2570   @Override
2571   public void setCentreColumnLabels(boolean centreColumnLabels)
2572   {
2573     viewStyle.setCentreColumnLabels(centreColumnLabels);
2574   }
2575
2576   /**
2577    * @param showdbrefs
2578    * @see jalview.api.ViewStyleI#setShowDBRefs(boolean)
2579    */
2580   @Override
2581   public void setShowDBRefs(boolean showdbrefs)
2582   {
2583     viewStyle.setShowDBRefs(showdbrefs);
2584   }
2585
2586   /**
2587    * @return
2588    * @see jalview.api.ViewStyleI#isShowDBRefs()
2589    */
2590   @Override
2591   public boolean isShowDBRefs()
2592   {
2593     return viewStyle.isShowDBRefs();
2594   }
2595
2596   /**
2597    * @return
2598    * @see jalview.api.ViewStyleI#isShowNPFeats()
2599    */
2600   @Override
2601   public boolean isShowNPFeats()
2602   {
2603     return viewStyle.isShowNPFeats();
2604   }
2605
2606   /**
2607    * @param shownpfeats
2608    * @see jalview.api.ViewStyleI#setShowNPFeats(boolean)
2609    */
2610   @Override
2611   public void setShowNPFeats(boolean shownpfeats)
2612   {
2613     viewStyle.setShowNPFeats(shownpfeats);
2614   }
2615
2616   public abstract StructureSelectionManager getStructureSelectionManager();
2617
2618   /**
2619    * Add one command to the command history list.
2620    * 
2621    * @param command
2622    */
2623   public void addToHistoryList(CommandI command)
2624   {
2625     if (this.historyList != null)
2626     {
2627       this.historyList.push(command);
2628       broadcastCommand(command, false);
2629       setSavedUpToDate(false);
2630       Jalview2XML.setStateSavedUpToDate(false);
2631     }
2632   }
2633
2634   protected void broadcastCommand(CommandI command, boolean undo)
2635   {
2636     getStructureSelectionManager().commandPerformed(command, undo,
2637             getVamsasSource());
2638   }
2639
2640   /**
2641    * Add one command to the command redo list.
2642    * 
2643    * @param command
2644    */
2645   public void addToRedoList(CommandI command)
2646   {
2647     if (this.redoList != null)
2648     {
2649       this.redoList.push(command);
2650     }
2651     broadcastCommand(command, true);
2652   }
2653
2654   /**
2655    * Clear the command redo list.
2656    */
2657   public void clearRedoList()
2658   {
2659     if (this.redoList != null)
2660     {
2661       this.redoList.clear();
2662     }
2663   }
2664
2665   public void setHistoryList(Deque<CommandI> list)
2666   {
2667     this.historyList = list;
2668   }
2669
2670   public Deque<CommandI> getHistoryList()
2671   {
2672     return this.historyList;
2673   }
2674
2675   public void setRedoList(Deque<CommandI> list)
2676   {
2677     this.redoList = list;
2678   }
2679
2680   public Deque<CommandI> getRedoList()
2681   {
2682     return this.redoList;
2683   }
2684
2685   @Override
2686   public VamsasSource getVamsasSource()
2687   {
2688     return this;
2689   }
2690
2691   public SequenceAnnotationOrder getSortAnnotationsBy()
2692   {
2693     return sortAnnotationsBy;
2694   }
2695
2696   public void setSortAnnotationsBy(
2697           SequenceAnnotationOrder sortAnnotationsBy)
2698   {
2699     this.sortAnnotationsBy = sortAnnotationsBy;
2700   }
2701
2702   public boolean isShowAutocalculatedAbove()
2703   {
2704     return showAutocalculatedAbove;
2705   }
2706
2707   public void setShowAutocalculatedAbove(boolean showAutocalculatedAbove)
2708   {
2709     this.showAutocalculatedAbove = showAutocalculatedAbove;
2710   }
2711
2712   @Override
2713   public boolean isScaleProteinAsCdna()
2714   {
2715     return viewStyle.isScaleProteinAsCdna();
2716   }
2717
2718   @Override
2719   public void setScaleProteinAsCdna(boolean b)
2720   {
2721     viewStyle.setScaleProteinAsCdna(b);
2722   }
2723
2724   @Override
2725   public boolean isProteinFontAsCdna()
2726   {
2727     return viewStyle.isProteinFontAsCdna();
2728   }
2729
2730   @Override
2731   public void setProteinFontAsCdna(boolean b)
2732   {
2733     viewStyle.setProteinFontAsCdna(b);
2734   }
2735
2736   @Override
2737   public void setShowComplementFeatures(boolean b)
2738   {
2739     viewStyle.setShowComplementFeatures(b);
2740   }
2741
2742   @Override
2743   public boolean isShowComplementFeatures()
2744   {
2745     return viewStyle.isShowComplementFeatures();
2746   }
2747
2748   @Override
2749   public void setShowComplementFeaturesOnTop(boolean b)
2750   {
2751     viewStyle.setShowComplementFeaturesOnTop(b);
2752   }
2753
2754   @Override
2755   public boolean isShowComplementFeaturesOnTop()
2756   {
2757     return viewStyle.isShowComplementFeaturesOnTop();
2758   }
2759
2760   /**
2761    * @return true if view should scroll to show the highlighted region of a
2762    *         sequence
2763    * @return
2764    */
2765   @Override
2766   public final boolean isFollowHighlight()
2767   {
2768     return followHighlight;
2769   }
2770
2771   @Override
2772   public final void setFollowHighlight(boolean b)
2773   {
2774     this.followHighlight = b;
2775   }
2776
2777   @Override
2778   public ViewportRanges getRanges()
2779   {
2780     return ranges;
2781   }
2782
2783   /**
2784    * Helper method to populate the SearchResults with the location in the
2785    * complementary alignment to scroll to, in order to match this one.
2786    * 
2787    * @param sr
2788    *          the SearchResults to add to
2789    * @return the offset (below top of visible region) of the matched sequence
2790    */
2791   protected int findComplementScrollTarget(SearchResultsI sr)
2792   {
2793     final AlignViewportI complement = getCodingComplement();
2794     if (complement == null || !complement.isFollowHighlight())
2795     {
2796       return 0;
2797     }
2798     boolean iAmProtein = !getAlignment().isNucleotide();
2799     AlignmentI proteinAlignment = iAmProtein ? getAlignment()
2800             : complement.getAlignment();
2801     if (proteinAlignment == null)
2802     {
2803       return 0;
2804     }
2805     final List<AlignedCodonFrame> mappings = proteinAlignment
2806             .getCodonFrames();
2807
2808     /*
2809      * Heuristic: find the first mapped sequence (if any) with a non-gapped
2810      * residue in the middle column of the visible region. Scroll the
2811      * complementary alignment to line up the corresponding residue.
2812      */
2813     int seqOffset = 0;
2814     SequenceI sequence = null;
2815
2816     /*
2817      * locate 'middle' column (true middle if an odd number visible, left of
2818      * middle if an even number visible)
2819      */
2820     int middleColumn = ranges.getStartRes()
2821             + (ranges.getEndRes() - ranges.getStartRes()) / 2;
2822     final HiddenSequences hiddenSequences = getAlignment()
2823             .getHiddenSequences();
2824
2825     /*
2826      * searching to the bottom of the alignment gives smoother scrolling across
2827      * all gapped visible regions
2828      */
2829     int lastSeq = alignment.getHeight() - 1;
2830     List<AlignedCodonFrame> seqMappings = null;
2831     for (int seqNo = ranges
2832             .getStartSeq(); seqNo <= lastSeq; seqNo++, seqOffset++)
2833     {
2834       sequence = getAlignment().getSequenceAt(seqNo);
2835       if (hiddenSequences != null && hiddenSequences.isHidden(sequence))
2836       {
2837         continue;
2838       }
2839       if (Comparison.isGap(sequence.getCharAt(middleColumn)))
2840       {
2841         continue;
2842       }
2843       seqMappings = MappingUtils.findMappingsForSequenceAndOthers(sequence,
2844               mappings,
2845               getCodingComplement().getAlignment().getSequences());
2846       if (!seqMappings.isEmpty())
2847       {
2848         break;
2849       }
2850     }
2851
2852     if (sequence == null || seqMappings == null || seqMappings.isEmpty())
2853     {
2854       /*
2855        * No ungapped mapped sequence in middle column - do nothing
2856        */
2857       return 0;
2858     }
2859     MappingUtils.addSearchResults(sr, sequence,
2860             sequence.findPosition(middleColumn), seqMappings);
2861     return seqOffset;
2862   }
2863
2864   /**
2865    * synthesize a column selection if none exists so it covers the given
2866    * selection group. if wholewidth is false, no column selection is made if the
2867    * selection group covers the whole alignment width.
2868    * 
2869    * @param sg
2870    * @param wholewidth
2871    */
2872   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
2873   {
2874     int sgs, sge;
2875     if (sg != null && (sgs = sg.getStartRes()) >= 0
2876             && sg.getStartRes() <= (sge = sg.getEndRes())
2877             && !this.hasSelectedColumns())
2878     {
2879       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
2880       {
2881         // do nothing
2882         return;
2883       }
2884       if (colSel == null)
2885       {
2886         colSel = new ColumnSelection();
2887       }
2888       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
2889       {
2890         colSel.addElement(cspos);
2891       }
2892     }
2893   }
2894
2895   /**
2896    * hold status of current selection group - defined on alignment or not.
2897    */
2898   private boolean selectionIsDefinedGroup = false;
2899
2900   @Override
2901   public boolean isSelectionDefinedGroup()
2902   {
2903     if (selectionGroup == null)
2904     {
2905       return false;
2906     }
2907     if (isSelectionGroupChanged(true))
2908     {
2909       selectionIsDefinedGroup = false;
2910       List<SequenceGroup> gps = alignment.getGroups();
2911       if (gps == null || gps.size() == 0)
2912       {
2913         selectionIsDefinedGroup = false;
2914       }
2915       else
2916       {
2917         selectionIsDefinedGroup = gps.contains(selectionGroup);
2918       }
2919     }
2920     return selectionGroup.isDefined() || selectionIsDefinedGroup;
2921   }
2922
2923   /**
2924    * null, or currently highlighted results on this view
2925    */
2926   private SearchResultsI searchResults = null;
2927
2928   protected TreeModel currentTree = null;
2929
2930   @Override
2931   public boolean hasSearchResults()
2932   {
2933     return searchResults != null;
2934   }
2935
2936   @Override
2937   public void setSearchResults(SearchResultsI results)
2938   {
2939     searchResults = results;
2940   }
2941
2942   @Override
2943   public SearchResultsI getSearchResults()
2944   {
2945     return searchResults;
2946   }
2947
2948   @Override
2949   public ContactListI getContactList(AlignmentAnnotation _aa, int column)
2950   {
2951     return alignment.getContactListFor(_aa, column);
2952   }
2953
2954   @Override
2955   public ContactMatrixI getContactMatrix(
2956           AlignmentAnnotation alignmentAnnotation)
2957   {
2958     return alignment.getContactMatrixFor(alignmentAnnotation);
2959   }
2960
2961   /**
2962    * get the consensus sequence as displayed under the PID consensus annotation
2963    * row.
2964    * 
2965    * @return consensus sequence as a new sequence object
2966    */
2967   public SequenceI getConsensusSeq()
2968   {
2969     if (consensus == null)
2970     {
2971       updateConsensus(null);
2972     }
2973     if (consensus == null)
2974     {
2975       return null;
2976     }
2977     StringBuffer seqs = new StringBuffer();
2978     for (int i = 0; i < consensus.annotations.length; i++)
2979     {
2980       Annotation annotation = consensus.annotations[i];
2981       if (annotation != null)
2982       {
2983         String description = annotation.description;
2984         if (description != null && description.startsWith("["))
2985         {
2986           // consensus is a tie - just pick the first one
2987           seqs.append(description.charAt(1));
2988         }
2989         else
2990         {
2991           seqs.append(annotation.displayCharacter);
2992         }
2993       }
2994     }
2995
2996     SequenceI sq = new Sequence("Consensus", seqs.toString());
2997     sq.setDescription("Percentage Identity Consensus "
2998             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
2999     return sq;
3000   }
3001
3002   @Override
3003   public void setCurrentTree(TreeModel tree)
3004   {
3005     currentTree = tree;
3006   }
3007
3008   @Override
3009   public TreeModel getCurrentTree()
3010   {
3011     return currentTree;
3012   }
3013
3014   @Override
3015   public AlignmentExportData getAlignExportData(
3016           AlignExportSettingsI options)
3017   {
3018     AlignmentI alignmentToExport = null;
3019     String[] omitHidden = null;
3020     alignmentToExport = null;
3021
3022     if (hasHiddenColumns() && !options.isExportHiddenColumns())
3023     {
3024       omitHidden = getViewAsString(false,
3025               options.isExportHiddenSequences());
3026     }
3027
3028     int[] alignmentStartEnd = new int[2];
3029     if (hasHiddenRows() && options.isExportHiddenSequences())
3030     {
3031       alignmentToExport = getAlignment().getHiddenSequences()
3032               .getFullAlignment();
3033     }
3034     else
3035     {
3036       alignmentToExport = getAlignment();
3037     }
3038     alignmentStartEnd = getAlignment().getHiddenColumns()
3039             .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
3040     AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
3041             omitHidden, alignmentStartEnd);
3042     return ed;
3043   }
3044
3045   /**
3046    * flag set to indicate if structure views might be out of sync with sequences
3047    * in the alignment
3048    */
3049
3050   private boolean needToUpdateStructureViews = false;
3051
3052   @Override
3053   public boolean isUpdateStructures()
3054   {
3055     return needToUpdateStructureViews;
3056   }
3057
3058   @Override
3059   public void setUpdateStructures(boolean update)
3060   {
3061     needToUpdateStructureViews = update;
3062   }
3063
3064   @Override
3065   public boolean needToUpdateStructureViews()
3066   {
3067     boolean update = needToUpdateStructureViews;
3068     needToUpdateStructureViews = false;
3069     return update;
3070   }
3071
3072   @Override
3073   public void addSequenceGroup(SequenceGroup sequenceGroup)
3074   {
3075     alignment.addGroup(sequenceGroup);
3076
3077     Color col = sequenceGroup.idColour;
3078     if (col != null)
3079     {
3080       col = col.brighter();
3081
3082       for (SequenceI sq : sequenceGroup.getSequences())
3083       {
3084         setSequenceColour(sq, col);
3085       }
3086     }
3087
3088     if (codingComplement != null)
3089     {
3090       SequenceGroup mappedGroup = MappingUtils
3091               .mapSequenceGroup(sequenceGroup, this, codingComplement);
3092       if (mappedGroup.getSequences().size() > 0)
3093       {
3094         codingComplement.getAlignment().addGroup(mappedGroup);
3095
3096         if (col != null)
3097         {
3098           for (SequenceI seq : mappedGroup.getSequences())
3099           {
3100             codingComplement.setSequenceColour(seq, col);
3101           }
3102         }
3103       }
3104       // propagate the structure view update flag according to our own setting
3105       codingComplement.setUpdateStructures(needToUpdateStructureViews);
3106     }
3107   }
3108
3109   @Override
3110   public Iterator<int[]> getViewAsVisibleContigs(boolean selectedRegionOnly)
3111   {
3112     int start = 0;
3113     int end = 0;
3114     if (selectedRegionOnly && selectionGroup != null)
3115     {
3116       start = selectionGroup.getStartRes();
3117       end = selectionGroup.getEndRes() + 1;
3118     }
3119     else
3120     {
3121       end = alignment.getWidth();
3122     }
3123     return (alignment.getHiddenColumns().getVisContigsIterator(start, end,
3124             false));
3125   }
3126
3127   public void setSavedUpToDate(boolean s)
3128   {
3129     setSavedUpToDate(s, QuitHandler.Message.UNSAVED_CHANGES);
3130   }
3131
3132   public void setSavedUpToDate(boolean s, QuitHandler.Message m)
3133   {
3134     Console.debug(
3135             "Setting " + this.getViewId() + " setSavedUpToDate to " + s);
3136     savedUpToDate = s;
3137     QuitHandler.setMessage(m);
3138   }
3139
3140   public boolean savedUpToDate()
3141   {
3142     Console.debug("Returning " + this.getViewId() + " savedUpToDate value: "
3143             + savedUpToDate);
3144     return savedUpToDate;
3145   }
3146 }