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