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