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