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