779b48e3d7b5ec27a5750cf06d121f113416ccac
[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     autoCalculateConsensusAndConservation = 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       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 && Desktop.getInstance() != null)
414       {
415         // StructureSelectionManager ssm = Desktop.getInstance()
416         // .getStructureSelectionManager();
417
418         // BH 2019.08.27 allows for null Desktop instance
419         StructureSelectionManager ssm = getStructureSelectionManager();
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     getStructureSelectionManager().sendSelection(
545             new SequenceGroup(getSelectionGroup()),
546             new ColumnSelection(getColumnSelection()),
547             new HiddenColumns(getAlignment().getHiddenColumns()), this);
548   }
549
550   /**
551    * return the alignPanel containing the given viewport. Use this to get the
552    * components currently handling the given viewport.
553    * 
554    * @param av
555    * @return null or an alignPanel guaranteed to have non-null alignFrame
556    *         reference
557    */
558   public AlignmentPanel getAlignPanel()
559   {
560     AlignmentPanel[] aps = PaintRefresher
561             .getAssociatedPanels(this.getSequenceSetId());
562     for (int p = 0; aps != null && p < aps.length; p++)
563     {
564       if (aps[p].av == this)
565       {
566         return aps[p];
567       }
568     }
569     return null;
570   }
571
572   public boolean getSortByTree()
573   {
574     return sortByTree;
575   }
576
577   public void setSortByTree(boolean sort)
578   {
579     sortByTree = sort;
580   }
581
582   /**
583    * Returns the (Desktop) instance of the StructureSelectionManager
584    */
585   @Override
586   public StructureSelectionManager getStructureSelectionManager()
587   {
588     // BH allows for null Desktop instance
589     return StructureSelectionManager
590             .getStructureSelectionManager(Desktop.getInstance());
591   }
592
593   @Override
594   public boolean isNormaliseSequenceLogo()
595   {
596     return normaliseSequenceLogo;
597   }
598
599   public void setNormaliseSequenceLogo(boolean state)
600   {
601     normaliseSequenceLogo = state;
602   }
603
604   /**
605    * 
606    * @return true if alignment characters should be displayed
607    */
608   @Override
609   public boolean isValidCharWidth()
610   {
611     return validCharWidth;
612   }
613
614   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<>();
615
616   public AutoCalcSetting getCalcIdSettingsFor(String calcId)
617   {
618     return calcIdParams.get(calcId);
619   }
620
621   public void setCalcIdSettingsFor(String calcId, AutoCalcSetting settings,
622           boolean needsUpdate)
623   {
624     calcIdParams.put(calcId, settings);
625     // TODO: create a restart list to trigger any calculations that need to be
626     // restarted after load
627     // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
628     if (needsUpdate)
629     {
630       Cache.log.debug("trigger update for " + calcId);
631     }
632   }
633
634   /**
635    * Method called when another alignment's edit (or possibly other) command is
636    * broadcast to here.
637    *
638    * To allow for sequence mappings (e.g. protein to cDNA), we have to first
639    * 'unwind' the command on the source sequences (in simulation, not in fact),
640    * and then for each edit in turn:
641    * <ul>
642    * <li>compute the equivalent edit on the mapped sequences</li>
643    * <li>apply the mapped edit</li>
644    * <li>'apply' the source edit to the working copy of the source
645    * sequences</li>
646    * </ul>
647    * 
648    * @param command
649    * @param undo
650    * @param ssm
651    */
652   @Override
653   public void mirrorCommand(CommandI command, boolean undo,
654           StructureSelectionManager ssm, VamsasSource source)
655   {
656     /*
657      * Do nothing unless we are a 'complement' of the source. May replace this
658      * with direct calls not via SSM.
659      */
660     if (source instanceof AlignViewportI
661             && ((AlignViewportI) source).getCodingComplement() == this)
662     {
663       // ok to continue;
664     }
665     else
666     {
667       return;
668     }
669
670     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
671             getGapCharacter());
672     if (mappedCommand != null)
673     {
674       AlignmentI[] views = getAlignPanel().alignFrame.getViewAlignments();
675       mappedCommand.doCommand(views);
676       getAlignPanel().alignmentChanged();
677     }
678   }
679
680   /**
681    * Add the sequences from the given alignment to this viewport. Optionally,
682    * may give the user the option to open a new frame, or split panel, with cDNA
683    * and protein linked.
684    * 
685    * @param toAdd
686    * @param title
687    */
688   public void addAlignment(AlignmentI toAdd, String title)
689   {
690     // TODO: promote to AlignViewportI? applet CutAndPasteTransfer is different
691
692     // JBPComment: title is a largely redundant parameter at the moment
693     // JBPComment: this really should be an 'insert/pre/append' controller
694     // JBPComment: but the DNA/Protein check makes it a bit more complex
695
696     // refactored from FileLoader / CutAndPasteTransfer / SequenceFetcher with
697     // this comment:
698     // TODO: create undo object for this JAL-1101
699
700     /*
701      * Ensure datasets are created for the new alignment as
702      * mappings operate on dataset sequences
703      */
704     toAdd.setDataset(null);
705
706     /*
707      * Check if any added sequence could be the object of a mapping or
708      * cross-reference; if so, make the mapping explicit 
709      */
710     getAlignment().realiseMappings(toAdd.getSequences());
711
712     /*
713      * If any cDNA/protein mappings exist or can be made between the alignments, 
714      * offer to open a split frame with linked alignments
715      */
716     if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
717     {
718       if (AlignmentUtils.isMappable(toAdd, getAlignment()))
719       {
720         openLinkedAlignment(toAdd, title);
721         return;
722       }
723     }
724     addDataToAlignment(toAdd);
725   }
726
727   /**
728    * adds sequences to this alignment
729    * 
730    * @param toAdd
731    */
732   void addDataToAlignment(AlignmentI toAdd)
733   {
734     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
735     // provenance) should share the same dataset sequence
736
737     AlignmentI al = getAlignment();
738     String gap = String.valueOf(al.getGapCharacter());
739     for (int i = 0; i < toAdd.getHeight(); i++)
740     {
741       SequenceI seq = toAdd.getSequenceAt(i);
742       /*
743        * experimental!
744        * - 'align' any mapped sequences as per existing 
745        *    e.g. cdna to genome, domain hit to protein sequence
746        * very experimental! (need a separate menu option for this)
747        * - only add mapped sequences ('select targets from a dataset')
748        */
749       if (true /*AlignmentUtils.alignSequenceAs(seq, al, gap, true, true)*/)
750       {
751         al.addSequence(seq);
752       }
753     }
754
755     ranges.setEndSeq(getAlignment().getHeight() - 1); // BH 2019.04.18
756     firePropertyChange("alignment", null, getAlignment().getSequences());
757   }
758
759   public final static int NO_SPLIT = 0;
760
761   public final static int SPLIT_FRAME = 1;
762
763   public final static int NEW_WINDOW = 2;
764
765   /**
766    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
767    * alignment, either as a standalone alignment or in a split frame. Returns
768    * true if the new alignment was opened, false if not, because the user
769    * declined the offer.
770    * 
771    * @param al
772    * @param title
773    */
774   protected void openLinkedAlignment(AlignmentI al, String title)
775   {
776     String[] options = new String[] { MessageManager.getString("action.no"),
777         MessageManager.getString("label.split_window"),
778         MessageManager.getString("label.new_window"), };
779     final String question = JvSwingUtils.wrapTooltip(true,
780             MessageManager.getString("label.open_split_window?"));
781
782     /*
783      * options No, Split Window, New Window correspond to
784      * dialog responses 0, 1, 2 (even though JOptionPane shows them
785      * in reverse order)
786      */
787     JvOptionPane dialog = JvOptionPane
788             .newOptionDialog(Desktop.getDesktopPane())
789             .setResponseHandler(NO_SPLIT, new Runnable()
790             {
791               @Override
792               public void run()
793               {
794                 addDataToAlignment(al);
795               }
796             }).setResponseHandler(SPLIT_FRAME, new Runnable()
797             {
798               @Override
799               public void run()
800               {
801                 openLinkedAlignmentAs(getAlignPanel().alignFrame,
802                         new Alignment(getAlignment()), al, title,
803                         SPLIT_FRAME);
804               }
805             }).setResponseHandler(NEW_WINDOW, new Runnable()
806             {
807               @Override
808               public void run()
809               {
810                 openLinkedAlignmentAs(null, getAlignment(), al, title,
811                         NEW_WINDOW);
812               }
813             });
814     dialog.showDialog(question,
815             MessageManager.getString("label.open_split_window"),
816             JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
817             options, options[0]);
818   }
819
820   /**
821    * Open a split frame or a new window
822    * 
823    * @param al
824    * @param title
825    * @param mode
826    *          SPLIT_FRAME or NEW_WINDOW
827    */
828   public static void openLinkedAlignmentAs(AlignFrame thisFrame,
829           AlignmentI thisAlignment, AlignmentI al, String title, int mode)
830   {
831     /*
832      * Identify protein and dna alignments. Make a copy of this one if opening
833      * in a new split pane.
834      */
835     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
836     AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
837
838     /*
839      * Map sequences. At least one should get mapped as we have already passed
840      * the test for 'mappability'. Any mappings made will be added to the
841      * protein alignment. Note creating dataset sequences on the new alignment
842      * is a pre-requisite for building mappings.
843      */
844     al.setDataset(null);
845     AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna);
846
847     /*
848      * Create the AlignFrame for the added alignment. If it is protein, mappings
849      * are registered with StructureSelectionManager as a side-effect.
850      */
851     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
852             AlignFrame.DEFAULT_HEIGHT);
853     newAlignFrame.setTitle(title);
854     newAlignFrame.setStatus(MessageManager
855             .formatMessage("label.successfully_loaded_file", new Object[]
856             { title }));
857
858     // TODO if we want this (e.g. to enable reload of the alignment from file),
859     // we will need to add parameters to the stack.
860     // if (!protocol.equals(DataSourceType.PASTE))
861     // {
862     // alignFrame.setFileName(file, format);
863     // }
864
865     if (mode == NEW_WINDOW)
866     {
867       Desktop.addInternalFrame(newAlignFrame, title,
868               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
869     }
870
871     try
872     {
873       newAlignFrame.setMaximum(jalview.bin.Cache
874               .getDefault(Preferences.SHOW_FULLSCREEN, false));
875     } catch (java.beans.PropertyVetoException ex)
876     {
877     }
878
879     if (mode == SPLIT_FRAME)
880     {
881       al.alignAs(thisAlignment);
882       openSplitFrame(thisFrame, newAlignFrame, thisAlignment);
883     }
884   }
885
886   /**
887    * Helper method to open a new SplitFrame holding linked dna and protein
888    * alignments.
889    * 
890    * @param newAlignFrame
891    *          containing a new alignment to be shown
892    * @param complement
893    *          cdna/protein complement alignment to show in the other split half
894    * @return the protein alignment in the split frame
895    */
896   static protected AlignmentI openSplitFrame(AlignFrame thisFrame,
897           AlignFrame newAlignFrame, AlignmentI complement)
898   {
899     /*
900      * Make a new frame with a copy of the alignment we are adding to. If this
901      * is protein, the mappings to cDNA will be registered with
902      * StructureSelectionManager as a side-effect.
903      */
904     AlignFrame copyMe = new AlignFrame(complement, AlignFrame.DEFAULT_WIDTH,
905             AlignFrame.DEFAULT_HEIGHT);
906     copyMe.setTitle(thisFrame.getTitle());
907
908     AlignmentI al = newAlignFrame.viewport.getAlignment();
909     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
910             : newAlignFrame;
911     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame : copyMe;
912     cdnaFrame.setVisible(true);
913     proteinFrame.setVisible(true);
914     String linkedTitle = MessageManager
915             .getString("label.linked_view_title");
916
917     /*
918      * Open in split pane. DNA sequence above, protein below.
919      */
920     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
921     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
922
923     return proteinFrame.viewport.getAlignment();
924   }
925
926   public AnnotationColumnChooser getAnnotationColumnSelectionState()
927   {
928     return annotationColumnSelectionState;
929   }
930
931   public void setAnnotationColumnSelectionState(
932           AnnotationColumnChooser currentAnnotationColumnSelectionState)
933   {
934     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
935   }
936
937   @Override
938   public void setIdWidth(int i)
939   {
940     super.setIdWidth(i);
941     AlignmentPanel ap = getAlignPanel();
942     if (ap != null)
943     {
944       // modify GUI elements to reflect geometry change
945       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
946               .getPreferredSize();
947       idw.width = i;
948       getAlignPanel().getIdPanel().getIdCanvas().setPreferredSize(idw);
949     }
950   }
951
952   public Rectangle getExplodedGeometry()
953   {
954     return explodedGeometry;
955   }
956
957   public void setExplodedGeometry(Rectangle explodedPosition)
958   {
959     this.explodedGeometry = explodedPosition;
960   }
961
962   public boolean isGatherViewsHere()
963   {
964     return gatherViewsHere;
965   }
966
967   public void setGatherViewsHere(boolean gatherViewsHere)
968   {
969     this.gatherViewsHere = gatherViewsHere;
970   }
971
972   /**
973    * If this viewport has a (Protein/cDNA) complement, then scroll the
974    * complementary alignment to match this one.
975    */
976   public void scrollComplementaryAlignment()
977   {
978     /*
979      * Populate a SearchResults object with the mapped location to scroll to. If
980      * there is no complement, or it is not following highlights, or no mapping
981      * is found, the result will be empty.
982      */
983     SearchResultsI sr = new SearchResults();
984     int verticalOffset = findComplementScrollTarget(sr);
985     if (!sr.isEmpty())
986     {
987       // TODO would like next line without cast but needs more refactoring...
988       final AlignmentPanel complementPanel = ((AlignViewport) getCodingComplement())
989               .getAlignPanel();
990       complementPanel.setToScrollComplementPanel(false);
991       complementPanel.scrollToCentre(sr, verticalOffset);
992       complementPanel.setToScrollComplementPanel(true);
993     }
994   }
995
996   /**
997    * Answers true if no alignment holds a reference to the given mapping
998    * 
999    * @param acf
1000    * @return
1001    */
1002   protected boolean noReferencesTo(AlignedCodonFrame acf)
1003   {
1004     AlignFrame[] frames = Desktop.getAlignFrames();
1005     if (frames == null)
1006     {
1007       return true;
1008     }
1009     for (AlignFrame af : frames)
1010     {
1011       if (!af.isClosed())
1012       {
1013         for (AlignmentViewPanel ap : af.getAlignPanels())
1014         {
1015           AlignmentI al = ap.getAlignment();
1016           if (al != null && al.getCodonFrames().contains(acf))
1017           {
1018             return false;
1019           }
1020         }
1021       }
1022     }
1023     return true;
1024   }
1025
1026   /**
1027    * Applies the supplied feature settings descriptor to currently known
1028    * features. This supports an 'initial configuration' of feature colouring
1029    * based on a preset or user favourite. This may then be modified in the usual
1030    * way using the Feature Settings dialogue.
1031    * 
1032    * @param featureSettings
1033    */
1034   @Override
1035   public void applyFeaturesStyle(FeatureSettingsModelI featureSettings)
1036   {
1037     if (featureSettings == null)
1038     {
1039       return;
1040     }
1041
1042     FeatureRenderer fr = getAlignPanel().getSeqPanel().seqCanvas
1043             .getFeatureRenderer();
1044     fr.findAllFeatures(true);
1045     List<String> renderOrder = fr.getRenderOrder();
1046     FeaturesDisplayedI displayed = fr.getFeaturesDisplayed();
1047     displayed.clear();
1048     // TODO this clears displayed.featuresRegistered - do we care?
1049
1050     /*
1051      * set feature colour if specified by feature settings
1052      * set visibility of all features
1053      */
1054     for (String type : renderOrder)
1055     {
1056       FeatureColourI preferredColour = featureSettings
1057               .getFeatureColour(type);
1058       if (preferredColour != null)
1059       {
1060         fr.setColour(type, preferredColour);
1061       }
1062       if (featureSettings.isFeatureDisplayed(type))
1063       {
1064         displayed.setVisible(type);
1065       }
1066     }
1067
1068     /*
1069      * set visibility of feature groups
1070      */
1071     for (String group : fr.getFeatureGroups())
1072     {
1073       fr.setGroupVisibility(group, featureSettings.isGroupDisplayed(group));
1074     }
1075
1076     /*
1077      * order the features
1078      */
1079     if (featureSettings.optimiseOrder())
1080     {
1081       // TODO not supported (yet?)
1082     }
1083     else
1084     {
1085       fr.orderFeatures(featureSettings);
1086     }
1087     fr.setTransparency(featureSettings.getTransparency());
1088   }
1089
1090   public String getViewName()
1091   {
1092     return viewName;
1093   }
1094
1095   public void setViewName(String viewName)
1096   {
1097     this.viewName = viewName;
1098   }
1099 }