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