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