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