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