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