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