JAL-845 refinements + tests for making mappings between alignments
[jalview.git] / src / jalview / appletgui / CutAndPasteTransfer.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.appletgui;
22
23 import jalview.analysis.AlignmentUtils;
24 import jalview.bin.JalviewLite;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.Sequence;
29 import jalview.io.AnnotationFile;
30 import jalview.io.AppletFormatAdapter;
31 import jalview.io.IdentifyFile;
32 import jalview.io.NewickFile;
33 import jalview.io.TCoffeeScoreFile;
34 import jalview.schemes.TCoffeeColourScheme;
35 import jalview.util.MessageManager;
36
37 import java.awt.BorderLayout;
38 import java.awt.Button;
39 import java.awt.Dialog;
40 import java.awt.Font;
41 import java.awt.Frame;
42 import java.awt.Label;
43 import java.awt.Panel;
44 import java.awt.TextArea;
45 import java.awt.event.ActionEvent;
46 import java.awt.event.ActionListener;
47 import java.awt.event.MouseEvent;
48 import java.awt.event.MouseListener;
49
50 public class CutAndPasteTransfer extends Panel implements ActionListener,
51         MouseListener
52 {
53   boolean pdbImport = false;
54
55   boolean treeImport = false;
56
57   boolean annotationImport = false;
58
59   Sequence seq;
60
61   AlignFrame alignFrame;
62
63   public CutAndPasteTransfer(boolean forImport, AlignFrame alignFrame)
64   {
65     try
66     {
67       jbInit();
68     } catch (Exception e)
69     {
70       e.printStackTrace();
71     }
72
73     this.alignFrame = alignFrame;
74
75     if (!forImport)
76     {
77       buttonPanel.setVisible(false);
78     }
79   }
80
81   public String getText()
82   {
83     return textarea.getText();
84   }
85
86   public void setText(String text)
87   {
88     textarea.setText(text);
89   }
90
91   public void setPDBImport(Sequence seq)
92   {
93     this.seq = seq;
94     accept.setLabel(MessageManager.getString("action.accept"));
95     addSequences.setVisible(false);
96     pdbImport = true;
97   }
98
99   public void setTreeImport()
100   {
101     treeImport = true;
102     accept.setLabel(MessageManager.getString("action.accept"));
103     addSequences.setVisible(false);
104   }
105
106   public void setAnnotationImport()
107   {
108     annotationImport = true;
109     accept.setLabel(MessageManager.getString("action.accept"));
110     addSequences.setVisible(false);
111   }
112
113   public void actionPerformed(ActionEvent evt)
114   {
115     if (evt.getSource() == accept)
116     {
117       ok(true);
118     }
119     else if (evt.getSource() == addSequences)
120     {
121       ok(false);
122     }
123     else if (evt.getSource() == cancel)
124     {
125       cancel();
126     }
127   }
128
129   protected void ok(boolean newWindow)
130   {
131     String text = getText();
132     int length = text.length();
133     textarea.append("\n");
134     if (textarea.getText().length() == length)
135     {
136       String warning = "\n\n#################################################\n"
137               + "WARNING!! THIS IS THE MAXIMUM SIZE OF TEXTAREA!!\n"
138               + "\nCAN'T INPUT FULL ALIGNMENT"
139               + "\n\nYOU MUST DELETE THIS WARNING TO CONTINUE"
140               + "\n\nMAKE SURE LAST SEQUENCE PASTED IS COMPLETE"
141               + "\n#################################################\n";
142       textarea.setText(text.substring(0, text.length() - warning.length())
143               + warning);
144
145       textarea.setCaretPosition(text.length());
146     }
147
148     if (pdbImport)
149     {
150       openPdbViewer(text);
151
152     }
153     else if (treeImport)
154     {
155       if (!loadTree())
156       {
157         return;
158       }
159     }
160     else if (annotationImport)
161     {
162       loadAnnotations();
163     }
164     else if (alignFrame != null)
165     {
166       loadAlignment(text, newWindow);
167     }
168
169     // TODO: dialog should indicate if data was parsed correctly or not - see
170     // JAL-1102
171     if (this.getParent() instanceof Frame)
172     {
173       ((Frame) this.getParent()).setVisible(false);
174     }
175     else
176     {
177       ((Dialog) this.getParent()).setVisible(false);
178     }
179   }
180
181   /**
182    * Parses text as Newick Tree format, and loads on to the alignment. Returns
183    * true if successful, else false.
184    */
185   protected boolean loadTree()
186   {
187     try
188     {
189       NewickFile fin = new NewickFile(textarea.getText(), "Paste");
190
191       fin.parse();
192       if (fin.getTree() != null)
193       {
194         alignFrame.loadTree(fin, "Pasted tree file");
195         return true;
196       }
197     } catch (Exception ex)
198     {
199       // TODO: JAL-1102 - should have a warning message in dialog, not simply
200       // overwrite the broken input data with the exception
201       textarea.setText(MessageManager.formatMessage(
202               "label.could_not_parse_newick_file", new Object[]
203               { ex.getMessage() }));
204       return false;
205     }
206     return false;
207   }
208
209   /**
210    * Parse text as an alignment file and add to the current or a new window.
211    * 
212    * @param text
213    * @param newWindow
214    */
215   protected void loadAlignment(String text, boolean newWindow)
216   {
217     Alignment al = null;
218
219     String format = new IdentifyFile().Identify(text,
220             AppletFormatAdapter.PASTE);
221     try
222     {
223       al = new AppletFormatAdapter().readFile(text,
224               AppletFormatAdapter.PASTE, format);
225     } catch (java.io.IOException ex)
226     {
227       ex.printStackTrace();
228     }
229
230     if (al != null)
231     {
232       al.setDataset(null); // set dataset on alignment/sequences
233       if (openSplitFrame(al, format))
234       {
235         return;
236       }
237       if (newWindow)
238       {
239         AlignFrame af = new AlignFrame(al, alignFrame.viewport.applet,
240                 "Cut & Paste input - " + format, false);
241         af.statusBar
242                 .setText(MessageManager
243                         .getString("label.successfully_pasted_annotation_to_alignment"));
244       }
245       else
246       {
247         alignFrame.addSequences(al.getSequencesArray());
248         alignFrame.statusBar.setText(MessageManager
249                 .getString("label.successfully_pasted_alignment_file"));
250       }
251     }
252   }
253
254   /**
255    * Check whether the new alignment could be mapped to the current one as
256    * cDNA/protein, if so offer the option to open as split frame view. Returns
257    * true if a split frame view is opened, false if not.
258    * 
259    * @param al
260    * @return
261    */
262   protected boolean openSplitFrame(Alignment al, String format)
263   {
264     final AlignmentI thisAlignment = this.alignFrame.getAlignViewport().getAlignment();
265     if (thisAlignment.isNucleotide() == al.isNucleotide())
266     {
267       // both nucleotide or both protein
268       return false;
269     }
270     AlignmentI protein = thisAlignment.isNucleotide() ? al : thisAlignment;
271     AlignmentI dna = thisAlignment.isNucleotide() ? thisAlignment : al;
272     boolean mapped = AlignmentUtils.mapProteinToCdna(protein, dna);
273     if (!mapped)
274     {
275       return false;
276     }
277
278     /*
279      * A mapping is possible; ask user if they want a split frame.
280      */
281     String title = MessageManager.getString("label.open_split_window");
282     final JVDialog dialog = new JVDialog((Frame) this.getParent(), title,
283             true, 100, 400);
284     dialog.ok.setLabel(MessageManager.getString("action.yes"));
285     dialog.cancel.setLabel(MessageManager.getString("action.no"));
286     Panel question = new Panel(new BorderLayout());
287     final String text = MessageManager
288             .getString("label.open_split_window?");
289     question.add(new Label(text, Label.CENTER), BorderLayout.CENTER);
290     dialog.setMainPanel(question);
291     dialog.setVisible(true);
292     dialog.toFront();
293     
294     if (!dialog.accept)
295     {
296       return false;
297     }
298
299     /*
300      * Open SplitFrame with DNA above and protein below, including the alignment
301      * from textbox and a copy of the original.
302      */
303     final JalviewLite applet = this.alignFrame.viewport.applet;
304     AlignFrame copyFrame = new AlignFrame(
305             this.alignFrame.viewport.getAlignment(), applet,
306             alignFrame.getTitle(), false, false);
307     AlignFrame newFrame = new AlignFrame(al, alignFrame.viewport.applet,
308             "Cut & Paste input - " + format, false, false);
309     AlignFrame dnaFrame = al.isNucleotide() ? newFrame : copyFrame;
310     AlignFrame proteinFrame = al.isNucleotide() ? copyFrame
311             : newFrame;
312     SplitFrame sf = new SplitFrame(dnaFrame, proteinFrame);
313     sf.addToDisplay(false, applet);
314     return true;
315   }
316
317   /**
318    * Parse the text as a TCoffee score file, if successful add scores as
319    * alignment annotations.
320    */
321   protected void loadAnnotations()
322   {
323     TCoffeeScoreFile tcf = null;
324     try
325     {
326       tcf = new TCoffeeScoreFile(textarea.getText(),
327               jalview.io.AppletFormatAdapter.PASTE);
328       if (tcf.isValid())
329       {
330         if (tcf.annotateAlignment(alignFrame.viewport.getAlignment(),
331                 true))
332         {
333           alignFrame.tcoffeeColour.setEnabled(true);
334           alignFrame.alignPanel.fontChanged();
335           alignFrame.changeColour(new TCoffeeColourScheme(
336                   alignFrame.viewport.getAlignment()));
337           alignFrame.statusBar
338                   .setText(MessageManager
339                           .getString("label.successfully_pasted_tcoffee_scores_to_alignment"));
340         }
341         else
342         {
343           // file valid but didn't get added to alignment for some reason
344           alignFrame.statusBar.setText(MessageManager.formatMessage(
345                   "label.failed_add_tcoffee_scores",
346                   new Object[]
347                   { (tcf.getWarningMessage() != null ? tcf
348                           .getWarningMessage() : "") }));
349         }
350       }
351       else
352       {
353         tcf = null;
354       }
355     } catch (Exception x)
356     {
357       tcf = null;
358     }
359     if (tcf == null)
360     {
361       if (new AnnotationFile().annotateAlignmentView(alignFrame.viewport,
362               textarea.getText(),
363               jalview.io.AppletFormatAdapter.PASTE))
364       {
365         alignFrame.alignPanel.fontChanged();
366         alignFrame.alignPanel.setScrollValues(0, 0);
367         alignFrame.statusBar
368                 .setText(MessageManager
369                         .getString("label.successfully_pasted_annotation_to_alignment"));
370
371       }
372       else
373       {
374         if (!alignFrame.parseFeaturesFile(textarea.getText(),
375                 jalview.io.AppletFormatAdapter.PASTE))
376         {
377           alignFrame.statusBar
378                   .setText(MessageManager
379                           .getString("label.couldnt_parse_pasted_text_as_valid_annotation_feature_GFF_tcoffee_file"));
380         }
381       }
382     }
383   }
384
385   /**
386    * Open a Jmol viewer (if available), failing that the built-in PDB viewer,
387    * passing the input text as the PDB file data.
388    * 
389    * @param text
390    */
391   protected void openPdbViewer(String text)
392   {
393     PDBEntry pdb = new PDBEntry();
394     pdb.setFile(text);
395
396     if (alignFrame.alignPanel.av.applet.jmolAvailable)
397     {
398       new jalview.appletgui.AppletJmol(pdb, new Sequence[]
399       { seq }, null, alignFrame.alignPanel, AppletFormatAdapter.PASTE);
400     }
401     else
402     {
403       new MCview.AppletPDBViewer(pdb, new Sequence[]
404       { seq }, null, alignFrame.alignPanel, AppletFormatAdapter.PASTE);
405     }
406   }
407
408   protected void cancel()
409   {
410     textarea.setText("");
411     if (this.getParent() instanceof Frame)
412     {
413       ((Frame) this.getParent()).setVisible(false);
414     }
415     else
416     {
417       ((Dialog) this.getParent()).setVisible(false);
418     }
419   }
420
421   protected TextArea textarea = new TextArea();
422
423   Button accept = new Button("New Window");
424
425   Button addSequences = new Button("Add to Current Alignment");
426
427   Button cancel = new Button("Close");
428
429   protected Panel buttonPanel = new Panel();
430
431   BorderLayout borderLayout1 = new BorderLayout();
432
433   private void jbInit() throws Exception
434   {
435     textarea.setFont(new java.awt.Font("Monospaced", Font.PLAIN, 10));
436     textarea.setText(MessageManager
437             .getString("label.paste_your_alignment_file"));
438     textarea.addMouseListener(this);
439     this.setLayout(borderLayout1);
440     accept.addActionListener(this);
441     addSequences.addActionListener(this);
442     cancel.addActionListener(this);
443     this.add(buttonPanel, BorderLayout.SOUTH);
444     buttonPanel.add(accept, null);
445     buttonPanel.add(addSequences);
446     buttonPanel.add(cancel, null);
447     this.add(textarea, java.awt.BorderLayout.CENTER);
448   }
449
450   public void mousePressed(MouseEvent evt)
451   {
452     if (textarea.getText().startsWith(
453             MessageManager.getString("label.paste_your")))
454     {
455       textarea.setText("");
456     }
457   }
458
459   public void mouseReleased(MouseEvent evt)
460   {
461   }
462
463   public void mouseClicked(MouseEvent evt)
464   {
465   }
466
467   public void mouseEntered(MouseEvent evt)
468   {
469   }
470
471   public void mouseExited(MouseEvent evt)
472   {
473   }
474 }