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