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