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