Merge branch 'develop' into features/JAL-653_JAL-1766_htslib_refseqsupport
[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       if (alignment.getHiddenSequences() != null)
1571       {
1572         iSize = alignment.getHiddenSequences().getFullAlignment()
1573                 .getHeight();
1574         seqs = alignment.getHiddenSequences().getFullAlignment()
1575                 .getSequencesArray();
1576         end = alignment.getHiddenSequences().getFullAlignment().getWidth();
1577       }
1578       else
1579       {
1580         iSize = alignment.getHeight();
1581         seqs = alignment.getSequencesArray();
1582         end = alignment.getWidth();
1583       }
1584     }
1585
1586     selection = new String[iSize];
1587     if (colSel != null && colSel.hasHiddenColumns())
1588     {
1589       selection = colSel.getVisibleSequenceStrings(start, end, seqs);
1590     }
1591     else
1592     {
1593       for (i = 0; i < iSize; i++)
1594       {
1595         selection[i] = seqs[i].getSequenceAsString(start, end);
1596       }
1597
1598     }
1599     return selection;
1600   }
1601
1602   @Override
1603   public List<int[]> getVisibleRegionBoundaries(int min, int max)
1604   {
1605     ArrayList<int[]> regions = new ArrayList<int[]>();
1606     int start = min;
1607     int end = max;
1608
1609     do
1610     {
1611       if (colSel != null && colSel.hasHiddenColumns())
1612       {
1613         if (start == 0)
1614         {
1615           start = colSel.adjustForHiddenColumns(start);
1616         }
1617
1618         end = colSel.getHiddenBoundaryRight(start);
1619         if (start == end)
1620         {
1621           end = max;
1622         }
1623         if (end > max)
1624         {
1625           end = max;
1626         }
1627       }
1628
1629       regions.add(new int[] { start, end });
1630
1631       if (colSel != null && colSel.hasHiddenColumns())
1632       {
1633         start = colSel.adjustForHiddenColumns(end);
1634         start = colSel.getHiddenBoundaryLeft(start) + 1;
1635       }
1636     } while (end < max);
1637
1638     int[][] startEnd = new int[regions.size()][2];
1639
1640     return regions;
1641   }
1642
1643   @Override
1644   public List<AlignmentAnnotation> getVisibleAlignmentAnnotation(
1645           boolean selectedOnly)
1646   {
1647     ArrayList<AlignmentAnnotation> ala = new ArrayList<AlignmentAnnotation>();
1648     AlignmentAnnotation[] aa;
1649     if ((aa = alignment.getAlignmentAnnotation()) != null)
1650     {
1651       for (AlignmentAnnotation annot : aa)
1652       {
1653         AlignmentAnnotation clone = new AlignmentAnnotation(annot);
1654         if (selectedOnly && selectionGroup != null)
1655         {
1656           colSel.makeVisibleAnnotation(selectionGroup.getStartRes(),
1657                   selectionGroup.getEndRes(), clone);
1658         }
1659         else
1660         {
1661           colSel.makeVisibleAnnotation(clone);
1662         }
1663         ala.add(clone);
1664       }
1665     }
1666     return ala;
1667   }
1668
1669   @Override
1670   public boolean isPadGaps()
1671   {
1672     return padGaps;
1673   }
1674
1675   @Override
1676   public void setPadGaps(boolean padGaps)
1677   {
1678     this.padGaps = padGaps;
1679   }
1680
1681   /**
1682    * apply any post-edit constraints and trigger any calculations needed after
1683    * an edit has been performed on the alignment
1684    * 
1685    * @param ap
1686    */
1687   @Override
1688   public void alignmentChanged(AlignmentViewPanel ap)
1689   {
1690     if (isPadGaps())
1691     {
1692       alignment.padGaps();
1693     }
1694     if (autoCalculateConsensus)
1695     {
1696       updateConsensus(ap);
1697     }
1698     if (hconsensus != null && autoCalculateConsensus)
1699     {
1700       updateConservation(ap);
1701     }
1702     if (autoCalculateStrucConsensus)
1703     {
1704       updateStrucConsensus(ap);
1705     }
1706
1707     // Reset endRes of groups if beyond alignment width
1708     int alWidth = alignment.getWidth();
1709     List<SequenceGroup> groups = alignment.getGroups();
1710     if (groups != null)
1711     {
1712       for (SequenceGroup sg : groups)
1713       {
1714         if (sg.getEndRes() > alWidth)
1715         {
1716           sg.setEndRes(alWidth - 1);
1717         }
1718       }
1719     }
1720
1721     if (selectionGroup != null && selectionGroup.getEndRes() > alWidth)
1722     {
1723       selectionGroup.setEndRes(alWidth - 1);
1724     }
1725
1726     resetAllColourSchemes();
1727     calculator.restartWorkers();
1728     // alignment.adjustSequenceAnnotations();
1729   }
1730
1731   /**
1732    * reset scope and do calculations for all applied colourschemes on alignment
1733    */
1734   void resetAllColourSchemes()
1735   {
1736     ColourSchemeI cs = globalColourScheme;
1737     if (cs != null)
1738     {
1739       cs.alignmentChanged(alignment, hiddenRepSequences);
1740
1741       cs.setConsensus(hconsensus);
1742       if (cs.conservationApplied())
1743       {
1744         cs.setConservation(Conservation.calculateConservation("All",
1745                 ResidueProperties.propHash, 3, alignment.getSequences(), 0,
1746                 alignment.getWidth(), false, getConsPercGaps(), false));
1747       }
1748     }
1749
1750     for (SequenceGroup sg : alignment.getGroups())
1751     {
1752       if (sg.cs != null)
1753       {
1754         sg.cs.alignmentChanged(sg, hiddenRepSequences);
1755       }
1756       sg.recalcConservation();
1757     }
1758   }
1759
1760   protected void initAutoAnnotation()
1761   {
1762     // TODO: add menu option action that nulls or creates consensus object
1763     // depending on if the user wants to see the annotation or not in a
1764     // specific alignment
1765
1766     if (hconsensus == null && !isDataset)
1767     {
1768       if (!alignment.isNucleotide())
1769       {
1770         initConservation();
1771         initQuality();
1772       }
1773       else
1774       {
1775         initRNAStructure();
1776       }
1777       consensus = new AlignmentAnnotation("Consensus", "PID",
1778               new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH);
1779       initConsensus(consensus);
1780
1781       initComplementConsensus();
1782     }
1783   }
1784
1785   /**
1786    * If this is a protein alignment and there are mappings to cDNA, add the cDNA
1787    * consensus annotation.
1788    */
1789   public void initComplementConsensus()
1790   {
1791     if (!alignment.isNucleotide())
1792     {
1793       final List<AlignedCodonFrame> codonMappings = alignment
1794               .getCodonFrames();
1795       if (codonMappings != null && !codonMappings.isEmpty())
1796       {
1797         // fudge: check mappings are not protein-to-protein
1798         // TODO: nicer
1799         AlignedCodonFrame mapping = codonMappings.iterator().next();
1800         if (mapping.getdnaToProt()[0].getFromRatio() == 3)
1801         {
1802           complementConsensus = new AlignmentAnnotation("cDNA Consensus",
1803                   "PID for cDNA", new Annotation[1], 0f, 100f,
1804                   AlignmentAnnotation.BAR_GRAPH);
1805           initConsensus(complementConsensus);
1806         }
1807       }
1808     }
1809   }
1810
1811   private void initConsensus(AlignmentAnnotation aa)
1812   {
1813     aa.hasText = true;
1814     aa.autoCalculated = true;
1815
1816     if (showConsensus)
1817     {
1818       alignment.addAnnotation(aa);
1819     }
1820   }
1821
1822   private void initConservation()
1823   {
1824     if (showConservation)
1825     {
1826       if (conservation == null)
1827       {
1828         conservation = new AlignmentAnnotation("Conservation",
1829                 "Conservation of total alignment less than "
1830                         + getConsPercGaps() + "% gaps", new Annotation[1],
1831                 0f, 11f, AlignmentAnnotation.BAR_GRAPH);
1832         conservation.hasText = true;
1833         conservation.autoCalculated = true;
1834         alignment.addAnnotation(conservation);
1835       }
1836     }
1837   }
1838
1839   private void initQuality()
1840   {
1841     if (showQuality)
1842     {
1843       if (quality == null)
1844       {
1845         quality = new AlignmentAnnotation("Quality",
1846                 "Alignment Quality based on Blosum62 scores",
1847                 new Annotation[1], 0f, 11f, AlignmentAnnotation.BAR_GRAPH);
1848         quality.hasText = true;
1849         quality.autoCalculated = true;
1850         alignment.addAnnotation(quality);
1851       }
1852     }
1853   }
1854
1855   private void initRNAStructure()
1856   {
1857     if (alignment.hasRNAStructure() && strucConsensus == null)
1858     {
1859       strucConsensus = new AlignmentAnnotation("StrucConsensus", "PID",
1860               new Annotation[1], 0f, 100f, AlignmentAnnotation.BAR_GRAPH);
1861       strucConsensus.hasText = true;
1862       strucConsensus.autoCalculated = true;
1863
1864       if (showConsensus)
1865       {
1866         alignment.addAnnotation(strucConsensus);
1867       }
1868     }
1869   }
1870
1871   /*
1872    * (non-Javadoc)
1873    * 
1874    * @see jalview.api.AlignViewportI#calcPanelHeight()
1875    */
1876   @Override
1877   public int calcPanelHeight()
1878   {
1879     // setHeight of panels
1880     AlignmentAnnotation[] anns = getAlignment().getAlignmentAnnotation();
1881     int height = 0;
1882     int charHeight = getCharHeight();
1883     if (anns != null)
1884     {
1885       BitSet graphgrp = new BitSet();
1886       for (AlignmentAnnotation aa : anns)
1887       {
1888         if (aa == null)
1889         {
1890           System.err.println("Null annotation row: ignoring.");
1891           continue;
1892         }
1893         if (!aa.visible)
1894         {
1895           continue;
1896         }
1897         if (aa.graphGroup > -1)
1898         {
1899           if (graphgrp.get(aa.graphGroup))
1900           {
1901             continue;
1902           }
1903           else
1904           {
1905             graphgrp.set(aa.graphGroup);
1906           }
1907         }
1908         aa.height = 0;
1909
1910         if (aa.hasText)
1911         {
1912           aa.height += charHeight;
1913         }
1914
1915         if (aa.hasIcons)
1916         {
1917           aa.height += 16;
1918         }
1919
1920         if (aa.graph > 0)
1921         {
1922           aa.height += aa.graphHeight;
1923         }
1924
1925         if (aa.height == 0)
1926         {
1927           aa.height = 20;
1928         }
1929
1930         height += aa.height;
1931       }
1932     }
1933     if (height == 0)
1934     {
1935       // set minimum
1936       height = 20;
1937     }
1938     return height;
1939   }
1940
1941   @Override
1942   public void updateGroupAnnotationSettings(boolean applyGlobalSettings,
1943           boolean preserveNewGroupSettings)
1944   {
1945     boolean updateCalcs = false;
1946     boolean conv = isShowGroupConservation();
1947     boolean cons = isShowGroupConsensus();
1948     boolean showprf = isShowSequenceLogo();
1949     boolean showConsHist = isShowConsensusHistogram();
1950     boolean normLogo = isNormaliseSequenceLogo();
1951
1952     /**
1953      * TODO reorder the annotation rows according to group/sequence ordering on
1954      * alignment
1955      */
1956     boolean sortg = true;
1957
1958     // remove old automatic annotation
1959     // add any new annotation
1960
1961     // intersect alignment annotation with alignment groups
1962
1963     AlignmentAnnotation[] aan = alignment.getAlignmentAnnotation();
1964     List<SequenceGroup> oldrfs = new ArrayList<SequenceGroup>();
1965     if (aan != null)
1966     {
1967       for (int an = 0; an < aan.length; an++)
1968       {
1969         if (aan[an].autoCalculated && aan[an].groupRef != null)
1970         {
1971           oldrfs.add(aan[an].groupRef);
1972           alignment.deleteAnnotation(aan[an], false);
1973         }
1974       }
1975     }
1976     if (alignment.getGroups() != null)
1977     {
1978       for (SequenceGroup sg : alignment.getGroups())
1979       {
1980         updateCalcs = false;
1981         if (applyGlobalSettings
1982                 || (!preserveNewGroupSettings && !oldrfs.contains(sg)))
1983         {
1984           // set defaults for this group's conservation/consensus
1985           sg.setshowSequenceLogo(showprf);
1986           sg.setShowConsensusHistogram(showConsHist);
1987           sg.setNormaliseSequenceLogo(normLogo);
1988         }
1989         if (conv)
1990         {
1991           updateCalcs = true;
1992           alignment.addAnnotation(sg.getConservationRow(), 0);
1993         }
1994         if (cons)
1995         {
1996           updateCalcs = true;
1997           alignment.addAnnotation(sg.getConsensus(), 0);
1998         }
1999         // refresh the annotation rows
2000         if (updateCalcs)
2001         {
2002           sg.recalcConservation();
2003         }
2004       }
2005     }
2006     oldrfs.clear();
2007   }
2008
2009   @Override
2010   public boolean isDisplayReferenceSeq()
2011   {
2012     return alignment.hasSeqrep() && viewStyle.isDisplayReferenceSeq();
2013   }
2014
2015   @Override
2016   public void setDisplayReferenceSeq(boolean displayReferenceSeq)
2017   {
2018     viewStyle.setDisplayReferenceSeq(displayReferenceSeq);
2019   }
2020
2021   @Override
2022   public boolean isColourByReferenceSeq()
2023   {
2024     return alignment.hasSeqrep() && viewStyle.isColourByReferenceSeq();
2025   }
2026
2027   @Override
2028   public Color getSequenceColour(SequenceI seq)
2029   {
2030     Color sqc = sequenceColours.get(seq);
2031     return (sqc == null ? Color.white : sqc);
2032   }
2033
2034   @Override
2035   public void setSequenceColour(SequenceI seq, Color col)
2036   {
2037     if (col == null)
2038     {
2039       sequenceColours.remove(seq);
2040     }
2041     else
2042     {
2043       sequenceColours.put(seq, col);
2044     }
2045   }
2046
2047   @Override
2048   public void updateSequenceIdColours()
2049   {
2050     for (SequenceGroup sg : alignment.getGroups())
2051     {
2052       if (sg.idColour != null)
2053       {
2054         for (SequenceI s : sg.getSequences(getHiddenRepSequences()))
2055         {
2056           sequenceColours.put(s, sg.idColour);
2057         }
2058       }
2059     }
2060   }
2061
2062   @Override
2063   public void clearSequenceColours()
2064   {
2065     sequenceColours.clear();
2066   };
2067
2068   @Override
2069   public AlignViewportI getCodingComplement()
2070   {
2071     return this.codingComplement;
2072   }
2073
2074   /**
2075    * Set this as the (cDna/protein) complement of the given viewport. Also
2076    * ensures the reverse relationship is set on the given viewport.
2077    */
2078   @Override
2079   public void setCodingComplement(AlignViewportI av)
2080   {
2081     if (this == av)
2082     {
2083       System.err.println("Ignoring recursive setCodingComplement request");
2084     }
2085     else
2086     {
2087       this.codingComplement = av;
2088       // avoid infinite recursion!
2089       if (av.getCodingComplement() != this)
2090       {
2091         av.setCodingComplement(this);
2092       }
2093     }
2094   }
2095
2096   @Override
2097   public boolean isNucleotide()
2098   {
2099     return getAlignment() == null ? false : getAlignment().isNucleotide();
2100   }
2101
2102   @Override
2103   public FeaturesDisplayedI getFeaturesDisplayed()
2104   {
2105     return featuresDisplayed;
2106   }
2107
2108   @Override
2109   public void setFeaturesDisplayed(FeaturesDisplayedI featuresDisplayedI)
2110   {
2111     featuresDisplayed = featuresDisplayedI;
2112   }
2113
2114   @Override
2115   public boolean areFeaturesDisplayed()
2116   {
2117     return featuresDisplayed != null
2118             && featuresDisplayed.getRegisteredFeaturesCount() > 0;
2119   }
2120
2121   /**
2122    * set the flag
2123    * 
2124    * @param b
2125    *          features are displayed if true
2126    */
2127   @Override
2128   public void setShowSequenceFeatures(boolean b)
2129   {
2130     viewStyle.setShowSequenceFeatures(b);
2131   }
2132
2133   @Override
2134   public boolean isShowSequenceFeatures()
2135   {
2136     return viewStyle.isShowSequenceFeatures();
2137   }
2138
2139   @Override
2140   public void setShowSequenceFeaturesHeight(boolean selected)
2141   {
2142     viewStyle.setShowSequenceFeaturesHeight(selected);
2143   }
2144
2145   @Override
2146   public boolean isShowSequenceFeaturesHeight()
2147   {
2148     return viewStyle.isShowSequenceFeaturesHeight();
2149   }
2150
2151   @Override
2152   public void setShowAnnotation(boolean b)
2153   {
2154     viewStyle.setShowAnnotation(b);
2155   }
2156
2157   @Override
2158   public boolean isShowAnnotation()
2159   {
2160     return viewStyle.isShowAnnotation();
2161   }
2162
2163   @Override
2164   public boolean isRightAlignIds()
2165   {
2166     return viewStyle.isRightAlignIds();
2167   }
2168
2169   @Override
2170   public void setRightAlignIds(boolean rightAlignIds)
2171   {
2172     viewStyle.setRightAlignIds(rightAlignIds);
2173   }
2174
2175   @Override
2176   public boolean getConservationSelected()
2177   {
2178     return viewStyle.getConservationSelected();
2179   }
2180
2181   @Override
2182   public void setShowBoxes(boolean state)
2183   {
2184     viewStyle.setShowBoxes(state);
2185   }
2186
2187   /**
2188    * @return
2189    * @see jalview.api.ViewStyleI#getTextColour()
2190    */
2191   @Override
2192   public Color getTextColour()
2193   {
2194     return viewStyle.getTextColour();
2195   }
2196
2197   /**
2198    * @return
2199    * @see jalview.api.ViewStyleI#getTextColour2()
2200    */
2201   @Override
2202   public Color getTextColour2()
2203   {
2204     return viewStyle.getTextColour2();
2205   }
2206
2207   /**
2208    * @return
2209    * @see jalview.api.ViewStyleI#getThresholdTextColour()
2210    */
2211   @Override
2212   public int getThresholdTextColour()
2213   {
2214     return viewStyle.getThresholdTextColour();
2215   }
2216
2217   /**
2218    * @return
2219    * @see jalview.api.ViewStyleI#isConservationColourSelected()
2220    */
2221   @Override
2222   public boolean isConservationColourSelected()
2223   {
2224     return viewStyle.isConservationColourSelected();
2225   }
2226
2227   /**
2228    * @return
2229    * @see jalview.api.ViewStyleI#isRenderGaps()
2230    */
2231   @Override
2232   public boolean isRenderGaps()
2233   {
2234     return viewStyle.isRenderGaps();
2235   }
2236
2237   /**
2238    * @return
2239    * @see jalview.api.ViewStyleI#isShowColourText()
2240    */
2241   @Override
2242   public boolean isShowColourText()
2243   {
2244     return viewStyle.isShowColourText();
2245   }
2246
2247   /**
2248    * @param conservationColourSelected
2249    * @see jalview.api.ViewStyleI#setConservationColourSelected(boolean)
2250    */
2251   @Override
2252   public void setConservationColourSelected(
2253           boolean conservationColourSelected)
2254   {
2255     viewStyle.setConservationColourSelected(conservationColourSelected);
2256   }
2257
2258   /**
2259    * @param showColourText
2260    * @see jalview.api.ViewStyleI#setShowColourText(boolean)
2261    */
2262   @Override
2263   public void setShowColourText(boolean showColourText)
2264   {
2265     viewStyle.setShowColourText(showColourText);
2266   }
2267
2268   /**
2269    * @param textColour
2270    * @see jalview.api.ViewStyleI#setTextColour(java.awt.Color)
2271    */
2272   @Override
2273   public void setTextColour(Color textColour)
2274   {
2275     viewStyle.setTextColour(textColour);
2276   }
2277
2278   /**
2279    * @param thresholdTextColour
2280    * @see jalview.api.ViewStyleI#setThresholdTextColour(int)
2281    */
2282   @Override
2283   public void setThresholdTextColour(int thresholdTextColour)
2284   {
2285     viewStyle.setThresholdTextColour(thresholdTextColour);
2286   }
2287
2288   /**
2289    * @param textColour2
2290    * @see jalview.api.ViewStyleI#setTextColour2(java.awt.Color)
2291    */
2292   @Override
2293   public void setTextColour2(Color textColour2)
2294   {
2295     viewStyle.setTextColour2(textColour2);
2296   }
2297
2298   @Override
2299   public ViewStyleI getViewStyle()
2300   {
2301     return new ViewStyle(viewStyle);
2302   }
2303
2304   @Override
2305   public void setViewStyle(ViewStyleI settingsForView)
2306   {
2307     viewStyle = new ViewStyle(settingsForView);
2308   }
2309
2310   @Override
2311   public boolean sameStyle(ViewStyleI them)
2312   {
2313     return viewStyle.sameStyle(them);
2314   }
2315
2316   /**
2317    * @return
2318    * @see jalview.api.ViewStyleI#getIdWidth()
2319    */
2320   @Override
2321   public int getIdWidth()
2322   {
2323     return viewStyle.getIdWidth();
2324   }
2325
2326   /**
2327    * @param i
2328    * @see jalview.api.ViewStyleI#setIdWidth(int)
2329    */
2330   @Override
2331   public void setIdWidth(int i)
2332   {
2333     viewStyle.setIdWidth(i);
2334   }
2335
2336   /**
2337    * @return
2338    * @see jalview.api.ViewStyleI#isCentreColumnLabels()
2339    */
2340   @Override
2341   public boolean isCentreColumnLabels()
2342   {
2343     return viewStyle.isCentreColumnLabels();
2344   }
2345
2346   /**
2347    * @param centreColumnLabels
2348    * @see jalview.api.ViewStyleI#setCentreColumnLabels(boolean)
2349    */
2350   @Override
2351   public void setCentreColumnLabels(boolean centreColumnLabels)
2352   {
2353     viewStyle.setCentreColumnLabels(centreColumnLabels);
2354   }
2355
2356   /**
2357    * @param showdbrefs
2358    * @see jalview.api.ViewStyleI#setShowDBRefs(boolean)
2359    */
2360   @Override
2361   public void setShowDBRefs(boolean showdbrefs)
2362   {
2363     viewStyle.setShowDBRefs(showdbrefs);
2364   }
2365
2366   /**
2367    * @return
2368    * @see jalview.api.ViewStyleI#isShowDBRefs()
2369    */
2370   @Override
2371   public boolean isShowDBRefs()
2372   {
2373     return viewStyle.isShowDBRefs();
2374   }
2375
2376   /**
2377    * @return
2378    * @see jalview.api.ViewStyleI#isShowNPFeats()
2379    */
2380   @Override
2381   public boolean isShowNPFeats()
2382   {
2383     return viewStyle.isShowNPFeats();
2384   }
2385
2386   /**
2387    * @param shownpfeats
2388    * @see jalview.api.ViewStyleI#setShowNPFeats(boolean)
2389    */
2390   @Override
2391   public void setShowNPFeats(boolean shownpfeats)
2392   {
2393     viewStyle.setShowNPFeats(shownpfeats);
2394   }
2395
2396   public abstract StructureSelectionManager getStructureSelectionManager();
2397
2398   /**
2399    * Add one command to the command history list.
2400    * 
2401    * @param command
2402    */
2403   public void addToHistoryList(CommandI command)
2404   {
2405     if (this.historyList != null)
2406     {
2407       this.historyList.push(command);
2408       broadcastCommand(command, false);
2409     }
2410   }
2411
2412   protected void broadcastCommand(CommandI command, boolean undo)
2413   {
2414     getStructureSelectionManager().commandPerformed(command, undo,
2415             getVamsasSource());
2416   }
2417
2418   /**
2419    * Add one command to the command redo list.
2420    * 
2421    * @param command
2422    */
2423   public void addToRedoList(CommandI command)
2424   {
2425     if (this.redoList != null)
2426     {
2427       this.redoList.push(command);
2428     }
2429     broadcastCommand(command, true);
2430   }
2431
2432   /**
2433    * Clear the command redo list.
2434    */
2435   public void clearRedoList()
2436   {
2437     if (this.redoList != null)
2438     {
2439       this.redoList.clear();
2440     }
2441   }
2442
2443   public void setHistoryList(Deque<CommandI> list)
2444   {
2445     this.historyList = list;
2446   }
2447
2448   public Deque<CommandI> getHistoryList()
2449   {
2450     return this.historyList;
2451   }
2452
2453   public void setRedoList(Deque<CommandI> list)
2454   {
2455     this.redoList = list;
2456   }
2457
2458   public Deque<CommandI> getRedoList()
2459   {
2460     return this.redoList;
2461   }
2462
2463   @Override
2464   public VamsasSource getVamsasSource()
2465   {
2466     return this;
2467   }
2468
2469   public SequenceAnnotationOrder getSortAnnotationsBy()
2470   {
2471     return sortAnnotationsBy;
2472   }
2473
2474   public void setSortAnnotationsBy(SequenceAnnotationOrder sortAnnotationsBy)
2475   {
2476     this.sortAnnotationsBy = sortAnnotationsBy;
2477   }
2478
2479   public boolean isShowAutocalculatedAbove()
2480   {
2481     return showAutocalculatedAbove;
2482   }
2483
2484   public void setShowAutocalculatedAbove(boolean showAutocalculatedAbove)
2485   {
2486     this.showAutocalculatedAbove = showAutocalculatedAbove;
2487   }
2488
2489   @Override
2490   public boolean isScaleProteinAsCdna()
2491   {
2492     return viewStyle.isScaleProteinAsCdna();
2493   }
2494
2495   @Override
2496   public void setScaleProteinAsCdna(boolean b)
2497   {
2498     viewStyle.setScaleProteinAsCdna(b);
2499   }
2500
2501   /**
2502    * @return true if view should scroll to show the highlighted region of a
2503    *         sequence
2504    * @return
2505    */
2506   @Override
2507   public final boolean isFollowHighlight()
2508   {
2509     return followHighlight;
2510   }
2511
2512   @Override
2513   public final void setFollowHighlight(boolean b)
2514   {
2515     this.followHighlight = b;
2516   }
2517
2518   public int getStartRes()
2519   {
2520     return startRes;
2521   }
2522
2523   @Override
2524   public int getEndRes()
2525   {
2526     return endRes;
2527   }
2528
2529   public int getStartSeq()
2530   {
2531     return startSeq;
2532   }
2533
2534   public void setStartRes(int res)
2535   {
2536     this.startRes = res;
2537   }
2538
2539   public void setStartSeq(int seq)
2540   {
2541     this.startSeq = seq;
2542   }
2543
2544   public void setEndRes(int res)
2545   {
2546     if (res > alignment.getWidth() - 1)
2547     {
2548       // log.System.out.println(" Corrected res from " + res + " to maximum " +
2549       // (alignment.getWidth()-1));
2550       res = alignment.getWidth() - 1;
2551     }
2552     if (res < 0)
2553     {
2554       res = 0;
2555     }
2556     this.endRes = res;
2557   }
2558
2559   public void setEndSeq(int seq)
2560   {
2561     if (seq > alignment.getHeight())
2562     {
2563       seq = alignment.getHeight();
2564     }
2565     if (seq < 0)
2566     {
2567       seq = 0;
2568     }
2569     this.endSeq = seq;
2570   }
2571
2572   public int getEndSeq()
2573   {
2574     return endSeq;
2575   }
2576
2577   /**
2578    * Helper method to populate the SearchResults with the location in the
2579    * complementary alignment to scroll to, in order to match this one.
2580    * 
2581    * @param sr
2582    *          the SearchResults to add to
2583    * @return the offset (below top of visible region) of the matched sequence
2584    */
2585   protected int findComplementScrollTarget(SearchResults sr)
2586   {
2587     final AlignViewportI complement = getCodingComplement();
2588     if (complement == null || !complement.isFollowHighlight())
2589     {
2590       return 0;
2591     }
2592     boolean iAmProtein = !getAlignment().isNucleotide();
2593     AlignmentI proteinAlignment = iAmProtein ? getAlignment() : complement
2594             .getAlignment();
2595     if (proteinAlignment == null)
2596     {
2597       return 0;
2598     }
2599     final List<AlignedCodonFrame> mappings = proteinAlignment
2600             .getCodonFrames();
2601
2602     /*
2603      * Heuristic: find the first mapped sequence (if any) with a non-gapped
2604      * residue in the middle column of the visible region. Scroll the
2605      * complementary alignment to line up the corresponding residue.
2606      */
2607     int seqOffset = 0;
2608     SequenceI sequence = null;
2609
2610     /*
2611      * locate 'middle' column (true middle if an odd number visible, left of
2612      * middle if an even number visible)
2613      */
2614     int middleColumn = getStartRes() + (getEndRes() - getStartRes()) / 2;
2615     final HiddenSequences hiddenSequences = getAlignment()
2616             .getHiddenSequences();
2617
2618     /*
2619      * searching to the bottom of the alignment gives smoother scrolling across
2620      * all gapped visible regions
2621      */
2622     int lastSeq = alignment.getHeight() - 1;
2623     for (int seqNo = getStartSeq(); seqNo < lastSeq; seqNo++, seqOffset++)
2624     {
2625       sequence = getAlignment().getSequenceAt(seqNo);
2626       if (hiddenSequences != null && hiddenSequences.isHidden(sequence))
2627       {
2628         continue;
2629       }
2630       if (Comparison.isGap(sequence.getCharAt(middleColumn)))
2631       {
2632         continue;
2633       }
2634       List<AlignedCodonFrame> seqMappings = MappingUtils
2635               .findMappingsForSequence(sequence, mappings);
2636       if (!seqMappings.isEmpty())
2637       {
2638         break;
2639       }
2640     }
2641
2642     if (sequence == null)
2643     {
2644       /*
2645        * No ungapped mapped sequence in middle column - do nothing
2646        */
2647       return 0;
2648     }
2649     MappingUtils.addSearchResults(sr, sequence,
2650             sequence.findPosition(middleColumn), mappings);
2651     return seqOffset;
2652   }
2653 }