Merge branch 'develop' into trialMerge
[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.PDBEntry;
39 import jalview.datamodel.SearchResults;
40 import jalview.datamodel.SearchResultsI;
41 import jalview.datamodel.SequenceGroup;
42 import jalview.datamodel.SequenceI;
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.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 import java.util.Vector;
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;
84
85   String viewName;
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   boolean validCharWidth;
99
100   public boolean followSelection = true;
101
102   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<>();
103
104   /**
105    * Creates a new AlignViewport object.
106    * 
107    * @param al
108    *          alignment to view
109    */
110   public AlignViewport(AlignmentI al)
111   {
112     super(al);
113     init();
114   }
115
116   /**
117    * Create a new AlignViewport object with a specific sequence set ID
118    * 
119    * @param al
120    * @param seqsetid
121    *          (may be null - but potential for ambiguous constructor exception)
122    */
123   public AlignViewport(AlignmentI al, String seqsetid)
124   {
125     this(al, seqsetid, null);
126   }
127
128   public AlignViewport(AlignmentI al, String seqsetid, String viewid)
129   {
130     super(al);
131     sequenceSetID = seqsetid;
132     viewId = viewid;
133     // TODO remove these once 2.4.VAMSAS release finished
134     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
135     {
136       Cache.log.debug(
137               "Setting viewport's sequence set id : " + sequenceSetID);
138     }
139     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
140     {
141       Cache.log.debug("Setting viewport's view id : " + viewId);
142     }
143     init();
144
145   }
146
147   /**
148    * Create a new AlignViewport with hidden regions
149    * 
150    * @param al
151    *          AlignmentI
152    * @param hiddenColumns
153    *          ColumnSelection
154    */
155   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns)
156   {
157     super(al);
158     if (hiddenColumns != null)
159     {
160       al.setHiddenColumns(hiddenColumns);
161     }
162     init();
163   }
164
165   /**
166    * New viewport with hidden columns and an existing sequence set id
167    * 
168    * @param al
169    * @param hiddenColumns
170    * @param seqsetid
171    *          (may be null)
172    */
173   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns,
174           String seqsetid)
175   {
176     this(al, hiddenColumns, seqsetid, null);
177   }
178
179   /**
180    * New viewport with hidden columns and an existing sequence set id and viewid
181    * 
182    * @param al
183    * @param hiddenColumns
184    * @param seqsetid
185    *          (may be null)
186    * @param viewid
187    *          (may be null)
188    */
189   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns,
190           String seqsetid, String viewid)
191   {
192     super(al);
193     sequenceSetID = seqsetid;
194     viewId = viewid;
195     // TODO remove these once 2.4.VAMSAS release finished
196     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
197     {
198       Cache.log.debug(
199               "Setting viewport's sequence set id : " + sequenceSetID);
200     }
201     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
202     {
203       Cache.log.debug("Setting viewport's view id : " + viewId);
204     }
205
206     if (hiddenColumns != null)
207     {
208       al.setHiddenColumns(hiddenColumns);
209     }
210     init();
211   }
212
213   /**
214    * Apply any settings saved in user preferences
215    */
216   private void applyViewProperties()
217   {
218     antiAlias = Cache.getDefault("ANTI_ALIAS", false);
219
220     viewStyle.setShowJVSuffix(Cache.getDefault("SHOW_JVSUFFIX", true));
221     setShowAnnotation(Cache.getDefault("SHOW_ANNOTATIONS", true));
222
223     setRightAlignIds(Cache.getDefault("RIGHT_ALIGN_IDS", false));
224     setCentreColumnLabels(Cache.getDefault("CENTRE_COLUMN_LABELS", false));
225     autoCalculateConsensus = Cache.getDefault("AUTO_CALC_CONSENSUS", true);
226
227     setPadGaps(Cache.getDefault("PAD_GAPS", true));
228     setShowNPFeats(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
229     setShowDBRefs(Cache.getDefault("SHOW_DBREFS_TOOLTIP", true));
230     viewStyle.setSeqNameItalics(Cache.getDefault("ID_ITALICS", true));
231     viewStyle.setWrapAlignment(Cache.getDefault("WRAP_ALIGNMENT", false));
232     viewStyle.setShowUnconserved(
233             Cache.getDefault("SHOW_UNCONSERVED", false));
234     sortByTree = Cache.getDefault("SORT_BY_TREE", false);
235     followSelection = Cache.getDefault("FOLLOW_SELECTIONS", true);
236     sortAnnotationsBy = SequenceAnnotationOrder
237             .valueOf(Cache.getDefault(Preferences.SORT_ANNOTATIONS,
238                     SequenceAnnotationOrder.NONE.name()));
239     showAutocalculatedAbove = Cache
240             .getDefault(Preferences.SHOW_AUTOCALC_ABOVE, false);
241     viewStyle.setScaleProteinAsCdna(
242             Cache.getDefault(Preferences.SCALE_PROTEIN_TO_CDNA, true));
243   }
244
245   void init()
246   {
247     applyViewProperties();
248
249     String fontName = Cache.getDefault("FONT_NAME", "SansSerif");
250     String fontStyle = Cache.getDefault("FONT_STYLE", Font.PLAIN + "");
251     String fontSize = Cache.getDefault("FONT_SIZE", "10");
252
253     int style = 0;
254
255     if (fontStyle.equals("bold"))
256     {
257       style = 1;
258     }
259     else if (fontStyle.equals("italic"))
260     {
261       style = 2;
262     }
263
264     setFont(new Font(fontName, style, Integer.parseInt(fontSize)), true);
265
266     AlignmentI al = getAlignment();
267     al.setGapCharacter(Cache.getDefault("GAP_SYMBOL", "-").charAt(0));
268
269     // We must set conservation and consensus before setting colour,
270     // as Blosum and Clustal require this to be done
271     if (consensusProfiles == null && !isDataset)
272     {
273       if (!al.isNucleotide())
274       {
275         showConservation = Cache.getDefault("SHOW_CONSERVATION", true);
276         showQuality = Cache.getDefault("SHOW_QUALITY", true);
277         showGroupConservation = Cache.getDefault("SHOW_GROUP_CONSERVATION",
278                 false);
279       }
280       showConsensusHistogram = Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM",
281               true);
282       showSequenceLogo = Cache.getDefault("SHOW_CONSENSUS_LOGO", false);
283       normaliseSequenceLogo = Cache.getDefault("NORMALISE_CONSENSUS_LOGO",
284               false);
285       showGroupConsensus = Cache.getDefault("SHOW_GROUP_CONSENSUS", false);
286       showConsensus = Cache.getDefault("SHOW_IDENTITY", true);
287
288       showOccupancy = Cache.getDefault(Preferences.SHOW_OCCUPANCY, true);
289     }
290     initAutoAnnotation();
291     // initInformation();
292
293     String colourProperty = al.isNucleotide()
294             ? Preferences.DEFAULT_COLOUR_NUC
295             : Preferences.DEFAULT_COLOUR_PROT;
296     String schemeName = Cache.getProperty(colourProperty);
297     if (schemeName == null)
298     {
299       // only DEFAULT_COLOUR available in Jalview before 2.9
300       schemeName = Cache.getDefault(Preferences.DEFAULT_COLOUR,
301               ResidueColourScheme.NONE);
302     }
303     ColourSchemeI colourScheme = ColourSchemeProperty
304             .getColourScheme(al, schemeName);
305     residueShading = new ResidueShader(colourScheme);
306
307     if (colourScheme instanceof UserColourScheme)
308     {
309       residueShading = new ResidueShader(
310               UserDefinedColours.loadDefaultColours());
311       residueShading.setThreshold(0, isIgnoreGapsConsensus());
312     }
313
314     if (residueShading != null)
315     {
316       residueShading.setConsensus(consensusProfiles);
317     }
318   }
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 (getAlignment() != null && align != null)
403     {
404       getAlignment().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 = getAlignment().getWidth();
474     }
475
476     return getAlignment().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   /**
527    * @return true if view selection should always follow the selections
528    *         broadcast by other selection sources
529    */
530   public boolean getFollowSelection()
531   {
532     return followSelection;
533   }
534
535   /**
536    * Send the current selection to be broadcast to any selection listeners.
537    */
538   @Override
539   public void sendSelection()
540   {
541     jalview.structure.StructureSelectionManager
542             .getStructureSelectionManager(Desktop.instance)
543             .sendSelection(new SequenceGroup(getSelectionGroup()),
544                     new ColumnSelection(getColumnSelection()),
545                     new HiddenColumns(getAlignment().getHiddenColumns()),
546                     this);
547   }
548
549   /**
550    * return the alignPanel containing the given viewport. Use this to get the
551    * components currently handling the given viewport.
552    * 
553    * @param av
554    * @return null or an alignPanel guaranteed to have non-null alignFrame
555    *         reference
556    */
557   public AlignmentPanel getAlignPanel()
558   {
559     AlignmentPanel[] aps = PaintRefresher
560             .getAssociatedPanels(this.getSequenceSetId());
561     for (int p = 0; aps != null && p < aps.length; p++)
562     {
563       if (aps[p].av == this)
564       {
565         return aps[p];
566       }
567     }
568     return null;
569   }
570
571   public boolean getSortByTree()
572   {
573     return sortByTree;
574   }
575
576   public void setSortByTree(boolean sort)
577   {
578     sortByTree = sort;
579   }
580
581   /**
582    * Returns the (Desktop) instance of the StructureSelectionManager
583    */
584   @Override
585   public StructureSelectionManager getStructureSelectionManager()
586   {
587     return StructureSelectionManager
588             .getStructureSelectionManager(Desktop.instance);
589   }
590
591   @Override
592   public boolean isNormaliseSequenceLogo()
593   {
594     return normaliseSequenceLogo;
595   }
596
597
598   public void setNormaliseSequenceLogo(boolean state)
599   {
600     normaliseSequenceLogo = state;
601   }
602
603   public void setNormaliseHMMSequenceLogo(boolean state)
604   {
605     normaliseHMMSequenceLogo = state;
606   }
607
608   /**
609    * 
610    * @return true if alignment characters should be displayed
611    */
612   @Override
613   public boolean isValidCharWidth()
614   {
615     return validCharWidth;
616   }
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.statusBar.setText(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 = getAlignPanel().getIdPanel().getIdCanvas()
904               .getPreferredSize();
905       idw.width = i;
906       getAlignPanel().getIdPanel().getIdCanvas().setPreferredSize(idw);
907     }
908   }
909
910   public Rectangle getExplodedGeometry()
911   {
912     return explodedGeometry;
913   }
914
915   public void setExplodedGeometry(Rectangle explodedPosition)
916   {
917     this.explodedGeometry = explodedPosition;
918   }
919
920   public boolean isGatherViewsHere()
921   {
922     return gatherViewsHere;
923   }
924
925   public void setGatherViewsHere(boolean gatherViewsHere)
926   {
927     this.gatherViewsHere = gatherViewsHere;
928   }
929
930   /**
931    * If this viewport has a (Protein/cDNA) complement, then scroll the
932    * complementary alignment to match this one.
933    */
934   public void scrollComplementaryAlignment()
935   {
936     /*
937      * Populate a SearchResults object with the mapped location to scroll to. If
938      * there is no complement, or it is not following highlights, or no mapping
939      * is found, the result will be empty.
940      */
941     SearchResultsI sr = new SearchResults();
942     int verticalOffset = findComplementScrollTarget(sr);
943     if (!sr.isEmpty())
944     {
945       // TODO would like next line without cast but needs more refactoring...
946       final AlignmentPanel complementPanel = ((AlignViewport) getCodingComplement())
947               .getAlignPanel();
948       complementPanel.setToScrollComplementPanel(false);
949       complementPanel.scrollToCentre(sr, verticalOffset);
950       complementPanel.setToScrollComplementPanel(true);
951     }
952   }
953
954   /**
955    * Answers true if no alignment holds a reference to the given mapping
956    * 
957    * @param acf
958    * @return
959    */
960   protected boolean noReferencesTo(AlignedCodonFrame acf)
961   {
962     AlignFrame[] frames = Desktop.getAlignFrames();
963     if (frames == null)
964     {
965       return true;
966     }
967     for (AlignFrame af : frames)
968     {
969       if (!af.isClosed())
970       {
971         for (AlignmentViewPanel ap : af.getAlignPanels())
972         {
973           AlignmentI al = ap.getAlignment();
974           if (al != null && al.getCodonFrames().contains(acf))
975           {
976             return false;
977           }
978         }
979       }
980     }
981     return true;
982   }
983
984   /**
985    * Applies the supplied feature settings descriptor to currently known
986    * features. This supports an 'initial configuration' of feature colouring
987    * based on a preset or user favourite. This may then be modified in the usual
988    * way using the Feature Settings dialogue.
989    * 
990    * @param featureSettings
991    */
992   @Override
993   public void applyFeaturesStyle(FeatureSettingsModelI featureSettings)
994   {
995     if (featureSettings == null)
996     {
997       return;
998     }
999
1000     FeatureRenderer fr = getAlignPanel().getSeqPanel().seqCanvas
1001             .getFeatureRenderer();
1002     fr.findAllFeatures(true);
1003     List<String> renderOrder = fr.getRenderOrder();
1004     FeaturesDisplayedI displayed = fr.getFeaturesDisplayed();
1005     displayed.clear();
1006     // TODO this clears displayed.featuresRegistered - do we care?
1007
1008     /*
1009      * set feature colour if specified by feature settings
1010      * set visibility of all features
1011      */
1012     for (String type : renderOrder)
1013     {
1014       FeatureColourI preferredColour = featureSettings
1015               .getFeatureColour(type);
1016       if (preferredColour != null)
1017       {
1018         fr.setColour(type, preferredColour);
1019       }
1020       if (featureSettings.isFeatureDisplayed(type))
1021       {
1022         displayed.setVisible(type);
1023       }
1024     }
1025
1026     /*
1027      * set visibility of feature groups
1028      */
1029     for (String group : fr.getFeatureGroups())
1030     {
1031       fr.setGroupVisibility(group, featureSettings.isGroupDisplayed(group));
1032     }
1033
1034     /*
1035      * order the features
1036      */
1037     if (featureSettings.optimiseOrder())
1038     {
1039       // TODO not supported (yet?)
1040     }
1041     else
1042     {
1043       fr.orderFeatures(featureSettings);
1044     }
1045     fr.setTransparency(featureSettings.getTransparency());
1046   }
1047
1048   @Override
1049   public boolean isNormaliseHMMSequenceLogo()
1050   {
1051     return normaliseHMMSequenceLogo;
1052   }
1053
1054 }