[JAL-3226] problem that JavaScript (or Java) may consolidate multiple
[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<String, Object>[] hcomplementConsensus = null;
715
716   /**
717    * results of secondary structure base pair consensus for visible portion of
718    * view
719    */
720   protected Hashtable<String, Object>[] 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(
750           Hashtable<String, Object>[] hconsensus)
751   {
752     this.hcomplementConsensus = hconsensus;
753   }
754
755   @Override
756   public ProfilesI getSequenceConsensusHash()
757   {
758     return hconsensus;
759   }
760
761   @Override
762   public Hashtable<String, Object>[] getComplementConsensusHash()
763   {
764     return hcomplementConsensus;
765   }
766
767   @Override
768   public Hashtable<String, Object>[] getRnaStructureConsensusHash()
769   {
770     return hStrucConsensus;
771   }
772
773   @Override
774   public void setRnaStructureConsensusHash(
775           Hashtable<String, Object>[] hStrucConsensus)
776   {
777     this.hStrucConsensus = hStrucConsensus;
778
779   }
780
781   @Override
782   public AlignmentAnnotation getAlignmentQualityAnnot()
783   {
784     return quality;
785   }
786
787   @Override
788   public AlignmentAnnotation getAlignmentConservationAnnotation()
789   {
790     return conservation;
791   }
792
793   @Override
794   public AlignmentAnnotation getAlignmentConsensusAnnotation()
795   {
796     return consensus;
797   }
798
799   @Override
800   public AlignmentAnnotation getAlignmentGapAnnotation()
801   {
802     return gapcounts;
803   }
804
805   @Override
806   public AlignmentAnnotation getComplementConsensusAnnotation()
807   {
808     return complementConsensus;
809   }
810
811   @Override
812   public AlignmentAnnotation getAlignmentStrucConsensusAnnotation()
813   {
814     return strucConsensus;
815   }
816
817   protected AlignCalcManagerI calculator = new AlignCalcManager();
818
819   /**
820    * trigger update of conservation annotation
821    */
822   public void updateConservation(final AlignmentViewPanel ap)
823   {
824     // see note in mantis : issue number 8585
825     if (alignment.isNucleotide()
826             || (conservation == null && quality == null)
827             || !autoCalculateConsensus)
828     {
829       return;
830     }
831     if (calculator.getRegisteredWorkersOfClass(
832             jalview.workers.ConservationThread.class) == null)
833     {
834       calculator.registerWorker(
835               new jalview.workers.ConservationThread(this, ap));
836     }
837   }
838
839   /**
840    * trigger update of consensus annotation
841    */
842   public void updateConsensus(final AlignmentViewPanel ap)
843   {
844     // see note in mantis : issue number 8585
845     if (consensus == null || !autoCalculateConsensus)
846     {
847       return;
848     }
849     if (calculator
850             .getRegisteredWorkersOfClass(ConsensusThread.class) == null)
851     {
852       calculator.registerWorker(new ConsensusThread(this, ap));
853     }
854
855     /*
856      * A separate thread to compute cDNA consensus for a protein alignment
857      * which has mapping to cDNA
858      */
859     final AlignmentI al = this.getAlignment();
860     if (!al.isNucleotide() && al.getCodonFrames() != null
861             && !al.getCodonFrames().isEmpty())
862     {
863       /*
864        * fudge - check first for protein-to-nucleotide mappings
865        * (we don't want to do this for protein-to-protein)
866        */
867       boolean doConsensus = false;
868       for (AlignedCodonFrame mapping : al.getCodonFrames())
869       {
870         // TODO hold mapping type e.g. dna-to-protein in AlignedCodonFrame?
871         MapList[] mapLists = mapping.getdnaToProt();
872         // mapLists can be empty if project load has not finished resolving seqs
873         if (mapLists.length > 0 && mapLists[0].getFromRatio() == 3)
874         {
875           doConsensus = true;
876           break;
877         }
878       }
879       if (doConsensus)
880       {
881         if (calculator.getRegisteredWorkersOfClass(
882                 ComplementConsensusThread.class) == null)
883         {
884           calculator
885                   .registerWorker(new ComplementConsensusThread(this, ap));
886         }
887       }
888     }
889   }
890
891   // --------START Structure Conservation
892   public void updateStrucConsensus(final AlignmentViewPanel ap)
893   {
894     if (autoCalculateStrucConsensus && strucConsensus == null
895             && alignment.isNucleotide() && alignment.hasRNAStructure())
896     {
897       // secondary structure has been added - so init the consensus line
898       initRNAStructure();
899     }
900
901     // see note in mantis : issue number 8585
902     if (strucConsensus == null || !autoCalculateStrucConsensus)
903     {
904       return;
905     }
906     if (calculator.getRegisteredWorkersOfClass(
907             StrucConsensusThread.class) == null)
908     {
909       calculator.registerWorker(new StrucConsensusThread(this, ap));
910     }
911   }
912
913   public boolean isCalcInProgress()
914   {
915     return calculator.isWorking();
916   }
917
918   @Override
919   public boolean isCalculationInProgress(
920           AlignmentAnnotation alignmentAnnotation)
921   {
922     if (!alignmentAnnotation.autoCalculated)
923     {
924       return false;
925     }
926     if (calculator.workingInvolvedWith(alignmentAnnotation))
927     {
928       // System.err.println("grey out ("+alignmentAnnotation.label+")");
929       return true;
930     }
931     return false;
932   }
933
934   public void setAlignment(AlignmentI align)
935   {
936     this.alignment = align;
937   }
938
939   /**
940    * Clean up references when this viewport is closed
941    */
942   @Override
943   public void dispose()
944   {
945     /*
946      * defensively null out references to large objects in case
947      * this object is not garbage collected (as if!)
948      */
949     consensus = null;
950     complementConsensus = null;
951     strucConsensus = null;
952     conservation = null;
953     quality = null;
954     groupConsensus = null;
955     groupConservation = null;
956     hconsensus = null;
957     hconservation = null;
958     hcomplementConsensus = null;
959     gapcounts = null;
960     calculator = null;
961     residueShading = null; // may hold a reference to Consensus
962     changeSupport = null;
963     ranges = null;
964     currentTree = null;
965     selectionGroup = null;
966     setAlignment(null);
967   }
968
969   @Override
970   public boolean isClosed()
971   {
972     // TODO: check that this isClosed is only true after panel is closed, not
973     // before it is fully constructed.
974     return alignment == null;
975   }
976
977   @Override
978   public AlignCalcManagerI getCalcManager()
979   {
980     return calculator;
981   }
982
983   /**
984    * should conservation rows be shown for groups
985    */
986   protected boolean showGroupConservation = false;
987
988   /**
989    * should consensus rows be shown for groups
990    */
991   protected boolean showGroupConsensus = false;
992
993   /**
994    * should consensus profile be rendered by default
995    */
996   protected boolean showSequenceLogo = false;
997
998   /**
999    * should consensus profile be rendered normalised to row height
1000    */
1001   protected boolean normaliseSequenceLogo = false;
1002
1003   /**
1004    * should consensus histograms be rendered by default
1005    */
1006   protected boolean showConsensusHistogram = true;
1007
1008   /**
1009    * @return the showConsensusProfile
1010    */
1011   @Override
1012   public boolean isShowSequenceLogo()
1013   {
1014     return showSequenceLogo;
1015   }
1016
1017   /**
1018    * @param showSequenceLogo
1019    *          the new value
1020    */
1021   public void setShowSequenceLogo(boolean showSequenceLogo)
1022   {
1023     if (showSequenceLogo != this.showSequenceLogo)
1024     {
1025       // TODO: decouple settings setting from calculation when refactoring
1026       // annotation update method from alignframe to viewport
1027       this.showSequenceLogo = showSequenceLogo;
1028       calculator.updateAnnotationFor(ConsensusThread.class);
1029       calculator.updateAnnotationFor(ComplementConsensusThread.class);
1030       calculator.updateAnnotationFor(StrucConsensusThread.class);
1031     }
1032     this.showSequenceLogo = showSequenceLogo;
1033   }
1034
1035   /**
1036    * @param showConsensusHistogram
1037    *          the showConsensusHistogram to set
1038    */
1039   public void setShowConsensusHistogram(boolean showConsensusHistogram)
1040   {
1041     this.showConsensusHistogram = showConsensusHistogram;
1042   }
1043
1044   /**
1045    * @return the showGroupConservation
1046    */
1047   public boolean isShowGroupConservation()
1048   {
1049     return showGroupConservation;
1050   }
1051
1052   /**
1053    * @param showGroupConservation
1054    *          the showGroupConservation to set
1055    */
1056   public void setShowGroupConservation(boolean showGroupConservation)
1057   {
1058     this.showGroupConservation = showGroupConservation;
1059   }
1060
1061   /**
1062    * @return the showGroupConsensus
1063    */
1064   public boolean isShowGroupConsensus()
1065   {
1066     return showGroupConsensus;
1067   }
1068
1069   /**
1070    * @param showGroupConsensus
1071    *          the showGroupConsensus to set
1072    */
1073   public void setShowGroupConsensus(boolean showGroupConsensus)
1074   {
1075     this.showGroupConsensus = showGroupConsensus;
1076   }
1077
1078   /**
1079    * 
1080    * @return flag to indicate if the consensus histogram should be rendered by
1081    *         default
1082    */
1083   @Override
1084   public boolean isShowConsensusHistogram()
1085   {
1086     return this.showConsensusHistogram;
1087   }
1088
1089   /**
1090    * when set, updateAlignment will always ensure sequences are of equal length
1091    */
1092   private boolean padGaps = false;
1093
1094   /**
1095    * when set, alignment should be reordered according to a newly opened tree
1096    */
1097   public boolean sortByTree = false;
1098
1099   /**
1100    * 
1101    * 
1102    * @return null or the currently selected sequence region
1103    */
1104   @Override
1105   public SequenceGroup getSelectionGroup()
1106   {
1107     return selectionGroup;
1108   }
1109
1110   /**
1111    * Set the selection group for this window. Also sets the current alignment as
1112    * the context for the group, if it does not already have one.
1113    * 
1114    * @param sg
1115    *          - group holding references to sequences in this alignment view
1116    * 
1117    */
1118   @Override
1119   public void setSelectionGroup(SequenceGroup sg)
1120   {
1121     selectionGroup = sg;
1122     if (sg != null && sg.getContext() == null)
1123     {
1124       sg.setContext(alignment);
1125     }
1126   }
1127
1128   public void setHiddenColumns(HiddenColumns hidden)
1129   {
1130     this.alignment.setHiddenColumns(hidden);
1131   }
1132
1133   @Override
1134   public ColumnSelection getColumnSelection()
1135   {
1136     return colSel;
1137   }
1138
1139   @Override
1140   public void setColumnSelection(ColumnSelection colSel)
1141   {
1142     this.colSel = colSel;
1143     if (colSel != null)
1144     {
1145       updateHiddenColumns();
1146     }
1147     isColSelChanged(true);
1148   }
1149
1150   /**
1151    * 
1152    * @return
1153    */
1154   @Override
1155   public Map<SequenceI, SequenceCollectionI> getHiddenRepSequences()
1156   {
1157     return hiddenRepSequences;
1158   }
1159
1160   @Override
1161   public void setHiddenRepSequences(
1162           Map<SequenceI, SequenceCollectionI> hiddenRepSequences)
1163   {
1164     this.hiddenRepSequences = hiddenRepSequences;
1165   }
1166
1167   @Override
1168   public boolean hasSelectedColumns()
1169   {
1170     ColumnSelection columnSelection = getColumnSelection();
1171     return columnSelection != null && columnSelection.hasSelectedColumns();
1172   }
1173
1174   @Override
1175   public boolean hasHiddenColumns()
1176   {
1177     return alignment.getHiddenColumns() != null
1178             && alignment.getHiddenColumns().hasHiddenColumns();
1179   }
1180
1181   public void updateHiddenColumns()
1182   {
1183     // this method doesn't really do anything now. But - it could, since a
1184     // column Selection could be in the process of modification
1185     // hasHiddenColumns = colSel.hasHiddenColumns();
1186   }
1187
1188   @Override
1189   public boolean hasHiddenRows()
1190   {
1191     return alignment.getHiddenSequences().getSize() > 0;
1192   }
1193
1194   protected SequenceGroup selectionGroup;
1195
1196   public void setSequenceSetId(String newid)
1197   {
1198     if (sequenceSetID != null)
1199     {
1200       System.err.println(
1201               "Warning - overwriting a sequenceSetId for a viewport!");
1202     }
1203     sequenceSetID = new String(newid);
1204   }
1205
1206   @Override
1207   public String getSequenceSetId()
1208   {
1209     if (sequenceSetID == null)
1210     {
1211       sequenceSetID = alignment.hashCode() + "";
1212     }
1213
1214     return sequenceSetID;
1215   }
1216
1217   /**
1218    * unique viewId for synchronizing state (e.g. with stored Jalview Project)
1219    * 
1220    */
1221   protected String viewId = null;
1222
1223   @Override
1224   public String getViewId()
1225   {
1226     if (viewId == null)
1227     {
1228       viewId = this.getSequenceSetId() + "." + this.hashCode() + "";
1229     }
1230     return viewId;
1231   }
1232
1233   public void setIgnoreGapsConsensus(boolean b, AlignmentViewPanel ap)
1234   {
1235     ignoreGapsInConsensusCalculation = b;
1236     if (ap != null)
1237     {
1238       updateConsensus(ap);
1239       if (residueShading != null)
1240       {
1241         residueShading.setThreshold(residueShading.getThreshold(),
1242                 ignoreGapsInConsensusCalculation);
1243       }
1244     }
1245
1246   }
1247
1248   private long sgrouphash = -1, colselhash = -1;
1249
1250   /**
1251    * checks current SelectionGroup against record of last hash value, and
1252    * updates record.
1253    * 
1254    * @param b
1255    *          update the record of last hash value
1256    * 
1257    * @return true if SelectionGroup changed since last call (when b is true)
1258    */
1259   public boolean isSelectionGroupChanged(boolean b)
1260   {
1261     int hc = (selectionGroup == null || selectionGroup.getSize() == 0) ? -1
1262             : selectionGroup.hashCode();
1263     if (hc != -1 && hc != sgrouphash)
1264     {
1265       if (b)
1266       {
1267         sgrouphash = hc;
1268       }
1269       return true;
1270     }
1271     return false;
1272   }
1273
1274   /**
1275    * checks current colsel against record of last hash value, and optionally
1276    * updates record.
1277    * 
1278    * @param b
1279    *          update the record of last hash value
1280    * @return true if colsel changed since last call (when b is true)
1281    */
1282   public boolean isColSelChanged(boolean b)
1283   {
1284     int hc = (colSel == null || colSel.isEmpty()) ? -1 : colSel.hashCode();
1285     if (hc != -1 && hc != colselhash)
1286     {
1287       if (b)
1288       {
1289         colselhash = hc;
1290       }
1291       return true;
1292     }
1293     return false;
1294   }
1295
1296   @Override
1297   public boolean isIgnoreGapsConsensus()
1298   {
1299     return ignoreGapsInConsensusCalculation;
1300   }
1301
1302   // property change stuff
1303   // JBPNote Prolly only need this in the applet version.
1304   private PropertyChangeSupport changeSupport = new PropertyChangeSupport(
1305           this);
1306
1307   protected boolean showConservation = true;
1308
1309   protected boolean showQuality = true;
1310
1311   protected boolean showConsensus = true;
1312
1313   protected boolean showOccupancy = true;
1314
1315   private Map<SequenceI, Color> sequenceColours = new HashMap<>();
1316
1317   protected SequenceAnnotationOrder sortAnnotationsBy = null;
1318
1319   protected boolean showAutocalculatedAbove;
1320
1321   /**
1322    * when set, view will scroll to show the highlighted position
1323    */
1324   private boolean followHighlight = true;
1325
1326   // private boolean disableFastPaint; // BH 2019.04.18
1327   //
1328   // /**
1329   // * BH 2019.04.18 When gap filling is on and a modification is made to fill
1330   // * those, we need to disallow fast painting for paste just once
1331   // *
1332   // * @return
1333   // */
1334   // public boolean isFastPaintDisabled()
1335   // {
1336   // boolean ret = disableFastPaint;
1337   // disableFastPaint = false;
1338   // return ret;
1339   // }
1340
1341   /**
1342    * Property change listener for changes in alignment
1343    * 
1344    * @param listener
1345    *          DOCUMENT ME!
1346    */
1347   public void addPropertyChangeListener(
1348           java.beans.PropertyChangeListener listener)
1349   {
1350     changeSupport.addPropertyChangeListener(listener);
1351   }
1352
1353   /**
1354    * DOCUMENT ME!
1355    * 
1356    * @param listener
1357    *          DOCUMENT ME!
1358    */
1359   public void removePropertyChangeListener(
1360           java.beans.PropertyChangeListener listener)
1361   {
1362     if (changeSupport != null)
1363     {
1364       changeSupport.removePropertyChangeListener(listener);
1365     }
1366   }
1367
1368   /**
1369    * Property change listener for changes in alignment
1370    * 
1371    * @param prop
1372    *          DOCUMENT ME!
1373    * @param oldvalue
1374    *          DOCUMENT ME!
1375    * @param newvalue
1376    *          DOCUMENT ME!
1377    */
1378   public void firePropertyChange(String prop, Object oldvalue,
1379           Object newvalue)
1380   {
1381     changeSupport.firePropertyChange(prop, oldvalue, newvalue);
1382   }
1383
1384   // common hide/show column stuff
1385
1386   public void hideSelectedColumns()
1387   {
1388     if (colSel.isEmpty())
1389     {
1390       return;
1391     }
1392
1393     colSel.hideSelectedColumns(alignment);
1394     setSelectionGroup(null);
1395     isColSelChanged(true);
1396   }
1397
1398   public void hideColumns(int start, int end)
1399   {
1400     if (start == end)
1401     {
1402       colSel.hideSelectedColumns(start, alignment.getHiddenColumns());
1403     }
1404     else
1405     {
1406       alignment.getHiddenColumns().hideColumns(start, end);
1407     }
1408     isColSelChanged(true);
1409   }
1410
1411   public void showColumn(int col)
1412   {
1413     alignment.getHiddenColumns().revealHiddenColumns(col, colSel);
1414     isColSelChanged(true);
1415   }
1416
1417   public void showAllHiddenColumns()
1418   {
1419     alignment.getHiddenColumns().revealAllHiddenColumns(colSel);
1420     isColSelChanged(true);
1421   }
1422
1423   // common hide/show seq stuff
1424   public void showAllHiddenSeqs()
1425   {
1426     int startSeq = ranges.getStartSeq();
1427     int endSeq = ranges.getEndSeq();
1428
1429     if (alignment.getHiddenSequences().getSize() > 0)
1430     {
1431       if (selectionGroup == null)
1432       {
1433         selectionGroup = new SequenceGroup();
1434         selectionGroup.setEndRes(alignment.getWidth() - 1);
1435       }
1436       List<SequenceI> tmp = alignment.getHiddenSequences()
1437               .showAll(hiddenRepSequences);
1438       for (SequenceI seq : tmp)
1439       {
1440         selectionGroup.addSequence(seq, false);
1441         setSequenceAnnotationsVisible(seq, true);
1442       }
1443
1444       hiddenRepSequences = null;
1445
1446       ranges.setStartEndSeq(startSeq, endSeq + tmp.size());
1447
1448       firePropertyChange("alignment", null, alignment.getSequences());
1449       // used to set hasHiddenRows/hiddenRepSequences here, after the property
1450       // changed event
1451       sendSelection();
1452     }
1453   }
1454
1455   public void showSequence(int index)
1456   {
1457     int startSeq = ranges.getStartSeq();
1458     int endSeq = ranges.getEndSeq();
1459
1460     List<SequenceI> tmp = alignment.getHiddenSequences().showSequence(index,
1461             hiddenRepSequences);
1462     if (tmp.size() > 0)
1463     {
1464       if (selectionGroup == null)
1465       {
1466         selectionGroup = new SequenceGroup();
1467         selectionGroup.setEndRes(alignment.getWidth() - 1);
1468       }
1469
1470       for (SequenceI seq : tmp)
1471       {
1472         selectionGroup.addSequence(seq, false);
1473         setSequenceAnnotationsVisible(seq, true);
1474       }
1475
1476       ranges.setStartEndSeq(startSeq, endSeq + tmp.size());
1477
1478       firePropertyChange("alignment", null, alignment.getSequences());
1479       sendSelection();
1480     }
1481   }
1482
1483   public void hideAllSelectedSeqs()
1484   {
1485     if (selectionGroup == null || selectionGroup.getSize() < 1)
1486     {
1487       return;
1488     }
1489
1490     SequenceI[] seqs = selectionGroup.getSequencesInOrder(alignment);
1491
1492     hideSequence(seqs);
1493
1494     setSelectionGroup(null);
1495   }
1496
1497   public void hideSequence(SequenceI[] seq)
1498   {
1499     /*
1500      * cache offset to first visible sequence
1501      */
1502     int startSeq = ranges.getStartSeq();
1503
1504     if (seq != null)
1505     {
1506       for (int i = 0; i < seq.length; i++)
1507       {
1508         alignment.getHiddenSequences().hideSequence(seq[i]);
1509         setSequenceAnnotationsVisible(seq[i], false);
1510       }
1511       ranges.setStartSeq(startSeq);
1512       firePropertyChange("alignment", null, alignment.getSequences());
1513     }
1514   }
1515
1516   /**
1517    * Hides the specified sequence, or the sequences it represents
1518    * 
1519    * @param sequence
1520    *          the sequence to hide, or keep as representative
1521    * @param representGroup
1522    *          if true, hide the current selection group except for the
1523    *          representative sequence
1524    */
1525   public void hideSequences(SequenceI sequence, boolean representGroup)
1526   {
1527     if (selectionGroup == null || selectionGroup.getSize() < 1)
1528     {
1529       hideSequence(new SequenceI[] { sequence });
1530       return;
1531     }
1532
1533     if (representGroup)
1534     {
1535       hideRepSequences(sequence, selectionGroup);
1536       setSelectionGroup(null);
1537       return;
1538     }
1539
1540     int gsize = selectionGroup.getSize();
1541     SequenceI[] hseqs = selectionGroup.getSequences()
1542             .toArray(new SequenceI[gsize]);
1543
1544     hideSequence(hseqs);
1545     setSelectionGroup(null);
1546     sendSelection();
1547   }
1548
1549   /**
1550    * Set visibility for any annotations for the given sequence.
1551    * 
1552    * @param sequenceI
1553    */
1554   protected void setSequenceAnnotationsVisible(SequenceI sequenceI,
1555           boolean visible)
1556   {
1557     AlignmentAnnotation[] anns = alignment.getAlignmentAnnotation();
1558     if (anns != null)
1559     {
1560       for (AlignmentAnnotation ann : anns)
1561       {
1562         if (ann.sequenceRef == sequenceI)
1563         {
1564           ann.visible = visible;
1565         }
1566       }
1567     }
1568   }
1569
1570   public void hideRepSequences(SequenceI repSequence, SequenceGroup sg)
1571   {
1572     int sSize = sg.getSize();
1573     if (sSize < 2)
1574     {
1575       return;
1576     }
1577
1578     if (hiddenRepSequences == null)
1579     {
1580       hiddenRepSequences = new Hashtable<>();
1581     }
1582
1583     hiddenRepSequences.put(repSequence, sg);
1584
1585     // Hide all sequences except the repSequence
1586     SequenceI[] seqs = new SequenceI[sSize - 1];
1587     int index = 0;
1588     for (int i = 0; i < sSize; i++)
1589     {
1590       if (sg.getSequenceAt(i) != repSequence)
1591       {
1592         if (index == sSize - 1)
1593         {
1594           return;
1595         }
1596
1597         seqs[index++] = sg.getSequenceAt(i);
1598       }
1599     }
1600     sg.setSeqrep(repSequence); // note: not done in 2.7applet
1601     sg.setHidereps(true); // note: not done in 2.7applet
1602     hideSequence(seqs);
1603
1604   }
1605
1606   /**
1607    * 
1608    * @return null or the current reference sequence
1609    */
1610   public SequenceI getReferenceSeq()
1611   {
1612     return alignment.getSeqrep();
1613   }
1614
1615   /**
1616    * @param seq
1617    * @return true iff seq is the reference for the alignment
1618    */
1619   public boolean isReferenceSeq(SequenceI seq)
1620   {
1621     return alignment.getSeqrep() == seq;
1622   }
1623
1624   /**
1625    * 
1626    * @param seq
1627    * @return true if there are sequences represented by this sequence that are
1628    *         currently hidden
1629    */
1630   public boolean isHiddenRepSequence(SequenceI seq)
1631   {
1632     return (hiddenRepSequences != null
1633             && hiddenRepSequences.containsKey(seq));
1634   }
1635
1636   /**
1637    * 
1638    * @param seq
1639    * @return null or a sequence group containing the sequences that seq
1640    *         represents
1641    */
1642   public SequenceGroup getRepresentedSequences(SequenceI seq)
1643   {
1644     return (SequenceGroup) (hiddenRepSequences == null ? null
1645             : hiddenRepSequences.get(seq));
1646   }
1647
1648   @Override
1649   public int adjustForHiddenSeqs(int alignmentIndex)
1650   {
1651     return alignment.getHiddenSequences()
1652             .adjustForHiddenSeqs(alignmentIndex);
1653   }
1654
1655   @Override
1656   public void invertColumnSelection()
1657   {
1658     colSel.invertColumnSelection(0, alignment.getWidth(), alignment);
1659     isColSelChanged(true);
1660   }
1661
1662   @Override
1663   public SequenceI[] getSelectionAsNewSequence()
1664   {
1665     SequenceI[] sequences;
1666     // JBPNote: Need to test jalviewLite.getSelectedSequencesAsAlignmentFrom -
1667     // this was the only caller in the applet for this method
1668     // JBPNote: in applet, this method returned references to the alignment
1669     // sequences, and it did not honour the presence/absence of annotation
1670     // attached to the alignment (probably!)
1671     if (selectionGroup == null || selectionGroup.getSize() == 0)
1672     {
1673       sequences = alignment.getSequencesArray();
1674       AlignmentAnnotation[] annots = alignment.getAlignmentAnnotation();
1675       for (int i = 0; i < sequences.length; i++)
1676       {
1677         // construct new sequence with subset of visible annotation
1678         sequences[i] = new Sequence(sequences[i], annots);
1679       }
1680     }
1681     else
1682     {
1683       sequences = selectionGroup.getSelectionAsNewSequences(alignment);
1684     }
1685
1686     return sequences;
1687   }
1688
1689   @Override
1690   public SequenceI[] getSequenceSelection()
1691   {
1692     SequenceI[] sequences = null;
1693     if (selectionGroup != null)
1694     {
1695       sequences = selectionGroup.getSequencesInOrder(alignment);
1696     }
1697     if (sequences == null)
1698     {
1699       sequences = alignment.getSequencesArray();
1700     }
1701     return sequences;
1702   }
1703
1704   @Override
1705   public jalview.datamodel.AlignmentView getAlignmentView(
1706           boolean selectedOnly)
1707   {
1708     return getAlignmentView(selectedOnly, false);
1709   }
1710
1711   @Override
1712   public jalview.datamodel.AlignmentView getAlignmentView(
1713           boolean selectedOnly, boolean markGroups)
1714   {
1715     return new AlignmentView(alignment, alignment.getHiddenColumns(),
1716             selectionGroup,
1717             alignment.getHiddenColumns() != null
1718                     && alignment.getHiddenColumns().hasHiddenColumns(),
1719             selectedOnly, markGroups);
1720   }
1721
1722   @Override
1723   public String[] getViewAsString(boolean selectedRegionOnly)
1724   {
1725     return getViewAsString(selectedRegionOnly, true);
1726   }
1727
1728   @Override
1729   public String[] getViewAsString(boolean selectedRegionOnly,
1730           boolean exportHiddenSeqs)
1731   {
1732     String[] selection = null;
1733     SequenceI[] seqs = null;
1734     int i, iSize;
1735     int start = 0, end = 0;
1736     if (selectedRegionOnly && selectionGroup != null)
1737     {
1738       iSize = selectionGroup.getSize();
1739       seqs = selectionGroup.getSequencesInOrder(alignment);
1740       start = selectionGroup.getStartRes();
1741       end = selectionGroup.getEndRes() + 1;
1742     }
1743     else
1744     {
1745       if (hasHiddenRows() && exportHiddenSeqs)
1746       {
1747         AlignmentI fullAlignment = alignment.getHiddenSequences()
1748                 .getFullAlignment();
1749         iSize = fullAlignment.getHeight();
1750         seqs = fullAlignment.getSequencesArray();
1751         end = fullAlignment.getWidth();
1752       }
1753       else
1754       {
1755         iSize = alignment.getHeight();
1756         seqs = alignment.getSequencesArray();
1757         end = alignment.getWidth();
1758       }
1759     }
1760
1761     selection = new String[iSize];
1762     if (alignment.getHiddenColumns() != null
1763             && alignment.getHiddenColumns().hasHiddenColumns())
1764     {
1765       for (i = 0; i < iSize; i++)
1766       {
1767         Iterator<int[]> blocks = alignment.getHiddenColumns()
1768                 .getVisContigsIterator(start, end + 1, false);
1769         selection[i] = seqs[i].getSequenceStringFromIterator(blocks);
1770       }
1771     }
1772     else
1773     {
1774       for (i = 0; i < iSize; i++)
1775       {
1776         selection[i] = seqs[i].getSequenceAsString(start, end);
1777       }
1778
1779     }
1780     return selection;
1781   }
1782
1783   @Override
1784   public List<int[]> getVisibleRegionBoundaries(int min, int max)
1785   {
1786     ArrayList<int[]> regions = new ArrayList<>();
1787     int start = min;
1788     int end = max;
1789
1790     do
1791     {
1792       HiddenColumns hidden = alignment.getHiddenColumns();
1793       if (hidden != null && hidden.hasHiddenColumns())
1794       {
1795         if (start == 0)
1796         {
1797           start = hidden.visibleToAbsoluteColumn(start);
1798         }
1799
1800         end = hidden.getNextHiddenBoundary(false, start);
1801         if (start == end)
1802         {
1803           end = max;
1804         }
1805         if (end > max)
1806         {
1807           end = max;
1808         }
1809       }
1810
1811       regions.add(new int[] { start, end });
1812
1813       if (hidden != null && hidden.hasHiddenColumns())
1814       {
1815         start = hidden.visibleToAbsoluteColumn(end);
1816         start = hidden.getNextHiddenBoundary(true, start) + 1;
1817       }
1818     } while (end < max);
1819
1820     // int[][] startEnd = new int[regions.size()][2];
1821
1822     return regions;
1823   }
1824
1825   @Override
1826   public List<AlignmentAnnotation> getVisibleAlignmentAnnotation(
1827           boolean selectedOnly)
1828   {
1829     ArrayList<AlignmentAnnotation> ala = new ArrayList<>();
1830     AlignmentAnnotation[] aa;
1831     if ((aa = alignment.getAlignmentAnnotation()) != null)
1832     {
1833       for (AlignmentAnnotation annot : aa)
1834       {
1835         AlignmentAnnotation clone = new AlignmentAnnotation(annot);
1836         if (selectedOnly && selectionGroup != null)
1837         {
1838           clone.makeVisibleAnnotation(
1839                   selectionGroup.getStartRes(), selectionGroup.getEndRes(),
1840                   alignment.getHiddenColumns());
1841         }
1842         else
1843         {
1844           clone.makeVisibleAnnotation(alignment.getHiddenColumns());
1845         }
1846         ala.add(clone);
1847       }
1848     }
1849     return ala;
1850   }
1851
1852   @Override
1853   public boolean isPadGaps()
1854   {
1855     return padGaps;
1856   }
1857
1858   @Override
1859   public void setPadGaps(boolean padGaps)
1860   {
1861     this.padGaps = padGaps;
1862   }
1863
1864   /**
1865    * apply any post-edit constraints and trigger any calculations needed after
1866    * an edit has been performed on the alignment
1867    * 
1868    * @param ap
1869    */
1870   @Override
1871   public void alignmentChanged(AlignmentViewPanel ap)
1872   {
1873     if (isPadGaps())
1874     {
1875       alignment.padGaps();
1876       // if (alignment.padGaps())
1877       // {
1878       // // the new alignment has been modified -- can't fast paint
1879       // disableFastPaint = true;
1880       // }
1881     }
1882     if (autoCalculateConsensus)
1883     {
1884       updateConsensus(ap);
1885     }
1886     if (hconsensus != null && autoCalculateConsensus)
1887     {
1888       updateConservation(ap);
1889     }
1890     if (autoCalculateStrucConsensus)
1891     {
1892       updateStrucConsensus(ap);
1893     }
1894
1895     // Reset endRes of groups if beyond alignment width
1896     int alWidth = alignment.getWidth();
1897     List<SequenceGroup> groups = alignment.getGroups();
1898     if (groups != null)
1899     {
1900       for (SequenceGroup sg : groups)
1901       {
1902         if (sg.getEndRes() > alWidth)
1903         {
1904           sg.setEndRes(alWidth - 1);
1905         }
1906       }
1907     }
1908
1909     if (selectionGroup != null && selectionGroup.getEndRes() > alWidth)
1910     {
1911       selectionGroup.setEndRes(alWidth - 1);
1912     }
1913
1914     updateAllColourSchemes();
1915     calculator.restartWorkers();
1916     // alignment.adjustSequenceAnnotations();
1917   }
1918
1919   /**
1920    * reset scope and do calculations for all applied colourschemes on alignment
1921    */
1922   void updateAllColourSchemes()
1923   {
1924     ResidueShaderI rs = residueShading;
1925     if (rs != null)
1926     {
1927       rs.alignmentChanged(alignment, hiddenRepSequences);
1928
1929       rs.setConsensus(hconsensus);
1930       if (rs.conservationApplied())
1931       {
1932         rs.setConservation(Conservation.calculateConservation("All",
1933                 alignment.getSequences(), 0, alignment.getWidth(), false,
1934                 getConsPercGaps(), false));
1935       }
1936     }
1937
1938     for (SequenceGroup sg : alignment.getGroups())
1939     {
1940       if (sg.cs != null)
1941       {
1942         sg.cs.alignmentChanged(sg, hiddenRepSequences);
1943       }
1944       sg.recalcConservation();
1945     }
1946   }
1947
1948   protected void initAutoAnnotation()
1949   {
1950     // TODO: add menu option action that nulls or creates consensus object
1951     // depending on if the user wants to see the annotation or not in a
1952     // specific alignment
1953
1954     if (hconsensus == null && !isDataset)
1955     {
1956       if (!alignment.isNucleotide())
1957       {
1958         initConservation();
1959         initQuality();
1960       }
1961       else
1962       {
1963         initRNAStructure();
1964       }
1965       consensus = new AlignmentAnnotation("Consensus",
1966               MessageManager.getString("label.consensus_descr"),
1967               new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH);
1968       initConsensus(consensus);
1969       initGapCounts();
1970
1971       initComplementConsensus();
1972     }
1973   }
1974
1975   /**
1976    * If this is a protein alignment and there are mappings to cDNA, adds the
1977    * cDNA consensus annotation and returns true, else returns false.
1978    */
1979   public boolean initComplementConsensus()
1980   {
1981     if (!alignment.isNucleotide())
1982     {
1983       final List<AlignedCodonFrame> codonMappings = alignment
1984               .getCodonFrames();
1985       if (codonMappings != null && !codonMappings.isEmpty())
1986       {
1987         boolean doConsensus = false;
1988         for (AlignedCodonFrame mapping : codonMappings)
1989         {
1990           // TODO hold mapping type e.g. dna-to-protein in AlignedCodonFrame?
1991           MapList[] mapLists = mapping.getdnaToProt();
1992           // mapLists can be empty if project load has not finished resolving
1993           // seqs
1994           if (mapLists.length > 0 && mapLists[0].getFromRatio() == 3)
1995           {
1996             doConsensus = true;
1997             break;
1998           }
1999         }
2000         if (doConsensus)
2001         {
2002           complementConsensus = new AlignmentAnnotation("cDNA Consensus",
2003                   MessageManager
2004                           .getString("label.complement_consensus_descr"),
2005                   new Annotation[1], 0f, 100f,
2006                   AlignmentAnnotation.BAR_GRAPH);
2007           initConsensus(complementConsensus);
2008           return true;
2009         }
2010       }
2011     }
2012     return false;
2013   }
2014
2015   private void initConsensus(AlignmentAnnotation aa)
2016   {
2017     aa.hasText = true;
2018     aa.autoCalculated = true;
2019
2020     if (showConsensus)
2021     {
2022       alignment.addAnnotation(aa);
2023     }
2024   }
2025
2026   // these should be extracted from the view model - style and settings for
2027   // derived annotation
2028   private void initGapCounts()
2029   {
2030     if (showOccupancy)
2031     {
2032       gapcounts = new AlignmentAnnotation("Occupancy",
2033               MessageManager.getString("label.occupancy_descr"),
2034               new Annotation[1], 0f, alignment.getHeight(),
2035               AlignmentAnnotation.BAR_GRAPH);
2036       gapcounts.hasText = true;
2037       gapcounts.autoCalculated = true;
2038       gapcounts.scaleColLabel = true;
2039       gapcounts.graph = AlignmentAnnotation.BAR_GRAPH;
2040
2041       alignment.addAnnotation(gapcounts);
2042     }
2043   }
2044
2045   private void initConservation()
2046   {
2047     if (showConservation)
2048     {
2049       if (conservation == null)
2050       {
2051         conservation = new AlignmentAnnotation("Conservation",
2052                 MessageManager.formatMessage("label.conservation_descr",
2053                         getConsPercGaps()),
2054                 new Annotation[1], 0f, 11f, AlignmentAnnotation.BAR_GRAPH);
2055         conservation.hasText = true;
2056         conservation.autoCalculated = true;
2057         alignment.addAnnotation(conservation);
2058       }
2059     }
2060   }
2061
2062   private void initQuality()
2063   {
2064     if (showQuality)
2065     {
2066       if (quality == null)
2067       {
2068         quality = new AlignmentAnnotation("Quality",
2069                 MessageManager.getString("label.quality_descr"),
2070                 new Annotation[1], 0f, 11f, AlignmentAnnotation.BAR_GRAPH);
2071         quality.hasText = true;
2072         quality.autoCalculated = true;
2073         alignment.addAnnotation(quality);
2074       }
2075     }
2076   }
2077
2078   private void initRNAStructure()
2079   {
2080     if (alignment.hasRNAStructure() && strucConsensus == null)
2081     {
2082       strucConsensus = new AlignmentAnnotation("StrucConsensus",
2083               MessageManager.getString("label.strucconsensus_descr"),
2084               new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH);
2085       strucConsensus.hasText = true;
2086       strucConsensus.autoCalculated = true;
2087
2088       if (showConsensus)
2089       {
2090         alignment.addAnnotation(strucConsensus);
2091       }
2092     }
2093   }
2094
2095   /*
2096    * (non-Javadoc)
2097    * 
2098    * @see jalview.api.AlignViewportI#calcPanelHeight()
2099    */
2100   @Override
2101   public int calcPanelHeight()
2102   {
2103     // setHeight of panels
2104     AlignmentAnnotation[] anns = getAlignment().getAlignmentAnnotation();
2105     int height = 0;
2106     int charHeight = getCharHeight();
2107     if (anns != null)
2108     {
2109       BitSet graphgrp = new BitSet();
2110       for (AlignmentAnnotation aa : anns)
2111       {
2112         if (aa == null)
2113         {
2114           System.err.println("Null annotation row: ignoring.");
2115           continue;
2116         }
2117         if (!aa.visible)
2118         {
2119           continue;
2120         }
2121         if (aa.graphGroup > -1)
2122         {
2123           if (graphgrp.get(aa.graphGroup))
2124           {
2125             continue;
2126           }
2127           else
2128           {
2129             graphgrp.set(aa.graphGroup);
2130           }
2131         }
2132         aa.height = 0;
2133
2134         if (aa.hasText)
2135         {
2136           aa.height += charHeight;
2137         }
2138
2139         if (aa.hasIcons)
2140         {
2141           aa.height += 16;
2142         }
2143
2144         if (aa.graph > 0)
2145         {
2146           aa.height += aa.graphHeight;
2147         }
2148
2149         if (aa.height == 0)
2150         {
2151           aa.height = 20;
2152         }
2153
2154         height += aa.height;
2155       }
2156     }
2157     if (height == 0)
2158     {
2159       // set minimum
2160       height = 20;
2161     }
2162     return height;
2163   }
2164
2165   @Override
2166   public void updateGroupAnnotationSettings(boolean applyGlobalSettings,
2167           boolean preserveNewGroupSettings)
2168   {
2169     boolean updateCalcs = false;
2170     boolean conv = isShowGroupConservation();
2171     boolean cons = isShowGroupConsensus();
2172     boolean showprf = isShowSequenceLogo();
2173     boolean showConsHist = isShowConsensusHistogram();
2174     boolean normLogo = isNormaliseSequenceLogo();
2175
2176     /**
2177      * TODO reorder the annotation rows according to group/sequence ordering on
2178      * alignment
2179      */
2180     // boolean sortg = true;
2181
2182     // remove old automatic annotation
2183     // add any new annotation
2184
2185     // intersect alignment annotation with alignment groups
2186
2187     AlignmentAnnotation[] aan = alignment.getAlignmentAnnotation();
2188     List<SequenceGroup> oldrfs = new ArrayList<>();
2189     if (aan != null)
2190     {
2191       for (int an = 0; an < aan.length; an++)
2192       {
2193         if (aan[an].autoCalculated && aan[an].groupRef != null)
2194         {
2195           oldrfs.add(aan[an].groupRef);
2196           alignment.deleteAnnotation(aan[an], false);
2197         }
2198       }
2199     }
2200     if (alignment.getGroups() != null)
2201     {
2202       for (SequenceGroup sg : alignment.getGroups())
2203       {
2204         updateCalcs = false;
2205         if (applyGlobalSettings
2206                 || (!preserveNewGroupSettings && !oldrfs.contains(sg)))
2207         {
2208           // set defaults for this group's conservation/consensus
2209           sg.setshowSequenceLogo(showprf);
2210           sg.setShowConsensusHistogram(showConsHist);
2211           sg.setNormaliseSequenceLogo(normLogo);
2212         }
2213         if (conv)
2214         {
2215           updateCalcs = true;
2216           alignment.addAnnotation(sg.getConservationRow(), 0);
2217         }
2218         if (cons)
2219         {
2220           updateCalcs = true;
2221           alignment.addAnnotation(sg.getConsensus(), 0);
2222         }
2223         // refresh the annotation rows
2224         if (updateCalcs)
2225         {
2226           sg.recalcConservation();
2227         }
2228       }
2229     }
2230     oldrfs.clear();
2231   }
2232
2233   @Override
2234   public boolean isDisplayReferenceSeq()
2235   {
2236     return alignment.hasSeqrep() && viewStyle.isDisplayReferenceSeq();
2237   }
2238
2239   @Override
2240   public void setDisplayReferenceSeq(boolean displayReferenceSeq)
2241   {
2242     viewStyle.setDisplayReferenceSeq(displayReferenceSeq);
2243   }
2244
2245   @Override
2246   public boolean isColourByReferenceSeq()
2247   {
2248     return alignment.hasSeqrep() && viewStyle.isColourByReferenceSeq();
2249   }
2250
2251   @Override
2252   public Color getSequenceColour(SequenceI seq)
2253   {
2254     Color sqc = sequenceColours.get(seq);
2255     return (sqc == null ? Color.white : sqc);
2256   }
2257
2258   @Override
2259   public void setSequenceColour(SequenceI seq, Color col)
2260   {
2261     if (col == null)
2262     {
2263       sequenceColours.remove(seq);
2264     }
2265     else
2266     {
2267       sequenceColours.put(seq, col);
2268     }
2269   }
2270
2271   @Override
2272   public void updateSequenceIdColours()
2273   {
2274     for (SequenceGroup sg : alignment.getGroups())
2275     {
2276       if (sg.idColour != null)
2277       {
2278         for (SequenceI s : sg.getSequences(getHiddenRepSequences()))
2279         {
2280           sequenceColours.put(s, sg.idColour);
2281         }
2282       }
2283     }
2284   }
2285
2286   @Override
2287   public void clearSequenceColours()
2288   {
2289     sequenceColours.clear();
2290   };
2291
2292   @Override
2293   public AlignViewportI getCodingComplement()
2294   {
2295     return this.codingComplement;
2296   }
2297
2298   /**
2299    * Set this as the (cDna/protein) complement of the given viewport. Also
2300    * ensures the reverse relationship is set on the given viewport.
2301    */
2302   @Override
2303   public void setCodingComplement(AlignViewportI av)
2304   {
2305     if (this == av)
2306     {
2307       System.err.println("Ignoring recursive setCodingComplement request");
2308     }
2309     else
2310     {
2311       this.codingComplement = av;
2312       // avoid infinite recursion!
2313       if (av.getCodingComplement() != this)
2314       {
2315         av.setCodingComplement(this);
2316       }
2317     }
2318   }
2319
2320   @Override
2321   public boolean isNucleotide()
2322   {
2323     return getAlignment() == null ? false : getAlignment().isNucleotide();
2324   }
2325
2326   @Override
2327   public FeaturesDisplayedI getFeaturesDisplayed()
2328   {
2329     return featuresDisplayed;
2330   }
2331
2332   @Override
2333   public void setFeaturesDisplayed(FeaturesDisplayedI featuresDisplayedI)
2334   {
2335     featuresDisplayed = featuresDisplayedI;
2336   }
2337
2338   @Override
2339   public boolean areFeaturesDisplayed()
2340   {
2341     return featuresDisplayed != null
2342             && featuresDisplayed.getRegisteredFeaturesCount() > 0;
2343   }
2344
2345   /**
2346    * set the flag
2347    * 
2348    * @param b
2349    *          features are displayed if true
2350    */
2351   @Override
2352   public void setShowSequenceFeatures(boolean b)
2353   {
2354     viewStyle.setShowSequenceFeatures(b);
2355   }
2356
2357   @Override
2358   public boolean isShowSequenceFeatures()
2359   {
2360     return viewStyle.isShowSequenceFeatures();
2361   }
2362
2363   @Override
2364   public void setShowSequenceFeaturesHeight(boolean selected)
2365   {
2366     viewStyle.setShowSequenceFeaturesHeight(selected);
2367   }
2368
2369   @Override
2370   public boolean isShowSequenceFeaturesHeight()
2371   {
2372     return viewStyle.isShowSequenceFeaturesHeight();
2373   }
2374
2375   @Override
2376   public void setShowAnnotation(boolean b)
2377   {
2378     viewStyle.setShowAnnotation(b);
2379   }
2380
2381   @Override
2382   public boolean isShowAnnotation()
2383   {
2384     return viewStyle.isShowAnnotation();
2385   }
2386
2387   @Override
2388   public boolean isRightAlignIds()
2389   {
2390     return viewStyle.isRightAlignIds();
2391   }
2392
2393   @Override
2394   public void setRightAlignIds(boolean rightAlignIds)
2395   {
2396     viewStyle.setRightAlignIds(rightAlignIds);
2397   }
2398
2399   @Override
2400   public boolean getConservationSelected()
2401   {
2402     return viewStyle.getConservationSelected();
2403   }
2404
2405   @Override
2406   public void setShowBoxes(boolean state)
2407   {
2408     viewStyle.setShowBoxes(state);
2409   }
2410
2411   /**
2412    * @return
2413    * @see jalview.api.ViewStyleI#getTextColour()
2414    */
2415   @Override
2416   public Color getTextColour()
2417   {
2418     return viewStyle.getTextColour();
2419   }
2420
2421   /**
2422    * @return
2423    * @see jalview.api.ViewStyleI#getTextColour2()
2424    */
2425   @Override
2426   public Color getTextColour2()
2427   {
2428     return viewStyle.getTextColour2();
2429   }
2430
2431   /**
2432    * @return
2433    * @see jalview.api.ViewStyleI#getThresholdTextColour()
2434    */
2435   @Override
2436   public int getThresholdTextColour()
2437   {
2438     return viewStyle.getThresholdTextColour();
2439   }
2440
2441   /**
2442    * @return
2443    * @see jalview.api.ViewStyleI#isConservationColourSelected()
2444    */
2445   @Override
2446   public boolean isConservationColourSelected()
2447   {
2448     return viewStyle.isConservationColourSelected();
2449   }
2450
2451   /**
2452    * @return
2453    * @see jalview.api.ViewStyleI#isRenderGaps()
2454    */
2455   @Override
2456   public boolean isRenderGaps()
2457   {
2458     return viewStyle.isRenderGaps();
2459   }
2460
2461   /**
2462    * @return
2463    * @see jalview.api.ViewStyleI#isShowColourText()
2464    */
2465   @Override
2466   public boolean isShowColourText()
2467   {
2468     return viewStyle.isShowColourText();
2469   }
2470
2471   /**
2472    * @param conservationColourSelected
2473    * @see jalview.api.ViewStyleI#setConservationColourSelected(boolean)
2474    */
2475   @Override
2476   public void setConservationColourSelected(
2477           boolean conservationColourSelected)
2478   {
2479     viewStyle.setConservationColourSelected(conservationColourSelected);
2480   }
2481
2482   /**
2483    * @param showColourText
2484    * @see jalview.api.ViewStyleI#setShowColourText(boolean)
2485    */
2486   @Override
2487   public void setShowColourText(boolean showColourText)
2488   {
2489     viewStyle.setShowColourText(showColourText);
2490   }
2491
2492   /**
2493    * @param textColour
2494    * @see jalview.api.ViewStyleI#setTextColour(java.awt.Color)
2495    */
2496   @Override
2497   public void setTextColour(Color textColour)
2498   {
2499     viewStyle.setTextColour(textColour);
2500   }
2501
2502   /**
2503    * @param thresholdTextColour
2504    * @see jalview.api.ViewStyleI#setThresholdTextColour(int)
2505    */
2506   @Override
2507   public void setThresholdTextColour(int thresholdTextColour)
2508   {
2509     viewStyle.setThresholdTextColour(thresholdTextColour);
2510   }
2511
2512   /**
2513    * @param textColour2
2514    * @see jalview.api.ViewStyleI#setTextColour2(java.awt.Color)
2515    */
2516   @Override
2517   public void setTextColour2(Color textColour2)
2518   {
2519     viewStyle.setTextColour2(textColour2);
2520   }
2521
2522   @Override
2523   public ViewStyleI getViewStyle()
2524   {
2525     return new ViewStyle(viewStyle);
2526   }
2527
2528   @Override
2529   public void setViewStyle(ViewStyleI settingsForView)
2530   {
2531     viewStyle = new ViewStyle(settingsForView);
2532     if (residueShading != null)
2533     {
2534       residueShading.setConservationApplied(
2535               settingsForView.isConservationColourSelected());
2536     }
2537   }
2538
2539   @Override
2540   public boolean sameStyle(ViewStyleI them)
2541   {
2542     return viewStyle.sameStyle(them);
2543   }
2544
2545   /**
2546    * @return
2547    * @see jalview.api.ViewStyleI#getIdWidth()
2548    */
2549   @Override
2550   public int getIdWidth()
2551   {
2552     return viewStyle.getIdWidth();
2553   }
2554
2555   /**
2556    * @param i
2557    * @see jalview.api.ViewStyleI#setIdWidth(int)
2558    */
2559   @Override
2560   public void setIdWidth(int i)
2561   {
2562     viewStyle.setIdWidth(i);
2563   }
2564
2565   /**
2566    * @return
2567    * @see jalview.api.ViewStyleI#isCentreColumnLabels()
2568    */
2569   @Override
2570   public boolean isCentreColumnLabels()
2571   {
2572     return viewStyle.isCentreColumnLabels();
2573   }
2574
2575   /**
2576    * @param centreColumnLabels
2577    * @see jalview.api.ViewStyleI#setCentreColumnLabels(boolean)
2578    */
2579   @Override
2580   public void setCentreColumnLabels(boolean centreColumnLabels)
2581   {
2582     viewStyle.setCentreColumnLabels(centreColumnLabels);
2583   }
2584
2585   /**
2586    * @param showdbrefs
2587    * @see jalview.api.ViewStyleI#setShowDBRefs(boolean)
2588    */
2589   @Override
2590   public void setShowDBRefs(boolean showdbrefs)
2591   {
2592     viewStyle.setShowDBRefs(showdbrefs);
2593   }
2594
2595   /**
2596    * @return
2597    * @see jalview.api.ViewStyleI#isShowDBRefs()
2598    */
2599   @Override
2600   public boolean isShowDBRefs()
2601   {
2602     return viewStyle.isShowDBRefs();
2603   }
2604
2605   /**
2606    * @return
2607    * @see jalview.api.ViewStyleI#isShowNPFeats()
2608    */
2609   @Override
2610   public boolean isShowNPFeats()
2611   {
2612     return viewStyle.isShowNPFeats();
2613   }
2614
2615   /**
2616    * @param shownpfeats
2617    * @see jalview.api.ViewStyleI#setShowNPFeats(boolean)
2618    */
2619   @Override
2620   public void setShowNPFeats(boolean shownpfeats)
2621   {
2622     viewStyle.setShowNPFeats(shownpfeats);
2623   }
2624
2625   public abstract StructureSelectionManager getStructureSelectionManager();
2626
2627   /**
2628    * Add one command to the command history list.
2629    * 
2630    * @param command
2631    */
2632   public void addToHistoryList(CommandI command)
2633   {
2634     if (this.historyList != null)
2635     {
2636       this.historyList.push(command);
2637       broadcastCommand(command, false);
2638     }
2639   }
2640
2641   protected void broadcastCommand(CommandI command, boolean undo)
2642   {
2643     getStructureSelectionManager().commandPerformed(command, undo,
2644             getVamsasSource());
2645   }
2646
2647   /**
2648    * Add one command to the command redo list.
2649    * 
2650    * @param command
2651    */
2652   public void addToRedoList(CommandI command)
2653   {
2654     if (this.redoList != null)
2655     {
2656       this.redoList.push(command);
2657     }
2658     broadcastCommand(command, true);
2659   }
2660
2661   /**
2662    * Clear the command redo list.
2663    */
2664   public void clearRedoList()
2665   {
2666     if (this.redoList != null)
2667     {
2668       this.redoList.clear();
2669     }
2670   }
2671
2672   public void setHistoryList(Deque<CommandI> list)
2673   {
2674     this.historyList = list;
2675   }
2676
2677   public Deque<CommandI> getHistoryList()
2678   {
2679     return this.historyList;
2680   }
2681
2682   public void setRedoList(Deque<CommandI> list)
2683   {
2684     this.redoList = list;
2685   }
2686
2687   public Deque<CommandI> getRedoList()
2688   {
2689     return this.redoList;
2690   }
2691
2692   @Override
2693   public VamsasSource getVamsasSource()
2694   {
2695     return this;
2696   }
2697
2698   public SequenceAnnotationOrder getSortAnnotationsBy()
2699   {
2700     return sortAnnotationsBy;
2701   }
2702
2703   public void setSortAnnotationsBy(
2704           SequenceAnnotationOrder sortAnnotationsBy)
2705   {
2706     this.sortAnnotationsBy = sortAnnotationsBy;
2707   }
2708
2709   public boolean isShowAutocalculatedAbove()
2710   {
2711     return showAutocalculatedAbove;
2712   }
2713
2714   public void setShowAutocalculatedAbove(boolean showAutocalculatedAbove)
2715   {
2716     this.showAutocalculatedAbove = showAutocalculatedAbove;
2717   }
2718
2719   @Override
2720   public boolean isScaleProteinAsCdna()
2721   {
2722     return viewStyle.isScaleProteinAsCdna();
2723   }
2724
2725   @Override
2726   public void setScaleProteinAsCdna(boolean b)
2727   {
2728     viewStyle.setScaleProteinAsCdna(b);
2729   }
2730
2731   @Override
2732   public boolean isProteinFontAsCdna()
2733   {
2734     return viewStyle.isProteinFontAsCdna();
2735   }
2736
2737   @Override
2738   public void setProteinFontAsCdna(boolean b)
2739   {
2740     viewStyle.setProteinFontAsCdna(b);
2741   }
2742
2743   /**
2744    * @return true if view should scroll to show the highlighted region of a
2745    *         sequence
2746    * @return
2747    */
2748   @Override
2749   public final boolean isFollowHighlight()
2750   {
2751     return followHighlight;
2752   }
2753
2754   @Override
2755   public final void setFollowHighlight(boolean b)
2756   {
2757     this.followHighlight = b;
2758   }
2759
2760   @Override
2761   public ViewportRanges getRanges()
2762   {
2763     return ranges;
2764   }
2765
2766   /**
2767    * Helper method to populate the SearchResults with the location in the
2768    * complementary alignment to scroll to, in order to match this one.
2769    * 
2770    * @param sr
2771    *          the SearchResults to add to
2772    * @return the offset (below top of visible region) of the matched sequence
2773    */
2774   protected int findComplementScrollTarget(SearchResultsI sr)
2775   {
2776     final AlignViewportI complement = getCodingComplement();
2777     if (complement == null || !complement.isFollowHighlight())
2778     {
2779       return 0;
2780     }
2781     boolean iAmProtein = !getAlignment().isNucleotide();
2782     AlignmentI proteinAlignment = iAmProtein ? getAlignment()
2783             : complement.getAlignment();
2784     if (proteinAlignment == null)
2785     {
2786       return 0;
2787     }
2788     final List<AlignedCodonFrame> mappings = proteinAlignment
2789             .getCodonFrames();
2790
2791     /*
2792      * Heuristic: find the first mapped sequence (if any) with a non-gapped
2793      * residue in the middle column of the visible region. Scroll the
2794      * complementary alignment to line up the corresponding residue.
2795      */
2796     int seqOffset = 0;
2797     SequenceI sequence = null;
2798
2799     /*
2800      * locate 'middle' column (true middle if an odd number visible, left of
2801      * middle if an even number visible)
2802      */
2803     int middleColumn = ranges.getStartRes()
2804             + (ranges.getEndRes() - ranges.getStartRes()) / 2;
2805     final HiddenSequences hiddenSequences = getAlignment()
2806             .getHiddenSequences();
2807
2808     /*
2809      * searching to the bottom of the alignment gives smoother scrolling across
2810      * all gapped visible regions
2811      */
2812     int lastSeq = alignment.getHeight() - 1;
2813     List<AlignedCodonFrame> seqMappings = null;
2814     for (int seqNo = ranges
2815             .getStartSeq(); seqNo <= lastSeq; seqNo++, seqOffset++)
2816     {
2817       sequence = getAlignment().getSequenceAt(seqNo);
2818       if (hiddenSequences != null && hiddenSequences.isHidden(sequence))
2819       {
2820         continue;
2821       }
2822       if (Comparison.isGap(sequence.getCharAt(middleColumn)))
2823       {
2824         continue;
2825       }
2826       seqMappings = MappingUtils.findMappingsForSequenceAndOthers(sequence,
2827               mappings,
2828               getCodingComplement().getAlignment().getSequences());
2829       if (!seqMappings.isEmpty())
2830       {
2831         break;
2832       }
2833     }
2834
2835     if (sequence == null || seqMappings == null || seqMappings.isEmpty())
2836     {
2837       /*
2838        * No ungapped mapped sequence in middle column - do nothing
2839        */
2840       return 0;
2841     }
2842     MappingUtils.addSearchResults(sr, sequence,
2843             sequence.findPosition(middleColumn), seqMappings);
2844     return seqOffset;
2845   }
2846
2847   /**
2848    * synthesize a column selection if none exists so it covers the given
2849    * selection group. if wholewidth is false, no column selection is made if the
2850    * selection group covers the whole alignment width.
2851    * 
2852    * @param sg
2853    * @param wholewidth
2854    */
2855   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
2856   {
2857     int sgs, sge;
2858     if (sg != null && (sgs = sg.getStartRes()) >= 0
2859             && sg.getStartRes() <= (sge = sg.getEndRes())
2860             && !this.hasSelectedColumns())
2861     {
2862       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
2863       {
2864         // do nothing
2865         return;
2866       }
2867       if (colSel == null)
2868       {
2869         colSel = new ColumnSelection();
2870       }
2871       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
2872       {
2873         colSel.addElement(cspos);
2874       }
2875     }
2876   }
2877
2878   /**
2879    * hold status of current selection group - defined on alignment or not.
2880    */
2881   private boolean selectionIsDefinedGroup = false;
2882
2883   @Override
2884   public boolean isSelectionDefinedGroup()
2885   {
2886     if (selectionGroup == null)
2887     {
2888       return false;
2889     }
2890     if (isSelectionGroupChanged(true))
2891     {
2892       selectionIsDefinedGroup = false;
2893       List<SequenceGroup> gps = alignment.getGroups();
2894       if (gps == null || gps.size() == 0)
2895       {
2896         selectionIsDefinedGroup = false;
2897       }
2898       else
2899       {
2900         selectionIsDefinedGroup = gps.contains(selectionGroup);
2901       }
2902     }
2903     return selectionGroup.isDefined() || selectionIsDefinedGroup;
2904   }
2905
2906   /**
2907    * null, or currently highlighted results on this view
2908    */
2909   private SearchResultsI searchResults = null;
2910
2911   protected TreeModel currentTree = null;
2912
2913   @Override
2914   public boolean hasSearchResults()
2915   {
2916     return searchResults != null;
2917   }
2918
2919   @Override
2920   public void setSearchResults(SearchResultsI results)
2921   {
2922     searchResults = results;
2923   }
2924
2925   @Override
2926   public SearchResultsI getSearchResults()
2927   {
2928     return searchResults;
2929   }
2930
2931   /**
2932    * get the consensus sequence as displayed under the PID consensus annotation
2933    * row.
2934    * 
2935    * @return consensus sequence as a new sequence object
2936    */
2937   public SequenceI getConsensusSeq()
2938   {
2939     if (consensus == null)
2940     {
2941       updateConsensus(null);
2942     }
2943     if (consensus == null)
2944     {
2945       return null;
2946     }
2947     StringBuffer seqs = new StringBuffer();
2948     for (int i = 0; i < consensus.annotations.length; i++)
2949     {
2950       Annotation annotation = consensus.annotations[i];
2951       if (annotation != null)
2952       {
2953         String description = annotation.description;
2954         if (description != null && description.startsWith("["))
2955         {
2956           // consensus is a tie - just pick the first one
2957           seqs.append(description.charAt(1));
2958         }
2959         else
2960         {
2961           seqs.append(annotation.displayCharacter);
2962         }
2963       }
2964     }
2965
2966     SequenceI sq = new Sequence("Consensus", seqs.toString());
2967     sq.setDescription("Percentage Identity Consensus "
2968             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
2969     return sq;
2970   }
2971
2972   @Override
2973   public void setCurrentTree(TreeModel tree)
2974   {
2975     currentTree = tree;
2976   }
2977
2978   @Override
2979   public TreeModel getCurrentTree()
2980   {
2981     return currentTree;
2982   }
2983
2984   @Override
2985   public AlignmentExportData getAlignExportData(AlignExportSettingsI options)
2986   {
2987     AlignmentI alignmentToExport = null;
2988     String[] omitHidden = null;
2989     alignmentToExport = null;
2990
2991     if (hasHiddenColumns() && !options.isExportHiddenColumns())
2992     {
2993       omitHidden = getViewAsString(false,
2994               options.isExportHiddenSequences());
2995     }
2996
2997     int[] alignmentStartEnd = new int[2];
2998     if (hasHiddenRows() && options.isExportHiddenSequences())
2999     {
3000       alignmentToExport = getAlignment().getHiddenSequences()
3001               .getFullAlignment();
3002     }
3003     else
3004     {
3005       alignmentToExport = getAlignment();
3006     }
3007     alignmentStartEnd = getAlignment().getHiddenColumns()
3008             .getVisibleStartAndEndIndex(alignmentToExport.getWidth());
3009     AlignmentExportData ed = new AlignmentExportData(alignmentToExport,
3010             omitHidden, alignmentStartEnd);
3011     return ed;
3012   }
3013   
3014   /**
3015    * flag set to indicate if structure views might be out of sync with sequences
3016    * in the alignment
3017    */
3018
3019   private boolean needToUpdateStructureViews = false;
3020
3021   @Override
3022   public boolean isUpdateStructures()
3023   {
3024     return needToUpdateStructureViews;
3025   }
3026
3027   @Override
3028   public void setUpdateStructures(boolean update)
3029   {
3030     needToUpdateStructureViews = update;
3031   }
3032
3033   @Override
3034   public boolean needToUpdateStructureViews()
3035   {
3036     boolean update = needToUpdateStructureViews;
3037     needToUpdateStructureViews = false;
3038     return update;
3039   }
3040
3041   @Override
3042   public void addSequenceGroup(SequenceGroup sequenceGroup)
3043   {
3044     alignment.addGroup(sequenceGroup);
3045
3046     Color col = sequenceGroup.idColour;
3047     if (col != null)
3048     {
3049       col = col.brighter();
3050
3051       for (SequenceI sq : sequenceGroup.getSequences())
3052       {
3053         setSequenceColour(sq, col);
3054       }
3055     }
3056
3057     if (codingComplement != null)
3058     {
3059       SequenceGroup mappedGroup = MappingUtils
3060               .mapSequenceGroup(sequenceGroup, this, codingComplement);
3061       if (mappedGroup.getSequences().size() > 0)
3062       {
3063         codingComplement.getAlignment().addGroup(mappedGroup);
3064
3065         if (col != null)
3066         {
3067           for (SequenceI seq : mappedGroup.getSequences())
3068           {
3069             codingComplement.setSequenceColour(seq, col);
3070           }
3071         }
3072       }
3073       // propagate the structure view update flag according to our own setting
3074       codingComplement.setUpdateStructures(needToUpdateStructureViews);
3075     }
3076   }
3077 }