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