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