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