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