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