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