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