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