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