JAL-3509 JAL-1842 minor tidying of code
[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     JalviewFileChooser chooser = new JalviewFileChooser(
139             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
140
141     chooser.setAcceptAllFileFilterUsed(false);
142     chooser.setFileView(new JalviewFileView());
143     chooser.setDialogTitle(
144             MessageManager.getString("label.save_text_to_file"));
145     chooser.setToolTipText(MessageManager.getString("action.save"));
146
147     int value = chooser.showSaveDialog(this);
148
149     if (value == JalviewFileChooser.APPROVE_OPTION)
150     {
151       try
152       {
153         PrintWriter out = new PrintWriter(
154                 new FileWriter(chooser.getSelectedFile()));
155
156         out.print(getText());
157         out.close();
158       } catch (Exception ex)
159       {
160         ex.printStackTrace();
161       }
162
163     }
164   }
165
166   /**
167    * DOCUMENT ME!
168    * 
169    * @param e
170    *          DOCUMENT ME!
171    */
172   @Override
173   public void copyItem_actionPerformed(ActionEvent e)
174   {
175     textarea.getSelectedText();
176     Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
177     c.setContents(new StringSelection(textarea.getSelectedText()), null);
178   }
179
180   /**
181    * DOCUMENT ME!
182    * 
183    * @param e
184    *          DOCUMENT ME!
185    */
186   @Override
187   public void pasteMenu_actionPerformed(ActionEvent e)
188   {
189     Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
190     Transferable contents = c.getContents(this);
191
192     if (contents == null)
193     {
194       return;
195     }
196
197     try
198     {
199       textarea.append(
200               (String) contents.getTransferData(DataFlavor.stringFlavor));
201     } catch (Exception ex)
202     {
203     }
204   }
205
206   /**
207    * DOCUMENT ME!
208    * 
209    * @param e
210    *          DOCUMENT ME!
211    */
212   @Override
213   public void ok_actionPerformed(ActionEvent e)
214   {
215     String text = getText();
216     if (text.trim().length() < 1)
217     {
218       return;
219     }
220
221     FileFormatI format = null;
222     try
223     {
224       format = new IdentifyFile().identify(text, DataSourceType.PASTE);
225     } catch (FileFormatException e1)
226     {
227       // leave as null
228     }
229     if (format == null)
230     {
231       System.err
232               .println(MessageManager.getString("label.couldnt_read_data"));
233       if (!Jalview.isHeadlessMode())
234       {
235         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
236                 AppletFormatAdapter.getSupportedFormats(),
237                 MessageManager.getString("label.couldnt_read_data"),
238                 JvOptionPane.WARNING_MESSAGE);
239       }
240       return;
241     }
242
243     // TODO: identify feature, annotation or tree file and parse appropriately.
244     AlignmentI al = null;
245
246     try
247     {
248       FormatAdapter fa = new FormatAdapter(alignpanel);
249       al = fa.readFile(getText(), DataSourceType.PASTE, format);
250       source = fa.getAlignFile();
251
252     } catch (IOException ex)
253     {
254       JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
255               .formatMessage("label.couldnt_read_pasted_text", new String[]
256               { ex.toString() }),
257               MessageManager.getString("label.error_parsing_text"),
258               JvOptionPane.WARNING_MESSAGE);
259     }
260
261     if (al != null && al.hasValidSequence())
262     {
263       String title = MessageManager
264               .formatMessage("label.input_cut_paste_params", new String[]
265               { format.getName() });
266       FeatureSettingsModelI proxyColourScheme = source
267               .getFeatureColourScheme();
268
269       /*
270        * if the view panel was closed its alignment is nulled
271        * and this is an orphaned cut and paste window
272        */
273       if (viewport != null && viewport.getAlignment() != null)
274       {
275         ((AlignViewport) viewport).addAlignment(al, title);
276         viewport.applyFeaturesStyle(proxyColourScheme);
277       }
278       else
279       {
280
281         AlignFrame af;
282         if (source instanceof ComplexAlignFile)
283         {
284           HiddenColumns hidden = ((ComplexAlignFile) source)
285                   .getHiddenColumns();
286           SequenceI[] hiddenSeqs = ((ComplexAlignFile) source)
287                   .getHiddenSequences();
288           boolean showSeqFeatures = ((ComplexAlignFile) source)
289                   .isShowSeqFeatures();
290           String colourSchemeName = ((ComplexAlignFile) source)
291                   .getGlobalColourScheme();
292           FeaturesDisplayedI fd = ((ComplexAlignFile) source)
293                   .getDisplayedFeatures();
294           af = new AlignFrame(al, hiddenSeqs, hidden,
295                   AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
296           af.getViewport().setShowSequenceFeatures(showSeqFeatures);
297           af.getViewport().setFeaturesDisplayed(fd);
298           af.setMenusForViewport();
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.setStatus(MessageManager
323                 .getString("label.successfully_pasted_alignment_file"));
324
325         try
326         {
327           af.setMaximum(
328                   jalview.bin.Cache.getDefault("SHOW_FULLSCREEN", false));
329         } catch (Exception ex)
330         {
331         }
332       }
333     }
334     else
335     {
336       System.err
337               .println(MessageManager.getString("label.couldnt_read_data"));
338       if (!Jalview.isHeadlessMode())
339       {
340         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
341                 AppletFormatAdapter.getSupportedFormats(),
342                 MessageManager.getString("label.couldnt_read_data"),
343                 JvOptionPane.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 }