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