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