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