future bug fix todo
[jalview.git] / src / jalview / gui / Desktop.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 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.lang.reflect.Constructor;
28 import java.util.*;
29
30 import javax.swing.*;
31 import javax.swing.event.MenuEvent;
32 import javax.swing.event.MenuListener;
33
34 /**
35  * DOCUMENT ME!
36  *
37  * @author $author$
38  * @version $Revision$
39  */
40 public class Desktop
41     extends jalview.jbgui.GDesktop implements DropTargetListener,
42     ClipboardOwner, IProgressIndicator
43 {
44   /** DOCUMENT ME!! */
45   public static Desktop instance;
46
47   //Need to decide if the Memory Usage is to be included in
48   //Next release or not.
49   public static MyDesktopPane desktop;
50   // public static JDesktopPane desktop;
51
52
53   static int openFrameCount = 0;
54   static final int xOffset = 30;
55   static final int yOffset = 30;
56   public static jalview.ws.Discoverer discoverer;
57
58   public static Object[] jalviewClipboard;
59   public static boolean internalCopy = false;
60
61   static int fileLoadingCount = 0;
62
63   /**
64    * Creates a new Desktop object.
65    */
66   public Desktop()
67   {
68     /**
69      * A note to implementors. It is ESSENTIAL that any 
70      * activities that might block are spawned off as threads rather 
71      * than waited for during this constructor.
72      */
73     instance = this;
74     doVamsasClientCheck();
75     doGroovyCheck();
76
77
78     setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
79     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
80     boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",false);
81     desktop = new MyDesktopPane(selmemusage);
82     showMemusage.setSelected(selmemusage);
83     desktop.setBackground(Color.white);
84     getContentPane().setLayout(new BorderLayout());
85     getContentPane().add(desktop, BorderLayout.CENTER);
86     desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
87
88     // This line prevents Windows Look&Feel resizing all new windows to maximum
89     // if previous window was maximised
90     desktop.setDesktopManager(new DefaultDesktopManager());
91
92     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
93     String x = jalview.bin.Cache.getProperty("SCREEN_X");
94     String y = jalview.bin.Cache.getProperty("SCREEN_Y");
95     String width = jalview.bin.Cache.getProperty("SCREEN_WIDTH");
96     String height = jalview.bin.Cache.getProperty("SCREEN_HEIGHT");
97
98     if ( (x != null) && (y != null) && (width != null) && (height != null))
99     {
100       setBounds(Integer.parseInt(x), Integer.parseInt(y),
101                 Integer.parseInt(width), Integer.parseInt(height));
102     }
103     else
104     {
105       setBounds( (int) (screenSize.width - 900) / 2,
106                 (int) (screenSize.height - 650) / 2, 900, 650);
107     }
108
109     this.addWindowListener(new WindowAdapter()
110     {
111       public void windowClosing(WindowEvent evt)
112       {
113         quit();
114       }
115     });
116
117     this.addMouseListener(new MouseAdapter()
118         {
119           public void mousePressed(MouseEvent evt)
120           {
121             if(SwingUtilities.isRightMouseButton(evt))
122             {
123               showPasteMenu(evt.getX(), evt.getY());
124             }
125           }
126         });
127
128
129     this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
130     // Spawn a thread that shows the splashscreen
131     new SplashScreen();     
132
133
134
135     discoverer = new jalview.ws.Discoverer(); // Only gets started if gui is displayed.
136   }
137
138   private void doVamsasClientCheck()
139   {
140     if (jalview.bin.Cache.vamsasJarsPresent())
141     {
142       setupVamsasDisconnectedGui();
143       VamsasMenu.setVisible(true);
144       final Desktop us = this;
145       VamsasMenu.addMenuListener(new MenuListener() {
146         // this listener remembers when the menu was first selected, and
147         // doesn't rebuild the session list until it has been cleared and
148         // reselected again.
149         boolean refresh=true;
150         public void menuCanceled(MenuEvent e)
151         {
152           refresh=true;
153         }
154
155         public void menuDeselected(MenuEvent e)
156         {
157           refresh = true;
158         }
159
160         public void menuSelected(MenuEvent e)
161         {
162           if (refresh)
163           {
164             us.buildVamsasStMenu();
165             refresh=false;
166           }
167         }
168       });
169       vamsasStart.setVisible(true);
170     }
171   }
172
173   void showPasteMenu(int x, int y)
174   {
175     JPopupMenu popup = new JPopupMenu();
176     JMenuItem item = new JMenuItem("Paste To New Window");
177     item.addActionListener(new ActionListener()
178     {
179       public void actionPerformed(ActionEvent evt)
180       {
181         paste();
182       }
183     });
184
185     popup.add(item);
186     popup.show(this, x, y);
187   }
188
189   public void paste()
190   {
191     try
192     {
193       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
194       Transferable contents = c.getContents(this);
195
196       if (contents != null)
197       {
198         String file = (String) contents
199             .getTransferData(DataFlavor.stringFlavor);
200
201         String format = new IdentifyFile().Identify(file,
202                                                     FormatAdapter.PASTE);
203
204         new FileLoader().LoadFile(file, FormatAdapter.PASTE, format);
205
206       }
207     }
208     catch (Exception ex)
209     {
210       System.out.println("Unable to paste alignment from system clipboard:\n"
211                          + ex);
212     }
213   }
214
215   /**
216    * DOCUMENT ME!
217    *
218    * @param frame DOCUMENT ME!
219    * @param title DOCUMENT ME!
220    * @param w DOCUMENT ME!
221    * @param h DOCUMENT ME!
222    */
223   public static synchronized void addInternalFrame(final JInternalFrame frame,
224       String title, int w, int h)
225   {
226     addInternalFrame(frame, title, w, h, true);
227   }
228
229   /**
230    * DOCUMENT ME!
231    *
232    * @param frame DOCUMENT ME!
233    * @param title DOCUMENT ME!
234    * @param w DOCUMENT ME!
235    * @param h DOCUMENT ME!
236    * @param resizable DOCUMENT ME!
237    */
238   public static synchronized void addInternalFrame(final JInternalFrame frame,
239       String title, int w, int h, boolean resizable)
240   {
241
242     // TODO: consider fixing method to update entries in the window submenu with the current window title 
243
244     frame.setTitle(title);
245     if (frame.getWidth() < 1 || frame.getHeight() < 1)
246     {
247       frame.setSize(w, h);
248     }
249     // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
250     // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
251     // IF JALVIEW IS RUNNING HEADLESS
252     /////////////////////////////////////////////////
253     if (System.getProperty("java.awt.headless") != null
254         && System.getProperty("java.awt.headless").equals("true"))
255     {
256       return;
257     }
258
259     openFrameCount++;
260
261     frame.setVisible(true);
262     frame.setClosable(true);
263     frame.setResizable(resizable);
264     frame.setMaximizable(resizable);
265     frame.setIconifiable(resizable);
266     frame.setFrameIcon(null);
267
268     if (frame.getX() < 1 && frame.getY() < 1)
269     {
270       frame.setLocation(xOffset * openFrameCount,
271                         yOffset * ( (openFrameCount - 1) % 10) + yOffset);
272     }
273
274     final JMenuItem menuItem = new JMenuItem(title);
275     frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
276     {
277       public void internalFrameActivated(javax.swing.event.
278                                          InternalFrameEvent evt)
279       {
280         JInternalFrame itf = desktop.getSelectedFrame();
281         if (itf != null)
282         {
283           itf.requestFocus();
284         }
285
286       }
287
288       public void internalFrameClosed(
289           javax.swing.event.InternalFrameEvent evt)
290       {
291         PaintRefresher.RemoveComponent(frame);
292         openFrameCount--;
293         windowMenu.remove(menuItem);
294         JInternalFrame itf = desktop.getSelectedFrame();
295         if (itf != null)
296         {
297           itf.requestFocus();
298         }
299         System.gc();
300       }
301       ;
302     });
303
304     menuItem.addActionListener(new ActionListener()
305     {
306       public void actionPerformed(ActionEvent e)
307       {
308         try
309         {
310           frame.setSelected(true);
311           frame.setIcon(false);
312         }
313         catch (java.beans.PropertyVetoException ex)
314         {
315
316         }
317       }
318     });
319
320     windowMenu.add(menuItem);
321
322     desktop.add(frame);
323     frame.toFront();
324     try
325     {
326       frame.setSelected(true);
327       frame.requestFocus();
328     }
329     catch (java.beans.PropertyVetoException ve)
330     {}
331   }
332
333   public void lostOwnership(Clipboard clipboard, Transferable contents)
334   {
335     if (!internalCopy)
336     {
337       Desktop.jalviewClipboard = null;
338     }
339
340     internalCopy = false;
341   }
342
343   public void dragEnter(DropTargetDragEvent evt)
344   {}
345
346   public void dragExit(DropTargetEvent evt)
347   {}
348
349   public void dragOver(DropTargetDragEvent evt)
350   {}
351
352   public void dropActionChanged(DropTargetDragEvent evt)
353   {}
354
355   /**
356    * DOCUMENT ME!
357    *
358    * @param evt DOCUMENT ME!
359    */
360   public void drop(DropTargetDropEvent evt)
361   {
362     Transferable t = evt.getTransferable();
363     java.util.List files = null;
364
365     try
366     {
367       DataFlavor uriListFlavor = new DataFlavor(
368           "text/uri-list;class=java.lang.String");
369       if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
370       {
371         //Works on Windows and MacOSX
372         evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
373         files = (java.util.List) t.getTransferData(DataFlavor.
374             javaFileListFlavor);
375       }
376       else if (t.isDataFlavorSupported(uriListFlavor))
377       {
378         // This is used by Unix drag system
379         evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
380         String data = (String) t.getTransferData(uriListFlavor);
381         files = new java.util.ArrayList(1);
382         for (java.util.StringTokenizer st = new java.util.StringTokenizer(
383             data,
384             "\r\n");
385              st.hasMoreTokens(); )
386         {
387           String s = st.nextToken();
388           if (s.startsWith("#"))
389           {
390             // the line is a comment (as per the RFC 2483)
391             continue;
392           }
393
394           java.net.URI uri = new java.net.URI(s);
395           java.io.File file = new java.io.File(uri);
396           files.add(file);
397         }
398       }
399     }
400     catch (Exception e)
401     {}
402
403     if (files != null)
404     {
405       try
406       {
407         for (int i = 0; i < files.size(); i++)
408         {
409           String file = files.get(i).toString();
410           String protocol = FormatAdapter.FILE;
411           String format = null;
412
413           if (file.endsWith(".jar"))
414           {
415             format = "Jalview";
416
417           }
418           else
419           {
420             format = new IdentifyFile().Identify(file,
421                                                  protocol);
422           }
423
424           new FileLoader().LoadFile(file, protocol, format);
425
426         }
427       }
428       catch (Exception ex)
429       {}
430     }
431   }
432
433   /**
434    * DOCUMENT ME!
435    *
436    * @param e DOCUMENT ME!
437    */
438   public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
439   {
440     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
441         getProperty(
442             "LAST_DIRECTORY"),
443             jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
444             jalview.io.AppletFormatAdapter.READABLE_FNAMES, 
445             jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
446
447     chooser.setFileView(new JalviewFileView());
448     chooser.setDialogTitle("Open local file");
449     chooser.setToolTipText("Open");
450
451     int value = chooser.showOpenDialog(this);
452
453     if (value == JalviewFileChooser.APPROVE_OPTION)
454     {
455       String choice = chooser.getSelectedFile().getPath();
456       jalview.bin.Cache.setProperty("LAST_DIRECTORY",
457                                     chooser.getSelectedFile().getParent());
458
459       String format = null;
460       if (chooser.getSelectedFormat().equals("Jalview"))
461       {
462         format = "Jalview";
463       }
464       else
465       {
466         format = new IdentifyFile().Identify(choice, FormatAdapter.FILE);
467       }
468
469       if (viewport != null)
470       {
471         new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE, format);
472       }
473       else
474       {
475         new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
476       }
477     }
478   }
479
480   /**
481    * DOCUMENT ME!
482    *
483    * @param e DOCUMENT ME!
484    */
485   public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
486   {
487     // This construct allows us to have a wider textfield
488     // for viewing
489     JLabel label = new JLabel("Enter URL of Input File");
490     final JComboBox history = new JComboBox();
491
492     JPanel panel = new JPanel(new GridLayout(2, 1));
493     panel.add(label);
494     panel.add(history);
495     history.setPreferredSize(new Dimension(400, 20));
496     history.setEditable(true);
497     history.addItem("http://www.");
498
499     String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
500
501     StringTokenizer st;
502
503     if (historyItems != null)
504     {
505       st = new StringTokenizer(historyItems, "\t");
506
507       while (st.hasMoreTokens())
508       {
509         history.addItem(st.nextElement());
510       }
511     }
512
513     int reply = JOptionPane.showInternalConfirmDialog(desktop,
514         panel, "Input Alignment From URL",
515         JOptionPane.OK_CANCEL_OPTION);
516
517     if (reply != JOptionPane.OK_OPTION)
518     {
519       return;
520     }
521
522     String url = history.getSelectedItem().toString();
523
524     if (url.toLowerCase().endsWith(".jar"))
525     {
526       if (viewport != null)
527       {
528         new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, "Jalview");
529       }
530       else
531       {
532         new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
533       }
534     }
535     else
536     {
537       String format = new IdentifyFile().Identify(url, FormatAdapter.URL);
538
539       if (format.equals("URL NOT FOUND"))
540       {
541         JOptionPane.showInternalMessageDialog(Desktop.desktop,
542                                               "Couldn't locate " + url,
543                                               "URL not found",
544                                               JOptionPane.WARNING_MESSAGE);
545
546         return;
547       }
548
549       if (viewport != null)
550       {
551         new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
552       }
553       else
554       {
555         new FileLoader().LoadFile(url, FormatAdapter.URL, format);
556       }
557     }
558   }
559
560   /**
561    * DOCUMENT ME!
562    *
563    * @param e DOCUMENT ME!
564    */
565   public void inputTextboxMenuItem_actionPerformed(AlignViewport viewport)
566   {
567     CutAndPasteTransfer cap = new CutAndPasteTransfer();
568     cap.setForInput(viewport);
569     Desktop.addInternalFrame(cap, "Cut & Paste Alignment File", 600, 500);
570   }
571
572   /*
573    * Exit the program
574    */
575   public void quit()
576   {
577     jalview.bin.Cache.setProperty("SCREEN_X", getBounds().x + "");
578     jalview.bin.Cache.setProperty("SCREEN_Y", getBounds().y + "");
579     jalview.bin.Cache.setProperty("SCREEN_WIDTH", getWidth() + "");
580     jalview.bin.Cache.setProperty("SCREEN_HEIGHT", getHeight() + "");
581     System.exit(0);
582   }
583
584   /**
585    * DOCUMENT ME!
586    *
587    * @param e DOCUMENT ME!
588    */
589   public void aboutMenuItem_actionPerformed(ActionEvent e)
590   {
591     StringBuffer message = new StringBuffer("Jalview version " +
592                                             jalview.bin.Cache.getProperty(
593                                                 "VERSION") +
594                                             "; last updated: " +
595                                             jalview.bin.
596                                             Cache.getDefault("BUILD_DATE",
597         "unknown"));
598
599     if (!jalview.bin.Cache.getProperty("LATEST_VERSION").equals(
600         jalview.bin.Cache.getProperty("VERSION")))
601     {
602       message.append("\n\n!! Jalview version "
603                      + jalview.bin.Cache.getProperty("LATEST_VERSION")
604                      +
605           " is available for download from http://www.jalview.org !!\n");
606
607     }
608
609     message.append("\nAuthors:  Michele Clamp, James Cuff, Steve Searle, Andrew Waterhouse, Jim Procter & Geoff Barton." +
610                    "\nDevelopment managed by The Barton Group, University of Dundee.\n"+
611                    "\nFor specific issues relating to Jalview, email help@jalview.org\n"+
612                    " or join the jalview-discuss@jalview.org mailing list" +
613                    "\n\nIf  you use Jalview, please cite:" +
614                    "\n\"Clamp, M., Cuff, J., Searle, S. M. and Barton, G. J. (2004), The Jalview Java Alignment Editor\"" +
615                    "\nBioinformatics,  2004 20;426-7.");
616
617     JOptionPane.showInternalMessageDialog(Desktop.desktop,
618
619                                           message.toString(), "About Jalview",
620                                           JOptionPane.INFORMATION_MESSAGE);
621   }
622
623   /**
624    * DOCUMENT ME!
625    *
626    * @param e DOCUMENT ME!
627    */
628   public void documentationMenuItem_actionPerformed(ActionEvent e)
629   {
630     try
631     {
632       ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
633       java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
634       javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
635
636       javax.help.HelpBroker hb = hs.createHelpBroker();
637       hb.setCurrentID("home");
638       hb.setDisplayed(true);
639     }
640     catch (Exception ex)
641     {}
642   }
643
644   public void closeAll_actionPerformed(ActionEvent e)
645   {
646     JInternalFrame[] frames = desktop.getAllFrames();
647     for (int i = 0; i < frames.length; i++)
648     {
649       try
650       {
651         frames[i].setClosed(true);
652       }
653       catch (java.beans.PropertyVetoException ex)
654       {}
655     }
656     System.out.println("ALL CLOSED");
657
658   }
659
660   public void raiseRelated_actionPerformed(ActionEvent e)
661   {
662     reorderAssociatedWindows(false, false);
663   }
664
665   public void minimizeAssociated_actionPerformed(ActionEvent e)
666   {
667     reorderAssociatedWindows(true, false);
668   }
669
670   void closeAssociatedWindows()
671   {
672     reorderAssociatedWindows(false, true);
673   }
674
675   /* (non-Javadoc)
676    * @see jalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.ActionEvent)
677    */
678   protected void garbageCollect_actionPerformed(ActionEvent e)
679   {
680     // We simply collect the garbage
681     jalview.bin.Cache.log.debug("Collecting garbage...");
682     System.gc();
683     jalview.bin.Cache.log.debug("Finished garbage collection.");
684   }
685
686   /* (non-Javadoc)
687    * @see jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent)
688    */
689   protected void showMemusage_actionPerformed(ActionEvent e)
690   {
691     desktop.showMemoryUsage(showMemusage.isSelected());
692   }
693
694   void reorderAssociatedWindows(boolean minimize, boolean close)
695   {
696     JInternalFrame[] frames = desktop.getAllFrames();
697     if (frames == null || frames.length < 1)
698     {
699       return;
700     }
701
702     AlignViewport source = null, target = null;
703     if (frames[0] instanceof AlignFrame)
704     {
705       source = ( (AlignFrame) frames[0]).getCurrentView();
706     }
707     else if (frames[0] instanceof TreePanel)
708     {
709       source = ( (TreePanel) frames[0]).getViewPort();
710     }
711     else if (frames[0] instanceof PCAPanel)
712     {
713       source = ( (PCAPanel) frames[0]).av;
714     }
715     else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
716     {
717       source = ( (PairwiseAlignPanel) frames[0].getContentPane()).av;
718     }
719
720     if (source != null)
721     {
722       for (int i = 0; i < frames.length; i++)
723       {
724         target = null;
725         if (frames[i] == null)
726         {
727           continue;
728         }
729         if (frames[i] instanceof AlignFrame)
730         {
731           target = ( (AlignFrame) frames[i]).getCurrentView();
732         }
733         else if (frames[i] instanceof TreePanel)
734         {
735           target = ( (TreePanel) frames[i]).getViewPort();
736         }
737         else if (frames[i] instanceof PCAPanel)
738         {
739           target = ( (PCAPanel) frames[i]).av;
740         }
741         else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
742         {
743           target = ( (PairwiseAlignPanel) frames[i].getContentPane()).av;
744         }
745
746         if (source == target)
747         {
748           try
749           {
750             if (close)
751             {
752               frames[i].setClosed(true);
753             }
754             else
755             {
756               frames[i].setIcon(minimize);
757               if (!minimize)
758               {
759                 frames[i].toFront();
760               }
761             }
762
763           }
764           catch (java.beans.PropertyVetoException ex)
765           {}
766         }
767       }
768     }
769   }
770   /**
771    * DOCUMENT ME!
772    *
773    * @param e DOCUMENT ME!
774    */
775   protected void preferences_actionPerformed(ActionEvent e)
776   {
777     new Preferences();
778   }
779
780   /**
781    * DOCUMENT ME!
782    *
783    * @param e DOCUMENT ME!
784    */
785   public void saveState_actionPerformed(ActionEvent e)
786   {
787     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
788         getProperty(
789             "LAST_DIRECTORY"), new String[]
790         {"jar"},
791         new String[]
792         {"Jalview Project"}, "Jalview Project");
793
794     chooser.setFileView(new JalviewFileView());
795     chooser.setDialogTitle("Save State");
796
797     int value = chooser.showSaveDialog(this);
798
799     if (value == JalviewFileChooser.APPROVE_OPTION)
800     {
801       java.io.File choice = chooser.getSelectedFile();
802       jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
803       new Jalview2XML().SaveState(choice);
804     }
805   }
806
807   /**
808    * DOCUMENT ME!
809    *
810    * @param e DOCUMENT ME!
811    */
812   public void loadState_actionPerformed(ActionEvent e)
813   {
814     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
815         getProperty(
816             "LAST_DIRECTORY"), new String[]
817         {"jar"},
818         new String[]
819         {"Jalview Project"}, "Jalview Project");
820     chooser.setFileView(new JalviewFileView());
821     chooser.setDialogTitle("Restore state");
822
823     int value = chooser.showOpenDialog(this);
824
825     if (value == JalviewFileChooser.APPROVE_OPTION)
826     {
827       String choice = chooser.getSelectedFile().getAbsolutePath();
828       jalview.bin.Cache.setProperty("LAST_DIRECTORY",
829                                     chooser.getSelectedFile().getParent());
830       new Jalview2XML().LoadJalviewAlign(choice);
831     }
832   }
833
834   public void inputSequence_actionPerformed(ActionEvent e)
835   {
836     new SequenceFetcher(this);
837   }
838
839   JPanel progressPanel;
840
841   public void startLoading(final String fileName)
842   {
843     if (fileLoadingCount == 0)
844     {
845       addProgressPanel("Loading File: " + fileName + "   ");
846       
847     }
848     fileLoadingCount++;
849   }
850   private JProgressBar addProgressPanel(String string)
851   {
852     if (progressPanel==null)
853     {
854       progressPanel = new JPanel(new BorderLayout());
855       totalProgressCount=0;
856     }
857     JProgressBar progressBar = new JProgressBar();
858     progressBar.setIndeterminate(true);
859
860     progressPanel.add(new JLabel(string),
861                       BorderLayout.WEST);
862
863     progressPanel.add(progressBar, BorderLayout.CENTER);
864
865     instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
866     totalProgressCount++;
867     validate();
868     return progressBar;
869   }
870   int totalProgressCount=0;
871   private void removeProgressPanel(JProgressBar progbar)
872   {
873     if (progressPanel!=null)
874     {
875       progressPanel.remove(progbar);
876       if (--totalProgressCount<1)
877       {
878         this.getContentPane().remove(progressPanel);
879         progressPanel = null;
880       }
881     }
882     validate();
883   }
884   public void stopLoading()
885   {
886     fileLoadingCount--;
887     if (fileLoadingCount < 1)
888     {
889       if (progressPanel != null)
890       {
891         this.getContentPane().remove(progressPanel);
892         progressPanel = null;
893       }
894       fileLoadingCount = 0;
895     }
896     validate();
897   }
898   public static int getViewCount(String viewId)
899   {
900     int count = 0;
901     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
902     for (int t = 0; t < frames.length; t++)
903     {
904       if (frames[t] instanceof AlignFrame)
905       {
906         AlignFrame af = (AlignFrame) frames[t];
907         for (int a = 0; a < af.alignPanels.size(); a++)
908         {
909           if (viewId.equals(
910               ( (AlignmentPanel) af.alignPanels.elementAt(a)).av.
911               getSequenceSetId())
912               )
913           {
914             count++;
915           }
916         }
917       }
918     }
919
920     return count;
921   }
922
923   public void explodeViews(AlignFrame af)
924   {
925     int size = af.alignPanels.size();
926     if (size < 2)
927     {
928       return;
929     }
930
931     for (int i = 0; i < size; i++)
932     {
933       AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(i);
934       AlignFrame newaf = new AlignFrame(ap);
935       if (ap.av.explodedPosition != null &&
936           !ap.av.explodedPosition.equals(af.getBounds()))
937       {
938         newaf.setBounds(ap.av.explodedPosition);
939       }
940
941       ap.av.gatherViewsHere = false;
942
943       addInternalFrame(newaf, af.getTitle(),
944                        AlignFrame.DEFAULT_WIDTH,
945                        AlignFrame.DEFAULT_HEIGHT);
946     }
947
948     af.alignPanels.clear();
949     af.closeMenuItem_actionPerformed(true);
950
951   }
952
953   public void gatherViews(AlignFrame source)
954   {
955     source.viewport.gatherViewsHere = true;
956     source.viewport.explodedPosition = source.getBounds();
957     JInternalFrame[] frames = desktop.getAllFrames();
958     String viewId = source.viewport.sequenceSetID;
959
960     for (int t = 0; t < frames.length; t++)
961     {
962       if (frames[t] instanceof AlignFrame && frames[t] != source)
963       {
964         AlignFrame af = (AlignFrame) frames[t];
965         boolean gatherThis = false;
966         for (int a = 0; a < af.alignPanels.size(); a++)
967         {
968           AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(a);
969           if (viewId.equals(ap.av.getSequenceSetId()))
970           {
971             gatherThis = true;
972             ap.av.gatherViewsHere = false;
973             ap.av.explodedPosition = af.getBounds();
974             source.addAlignmentPanel(ap, false);
975           }
976         }
977
978         if (gatherThis)
979         {
980           af.alignPanels.clear();
981           af.closeMenuItem_actionPerformed(true);
982         }
983       }
984     }
985
986   }
987
988   jalview.gui.VamsasApplication v_client = null;
989   public void vamsasImport_actionPerformed(ActionEvent e)
990   {
991     if (v_client==null)
992     {
993       // Load and try to start a session.
994       JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
995           getProperty("LAST_DIRECTORY"));
996
997       chooser.setFileView(new JalviewFileView());
998       chooser.setDialogTitle("Open a saved VAMSAS session");
999       chooser.setToolTipText("select a vamsas session to be opened as a new vamsas session.");
1000
1001       int value = chooser.showOpenDialog(this);
1002
1003       if (value == JalviewFileChooser.APPROVE_OPTION)
1004       {
1005         try {
1006           v_client = new jalview.gui.VamsasApplication(this,
1007                                                 chooser.getSelectedFile());
1008         } catch (Exception ex)
1009         {
1010           jalview.bin.Cache.log.error("New vamsas session from existing session file failed:",ex);
1011           return;
1012         }
1013         setupVamsasConnectedGui();
1014         v_client.initial_update(); // TODO: thread ?
1015       }
1016     }else {
1017       jalview.bin.Cache.log.error("Implementation error - load session from a running session is not supported.");
1018     }
1019   }
1020
1021   public void vamsasStart_actionPerformed(ActionEvent e)
1022   {
1023     if (v_client == null)
1024     {
1025       // Start a session.
1026       // we just start a default session for moment.
1027       /*
1028       JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
1029           getProperty("LAST_DIRECTORY"));
1030
1031       chooser.setFileView(new JalviewFileView());
1032       chooser.setDialogTitle("Load Vamsas file");
1033       chooser.setToolTipText("Import");
1034
1035       int value = chooser.showOpenDialog(this);
1036
1037       if (value == JalviewFileChooser.APPROVE_OPTION)
1038       {
1039         v_client = new jalview.gui.VamsasApplication(this,
1040                                                 chooser.getSelectedFile());
1041                                                 *
1042                                                 */
1043       v_client = new VamsasApplication(this);
1044       setupVamsasConnectedGui();
1045       v_client.initial_update(); // TODO: thread ?
1046     }
1047     else
1048     {
1049       // store current data in session.
1050       v_client.push_update(); // TODO: thread
1051     }
1052   }
1053
1054   protected void setupVamsasConnectedGui()
1055   {
1056     vamsasStart.setText("Session Update");
1057     vamsasSave.setVisible(true);
1058     vamsasStop.setVisible(true);
1059     vamsasImport.setVisible(false); // Document import to existing session is not possible for vamsas-client-1.0.
1060   }
1061   protected void setupVamsasDisconnectedGui()
1062   {
1063     vamsasSave.setVisible(false);
1064     vamsasStop.setVisible(false);
1065     vamsasImport.setVisible(true);
1066     vamsasStart.setText("New Vamsas Session");
1067   }
1068
1069   public void vamsasStop_actionPerformed(ActionEvent e)
1070   {
1071     if (v_client != null)
1072     {
1073       v_client.end_session();
1074       v_client = null;
1075       setupVamsasDisconnectedGui();
1076     }
1077   }
1078   protected void buildVamsasStMenu()
1079   {
1080     if (v_client == null)
1081     {
1082       String[] sess = null;
1083       try
1084       {
1085         sess = VamsasApplication.getSessionList();
1086       } catch (Exception e)
1087       {
1088         jalview.bin.Cache.log.warn(
1089                 "Problem getting current sessions list.", e);
1090         sess = null;
1091       }
1092       if (sess != null)
1093       {
1094         jalview.bin.Cache.log.debug("Got current sessions list: "
1095                 + sess.length + " entries.");
1096         VamsasStMenu.removeAll();
1097         for (int i = 0; i < sess.length; i++)
1098         {
1099           JMenuItem sessit = new JMenuItem();
1100           sessit.setText(sess[i]);
1101           sessit.setToolTipText("Connect to session " + sess[i]);
1102           final Desktop dsktp = this;
1103           final String mysesid = sess[i];
1104           sessit.addActionListener(new ActionListener()
1105           {
1106
1107             public void actionPerformed(ActionEvent e)
1108             {
1109               if (dsktp.v_client == null)
1110               {
1111                 Thread rthr = new Thread(new Runnable() {
1112
1113                   public void run()
1114                   {
1115                     dsktp.v_client = new VamsasApplication(dsktp, mysesid);
1116                     dsktp.setupVamsasConnectedGui();
1117                     dsktp.v_client.initial_update();
1118                   }
1119                   
1120                 });
1121                 rthr.start();
1122               }
1123             };
1124           });
1125           VamsasStMenu.add(sessit);
1126         }
1127         // don't show an empty menu.
1128         VamsasStMenu.setVisible(sess.length>0);
1129         
1130       }
1131       else
1132       {
1133         jalview.bin.Cache.log.debug("No current vamsas sessions.");
1134         VamsasStMenu.removeAll();
1135         VamsasStMenu.setVisible(false);
1136       }
1137     } else {
1138       // Not interested in the content. Just hide ourselves.
1139       VamsasStMenu.setVisible(false);
1140     }
1141   }
1142   public void vamsasSave_actionPerformed(ActionEvent e)
1143   {
1144     if (v_client != null)
1145     {
1146       JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
1147             getProperty(
1148                 "LAST_DIRECTORY"), new String[]
1149             {"vdj"}, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
1150             new String[]
1151             {"Vamsas Document"}, "Vamsas Document");
1152
1153         chooser.setFileView(new JalviewFileView());
1154         chooser.setDialogTitle("Save Vamsas Document Archive");
1155
1156         int value = chooser.showSaveDialog(this);
1157
1158         if (value == JalviewFileChooser.APPROVE_OPTION)
1159         {
1160           java.io.File choice = chooser.getSelectedFile();
1161           jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1162           String warnmsg=null;
1163           String warnttl=null;
1164           try {
1165             v_client.vclient.storeDocument(choice);
1166           }
1167           catch (Error ex)
1168           {
1169             warnttl = "Serious Problem saving Vamsas Document";
1170             warnmsg = ex.toString();
1171             jalview.bin.Cache.log.error("Error Whilst saving document to "+choice,ex);
1172             
1173           }
1174           catch (Exception ex)
1175           {
1176             warnttl = "Problem saving Vamsas Document.";
1177             warnmsg = ex.toString();
1178             jalview.bin.Cache.log.warn("Exception Whilst saving document to "+choice,ex);
1179             
1180           }
1181           if (warnmsg!=null)
1182           {
1183             JOptionPane.showInternalMessageDialog(Desktop.desktop,
1184
1185                   warnmsg, warnttl,
1186                   JOptionPane.ERROR_MESSAGE);
1187           }
1188         }
1189     }
1190   }
1191   JProgressBar vamUpdate = null;
1192   /**
1193    * hide vamsas user gui bits when a vamsas document event is being handled.
1194    * @param b true to hide gui, false to reveal gui
1195    */
1196   public void setVamsasUpdate(boolean b)
1197   {
1198     jalview.bin.Cache.log.debug("Setting gui for Vamsas update " +
1199                                 (b ? "in progress" : "finished"));
1200     
1201     if (vamUpdate!=null)
1202     {
1203       this.removeProgressPanel(vamUpdate);
1204     }
1205     if (b)
1206     {
1207       vamUpdate = this.addProgressPanel("Updating vamsas session");
1208     }
1209     vamsasStart.setVisible(!b);
1210     vamsasStop.setVisible(!b);
1211     vamsasSave.setVisible(!b);
1212   }
1213
1214   public JInternalFrame[] getAllFrames()
1215   {
1216     return desktop.getAllFrames();
1217   }
1218
1219
1220   /**
1221    * Checks the given url to see if it gives a response indicating that
1222    * the user should be informed of a new questionnaire.
1223    * @param url
1224    */
1225   public void checkForQuestionnaire(String url)
1226   {
1227     UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
1228     //javax.swing.SwingUtilities.invokeLater(jvq);
1229     new Thread(jvq).start();
1230   }
1231   /**
1232    * Proxy class for JDesktopPane which optionally 
1233    * displays the current memory usage and highlights 
1234    * the desktop area with a red bar if free memory runs low.
1235    * @author AMW
1236    */
1237   public class  MyDesktopPane extends JDesktopPane implements Runnable
1238   {
1239     
1240     boolean showMemoryUsage = false;
1241     Runtime runtime;
1242     java.text.NumberFormat df;
1243
1244     float maxMemory, allocatedMemory, freeMemory, totalFreeMemory, percentUsage;
1245
1246     public MyDesktopPane(boolean showMemoryUsage)
1247     {
1248       showMemoryUsage(showMemoryUsage);
1249     }
1250
1251     public void showMemoryUsage(boolean showMemoryUsage)
1252     {
1253       this.showMemoryUsage = showMemoryUsage;
1254       if (showMemoryUsage)
1255       {
1256         Thread worker = new Thread(this);
1257         worker.start();
1258       }
1259     }
1260     public boolean isShowMemoryUsage()
1261     {
1262       return showMemoryUsage;
1263     }
1264     public void run()
1265     {
1266       df = java.text.NumberFormat.getNumberInstance();
1267       df.setMaximumFractionDigits(2);
1268       runtime = Runtime.getRuntime();
1269
1270       while (showMemoryUsage)
1271       {
1272         try
1273         {
1274           Thread.sleep(3000);
1275           maxMemory = runtime.maxMemory() / 1048576f;
1276           allocatedMemory = runtime.totalMemory() / 1048576f;
1277           freeMemory = runtime.freeMemory() / 1048576f;
1278           totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
1279
1280           percentUsage = (totalFreeMemory / maxMemory) * 100;
1281
1282         //  if (percentUsage < 20)
1283           {
1284             //   border1 = BorderFactory.createMatteBorder(12, 12, 12, 12, Color.red);
1285             //    instance.set.setBorder(border1);
1286           }
1287           repaint();
1288
1289         }
1290         catch (Exception ex)
1291         {
1292           ex.printStackTrace();
1293         }
1294       }
1295     }
1296
1297     public void paintComponent(Graphics g)
1298     {
1299       if(showMemoryUsage)
1300       {
1301         if (percentUsage < 20)
1302           g.setColor(Color.red);
1303
1304         g.drawString("Total Free Memory: " + df.format(totalFreeMemory)
1305                      + "MB; Max Memory: " + df.format(maxMemory)
1306                      + "MB; " + df.format(percentUsage) + "%", 10,
1307                      getHeight() - g.getFontMetrics().getHeight());
1308       }
1309     }
1310
1311     
1312     
1313   }
1314   protected JMenuItem groovyShell;
1315   public void doGroovyCheck() {
1316     if (jalview.bin.Cache.groovyJarsPresent())
1317     {
1318       groovyShell = new JMenuItem();
1319       groovyShell.setText("Groovy Console...");
1320       groovyShell.addActionListener(new ActionListener()
1321       {
1322           public void actionPerformed(ActionEvent e) {
1323               groovyShell_actionPerformed(e);
1324           }
1325       });
1326       toolsMenu.add(groovyShell);
1327       groovyShell.setVisible(true);
1328     }
1329   }
1330   /**
1331    * Accessor method to quickly get all the AlignmentFrames
1332    * loaded.
1333    */
1334   public static AlignFrame[] getAlignframes() {
1335     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1336
1337     if (frames == null)
1338     {
1339       return null;
1340       }
1341       Vector avp=new Vector();
1342       try
1343       {
1344           //REVERSE ORDER
1345           for (int i = frames.length - 1; i > -1; i--)
1346           {
1347               if (frames[i] instanceof AlignFrame)
1348               {
1349                   AlignFrame af = (AlignFrame) frames[i];
1350                   avp.addElement(af);
1351               }
1352           }
1353       }
1354       catch (Exception ex)
1355       {
1356           ex.printStackTrace();
1357       }
1358       if (avp.size()==0)
1359       {
1360           return null;
1361       }
1362       AlignFrame afs[] = new AlignFrame[avp.size()];
1363       for (int i=0,j=avp.size(); i<j; i++) {
1364           afs[i] = (AlignFrame) avp.elementAt(i);
1365       }
1366       avp.clear();
1367       return afs;
1368   }
1369
1370   /**
1371     * Add Groovy Support to Jalview
1372     */
1373   public void groovyShell_actionPerformed(ActionEvent e) {
1374     // use reflection to avoid creating compilation dependency.
1375     if (!jalview.bin.Cache.groovyJarsPresent())
1376     {
1377       throw new Error("Implementation Error. Cannot create groovyShell without Groovy on the classpath!");
1378     }
1379     try {
1380     Class gcClass = Desktop.class.getClassLoader().loadClass("groovy.ui.Console");
1381     Constructor gccons = gcClass.getConstructor(null);
1382     java.lang.reflect.Method setvar = gcClass.getMethod("setVariable", new Class[] { String.class, Object.class} );
1383     java.lang.reflect.Method run = gcClass.getMethod("run", null);
1384     Object gc = gccons.newInstance(null);
1385     setvar.invoke(gc, new Object[] { "Jalview", this});
1386     run.invoke(gc, null);
1387     }
1388     catch (Exception ex)
1389     {
1390       jalview.bin.Cache.log.error("Groovy Shell Creation failed.",ex);
1391       JOptionPane.showInternalMessageDialog(Desktop.desktop,
1392
1393               "Couldn't create the groovy Shell. Check the error log for the details of what went wrong.", "Jalview Groovy Support Failed",
1394               JOptionPane.ERROR_MESSAGE);
1395     }
1396   }
1397
1398   /**
1399    *  Progress bars managed by the IProgressIndicator method.
1400    */
1401   private Hashtable progressBars;
1402   /* (non-Javadoc)
1403    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1404    */
1405   public void setProgressBar(String message, long id)
1406   {
1407     if(progressBars == null)
1408     {
1409       progressBars = new Hashtable();
1410     }
1411
1412     if(progressBars.get( new Long(id) )!=null)
1413     {
1414       JProgressBar progressPanel = (JProgressBar)progressBars.remove( new Long(id) );
1415        removeProgressPanel(progressPanel);
1416     } else {
1417       progressBars.put(new Long(id), addProgressPanel(message));
1418     }
1419   }
1420 }