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