2005b91757de11968e32e4cff50d0280d8f63a5f
[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.Sequence;
43 import jalview.datamodel.SequenceGroup;
44 import jalview.datamodel.SequenceI;
45 import jalview.renderer.ResidueShader;
46 import jalview.schemes.ColourSchemeI;
47 import jalview.schemes.ColourSchemeProperty;
48 import jalview.schemes.ResidueColourScheme;
49 import jalview.schemes.UserColourScheme;
50 import jalview.structure.SelectionSource;
51 import jalview.structure.StructureSelectionManager;
52 import jalview.structure.VamsasSource;
53 import jalview.util.MessageManager;
54 import jalview.viewmodel.AlignmentViewport;
55 import jalview.ws.params.AutoCalcSetting;
56
57 import java.awt.Container;
58 import java.awt.Dimension;
59 import java.awt.Font;
60 import java.awt.FontMetrics;
61 import java.awt.Rectangle;
62 import java.util.ArrayList;
63 import java.util.Hashtable;
64 import java.util.List;
65 import java.util.Vector;
66
67 import javax.swing.JInternalFrame;
68
69 /**
70  * DOCUMENT ME!
71  * 
72  * @author $author$
73  * @version $Revision: 1.141 $
74  */
75 public class AlignViewport extends AlignmentViewport implements
76         SelectionSource
77 {
78   Font font;
79
80   TreeModel currentTree = null;
81
82   boolean cursorMode = false;
83
84   boolean antiAlias = false;
85
86   private Rectangle explodedGeometry;
87
88   String viewName;
89
90   /*
91    * Flag set true on the view that should 'gather' multiple views of the same
92    * sequence set id when a project is reloaded. Set false on all views when
93    * they are 'exploded' into separate windows. Set true on the current view
94    * when 'Gather' is performed, and also on the first tab when the first new
95    * view is created.
96    */
97   private boolean gatherViewsHere = false;
98
99   private AnnotationColumnChooser annotationColumnSelectionState;
100
101   /**
102    * Creates a new AlignViewport object.
103    * 
104    * @param al
105    *          alignment to view
106    */
107   public AlignViewport(AlignmentI al)
108   {
109     super(al);
110     init();
111   }
112
113   /**
114    * Create a new AlignViewport object with a specific sequence set ID
115    * 
116    * @param al
117    * @param seqsetid
118    *          (may be null - but potential for ambiguous constructor exception)
119    */
120   public AlignViewport(AlignmentI al, String seqsetid)
121   {
122     this(al, seqsetid, null);
123   }
124
125   public AlignViewport(AlignmentI al, String seqsetid, String viewid)
126   {
127     super(al);
128     sequenceSetID = seqsetid;
129     viewId = viewid;
130     // TODO remove these once 2.4.VAMSAS release finished
131     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
132     {
133       Cache.log.debug("Setting viewport's sequence set id : "
134               + sequenceSetID);
135     }
136     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
137     {
138       Cache.log.debug("Setting viewport's view id : " + viewId);
139     }
140     init();
141
142   }
143
144   /**
145    * Create a new AlignViewport with hidden regions
146    * 
147    * @param al
148    *          AlignmentI
149    * @param hiddenColumns
150    *          ColumnSelection
151    */
152   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns)
153   {
154     super(al);
155     if (hiddenColumns != null)
156     {
157       al.setHiddenColumns(hiddenColumns);
158     }
159     init();
160   }
161
162   /**
163    * New viewport with hidden columns and an existing sequence set id
164    * 
165    * @param al
166    * @param hiddenColumns
167    * @param seqsetid
168    *          (may be null)
169    */
170   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns,
171           String seqsetid)
172   {
173     this(al, hiddenColumns, seqsetid, null);
174   }
175
176   /**
177    * New viewport with hidden columns and an existing sequence set id and viewid
178    * 
179    * @param al
180    * @param hiddenColumns
181    * @param seqsetid
182    *          (may be null)
183    * @param viewid
184    *          (may be null)
185    */
186   public AlignViewport(AlignmentI al, HiddenColumns hiddenColumns,
187           String seqsetid, String viewid)
188   {
189     super(al);
190     sequenceSetID = seqsetid;
191     viewId = viewid;
192     // TODO remove these once 2.4.VAMSAS release finished
193     if (Cache.log != null && Cache.log.isDebugEnabled() && seqsetid != null)
194     {
195       Cache.log.debug("Setting viewport's sequence set id : "
196               + sequenceSetID);
197     }
198     if (Cache.log != null && Cache.log.isDebugEnabled() && viewId != null)
199     {
200       Cache.log.debug("Setting viewport's view id : " + viewId);
201     }
202
203     if (hiddenColumns != null)
204     {
205       al.setHiddenColumns(hiddenColumns);
206     }
207     init();
208   }
209
210   /**
211    * Apply any settings saved in user preferences
212    */
213   private void applyViewProperties()
214   {
215     antiAlias = Cache.getDefault("ANTI_ALIAS", false);
216
217     viewStyle.setShowJVSuffix(Cache.getDefault("SHOW_JVSUFFIX", true));
218     setShowAnnotation(Cache.getDefault("SHOW_ANNOTATIONS", true));
219
220     setRightAlignIds(Cache.getDefault("RIGHT_ALIGN_IDS", false));
221     setCentreColumnLabels(Cache.getDefault("CENTRE_COLUMN_LABELS", false));
222     autoCalculateConsensus = Cache.getDefault("AUTO_CALC_CONSENSUS", true);
223
224     setPadGaps(Cache.getDefault("PAD_GAPS", true));
225     setShowNPFeats(Cache.getDefault("SHOW_NPFEATS_TOOLTIP", true));
226     setShowDBRefs(Cache.getDefault("SHOW_DBREFS_TOOLTIP", true));
227     viewStyle.setSeqNameItalics(Cache.getDefault("ID_ITALICS", true));
228     viewStyle.setWrapAlignment(Cache.getDefault("WRAP_ALIGNMENT", false));
229     viewStyle.setShowUnconserved(Cache
230             .getDefault("SHOW_UNCONSERVED", false));
231     sortByTree = Cache.getDefault("SORT_BY_TREE", false);
232     followSelection = Cache.getDefault("FOLLOW_SELECTIONS", true);
233     sortAnnotationsBy = SequenceAnnotationOrder.valueOf(Cache.getDefault(
234             Preferences.SORT_ANNOTATIONS,
235             SequenceAnnotationOrder.NONE.name()));
236     showAutocalculatedAbove = Cache.getDefault(
237             Preferences.SHOW_AUTOCALC_ABOVE, false);
238     viewStyle.setScaleProteinAsCdna(Cache.getDefault(
239             Preferences.SCALE_PROTEIN_TO_CDNA, true));
240   }
241
242   void init()
243   {
244     applyViewProperties();
245
246     String fontName = Cache.getDefault("FONT_NAME", "SansSerif");
247     String fontStyle = Cache.getDefault("FONT_STYLE", Font.PLAIN + "");
248     String fontSize = Cache.getDefault("FONT_SIZE", "10");
249
250     int style = 0;
251
252     if (fontStyle.equals("bold"))
253     {
254       style = 1;
255     }
256     else if (fontStyle.equals("italic"))
257     {
258       style = 2;
259     }
260
261     setFont(new Font(fontName, style, Integer.parseInt(fontSize)), true);
262
263     alignment
264             .setGapCharacter(Cache.getDefault("GAP_SYMBOL", "-").charAt(0));
265
266     // We must set conservation and consensus before setting colour,
267     // as Blosum and Clustal require this to be done
268     if (hconsensus == null && !isDataset)
269     {
270       if (!alignment.isNucleotide())
271       {
272         showConservation = Cache.getDefault("SHOW_CONSERVATION", true);
273         showQuality = Cache.getDefault("SHOW_QUALITY", true);
274         showGroupConservation = Cache.getDefault("SHOW_GROUP_CONSERVATION",
275                 false);
276       }
277       showConsensusHistogram = Cache.getDefault("SHOW_CONSENSUS_HISTOGRAM",
278               true);
279       showSequenceLogo = Cache.getDefault("SHOW_CONSENSUS_LOGO", false);
280       normaliseSequenceLogo = Cache.getDefault("NORMALISE_CONSENSUS_LOGO",
281               false);
282       showGroupConsensus = Cache.getDefault("SHOW_GROUP_CONSENSUS", false);
283       showConsensus = Cache.getDefault("SHOW_IDENTITY", true);
284
285       showOccupancy = Cache.getDefault(Preferences.SHOW_OCCUPANCY, true);
286     }
287     initAutoAnnotation();
288     String colourProperty = alignment.isNucleotide() ? 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.getColourScheme(
298             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   }
313
314   /**
315    * get the consensus sequence as displayed under the PID consensus annotation
316    * row.
317    * 
318    * @return consensus sequence as a new sequence object
319    */
320   public SequenceI getConsensusSeq()
321   {
322     if (consensus == null)
323     {
324       updateConsensus(null);
325     }
326     if (consensus == null)
327     {
328       return null;
329     }
330     StringBuffer seqs = new StringBuffer();
331     for (int i = 0; i < consensus.annotations.length; i++)
332     {
333       if (consensus.annotations[i] != null)
334       {
335         if (consensus.annotations[i].description.charAt(0) == '[')
336         {
337           seqs.append(consensus.annotations[i].description.charAt(1));
338         }
339         else
340         {
341           seqs.append(consensus.annotations[i].displayCharacter);
342         }
343       }
344     }
345
346     SequenceI sq = new Sequence("Consensus", seqs.toString());
347     sq.setDescription("Percentage Identity Consensus "
348             + ((ignoreGapsInConsensusCalculation) ? " without gaps" : ""));
349     return sq;
350   }
351
352   boolean validCharWidth;
353
354   /**
355    * {@inheritDoc}
356    */
357   @Override
358   public void setFont(Font f, boolean setGrid)
359   {
360     font = f;
361
362     Container c = new Container();
363
364     if (setGrid)
365     {
366       FontMetrics fm = c.getFontMetrics(font);
367       int ww = fm.charWidth('M');
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(TreeModel tree)
495   {
496     currentTree = tree;
497   }
498
499   /**
500    * DOCUMENT ME!
501    * 
502    * @return DOCUMENT ME!
503    */
504   public TreeModel 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 = alignment.getHiddenColumns().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()),
601                     new HiddenColumns(getAlignment().getHiddenColumns()),
602                     this);
603   }
604
605   /**
606    * return the alignPanel containing the given viewport. Use this to get the
607    * components currently handling the given viewport.
608    * 
609    * @param av
610    * @return null or an alignPanel guaranteed to have non-null alignFrame
611    *         reference
612    */
613   public AlignmentPanel getAlignPanel()
614   {
615     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(this
616             .getSequenceSetId());
617     for (int p = 0; aps != null && p < aps.length; p++)
618     {
619       if (aps[p].av == this)
620       {
621         return aps[p];
622       }
623     }
624     return null;
625   }
626
627   public boolean getSortByTree()
628   {
629     return sortByTree;
630   }
631
632   public void setSortByTree(boolean sort)
633   {
634     sortByTree = sort;
635   }
636
637   /**
638    * Returns the (Desktop) instance of the StructureSelectionManager
639    */
640   @Override
641   public StructureSelectionManager getStructureSelectionManager()
642   {
643     return StructureSelectionManager
644             .getStructureSelectionManager(Desktop.instance);
645   }
646
647   /**
648    * 
649    * @param pdbEntries
650    * @return an array of SequenceI arrays, one for each PDBEntry, listing which
651    *         sequences in the alignment hold a reference to it
652    */
653   public SequenceI[][] collateForPDB(PDBEntry[] pdbEntries)
654   {
655     List<SequenceI[]> seqvectors = new ArrayList<>();
656     for (PDBEntry pdb : pdbEntries)
657     {
658       List<SequenceI> choosenSeqs = new ArrayList<>();
659       for (SequenceI sq : alignment.getSequences())
660       {
661         Vector<PDBEntry> pdbRefEntries = sq.getDatasetSequence()
662                 .getAllPDBEntries();
663         if (pdbRefEntries == null)
664         {
665           continue;
666         }
667         for (PDBEntry pdbRefEntry : pdbRefEntries)
668         {
669           if (pdbRefEntry.getId().equals(pdb.getId()))
670           {
671             if (pdbRefEntry.getChainCode() != null
672                     && pdb.getChainCode() != null)
673             {
674               if (pdbRefEntry.getChainCode().equalsIgnoreCase(
675                       pdb.getChainCode())
676                       && !choosenSeqs.contains(sq))
677               {
678                 choosenSeqs.add(sq);
679                 continue;
680               }
681             }
682             else
683             {
684               if (!choosenSeqs.contains(sq))
685               {
686                 choosenSeqs.add(sq);
687                 continue;
688               }
689             }
690
691           }
692         }
693       }
694       seqvectors
695               .add(choosenSeqs.toArray(new SequenceI[choosenSeqs.size()]));
696     }
697     return seqvectors.toArray(new SequenceI[seqvectors.size()][]);
698   }
699
700   @Override
701   public boolean isNormaliseSequenceLogo()
702   {
703     return normaliseSequenceLogo;
704   }
705
706   public void setNormaliseSequenceLogo(boolean state)
707   {
708     normaliseSequenceLogo = state;
709   }
710
711   public void setNormaliseHMMSequenceLogo(boolean state)
712   {
713     normaliseHMMSequenceLogo = state;
714   }
715
716   /**
717    * 
718    * @return true if alignment characters should be displayed
719    */
720   @Override
721   public boolean isValidCharWidth()
722   {
723     return validCharWidth;
724   }
725
726   private Hashtable<String, AutoCalcSetting> calcIdParams = new Hashtable<>();
727
728   public AutoCalcSetting getCalcIdSettingsFor(String calcId)
729   {
730     return calcIdParams.get(calcId);
731   }
732
733   public void setCalcIdSettingsFor(String calcId, AutoCalcSetting settings,
734           boolean needsUpdate)
735   {
736     calcIdParams.put(calcId, settings);
737     // TODO: create a restart list to trigger any calculations that need to be
738     // restarted after load
739     // calculator.getRegisteredWorkersOfClass(settings.getWorkerClass())
740     if (needsUpdate)
741     {
742       Cache.log.debug("trigger update for " + calcId);
743     }
744   }
745
746   /**
747    * Method called when another alignment's edit (or possibly other) command is
748    * broadcast to here.
749    *
750    * To allow for sequence mappings (e.g. protein to cDNA), we have to first
751    * 'unwind' the command on the source sequences (in simulation, not in fact),
752    * and then for each edit in turn:
753    * <ul>
754    * <li>compute the equivalent edit on the mapped sequences</li>
755    * <li>apply the mapped edit</li>
756    * <li>'apply' the source edit to the working copy of the source sequences</li>
757    * </ul>
758    * 
759    * @param command
760    * @param undo
761    * @param ssm
762    */
763   @Override
764   public void mirrorCommand(CommandI command, boolean undo,
765           StructureSelectionManager ssm, VamsasSource source)
766   {
767     /*
768      * Do nothing unless we are a 'complement' of the source. May replace this
769      * with direct calls not via SSM.
770      */
771     if (source instanceof AlignViewportI
772             && ((AlignViewportI) source).getCodingComplement() == this)
773     {
774       // ok to continue;
775     }
776     else
777     {
778       return;
779     }
780
781     CommandI mappedCommand = ssm.mapCommand(command, undo, getAlignment(),
782             getGapCharacter());
783     if (mappedCommand != null)
784     {
785       AlignmentI[] views = getAlignPanel().alignFrame.getViewAlignments();
786       mappedCommand.doCommand(views);
787       getAlignPanel().alignmentChanged();
788     }
789   }
790
791   /**
792    * Add the sequences from the given alignment to this viewport. Optionally,
793    * may give the user the option to open a new frame, or split panel, with cDNA
794    * and protein linked.
795    * 
796    * @param toAdd
797    * @param title
798    */
799   public void addAlignment(AlignmentI toAdd, String title)
800   {
801     // TODO: promote to AlignViewportI? applet CutAndPasteTransfer is different
802
803     // JBPComment: title is a largely redundant parameter at the moment
804     // JBPComment: this really should be an 'insert/pre/append' controller
805     // JBPComment: but the DNA/Protein check makes it a bit more complex
806
807     // refactored from FileLoader / CutAndPasteTransfer / SequenceFetcher with
808     // this comment:
809     // TODO: create undo object for this JAL-1101
810
811     /*
812      * Ensure datasets are created for the new alignment as
813      * mappings operate on dataset sequences
814      */
815     toAdd.setDataset(null);
816
817     /*
818      * Check if any added sequence could be the object of a mapping or
819      * cross-reference; if so, make the mapping explicit 
820      */
821     getAlignment().realiseMappings(toAdd.getSequences());
822
823     /*
824      * If any cDNA/protein mappings exist or can be made between the alignments, 
825      * offer to open a split frame with linked alignments
826      */
827     if (Cache.getDefault(Preferences.ENABLE_SPLIT_FRAME, true))
828     {
829       if (AlignmentUtils.isMappable(toAdd, getAlignment()))
830       {
831         if (openLinkedAlignment(toAdd, title))
832         {
833           return;
834         }
835       }
836     }
837
838     /*
839      * No mappings, or offer declined - add sequences to this alignment
840      */
841     // TODO: JAL-407 regardless of above - identical sequences (based on ID and
842     // provenance) should share the same dataset sequence
843
844     AlignmentI al = getAlignment();
845     String gap = String.valueOf(al.getGapCharacter());
846     for (int i = 0; i < toAdd.getHeight(); i++)
847     {
848       SequenceI seq = toAdd.getSequenceAt(i);
849       /*
850        * experimental!
851        * - 'align' any mapped sequences as per existing 
852        *    e.g. cdna to genome, domain hit to protein sequence
853        * very experimental! (need a separate menu option for this)
854        * - only add mapped sequences ('select targets from a dataset')
855        */
856       if (true /*AlignmentUtils.alignSequenceAs(seq, al, gap, true, true)*/)
857       {
858         al.addSequence(seq);
859       }
860     }
861
862     ranges.setEndSeq(getAlignment().getHeight());
863     firePropertyChange("alignment", null, getAlignment().getSequences());
864   }
865
866   /**
867    * Show a dialog with the option to open and link (cDNA <-> protein) as a new
868    * alignment, either as a standalone alignment or in a split frame. Returns
869    * true if the new alignment was opened, false if not, because the user
870    * declined the offer.
871    * 
872    * @param al
873    * @param title
874    */
875   protected boolean openLinkedAlignment(AlignmentI al, String title)
876   {
877     String[] options = new String[] {
878         MessageManager.getString("action.no"),
879         MessageManager.getString("label.split_window"),
880         MessageManager.getString("label.new_window"), };
881     final String question = JvSwingUtils.wrapTooltip(true,
882             MessageManager.getString("label.open_split_window?"));
883     int response = JvOptionPane.showOptionDialog(Desktop.desktop, question,
884             MessageManager.getString("label.open_split_window"),
885             JvOptionPane.DEFAULT_OPTION, JvOptionPane.PLAIN_MESSAGE, null,
886             options, options[0]);
887
888     if (response != 1 && response != 2)
889     {
890       return false;
891     }
892     final boolean openSplitPane = (response == 1);
893     final boolean openInNewWindow = (response == 2);
894
895     /*
896      * Identify protein and dna alignments. Make a copy of this one if opening
897      * in a new split pane.
898      */
899     AlignmentI thisAlignment = openSplitPane ? new Alignment(getAlignment())
900             : getAlignment();
901     AlignmentI protein = al.isNucleotide() ? thisAlignment : al;
902     final AlignmentI cdna = al.isNucleotide() ? al : thisAlignment;
903
904     /*
905      * Map sequences. At least one should get mapped as we have already passed
906      * the test for 'mappability'. Any mappings made will be added to the
907      * protein alignment. Note creating dataset sequences on the new alignment
908      * is a pre-requisite for building mappings.
909      */
910     al.setDataset(null);
911     AlignmentUtils.mapProteinAlignmentToCdna(protein, cdna);
912
913     /*
914      * Create the AlignFrame for the added alignment. If it is protein, mappings
915      * are registered with StructureSelectionManager as a side-effect.
916      */
917     AlignFrame newAlignFrame = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
918             AlignFrame.DEFAULT_HEIGHT);
919     newAlignFrame.setTitle(title);
920     newAlignFrame.statusBar.setText(MessageManager.formatMessage(
921             "label.successfully_loaded_file", new Object[] { title }));
922
923     // TODO if we want this (e.g. to enable reload of the alignment from file),
924     // we will need to add parameters to the stack.
925     // if (!protocol.equals(DataSourceType.PASTE))
926     // {
927     // alignFrame.setFileName(file, format);
928     // }
929
930     if (openInNewWindow)
931     {
932       Desktop.addInternalFrame(newAlignFrame, title,
933               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
934     }
935
936     try
937     {
938       newAlignFrame.setMaximum(jalview.bin.Cache.getDefault(
939               "SHOW_FULLSCREEN", false));
940     } catch (java.beans.PropertyVetoException ex)
941     {
942     }
943
944     if (openSplitPane)
945     {
946       al.alignAs(thisAlignment);
947       protein = openSplitFrame(newAlignFrame, thisAlignment);
948     }
949
950     return true;
951   }
952
953   /**
954    * Helper method to open a new SplitFrame holding linked dna and protein
955    * alignments.
956    * 
957    * @param newAlignFrame
958    *          containing a new alignment to be shown
959    * @param complement
960    *          cdna/protein complement alignment to show in the other split half
961    * @return the protein alignment in the split frame
962    */
963   protected AlignmentI openSplitFrame(AlignFrame newAlignFrame,
964           AlignmentI complement)
965   {
966     /*
967      * Make a new frame with a copy of the alignment we are adding to. If this
968      * is protein, the mappings to cDNA will be registered with
969      * StructureSelectionManager as a side-effect.
970      */
971     AlignFrame copyMe = new AlignFrame(complement,
972             AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
973     copyMe.setTitle(getAlignPanel().alignFrame.getTitle());
974
975     AlignmentI al = newAlignFrame.viewport.getAlignment();
976     final AlignFrame proteinFrame = al.isNucleotide() ? copyMe
977             : newAlignFrame;
978     final AlignFrame cdnaFrame = al.isNucleotide() ? newAlignFrame : copyMe;
979     cdnaFrame.setVisible(true);
980     proteinFrame.setVisible(true);
981     String linkedTitle = MessageManager
982             .getString("label.linked_view_title");
983
984     /*
985      * Open in split pane. DNA sequence above, protein below.
986      */
987     JInternalFrame splitFrame = new SplitFrame(cdnaFrame, proteinFrame);
988     Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
989
990     return proteinFrame.viewport.getAlignment();
991   }
992
993   public AnnotationColumnChooser getAnnotationColumnSelectionState()
994   {
995     return annotationColumnSelectionState;
996   }
997
998   public void setAnnotationColumnSelectionState(
999           AnnotationColumnChooser currentAnnotationColumnSelectionState)
1000   {
1001     this.annotationColumnSelectionState = currentAnnotationColumnSelectionState;
1002   }
1003
1004   @Override
1005   public void setIdWidth(int i)
1006   {
1007     super.setIdWidth(i);
1008     AlignmentPanel ap = getAlignPanel();
1009     if (ap != null)
1010     {
1011       // modify GUI elements to reflect geometry change
1012       Dimension idw = getAlignPanel().getIdPanel().getIdCanvas()
1013               .getPreferredSize();
1014       idw.width = i;
1015       getAlignPanel().getIdPanel().getIdCanvas().setPreferredSize(idw);
1016     }
1017   }
1018
1019   public Rectangle getExplodedGeometry()
1020   {
1021     return explodedGeometry;
1022   }
1023
1024   public void setExplodedGeometry(Rectangle explodedPosition)
1025   {
1026     this.explodedGeometry = explodedPosition;
1027   }
1028
1029   public boolean isGatherViewsHere()
1030   {
1031     return gatherViewsHere;
1032   }
1033
1034   public void setGatherViewsHere(boolean gatherViewsHere)
1035   {
1036     this.gatherViewsHere = gatherViewsHere;
1037   }
1038
1039   /**
1040    * If this viewport has a (Protein/cDNA) complement, then scroll the
1041    * complementary alignment to match this one.
1042    */
1043   public void scrollComplementaryAlignment()
1044   {
1045     /*
1046      * Populate a SearchResults object with the mapped location to scroll to. If
1047      * there is no complement, or it is not following highlights, or no mapping
1048      * is found, the result will be empty.
1049      */
1050     SearchResultsI sr = new SearchResults();
1051     int verticalOffset = findComplementScrollTarget(sr);
1052     if (!sr.isEmpty())
1053     {
1054       // TODO would like next line without cast but needs more refactoring...
1055       final AlignmentPanel complementPanel = ((AlignViewport) getCodingComplement())
1056               .getAlignPanel();
1057       complementPanel.setToScrollComplementPanel(false);
1058       complementPanel.scrollToCentre(sr, verticalOffset);
1059       complementPanel.setToScrollComplementPanel(true);
1060     }
1061   }
1062
1063   /**
1064    * Answers true if no alignment holds a reference to the given mapping
1065    * 
1066    * @param acf
1067    * @return
1068    */
1069   protected boolean noReferencesTo(AlignedCodonFrame acf)
1070   {
1071     AlignFrame[] frames = Desktop.getAlignFrames();
1072     if (frames == null)
1073     {
1074       return true;
1075     }
1076     for (AlignFrame af : frames)
1077     {
1078       if (!af.isClosed())
1079       {
1080         for (AlignmentViewPanel ap : af.getAlignPanels())
1081         {
1082           AlignmentI al = ap.getAlignment();
1083           if (al != null && al.getCodonFrames().contains(acf))
1084           {
1085             return false;
1086           }
1087         }
1088       }
1089     }
1090     return true;
1091   }
1092
1093   /**
1094    * Applies the supplied feature settings descriptor to currently known
1095    * features. This supports an 'initial configuration' of feature colouring
1096    * based on a preset or user favourite. This may then be modified in the usual
1097    * way using the Feature Settings dialogue.
1098    * 
1099    * @param featureSettings
1100    */
1101   @Override
1102   public void applyFeaturesStyle(FeatureSettingsModelI featureSettings)
1103   {
1104     if (featureSettings == null)
1105     {
1106       return;
1107     }
1108
1109     FeatureRenderer fr = getAlignPanel().getSeqPanel().seqCanvas
1110             .getFeatureRenderer();
1111     fr.findAllFeatures(true);
1112     List<String> renderOrder = fr.getRenderOrder();
1113     FeaturesDisplayedI displayed = fr.getFeaturesDisplayed();
1114     displayed.clear();
1115     // TODO this clears displayed.featuresRegistered - do we care?
1116
1117     /*
1118      * set feature colour if specified by feature settings
1119      * set visibility of all features
1120      */
1121     for (String type : renderOrder)
1122     {
1123       FeatureColourI preferredColour = featureSettings
1124               .getFeatureColour(type);
1125       if (preferredColour != null)
1126       {
1127         fr.setColour(type, preferredColour);
1128       }
1129       if (featureSettings.isFeatureDisplayed(type))
1130       {
1131         displayed.setVisible(type);
1132       }
1133     }
1134
1135     /*
1136      * set visibility of feature groups
1137      */
1138     for (String group : fr.getFeatureGroups())
1139     {
1140       fr.setGroupVisibility(group, featureSettings.isGroupDisplayed(group));
1141     }
1142
1143     /*
1144      * order the features
1145      */
1146     if (featureSettings.optimiseOrder())
1147     {
1148       // TODO not supported (yet?)
1149     }
1150     else
1151     {
1152       fr.orderFeatures(featureSettings);
1153     }
1154     fr.setTransparency(featureSettings.getTransparency());
1155   }
1156
1157   @Override
1158   public boolean isNormaliseHMMSequenceLogo()
1159   {
1160     // TODO Auto-generated method stub
1161     return normaliseHMMSequenceLogo;
1162   }
1163
1164 }