JAL-1443 bugfix to prevent loading of unidentifiable gibberish data
[jalview.git] / src / jalview / gui / 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.gui;
22
23 import jalview.api.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.api.ComplexAlignFile;
26 import jalview.api.FeaturesDisplayedI;
27 import jalview.bin.Jalview;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.ColumnSelection;
30 import jalview.datamodel.SequenceI;
31 import jalview.io.FileParse;
32 import jalview.io.FormatAdapter;
33 import jalview.io.IdentifyFile;
34 import jalview.io.JalviewFileChooser;
35 import jalview.io.JalviewFileView;
36 import jalview.jbgui.GCutAndPasteTransfer;
37 import jalview.schemes.ColourSchemeI;
38 import jalview.util.MessageManager;
39
40 import java.awt.Toolkit;
41 import java.awt.datatransfer.Clipboard;
42 import java.awt.datatransfer.DataFlavor;
43 import java.awt.datatransfer.StringSelection;
44 import java.awt.datatransfer.Transferable;
45 import java.awt.event.ActionEvent;
46 import java.awt.event.ActionListener;
47 import java.awt.event.MouseEvent;
48
49 import javax.swing.JMenuItem;
50 import javax.swing.JOptionPane;
51 import javax.swing.JPopupMenu;
52 import javax.swing.SwingUtilities;
53
54 /**
55  * Cut'n'paste files into the desktop See JAL-1105
56  * 
57  * @author $author$
58  * @version $Revision$
59  */
60 public class CutAndPasteTransfer extends GCutAndPasteTransfer
61 {
62
63   AlignmentViewPanel alignpanel;
64
65   AlignViewportI viewport;
66
67   FileParse source = null;
68   public CutAndPasteTransfer()
69   {
70     SwingUtilities.invokeLater(new Runnable()
71     {
72       public void run()
73       {
74         textarea.requestFocus();
75       }
76     });
77
78   }
79
80   /**
81    * DOCUMENT ME!
82    */
83   public void setForInput(AlignmentViewPanel viewpanel)
84   {
85     this.alignpanel = viewpanel;
86     if (alignpanel != null)
87     {
88       this.viewport = alignpanel.getAlignViewport();
89     }
90     if (viewport != null)
91     {
92       ok.setText(MessageManager.getString("action.add"));
93     }
94
95     getContentPane().add(inputButtonPanel, java.awt.BorderLayout.SOUTH);
96   }
97
98   /**
99    * DOCUMENT ME!
100    * 
101    * @return DOCUMENT ME!
102    */
103   public String getText()
104   {
105     return textarea.getText();
106   }
107
108   /**
109    * DOCUMENT ME!
110    * 
111    * @param text
112    *          DOCUMENT ME!
113    */
114   public void setText(String text)
115   {
116     textarea.setText(text);
117   }
118
119   public void appendText(String text)
120   {
121     textarea.append(text);
122   }
123
124   public void save_actionPerformed(ActionEvent e)
125   {
126     JalviewFileChooser chooser = new JalviewFileChooser(
127             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
128
129     chooser.setAcceptAllFileFilterUsed(false);
130     chooser.setFileView(new JalviewFileView());
131     chooser.setDialogTitle(MessageManager.getString("label.save_text_to_file"));
132     chooser.setToolTipText(MessageManager.getString("action.save"));
133
134     int value = chooser.showSaveDialog(this);
135
136     if (value == JalviewFileChooser.APPROVE_OPTION)
137     {
138       try
139       {
140         java.io.PrintWriter out = new java.io.PrintWriter(
141                 new java.io.FileWriter(chooser.getSelectedFile()));
142
143         out.print(getText());
144         out.close();
145       } catch (Exception ex)
146       {
147         ex.printStackTrace();
148       }
149
150     }
151   }
152
153   /**
154    * DOCUMENT ME!
155    * 
156    * @param e
157    *          DOCUMENT ME!
158    */
159   public void copyItem_actionPerformed(ActionEvent e)
160   {
161     textarea.getSelectedText();
162     Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
163     c.setContents(new StringSelection(textarea.getSelectedText()), null);
164   }
165
166   /**
167    * DOCUMENT ME!
168    * 
169    * @param e
170    *          DOCUMENT ME!
171    */
172   public void pasteMenu_actionPerformed(ActionEvent e)
173   {
174     Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
175     Transferable contents = c.getContents(this);
176
177     if (contents == null)
178     {
179       return;
180     }
181
182     try
183     {
184       textarea.append((String) contents
185               .getTransferData(DataFlavor.stringFlavor));
186     } catch (Exception ex)
187     {
188     }
189   }
190
191   /**
192    * DOCUMENT ME!
193    * 
194    * @param e
195    *          DOCUMENT ME!
196    */
197   public void ok_actionPerformed(ActionEvent e)
198   {
199     String text = getText();
200     if (text.trim().length() < 1)
201     {
202       return;
203     }
204
205     String format = new IdentifyFile().Identify(text, "Paste");
206     if (format == null || format.equalsIgnoreCase("EMPTY DATA FILE"))
207     {
208       System.err.println(MessageManager
209               .getString("label.null_or_unidentifiable_data"));
210       if (!Jalview.isHeadlessMode())
211       {
212         JOptionPane.showMessageDialog(null,
213  MessageManager
214                 .getString("label.null_or_unidentifiable_data"),
215                 MessageManager.getString("label.unidentifiable_data"),
216                 JOptionPane.ERROR_MESSAGE);
217       }
218       return;
219     }
220
221     // TODO: identify feature, annotation or tree file and parse appropriately.
222     AlignmentI al = null;
223
224     if (FormatAdapter.isValidFormat(format))
225     {
226       try
227       {
228         FormatAdapter fa = new FormatAdapter(alignpanel);
229         al = fa.readFile(getText(), "Paste", format);
230         source = fa.getAlignFile();
231
232       } catch (java.io.IOException ex)
233       {
234         JOptionPane.showInternalMessageDialog(Desktop.desktop,
235                 MessageManager.formatMessage(
236                         "label.couldnt_read_pasted_text", new String[]
237                         { ex.toString() }), MessageManager
238                         .getString("label.error_parsing_text"),
239                 JOptionPane.WARNING_MESSAGE);
240       }
241     }
242
243     if (al != null && al.hasValidSequence())
244     {
245       String title = MessageManager.formatMessage(
246               "label.input_cut_paste_params", new String[]
247               { format });
248       if (viewport != null)
249       {
250         ((AlignViewport) viewport).addAlignment(al, title);
251       }
252       else
253       {
254
255         AlignFrame af;
256         if (source instanceof ComplexAlignFile)
257         {
258           ColumnSelection colSel = ((ComplexAlignFile) source)
259                   .getColumnSelection();
260           SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
261                   .getHiddenSequences();
262           boolean showSeqFeatures = ((ComplexAlignFile) source)
263                   .isShowSeqFeatures();
264           ColourSchemeI cs = ((ComplexAlignFile) source).getColourScheme();
265           FeaturesDisplayedI fd = ((ComplexAlignFile) source)
266                   .getDisplayedFeatures();
267           af = new AlignFrame(al, hiddenSeqs, colSel,
268                   AlignFrame.DEFAULT_WIDTH,
269                   AlignFrame.DEFAULT_HEIGHT);
270           af.getViewport().setShowSequenceFeatures(showSeqFeatures);
271           af.getViewport().setFeaturesDisplayed(fd);
272           af.changeColour(cs);
273         }
274         else
275         {
276           af = new AlignFrame(al, AlignFrame.DEFAULT_WIDTH,
277                   AlignFrame.DEFAULT_HEIGHT);
278         }
279
280         af.currentFileFormat = format;
281         Desktop.addInternalFrame(af, title, AlignFrame.DEFAULT_WIDTH,
282                 AlignFrame.DEFAULT_HEIGHT);
283         af.statusBar.setText(MessageManager
284                 .getString("label.successfully_pasted_alignment_file"));
285
286         try
287         {
288           af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN",
289                   false));
290         } catch (Exception ex)
291         {
292         }
293       }
294     }
295     else
296     {
297       System.err.println(MessageManager
298               .getString("label.null_or_invalid_alignment"));
299       if (!Jalview.isHeadlessMode())
300       {
301         JOptionPane
302                 .showMessageDialog(
303                         null,
304                         MessageManager
305                                 .getString("label.null_or_invalid_alignment"),
306                         MessageManager
307                                 .getString("label.unable_to_create_alignment"),
308                         JOptionPane.ERROR_MESSAGE);
309       }
310     }
311   }
312
313
314   /**
315    * DOCUMENT ME!
316    * 
317    * @param e
318    *          DOCUMENT ME!
319    */
320   public void cancel_actionPerformed(ActionEvent e)
321   {
322     try
323     {
324       this.setClosed(true);
325     } catch (Exception ex)
326     {
327     }
328   }
329
330   public void textarea_mousePressed(MouseEvent e)
331   {
332     if (SwingUtilities.isRightMouseButton(e))
333     {
334       JPopupMenu popup = new JPopupMenu(
335               MessageManager.getString("action.edit"));
336       JMenuItem item = new JMenuItem(
337               MessageManager.getString("action.copy"));
338       item.addActionListener(new ActionListener()
339       {
340         public void actionPerformed(ActionEvent e)
341         {
342           copyItem_actionPerformed(e);
343         }
344       });
345       popup.add(item);
346       item = new JMenuItem(MessageManager.getString("action.paste"));
347       item.addActionListener(new ActionListener()
348       {
349         public void actionPerformed(ActionEvent e)
350         {
351           pasteMenu_actionPerformed(e);
352         }
353       });
354       popup.add(item);
355       popup.show(this, e.getX() + 10, e.getY() + textarea.getY() + 40);
356
357     }
358   }
359
360 }