JAL-1934 new preference to disable gap character normalisation when a new alignment...
[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     if (Cache.getDefault("NORMALISE_GAPS", true))
278     {
279       alignment.setGapCharacter(Cache.getDefault("GAP_SYMBOL", "-").charAt(
280               0));
281     }
282     // We must set conservation and consensus before setting colour,
283     // as Blosum and Clustal require this to be done
284     if (hconsensus == null && !isDataset)
285     {
286       if (!alignment.isNucleotide())
287       {
288         showConservation = Cache.getDefault("SHOW_CONSERVATION", true);
289         showQuality = Cache.getDefault("SHOW_QUALITY", true);
290         showGroupConservation = Cache.getDefault("SHOW_GROUP_CONSERVATION",
291                 false);
292       }
293       showConsensusHistogram = Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM",
294               true);
295       showSequenceLogo = Cache.getDefault("SHOW_CONSENSUS_LOGO", false);
296       normaliseSequenceLogo = Cache.getDefault("NORMALISE_CONSENSUS_LOGO",
297               false);
298       showGroupConsensus = Cache.getDefault("SHOW_GROUP_CONSENSUS", false);
299       showConsensus = Cache.getDefault("SHOW_IDENTITY", true);
300     }
301     initAutoAnnotation();
302     String colourProperty = alignment.isNucleotide() ? Preferences.DEFAULT_COLOUR_NUC
303             : Preferences.DEFAULT_COLOUR_PROT;
304     String propertyValue = Cache.getProperty(colourProperty);
305     if (propertyValue == null)
306     {
307       // fall back on this property for backwards compatibility
308       propertyValue = Cache.getProperty(Preferences.DEFAULT_COLOUR);
309     }
310     if (propertyValue != null)
311     {
312       globalColourScheme = ColourSchemeProperty.getColour(alignment,
313               propertyValue);
314
315       if (globalColourScheme instanceof UserColourScheme)
316       {
317         globalColourScheme = UserDefinedColours.loadDefaultColours();
318         ((UserColourScheme) globalColourScheme).setThreshold(0,
319                 isIgnoreGapsConsensus());
320       }
321
322       if (globalColourScheme != null)
323       {
324         globalColourScheme.setConsensus(hconsensus);
325       }
326     }
327   }
328
329   /**
330    * get the consensus sequence as displayed under the PID consensus annotation
331    * row.
332    * 
333    * @return consensus sequence as a new sequence object
334    */
335   public SequenceI getConsensusSeq()
336   {
337     if (consensus == null)
338     {
339       updateConsensus(null);
340     }
341     if (consensus == null)
342     {
343       return null;
344     }
345     StringBuffer seqs = new StringBuffer();
346     for (int i = 0; i < consensus.annotations.length; i++)
347     {
348       if (consensus.annotations[i] != null)
349       {
350         if (consensus.annotations[i].description.charAt(0) == '[')
351         {
352           seqs.append(consensus.annotations[i].description.charAt(1));
353         }
354         else
355         {
356           seqs.append(consensus.annotations[i].displayCharacter);
357         }
358       }
359     }
360
361     SequenceI sq = new Sequence("Consensus", seqs.toString());
362     sq.setDescription("Percentage Identity Consensus "
363             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
364     return sq;
365   }
366
367   boolean validCharWidth;
368
369   /**
370    * update view settings with the given font. You may need to call
371    * alignPanel.fontChanged to update the layout geometry
372    * 
373    * @param setGrid
374    *          when true, charWidth/height is set according to font mentrics
375    */
376   public void setFont(Font f, boolean setGrid)
377   {
378     font = f;
379
380     Container c = new Container();
381
382     java.awt.FontMetrics fm = c.getFontMetrics(font);
383     int w = viewStyle.getCharWidth(), ww = fm.charWidth('M'), h = viewStyle
384             .getCharHeight();
385     if (setGrid)
386     {
387       setCharHeight(fm.getHeight());
388       setCharWidth(ww);
389     }
390     viewStyle.setFontName(font.getName());
391     viewStyle.setFontStyle(font.getStyle());
392     viewStyle.setFontSize(font.getSize());
393
394     validCharWidth = true;
395   }
396
397   @Override
398   public void setViewStyle(ViewStyleI settingsForView)
399   {
400     super.setViewStyle(settingsForView);
401     setFont(new Font(viewStyle.getFontName(), viewStyle.getFontStyle(),
402             viewStyle.getFontSize()), false);
403
404   }
405
406   /**
407    * DOCUMENT ME!
408    * 
409    * @return DOCUMENT ME!
410    */
411   public Font getFont()
412   {
413     return font;
414   }
415
416   /**
417    * DOCUMENT ME!
418    * 
419    * @param align
420    *          DOCUMENT ME!
421    */
422   public void setAlignment(AlignmentI align)
423   {
424     replaceMappings(align);
425     this.alignment = align;
426   }
427
428   /**
429    * Replace any codon mappings for this viewport with those for the given
430    * viewport
431    * 
432    * @param align
433    */
434   public void replaceMappings(AlignmentI align)
435   {
436
437     /*
438      * Deregister current mappings (if any)
439      */
440     deregisterMappings();
441
442     /*
443      * Register new mappings (if any)
444      */
445     if (align != null)
446     {
447       StructureSelectionManager ssm = StructureSelectionManager
448               .getStructureSelectionManager(Desktop.instance);
449       ssm.registerMappings(align.getCodonFrames());
450     }
451
452     /*
453      * replace mappings on our alignment
454      */
455     if (alignment != null && align != null)
456     {
457       alignment.setCodonFrames(align.getCodonFrames());
458     }
459   }
460
461   protected void deregisterMappings()
462   {
463     AlignmentI al = getAlignment();
464     if (al != null)
465     {
466       Set<AlignedCodonFrame> mappings = al.getCodonFrames();
467       if (mappings != null)
468       {
469         StructureSelectionManager ssm = StructureSelectionManager
470                 .getStructureSelectionManager(Desktop.instance);
471         for (AlignedCodonFrame acf : mappings)
472         {
473           if (noReferencesTo(acf))
474           {
475             ssm.deregisterMapping(acf);
476           }
477         }
478       }
479     }
480   }
481
482   /**
483    * DOCUMENT ME!
484    * 
485    * @return DOCUMENT ME!
486    */
487   @Override
488   public char getGapCharacter()
489   {
490     return getAlignment().getGapCharacter();
491   }
492
493   /**
494    * DOCUMENT ME!
495    * 
496    * @param gap
497    *          DOCUMENT ME!
498    */
499   public void setGapCharacter(char gap)
500   {
501     if (getAlignment() != null)
502     {
503       getAlignment().setGapCharacter(gap);
504     }
505   }
506
507   /**
508    * DOCUMENT ME!
509    * 
510    * @return DOCUMENT ME!
511    */
512   @Override
513   public ColumnSelection getColumnSelection()
514   {
515     return colSel;
516   }
517
518   /**
519    * DOCUMENT ME!
520    * 
521    * @param tree
522    *          DOCUMENT ME!
523    */
524   public void setCurrentTree(NJTree tree)
525   {
526     currentTree = tree;
527   }
528
529   /**
530    * DOCUMENT ME!
531    * 
532    * @return DOCUMENT ME!
533    */
534   public NJTree getCurrentTree()
535   {
536     return currentTree;
537   }
538
539   /**
540    * returns the visible column regions of the alignment
541    * 
542    * @param selectedRegionOnly
543    *          true to just return the contigs intersecting with the selected
544    *          area
545    * @return
546    */
547   public int[] getViewAsVisibleContigs(boolean selectedRegionOnly)
548   {
549     int[] viscontigs = null;
550     int start = 0, end = 0;
551     if (selectedRegionOnly && selectionGroup != null)
552     {
553       start = selectionGroup.getStartRes();
554       end = selectionGroup.getEndRes() + 1;
555     }
556     else
557     {
558       end = alignment.getWidth();
559     }
560     viscontigs = colSel.getVisibleContigs(start, end);
561     return viscontigs;
562   }
563
564   /**
565    * get hash of undo and redo list for the alignment
566    * 
567    * @return long[] { historyList.hashCode, redoList.hashCode };
568    */
569   public long[] getUndoRedoHash()
570   {
571     // TODO: JAL-1126
572     if (historyList == null || redoList == null)
573     {
574       return new long[] { -1, -1 };
575     }
576     return new long[] { historyList.hashCode(), this.redoList.hashCode() };
577   }
578
579   /**
580    * test if a particular set of hashcodes are different to the hashcodes for
581    * the undo and redo list.
582    * 
583    * @param undoredo
584    *          the stored set of hashcodes as returned by getUndoRedoHash
585    * @return true if the hashcodes differ (ie the alignment has been edited) or
586    *         the stored hashcode array differs in size
587    */
588   public boolean isUndoRedoHashModified(long[] undoredo)
589   {
590     if (undoredo == null)
591     {
592       return true;
593     }
594     long[] cstate = getUndoRedoHash();
595     if (cstate.length != undoredo.length)
596     {
597       return true;
598     }
599
600     for (int i = 0; i < cstate.length; i++)
601     {
602       if (cstate[i] != undoredo[i])
603       {
604         return true;
605       }
606     }
607     return false;
608   }
609
610   public boolean followSelection = true;
611
612   /**
613    * @return true if view selection should always follow the selections
614    *         broadcast by other selection sources
615    */
616   public boolean getFollowSelection()
617   {
618     return followSelection;
619   }
620
621   /**
622    * Send the current selection to be broadcast to any selection listeners.
623    */
624   @Override
625   public void sendSelection()
626   {
627     jalview.structure.StructureSelectionManager
628             .getStructureSelectionManager(Desktop.instance).sendSelection(
629                     new SequenceGroup(getSelectionGroup()),
630                     new ColumnSelection(getColumnSelection()), this);
631   }
632
633   /**
634    * return the alignPanel containing the given viewport. Use this to get the
635    * components currently handling the given viewport.
636    * 
637    * @param av
638    * @return null or an alignPanel guaranteed to have non-null alignFrame
639    *         reference
640    */
641   public AlignmentPanel getAlignPanel()
642   {
643     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(this
644             .getSequenceSetId());
645     for (int p = 0; aps != null && p < aps.length; p++)
646     {
647       if (aps[p].av == this)
648       {
649         return aps[p];
650       }
651     }
652     return null;
653   }
654
655   public boolean getSortByTree()
656   {
657     return sortByTree;
658   }
659
660   public void setSortByTree(boolean sort)
661   {
662     sortByTree = sort;
663   }
664
665   /**
666    * synthesize a column selection if none exists so it covers the given
667    * selection group. if wholewidth is false, no column selection is made if the
668    * selection group covers the whole alignment width.
669    * 
670    * @param sg
671    * @param wholewidth
672    */
673   public void expandColSelection(SequenceGroup sg, boolean wholewidth)
674   {
675     int sgs, sge;
676     if (sg != null
677             && (sgs = sg.getStartRes()) >= 0
678             && sg.getStartRes() <= (sge = sg.getEndRes())
679             && (colSel == null || colSel.getSelected() == null || colSel
680                     .getSelected().size() == 0))
681     {
682       if (!wholewidth && alignment.getWidth() == (1 + sge - sgs))
683       {
684         // do nothing
685         return;
686       }
687       if (colSel == null)
688       {
689         colSel = new ColumnSelection();
690       }
691       for (int cspos = sg.getStartRes(); cspos <= sg.getEndRes(); cspos++)
692       {
693         colSel.addElement(cspos);
694       }
695     }
696   }
697
698   /**
699    * Returns the (Desktop) instance of the StructureSelectionManager
700    */
701   @Override
702   public StructureSelectionManager getStructureSelectionManager()
703   {
704     return StructureSelectionManager
705             .getStructureSelectionManager(Desktop.instance);
706   }
707
708   /**
709    * 
710    * @param pdbEntries
711    * @return an array of SequenceI arrays, one for each PDBEntry, listing which
712    *         sequences in the alignment hold a reference to it
713    */
714   public SequenceI[][] collateForPDB(PDBEntry[] pdbEntries)
715   {
716     List<SequenceI[]> seqvectors = new ArrayList<SequenceI[]>();
717     for (PDBEntry pdb : pdbEntries)
718     {
719       List<SequenceI> seqs = new ArrayList<SequenceI>();
720       for (SequenceI sq : alignment.getSequences())
721       {
722         Vector<PDBEntry> pdbs = sq.getDatasetSequence().getAllPDBEntries();
723         if (pdbs == null)
724         {
725           continue;
726         }
727         for (PDBEntry p1 : pdbs)
728         {
729           if (p1.getId().equals(pdb.getId()))
730           {
731             if (!seqs.contains(sq))
732             {
733               seqs.add(sq);
734               continue;
735             }
736           }
737         }
738       }
739       seqvectors.add(seqs.toArray(new SequenceI[seqs.size()]));
740     }
741     return seqvectors.toArray(new SequenceI[seqvectors.size()][]);
742   }
743
744   @Override
745   public boolean isNormaliseSequenceLogo()
746   {
747     return normaliseSequenceLogo;
748   }
749
750   public void setNormaliseSequenceLogo(boolean state)
751   {
752     normaliseSequenceLogo = state;
753   }
754
755   /**
756    * 
757    * @return true if alignment characters should be displayed
758    */
759   @Override
760   public boolean isValidCharWidth()
761   {
762     return validCharWidth;
763   }
764
765   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<String, AutoCalcSetting>();
766
767   public AutoCalcSetting getCalcIdSettingsFor(String calcId)
768   {
769     return calcIdParams.get(calcId);
770   }
771
772   public void setCalcIdSettingsFor(String calcId, AutoCalcSetting settings,
773           boolean needsUpdate)
774   {
775     calcIdParams.put(calcId, settings);
776     // TODO: create a restart list to trigger any calculations that need to be
777     // restarted after load
778     // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
779     if (needsUpdate)
780     {
781       Cache.log.debug("trigger update for " + calcId);
782     }
783   }
784
785   /**
786    * Method called when another alignment's edit (or possibly other) command is
787    * broadcast to here.
788    *
789    * To allow for sequence mappings (e.g. protein to cDNA), we have to first
790    * 'unwind' the command on the source sequences (in simulation, not in fact),
791    * and then for each edit in turn:
792    * <ul>
793    * <li>compute the equivalent edit on the mapped sequences</li>
794    * <li>apply the mapped edit</li>
795    * <li>'apply' the source edit to the working copy of the source sequences</li>
796    * </ul>
797    * 
798    * @param command
799    * @param undo
800    * @param ssm
801    */
802   @Override
803   public void mirrorCommand(CommandI command, boolean undo,
804           StructureSelectionManager ssm, VamsasSource source)
805   {
806     /*
807      * Do nothing unless we are a 'complement' of the source. May replace this
808      * with direct calls not via SSM.
809      */
810     if (source instanceof AlignViewportI
811             && ((AlignViewportI) source).getCodingComplement() == this)
812     {
813       // ok to continue;
814     }
815     else
816     {
817       return;
818     }
819
820     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
821             getGapCharacter());
822     if (mappedCommand != null)
823     {
824       AlignmentI[] views = getAlignPanel().alignFrame.getViewAlignments();
825       mappedCommand.doCommand(views);
826       getAlignPanel().alignmentChanged();
827     }
828   }
829
830   /**
831    * Add the sequences from the given alignment to this viewport. Optionally,
832    * may give the user the option to open a new frame, or split panel, with cDNA
833    * and protein linked.
834    * 
835    * @param al
836    * @param title
837    */
838   public void addAlignment(AlignmentI al, String title)
839   {
840     // TODO: promote to AlignViewportI? applet CutAndPasteTransfer is different
841
842     // JBPComment: title is a largely redundant parameter at the moment
843     // JBPComment: this really should be an 'insert/pre/append' controller
844     // JBPComment: but the DNA/Protein check makes it a bit more complex
845
846     // refactored from FileLoader / CutAndPasteTransfer / SequenceFetcher with
847     // this comment:
848     // TODO: create undo object for this JAL-1101
849
850     /*
851      * If any cDNA/protein mappings can be made between the alignments, offer to
852      * open a linked alignment with split frame option.
853      */
854     if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
855     {
856       if (al.getDataset() == null)
857       {
858         // need to create ds seqs
859         for (SequenceI sq : al.getSequences())
860         {
861           if (sq.getDatasetSequence() == null)
862           {
863             sq.createDatasetSequence();
864           }
865         }
866       }
867       if (AlignmentUtils.isMappable(al, getAlignment()))
868       {
869         if (openLinkedAlignment(al, title))
870         {
871           return;
872         }
873       }
874     }
875
876     /*
877      * No mappings, or offer declined - add sequences to this alignment
878      */
879     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
880     // provenance) should share the same dataset sequence
881
882     for (int i = 0; i < al.getHeight(); i++)
883     {
884       getAlignment().addSequence(al.getSequenceAt(i));
885     }
886
887     setEndSeq(getAlignment().getHeight());
888     firePropertyChange("alignment", null, getAlignment().getSequences());
889   }
890
891   /**
892    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
893    * alignment, either as a standalone alignment or in a split frame. Returns
894    * true if the new alignment was opened, false if not, because the user
895    * declined the offer.
896    * 
897    * @param al
898    * @param title
899    */
900   protected boolean openLinkedAlignment(AlignmentI al, String title)
901   {
902     String[] options = new String[] {
903         MessageManager.getString("action.no"),
904         MessageManager.getString("label.split_window"),
905         MessageManager.getString("label.new_window"), };
906     final String question = JvSwingUtils.wrapTooltip(true,
907             MessageManager.getString("label.open_split_window?"));
908     int response = JOptionPane.showOptionDialog(Desktop.desktop, question,
909             MessageManager.getString("label.open_split_window"),
910             JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null,
911             options, options[0]);
912
913     if (response != 1 && response != 2)
914     {
915       return false;
916     }
917     final boolean openSplitPane = (response == 1);
918     final boolean openInNewWindow = (response == 2);
919
920     /*
921      * Identify protein and dna alignments. Make a copy of this one if opening
922      * in a new split pane.
923      */
924     AlignmentI thisAlignment = openSplitPane ? new Alignment(getAlignment())
925             : getAlignment();
926     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
927     final AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
928
929     /*
930      * Map sequences. At least one should get mapped as we have already passed
931      * the test for 'mappability'. Any mappings made will be added to the
932      * protein alignment. Note creating dataset sequences on the new alignment
933      * is a pre-requisite for building mappings.
934      */
935     al.setDataset(null);
936     AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna);
937
938     /*
939      * Create the AlignFrame for the added alignment. If it is protein, mappings
940      * are registered with StructureSelectionManager as a side-effect.
941      */
942     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
943             AlignFrame.DEFAULT_HEIGHT);
944     newAlignFrame.setTitle(title);
945     newAlignFrame.statusBar.setText(MessageManager.formatMessage(
946             "label.successfully_loaded_file", new Object[] { title }));
947
948     // TODO if we want this (e.g. to enable reload of the alignment from file),
949     // we will need to add parameters to the stack.
950     // if (!protocol.equals(AppletFormatAdapter.PASTE))
951     // {
952     // alignFrame.setFileName(file, format);
953     // }
954
955     if (openInNewWindow)
956     {
957       Desktop.addInternalFrame(newAlignFrame, title,
958               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
959     }
960
961     try
962     {
963       newAlignFrame.setMaximum(jalview.bin.Cache.getDefault(
964               "SHOW_FULLSCREEN", false));
965     } catch (java.beans.PropertyVetoException ex)
966     {
967     }
968
969     if (openSplitPane)
970     {
971       al.alignAs(thisAlignment);
972       protein = openSplitFrame(newAlignFrame, thisAlignment);
973     }
974
975     return true;
976   }
977
978   /**
979    * Helper method to open a new SplitFrame holding linked dna and protein
980    * alignments.
981    * 
982    * @param newAlignFrame
983    *          containing a new alignment to be shown
984    * @param complement
985    *          cdna/protein complement alignment to show in the other split half
986    * @return the protein alignment in the split frame
987    */
988   protected AlignmentI openSplitFrame(AlignFrame newAlignFrame,
989           AlignmentI complement)
990   {
991     /*
992      * Make a new frame with a copy of the alignment we are adding to. If this
993      * is protein, the mappings to cDNA will be registered with
994      * StructureSelectionManager as a side-effect.
995      */
996     AlignFrame copyMe = new AlignFrame(complement,
997             AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
998     copyMe.setTitle(getAlignPanel().alignFrame.getTitle());
999
1000     AlignmentI al = newAlignFrame.viewport.getAlignment();
1001     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
1002             : newAlignFrame;
1003     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame : copyMe;
1004     cdnaFrame.setVisible(true);
1005     proteinFrame.setVisible(true);
1006     String linkedTitle = MessageManager
1007             .getString("label.linked_view_title");
1008
1009     /*
1010      * Open in split pane. DNA sequence above, protein below.
1011      */
1012     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
1013     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
1014
1015     return proteinFrame.viewport.getAlignment();
1016   }
1017
1018   public AnnotationColumnChooser getAnnotationColumnSelectionState()
1019   {
1020     return annotationColumnSelectionState;
1021   }
1022
1023   public void setAnnotationColumnSelectionState(
1024           AnnotationColumnChooser currentAnnotationColumnSelectionState)
1025   {
1026     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
1027   }
1028
1029   @Override
1030   public void setIdWidth(int i)
1031   {
1032     super.setIdWidth(i);
1033     AlignmentPanel ap = getAlignPanel();
1034     if (ap != null)
1035     {
1036       // modify GUI elements to reflect geometry change
1037       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
1038               .getPreferredSize();
1039       idw.width = i;
1040       getAlignPanel().getIdPanel().getIdCanvas().setPreferredSize(idw);
1041     }
1042   }
1043
1044   public Rectangle getExplodedGeometry()
1045   {
1046     return explodedGeometry;
1047   }
1048
1049   public void setExplodedGeometry(Rectangle explodedPosition)
1050   {
1051     this.explodedGeometry = explodedPosition;
1052   }
1053
1054   public boolean isGatherViewsHere()
1055   {
1056     return gatherViewsHere;
1057   }
1058
1059   public void setGatherViewsHere(boolean gatherViewsHere)
1060   {
1061     this.gatherViewsHere = gatherViewsHere;
1062   }
1063
1064   /**
1065    * If this viewport has a (Protein/cDNA) complement, then scroll the
1066    * complementary alignment to match this one.
1067    */
1068   public void scrollComplementaryAlignment()
1069   {
1070     /*
1071      * Populate a SearchResults object with the mapped location to scroll to. If
1072      * there is no complement, or it is not following highlights, or no mapping
1073      * is found, the result will be empty.
1074      */
1075     SearchResults sr = new SearchResults();
1076     int verticalOffset = findComplementScrollTarget(sr);
1077     if (!sr.isEmpty())
1078     {
1079       // TODO would like next line without cast but needs more refactoring...
1080       final AlignmentPanel complementPanel = ((AlignViewport) getCodingComplement())
1081               .getAlignPanel();
1082       complementPanel.setDontScrollComplement(true);
1083       complementPanel.scrollToCentre(sr, verticalOffset);
1084     }
1085   }
1086
1087   /**
1088    * Answers true if no alignment holds a reference to the given mapping
1089    * 
1090    * @param acf
1091    * @return
1092    */
1093   protected boolean noReferencesTo(AlignedCodonFrame acf)
1094   {
1095     AlignFrame[] frames = Desktop.getAlignFrames();
1096     if (frames == null)
1097     {
1098       return true;
1099     }
1100     for (AlignFrame af : frames)
1101     {
1102       if (!af.isClosed())
1103       {
1104         for (AlignmentViewPanel ap : af.getAlignPanels())
1105         {
1106           AlignmentI al = ap.getAlignment();
1107           if (al != null && al.getCodonFrames().contains(acf))
1108           {
1109             return false;
1110           }
1111         }
1112       }
1113     }
1114     return true;
1115   }
1116
1117 }