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