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