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