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