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