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