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