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