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