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