JAL-1691 linked scrollling in split frame (Desktop)
[jalview.git] / src / jalview / gui / AlignViewport.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 /*
22  * Jalview - A Sequence Alignment Editor and Viewer
23  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
24  *
25  * This program is free software; you can redistribute it and/or
26  * modify it under the terms of the GNU General Public License
27  * as published by the Free Software Foundation; either version 2
28  * of the License, or (at your option) any later version.
29  *
30  * This program is distributed in the hope that it will be useful,
31  * but WITHOUT ANY WARRANTY; without even the implied warranty of
32  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33  * GNU General Public License for more details.
34  *
35  * You should have received a copy of the GNU General Public License
36  * along with this program; if not, write to the Free Software
37  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
38  */
39 package jalview.gui;
40
41 import java.awt.Container;
42 import java.awt.Dimension;
43 import java.awt.Font;
44 import java.awt.Rectangle;
45 import java.util.ArrayList;
46 import java.util.Hashtable;
47 import java.util.List;
48 import java.util.Set;
49 import java.util.Vector;
50
51 import javax.swing.JInternalFrame;
52 import javax.swing.JOptionPane;
53
54 import jalview.analysis.AlignmentUtils;
55 import jalview.analysis.AnnotationSorter.SequenceAnnotationOrder;
56 import jalview.analysis.NJTree;
57 import jalview.api.AlignViewportI;
58 import jalview.api.ViewStyleI;
59 import jalview.bin.Cache;
60 import jalview.commands.CommandI;
61 import jalview.datamodel.AlignedCodonFrame;
62 import jalview.datamodel.Alignment;
63 import jalview.datamodel.AlignmentI;
64 import jalview.datamodel.ColumnSelection;
65 import jalview.datamodel.HiddenSequences;
66 import jalview.datamodel.PDBEntry;
67 import jalview.datamodel.SearchResults;
68 import jalview.datamodel.Sequence;
69 import jalview.datamodel.SequenceGroup;
70 import jalview.datamodel.SequenceI;
71 import jalview.schemes.ColourSchemeProperty;
72 import jalview.schemes.UserColourScheme;
73 import jalview.structure.CommandListener;
74 import jalview.structure.SelectionSource;
75 import jalview.structure.StructureSelectionManager;
76 import jalview.structure.VamsasSource;
77 import jalview.util.Comparison;
78 import jalview.util.MappingUtils;
79 import jalview.util.MessageManager;
80 import jalview.viewmodel.AlignmentViewport;
81 import jalview.ws.params.AutoCalcSetting;
82
83 /**
84  * DOCUMENT ME!
85  * 
86  * @author $author$
87  * @version $Revision: 1.141 $
88  */
89 public class AlignViewport extends AlignmentViewport implements
90         SelectionSource, AlignViewportI, CommandListener
91 {
92   int startRes;
93
94   int endRes;
95
96   int startSeq;
97
98   int endSeq;
99
100   Font font;
101
102   NJTree currentTree = null;
103
104   boolean cursorMode = false;
105
106   boolean antiAlias = false;
107
108   private Rectangle explodedGeometry;
109
110   String viewName;
111
112   /*
113    * Flag set true on the view that should 'gather' multiple views of the same
114    * sequence set id when a project is reloaded. Set false on all views when
115    * they are 'exploded' into separate windows. Set true on the current view
116    * when 'Gather' is performed, and also on the first tab when the first new
117    * view is created.
118    */
119   private boolean gatherViewsHere = false;
120
121   private AnnotationColumnChooser annotationColumnSelectionState;
122   /**
123    * Creates a new AlignViewport object.
124    * 
125    * @param al
126    *          alignment to view
127    */
128   public AlignViewport(AlignmentI al)
129   {
130     setAlignment(al);
131     init();
132   }
133
134   /**
135    * Create a new AlignViewport object with a specific sequence set ID
136    * 
137    * @param al
138    * @param seqsetid
139    *          (may be null - but potential for ambiguous constructor exception)
140    */
141   public AlignViewport(AlignmentI al, String seqsetid)
142   {
143     this(al, seqsetid, null);
144   }
145
146   public AlignViewport(AlignmentI al, String seqsetid, String viewid)
147   {
148     sequenceSetID = seqsetid;
149     viewId = viewid;
150     // TODO remove these once 2.4.VAMSAS release finished
151     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
152     {
153       Cache.log.debug("Setting viewport's sequence set id : "
154               + sequenceSetID);
155     }
156     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
157     {
158       Cache.log.debug("Setting viewport's view id : " + viewId);
159     }
160     setAlignment(al);
161     init();
162   }
163
164   /**
165    * Create a new AlignViewport with hidden regions
166    * 
167    * @param al
168    *          AlignmentI
169    * @param hiddenColumns
170    *          ColumnSelection
171    */
172   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns)
173   {
174     setAlignment(al);
175     if (hiddenColumns != null)
176     {
177       colSel = hiddenColumns;
178     }
179     init();
180   }
181
182   /**
183    * New viewport with hidden columns and an existing sequence set id
184    * 
185    * @param al
186    * @param hiddenColumns
187    * @param seqsetid
188    *          (may be null)
189    */
190   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns,
191           String seqsetid)
192   {
193     this(al, hiddenColumns, seqsetid, null);
194   }
195
196   /**
197    * New viewport with hidden columns and an existing sequence set id and viewid
198    * 
199    * @param al
200    * @param hiddenColumns
201    * @param seqsetid
202    *          (may be null)
203    * @param viewid
204    *          (may be null)
205    */
206   public AlignViewport(AlignmentI al, ColumnSelection hiddenColumns,
207           String seqsetid, String viewid)
208   {
209     sequenceSetID = seqsetid;
210     viewId = viewid;
211     // TODO remove these once 2.4.VAMSAS release finished
212     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
213     {
214       Cache.log.debug("Setting viewport's sequence set id : "
215               + sequenceSetID);
216     }
217     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
218     {
219       Cache.log.debug("Setting viewport's view id : " + viewId);
220     }
221     setAlignment(al);
222     if (hiddenColumns != null)
223     {
224       colSel = hiddenColumns;
225     }
226     init();
227   }
228
229   /**
230    * Apply any settings saved in user preferences
231    */
232   private void applyViewProperties()
233   {
234     antiAlias = Cache.getDefault("ANTI_ALIAS", false);
235
236     viewStyle.setShowJVSuffix(Cache.getDefault("SHOW_JVSUFFIX", true));
237     setShowAnnotation(Cache.getDefault("SHOW_ANNOTATIONS", true));
238
239     setRightAlignIds(Cache.getDefault("RIGHT_ALIGN_IDS", false));
240     setCentreColumnLabels(Cache.getDefault("CENTRE_COLUMN_LABELS", false));
241     autoCalculateConsensus = Cache.getDefault("AUTO_CALC_CONSENSUS", true);
242
243     setPadGaps(Cache.getDefault("PAD_GAPS", true));
244     setShowNPFeats(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
245     setShowDBRefs(Cache.getDefault("SHOW_DBREFS_TOOLTIP", true));
246     viewStyle.setSeqNameItalics(Cache.getDefault("ID_ITALICS", true));
247     viewStyle.setWrapAlignment(Cache.getDefault("WRAP_ALIGNMENT", false));
248     viewStyle.setShowUnconserved(Cache
249             .getDefault("SHOW_UNCONSERVED", false));
250     sortByTree = Cache.getDefault("SORT_BY_TREE", false);
251     followSelection = Cache.getDefault("FOLLOW_SELECTIONS", true);
252     sortAnnotationsBy = SequenceAnnotationOrder.valueOf(Cache.getDefault(
253             Preferences.SORT_ANNOTATIONS,
254             SequenceAnnotationOrder.NONE.name()));
255     showAutocalculatedAbove = Cache.getDefault(
256             Preferences.SHOW_AUTOCALC_ABOVE, false);
257     viewStyle.setScaleProteinAsCdna(Cache.getDefault(
258             Preferences.SCALE_PROTEIN_TO_CDNA, false));
259   }
260
261   void init()
262   {
263     this.startRes = 0;
264     this.endRes = alignment.getWidth() - 1;
265     this.startSeq = 0;
266     this.endSeq = alignment.getHeight() - 1;
267     applyViewProperties();
268
269     String fontName = Cache.getDefault("FONT_NAME", "SansSerif");
270     String fontStyle = Cache.getDefault("FONT_STYLE", Font.PLAIN + "");
271     String fontSize = Cache.getDefault("FONT_SIZE", "10");
272
273     int style = 0;
274
275     if (fontStyle.equals("bold"))
276     {
277       style = 1;
278     }
279     else if (fontStyle.equals("italic"))
280     {
281       style = 2;
282     }
283
284     setFont(new Font(fontName, style, Integer.parseInt(fontSize)), true);
285
286     alignment
287             .setGapCharacter(Cache.getDefault("GAP_SYMBOL", "-").charAt(0));
288
289     // We must set conservation and consensus before setting colour,
290     // as Blosum and Clustal require this to be done
291     if (hconsensus == null && !isDataset)
292     {
293       if (!alignment.isNucleotide())
294       {
295         showConservation = Cache.getDefault("SHOW_CONSERVATION", true);
296         showQuality = Cache.getDefault("SHOW_QUALITY", true);
297         showGroupConservation = Cache.getDefault("SHOW_GROUP_CONSERVATION",
298                 false);
299       }
300       showConsensusHistogram = Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM",
301               true);
302       showSequenceLogo = Cache.getDefault("SHOW_CONSENSUS_LOGO", false);
303       normaliseSequenceLogo = Cache.getDefault("NORMALISE_CONSENSUS_LOGO",
304               false);
305       showGroupConsensus = Cache.getDefault("SHOW_GROUP_CONSENSUS", false);
306       showConsensus = Cache.getDefault("SHOW_IDENTITY", true);
307     }
308     initAutoAnnotation();
309     String colourProperty = alignment.isNucleotide() ? Preferences.DEFAULT_COLOUR_NUC
310             : Preferences.DEFAULT_COLOUR_PROT;
311     String propertyValue = Cache.getProperty(colourProperty);
312     if (propertyValue == null)
313     {
314       // fall back on this property for backwards compatibility
315       propertyValue = Cache.getProperty(Preferences.DEFAULT_COLOUR);
316     }
317     if (propertyValue != null)
318     {
319       globalColourScheme = ColourSchemeProperty.getColour(alignment,
320               propertyValue);
321
322       if (globalColourScheme instanceof UserColourScheme)
323       {
324         globalColourScheme = UserDefinedColours.loadDefaultColours();
325         ((UserColourScheme) globalColourScheme).setThreshold(0,
326                 isIgnoreGapsConsensus());
327       }
328
329       if (globalColourScheme != null)
330       {
331         globalColourScheme.setConsensus(hconsensus);
332       }
333     }
334   }
335
336   /**
337    * get the consensus sequence as displayed under the PID consensus annotation
338    * row.
339    * 
340    * @return consensus sequence as a new sequence object
341    */
342   public SequenceI getConsensusSeq()
343   {
344     if (consensus == null)
345     {
346       updateConsensus(null);
347     }
348     if (consensus == null)
349     {
350       return null;
351     }
352     StringBuffer seqs = new StringBuffer();
353     for (int i = 0; i < consensus.annotations.length; i++)
354     {
355       if (consensus.annotations[i] != null)
356       {
357         if (consensus.annotations[i].description.charAt(0) == '[')
358         {
359           seqs.append(consensus.annotations[i].description.charAt(1));
360         }
361         else
362         {
363           seqs.append(consensus.annotations[i].displayCharacter);
364         }
365       }
366     }
367
368     SequenceI sq = new Sequence("Consensus", seqs.toString());
369     sq.setDescription("Percentage Identity Consensus "
370             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
371     return sq;
372   }
373
374   /**
375    * DOCUMENT ME!
376    * 
377    * @return DOCUMENT ME!
378    */
379   public int getStartRes()
380   {
381     return startRes;
382   }
383
384   /**
385    * DOCUMENT ME!
386    * 
387    * @return DOCUMENT ME!
388    */
389   public int getEndRes()
390   {
391     return endRes;
392   }
393
394   /**
395    * DOCUMENT ME!
396    * 
397    * @return DOCUMENT ME!
398    */
399   public int getStartSeq()
400   {
401     return startSeq;
402   }
403
404   /**
405    * DOCUMENT ME!
406    * 
407    * @param res
408    *          DOCUMENT ME!
409    */
410   public void setStartRes(int res)
411   {
412     this.startRes = res;
413   }
414
415   /**
416    * DOCUMENT ME!
417    * 
418    * @param seq
419    *          DOCUMENT ME!
420    */
421   public void setStartSeq(int seq)
422   {
423     this.startSeq = seq;
424   }
425
426   /**
427    * DOCUMENT ME!
428    * 
429    * @param res
430    *          DOCUMENT ME!
431    */
432   public void setEndRes(int res)
433   {
434     if (res > (alignment.getWidth() - 1))
435     {
436       // log.System.out.println(" Corrected res from " + res + " to maximum " +
437       // (alignment.getWidth()-1));
438       res = alignment.getWidth() - 1;
439     }
440
441     if (res < 0)
442     {
443       res = 0;
444     }
445
446     this.endRes = res;
447   }
448
449   /**
450    * DOCUMENT ME!
451    * 
452    * @param seq
453    *          DOCUMENT ME!
454    */
455   public void setEndSeq(int seq)
456   {
457     if (seq > alignment.getHeight())
458     {
459       seq = alignment.getHeight();
460     }
461
462     if (seq < 0)
463     {
464       seq = 0;
465     }
466
467     this.endSeq = seq;
468   }
469
470   /**
471    * DOCUMENT ME!
472    * 
473    * @return DOCUMENT ME!
474    */
475   public int getEndSeq()
476   {
477     return endSeq;
478   }
479
480   boolean validCharWidth;
481
482   /**
483    * update view settings with the given font. You may need to call
484    * alignPanel.fontChanged to update the layout geometry
485    * 
486    * @param setGrid
487    *          when true, charWidth/height is set according to font mentrics
488    */
489   public void setFont(Font f, boolean setGrid)
490   {
491     font = f;
492
493     Container c = new Container();
494
495     java.awt.FontMetrics fm = c.getFontMetrics(font);
496     int w = viewStyle.getCharWidth(), ww = fm.charWidth('M'), h = viewStyle
497             .getCharHeight();
498     if (setGrid)
499     {
500       setCharHeight(fm.getHeight());
501       setCharWidth(ww);
502     }
503     viewStyle.setFontName(font.getName());
504     viewStyle.setFontStyle(font.getStyle());
505     viewStyle.setFontSize(font.getSize());
506
507     validCharWidth = true;
508   }
509
510   @Override
511   public void setViewStyle(ViewStyleI settingsForView)
512   {
513     super.setViewStyle(settingsForView);
514     setFont(new Font(viewStyle.getFontName(), viewStyle.getFontStyle(),
515             viewStyle.getFontSize()), false);
516
517   }
518   /**
519    * DOCUMENT ME!
520    * 
521    * @return DOCUMENT ME!
522    */
523   public Font getFont()
524   {
525     return font;
526   }
527
528   /**
529    * DOCUMENT ME!
530    * 
531    * @param align
532    *          DOCUMENT ME!
533    */
534   public void setAlignment(AlignmentI align)
535   {
536     if (alignment != null && alignment.getCodonFrames() != null)
537     {
538       StructureSelectionManager.getStructureSelectionManager(
539               Desktop.instance).removeMappings(alignment.getCodonFrames());
540     }
541     this.alignment = align;
542     if (alignment != null && alignment.getCodonFrames() != null)
543     {
544       StructureSelectionManager.getStructureSelectionManager(
545               Desktop.instance).addMappings(alignment.getCodonFrames());
546     }
547   }
548
549   /**
550    * DOCUMENT ME!
551    * 
552    * @return DOCUMENT ME!
553    */
554   public char getGapCharacter()
555   {
556     return getAlignment().getGapCharacter();
557   }
558
559   /**
560    * DOCUMENT ME!
561    * 
562    * @param gap
563    *          DOCUMENT ME!
564    */
565   public void setGapCharacter(char gap)
566   {
567     if (getAlignment() != null)
568     {
569       getAlignment().setGapCharacter(gap);
570     }
571   }
572
573   /**
574    * DOCUMENT ME!
575    * 
576    * @return DOCUMENT ME!
577    */
578   public ColumnSelection getColumnSelection()
579   {
580     return colSel;
581   }
582
583   /**
584    * DOCUMENT ME!
585    * 
586    * @param tree
587    *          DOCUMENT ME!
588    */
589   public void setCurrentTree(NJTree tree)
590   {
591     currentTree = tree;
592   }
593
594   /**
595    * DOCUMENT ME!
596    * 
597    * @return DOCUMENT ME!
598    */
599   public NJTree getCurrentTree()
600   {
601     return currentTree;
602   }
603
604   /**
605    * returns the visible column regions of the alignment
606    * 
607    * @param selectedRegionOnly
608    *          true to just return the contigs intersecting with the selected
609    *          area
610    * @return
611    */
612   public int[] getViewAsVisibleContigs(boolean selectedRegionOnly)
613   {
614     int[] viscontigs = null;
615     int start = 0, end = 0;
616     if (selectedRegionOnly && selectionGroup != null)
617     {
618       start = selectionGroup.getStartRes();
619       end = selectionGroup.getEndRes() + 1;
620     }
621     else
622     {
623       end = alignment.getWidth();
624     }
625     viscontigs = colSel.getVisibleContigs(start, end);
626     return viscontigs;
627   }
628
629   /**
630    * get hash of undo and redo list for the alignment
631    * 
632    * @return long[] { historyList.hashCode, redoList.hashCode };
633    */
634   public long[] getUndoRedoHash()
635   {
636     // TODO: JAL-1126
637     if (historyList == null || redoList == null)
638     {
639       return new long[]
640       { -1, -1 };
641     }
642     return new long[]
643     { historyList.hashCode(), this.redoList.hashCode() };
644   }
645
646   /**
647    * test if a particular set of hashcodes are different to the hashcodes for
648    * the undo and redo list.
649    * 
650    * @param undoredo
651    *          the stored set of hashcodes as returned by getUndoRedoHash
652    * @return true if the hashcodes differ (ie the alignment has been edited) or
653    *         the stored hashcode array differs in size
654    */
655   public boolean isUndoRedoHashModified(long[] undoredo)
656   {
657     if (undoredo == null)
658     {
659       return true;
660     }
661     long[] cstate = getUndoRedoHash();
662     if (cstate.length != undoredo.length)
663     {
664       return true;
665     }
666
667     for (int i = 0; i < cstate.length; i++)
668     {
669       if (cstate[i] != undoredo[i])
670       {
671         return true;
672       }
673     }
674     return false;
675   }
676
677   /**
678    * when set, view will scroll to show the highlighted position
679    */
680   public boolean followHighlight = true;
681
682   /**
683    * @return true if view should scroll to show the highlighted region of a
684    *         sequence
685    * @return
686    */
687   public boolean getFollowHighlight()
688   {
689     return followHighlight;
690   }
691
692   public boolean followSelection = true;
693
694   /**
695    * @return true if view selection should always follow the selections
696    *         broadcast by other selection sources
697    */
698   public boolean getFollowSelection()
699   {
700     return followSelection;
701   }
702
703   /**
704    * Send the current selection to be broadcast to any selection listeners.
705    */
706   public void sendSelection()
707   {
708     jalview.structure.StructureSelectionManager
709             .getStructureSelectionManager(Desktop.instance).sendSelection(
710                     new SequenceGroup(getSelectionGroup()),
711                     new ColumnSelection(getColumnSelection()), this);
712   }
713
714   /**
715    * return the alignPanel containing the given viewport. Use this to get the
716    * components currently handling the given viewport.
717    * 
718    * @param av
719    * @return null or an alignPanel guaranteed to have non-null alignFrame
720    *         reference
721    */
722   public AlignmentPanel getAlignPanel()
723   {
724     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(this
725             .getSequenceSetId());
726     for (int p = 0; aps != null && p < aps.length; p++)
727     {
728       if (aps[p].av == this)
729       {
730         return aps[p];
731       }
732     }
733     return null;
734   }
735
736   public boolean getSortByTree()
737   {
738     return sortByTree;
739   }
740
741   public void setSortByTree(boolean sort)
742   {
743     sortByTree = sort;
744   }
745
746   /**
747    * synthesize a column selection if none exists so it covers the given
748    * selection group. if wholewidth is false, no column selection is made if the
749    * selection group covers the whole alignment width.
750    * 
751    * @param sg
752    * @param wholewidth
753    */
754   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
755   {
756     int sgs, sge;
757     if (sg != null
758             && (sgs = sg.getStartRes()) >= 0
759             && sg.getStartRes() <= (sge = sg.getEndRes())
760             && (colSel == null || colSel.getSelected() == null || colSel
761                     .getSelected().size() == 0))
762     {
763       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
764       {
765         // do nothing
766         return;
767       }
768       if (colSel == null)
769       {
770         colSel = new ColumnSelection();
771       }
772       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
773       {
774         colSel.addElement(cspos);
775       }
776     }
777   }
778
779   /**
780    * Returns the (Desktop) instance of the StructureSelectionManager
781    */
782   @Override
783   public StructureSelectionManager getStructureSelectionManager()
784   {
785     return StructureSelectionManager
786             .getStructureSelectionManager(Desktop.instance);
787   }
788
789   /**
790    * 
791    * @param pdbEntries
792    * @return a series of SequenceI arrays, one for each PDBEntry, listing which
793    *         sequence in the alignment holds a reference to it
794    */
795   public SequenceI[][] collateForPDB(PDBEntry[] pdbEntries)
796   {
797     ArrayList<SequenceI[]> seqvectors = new ArrayList<SequenceI[]>();
798     for (PDBEntry pdb : pdbEntries)
799     {
800       ArrayList<SequenceI> seqs = new ArrayList<SequenceI>();
801       for (int i = 0; i < alignment.getHeight(); i++)
802       {
803         Vector pdbs = alignment.getSequenceAt(i).getDatasetSequence()
804                 .getPDBId();
805         if (pdbs == null)
806         {
807           continue;
808         }
809         SequenceI sq;
810         for (int p = 0; p < pdbs.size(); p++)
811         {
812           PDBEntry p1 = (PDBEntry) pdbs.elementAt(p);
813           if (p1.getId().equals(pdb.getId()))
814           {
815             if (!seqs.contains(sq = alignment.getSequenceAt(i)))
816             {
817               seqs.add(sq);
818             }
819
820             continue;
821           }
822         }
823       }
824       seqvectors.add(seqs.toArray(new SequenceI[seqs.size()]));
825     }
826     return seqvectors.toArray(new SequenceI[seqvectors.size()][]);
827   }
828
829   public boolean isNormaliseSequenceLogo()
830   {
831     return normaliseSequenceLogo;
832   }
833
834   public void setNormaliseSequenceLogo(boolean state)
835   {
836     normaliseSequenceLogo = state;
837   }
838
839   /**
840    * 
841    * @return true if alignment characters should be displayed
842    */
843   public boolean isValidCharWidth()
844   {
845     return validCharWidth;
846   }
847
848   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<String, AutoCalcSetting>();
849
850   public AutoCalcSetting getCalcIdSettingsFor(String calcId)
851   {
852     return calcIdParams.get(calcId);
853   }
854
855   public void setCalcIdSettingsFor(String calcId, AutoCalcSetting settings,
856           boolean needsUpdate)
857   {
858     calcIdParams.put(calcId, settings);
859     // TODO: create a restart list to trigger any calculations that need to be
860     // restarted after load
861     // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
862     if (needsUpdate)
863     {
864       Cache.log.debug("trigger update for " + calcId);
865     }
866   }
867
868   /**
869    * Method called when another alignment's edit (or possibly other) command is
870    * broadcast to here.
871    *
872    * To allow for sequence mappings (e.g. protein to cDNA), we have to first
873    * 'unwind' the command on the source sequences (in simulation, not in fact),
874    * and then for each edit in turn:
875    * <ul>
876    * <li>compute the equivalent edit on the mapped sequences</li>
877    * <li>apply the mapped edit</li>
878    * <li>'apply' the source edit to the working copy of the source sequences</li>
879    * </ul>
880    * 
881    * @param command
882    * @param undo
883    * @param ssm
884    */
885   @Override
886   public void mirrorCommand(CommandI command, boolean undo,
887           StructureSelectionManager ssm, VamsasSource source)
888   {
889     /*
890      * Do nothing unless we are a 'complement' of the source. May replace this
891      * with direct calls not via SSM.
892      */
893     if (source instanceof AlignViewportI
894             && ((AlignViewportI) source).getCodingComplement() == this)
895     {
896       // ok to continue;
897     }
898     else
899     {
900       return;
901     }
902
903     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
904             getGapCharacter());
905     if (mappedCommand != null)
906     {
907       AlignmentI[] views = getAlignPanel().alignFrame.getViewAlignments();
908       mappedCommand.doCommand(views);
909       getAlignPanel().alignmentChanged();
910     }
911   }
912
913   /**
914    * Add the sequences from the given alignment to this viewport. Optionally,
915    * may give the user the option to open a new frame, or split panel, with cDNA
916    * and protein linked.
917    * 
918    * @param al
919    * @param title
920    */
921   public void addAlignment(AlignmentI al, String title)
922   {
923     // TODO: promote to AlignViewportI? applet CutAndPasteTransfer is different
924
925     // JBPComment: title is a largely redundant parameter at the moment
926     // JBPComment: this really should be an 'insert/pre/append' controller
927     // JBPComment: but the DNA/Protein check makes it a bit more complex
928
929     // refactored from FileLoader / CutAndPasteTransfer / SequenceFetcher with
930     // this comment:
931     // TODO: create undo object for this JAL-1101
932
933     /*
934      * If one alignment is protein and one nucleotide, with at least one
935      * sequence name in common, offer to open a linked alignment.
936      */
937     if (AlignmentUtils.isMappable(al, getAlignment()))
938     {
939       if (openLinkedAlignment(al, title))
940       {
941         return;
942       }
943     }
944     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
945     // provenance) should share the same dataset sequence
946
947     for (int i = 0; i < al.getHeight(); i++)
948     {
949       getAlignment().addSequence(al.getSequenceAt(i));
950     }
951     // TODO this call was done by SequenceFetcher but not FileLoader or
952     // CutAndPasteTransfer. Is it needed?
953     // JBPComment: this repositions the view to show the new sequences
954     // JBPComment: so it is needed for UX
955     setEndSeq(getAlignment().getHeight());
956     firePropertyChange("alignment", null, getAlignment().getSequences());
957   }
958
959   /**
960    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
961    * alignment. Returns true if the new alignment was opened, false if not,
962    * because the user declined the offer.
963    * 
964    * @param title
965    */
966   protected boolean openLinkedAlignment(AlignmentI al, String title)
967   {
968     String[] options = new String[]
969     { MessageManager.getString("action.no"),
970         MessageManager.getString("label.split_window"),
971         MessageManager.getString("label.new_window"), };
972     final String question = JvSwingUtils.wrapTooltip(true,
973             MessageManager.getString("label.open_split_window?"));
974     int response = JOptionPane.showOptionDialog(Desktop.desktop, question,
975             MessageManager.getString("label.open_split_window"),
976             JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
977             options, options[0]);
978
979     if (response != 1 && response != 2)
980     {
981       return false;
982     }
983     final boolean openSplitPane = (response == 1);
984     final boolean openInNewWindow = (response == 2);
985
986     /*
987      * Create the AlignFrame first (which creates the new alignment's datasets),
988      * before attempting sequence mapping.
989      */
990     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
991             AlignFrame.DEFAULT_HEIGHT);
992     newAlignFrame.setTitle(title);
993
994     /*
995      * Identify protein and dna alignments. Make a copy of this one if opening
996      * in a new split pane.
997      */
998     AlignmentI thisAlignment = openSplitPane ? new Alignment(getAlignment())
999             : getAlignment();
1000     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
1001     final AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
1002
1003     newAlignFrame.statusBar.setText(MessageManager.formatMessage(
1004             "label.successfully_loaded_file", new Object[]
1005             { title }));
1006
1007     // TODO if we want this (e.g. to enable reload of the alignment from file),
1008     // we will need to add parameters to the stack.
1009     // if (!protocol.equals(AppletFormatAdapter.PASTE))
1010     // {
1011     // alignFrame.setFileName(file, format);
1012     // }
1013
1014     if (openInNewWindow)
1015     {
1016       Desktop.addInternalFrame(newAlignFrame, title,
1017               AlignFrame.DEFAULT_WIDTH,
1018               AlignFrame.DEFAULT_HEIGHT);
1019     }
1020
1021     /*
1022      * Map sequences. At least one should get mapped as we have already passed
1023      * the test for 'mappability'. Any mappings made will be added to the
1024      * protein alignment.
1025      */
1026     AlignmentUtils.mapProteinToCdna(protein, cdna);
1027
1028     try
1029     {
1030       newAlignFrame.setMaximum(jalview.bin.Cache.getDefault(
1031               "SHOW_FULLSCREEN",
1032               false));
1033     } catch (java.beans.PropertyVetoException ex)
1034     {
1035     }
1036
1037     if (openSplitPane)
1038     {
1039       protein = openSplitFrame(newAlignFrame, thisAlignment,
1040               protein.getCodonFrames());
1041     }
1042
1043     /*
1044      * Register the mappings (held on the protein alignment) with the
1045      * StructureSelectionManager (for mouseover linking).
1046      */
1047     final StructureSelectionManager ssm = StructureSelectionManager
1048             .getStructureSelectionManager(Desktop.instance);
1049     ssm.addMappings(protein.getCodonFrames());
1050
1051     return true;
1052   }
1053
1054   /**
1055    * Helper method to open a new SplitFrame holding linked dna and protein
1056    * alignments.
1057    * 
1058    * @param newAlignFrame
1059    *          containing a new alignment to be shown
1060    * @param complement
1061    *          cdna/protein complement alignment to show in the other split half
1062    * @param mappings
1063    * @return the protein alignment in the split frame
1064    */
1065   protected AlignmentI openSplitFrame(AlignFrame newAlignFrame,
1066           AlignmentI complement, Set<AlignedCodonFrame> mappings)
1067   {
1068     /*
1069      * Open in split pane. DNA sequence above, protein below.
1070      */
1071     AlignFrame copyMe = new AlignFrame(complement,
1072             AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
1073     copyMe.setTitle(getAlignPanel().alignFrame.getTitle());
1074
1075     AlignmentI al = newAlignFrame.viewport.getAlignment();
1076     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
1077             : newAlignFrame;
1078     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame
1079             : copyMe;
1080     AlignmentI protein = proteinFrame.viewport.getAlignment();
1081     protein.setCodonFrames(mappings);
1082
1083     cdnaFrame.setVisible(true);
1084     proteinFrame.setVisible(true);
1085     String linkedTitle = MessageManager
1086             .getString("label.linked_view_title");
1087     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
1088     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
1089
1090     return protein;
1091   }
1092
1093   public AnnotationColumnChooser getAnnotationColumnSelectionState()
1094   {
1095     return annotationColumnSelectionState;
1096   }
1097
1098   public void setAnnotationColumnSelectionState(
1099           AnnotationColumnChooser currentAnnotationColumnSelectionState)
1100   {
1101     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
1102   }
1103
1104   @Override
1105   public void setIdWidth(int i)
1106   {
1107     super.setIdWidth(i);
1108     AlignmentPanel ap = getAlignPanel();
1109     if (ap != null)
1110     {
1111       // modify GUI elements to reflect geometry change
1112       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
1113               .getPreferredSize();
1114       idw.width = i;
1115       getAlignPanel().getIdPanel().getIdCanvas().setPreferredSize(idw);
1116     }
1117   }
1118
1119   public Rectangle getExplodedGeometry()
1120   {
1121     return explodedGeometry;
1122   }
1123
1124   public void setExplodedGeometry(Rectangle explodedPosition)
1125   {
1126     this.explodedGeometry = explodedPosition;
1127   }
1128
1129   public boolean isGatherViewsHere()
1130   {
1131     return gatherViewsHere;
1132   }
1133
1134   public void setGatherViewsHere(boolean gatherViewsHere)
1135   {
1136     this.gatherViewsHere = gatherViewsHere;
1137   }
1138
1139   /**
1140    * If this viewport has a (Protein/cDNA) complement, then scroll the
1141    * complementary alignment to match this one.
1142    * 
1143    * @param horizontal
1144    *          true for horizontal scroll event, false for vertical
1145    */
1146   public void scrollComplementaryAlignment(boolean horizontal)
1147   {
1148     /*
1149      * If no complement, or it is not following scrolling, do nothing.
1150      */
1151     // TODO pull up followHighlight to AlignmentViewport/AlignViewportI
1152     final AlignViewport codingComplement = (AlignViewport) getCodingComplement();
1153     if (codingComplement == null || !codingComplement.followHighlight)
1154     {
1155       return;
1156     }
1157     boolean iAmProtein = !getAlignment().isNucleotide();
1158     AlignmentI proteinAlignment = iAmProtein ? getAlignment()
1159             : codingComplement.getAlignment();
1160     if (proteinAlignment == null)
1161     {
1162       return;
1163     }
1164     final Set<AlignedCodonFrame> mappings = proteinAlignment
1165             .getCodonFrames();
1166
1167     /*
1168      * Heuristic: find the first mapped sequence (if any) with a non-gapped
1169      * residue in the middle column of the visible region. Scroll the
1170      * complementary alignment to line up the corresponding residue.
1171      */
1172     int seqOffset = 0;
1173     SequenceI sequence = null;
1174     int middleColumn = getStartRes() + (getEndRes() - getStartRes()) / 2;
1175     final HiddenSequences hiddenSequences = getAlignment()
1176             .getHiddenSequences();
1177     for (int seqNo = getStartSeq(); seqNo < getEndSeq(); seqNo++, seqOffset++)
1178     {
1179       sequence = getAlignment().getSequenceAt(seqNo);
1180       if (hiddenSequences != null && hiddenSequences.isHidden(sequence))
1181       {
1182         continue;
1183       }
1184       if (Comparison.isGap(sequence.getCharAt(middleColumn)))
1185       {
1186         continue;
1187       }
1188       List<AlignedCodonFrame> seqMappings = MappingUtils
1189               .findMappingsForSequence(sequence, mappings);
1190       if (!seqMappings.isEmpty())
1191       {
1192         break;
1193       }
1194     }
1195
1196     if (sequence == null)
1197     {
1198       /*
1199        * No ungapped mapped sequence in middle column - do nothing
1200        */
1201       return;
1202     }
1203     SearchResults sr = MappingUtils.buildSearchResults(sequence,
1204             sequence.findPosition(middleColumn), mappings);
1205     codingComplement.getAlignPanel().scrollAsComplement(sr, seqOffset,
1206             horizontal);
1207   }
1208 }