7c3dca0f7b09b96df2447d61a54cc27734c11569
[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.MessageManager;
51 import jalview.viewmodel.AlignmentViewport;
52 import jalview.ws.params.AutoCalcSetting;
53
54 import java.awt.Container;
55 import java.awt.Dimension;
56 import java.awt.Font;
57 import java.awt.FontMetrics;
58 import java.awt.Rectangle;
59 import java.util.Hashtable;
60 import java.util.Iterator;
61 import java.util.List;
62
63 import javax.swing.JInternalFrame;
64
65 /**
66  * DOCUMENT ME!
67  * 
68  * @author $author$
69  * @version $Revision: 1.141 $
70  */
71 public class AlignViewport extends AlignmentViewport
72         implements SelectionSource
73 {
74   Font font;
75
76   boolean cursorMode = false;
77
78   boolean antiAlias = false;
79
80   private Rectangle explodedGeometry;
81
82   private String viewName;
83
84   /*
85    * Flag set true on the view that should 'gather' multiple views of the same
86    * sequence set id when a project is reloaded. Set false on all views when
87    * they are 'exploded' into separate windows. Set true on the current view
88    * when 'Gather' is performed, and also on the first tab when the first new
89    * view is created.
90    */
91   private boolean gatherViewsHere = false;
92
93   private AnnotationColumnChooser annotationColumnSelectionState;
94
95   /**
96    * Creates a new AlignViewport object.
97    * 
98    * @param al
99    *          alignment to view
100    */
101   public AlignViewport(AlignmentI al)
102   {
103     super(al);
104     init();
105   }
106
107   /**
108    * Create a new AlignViewport object with a specific sequence set ID
109    * 
110    * @param al
111    * @param seqsetid
112    *          (may be null - but potential for ambiguous constructor exception)
113    */
114   public AlignViewport(AlignmentI al, String seqsetid)
115   {
116     this(al, seqsetid, null);
117   }
118
119   public AlignViewport(AlignmentI al, String seqsetid, String viewid)
120   {
121     super(al);
122     sequenceSetID = seqsetid;
123     viewId = viewid;
124     // TODO remove these once 2.4.VAMSAS release finished
125     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
126     {
127       Cache.log.debug(
128               "Setting viewport's sequence set id : " + sequenceSetID);
129     }
130     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
131     {
132       Cache.log.debug("Setting viewport's view id : " + viewId);
133     }
134     init();
135
136   }
137
138   /**
139    * Create a new AlignViewport with hidden regions
140    * 
141    * @param al
142    *          AlignmentI
143    * @param hiddenColumns
144    *          ColumnSelection
145    */
146   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns)
147   {
148     super(al);
149     if (hiddenColumns != null)
150     {
151       al.setHiddenColumns(hiddenColumns);
152     }
153     init();
154   }
155
156   /**
157    * New viewport with hidden columns and an existing sequence set id
158    * 
159    * @param al
160    * @param hiddenColumns
161    * @param seqsetid
162    *          (may be null)
163    */
164   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns,
165           String seqsetid)
166   {
167     this(al, hiddenColumns, seqsetid, null);
168   }
169
170   /**
171    * New viewport with hidden columns and an existing sequence set id and viewid
172    * 
173    * @param al
174    * @param hiddenColumns
175    * @param seqsetid
176    *          (may be null)
177    * @param viewid
178    *          (may be null)
179    */
180   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns,
181           String seqsetid, String viewid)
182   {
183     super(al);
184     sequenceSetID = seqsetid;
185     viewId = viewid;
186     // TODO remove these once 2.4.VAMSAS release finished
187     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
188     {
189       Cache.log.debug(
190               "Setting viewport's sequence set id : " + sequenceSetID);
191     }
192     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
193     {
194       Cache.log.debug("Setting viewport's view id : " + viewId);
195     }
196
197     if (hiddenColumns != null)
198     {
199       al.setHiddenColumns(hiddenColumns);
200     }
201     init();
202   }
203
204   /**
205    * Apply any settings saved in user preferences
206    */
207   private void applyViewProperties()
208   {
209     antiAlias = Cache.getDefault(Preferences.ANTI_ALIAS, false);
210
211     viewStyle.setShowJVSuffix(
212             Cache.getDefault(Preferences.SHOW_JVSUFFIX, true));
213     setShowAnnotation(Cache.getDefault(Preferences.SHOW_ANNOTATIONS, true));
214
215     setRightAlignIds(Cache.getDefault(Preferences.RIGHT_ALIGN_IDS, false));
216     setCentreColumnLabels(Cache.getDefault(Preferences.CENTRE_COLUMN_LABELS, false));
217     autoCalculateConsensus = Cache.getDefault(Preferences.AUTO_CALC_CONSENSUS, true);
218
219     setPadGaps(Cache.getDefault(Preferences.PAD_GAPS, true));
220     setShowNPFeats(Cache.getDefault(Preferences.SHOW_NPFEATS_TOOLTIP, true));
221     setShowDBRefs(Cache.getDefault(Preferences.SHOW_DBREFS_TOOLTIP, true));
222     viewStyle.setSeqNameItalics(Cache.getDefault(Preferences.ID_ITALICS, true));
223     viewStyle.setWrapAlignment(
224             Cache.getDefault(Preferences.WRAP_ALIGNMENT, false));
225     viewStyle.setShowUnconserved(
226             Cache.getDefault(Preferences.SHOW_UNCONSERVED, false));
227     sortByTree = Cache.getDefault(Preferences.SORT_BY_TREE, false);
228     followSelection = Cache.getDefault(Preferences.FOLLOW_SELECTIONS, true);
229     sortAnnotationsBy = SequenceAnnotationOrder
230             .valueOf(Cache.getDefault(Preferences.SORT_ANNOTATIONS,
231                     SequenceAnnotationOrder.NONE.name()));
232     showAutocalculatedAbove = Cache
233             .getDefault(Preferences.SHOW_AUTOCALC_ABOVE, false);
234     viewStyle.setScaleProteinAsCdna(
235             Cache.getDefault(Preferences.SCALE_PROTEIN_TO_CDNA, true));
236   }
237
238   void init()
239   {
240     applyViewProperties();
241
242     String fontName = Cache.getDefault(Preferences.FONT_NAME, "SansSerif");
243     String fontStyle = Cache.getDefault(Preferences.FONT_STYLE,
244             Font.PLAIN + "");
245     String fontSize = Cache.getDefault(Preferences.FONT_SIZE, "10");
246
247     int style = 0;
248
249     if (fontStyle.equals("bold"))
250     {
251       style = 1;
252     }
253     else if (fontStyle.equals("italic"))
254     {
255       style = 2;
256     }
257
258     setFont(new Font(fontName, style, Integer.parseInt(fontSize)), true);
259
260     alignment
261             .setGapCharacter(Cache.getDefault(Preferences.GAP_SYMBOL, "-")
262                     .charAt(0));
263
264     // We must set conservation and consensus before setting colour,
265     // as Blosum and Clustal require this to be done
266     if (hconsensus == null && !isDataset)
267     {
268       if (!alignment.isNucleotide())
269       {
270         showConservation = Cache.getDefault(Preferences.SHOW_CONSERVATION,
271                 true);
272         showQuality = Cache.getDefault(Preferences.SHOW_QUALITY, true);
273         showGroupConservation = Cache
274                 .getDefault(Preferences.SHOW_GROUP_CONSERVATION, false);
275       }
276       showConsensusHistogram = Cache
277               .getDefault(Preferences.SHOW_CONSENSUS_HISTOGRAM, true);
278       showSequenceLogo = Cache.getDefault(Preferences.SHOW_CONSENSUS_LOGO,
279               false);
280
281       normaliseSequenceLogo = Cache
282               .getDefault(Preferences.NORMALISE_CONSENSUS_LOGO, false);
283       showGroupConsensus = Cache
284               .getDefault(Preferences.SHOW_GROUP_CONSENSUS, false);
285       showConsensus = Cache.getDefault(Preferences.SHOW_IDENTITY, true);
286
287       showOccupancy = Cache.getDefault(Preferences.SHOW_OCCUPANCY, true);
288     }
289     initAutoAnnotation();
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.getColourScheme(this,
301             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       Desktop.getInstance().getStructureSelectionManager()
395               .registerMappings(align.getCodonFrames());
396     }
397
398     /*
399      * replace mappings on our alignment
400      */
401     if (alignment != null && align != null)
402     {
403       alignment.setCodonFrames(align.getCodonFrames());
404     }
405   }
406
407   protected void deregisterMappings()
408   {
409     AlignmentI al = getAlignment();
410     if (al != null)
411     {
412       List<AlignedCodonFrame> mappings = al.getCodonFrames();
413       if (mappings != null)
414       {
415         StructureSelectionManager ssm = Desktop.getInstance()
416                 .getStructureSelectionManager();
417         for (AlignedCodonFrame acf : mappings)
418         {
419           if (noReferencesTo(acf))
420           {
421             ssm.deregisterMapping(acf);
422           }
423         }
424       }
425     }
426   }
427
428   /**
429    * DOCUMENT ME!
430    * 
431    * @return DOCUMENT ME!
432    */
433   @Override
434   public char getGapCharacter()
435   {
436     return getAlignment().getGapCharacter();
437   }
438
439   /**
440    * DOCUMENT ME!
441    * 
442    * @param gap
443    *          DOCUMENT ME!
444    */
445   public void setGapCharacter(char gap)
446   {
447     if (getAlignment() != null)
448     {
449       getAlignment().setGapCharacter(gap);
450     }
451   }
452
453   /**
454    * returns the visible column regions of the alignment
455    * 
456    * @param selectedRegionOnly
457    *          true to just return the contigs intersecting with the selected
458    *          area
459    * @return
460    */
461   public Iterator<int[]> getViewAsVisibleContigs(boolean selectedRegionOnly)
462   {
463     int start = 0;
464     int end = 0;
465     if (selectedRegionOnly && selectionGroup != null)
466     {
467       start = selectionGroup.getStartRes();
468       end = selectionGroup.getEndRes() + 1;
469     }
470     else
471     {
472       end = alignment.getWidth();
473     }
474     return (alignment.getHiddenColumns().getVisContigsIterator(start, end,
475             false));
476   }
477
478   /**
479    * get hash of undo and redo list for the alignment
480    * 
481    * @return long[] { historyList.hashCode, redoList.hashCode };
482    */
483   public long[] getUndoRedoHash()
484   {
485     // TODO: JAL-1126
486     if (historyList == null || redoList == null)
487     {
488       return new long[] { -1, -1 };
489     }
490     return new long[] { historyList.hashCode(), this.redoList.hashCode() };
491   }
492
493   /**
494    * test if a particular set of hashcodes are different to the hashcodes for
495    * the undo and redo list.
496    * 
497    * @param undoredo
498    *          the stored set of hashcodes as returned by getUndoRedoHash
499    * @return true if the hashcodes differ (ie the alignment has been edited) or
500    *         the stored hashcode array differs in size
501    */
502   public boolean isUndoRedoHashModified(long[] undoredo)
503   {
504     if (undoredo == null)
505     {
506       return true;
507     }
508     long[] cstate = getUndoRedoHash();
509     if (cstate.length != undoredo.length)
510     {
511       return true;
512     }
513
514     for (int i = 0; i < cstate.length; i++)
515     {
516       if (cstate[i] != undoredo[i])
517       {
518         return true;
519       }
520     }
521     return false;
522   }
523
524   public boolean followSelection = true;
525
526   /**
527    * @return true if view selection should always follow the selections
528    *         broadcast by other selection sources
529    */
530   public boolean getFollowSelection()
531   {
532     return followSelection;
533   }
534
535   /**
536    * Send the current selection to be broadcast to any selection listeners.
537    */
538   @Override
539   public void sendSelection()
540   {
541     Desktop.getInstance().getStructureSelectionManager().sendSelection(
542             new SequenceGroup(getSelectionGroup()),
543             new ColumnSelection(getColumnSelection()),
544             new HiddenColumns(getAlignment().getHiddenColumns()), this);
545   }
546
547   /**
548    * return the alignPanel containing the given viewport. Use this to get the
549    * components currently handling the given viewport.
550    * 
551    * @param av
552    * @return null or an alignPanel guaranteed to have non-null alignFrame
553    *         reference
554    */
555   public AlignmentPanel getAlignPanel()
556   {
557     AlignmentPanel[] aps = PaintRefresher
558             .getAssociatedPanels(this.getSequenceSetId());
559     for (int p = 0; aps != null && p < aps.length; p++)
560     {
561       if (aps[p].av == this)
562       {
563         return aps[p];
564       }
565     }
566     return null;
567   }
568
569   public boolean getSortByTree()
570   {
571     return sortByTree;
572   }
573
574   public void setSortByTree(boolean sort)
575   {
576     sortByTree = sort;
577   }
578
579   /**
580    * Returns the (Desktop) instance of the StructureSelectionManager
581    */
582   @Override
583   public StructureSelectionManager getStructureSelectionManager()
584   {
585     return Desktop.getInstance().getStructureSelectionManager();
586   }
587
588   @Override
589   public boolean isNormaliseSequenceLogo()
590   {
591     return normaliseSequenceLogo;
592   }
593
594   public void setNormaliseSequenceLogo(boolean state)
595   {
596     normaliseSequenceLogo = state;
597   }
598
599   /**
600    * 
601    * @return true if alignment characters should be displayed
602    */
603   @Override
604   public boolean isValidCharWidth()
605   {
606     return validCharWidth;
607   }
608
609   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<>();
610
611   public AutoCalcSetting getCalcIdSettingsFor(String calcId)
612   {
613     return calcIdParams.get(calcId);
614   }
615
616   public void setCalcIdSettingsFor(String calcId, AutoCalcSetting settings,
617           boolean needsUpdate)
618   {
619     calcIdParams.put(calcId, settings);
620     // TODO: create a restart list to trigger any calculations that need to be
621     // restarted after load
622     // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
623     if (needsUpdate)
624     {
625       Cache.log.debug("trigger update for " + calcId);
626     }
627   }
628
629   /**
630    * Method called when another alignment's edit (or possibly other) command is
631    * broadcast to here.
632    *
633    * To allow for sequence mappings (e.g. protein to cDNA), we have to first
634    * 'unwind' the command on the source sequences (in simulation, not in fact),
635    * and then for each edit in turn:
636    * <ul>
637    * <li>compute the equivalent edit on the mapped sequences</li>
638    * <li>apply the mapped edit</li>
639    * <li>'apply' the source edit to the working copy of the source
640    * sequences</li>
641    * </ul>
642    * 
643    * @param command
644    * @param undo
645    * @param ssm
646    */
647   @Override
648   public void mirrorCommand(CommandI command, boolean undo,
649           StructureSelectionManager ssm, VamsasSource source)
650   {
651     /*
652      * Do nothing unless we are a 'complement' of the source. May replace this
653      * with direct calls not via SSM.
654      */
655     if (source instanceof AlignViewportI
656             && ((AlignViewportI) source).getCodingComplement() == this)
657     {
658       // ok to continue;
659     }
660     else
661     {
662       return;
663     }
664
665     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
666             getGapCharacter());
667     if (mappedCommand != null)
668     {
669       AlignmentI[] views = getAlignPanel().alignFrame.getViewAlignments();
670       mappedCommand.doCommand(views);
671       getAlignPanel().alignmentChanged();
672     }
673   }
674
675   /**
676    * Add the sequences from the given alignment to this viewport. Optionally,
677    * may give the user the option to open a new frame, or split panel, with cDNA
678    * and protein linked.
679    * 
680    * @param toAdd
681    * @param title
682    */
683   public void addAlignment(AlignmentI toAdd, String title)
684   {
685     // TODO: promote to AlignViewportI? applet CutAndPasteTransfer is different
686
687     // JBPComment: title is a largely redundant parameter at the moment
688     // JBPComment: this really should be an 'insert/pre/append' controller
689     // JBPComment: but the DNA/Protein check makes it a bit more complex
690
691     // refactored from FileLoader / CutAndPasteTransfer / SequenceFetcher with
692     // this comment:
693     // TODO: create undo object for this JAL-1101
694
695     /*
696      * Ensure datasets are created for the new alignment as
697      * mappings operate on dataset sequences
698      */
699     toAdd.setDataset(null);
700
701     /*
702      * Check if any added sequence could be the object of a mapping or
703      * cross-reference; if so, make the mapping explicit 
704      */
705     getAlignment().realiseMappings(toAdd.getSequences());
706
707     /*
708      * If any cDNA/protein mappings exist or can be made between the alignments, 
709      * offer to open a split frame with linked alignments
710      */
711     if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
712     {
713       if (AlignmentUtils.isMappable(toAdd, getAlignment()))
714       {
715         openLinkedAlignment(toAdd, title);
716         return;
717       }
718     }
719     addDataToAlignment(toAdd);
720   }
721
722   /**
723    * adds sequences to this alignment
724    * 
725    * @param toAdd
726    */
727   void addDataToAlignment(AlignmentI toAdd)
728   {
729     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
730     // provenance) should share the same dataset sequence
731
732     AlignmentI al = getAlignment();
733     String gap = String.valueOf(al.getGapCharacter());
734     for (int i = 0; i < toAdd.getHeight(); i++)
735     {
736       SequenceI seq = toAdd.getSequenceAt(i);
737       /*
738        * experimental!
739        * - 'align' any mapped sequences as per existing 
740        *    e.g. cdna to genome, domain hit to protein sequence
741        * very experimental! (need a separate menu option for this)
742        * - only add mapped sequences ('select targets from a dataset')
743        */
744       if (true /*AlignmentUtils.alignSequenceAs(seq, al, gap, true, true)*/)
745       {
746         al.addSequence(seq);
747       }
748     }
749
750     ranges.setEndSeq(getAlignment().getHeight() - 1); // BH 2019.04.18
751     firePropertyChange("alignment", null, getAlignment().getSequences());
752   }
753
754   public final static int NO_SPLIT = 0;
755
756   public final static int SPLIT_FRAME = 1;
757
758   public final static int NEW_WINDOW = 2;
759
760   /**
761    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
762    * alignment, either as a standalone alignment or in a split frame. Returns
763    * true if the new alignment was opened, false if not, because the user
764    * declined the offer.
765    * 
766    * @param al
767    * @param title
768    */
769   protected void openLinkedAlignment(AlignmentI al, String title)
770   {
771     String[] options = new String[] { MessageManager.getString("action.no"),
772         MessageManager.getString("label.split_window"),
773         MessageManager.getString("label.new_window"), };
774     final String question = JvSwingUtils.wrapTooltip(true,
775             MessageManager.getString("label.open_split_window?"));
776
777     /*
778      * options No, Split Window, New Window correspond to
779      * dialog responses 0, 1, 2 (even though JOptionPane shows them
780      * in reverse order)
781      */
782     JvOptionPane dialog = JvOptionPane
783             .newOptionDialog(Desktop.getDesktopPane())
784             .setResponseHandler(NO_SPLIT, new Runnable()
785             {
786               @Override
787               public void run()
788               {
789                 addDataToAlignment(al);
790               }
791             }).setResponseHandler(SPLIT_FRAME, new Runnable()
792             {
793               @Override
794               public void run()
795               {
796                 openLinkedAlignmentAs(getAlignPanel().alignFrame,
797                         new Alignment(getAlignment()), al, title,
798                         SPLIT_FRAME);
799               }
800             }).setResponseHandler(NEW_WINDOW, new Runnable()
801             {
802               @Override
803               public void run()
804               {
805                 openLinkedAlignmentAs(null, getAlignment(), al, title,
806                         NEW_WINDOW);
807               }
808             });
809     dialog.showDialog(question,
810             MessageManager.getString("label.open_split_window"),
811             JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
812             options, options[0]);
813   }
814
815   /**
816    * Open a split frame or a new window
817    * 
818    * @param al
819    * @param title
820    * @param mode
821    *          SPLIT_FRAME or NEW_WINDOW
822    */
823   public static void openLinkedAlignmentAs(AlignFrame thisFrame,
824           AlignmentI thisAlignment, AlignmentI al, String title, int mode)
825   {
826     /*
827      * Identify protein and dna alignments. Make a copy of this one if opening
828      * in a new split pane.
829      */
830     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
831     AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
832
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(jalview.bin.Cache
869               .getDefault(Preferences.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     AlignmentI al = newAlignFrame.viewport.getAlignment();
904     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
905             : newAlignFrame;
906     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame : copyMe;
907     cdnaFrame.setVisible(true);
908     proteinFrame.setVisible(true);
909     String linkedTitle = MessageManager
910             .getString("label.linked_view_title");
911
912     /*
913      * Open in split pane. DNA sequence above, protein below.
914      */
915     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
916     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
917
918     return proteinFrame.viewport.getAlignment();
919   }
920
921   public AnnotationColumnChooser getAnnotationColumnSelectionState()
922   {
923     return annotationColumnSelectionState;
924   }
925
926   public void setAnnotationColumnSelectionState(
927           AnnotationColumnChooser currentAnnotationColumnSelectionState)
928   {
929     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
930   }
931
932   @Override
933   public void setIdWidth(int i)
934   {
935     super.setIdWidth(i);
936     AlignmentPanel ap = getAlignPanel();
937     if (ap != null)
938     {
939       // modify GUI elements to reflect geometry change
940       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
941               .getPreferredSize();
942       idw.width = i;
943       getAlignPanel().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     if (featureSettings == null)
1033     {
1034       return;
1035     }
1036
1037     FeatureRenderer fr = getAlignPanel().getSeqPanel().seqCanvas
1038             .getFeatureRenderer();
1039     fr.findAllFeatures(true);
1040     List<String> renderOrder = fr.getRenderOrder();
1041     FeaturesDisplayedI displayed = fr.getFeaturesDisplayed();
1042     displayed.clear();
1043     // TODO this clears displayed.featuresRegistered - do we care?
1044
1045     /*
1046      * set feature colour if specified by feature settings
1047      * set visibility of all features
1048      */
1049     for (String type : renderOrder)
1050     {
1051       FeatureColourI preferredColour = featureSettings
1052               .getFeatureColour(type);
1053       if (preferredColour != null)
1054       {
1055         fr.setColour(type, preferredColour);
1056       }
1057       if (featureSettings.isFeatureDisplayed(type))
1058       {
1059         displayed.setVisible(type);
1060       }
1061     }
1062
1063     /*
1064      * set visibility of feature groups
1065      */
1066     for (String group : fr.getFeatureGroups())
1067     {
1068       fr.setGroupVisibility(group, featureSettings.isGroupDisplayed(group));
1069     }
1070
1071     /*
1072      * order the features
1073      */
1074     if (featureSettings.optimiseOrder())
1075     {
1076       // TODO not supported (yet?)
1077     }
1078     else
1079     {
1080       fr.orderFeatures(featureSettings);
1081     }
1082     fr.setTransparency(featureSettings.getTransparency());
1083   }
1084
1085   public String getViewName()
1086   {
1087     return viewName;
1088   }
1089
1090   public void setViewName(String viewName)
1091   {
1092     this.viewName = viewName;
1093   }
1094 }