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