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