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