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