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