updated to jalview 2.1 and begun ArchiveClient/VamsasClient/VamsasStore updates.
[jalview.git] / src / jalview / gui / Desktop.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21 import jalview.io.*;
22
23 import java.awt.*;
24 import java.awt.datatransfer.*;
25 import java.awt.dnd.*;
26 import java.awt.event.*;
27 import java.util.*;
28
29 import javax.swing.*;
30
31 import org.vamsas.test.simpleclient.ArchiveClient;
32
33 /**
34  * DOCUMENT ME!
35  *
36  * @author $author$
37  * @version $Revision$
38  */
39 public class Desktop extends jalview.jbgui.GDesktop
40     implements DropTargetListener, ClipboardOwner
41 {
42     /** DOCUMENT ME!! */
43     public static Desktop instance;
44     public static JDesktopPane desktop;
45     static int openFrameCount = 0;
46     static final int xOffset = 30;
47     static final int yOffset = 30;
48     public static jalview.ws.Discoverer discoverer;
49
50     public static Object [] jalviewClipboard;
51
52     static int fileLoadingCount= 0;
53
54     /**
55      * Creates a new Desktop object.
56      */
57     public Desktop()
58     {
59         instance = this;
60
61         Image image = null;
62
63         try
64         {
65             java.net.URL url = getClass().getResource("/images/logo.gif");
66
67             if (url != null)
68             {
69                 image = java.awt.Toolkit.getDefaultToolkit().createImage(url);
70
71                 MediaTracker mt = new MediaTracker(this);
72                 mt.addImage(image, 0);
73                 mt.waitForID(0);
74                 setIconImage(image);
75             }
76         }
77         catch (Exception ex)
78         {
79         }
80
81         setTitle("Jalview "+jalview.bin.Cache.getProperty("VERSION"));
82         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
83         desktop = new JDesktopPane();
84         desktop.setBackground(Color.white);
85         getContentPane().setLayout(new BorderLayout());
86         getContentPane().add(desktop, BorderLayout.CENTER);
87         desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
88
89         // This line prevents Windows Look&Feel resizing all new windows to maximum
90         // if previous window was maximised
91         desktop.setDesktopManager(new DefaultDesktopManager());
92
93         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
94         String x = jalview.bin.Cache.getProperty("SCREEN_X");
95         String y = jalview.bin.Cache.getProperty("SCREEN_Y");
96         String width = jalview.bin.Cache.getProperty("SCREEN_WIDTH");
97         String height = jalview.bin.Cache.getProperty("SCREEN_HEIGHT");
98
99         if ((x != null) && (y != null) && (width != null) && (height != null))
100         {
101             setBounds(Integer.parseInt(x), Integer.parseInt(y),
102                 Integer.parseInt(width), Integer.parseInt(height));
103         }
104         else
105         {
106             setBounds((int) (screenSize.width - 900) / 2,
107                 (int) (screenSize.height - 650) / 2, 900, 650);
108         }
109
110         this.addWindowListener(new WindowAdapter()
111             {
112                 public void windowClosing(WindowEvent evt)
113                 {
114                     quit();
115                 }
116             });
117
118         this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
119
120         /////////Add a splashscreen on startup
121         /////////Add a splashscreen on startup
122         JInternalFrame frame = new JInternalFrame();
123
124         SplashScreen splash = new SplashScreen(frame, image);
125         frame.setContentPane(splash);
126         frame.setLayer(JLayeredPane.PALETTE_LAYER);
127         frame.setLocation((int) ((getWidth() - 750) / 2),
128             (int) ((getHeight() - 160) / 2));
129
130         addInternalFrame(frame, "", 750, 160, false);
131
132         discoverer=new jalview.ws.Discoverer(); // Only gets started if gui is displayed.
133
134     }
135
136     /**
137      * DOCUMENT ME!
138      *
139      * @param frame DOCUMENT ME!
140      * @param title DOCUMENT ME!
141      * @param w DOCUMENT ME!
142      * @param h DOCUMENT ME!
143      */
144     public static synchronized void addInternalFrame(final JInternalFrame frame,
145         String title, int w, int h)
146     {
147         addInternalFrame(frame, title, w, h, true);
148     }
149
150     /**
151      * DOCUMENT ME!
152      *
153      * @param frame DOCUMENT ME!
154      * @param title DOCUMENT ME!
155      * @param w DOCUMENT ME!
156      * @param h DOCUMENT ME!
157      * @param resizable DOCUMENT ME!
158      */
159     public static synchronized void addInternalFrame(final JInternalFrame frame,
160         String title, int w, int h, boolean resizable)
161     {
162
163       frame.setTitle(title);
164       if(frame.getWidth()<1 || frame.getHeight()<1)
165       {
166         frame.setSize(w, h);
167       }
168       // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
169       // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
170       // IF JALVIEW IS RUNNING HEADLESS
171       /////////////////////////////////////////////////
172       if (System.getProperty("java.awt.headless") != null
173           && System.getProperty("java.awt.headless").equals("true"))
174       {
175         return;
176       }
177
178
179         openFrameCount++;
180
181         frame.setVisible(true);
182         frame.setClosable(true);
183         frame.setResizable(resizable);
184         frame.setMaximizable(resizable);
185         frame.setIconifiable(resizable);
186         frame.setFrameIcon(null);
187
188         if (frame.getX()<1 && frame.getY()<1)
189        {
190          frame.setLocation(xOffset * openFrameCount, yOffset * ((openFrameCount-1)%10)+yOffset);
191        }
192
193         final JMenuItem menuItem = new JMenuItem(title);
194         frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
195             {
196               public void internalFrameActivated(javax.swing.event.
197                                                  InternalFrameEvent evt)
198               {
199                 JInternalFrame itf = desktop.getSelectedFrame();
200                 if (itf != null)
201                   itf.requestFocus();
202
203               }
204
205                 public void internalFrameClosed(
206                     javax.swing.event.InternalFrameEvent evt)
207                 {
208                     openFrameCount--;
209                     windowMenu.remove(menuItem);
210                     JInternalFrame itf = desktop.getSelectedFrame();
211                        if (itf != null)
212                         itf.requestFocus();
213                 }
214                 ;
215             });
216
217         menuItem.addActionListener(new ActionListener()
218             {
219                 public void actionPerformed(ActionEvent e)
220                 {
221                     try
222                     {
223                         frame.setSelected(true);
224                         frame.setIcon(false);
225                     }
226                     catch (java.beans.PropertyVetoException ex)
227                     {
228
229                     }
230                 }
231             });
232
233         windowMenu.add(menuItem);
234
235         desktop.add(frame);
236         frame.toFront();
237         try{
238           frame.setSelected(true);
239           frame.requestFocus();
240         }catch(java.beans.PropertyVetoException ve)
241         {}
242     }
243
244     public void lostOwnership(Clipboard clipboard, Transferable contents)
245     {
246       Desktop.jalviewClipboard = null;
247     }
248
249     public void dragEnter(DropTargetDragEvent evt)
250     {}
251
252     public void dragExit(DropTargetEvent evt)
253     {}
254
255     public void dragOver(DropTargetDragEvent evt)
256     {}
257
258     public void dropActionChanged(DropTargetDragEvent evt)
259     {}
260
261     /**
262      * DOCUMENT ME!
263      *
264      * @param evt DOCUMENT ME!
265      */
266     public void drop(DropTargetDropEvent evt)
267     {
268         Transferable t = evt.getTransferable();
269         java.util.List files = null;
270
271         try
272         {
273           DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String");
274           if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
275           {
276             //Works on Windows and MacOSX
277             evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
278             files = (java.util.List) t.getTransferData(DataFlavor.javaFileListFlavor);
279           }
280           else if (t.isDataFlavorSupported(uriListFlavor))
281           {
282             // This is used by Unix drag system
283             evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
284             String data = (String) t.getTransferData(uriListFlavor);
285             files = new java.util.ArrayList(1);
286             for (java.util.StringTokenizer st = new java.util.StringTokenizer(
287                 data,
288                 "\r\n");
289                  st.hasMoreTokens(); )
290             {
291               String s = st.nextToken();
292               if (s.startsWith("#"))
293               {
294                 // the line is a comment (as per the RFC 2483)
295                 continue;
296               }
297
298               java.net.URI uri = new java.net.URI(s);
299               java.io.File file = new java.io.File(uri);
300               files.add(file);
301             }
302           }
303         }
304         catch (Exception e)
305         {
306           e.printStackTrace();
307         }
308
309         if (files != null)
310         {
311           try
312           {
313             for (int i = 0; i < files.size(); i++)
314             {
315               String file = files.get(i).toString();
316               String protocol = FormatAdapter.FILE;
317               String format = null;
318
319               if (file.endsWith(".jar"))
320               {
321                 format = "Jalview";
322
323               }
324               else
325               {
326                 format = new IdentifyFile().Identify(file,
327                                                           protocol);
328               }
329
330
331               new FileLoader().LoadFile(file, protocol, format);
332
333             }
334           }
335           catch (Exception ex)
336           {
337             ex.printStackTrace();
338           }
339         }
340     }
341
342     /**
343      * DOCUMENT ME!
344      *
345      * @param e DOCUMENT ME!
346      */
347     public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
348     {
349         JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.getProperty(
350                     "LAST_DIRECTORY"),
351                 new String[]
352                 {
353                     "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc",
354                     "jar"
355                 },
356                 new String[]
357                 {
358                     "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "Jalview"
359                 }, jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
360
361         chooser.setFileView(new JalviewFileView());
362         chooser.setDialogTitle("Open local file");
363         chooser.setToolTipText("Open");
364
365         int value = chooser.showOpenDialog(this);
366
367         if (value == JalviewFileChooser.APPROVE_OPTION)
368         {
369             String choice = chooser.getSelectedFile().getPath();
370             jalview.bin.Cache.setProperty("LAST_DIRECTORY",
371                 chooser.getSelectedFile().getParent());
372
373             String format = null;
374             if (chooser.getSelectedFormat().equals("Jalview"))
375             {
376                 format = "Jalview";
377             }
378             else
379             {
380                 format = new IdentifyFile().Identify(choice, FormatAdapter.FILE);
381             }
382
383             if (viewport != null)
384               new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE, format);
385             else
386               new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
387         }
388     }
389
390
391
392     /**
393      * DOCUMENT ME!
394      *
395      * @param e DOCUMENT ME!
396      */
397     public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
398     {
399       // This construct allows us to have a wider textfield
400       // for viewing
401       JLabel label = new JLabel("Enter URL of Input File");
402       final JComboBox history = new JComboBox();
403
404       JPanel panel = new JPanel(new GridLayout(2,1));
405       panel.add(label);
406       panel.add(history);
407       history.setPreferredSize(new Dimension(400,20));
408       history.setEditable(true);
409       history.addItem("http://www.");
410
411       String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
412
413       StringTokenizer st;
414
415       if (historyItems != null)
416       {
417         st = new StringTokenizer(historyItems, "\t");
418
419         while (st.hasMoreTokens())
420         {
421           history.addItem(st.nextElement());
422         }
423       }
424
425        int reply = JOptionPane.showInternalConfirmDialog(desktop,
426           panel, "Input Alignment From URL",
427           JOptionPane.OK_CANCEL_OPTION );
428
429
430         if (reply != JOptionPane.OK_OPTION )
431         {
432             return;
433         }
434
435         String url = history.getSelectedItem().toString();
436
437         if (url.toLowerCase().endsWith(".jar"))
438         {
439           if (viewport != null)
440             new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, "Jalview");
441           else
442             new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
443         }
444         else
445         {
446           String format = new IdentifyFile().Identify(url, FormatAdapter.URL);
447
448           if (format.equals("URL NOT FOUND"))
449           {
450             JOptionPane.showInternalMessageDialog(Desktop.desktop,
451                                                   "Couldn't locate " + url,
452                                                   "URL not found",
453                                                   JOptionPane.WARNING_MESSAGE);
454
455             return;
456           }
457
458           if (viewport != null)
459             new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
460           else
461             new FileLoader().LoadFile(url, FormatAdapter.URL, format);
462         }
463     }
464
465     /**
466      * DOCUMENT ME!
467      *
468      * @param e DOCUMENT ME!
469      */
470     public void inputTextboxMenuItem_actionPerformed(AlignViewport viewport)
471     {
472         CutAndPasteTransfer cap = new CutAndPasteTransfer();
473         cap.setForInput(viewport);
474         Desktop.addInternalFrame(cap, "Cut & Paste Alignment File", 600, 500);
475     }
476
477     /*
478      * Exit the program
479      */
480     public void quit()
481     {
482         jalview.bin.Cache.setProperty("SCREEN_X", getBounds().x + "");
483         jalview.bin.Cache.setProperty("SCREEN_Y", getBounds().y + "");
484         jalview.bin.Cache.setProperty("SCREEN_WIDTH", getWidth() + "");
485         jalview.bin.Cache.setProperty("SCREEN_HEIGHT", getHeight() + "");
486         System.exit(0);
487     }
488
489     /**
490      * DOCUMENT ME!
491      *
492      * @param e DOCUMENT ME!
493      */
494     public void aboutMenuItem_actionPerformed(ActionEvent e)
495     {
496       StringBuffer message = new StringBuffer("JalView version " +
497                                               jalview.bin.Cache.getProperty(
498           "VERSION") +
499                                               "; last updated: " +
500                                               jalview.bin.
501                                               Cache.getDefault("BUILD_DATE", "unknown"));
502
503       if (!jalview.bin.Cache.getProperty("LATEST_VERSION").equals(
504           jalview.bin.Cache.getProperty("VERSION")))
505       {
506         message.append("\n\n!! Jalview version "
507                        + jalview.bin.Cache.getProperty("LATEST_VERSION")
508                        + " is available for download from http://www.jalview.org !!\n");
509
510       }
511
512       message.append( "\nAuthors:  Michele Clamp, James Cuff, Steve Searle, Andrew Waterhouse, Jim Procter & Geoff Barton." +
513             "\nCurrent development managed by Andrew Waterhouse; Barton Group, University of Dundee." +
514             "\nFor all issues relating to Jalview, email help@jalview.org" +
515             "\n\nIf  you use JalView, please cite:" +
516             "\n\"Clamp, M., Cuff, J., Searle, S. M. and Barton, G. J. (2004), The Jalview Java Alignment Editor\"" +
517             "\nBioinformatics,  2004 20;426-7.");
518
519         JOptionPane.showInternalMessageDialog(Desktop.desktop,
520
521            message.toString(), "About Jalview",
522             JOptionPane.INFORMATION_MESSAGE);
523     }
524
525     /**
526      * DOCUMENT ME!
527      *
528      * @param e DOCUMENT ME!
529      */
530     public void documentationMenuItem_actionPerformed(ActionEvent e)
531     {
532         try
533         {
534             ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
535             java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
536             javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
537
538             javax.help.HelpBroker hb = hs.createHelpBroker();
539             hb.setCurrentID("home");
540             hb.setDisplayed(true);
541         }
542         catch (Exception ex)
543         {
544             ex.printStackTrace();
545         }
546     }
547
548     /**
549      * DOCUMENT ME!
550      *
551      * @param e DOCUMENT ME!
552      */
553     protected void preferences_actionPerformed(ActionEvent e)
554     {
555         new Preferences();
556     }
557
558     /**
559      * DOCUMENT ME!
560      *
561      * @param e DOCUMENT ME!
562      */
563     public void saveState_actionPerformed(ActionEvent e)
564     {
565         JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.getProperty(
566                     "LAST_DIRECTORY"), new String[] { "jar" },
567                 new String[] { "Jalview Project" }, "Jalview Project");
568
569         chooser.setFileView(new JalviewFileView());
570         chooser.setDialogTitle("Save State");
571
572         int value = chooser.showSaveDialog(this);
573
574         if (value == JalviewFileChooser.APPROVE_OPTION)
575         {
576             java.io.File choice = chooser.getSelectedFile();
577             jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
578             new Jalview2XML().SaveState(choice);
579         }
580     }
581
582     /**
583      * DOCUMENT ME!
584      *
585      * @param e DOCUMENT ME!
586      */
587     public void loadState_actionPerformed(ActionEvent e)
588     {
589         JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.getProperty(
590                     "LAST_DIRECTORY"), new String[] { "jar" },
591                 new String[] { "Jalview Project" }, "Jalview Project");
592         chooser.setFileView(new JalviewFileView());
593         chooser.setDialogTitle("Restore state");
594
595         int value = chooser.showOpenDialog(this);
596
597         if (value == JalviewFileChooser.APPROVE_OPTION)
598         {
599             String choice = chooser.getSelectedFile().getAbsolutePath();
600             jalview.bin.Cache.setProperty("LAST_DIRECTORY",
601                 chooser.getSelectedFile().getParent());
602             new Jalview2XML().LoadJalviewAlign(choice);
603         }
604     }
605
606   /*  public void vamsasLoad_actionPerformed(ActionEvent e)
607     {
608       JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
609           getProperty("LAST_DIRECTORY"));
610
611       chooser.setFileView(new JalviewFileView());
612       chooser.setDialogTitle("Load Vamsas file");
613       chooser.setToolTipText("Import");
614
615       int value = chooser.showOpenDialog(this);
616
617       if (value == JalviewFileChooser.APPROVE_OPTION)
618       {
619         jalview.io.VamsasDatastore vs = new jalview.io.VamsasDatastore(null);
620         vs.load(
621             chooser.getSelectedFile().getAbsolutePath()
622             );
623       }
624
625     }*/
626
627
628     public void inputSequence_actionPerformed(ActionEvent e)
629     {
630       new SequenceFetcher(null);
631     }
632
633     JPanel progressPanel;
634
635     public void startLoading(final String fileName)
636     {
637       if (fileLoadingCount == 0)
638       {
639         progressPanel = new JPanel(new BorderLayout());
640         JProgressBar progressBar = new JProgressBar();
641         progressBar.setIndeterminate(true);
642
643         progressPanel.add(new JLabel("Loading File: " + fileName + "   "),
644                           BorderLayout.WEST);
645
646         progressPanel.add(progressBar, BorderLayout.CENTER);
647
648         instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
649       }
650       fileLoadingCount++;
651       validate();
652     }
653
654     public void stopLoading()
655     {
656       fileLoadingCount--;
657       if (fileLoadingCount < 1)
658       {
659         if(progressPanel!=null)
660         {
661           this.getContentPane().remove(progressPanel);
662           progressPanel = null;
663         }
664         fileLoadingCount = 0;
665       }
666       validate();
667     }
668     jalview.gui.VamsasClient v_client=null;
669     public void vamsasLoad_actionPerformed(ActionEvent e)
670     {
671       if (v_client==null) {
672         // Start a session.
673         JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
674             getProperty("LAST_DIRECTORY"));
675
676         chooser.setFileView(new JalviewFileView());
677         chooser.setDialogTitle("Load Vamsas file");
678         chooser.setToolTipText("Import");
679
680         int value = chooser.showOpenDialog(this);
681
682         if (value == JalviewFileChooser.APPROVE_OPTION)
683         {
684           v_client = new jalview.gui.VamsasClient(this,
685               chooser.getSelectedFile());
686           this.vamsasLoad.setText("Session Update");
687           this.vamsasStop.setVisible(true);
688           v_client.initial_update();
689         }
690       } else {
691         // store current data in session.
692           v_client.push_update();
693       }
694     }
695     public void vamsasStop_actionPerformed(ActionEvent e) {
696         if (v_client!=null) {
697                 v_client.end_session();
698                 v_client=null;
699                 this.vamsasStop.setVisible(false);
700                 this.vamsasLoad.setText("Start Vamsas Session...");
701         }
702     }
703 }
704