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