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