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