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