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