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