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