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