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