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