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