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