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