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