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