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