JAL-2405 set context on selection group for tailored colour options
[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.
1077    * 
1078    * @param sg
1079    *          - group holding references to sequences in this alignment view
1080    * 
1081    */
1082   @Override
1083   public void setSelectionGroup(SequenceGroup sg)
1084   {
1085     selectionGroup = sg;
1086     if (sg != null)
1087     {
1088       sg.setContext(alignment);
1089     }
1090   }
1091
1092   public void setHiddenColumns(ColumnSelection colsel)
1093   {
1094     this.colSel = colsel;
1095   }
1096
1097   @Override
1098   public ColumnSelection getColumnSelection()
1099   {
1100     return colSel;
1101   }
1102
1103   @Override
1104   public void setColumnSelection(ColumnSelection colSel)
1105   {
1106     this.colSel = colSel;
1107     if (colSel != null)
1108     {
1109       updateHiddenColumns();
1110     }
1111     isColSelChanged(true);
1112   }
1113
1114   /**
1115    * 
1116    * @return
1117    */
1118   @Override
1119   public Map<SequenceI, SequenceCollectionI> getHiddenRepSequences()
1120   {
1121     return hiddenRepSequences;
1122   }
1123
1124   @Override
1125   public void setHiddenRepSequences(
1126           Map<SequenceI, SequenceCollectionI> hiddenRepSequences)
1127   {
1128     this.hiddenRepSequences = hiddenRepSequences;
1129   }
1130
1131   @Override
1132   public boolean hasSelectedColumns()
1133   {
1134     ColumnSelection columnSelection = getColumnSelection();
1135     return columnSelection != null && columnSelection.hasSelectedColumns();
1136   }
1137
1138   @Override
1139   public boolean hasHiddenColumns()
1140   {
1141     return colSel != null && colSel.hasHiddenColumns();
1142   }
1143
1144   public void updateHiddenColumns()
1145   {
1146     // this method doesn't really do anything now. But - it could, since a
1147     // column Selection could be in the process of modification
1148     // hasHiddenColumns = colSel.hasHiddenColumns();
1149   }
1150
1151   @Override
1152   public boolean hasHiddenRows()
1153   {
1154     return alignment.getHiddenSequences().getSize() > 0;
1155   }
1156
1157   protected SequenceGroup selectionGroup;
1158
1159   public void setSequenceSetId(String newid)
1160   {
1161     if (sequenceSetID != null)
1162     {
1163       System.err
1164               .println("Warning - overwriting a sequenceSetId for a viewport!");
1165     }
1166     sequenceSetID = new String(newid);
1167   }
1168
1169   @Override
1170   public String getSequenceSetId()
1171   {
1172     if (sequenceSetID == null)
1173     {
1174       sequenceSetID = alignment.hashCode() + "";
1175     }
1176
1177     return sequenceSetID;
1178   }
1179
1180   /**
1181    * unique viewId for synchronizing state (e.g. with stored Jalview Project)
1182    * 
1183    */
1184   protected String viewId = null;
1185
1186   @Override
1187   public String getViewId()
1188   {
1189     if (viewId == null)
1190     {
1191       viewId = this.getSequenceSetId() + "." + this.hashCode() + "";
1192     }
1193     return viewId;
1194   }
1195
1196   public void setIgnoreGapsConsensus(boolean b, AlignmentViewPanel ap)
1197   {
1198     ignoreGapsInConsensusCalculation = b;
1199     if (ap != null)
1200     {
1201       updateConsensus(ap);
1202       if (residueShading != null)
1203       {
1204         residueShading.setThreshold(residueShading.getThreshold(),
1205                 ignoreGapsInConsensusCalculation);
1206       }
1207     }
1208
1209   }
1210
1211   private long sgrouphash = -1, colselhash = -1;
1212
1213   /**
1214    * checks current SelectionGroup against record of last hash value, and
1215    * updates record.
1216    * 
1217    * @param b
1218    *          update the record of last hash value
1219    * 
1220    * @return true if SelectionGroup changed since last call (when b is true)
1221    */
1222   public boolean isSelectionGroupChanged(boolean b)
1223   {
1224     int hc = (selectionGroup == null || selectionGroup.getSize() == 0) ? -1
1225             : selectionGroup.hashCode();
1226     if (hc != -1 && hc != sgrouphash)
1227     {
1228       if (b)
1229       {
1230         sgrouphash = hc;
1231       }
1232       return true;
1233     }
1234     return false;
1235   }
1236
1237   /**
1238    * checks current colsel against record of last hash value, and optionally
1239    * updates record.
1240    * 
1241    * @param b
1242    *          update the record of last hash value
1243    * @return true if colsel changed since last call (when b is true)
1244    */
1245   public boolean isColSelChanged(boolean b)
1246   {
1247     int hc = (colSel == null || colSel.isEmpty()) ? -1 : colSel.hashCode();
1248     if (hc != -1 && hc != colselhash)
1249     {
1250       if (b)
1251       {
1252         colselhash = hc;
1253       }
1254       return true;
1255     }
1256     return false;
1257   }
1258
1259   @Override
1260   public boolean isIgnoreGapsConsensus()
1261   {
1262     return ignoreGapsInConsensusCalculation;
1263   }
1264
1265   // property change stuff
1266   // JBPNote Prolly only need this in the applet version.
1267   private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
1268           this);
1269
1270   protected boolean showConservation = true;
1271
1272   protected boolean showQuality = true;
1273
1274   protected boolean showConsensus = true;
1275
1276   private Map<SequenceI, Color> sequenceColours = new HashMap<SequenceI, Color>();
1277
1278   protected SequenceAnnotationOrder sortAnnotationsBy = null;
1279
1280   protected boolean showAutocalculatedAbove;
1281
1282   /**
1283    * when set, view will scroll to show the highlighted position
1284    */
1285   private boolean followHighlight = true;
1286
1287   // TODO private with getters and setters?
1288   public int startRes;
1289
1290   public int endRes;
1291
1292   public int startSeq;
1293
1294   public int endSeq;
1295
1296   /**
1297    * Property change listener for changes in alignment
1298    * 
1299    * @param listener
1300    *          DOCUMENT ME!
1301    */
1302   public void addPropertyChangeListener(
1303           java.beans.PropertyChangeListener listener)
1304   {
1305     changeSupport.addPropertyChangeListener(listener);
1306   }
1307
1308   /**
1309    * DOCUMENT ME!
1310    * 
1311    * @param listener
1312    *          DOCUMENT ME!
1313    */
1314   public void removePropertyChangeListener(
1315           java.beans.PropertyChangeListener listener)
1316   {
1317     changeSupport.removePropertyChangeListener(listener);
1318   }
1319
1320   /**
1321    * Property change listener for changes in alignment
1322    * 
1323    * @param prop
1324    *          DOCUMENT ME!
1325    * @param oldvalue
1326    *          DOCUMENT ME!
1327    * @param newvalue
1328    *          DOCUMENT ME!
1329    */
1330   public void firePropertyChange(String prop, Object oldvalue,
1331           Object newvalue)
1332   {
1333     changeSupport.firePropertyChange(prop, oldvalue, newvalue);
1334   }
1335
1336   // common hide/show column stuff
1337
1338   public void hideSelectedColumns()
1339   {
1340     if (colSel.isEmpty())
1341     {
1342       return;
1343     }
1344
1345     colSel.hideSelectedColumns();
1346     setSelectionGroup(null);
1347     isColSelChanged(true);
1348   }
1349
1350   public void hideColumns(int start, int end)
1351   {
1352     if (start == end)
1353     {
1354       colSel.hideColumns(start);
1355     }
1356     else
1357     {
1358       colSel.hideColumns(start, end);
1359     }
1360     isColSelChanged(true);
1361   }
1362
1363   public void showColumn(int col)
1364   {
1365     colSel.revealHiddenColumns(col);
1366     isColSelChanged(true);
1367   }
1368
1369   public void showAllHiddenColumns()
1370   {
1371     colSel.revealAllHiddenColumns();
1372     isColSelChanged(true);
1373   }
1374
1375   // common hide/show seq stuff
1376   public void showAllHiddenSeqs()
1377   {
1378     if (alignment.getHiddenSequences().getSize() > 0)
1379     {
1380       if (selectionGroup == null)
1381       {
1382         selectionGroup = new SequenceGroup();
1383         selectionGroup.setEndRes(alignment.getWidth() - 1);
1384       }
1385       List<SequenceI> tmp = alignment.getHiddenSequences().showAll(
1386               hiddenRepSequences);
1387       for (SequenceI seq : tmp)
1388       {
1389         selectionGroup.addSequence(seq, false);
1390         setSequenceAnnotationsVisible(seq, true);
1391       }
1392
1393       hiddenRepSequences = null;
1394
1395       firePropertyChange("alignment", null, alignment.getSequences());
1396       // used to set hasHiddenRows/hiddenRepSequences here, after the property
1397       // changed event
1398       sendSelection();
1399     }
1400   }
1401
1402   public void showSequence(int index)
1403   {
1404     List<SequenceI> tmp = alignment.getHiddenSequences().showSequence(
1405             index, hiddenRepSequences);
1406     if (tmp.size() > 0)
1407     {
1408       if (selectionGroup == null)
1409       {
1410         selectionGroup = new SequenceGroup();
1411         selectionGroup.setEndRes(alignment.getWidth() - 1);
1412       }
1413
1414       for (SequenceI seq : tmp)
1415       {
1416         selectionGroup.addSequence(seq, false);
1417         setSequenceAnnotationsVisible(seq, true);
1418       }
1419       firePropertyChange("alignment", null, alignment.getSequences());
1420       sendSelection();
1421     }
1422   }
1423
1424   public void hideAllSelectedSeqs()
1425   {
1426     if (selectionGroup == null || selectionGroup.getSize() < 1)
1427     {
1428       return;
1429     }
1430
1431     SequenceI[] seqs = selectionGroup.getSequencesInOrder(alignment);
1432
1433     hideSequence(seqs);
1434
1435     setSelectionGroup(null);
1436   }
1437
1438   public void hideSequence(SequenceI[] seq)
1439   {
1440     if (seq != null)
1441     {
1442       for (int i = 0; i < seq.length; i++)
1443       {
1444         alignment.getHiddenSequences().hideSequence(seq[i]);
1445         setSequenceAnnotationsVisible(seq[i], false);
1446       }
1447       firePropertyChange("alignment", null, alignment.getSequences());
1448     }
1449   }
1450
1451   /**
1452    * Hides the specified sequence, or the sequences it represents
1453    * 
1454    * @param sequence
1455    *          the sequence to hide, or keep as representative
1456    * @param representGroup
1457    *          if true, hide the current selection group except for the
1458    *          representative sequence
1459    */
1460   public void hideSequences(SequenceI sequence, boolean representGroup)
1461   {
1462     if (selectionGroup == null || selectionGroup.getSize() < 1)
1463     {
1464       hideSequence(new SequenceI[] { sequence });
1465       return;
1466     }
1467
1468     if (representGroup)
1469     {
1470       hideRepSequences(sequence, selectionGroup);
1471       setSelectionGroup(null);
1472       return;
1473     }
1474
1475     int gsize = selectionGroup.getSize();
1476     SequenceI[] hseqs = selectionGroup.getSequences().toArray(
1477             new SequenceI[gsize]);
1478
1479     hideSequence(hseqs);
1480     setSelectionGroup(null);
1481     sendSelection();
1482   }
1483
1484   /**
1485    * Set visibility for any annotations for the given sequence.
1486    * 
1487    * @param sequenceI
1488    */
1489   protected void setSequenceAnnotationsVisible(SequenceI sequenceI,
1490           boolean visible)
1491   {
1492     AlignmentAnnotation[] anns = alignment.getAlignmentAnnotation();
1493     if (anns != null)
1494     {
1495       for (AlignmentAnnotation ann : anns)
1496       {
1497         if (ann.sequenceRef == sequenceI)
1498         {
1499           ann.visible = visible;
1500         }
1501       }
1502     }
1503   }
1504
1505   public void hideRepSequences(SequenceI repSequence, SequenceGroup sg)
1506   {
1507     int sSize = sg.getSize();
1508     if (sSize < 2)
1509     {
1510       return;
1511     }
1512
1513     if (hiddenRepSequences == null)
1514     {
1515       hiddenRepSequences = new Hashtable<SequenceI, SequenceCollectionI>();
1516     }
1517
1518     hiddenRepSequences.put(repSequence, sg);
1519
1520     // Hide all sequences except the repSequence
1521     SequenceI[] seqs = new SequenceI[sSize - 1];
1522     int index = 0;
1523     for (int i = 0; i < sSize; i++)
1524     {
1525       if (sg.getSequenceAt(i) != repSequence)
1526       {
1527         if (index == sSize - 1)
1528         {
1529           return;
1530         }
1531
1532         seqs[index++] = sg.getSequenceAt(i);
1533       }
1534     }
1535     sg.setSeqrep(repSequence); // note: not done in 2.7applet
1536     sg.setHidereps(true); // note: not done in 2.7applet
1537     hideSequence(seqs);
1538
1539   }
1540
1541   /**
1542    * 
1543    * @return null or the current reference sequence
1544    */
1545   public SequenceI getReferenceSeq()
1546   {
1547     return alignment.getSeqrep();
1548   }
1549
1550   /**
1551    * @param seq
1552    * @return true iff seq is the reference for the alignment
1553    */
1554   public boolean isReferenceSeq(SequenceI seq)
1555   {
1556     return alignment.getSeqrep() == seq;
1557   }
1558
1559   /**
1560    * 
1561    * @param seq
1562    * @return true if there are sequences represented by this sequence that are
1563    *         currently hidden
1564    */
1565   public boolean isHiddenRepSequence(SequenceI seq)
1566   {
1567     return (hiddenRepSequences != null && hiddenRepSequences
1568             .containsKey(seq));
1569   }
1570
1571   /**
1572    * 
1573    * @param seq
1574    * @return null or a sequence group containing the sequences that seq
1575    *         represents
1576    */
1577   public SequenceGroup getRepresentedSequences(SequenceI seq)
1578   {
1579     return (SequenceGroup) (hiddenRepSequences == null ? null
1580             : hiddenRepSequences.get(seq));
1581   }
1582
1583   @Override
1584   public int adjustForHiddenSeqs(int alignmentIndex)
1585   {
1586     return alignment.getHiddenSequences().adjustForHiddenSeqs(
1587             alignmentIndex);
1588   }
1589
1590   @Override
1591   public void invertColumnSelection()
1592   {
1593     colSel.invertColumnSelection(0, alignment.getWidth());
1594   }
1595
1596   @Override
1597   public SequenceI[] getSelectionAsNewSequence()
1598   {
1599     SequenceI[] sequences;
1600     // JBPNote: Need to test jalviewLite.getSelectedSequencesAsAlignmentFrom -
1601     // this was the only caller in the applet for this method
1602     // JBPNote: in applet, this method returned references to the alignment
1603     // sequences, and it did not honour the presence/absence of annotation
1604     // attached to the alignment (probably!)
1605     if (selectionGroup == null || selectionGroup.getSize() == 0)
1606     {
1607       sequences = alignment.getSequencesArray();
1608       AlignmentAnnotation[] annots = alignment.getAlignmentAnnotation();
1609       for (int i = 0; i < sequences.length; i++)
1610       {
1611         // construct new sequence with subset of visible annotation
1612         sequences[i] = new Sequence(sequences[i], annots);
1613       }
1614     }
1615     else
1616     {
1617       sequences = selectionGroup.getSelectionAsNewSequences(alignment);
1618     }
1619
1620     return sequences;
1621   }
1622
1623   @Override
1624   public SequenceI[] getSequenceSelection()
1625   {
1626     SequenceI[] sequences = null;
1627     if (selectionGroup != null)
1628     {
1629       sequences = selectionGroup.getSequencesInOrder(alignment);
1630     }
1631     if (sequences == null)
1632     {
1633       sequences = alignment.getSequencesArray();
1634     }
1635     return sequences;
1636   }
1637
1638   @Override
1639   public CigarArray getViewAsCigars(boolean selectedRegionOnly)
1640   {
1641     return new CigarArray(alignment, colSel,
1642             (selectedRegionOnly ? selectionGroup : null));
1643   }
1644
1645   @Override
1646   public jalview.datamodel.AlignmentView getAlignmentView(
1647           boolean selectedOnly)
1648   {
1649     return getAlignmentView(selectedOnly, false);
1650   }
1651
1652   @Override
1653   public jalview.datamodel.AlignmentView getAlignmentView(
1654           boolean selectedOnly, boolean markGroups)
1655   {
1656     return new AlignmentView(alignment, colSel, selectionGroup,
1657             colSel != null && colSel.hasHiddenColumns(), selectedOnly,
1658             markGroups);
1659   }
1660
1661   @Override
1662   public String[] getViewAsString(boolean selectedRegionOnly)
1663   {
1664     return getViewAsString(selectedRegionOnly, true);
1665   }
1666
1667   @Override
1668   public String[] getViewAsString(boolean selectedRegionOnly,
1669           boolean exportHiddenSeqs)
1670   {
1671     String[] selection = null;
1672     SequenceI[] seqs = null;
1673     int i, iSize;
1674     int start = 0, end = 0;
1675     if (selectedRegionOnly && selectionGroup != null)
1676     {
1677       iSize = selectionGroup.getSize();
1678       seqs = selectionGroup.getSequencesInOrder(alignment);
1679       start = selectionGroup.getStartRes();
1680       end = selectionGroup.getEndRes() + 1;
1681     }
1682     else
1683     {
1684       if (hasHiddenRows() && exportHiddenSeqs)
1685       {
1686         AlignmentI fullAlignment = alignment.getHiddenSequences()
1687                 .getFullAlignment();
1688         iSize = fullAlignment.getHeight();
1689         seqs = fullAlignment.getSequencesArray();
1690         end = fullAlignment.getWidth();
1691       }
1692       else
1693       {
1694         iSize = alignment.getHeight();
1695         seqs = alignment.getSequencesArray();
1696         end = alignment.getWidth();
1697       }
1698     }
1699
1700     selection = new String[iSize];
1701     if (colSel != null && colSel.hasHiddenColumns())
1702     {
1703       selection = colSel.getVisibleSequenceStrings(start, end, seqs);
1704     }
1705     else
1706     {
1707       for (i = 0; i < iSize; i++)
1708       {
1709         selection[i] = seqs[i].getSequenceAsString(start, end);
1710       }
1711
1712     }
1713     return selection;
1714   }
1715
1716   @Override
1717   public List<int[]> getVisibleRegionBoundaries(int min, int max)
1718   {
1719     ArrayList<int[]> regions = new ArrayList<int[]>();
1720     int start = min;
1721     int end = max;
1722
1723     do
1724     {
1725       if (colSel != null && colSel.hasHiddenColumns())
1726       {
1727         if (start == 0)
1728         {
1729           start = colSel.adjustForHiddenColumns(start);
1730         }
1731
1732         end = colSel.getHiddenBoundaryRight(start);
1733         if (start == end)
1734         {
1735           end = max;
1736         }
1737         if (end > max)
1738         {
1739           end = max;
1740         }
1741       }
1742
1743       regions.add(new int[] { start, end });
1744
1745       if (colSel != null && colSel.hasHiddenColumns())
1746       {
1747         start = colSel.adjustForHiddenColumns(end);
1748         start = colSel.getHiddenBoundaryLeft(start) + 1;
1749       }
1750     } while (end < max);
1751
1752     int[][] startEnd = new int[regions.size()][2];
1753
1754     return regions;
1755   }
1756
1757   @Override
1758   public List<AlignmentAnnotation> getVisibleAlignmentAnnotation(
1759           boolean selectedOnly)
1760   {
1761     ArrayList<AlignmentAnnotation> ala = new ArrayList<AlignmentAnnotation>();
1762     AlignmentAnnotation[] aa;
1763     if ((aa = alignment.getAlignmentAnnotation()) != null)
1764     {
1765       for (AlignmentAnnotation annot : aa)
1766       {
1767         AlignmentAnnotation clone = new AlignmentAnnotation(annot);
1768         if (selectedOnly && selectionGroup != null)
1769         {
1770           colSel.makeVisibleAnnotation(selectionGroup.getStartRes(),
1771                   selectionGroup.getEndRes(), clone);
1772         }
1773         else
1774         {
1775           colSel.makeVisibleAnnotation(clone);
1776         }
1777         ala.add(clone);
1778       }
1779     }
1780     return ala;
1781   }
1782
1783   @Override
1784   public boolean isPadGaps()
1785   {
1786     return padGaps;
1787   }
1788
1789   @Override
1790   public void setPadGaps(boolean padGaps)
1791   {
1792     this.padGaps = padGaps;
1793   }
1794
1795   /**
1796    * apply any post-edit constraints and trigger any calculations needed after
1797    * an edit has been performed on the alignment
1798    * 
1799    * @param ap
1800    */
1801   @Override
1802   public void alignmentChanged(AlignmentViewPanel ap)
1803   {
1804     if (isPadGaps())
1805     {
1806       alignment.padGaps();
1807     }
1808     if (autoCalculateConsensus)
1809     {
1810       updateConsensus(ap);
1811     }
1812     if (hconsensus != null && autoCalculateConsensus)
1813     {
1814       updateConservation(ap);
1815     }
1816     if (autoCalculateStrucConsensus)
1817     {
1818       updateStrucConsensus(ap);
1819     }
1820
1821     // Reset endRes of groups if beyond alignment width
1822     int alWidth = alignment.getWidth();
1823     List<SequenceGroup> groups = alignment.getGroups();
1824     if (groups != null)
1825     {
1826       for (SequenceGroup sg : groups)
1827       {
1828         if (sg.getEndRes() > alWidth)
1829         {
1830           sg.setEndRes(alWidth - 1);
1831         }
1832       }
1833     }
1834
1835     if (selectionGroup != null && selectionGroup.getEndRes() > alWidth)
1836     {
1837       selectionGroup.setEndRes(alWidth - 1);
1838     }
1839
1840     updateAllColourSchemes();
1841     calculator.restartWorkers();
1842     // alignment.adjustSequenceAnnotations();
1843   }
1844
1845   /**
1846    * reset scope and do calculations for all applied colourschemes on alignment
1847    */
1848   void updateAllColourSchemes()
1849   {
1850     ResidueShaderI rs = residueShading;
1851     if (rs != null)
1852     {
1853       rs.alignmentChanged(alignment, hiddenRepSequences);
1854
1855       rs.setConsensus(hconsensus);
1856       if (rs.conservationApplied())
1857       {
1858         rs.setConservation(Conservation.calculateConservation("All",
1859                 alignment.getSequences(), 0, alignment.getWidth(), false,
1860                 getConsPercGaps(), false));
1861       }
1862     }
1863
1864     for (SequenceGroup sg : alignment.getGroups())
1865     {
1866       if (sg.cs != null)
1867       {
1868         sg.cs.alignmentChanged(sg, hiddenRepSequences);
1869       }
1870       sg.recalcConservation();
1871     }
1872   }
1873
1874   protected void initAutoAnnotation()
1875   {
1876     // TODO: add menu option action that nulls or creates consensus object
1877     // depending on if the user wants to see the annotation or not in a
1878     // specific alignment
1879
1880     if (hconsensus == null && !isDataset)
1881     {
1882       if (!alignment.isNucleotide())
1883       {
1884         initConservation();
1885         initQuality();
1886       }
1887       else
1888       {
1889         initRNAStructure();
1890       }
1891       consensus = new AlignmentAnnotation("Consensus", "PID",
1892               new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH);
1893       initConsensus(consensus);
1894
1895       initComplementConsensus();
1896     }
1897   }
1898
1899   /**
1900    * If this is a protein alignment and there are mappings to cDNA, add the cDNA
1901    * consensus annotation.
1902    */
1903   public void initComplementConsensus()
1904   {
1905     if (!alignment.isNucleotide())
1906     {
1907       final List<AlignedCodonFrame> codonMappings = alignment
1908               .getCodonFrames();
1909       if (codonMappings != null && !codonMappings.isEmpty())
1910       {
1911         boolean doConsensus = false;
1912         for (AlignedCodonFrame mapping : codonMappings)
1913         {
1914           // TODO hold mapping type e.g. dna-to-protein in AlignedCodonFrame?
1915           MapList[] mapLists = mapping.getdnaToProt();
1916           // mapLists can be empty if project load has not finished resolving
1917           // seqs
1918           if (mapLists.length > 0 && mapLists[0].getFromRatio() == 3)
1919           {
1920             doConsensus = true;
1921             break;
1922           }
1923         }
1924         if (doConsensus)
1925         {
1926           complementConsensus = new AlignmentAnnotation("cDNA Consensus",
1927                   "PID for cDNA", new Annotation[1], 0f, 100f,
1928                   AlignmentAnnotation.BAR_GRAPH);
1929           initConsensus(complementConsensus);
1930         }
1931       }
1932     }
1933   }
1934
1935   private void initConsensus(AlignmentAnnotation aa)
1936   {
1937     aa.hasText = true;
1938     aa.autoCalculated = true;
1939
1940     if (showConsensus)
1941     {
1942       alignment.addAnnotation(aa);
1943     }
1944   }
1945
1946   private void initConservation()
1947   {
1948     if (showConservation)
1949     {
1950       if (conservation == null)
1951       {
1952         conservation = new AlignmentAnnotation("Conservation",
1953                 "Conservation of total alignment less than "
1954                         + getConsPercGaps() + "% gaps", new Annotation[1],
1955                 0f, 11f, AlignmentAnnotation.BAR_GRAPH);
1956         conservation.hasText = true;
1957         conservation.autoCalculated = true;
1958         alignment.addAnnotation(conservation);
1959       }
1960     }
1961   }
1962
1963   private void initQuality()
1964   {
1965     if (showQuality)
1966     {
1967       if (quality == null)
1968       {
1969         quality = new AlignmentAnnotation("Quality",
1970                 "Alignment Quality based on Blosum62 scores",
1971                 new Annotation[1], 0f, 11f, AlignmentAnnotation.BAR_GRAPH);
1972         quality.hasText = true;
1973         quality.autoCalculated = true;
1974         alignment.addAnnotation(quality);
1975       }
1976     }
1977   }
1978
1979   private void initRNAStructure()
1980   {
1981     if (alignment.hasRNAStructure() && strucConsensus == null)
1982     {
1983       strucConsensus = new AlignmentAnnotation("StrucConsensus", "PID",
1984               new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH);
1985       strucConsensus.hasText = true;
1986       strucConsensus.autoCalculated = true;
1987
1988       if (showConsensus)
1989       {
1990         alignment.addAnnotation(strucConsensus);
1991       }
1992     }
1993   }
1994
1995   /*
1996    * (non-Javadoc)
1997    * 
1998    * @see jalview.api.AlignViewportI#calcPanelHeight()
1999    */
2000   @Override
2001   public int calcPanelHeight()
2002   {
2003     // setHeight of panels
2004     AlignmentAnnotation[] anns = getAlignment().getAlignmentAnnotation();
2005     int height = 0;
2006     int charHeight = getCharHeight();
2007     if (anns != null)
2008     {
2009       BitSet graphgrp = new BitSet();
2010       for (AlignmentAnnotation aa : anns)
2011       {
2012         if (aa == null)
2013         {
2014           System.err.println("Null annotation row: ignoring.");
2015           continue;
2016         }
2017         if (!aa.visible)
2018         {
2019           continue;
2020         }
2021         if (aa.graphGroup > -1)
2022         {
2023           if (graphgrp.get(aa.graphGroup))
2024           {
2025             continue;
2026           }
2027           else
2028           {
2029             graphgrp.set(aa.graphGroup);
2030           }
2031         }
2032         aa.height = 0;
2033
2034         if (aa.hasText)
2035         {
2036           aa.height += charHeight;
2037         }
2038
2039         if (aa.hasIcons)
2040         {
2041           aa.height += 16;
2042         }
2043
2044         if (aa.graph > 0)
2045         {
2046           aa.height += aa.graphHeight;
2047         }
2048
2049         if (aa.height == 0)
2050         {
2051           aa.height = 20;
2052         }
2053
2054         height += aa.height;
2055       }
2056     }
2057     if (height == 0)
2058     {
2059       // set minimum
2060       height = 20;
2061     }
2062     return height;
2063   }
2064
2065   @Override
2066   public void updateGroupAnnotationSettings(boolean applyGlobalSettings,
2067           boolean preserveNewGroupSettings)
2068   {
2069     boolean updateCalcs = false;
2070     boolean conv = isShowGroupConservation();
2071     boolean cons = isShowGroupConsensus();
2072     boolean showprf = isShowSequenceLogo();
2073     boolean showConsHist = isShowConsensusHistogram();
2074     boolean normLogo = isNormaliseSequenceLogo();
2075
2076     /**
2077      * TODO reorder the annotation rows according to group/sequence ordering on
2078      * alignment
2079      */
2080     boolean sortg = true;
2081
2082     // remove old automatic annotation
2083     // add any new annotation
2084
2085     // intersect alignment annotation with alignment groups
2086
2087     AlignmentAnnotation[] aan = alignment.getAlignmentAnnotation();
2088     List<SequenceGroup> oldrfs = new ArrayList<SequenceGroup>();
2089     if (aan != null)
2090     {
2091       for (int an = 0; an < aan.length; an++)
2092       {
2093         if (aan[an].autoCalculated && aan[an].groupRef != null)
2094         {
2095           oldrfs.add(aan[an].groupRef);
2096           alignment.deleteAnnotation(aan[an], false);
2097         }
2098       }
2099     }
2100     if (alignment.getGroups() != null)
2101     {
2102       for (SequenceGroup sg : alignment.getGroups())
2103       {
2104         updateCalcs = false;
2105         if (applyGlobalSettings
2106                 || (!preserveNewGroupSettings && !oldrfs.contains(sg)))
2107         {
2108           // set defaults for this group's conservation/consensus
2109           sg.setshowSequenceLogo(showprf);
2110           sg.setShowConsensusHistogram(showConsHist);
2111           sg.setNormaliseSequenceLogo(normLogo);
2112         }
2113         if (conv)
2114         {
2115           updateCalcs = true;
2116           alignment.addAnnotation(sg.getConservationRow(), 0);
2117         }
2118         if (cons)
2119         {
2120           updateCalcs = true;
2121           alignment.addAnnotation(sg.getConsensus(), 0);
2122         }
2123         // refresh the annotation rows
2124         if (updateCalcs)
2125         {
2126           sg.recalcConservation();
2127         }
2128       }
2129     }
2130     oldrfs.clear();
2131   }
2132
2133   @Override
2134   public boolean isDisplayReferenceSeq()
2135   {
2136     return alignment.hasSeqrep() && viewStyle.isDisplayReferenceSeq();
2137   }
2138
2139   @Override
2140   public void setDisplayReferenceSeq(boolean displayReferenceSeq)
2141   {
2142     viewStyle.setDisplayReferenceSeq(displayReferenceSeq);
2143   }
2144
2145   @Override
2146   public boolean isColourByReferenceSeq()
2147   {
2148     return alignment.hasSeqrep() && viewStyle.isColourByReferenceSeq();
2149   }
2150
2151   @Override
2152   public Color getSequenceColour(SequenceI seq)
2153   {
2154     Color sqc = sequenceColours.get(seq);
2155     return (sqc == null ? Color.white : sqc);
2156   }
2157
2158   @Override
2159   public void setSequenceColour(SequenceI seq, Color col)
2160   {
2161     if (col == null)
2162     {
2163       sequenceColours.remove(seq);
2164     }
2165     else
2166     {
2167       sequenceColours.put(seq, col);
2168     }
2169   }
2170
2171   @Override
2172   public void updateSequenceIdColours()
2173   {
2174     for (SequenceGroup sg : alignment.getGroups())
2175     {
2176       if (sg.idColour != null)
2177       {
2178         for (SequenceI s : sg.getSequences(getHiddenRepSequences()))
2179         {
2180           sequenceColours.put(s, sg.idColour);
2181         }
2182       }
2183     }
2184   }
2185
2186   @Override
2187   public void clearSequenceColours()
2188   {
2189     sequenceColours.clear();
2190   };
2191
2192   @Override
2193   public AlignViewportI getCodingComplement()
2194   {
2195     return this.codingComplement;
2196   }
2197
2198   /**
2199    * Set this as the (cDna/protein) complement of the given viewport. Also
2200    * ensures the reverse relationship is set on the given viewport.
2201    */
2202   @Override
2203   public void setCodingComplement(AlignViewportI av)
2204   {
2205     if (this == av)
2206     {
2207       System.err.println("Ignoring recursive setCodingComplement request");
2208     }
2209     else
2210     {
2211       this.codingComplement = av;
2212       // avoid infinite recursion!
2213       if (av.getCodingComplement() != this)
2214       {
2215         av.setCodingComplement(this);
2216       }
2217     }
2218   }
2219
2220   @Override
2221   public boolean isNucleotide()
2222   {
2223     return getAlignment() == null ? false : getAlignment().isNucleotide();
2224   }
2225
2226   @Override
2227   public FeaturesDisplayedI getFeaturesDisplayed()
2228   {
2229     return featuresDisplayed;
2230   }
2231
2232   @Override
2233   public void setFeaturesDisplayed(FeaturesDisplayedI featuresDisplayedI)
2234   {
2235     featuresDisplayed = featuresDisplayedI;
2236   }
2237
2238   @Override
2239   public boolean areFeaturesDisplayed()
2240   {
2241     return featuresDisplayed != null
2242             && featuresDisplayed.getRegisteredFeaturesCount() > 0;
2243   }
2244
2245   /**
2246    * set the flag
2247    * 
2248    * @param b
2249    *          features are displayed if true
2250    */
2251   @Override
2252   public void setShowSequenceFeatures(boolean b)
2253   {
2254     viewStyle.setShowSequenceFeatures(b);
2255   }
2256
2257   @Override
2258   public boolean isShowSequenceFeatures()
2259   {
2260     return viewStyle.isShowSequenceFeatures();
2261   }
2262
2263   @Override
2264   public void setShowSequenceFeaturesHeight(boolean selected)
2265   {
2266     viewStyle.setShowSequenceFeaturesHeight(selected);
2267   }
2268
2269   @Override
2270   public boolean isShowSequenceFeaturesHeight()
2271   {
2272     return viewStyle.isShowSequenceFeaturesHeight();
2273   }
2274
2275   @Override
2276   public void setShowAnnotation(boolean b)
2277   {
2278     viewStyle.setShowAnnotation(b);
2279   }
2280
2281   @Override
2282   public boolean isShowAnnotation()
2283   {
2284     return viewStyle.isShowAnnotation();
2285   }
2286
2287   @Override
2288   public boolean isRightAlignIds()
2289   {
2290     return viewStyle.isRightAlignIds();
2291   }
2292
2293   @Override
2294   public void setRightAlignIds(boolean rightAlignIds)
2295   {
2296     viewStyle.setRightAlignIds(rightAlignIds);
2297   }
2298
2299   @Override
2300   public boolean getConservationSelected()
2301   {
2302     return viewStyle.getConservationSelected();
2303   }
2304
2305   @Override
2306   public void setShowBoxes(boolean state)
2307   {
2308     viewStyle.setShowBoxes(state);
2309   }
2310
2311   /**
2312    * @return
2313    * @see jalview.api.ViewStyleI#getTextColour()
2314    */
2315   @Override
2316   public Color getTextColour()
2317   {
2318     return viewStyle.getTextColour();
2319   }
2320
2321   /**
2322    * @return
2323    * @see jalview.api.ViewStyleI#getTextColour2()
2324    */
2325   @Override
2326   public Color getTextColour2()
2327   {
2328     return viewStyle.getTextColour2();
2329   }
2330
2331   /**
2332    * @return
2333    * @see jalview.api.ViewStyleI#getThresholdTextColour()
2334    */
2335   @Override
2336   public int getThresholdTextColour()
2337   {
2338     return viewStyle.getThresholdTextColour();
2339   }
2340
2341   /**
2342    * @return
2343    * @see jalview.api.ViewStyleI#isConservationColourSelected()
2344    */
2345   @Override
2346   public boolean isConservationColourSelected()
2347   {
2348     return viewStyle.isConservationColourSelected();
2349   }
2350
2351   /**
2352    * @return
2353    * @see jalview.api.ViewStyleI#isRenderGaps()
2354    */
2355   @Override
2356   public boolean isRenderGaps()
2357   {
2358     return viewStyle.isRenderGaps();
2359   }
2360
2361   /**
2362    * @return
2363    * @see jalview.api.ViewStyleI#isShowColourText()
2364    */
2365   @Override
2366   public boolean isShowColourText()
2367   {
2368     return viewStyle.isShowColourText();
2369   }
2370
2371   /**
2372    * @param conservationColourSelected
2373    * @see jalview.api.ViewStyleI#setConservationColourSelected(boolean)
2374    */
2375   @Override
2376   public void setConservationColourSelected(
2377           boolean conservationColourSelected)
2378   {
2379     viewStyle.setConservationColourSelected(conservationColourSelected);
2380   }
2381
2382   /**
2383    * @param showColourText
2384    * @see jalview.api.ViewStyleI#setShowColourText(boolean)
2385    */
2386   @Override
2387   public void setShowColourText(boolean showColourText)
2388   {
2389     viewStyle.setShowColourText(showColourText);
2390   }
2391
2392   /**
2393    * @param textColour
2394    * @see jalview.api.ViewStyleI#setTextColour(java.awt.Color)
2395    */
2396   @Override
2397   public void setTextColour(Color textColour)
2398   {
2399     viewStyle.setTextColour(textColour);
2400   }
2401
2402   /**
2403    * @param thresholdTextColour
2404    * @see jalview.api.ViewStyleI#setThresholdTextColour(int)
2405    */
2406   @Override
2407   public void setThresholdTextColour(int thresholdTextColour)
2408   {
2409     viewStyle.setThresholdTextColour(thresholdTextColour);
2410   }
2411
2412   /**
2413    * @param textColour2
2414    * @see jalview.api.ViewStyleI#setTextColour2(java.awt.Color)
2415    */
2416   @Override
2417   public void setTextColour2(Color textColour2)
2418   {
2419     viewStyle.setTextColour2(textColour2);
2420   }
2421
2422   @Override
2423   public ViewStyleI getViewStyle()
2424   {
2425     return new ViewStyle(viewStyle);
2426   }
2427
2428   @Override
2429   public void setViewStyle(ViewStyleI settingsForView)
2430   {
2431     viewStyle = new ViewStyle(settingsForView);
2432   }
2433
2434   @Override
2435   public boolean sameStyle(ViewStyleI them)
2436   {
2437     return viewStyle.sameStyle(them);
2438   }
2439
2440   /**
2441    * @return
2442    * @see jalview.api.ViewStyleI#getIdWidth()
2443    */
2444   @Override
2445   public int getIdWidth()
2446   {
2447     return viewStyle.getIdWidth();
2448   }
2449
2450   /**
2451    * @param i
2452    * @see jalview.api.ViewStyleI#setIdWidth(int)
2453    */
2454   @Override
2455   public void setIdWidth(int i)
2456   {
2457     viewStyle.setIdWidth(i);
2458   }
2459
2460   /**
2461    * @return
2462    * @see jalview.api.ViewStyleI#isCentreColumnLabels()
2463    */
2464   @Override
2465   public boolean isCentreColumnLabels()
2466   {
2467     return viewStyle.isCentreColumnLabels();
2468   }
2469
2470   /**
2471    * @param centreColumnLabels
2472    * @see jalview.api.ViewStyleI#setCentreColumnLabels(boolean)
2473    */
2474   @Override
2475   public void setCentreColumnLabels(boolean centreColumnLabels)
2476   {
2477     viewStyle.setCentreColumnLabels(centreColumnLabels);
2478   }
2479
2480   /**
2481    * @param showdbrefs
2482    * @see jalview.api.ViewStyleI#setShowDBRefs(boolean)
2483    */
2484   @Override
2485   public void setShowDBRefs(boolean showdbrefs)
2486   {
2487     viewStyle.setShowDBRefs(showdbrefs);
2488   }
2489
2490   /**
2491    * @return
2492    * @see jalview.api.ViewStyleI#isShowDBRefs()
2493    */
2494   @Override
2495   public boolean isShowDBRefs()
2496   {
2497     return viewStyle.isShowDBRefs();
2498   }
2499
2500   /**
2501    * @return
2502    * @see jalview.api.ViewStyleI#isShowNPFeats()
2503    */
2504   @Override
2505   public boolean isShowNPFeats()
2506   {
2507     return viewStyle.isShowNPFeats();
2508   }
2509
2510   /**
2511    * @param shownpfeats
2512    * @see jalview.api.ViewStyleI#setShowNPFeats(boolean)
2513    */
2514   @Override
2515   public void setShowNPFeats(boolean shownpfeats)
2516   {
2517     viewStyle.setShowNPFeats(shownpfeats);
2518   }
2519
2520   public abstract StructureSelectionManager getStructureSelectionManager();
2521
2522   /**
2523    * Add one command to the command history list.
2524    * 
2525    * @param command
2526    */
2527   public void addToHistoryList(CommandI command)
2528   {
2529     if (this.historyList != null)
2530     {
2531       this.historyList.push(command);
2532       broadcastCommand(command, false);
2533     }
2534   }
2535
2536   protected void broadcastCommand(CommandI command, boolean undo)
2537   {
2538     getStructureSelectionManager().commandPerformed(command, undo,
2539             getVamsasSource());
2540   }
2541
2542   /**
2543    * Add one command to the command redo list.
2544    * 
2545    * @param command
2546    */
2547   public void addToRedoList(CommandI command)
2548   {
2549     if (this.redoList != null)
2550     {
2551       this.redoList.push(command);
2552     }
2553     broadcastCommand(command, true);
2554   }
2555
2556   /**
2557    * Clear the command redo list.
2558    */
2559   public void clearRedoList()
2560   {
2561     if (this.redoList != null)
2562     {
2563       this.redoList.clear();
2564     }
2565   }
2566
2567   public void setHistoryList(Deque<CommandI> list)
2568   {
2569     this.historyList = list;
2570   }
2571
2572   public Deque<CommandI> getHistoryList()
2573   {
2574     return this.historyList;
2575   }
2576
2577   public void setRedoList(Deque<CommandI> list)
2578   {
2579     this.redoList = list;
2580   }
2581
2582   public Deque<CommandI> getRedoList()
2583   {
2584     return this.redoList;
2585   }
2586
2587   @Override
2588   public VamsasSource getVamsasSource()
2589   {
2590     return this;
2591   }
2592
2593   public SequenceAnnotationOrder getSortAnnotationsBy()
2594   {
2595     return sortAnnotationsBy;
2596   }
2597
2598   public void setSortAnnotationsBy(SequenceAnnotationOrder sortAnnotationsBy)
2599   {
2600     this.sortAnnotationsBy = sortAnnotationsBy;
2601   }
2602
2603   public boolean isShowAutocalculatedAbove()
2604   {
2605     return showAutocalculatedAbove;
2606   }
2607
2608   public void setShowAutocalculatedAbove(boolean showAutocalculatedAbove)
2609   {
2610     this.showAutocalculatedAbove = showAutocalculatedAbove;
2611   }
2612
2613   @Override
2614   public boolean isScaleProteinAsCdna()
2615   {
2616     return viewStyle.isScaleProteinAsCdna();
2617   }
2618
2619   @Override
2620   public void setScaleProteinAsCdna(boolean b)
2621   {
2622     viewStyle.setScaleProteinAsCdna(b);
2623   }
2624
2625   /**
2626    * @return true if view should scroll to show the highlighted region of a
2627    *         sequence
2628    * @return
2629    */
2630   @Override
2631   public final boolean isFollowHighlight()
2632   {
2633     return followHighlight;
2634   }
2635
2636   @Override
2637   public final void setFollowHighlight(boolean b)
2638   {
2639     this.followHighlight = b;
2640   }
2641
2642   public int getStartRes()
2643   {
2644     return startRes;
2645   }
2646
2647   @Override
2648   public int getEndRes()
2649   {
2650     return endRes;
2651   }
2652
2653   public int getStartSeq()
2654   {
2655     return startSeq;
2656   }
2657
2658   public void setStartRes(int res)
2659   {
2660     this.startRes = res;
2661   }
2662
2663   public void setStartSeq(int seq)
2664   {
2665     this.startSeq = seq;
2666   }
2667
2668   public void setEndRes(int res)
2669   {
2670     if (res > alignment.getWidth() - 1)
2671     {
2672       // log.System.out.println(" Corrected res from " + res + " to maximum " +
2673       // (alignment.getWidth()-1));
2674       res = alignment.getWidth() - 1;
2675     }
2676     if (res < 0)
2677     {
2678       res = 0;
2679     }
2680     this.endRes = res;
2681   }
2682
2683   public void setEndSeq(int seq)
2684   {
2685     if (seq > alignment.getHeight())
2686     {
2687       seq = alignment.getHeight();
2688     }
2689     if (seq < 0)
2690     {
2691       seq = 0;
2692     }
2693     this.endSeq = seq;
2694   }
2695
2696   public int getEndSeq()
2697   {
2698     return endSeq;
2699   }
2700
2701   /**
2702    * Helper method to populate the SearchResults with the location in the
2703    * complementary alignment to scroll to, in order to match this one.
2704    * 
2705    * @param sr
2706    *          the SearchResults to add to
2707    * @return the offset (below top of visible region) of the matched sequence
2708    */
2709   protected int findComplementScrollTarget(SearchResultsI sr)
2710   {
2711     final AlignViewportI complement = getCodingComplement();
2712     if (complement == null || !complement.isFollowHighlight())
2713     {
2714       return 0;
2715     }
2716     boolean iAmProtein = !getAlignment().isNucleotide();
2717     AlignmentI proteinAlignment = iAmProtein ? getAlignment() : complement
2718             .getAlignment();
2719     if (proteinAlignment == null)
2720     {
2721       return 0;
2722     }
2723     final List<AlignedCodonFrame> mappings = proteinAlignment
2724             .getCodonFrames();
2725
2726     /*
2727      * Heuristic: find the first mapped sequence (if any) with a non-gapped
2728      * residue in the middle column of the visible region. Scroll the
2729      * complementary alignment to line up the corresponding residue.
2730      */
2731     int seqOffset = 0;
2732     SequenceI sequence = null;
2733
2734     /*
2735      * locate 'middle' column (true middle if an odd number visible, left of
2736      * middle if an even number visible)
2737      */
2738     int middleColumn = getStartRes() + (getEndRes() - getStartRes()) / 2;
2739     final HiddenSequences hiddenSequences = getAlignment()
2740             .getHiddenSequences();
2741
2742     /*
2743      * searching to the bottom of the alignment gives smoother scrolling across
2744      * all gapped visible regions
2745      */
2746     int lastSeq = alignment.getHeight() - 1;
2747     List<AlignedCodonFrame> seqMappings = null;
2748     for (int seqNo = getStartSeq(); seqNo < lastSeq; seqNo++, seqOffset++)
2749     {
2750       sequence = getAlignment().getSequenceAt(seqNo);
2751       if (hiddenSequences != null && hiddenSequences.isHidden(sequence))
2752       {
2753         continue;
2754       }
2755       if (Comparison.isGap(sequence.getCharAt(middleColumn)))
2756       {
2757         continue;
2758       }
2759       seqMappings = MappingUtils
2760               .findMappingsForSequenceAndOthers(sequence, mappings,
2761                       getCodingComplement().getAlignment().getSequences());
2762       if (!seqMappings.isEmpty())
2763       {
2764         break;
2765       }
2766     }
2767
2768     if (sequence == null || seqMappings == null || seqMappings.isEmpty())
2769     {
2770       /*
2771        * No ungapped mapped sequence in middle column - do nothing
2772        */
2773       return 0;
2774     }
2775     MappingUtils.addSearchResults(sr, sequence,
2776             sequence.findPosition(middleColumn), seqMappings);
2777     return seqOffset;
2778   }
2779
2780   /**
2781    * synthesize a column selection if none exists so it covers the given
2782    * selection group. if wholewidth is false, no column selection is made if the
2783    * selection group covers the whole alignment width.
2784    * 
2785    * @param sg
2786    * @param wholewidth
2787    */
2788   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
2789   {
2790     int sgs, sge;
2791     if (sg != null && (sgs = sg.getStartRes()) >= 0
2792             && sg.getStartRes() <= (sge = sg.getEndRes())
2793             && !this.hasSelectedColumns())
2794     {
2795       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
2796       {
2797         // do nothing
2798         return;
2799       }
2800       if (colSel == null)
2801       {
2802         colSel = new ColumnSelection();
2803       }
2804       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
2805       {
2806         colSel.addElement(cspos);
2807       }
2808     }
2809   }
2810
2811   /**
2812    * hold status of current selection group - defined on alignment or not.
2813    */
2814   private boolean selectionIsDefinedGroup = false;
2815
2816
2817   @Override
2818   public boolean isSelectionDefinedGroup()
2819   {
2820     if (selectionGroup == null)
2821     {
2822       return false;
2823     }
2824     if (isSelectionGroupChanged(true))
2825     {
2826       selectionIsDefinedGroup = false;
2827       List<SequenceGroup> gps = alignment.getGroups();
2828       if (gps == null || gps.size() == 0)
2829       {
2830         selectionIsDefinedGroup = false;
2831       }
2832       else
2833       {
2834         selectionIsDefinedGroup = gps.contains(selectionGroup);
2835       }
2836     }
2837     return selectionGroup.getContext() == alignment
2838             || selectionIsDefinedGroup;
2839   }
2840
2841   /**
2842    * null, or currently highlighted results on this view
2843    */
2844   private SearchResultsI searchResults = null;
2845
2846   @Override
2847   public boolean hasSearchResults()
2848   {
2849     return searchResults != null;
2850   }
2851
2852   @Override
2853   public void setSearchResults(SearchResultsI results)
2854   {
2855     searchResults = results;
2856   }
2857
2858   @Override
2859   public SearchResultsI getSearchResults()
2860   {
2861     return searchResults;
2862   }
2863 }