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