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