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