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