JAL-1812 JAL-2068 only allow one Groovy console open at a time
[jalview.git] / src / jalview / gui / Desktop.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.api.AlignViewportI;
24 import jalview.api.AlignmentViewPanel;
25 import jalview.bin.Cache;
26 import jalview.bin.Jalview;
27 import jalview.io.FileLoader;
28 import jalview.io.FormatAdapter;
29 import jalview.io.IdentifyFile;
30 import jalview.io.JalviewFileChooser;
31 import jalview.io.JalviewFileView;
32 import jalview.jbgui.GSplitFrame;
33 import jalview.jbgui.GStructureViewer;
34 import jalview.structure.StructureSelectionManager;
35 import jalview.util.ImageMaker;
36 import jalview.util.MessageManager;
37 import jalview.util.Platform;
38 import jalview.viewmodel.AlignmentViewport;
39 import jalview.ws.params.ParamManager;
40
41 import java.awt.BorderLayout;
42 import java.awt.Color;
43 import java.awt.Dimension;
44 import java.awt.FontMetrics;
45 import java.awt.Graphics;
46 import java.awt.GridLayout;
47 import java.awt.Point;
48 import java.awt.Rectangle;
49 import java.awt.Toolkit;
50 import java.awt.Window;
51 import java.awt.datatransfer.Clipboard;
52 import java.awt.datatransfer.ClipboardOwner;
53 import java.awt.datatransfer.DataFlavor;
54 import java.awt.datatransfer.Transferable;
55 import java.awt.dnd.DnDConstants;
56 import java.awt.dnd.DropTargetDragEvent;
57 import java.awt.dnd.DropTargetDropEvent;
58 import java.awt.dnd.DropTargetEvent;
59 import java.awt.dnd.DropTargetListener;
60 import java.awt.event.ActionEvent;
61 import java.awt.event.ActionListener;
62 import java.awt.event.FocusEvent;
63 import java.awt.event.FocusListener;
64 import java.awt.event.MouseAdapter;
65 import java.awt.event.MouseEvent;
66 import java.awt.event.MouseListener;
67 import java.awt.event.WindowAdapter;
68 import java.awt.event.WindowEvent;
69 import java.beans.PropertyChangeEvent;
70 import java.beans.PropertyChangeListener;
71 import java.beans.PropertyVetoException;
72 import java.io.BufferedInputStream;
73 import java.io.File;
74 import java.io.FileOutputStream;
75 import java.lang.reflect.Constructor;
76 import java.lang.reflect.InvocationTargetException;
77 import java.lang.reflect.Method;
78 import java.net.URL;
79 import java.util.ArrayList;
80 import java.util.Hashtable;
81 import java.util.List;
82 import java.util.StringTokenizer;
83 import java.util.Vector;
84 import java.util.concurrent.ExecutorService;
85 import java.util.concurrent.Executors;
86 import java.util.concurrent.Semaphore;
87
88 import javax.swing.DefaultDesktopManager;
89 import javax.swing.DesktopManager;
90 import javax.swing.JButton;
91 import javax.swing.JComboBox;
92 import javax.swing.JComponent;
93 import javax.swing.JDesktopPane;
94 import javax.swing.JFrame;
95 import javax.swing.JInternalFrame;
96 import javax.swing.JLabel;
97 import javax.swing.JMenuItem;
98 import javax.swing.JOptionPane;
99 import javax.swing.JPanel;
100 import javax.swing.JPopupMenu;
101 import javax.swing.JProgressBar;
102 import javax.swing.SwingUtilities;
103 import javax.swing.event.HyperlinkEvent;
104 import javax.swing.event.HyperlinkEvent.EventType;
105 import javax.swing.event.MenuEvent;
106 import javax.swing.event.MenuListener;
107
108 /**
109  * Jalview Desktop
110  * 
111  * 
112  * @author $author$
113  * @version $Revision: 1.155 $
114  */
115 public class Desktop extends jalview.jbgui.GDesktop implements
116         DropTargetListener, ClipboardOwner, IProgressIndicator,
117         jalview.api.StructureSelectionManagerProvider
118 {
119
120   private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
121
122   /**
123    * news reader - null if it was never started.
124    */
125   private BlogReader jvnews = null;
126
127   private File projectFile;
128
129   /**
130    * @param listener
131    * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.beans.PropertyChangeListener)
132    */
133   public void addJalviewPropertyChangeListener(
134           PropertyChangeListener listener)
135   {
136     changeSupport.addJalviewPropertyChangeListener(listener);
137   }
138
139   /**
140    * @param propertyName
141    * @param listener
142    * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.lang.String,
143    *      java.beans.PropertyChangeListener)
144    */
145   public void addJalviewPropertyChangeListener(String propertyName,
146           PropertyChangeListener listener)
147   {
148     changeSupport.addJalviewPropertyChangeListener(propertyName, listener);
149   }
150
151   /**
152    * @param propertyName
153    * @param listener
154    * @see jalview.gui.JalviewChangeSupport#removeJalviewPropertyChangeListener(java.lang.String,
155    *      java.beans.PropertyChangeListener)
156    */
157   public void removeJalviewPropertyChangeListener(String propertyName,
158           PropertyChangeListener listener)
159   {
160     changeSupport.removeJalviewPropertyChangeListener(propertyName,
161             listener);
162   }
163
164   /** Singleton Desktop instance */
165   public static Desktop instance;
166
167   public static MyDesktopPane desktop;
168
169   static int openFrameCount = 0;
170
171   static final int xOffset = 30;
172
173   static final int yOffset = 30;
174
175   private static AlignFrame currentAlignFrame;
176
177   public static jalview.ws.jws1.Discoverer discoverer;
178
179   public static Object[] jalviewClipboard;
180
181   public static boolean internalCopy = false;
182
183   static int fileLoadingCount = 0;
184
185   class MyDesktopManager implements DesktopManager
186   {
187
188     private DesktopManager delegate;
189
190     public MyDesktopManager(DesktopManager delegate)
191     {
192       this.delegate = delegate;
193     }
194
195     @Override
196     public void activateFrame(JInternalFrame f)
197     {
198       try
199       {
200         delegate.activateFrame(f);
201       } catch (NullPointerException npe)
202       {
203         Point p = getMousePosition();
204         instance.showPasteMenu(p.x, p.y);
205       }
206     }
207
208     @Override
209     public void beginDraggingFrame(JComponent f)
210     {
211       delegate.beginDraggingFrame(f);
212     }
213
214     @Override
215     public void beginResizingFrame(JComponent f, int direction)
216     {
217       delegate.beginResizingFrame(f, direction);
218     }
219
220     @Override
221     public void closeFrame(JInternalFrame f)
222     {
223       delegate.closeFrame(f);
224     }
225
226     @Override
227     public void deactivateFrame(JInternalFrame f)
228     {
229       delegate.deactivateFrame(f);
230     }
231
232     @Override
233     public void deiconifyFrame(JInternalFrame f)
234     {
235       delegate.deiconifyFrame(f);
236     }
237
238     @Override
239     public void dragFrame(JComponent f, int newX, int newY)
240     {
241       if (newY < 0)
242       {
243         newY = 0;
244       }
245       delegate.dragFrame(f, newX, newY);
246     }
247
248     @Override
249     public void endDraggingFrame(JComponent f)
250     {
251       delegate.endDraggingFrame(f);
252     }
253
254     @Override
255     public void endResizingFrame(JComponent f)
256     {
257       delegate.endResizingFrame(f);
258     }
259
260     @Override
261     public void iconifyFrame(JInternalFrame f)
262     {
263       delegate.iconifyFrame(f);
264     }
265
266     @Override
267     public void maximizeFrame(JInternalFrame f)
268     {
269       delegate.maximizeFrame(f);
270     }
271
272     @Override
273     public void minimizeFrame(JInternalFrame f)
274     {
275       delegate.minimizeFrame(f);
276     }
277
278     @Override
279     public void openFrame(JInternalFrame f)
280     {
281       delegate.openFrame(f);
282     }
283
284     @Override
285     public void resizeFrame(JComponent f, int newX, int newY, int newWidth,
286             int newHeight)
287     {
288       if (newY < 0)
289       {
290         newY = 0;
291       }
292       delegate.resizeFrame(f, newX, newY, newWidth, newHeight);
293     }
294
295     @Override
296     public void setBoundsForFrame(JComponent f, int newX, int newY,
297             int newWidth, int newHeight)
298     {
299       delegate.setBoundsForFrame(f, newX, newY, newWidth, newHeight);
300     }
301
302     // All other methods, simply delegate
303
304   }
305
306   /**
307    * Creates a new Desktop object.
308    */
309   public Desktop()
310   {
311     /**
312      * A note to implementors. It is ESSENTIAL that any activities that might
313      * block are spawned off as threads rather than waited for during this
314      * constructor.
315      */
316     instance = this;
317     doVamsasClientCheck();
318     doGroovyCheck();
319     doConfigureStructurePrefs();
320     setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
321     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
322     boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",
323             false);
324     boolean showjconsole = jalview.bin.Cache.getDefault(
325             "SHOW_JAVA_CONSOLE", false);
326     desktop = new MyDesktopPane(selmemusage);
327     if (Platform.isAMac())
328     {
329       desktop.setDoubleBuffered(false);
330     }
331     showMemusage.setSelected(selmemusage);
332     desktop.setBackground(Color.white);
333     getContentPane().setLayout(new BorderLayout());
334     // alternate config - have scrollbars - see notes in JAL-153
335     // JScrollPane sp = new JScrollPane();
336     // sp.getViewport().setView(desktop);
337     // getContentPane().add(sp, BorderLayout.CENTER);
338     getContentPane().add(desktop, BorderLayout.CENTER);
339     desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
340
341     // This line prevents Windows Look&Feel resizing all new windows to maximum
342     // if previous window was maximised
343     desktop.setDesktopManager(new MyDesktopManager(
344             new DefaultDesktopManager()));
345
346     Rectangle dims = getLastKnownDimensions("");
347     if (dims != null)
348     {
349       setBounds(dims);
350     }
351     else
352     {
353       Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
354       setBounds((screenSize.width - 900) / 2,
355               (screenSize.height - 650) / 2, 900, 650);
356     }
357     jconsole = new Console(this, showjconsole);
358     // add essential build information
359     jconsole.setHeader("Jalview Version: "
360             + jalview.bin.Cache.getProperty("VERSION") + "\n"
361             + "Jalview Installation: "
362             + jalview.bin.Cache.getDefault("INSTALLATION", "unknown")
363             + "\n" + "Build Date: "
364             + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown") + "\n"
365             + "Java version: " + System.getProperty("java.version") + "\n"
366             + System.getProperty("os.arch") + " "
367             + System.getProperty("os.name") + " "
368             + System.getProperty("os.version"));
369
370     showConsole(showjconsole);
371
372     showNews.setVisible(false);
373
374     this.addWindowListener(new WindowAdapter()
375     {
376       @Override
377       public void windowClosing(WindowEvent evt)
378       {
379         quit();
380       }
381     });
382
383     MouseAdapter ma;
384     this.addMouseListener(ma = new MouseAdapter()
385     {
386       @Override
387       public void mousePressed(MouseEvent evt)
388       {
389         if (evt.isPopupTrigger())
390         {
391           showPasteMenu(evt.getX(), evt.getY());
392         }
393       }
394     });
395     desktop.addMouseListener(ma);
396
397     this.addFocusListener(new FocusListener()
398     {
399
400       @Override
401       public void focusLost(FocusEvent e)
402       {
403         // TODO Auto-generated method stub
404
405       }
406
407       @Override
408       public void focusGained(FocusEvent e)
409       {
410         Cache.log.debug("Relaying windows after focus gain");
411         // make sure that we sort windows properly after we gain focus
412         instance.relayerWindows();
413       }
414     });
415     this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
416     // Spawn a thread that shows the splashscreen
417     SwingUtilities.invokeLater(new Runnable()
418     {
419       @Override
420       public void run()
421       {
422         new SplashScreen();
423       }
424     });
425
426     // displayed.
427     // Thread off a new instance of the file chooser - this reduces the time it
428     // takes to open it later on.
429     new Thread(new Runnable()
430     {
431       @Override
432       public void run()
433       {
434         Cache.log.debug("Filechooser init thread started.");
435         new JalviewFileChooser(
436                 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
437                 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
438                 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
439                 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
440         Cache.log.debug("Filechooser init thread finished.");
441       }
442     }).start();
443     // Add the service change listener
444     changeSupport.addJalviewPropertyChangeListener("services",
445             new PropertyChangeListener()
446             {
447
448               @Override
449               public void propertyChange(PropertyChangeEvent evt)
450               {
451                 Cache.log.debug("Firing service changed event for "
452                         + evt.getNewValue());
453                 JalviewServicesChanged(evt);
454               }
455
456             });
457   }
458
459   public void doConfigureStructurePrefs()
460   {
461     // configure services
462     StructureSelectionManager ssm = StructureSelectionManager
463             .getStructureSelectionManager(this);
464     if (jalview.bin.Cache.getDefault(Preferences.ADD_SS_ANN, true))
465     {
466       ssm.setAddTempFacAnnot(jalview.bin.Cache.getDefault(
467               Preferences.ADD_TEMPFACT_ANN, true));
468       ssm.setProcessSecondaryStructure(jalview.bin.Cache.getDefault(
469               Preferences.STRUCT_FROM_PDB, true));
470       ssm.setSecStructServices(jalview.bin.Cache.getDefault(
471               Preferences.USE_RNAVIEW, true));
472     }
473     else
474     {
475       ssm.setAddTempFacAnnot(false);
476       ssm.setProcessSecondaryStructure(false);
477       ssm.setSecStructServices(false);
478     }
479   }
480
481   public void checkForNews()
482   {
483     final Desktop me = this;
484     // Thread off the news reader, in case there are connection problems.
485     addDialogThread(new Runnable()
486     {
487       @Override
488       public void run()
489       {
490         Cache.log.debug("Starting news thread.");
491
492         jvnews = new BlogReader(me);
493         showNews.setVisible(true);
494         Cache.log.debug("Completed news thread.");
495       }
496     });
497   }
498
499   @Override
500   protected void showNews_actionPerformed(ActionEvent e)
501   {
502     showNews(showNews.isSelected());
503   }
504
505   void showNews(boolean visible)
506   {
507     {
508       Cache.log.debug((visible ? "Showing" : "Hiding") + " news.");
509       showNews.setSelected(visible);
510       if (visible && !jvnews.isVisible())
511       {
512         new Thread(new Runnable()
513         {
514           @Override
515           public void run()
516           {
517             long now = System.currentTimeMillis();
518             Desktop.instance.setProgressBar(
519                     MessageManager.getString("status.refreshing_news"), now);
520             jvnews.refreshNews();
521             Desktop.instance.setProgressBar(null, now);
522             jvnews.showNews();
523           }
524         }).start();
525       }
526     }
527   }
528
529   /**
530    * recover the last known dimensions for a jalview window
531    * 
532    * @param windowName
533    *          - empty string is desktop, all other windows have unique prefix
534    * @return null or last known dimensions scaled to current geometry (if last
535    *         window geom was known)
536    */
537   Rectangle getLastKnownDimensions(String windowName)
538   {
539     // TODO: lock aspect ratio for scaling desktop Bug #0058199
540     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
541     String x = jalview.bin.Cache.getProperty(windowName + "SCREEN_X");
542     String y = jalview.bin.Cache.getProperty(windowName + "SCREEN_Y");
543     String width = jalview.bin.Cache.getProperty(windowName
544             + "SCREEN_WIDTH");
545     String height = jalview.bin.Cache.getProperty(windowName
546             + "SCREEN_HEIGHT");
547     if ((x != null) && (y != null) && (width != null) && (height != null))
548     {
549       int ix = Integer.parseInt(x), iy = Integer.parseInt(y), iw = Integer
550               .parseInt(width), ih = Integer.parseInt(height);
551       if (jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
552       {
553         // attempt #1 - try to cope with change in screen geometry - this
554         // version doesn't preserve original jv aspect ratio.
555         // take ratio of current screen size vs original screen size.
556         double sw = ((1f * screenSize.width) / (1f * Integer
557                 .parseInt(jalview.bin.Cache
558                         .getProperty("SCREENGEOMETRY_WIDTH"))));
559         double sh = ((1f * screenSize.height) / (1f * Integer
560                 .parseInt(jalview.bin.Cache
561                         .getProperty("SCREENGEOMETRY_HEIGHT"))));
562         // rescale the bounds depending upon the current screen geometry.
563         ix = (int) (ix * sw);
564         iw = (int) (iw * sw);
565         iy = (int) (iy * sh);
566         ih = (int) (ih * sh);
567         while (ix >= screenSize.width)
568         {
569           jalview.bin.Cache.log
570                   .debug("Window geometry location recall error: shifting horizontal to within screenbounds.");
571           ix -= screenSize.width;
572         }
573         while (iy >= screenSize.height)
574         {
575           jalview.bin.Cache.log
576                   .debug("Window geometry location recall error: shifting vertical to within screenbounds.");
577           iy -= screenSize.height;
578         }
579         jalview.bin.Cache.log.debug("Got last known dimensions for "
580                 + windowName + ": x:" + ix + " y:" + iy + " width:" + iw
581                 + " height:" + ih);
582       }
583       // return dimensions for new instance
584       return new Rectangle(ix, iy, iw, ih);
585     }
586     return null;
587   }
588
589   private void doVamsasClientCheck()
590   {
591     if (jalview.bin.Cache.vamsasJarsPresent())
592     {
593       setupVamsasDisconnectedGui();
594       VamsasMenu.setVisible(true);
595       final Desktop us = this;
596       VamsasMenu.addMenuListener(new MenuListener()
597       {
598         // this listener remembers when the menu was first selected, and
599         // doesn't rebuild the session list until it has been cleared and
600         // reselected again.
601         boolean refresh = true;
602
603         @Override
604         public void menuCanceled(MenuEvent e)
605         {
606           refresh = true;
607         }
608
609         @Override
610         public void menuDeselected(MenuEvent e)
611         {
612           refresh = true;
613         }
614
615         @Override
616         public void menuSelected(MenuEvent e)
617         {
618           if (refresh)
619           {
620             us.buildVamsasStMenu();
621             refresh = false;
622           }
623         }
624       });
625       vamsasStart.setVisible(true);
626     }
627   }
628
629   void showPasteMenu(int x, int y)
630   {
631     JPopupMenu popup = new JPopupMenu();
632     JMenuItem item = new JMenuItem(
633             MessageManager.getString("label.paste_new_window"));
634     item.addActionListener(new ActionListener()
635     {
636       @Override
637       public void actionPerformed(ActionEvent evt)
638       {
639         paste();
640       }
641     });
642
643     popup.add(item);
644     popup.show(this, x, y);
645   }
646
647   public void paste()
648   {
649     try
650     {
651       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
652       Transferable contents = c.getContents(this);
653
654       if (contents != null)
655       {
656         String file = (String) contents
657                 .getTransferData(DataFlavor.stringFlavor);
658
659         String format = new IdentifyFile().identify(file,
660                 FormatAdapter.PASTE);
661
662         new FileLoader().LoadFile(file, FormatAdapter.PASTE, format);
663
664       }
665     } catch (Exception ex)
666     {
667       System.out
668               .println("Unable to paste alignment from system clipboard:\n"
669                       + ex);
670     }
671   }
672
673   /**
674    * Adds and opens the given frame to the desktop
675    * 
676    * @param frame
677    *          Frame to show
678    * @param title
679    *          Visible Title
680    * @param w
681    *          width
682    * @param h
683    *          height
684    */
685   public static synchronized void addInternalFrame(
686           final JInternalFrame frame, String title, int w, int h)
687   {
688     addInternalFrame(frame, title, true, w, h, true);
689   }
690
691   /**
692    * Add an internal frame to the Jalview desktop
693    * 
694    * @param frame
695    *          Frame to show
696    * @param title
697    *          Visible Title
698    * @param makeVisible
699    *          When true, display frame immediately, otherwise, caller must call
700    *          setVisible themselves.
701    * @param w
702    *          width
703    * @param h
704    *          height
705    */
706   public static synchronized void addInternalFrame(
707           final JInternalFrame frame, String title, boolean makeVisible,
708           int w, int h)
709   {
710     addInternalFrame(frame, title, makeVisible, w, h, true);
711   }
712
713   /**
714    * Add an internal frame to the Jalview desktop and make it visible
715    * 
716    * @param frame
717    *          Frame to show
718    * @param title
719    *          Visible Title
720    * @param w
721    *          width
722    * @param h
723    *          height
724    * @param resizable
725    *          Allow resize
726    */
727   public static synchronized void addInternalFrame(
728           final JInternalFrame frame, String title, int w, int h,
729           boolean resizable)
730   {
731     addInternalFrame(frame, title, true, w, h, resizable);
732   }
733
734   /**
735    * Add an internal frame to the Jalview desktop
736    * 
737    * @param frame
738    *          Frame to show
739    * @param title
740    *          Visible Title
741    * @param makeVisible
742    *          When true, display frame immediately, otherwise, caller must call
743    *          setVisible themselves.
744    * @param w
745    *          width
746    * @param h
747    *          height
748    * @param resizable
749    *          Allow resize
750    */
751   public static synchronized void addInternalFrame(
752           final JInternalFrame frame, String title, boolean makeVisible,
753           int w, int h, boolean resizable)
754   {
755
756     // TODO: allow callers to determine X and Y position of frame (eg. via
757     // bounds object).
758     // TODO: consider fixing method to update entries in the window submenu with
759     // the current window title
760
761     frame.setTitle(title);
762     if (frame.getWidth() < 1 || frame.getHeight() < 1)
763     {
764       frame.setSize(w, h);
765     }
766     // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
767     // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
768     // IF JALVIEW IS RUNNING HEADLESS
769     // ///////////////////////////////////////////////
770     if (instance == null
771             || (System.getProperty("java.awt.headless") != null && System
772                     .getProperty("java.awt.headless").equals("true")))
773     {
774       return;
775     }
776
777     openFrameCount++;
778
779     frame.setVisible(makeVisible);
780     frame.setClosable(true);
781     frame.setResizable(resizable);
782     frame.setMaximizable(resizable);
783     frame.setIconifiable(resizable);
784     if (Platform.isAMac())
785     {
786       frame.setIconifiable(false);
787       frame.setFrameIcon(null);
788       // frame.setDesktopIcon(null);
789       frame.setDoubleBuffered(false);
790     }
791     if (frame.getX() < 1 && frame.getY() < 1)
792     {
793       frame.setLocation(xOffset * openFrameCount, yOffset
794               * ((openFrameCount - 1) % 10) + yOffset);
795     }
796
797     final JMenuItem menuItem = new JMenuItem(title);
798     frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
799     {
800       @Override
801       public void internalFrameActivated(
802               javax.swing.event.InternalFrameEvent evt)
803       {
804         JInternalFrame itf = desktop.getSelectedFrame();
805         if (itf != null)
806         {
807           itf.requestFocus();
808         }
809
810       }
811
812       @Override
813       public void internalFrameClosed(
814               javax.swing.event.InternalFrameEvent evt)
815       {
816         PaintRefresher.RemoveComponent(frame);
817         openFrameCount--;
818         windowMenu.remove(menuItem);
819         JInternalFrame itf = desktop.getSelectedFrame();
820         if (itf != null)
821         {
822           itf.requestFocus();
823         }
824         System.gc();
825       };
826     });
827
828     menuItem.addActionListener(new ActionListener()
829     {
830       @Override
831       public void actionPerformed(ActionEvent e)
832       {
833         try
834         {
835           frame.setSelected(true);
836           frame.setIcon(false);
837         } catch (java.beans.PropertyVetoException ex)
838         {
839
840         }
841       }
842     });
843     menuItem.addMouseListener(new MouseListener()
844     {
845
846       @Override
847       public void mouseReleased(MouseEvent e)
848       {
849       }
850
851       @Override
852       public void mousePressed(MouseEvent e)
853       {
854       }
855
856       @Override
857       public void mouseExited(MouseEvent e)
858       {
859         try
860         {
861           frame.setSelected(false);
862         } catch (PropertyVetoException e1)
863         {
864         }
865       }
866
867       @Override
868       public void mouseEntered(MouseEvent e)
869       {
870         try
871         {
872           frame.setSelected(true);
873         } catch (PropertyVetoException e1)
874         {
875         }
876       }
877
878       @Override
879       public void mouseClicked(MouseEvent e)
880       {
881
882       }
883     });
884
885     windowMenu.add(menuItem);
886
887     desktop.add(frame);
888     frame.toFront();
889     try
890     {
891       frame.setSelected(true);
892       frame.requestFocus();
893     } catch (java.beans.PropertyVetoException ve)
894     {
895     } catch (java.lang.ClassCastException cex)
896     {
897       Cache.log
898               .warn("Squashed a possible GUI implementation error. If you can recreate this, please look at http://issues.jalview.org/browse/JAL-869",
899                       cex);
900     }
901   }
902
903   @Override
904   public void lostOwnership(Clipboard clipboard, Transferable contents)
905   {
906     if (!internalCopy)
907     {
908       Desktop.jalviewClipboard = null;
909     }
910
911     internalCopy = false;
912   }
913
914   @Override
915   public void dragEnter(DropTargetDragEvent evt)
916   {
917   }
918
919   @Override
920   public void dragExit(DropTargetEvent evt)
921   {
922   }
923
924   @Override
925   public void dragOver(DropTargetDragEvent evt)
926   {
927   }
928
929   @Override
930   public void dropActionChanged(DropTargetDragEvent evt)
931   {
932   }
933
934   /**
935    * DOCUMENT ME!
936    * 
937    * @param evt
938    *          DOCUMENT ME!
939    */
940   @Override
941   public void drop(DropTargetDropEvent evt)
942   {
943     boolean success = true;
944     Transferable t = evt.getTransferable();
945     java.util.List files = null;
946     java.util.List protocols = null;
947
948     try
949     {
950       DataFlavor uriListFlavor = new DataFlavor(
951               "text/uri-list;class=java.lang.String");
952       if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
953       {
954         // Works on Windows and MacOSX
955         evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
956         files = (java.util.List) t
957                 .getTransferData(DataFlavor.javaFileListFlavor);
958       }
959       else if (t.isDataFlavorSupported(uriListFlavor))
960       {
961         // This is used by Unix drag system
962         evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
963         String data = (String) t.getTransferData(uriListFlavor);
964         files = new java.util.ArrayList(1);
965         protocols = new java.util.ArrayList(1);
966         for (java.util.StringTokenizer st = new java.util.StringTokenizer(
967                 data, "\r\n"); st.hasMoreTokens();)
968         {
969           String s = st.nextToken();
970           if (s.startsWith("#"))
971           {
972             // the line is a comment (as per the RFC 2483)
973             continue;
974           }
975           java.net.URI uri = new java.net.URI(s);
976           if (uri.getScheme().toLowerCase().startsWith("http"))
977           {
978             protocols.add(FormatAdapter.URL);
979             files.add(uri.toString());
980           }
981           else
982           {
983             // otherwise preserve old behaviour: catch all for file objects
984             java.io.File file = new java.io.File(uri);
985             protocols.add(FormatAdapter.FILE);
986             files.add(file.toString());
987           }
988         }
989       }
990     } catch (Exception e)
991     {
992       success = false;
993     }
994
995     if (files != null)
996     {
997       try
998       {
999         for (int i = 0; i < files.size(); i++)
1000         {
1001           String file = files.get(i).toString();
1002           String protocol = (protocols == null) ? FormatAdapter.FILE
1003                   : (String) protocols.get(i);
1004           String format = null;
1005
1006           if (file.endsWith(".jar"))
1007           {
1008             format = "Jalview";
1009
1010           }
1011           else
1012           {
1013             format = new IdentifyFile().identify(file, protocol);
1014           }
1015
1016           new FileLoader().LoadFile(file, protocol, format);
1017
1018         }
1019       } catch (Exception ex)
1020       {
1021         success = false;
1022       }
1023     }
1024     evt.dropComplete(success); // need this to ensure input focus is properly
1025                                // transfered to any new windows created
1026   }
1027
1028   /**
1029    * DOCUMENT ME!
1030    * 
1031    * @param e
1032    *          DOCUMENT ME!
1033    */
1034   @Override
1035   public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
1036   {
1037     JalviewFileChooser chooser = new JalviewFileChooser(
1038             jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1039             jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
1040             jalview.io.AppletFormatAdapter.READABLE_FNAMES,
1041             jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
1042
1043     chooser.setFileView(new JalviewFileView());
1044     chooser.setDialogTitle(MessageManager
1045             .getString("label.open_local_file"));
1046     chooser.setToolTipText(MessageManager.getString("action.open"));
1047
1048     int value = chooser.showOpenDialog(this);
1049
1050     if (value == JalviewFileChooser.APPROVE_OPTION)
1051     {
1052       String choice = chooser.getSelectedFile().getPath();
1053       jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
1054               .getSelectedFile().getParent());
1055
1056       String format = null;
1057       if (chooser.getSelectedFormat() != null
1058               && chooser.getSelectedFormat().equals("Jalview"))
1059       {
1060         format = "Jalview";
1061       }
1062       else
1063       {
1064         format = new IdentifyFile().identify(choice, FormatAdapter.FILE);
1065       }
1066
1067       if (viewport != null)
1068       {
1069         new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE,
1070                 format);
1071       }
1072       else
1073       {
1074         new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
1075       }
1076     }
1077   }
1078
1079   /**
1080    * DOCUMENT ME!
1081    * 
1082    * @param e
1083    *          DOCUMENT ME!
1084    */
1085   @Override
1086   public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
1087   {
1088     // This construct allows us to have a wider textfield
1089     // for viewing
1090     JLabel label = new JLabel(
1091             MessageManager.getString("label.input_file_url"));
1092     final JComboBox history = new JComboBox();
1093
1094     JPanel panel = new JPanel(new GridLayout(2, 1));
1095     panel.add(label);
1096     panel.add(history);
1097     history.setPreferredSize(new Dimension(400, 20));
1098     history.setEditable(true);
1099     history.addItem("http://www.");
1100
1101     String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
1102
1103     StringTokenizer st;
1104
1105     if (historyItems != null)
1106     {
1107       st = new StringTokenizer(historyItems, "\t");
1108
1109       while (st.hasMoreTokens())
1110       {
1111         history.addItem(st.nextElement());
1112       }
1113     }
1114
1115     int reply = JOptionPane.showInternalConfirmDialog(desktop, panel,
1116             MessageManager.getString("label.input_alignment_from_url"),
1117             JOptionPane.OK_CANCEL_OPTION);
1118
1119     if (reply != JOptionPane.OK_OPTION)
1120     {
1121       return;
1122     }
1123
1124     String url = history.getSelectedItem().toString();
1125
1126     if (url.toLowerCase().endsWith(".jar"))
1127     {
1128       if (viewport != null)
1129       {
1130         new FileLoader().LoadFile(viewport, url, FormatAdapter.URL,
1131                 "Jalview");
1132       }
1133       else
1134       {
1135         new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
1136       }
1137     }
1138     else
1139     {
1140       String format = new IdentifyFile().identify(url, FormatAdapter.URL);
1141
1142       if (format.equals("URL NOT FOUND"))
1143       {
1144         JOptionPane.showInternalMessageDialog(Desktop.desktop,
1145                 MessageManager.formatMessage("label.couldnt_locate",
1146                         new Object[] { url }), MessageManager
1147                         .getString("label.url_not_found"),
1148                 JOptionPane.WARNING_MESSAGE);
1149
1150         return;
1151       }
1152
1153       if (viewport != null)
1154       {
1155         new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
1156       }
1157       else
1158       {
1159         new FileLoader().LoadFile(url, FormatAdapter.URL, format);
1160       }
1161     }
1162   }
1163
1164   /**
1165    * Opens the CutAndPaste window for the user to paste an alignment in to
1166    * 
1167    * @param viewPanel
1168    *          - if not null, the pasted alignment is added to the current
1169    *          alignment; if null, to a new alignment window
1170    */
1171   @Override
1172   public void inputTextboxMenuItem_actionPerformed(
1173           AlignmentViewPanel viewPanel)
1174   {
1175     CutAndPasteTransfer cap = new CutAndPasteTransfer();
1176     cap.setForInput(viewPanel);
1177     Desktop.addInternalFrame(cap,
1178             MessageManager.getString("label.cut_paste_alignmen_file"),
1179             true, 600, 500);
1180   }
1181
1182   /*
1183    * Exit the program
1184    */
1185   @Override
1186   public void quit()
1187   {
1188     Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
1189     jalview.bin.Cache
1190             .setProperty("SCREENGEOMETRY_WIDTH", screen.width + "");
1191     jalview.bin.Cache.setProperty("SCREENGEOMETRY_HEIGHT", screen.height
1192             + "");
1193     storeLastKnownDimensions("", new Rectangle(getBounds().x,
1194             getBounds().y, getWidth(), getHeight()));
1195
1196     if (jconsole != null)
1197     {
1198       storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
1199       jconsole.stopConsole();
1200     }
1201     if (jvnews != null)
1202     {
1203       storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
1204
1205     }
1206     if (dialogExecutor != null)
1207     {
1208       dialogExecutor.shutdownNow();
1209     }
1210     closeAll_actionPerformed(null);
1211     System.exit(0);
1212   }
1213
1214   private void storeLastKnownDimensions(String string, Rectangle jc)
1215   {
1216     jalview.bin.Cache.log.debug("Storing last known dimensions for "
1217             + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
1218             + " height:" + jc.height);
1219
1220     jalview.bin.Cache.setProperty(string + "SCREEN_X", jc.x + "");
1221     jalview.bin.Cache.setProperty(string + "SCREEN_Y", jc.y + "");
1222     jalview.bin.Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
1223     jalview.bin.Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
1224   }
1225
1226   /**
1227    * DOCUMENT ME!
1228    * 
1229    * @param e
1230    *          DOCUMENT ME!
1231    */
1232   @Override
1233   public void aboutMenuItem_actionPerformed(ActionEvent e)
1234   {
1235     // StringBuffer message = getAboutMessage(false);
1236     // JOptionPane.showInternalMessageDialog(Desktop.desktop,
1237     //
1238     // message.toString(), "About Jalview", JOptionPane.INFORMATION_MESSAGE);
1239     new Thread(new Runnable()
1240     {
1241       @Override
1242       public void run()
1243       {
1244         new SplashScreen(true);
1245       }
1246     }).start();
1247   }
1248
1249   public StringBuffer getAboutMessage(boolean shortv)
1250   {
1251     StringBuffer message = new StringBuffer();
1252     message.append("<html>");
1253     if (shortv)
1254     {
1255       message.append("<h1><strong>Version: "
1256               + jalview.bin.Cache.getProperty("VERSION") + "</strong></h1>");
1257       message.append("<strong>Last Updated: <em>"
1258               + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown")
1259               + "</em></strong>");
1260
1261     }
1262     else
1263     {
1264
1265       message.append("<strong>Version "
1266               + jalview.bin.Cache.getProperty("VERSION")
1267               + "; last updated: "
1268               + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1269     }
1270
1271     if (jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking").equals(
1272             "Checking"))
1273     {
1274       message.append("<br>...Checking latest version...</br>");
1275     }
1276     else if (!jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking")
1277             .equals(jalview.bin.Cache.getProperty("VERSION")))
1278     {
1279       boolean red = false;
1280       if (jalview.bin.Cache.getProperty("VERSION").toLowerCase()
1281               .indexOf("automated build") == -1)
1282       {
1283         red = true;
1284         // Displayed when code version and jnlp version do not match and code
1285         // version is not a development build
1286         message.append("<div style=\"color: #FF0000;font-style: bold;\">");
1287       }
1288
1289       message.append("<br>!! Version "
1290               + jalview.bin.Cache.getDefault("LATEST_VERSION",
1291                       "..Checking..")
1292               + " is available for download from "
1293               + jalview.bin.Cache.getDefault("www.jalview.org",
1294                       "http://www.jalview.org") + " !!");
1295       if (red)
1296       {
1297         message.append("</div>");
1298       }
1299     }
1300     message.append("<br>Authors:  "
1301             + jalview.bin.Cache
1302                     .getDefault("AUTHORFNAMES",
1303                             "The Jalview Authors (See AUTHORS file for current list)")
1304             + "<br><br>Development managed by The Barton Group, University of Dundee, Scotland, UK.<br>"
1305             + "<br><br>For help, see the FAQ at <a href=\"http://www.jalview.org/faq\">www.jalview.org/faq</a> and/or join the jalview-discuss@jalview.org mailing list"
1306             + "<br><br>If  you use Jalview, please cite:"
1307             + "<br>Waterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
1308             + "<br>Jalview Version 2 - a multiple sequence alignment editor and analysis workbench"
1309             + "<br>Bioinformatics doi: 10.1093/bioinformatics/btp033"
1310             + "</html>");
1311     return message;
1312   }
1313
1314   /**
1315    * DOCUMENT ME!
1316    * 
1317    * @param e
1318    *          DOCUMENT ME!
1319    */
1320   @Override
1321   public void documentationMenuItem_actionPerformed(ActionEvent e)
1322   {
1323     try
1324     {
1325       Help.showHelpWindow();
1326     } catch (Exception ex)
1327     {
1328     }
1329   }
1330
1331   @Override
1332   public void closeAll_actionPerformed(ActionEvent e)
1333   {
1334     JInternalFrame[] frames = desktop.getAllFrames();
1335     for (int i = 0; i < frames.length; i++)
1336     {
1337       try
1338       {
1339         frames[i].setClosed(true);
1340       } catch (java.beans.PropertyVetoException ex)
1341       {
1342       }
1343     }
1344     System.out.println("ALL CLOSED");
1345     if (v_client != null)
1346     {
1347       // TODO clear binding to vamsas document objects on close_all
1348     }
1349
1350     /*
1351      * reset state of singleton objects as appropriate (clear down session state
1352      * when all windows are closed)
1353      */
1354     StructureSelectionManager ssm = StructureSelectionManager
1355             .getStructureSelectionManager(this);
1356     if (ssm != null)
1357     {
1358       ssm.resetAll();
1359     }
1360   }
1361
1362   @Override
1363   public void raiseRelated_actionPerformed(ActionEvent e)
1364   {
1365     reorderAssociatedWindows(false, false);
1366   }
1367
1368   @Override
1369   public void minimizeAssociated_actionPerformed(ActionEvent e)
1370   {
1371     reorderAssociatedWindows(true, false);
1372   }
1373
1374   void closeAssociatedWindows()
1375   {
1376     reorderAssociatedWindows(false, true);
1377   }
1378
1379   /*
1380    * (non-Javadoc)
1381    * 
1382    * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1383    * ActionEvent)
1384    */
1385   @Override
1386   protected void garbageCollect_actionPerformed(ActionEvent e)
1387   {
1388     // We simply collect the garbage
1389     jalview.bin.Cache.log.debug("Collecting garbage...");
1390     System.gc();
1391     jalview.bin.Cache.log.debug("Finished garbage collection.");
1392   }
1393
1394   /*
1395    * (non-Javadoc)
1396    * 
1397    * @see
1398    * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
1399    * )
1400    */
1401   @Override
1402   protected void showMemusage_actionPerformed(ActionEvent e)
1403   {
1404     desktop.showMemoryUsage(showMemusage.isSelected());
1405   }
1406
1407   /*
1408    * (non-Javadoc)
1409    * 
1410    * @see
1411    * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1412    * )
1413    */
1414   @Override
1415   protected void showConsole_actionPerformed(ActionEvent e)
1416   {
1417     showConsole(showConsole.isSelected());
1418   }
1419
1420   Console jconsole = null;
1421
1422   /**
1423    * control whether the java console is visible or not
1424    * 
1425    * @param selected
1426    */
1427   void showConsole(boolean selected)
1428   {
1429     showConsole.setSelected(selected);
1430     // TODO: decide if we should update properties file
1431     Cache.setProperty("SHOW_JAVA_CONSOLE", Boolean.valueOf(selected)
1432             .toString());
1433     jconsole.setVisible(selected);
1434   }
1435
1436   void reorderAssociatedWindows(boolean minimize, boolean close)
1437   {
1438     JInternalFrame[] frames = desktop.getAllFrames();
1439     if (frames == null || frames.length < 1)
1440     {
1441       return;
1442     }
1443
1444     AlignmentViewport source = null, target = null;
1445     if (frames[0] instanceof AlignFrame)
1446     {
1447       source = ((AlignFrame) frames[0]).getCurrentView();
1448     }
1449     else if (frames[0] instanceof TreePanel)
1450     {
1451       source = ((TreePanel) frames[0]).getViewPort();
1452     }
1453     else if (frames[0] instanceof PCAPanel)
1454     {
1455       source = ((PCAPanel) frames[0]).av;
1456     }
1457     else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1458     {
1459       source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1460     }
1461
1462     if (source != null)
1463     {
1464       for (int i = 0; i < frames.length; i++)
1465       {
1466         target = null;
1467         if (frames[i] == null)
1468         {
1469           continue;
1470         }
1471         if (frames[i] instanceof AlignFrame)
1472         {
1473           target = ((AlignFrame) frames[i]).getCurrentView();
1474         }
1475         else if (frames[i] instanceof TreePanel)
1476         {
1477           target = ((TreePanel) frames[i]).getViewPort();
1478         }
1479         else if (frames[i] instanceof PCAPanel)
1480         {
1481           target = ((PCAPanel) frames[i]).av;
1482         }
1483         else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1484         {
1485           target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1486         }
1487
1488         if (source == target)
1489         {
1490           try
1491           {
1492             if (close)
1493             {
1494               frames[i].setClosed(true);
1495             }
1496             else
1497             {
1498               frames[i].setIcon(minimize);
1499               if (!minimize)
1500               {
1501                 frames[i].toFront();
1502               }
1503             }
1504
1505           } catch (java.beans.PropertyVetoException ex)
1506           {
1507           }
1508         }
1509       }
1510     }
1511   }
1512
1513   /**
1514    * DOCUMENT ME!
1515    * 
1516    * @param e
1517    *          DOCUMENT ME!
1518    */
1519   @Override
1520   protected void preferences_actionPerformed(ActionEvent e)
1521   {
1522     new Preferences();
1523   }
1524
1525   /**
1526    * DOCUMENT ME!
1527    * 
1528    * @param e
1529    *          DOCUMENT ME!
1530    */
1531   @Override
1532   public void saveState_actionPerformed(ActionEvent e)
1533   {
1534     JalviewFileChooser chooser = new JalviewFileChooser(
1535             jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
1536             new String[] { "jvp" }, new String[] { "Jalview Project" },
1537             "Jalview Project");
1538
1539     chooser.setFileView(new JalviewFileView());
1540     chooser.setDialogTitle(MessageManager.getString("label.save_state"));
1541
1542     int value = chooser.showSaveDialog(this);
1543
1544     if (value == JalviewFileChooser.APPROVE_OPTION)
1545     {
1546       final Desktop me = this;
1547       final java.io.File choice = chooser.getSelectedFile();
1548       setProjectFile(choice);
1549
1550       new Thread(new Runnable()
1551       {
1552         @Override
1553         public void run()
1554         {
1555           // TODO: refactor to Jalview desktop session controller action.
1556           setProgressBar(MessageManager.formatMessage(
1557                   "label.saving_jalview_project",
1558                   new Object[] { choice.getName() }), choice.hashCode());
1559           jalview.bin.Cache.setProperty("LAST_DIRECTORY",
1560                   choice.getParent());
1561           // TODO catch and handle errors for savestate
1562           // TODO prevent user from messing with the Desktop whilst we're saving
1563           try
1564           {
1565             new Jalview2XML().saveState(choice);
1566           } catch (OutOfMemoryError oom)
1567           {
1568             new OOMWarning("Whilst saving current state to "
1569                     + choice.getName(), oom);
1570           } catch (Exception ex)
1571           {
1572             Cache.log.error(
1573                     "Problems whilst trying to save to " + choice.getName(),
1574                     ex);
1575             JOptionPane.showMessageDialog(me, MessageManager.formatMessage(
1576                     "label.error_whilst_saving_current_state_to",
1577                     new Object[] { choice.getName() }), MessageManager
1578                     .getString("label.couldnt_save_project"),
1579                     JOptionPane.WARNING_MESSAGE);
1580           }
1581           setProgressBar(null, choice.hashCode());
1582         }
1583       }).start();
1584     }
1585   }
1586
1587   private void setProjectFile(File choice)
1588   {
1589     this.projectFile = choice;
1590   }
1591
1592   public File getProjectFile()
1593   {
1594     return this.projectFile;
1595   }
1596
1597   /**
1598    * DOCUMENT ME!
1599    * 
1600    * @param e
1601    *          DOCUMENT ME!
1602    */
1603   @Override
1604   public void loadState_actionPerformed(ActionEvent e)
1605   {
1606     JalviewFileChooser chooser = new JalviewFileChooser(
1607             jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[] {
1608                 "jvp", "jar" }, new String[] { "Jalview Project",
1609                 "Jalview Project (old)" }, "Jalview Project");
1610     chooser.setFileView(new JalviewFileView());
1611     chooser.setDialogTitle(MessageManager.getString("label.restore_state"));
1612
1613     int value = chooser.showOpenDialog(this);
1614
1615     if (value == JalviewFileChooser.APPROVE_OPTION)
1616     {
1617       final File selectedFile = chooser.getSelectedFile();
1618       setProjectFile(selectedFile);
1619       final String choice = selectedFile.getAbsolutePath();
1620       jalview.bin.Cache.setProperty("LAST_DIRECTORY",
1621               selectedFile.getParent());
1622       new Thread(new Runnable()
1623       {
1624         @Override
1625         public void run()
1626         {
1627           setProgressBar(
1628                   MessageManager.formatMessage(
1629                           "label.loading_jalview_project",
1630                           new Object[] { choice }), choice.hashCode());
1631           try
1632           {
1633             new Jalview2XML().loadJalviewAlign(choice);
1634           } catch (OutOfMemoryError oom)
1635           {
1636             new OOMWarning("Whilst loading project from " + choice, oom);
1637           } catch (Exception ex)
1638           {
1639             Cache.log.error("Problems whilst loading project from "
1640                     + choice, ex);
1641             JOptionPane.showMessageDialog(Desktop.desktop, MessageManager
1642                     .formatMessage(
1643                             "label.error_whilst_loading_project_from",
1644                             new Object[] { choice }), MessageManager
1645                     .getString("label.couldnt_load_project"),
1646                     JOptionPane.WARNING_MESSAGE);
1647           }
1648           setProgressBar(null, choice.hashCode());
1649         }
1650       }).start();
1651     }
1652   }
1653
1654   @Override
1655   public void inputSequence_actionPerformed(ActionEvent e)
1656   {
1657     new SequenceFetcher(this);
1658   }
1659
1660   JPanel progressPanel;
1661
1662   ArrayList<JPanel> fileLoadingPanels = new ArrayList<JPanel>();
1663
1664   public void startLoading(final String fileName)
1665   {
1666     if (fileLoadingCount == 0)
1667     {
1668       fileLoadingPanels.add(addProgressPanel(MessageManager.formatMessage(
1669               "label.loading_file", new Object[] { fileName })));
1670     }
1671     fileLoadingCount++;
1672   }
1673
1674   private JPanel addProgressPanel(String string)
1675   {
1676     if (progressPanel == null)
1677     {
1678       progressPanel = new JPanel(new GridLayout(1, 1));
1679       totalProgressCount = 0;
1680       instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
1681     }
1682     JPanel thisprogress = new JPanel(new BorderLayout(10, 5));
1683     JProgressBar progressBar = new JProgressBar();
1684     progressBar.setIndeterminate(true);
1685
1686     thisprogress.add(new JLabel(string), BorderLayout.WEST);
1687
1688     thisprogress.add(progressBar, BorderLayout.CENTER);
1689     progressPanel.add(thisprogress);
1690     ((GridLayout) progressPanel.getLayout())
1691             .setRows(((GridLayout) progressPanel.getLayout()).getRows() + 1);
1692     ++totalProgressCount;
1693     instance.validate();
1694     return thisprogress;
1695   }
1696
1697   int totalProgressCount = 0;
1698
1699   private void removeProgressPanel(JPanel progbar)
1700   {
1701     if (progressPanel != null)
1702     {
1703       synchronized (progressPanel)
1704       {
1705         progressPanel.remove(progbar);
1706         GridLayout gl = (GridLayout) progressPanel.getLayout();
1707         gl.setRows(gl.getRows() - 1);
1708         if (--totalProgressCount < 1)
1709         {
1710           this.getContentPane().remove(progressPanel);
1711           progressPanel = null;
1712         }
1713       }
1714     }
1715     validate();
1716   }
1717
1718   public void stopLoading()
1719   {
1720     fileLoadingCount--;
1721     if (fileLoadingCount < 1)
1722     {
1723       while (fileLoadingPanels.size() > 0)
1724       {
1725         removeProgressPanel(fileLoadingPanels.remove(0));
1726       }
1727       fileLoadingPanels.clear();
1728       fileLoadingCount = 0;
1729     }
1730     validate();
1731   }
1732
1733   public static int getViewCount(String alignmentId)
1734   {
1735     AlignmentViewport[] aps = getViewports(alignmentId);
1736     return (aps == null) ? 0 : aps.length;
1737   }
1738
1739   /**
1740    * 
1741    * @param alignmentId
1742    *          - if null, all sets are returned
1743    * @return all AlignmentPanels concerning the alignmentId sequence set
1744    */
1745   public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
1746   {
1747     if (Desktop.desktop == null)
1748     {
1749       // no frames created and in headless mode
1750       // TODO: verify that frames are recoverable when in headless mode
1751       return null;
1752     }
1753     List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>();
1754     AlignFrame[] frames = getAlignFrames();
1755     if (frames == null)
1756     {
1757       return null;
1758     }
1759     for (AlignFrame af : frames)
1760     {
1761       for (AlignmentPanel ap : af.alignPanels)
1762       {
1763         if (alignmentId == null
1764                 || alignmentId.equals(ap.av.getSequenceSetId()))
1765         {
1766           aps.add(ap);
1767         }
1768       }
1769     }
1770     if (aps.size() == 0)
1771     {
1772       return null;
1773     }
1774     AlignmentPanel[] vap = aps.toArray(new AlignmentPanel[aps.size()]);
1775     return vap;
1776   }
1777
1778   /**
1779    * get all the viewports on an alignment.
1780    * 
1781    * @param sequenceSetId
1782    *          unique alignment id (may be null - all viewports returned in that
1783    *          case)
1784    * @return all viewports on the alignment bound to sequenceSetId
1785    */
1786   public static AlignmentViewport[] getViewports(String sequenceSetId)
1787   {
1788     List<AlignmentViewport> viewp = new ArrayList<AlignmentViewport>();
1789     if (desktop != null)
1790     {
1791       AlignFrame[] frames = Desktop.getAlignFrames();
1792
1793       for (AlignFrame afr : frames)
1794       {
1795         if (sequenceSetId == null
1796                 || afr.getViewport().getSequenceSetId()
1797                         .equals(sequenceSetId))
1798         {
1799           if (afr.alignPanels != null)
1800           {
1801             for (AlignmentPanel ap : afr.alignPanels)
1802             {
1803               if (sequenceSetId == null
1804                       || sequenceSetId.equals(ap.av.getSequenceSetId()))
1805               {
1806                 viewp.add(ap.av);
1807               }
1808             }
1809           }
1810           else
1811           {
1812             viewp.add(afr.getViewport());
1813           }
1814         }
1815       }
1816       if (viewp.size() > 0)
1817       {
1818         return viewp.toArray(new AlignmentViewport[viewp.size()]);
1819       }
1820     }
1821     return null;
1822   }
1823
1824   /**
1825    * Explode the views in the given frame into separate AlignFrame
1826    * 
1827    * @param af
1828    */
1829   public void explodeViews(AlignFrame af)
1830   {
1831     int size = af.alignPanels.size();
1832     if (size < 2)
1833     {
1834       return;
1835     }
1836
1837     for (int i = 0; i < size; i++)
1838     {
1839       AlignmentPanel ap = af.alignPanels.get(i);
1840       AlignFrame newaf = new AlignFrame(ap);
1841
1842       /*
1843        * Restore the view's last exploded frame geometry if known. Multiple
1844        * views from one exploded frame share and restore the same (frame)
1845        * position and size.
1846        */
1847       Rectangle geometry = ap.av.getExplodedGeometry();
1848       if (geometry != null)
1849       {
1850         newaf.setBounds(geometry);
1851       }
1852
1853       ap.av.setGatherViewsHere(false);
1854
1855       addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1856               AlignFrame.DEFAULT_HEIGHT);
1857     }
1858
1859     af.alignPanels.clear();
1860     af.closeMenuItem_actionPerformed(true);
1861
1862   }
1863
1864   /**
1865    * Gather expanded views (separate AlignFrame's) with the same sequence set
1866    * identifier back in to this frame as additional views, and close the
1867    * expanded views. Note the expanded frames may themselves have multiple
1868    * views. We take the lot.
1869    * 
1870    * @param source
1871    */
1872   public void gatherViews(AlignFrame source)
1873   {
1874     source.viewport.setGatherViewsHere(true);
1875     source.viewport.setExplodedGeometry(source.getBounds());
1876     JInternalFrame[] frames = desktop.getAllFrames();
1877     String viewId = source.viewport.getSequenceSetId();
1878
1879     for (int t = 0; t < frames.length; t++)
1880     {
1881       if (frames[t] instanceof AlignFrame && frames[t] != source)
1882       {
1883         AlignFrame af = (AlignFrame) frames[t];
1884         boolean gatherThis = false;
1885         for (int a = 0; a < af.alignPanels.size(); a++)
1886         {
1887           AlignmentPanel ap = af.alignPanels.get(a);
1888           if (viewId.equals(ap.av.getSequenceSetId()))
1889           {
1890             gatherThis = true;
1891             ap.av.setGatherViewsHere(false);
1892             ap.av.setExplodedGeometry(af.getBounds());
1893             source.addAlignmentPanel(ap, false);
1894           }
1895         }
1896
1897         if (gatherThis)
1898         {
1899           af.alignPanels.clear();
1900           af.closeMenuItem_actionPerformed(true);
1901         }
1902       }
1903     }
1904
1905   }
1906
1907   jalview.gui.VamsasApplication v_client = null;
1908
1909   @Override
1910   public void vamsasImport_actionPerformed(ActionEvent e)
1911   {
1912     if (v_client == null)
1913     {
1914       // Load and try to start a session.
1915       JalviewFileChooser chooser = new JalviewFileChooser(
1916               jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1917
1918       chooser.setFileView(new JalviewFileView());
1919       chooser.setDialogTitle(MessageManager
1920               .getString("label.open_saved_vamsas_session"));
1921       chooser.setToolTipText(MessageManager
1922               .getString("label.select_vamsas_session_opened_as_new_vamsas_session"));
1923
1924       int value = chooser.showOpenDialog(this);
1925
1926       if (value == JalviewFileChooser.APPROVE_OPTION)
1927       {
1928         String fle = chooser.getSelectedFile().toString();
1929         if (!vamsasImport(chooser.getSelectedFile()))
1930         {
1931           JOptionPane
1932                   .showInternalMessageDialog(
1933                           Desktop.desktop,
1934                           MessageManager.formatMessage(
1935                                   "label.couldnt_import_as_vamsas_session",
1936                                   new Object[] { fle }),
1937                           MessageManager
1938                                   .getString("label.vamsas_document_import_failed"),
1939                           JOptionPane.ERROR_MESSAGE);
1940         }
1941       }
1942     }
1943     else
1944     {
1945       jalview.bin.Cache.log
1946               .error("Implementation error - load session from a running session is not supported.");
1947     }
1948   }
1949
1950   /**
1951    * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1952    * 
1953    * @param file
1954    * @return true if import was a success and a session was started.
1955    */
1956   public boolean vamsasImport(URL url)
1957   {
1958     // TODO: create progress bar
1959     if (v_client != null)
1960     {
1961
1962       jalview.bin.Cache.log
1963               .error("Implementation error - load session from a running session is not supported.");
1964       return false;
1965     }
1966
1967     try
1968     {
1969       // copy the URL content to a temporary local file
1970       // TODO: be a bit cleverer here with nio (?!)
1971       File file = File.createTempFile("vdocfromurl", ".vdj");
1972       FileOutputStream fos = new FileOutputStream(file);
1973       BufferedInputStream bis = new BufferedInputStream(url.openStream());
1974       byte[] buffer = new byte[2048];
1975       int ln;
1976       while ((ln = bis.read(buffer)) > -1)
1977       {
1978         fos.write(buffer, 0, ln);
1979       }
1980       bis.close();
1981       fos.close();
1982       v_client = new jalview.gui.VamsasApplication(this, file,
1983               url.toExternalForm());
1984     } catch (Exception ex)
1985     {
1986       jalview.bin.Cache.log.error(
1987               "Failed to create new vamsas session from contents of URL "
1988                       + url, ex);
1989       return false;
1990     }
1991     setupVamsasConnectedGui();
1992     v_client.initial_update(); // TODO: thread ?
1993     return v_client.inSession();
1994   }
1995
1996   /**
1997    * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1998    * 
1999    * @param file
2000    * @return true if import was a success and a session was started.
2001    */
2002   public boolean vamsasImport(File file)
2003   {
2004     if (v_client != null)
2005     {
2006
2007       jalview.bin.Cache.log
2008               .error("Implementation error - load session from a running session is not supported.");
2009       return false;
2010     }
2011
2012     setProgressBar(MessageManager.formatMessage(
2013             "status.importing_vamsas_session_from",
2014             new Object[] { file.getName() }), file.hashCode());
2015     try
2016     {
2017       v_client = new jalview.gui.VamsasApplication(this, file, null);
2018     } catch (Exception ex)
2019     {
2020       setProgressBar(MessageManager.formatMessage(
2021               "status.importing_vamsas_session_from",
2022               new Object[] { file.getName() }), file.hashCode());
2023       jalview.bin.Cache.log.error(
2024               "New vamsas session from existing session file failed:", ex);
2025       return false;
2026     }
2027     setupVamsasConnectedGui();
2028     v_client.initial_update(); // TODO: thread ?
2029     setProgressBar(MessageManager.formatMessage(
2030             "status.importing_vamsas_session_from",
2031             new Object[] { file.getName() }), file.hashCode());
2032     return v_client.inSession();
2033   }
2034
2035   public boolean joinVamsasSession(String mysesid)
2036   {
2037     if (v_client != null)
2038     {
2039       throw new Error(
2040               MessageManager
2041                       .getString("error.try_join_vamsas_session_another"));
2042     }
2043     if (mysesid == null)
2044     {
2045       throw new Error(
2046               MessageManager.getString("error.invalid_vamsas_session_id"));
2047     }
2048     v_client = new VamsasApplication(this, mysesid);
2049     setupVamsasConnectedGui();
2050     v_client.initial_update();
2051     return (v_client.inSession());
2052   }
2053
2054   @Override
2055   public void vamsasStart_actionPerformed(ActionEvent e)
2056   {
2057     if (v_client == null)
2058     {
2059       // Start a session.
2060       // we just start a default session for moment.
2061       /*
2062        * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
2063        * getProperty("LAST_DIRECTORY"));
2064        * 
2065        * chooser.setFileView(new JalviewFileView());
2066        * chooser.setDialogTitle("Load Vamsas file");
2067        * chooser.setToolTipText("Import");
2068        * 
2069        * int value = chooser.showOpenDialog(this);
2070        * 
2071        * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
2072        * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
2073        */
2074       v_client = new VamsasApplication(this);
2075       setupVamsasConnectedGui();
2076       v_client.initial_update(); // TODO: thread ?
2077     }
2078     else
2079     {
2080       // store current data in session.
2081       v_client.push_update(); // TODO: thread
2082     }
2083   }
2084
2085   protected void setupVamsasConnectedGui()
2086   {
2087     vamsasStart.setText(MessageManager.getString("label.session_update"));
2088     vamsasSave.setVisible(true);
2089     vamsasStop.setVisible(true);
2090     vamsasImport.setVisible(false); // Document import to existing session is
2091     // not possible for vamsas-client-1.0.
2092   }
2093
2094   protected void setupVamsasDisconnectedGui()
2095   {
2096     vamsasSave.setVisible(false);
2097     vamsasStop.setVisible(false);
2098     vamsasImport.setVisible(true);
2099     vamsasStart.setText(MessageManager
2100             .getString("label.new_vamsas_session"));
2101   }
2102
2103   @Override
2104   public void vamsasStop_actionPerformed(ActionEvent e)
2105   {
2106     if (v_client != null)
2107     {
2108       v_client.end_session();
2109       v_client = null;
2110       setupVamsasDisconnectedGui();
2111     }
2112   }
2113
2114   protected void buildVamsasStMenu()
2115   {
2116     if (v_client == null)
2117     {
2118       String[] sess = null;
2119       try
2120       {
2121         sess = VamsasApplication.getSessionList();
2122       } catch (Exception e)
2123       {
2124         jalview.bin.Cache.log.warn(
2125                 "Problem getting current sessions list.", e);
2126         sess = null;
2127       }
2128       if (sess != null)
2129       {
2130         jalview.bin.Cache.log.debug("Got current sessions list: "
2131                 + sess.length + " entries.");
2132         VamsasStMenu.removeAll();
2133         for (int i = 0; i < sess.length; i++)
2134         {
2135           JMenuItem sessit = new JMenuItem();
2136           sessit.setText(sess[i]);
2137           sessit.setToolTipText(MessageManager.formatMessage(
2138                   "label.connect_to_session", new Object[] { sess[i] }));
2139           final Desktop dsktp = this;
2140           final String mysesid = sess[i];
2141           sessit.addActionListener(new ActionListener()
2142           {
2143
2144             @Override
2145             public void actionPerformed(ActionEvent e)
2146             {
2147               if (dsktp.v_client == null)
2148               {
2149                 Thread rthr = new Thread(new Runnable()
2150                 {
2151
2152                   @Override
2153                   public void run()
2154                   {
2155                     dsktp.v_client = new VamsasApplication(dsktp, mysesid);
2156                     dsktp.setupVamsasConnectedGui();
2157                     dsktp.v_client.initial_update();
2158                   }
2159
2160                 });
2161                 rthr.start();
2162               }
2163             };
2164           });
2165           VamsasStMenu.add(sessit);
2166         }
2167         // don't show an empty menu.
2168         VamsasStMenu.setVisible(sess.length > 0);
2169
2170       }
2171       else
2172       {
2173         jalview.bin.Cache.log.debug("No current vamsas sessions.");
2174         VamsasStMenu.removeAll();
2175         VamsasStMenu.setVisible(false);
2176       }
2177     }
2178     else
2179     {
2180       // Not interested in the content. Just hide ourselves.
2181       VamsasStMenu.setVisible(false);
2182     }
2183   }
2184
2185   @Override
2186   public void vamsasSave_actionPerformed(ActionEvent e)
2187   {
2188     if (v_client != null)
2189     {
2190       JalviewFileChooser chooser = new JalviewFileChooser(
2191               jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
2192               { "vdj" }, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
2193               new String[] { "Vamsas Document" }, "Vamsas Document");
2194
2195       chooser.setFileView(new JalviewFileView());
2196       chooser.setDialogTitle(MessageManager
2197               .getString("label.save_vamsas_document_archive"));
2198
2199       int value = chooser.showSaveDialog(this);
2200
2201       if (value == JalviewFileChooser.APPROVE_OPTION)
2202       {
2203         java.io.File choice = chooser.getSelectedFile();
2204         JPanel progpanel = addProgressPanel(MessageManager.formatMessage(
2205                 "label.saving_vamsas_doc",
2206                 new Object[] { choice.getName() }));
2207         jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
2208         String warnmsg = null;
2209         String warnttl = null;
2210         try
2211         {
2212           v_client.vclient.storeDocument(choice);
2213         } catch (Error ex)
2214         {
2215           warnttl = "Serious Problem saving Vamsas Document";
2216           warnmsg = ex.toString();
2217           jalview.bin.Cache.log.error("Error Whilst saving document to "
2218                   + choice, ex);
2219
2220         } catch (Exception ex)
2221         {
2222           warnttl = "Problem saving Vamsas Document.";
2223           warnmsg = ex.toString();
2224           jalview.bin.Cache.log.warn("Exception Whilst saving document to "
2225                   + choice, ex);
2226
2227         }
2228         removeProgressPanel(progpanel);
2229         if (warnmsg != null)
2230         {
2231           JOptionPane.showInternalMessageDialog(Desktop.desktop,
2232
2233           warnmsg, warnttl, JOptionPane.ERROR_MESSAGE);
2234         }
2235       }
2236     }
2237   }
2238
2239   JPanel vamUpdate = null;
2240
2241   /**
2242    * hide vamsas user gui bits when a vamsas document event is being handled.
2243    * 
2244    * @param b
2245    *          true to hide gui, false to reveal gui
2246    */
2247   public void setVamsasUpdate(boolean b)
2248   {
2249     jalview.bin.Cache.log.debug("Setting gui for Vamsas update "
2250             + (b ? "in progress" : "finished"));
2251
2252     if (vamUpdate != null)
2253     {
2254       this.removeProgressPanel(vamUpdate);
2255     }
2256     if (b)
2257     {
2258       vamUpdate = this.addProgressPanel(MessageManager
2259               .getString("label.updating_vamsas_session"));
2260     }
2261     vamsasStart.setVisible(!b);
2262     vamsasStop.setVisible(!b);
2263     vamsasSave.setVisible(!b);
2264   }
2265
2266   public JInternalFrame[] getAllFrames()
2267   {
2268     return desktop.getAllFrames();
2269   }
2270
2271   /**
2272    * Checks the given url to see if it gives a response indicating that the user
2273    * should be informed of a new questionnaire.
2274    * 
2275    * @param url
2276    */
2277   public void checkForQuestionnaire(String url)
2278   {
2279     UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
2280     // javax.swing.SwingUtilities.invokeLater(jvq);
2281     new Thread(jvq).start();
2282   }
2283
2284   /**
2285    * Proxy class for JDesktopPane which optionally displays the current memory
2286    * usage and highlights the desktop area with a red bar if free memory runs
2287    * low.
2288    * 
2289    * @author AMW
2290    */
2291   public class MyDesktopPane extends JDesktopPane implements Runnable
2292   {
2293
2294     private static final float ONE_MB = 1048576f;
2295
2296     boolean showMemoryUsage = false;
2297
2298     Runtime runtime;
2299
2300     java.text.NumberFormat df;
2301
2302     float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
2303             percentUsage;
2304
2305     public MyDesktopPane(boolean showMemoryUsage)
2306     {
2307       showMemoryUsage(showMemoryUsage);
2308     }
2309
2310     public void showMemoryUsage(boolean showMemory)
2311     {
2312       this.showMemoryUsage = showMemory;
2313       if (showMemory)
2314       {
2315         Thread worker = new Thread(this);
2316         worker.start();
2317       }
2318     }
2319
2320     public boolean isShowMemoryUsage()
2321     {
2322       return showMemoryUsage;
2323     }
2324
2325     @Override
2326     public void run()
2327     {
2328       df = java.text.NumberFormat.getNumberInstance();
2329       df.setMaximumFractionDigits(2);
2330       runtime = Runtime.getRuntime();
2331
2332       while (showMemoryUsage)
2333       {
2334         try
2335         {
2336           maxMemory = runtime.maxMemory() / ONE_MB;
2337           allocatedMemory = runtime.totalMemory() / ONE_MB;
2338           freeMemory = runtime.freeMemory() / ONE_MB;
2339           totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
2340
2341           percentUsage = (totalFreeMemory / maxMemory) * 100;
2342
2343           // if (percentUsage < 20)
2344           {
2345             // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
2346             // Color.red);
2347             // instance.set.setBorder(border1);
2348           }
2349           repaint();
2350           // sleep after showing usage
2351           Thread.sleep(3000);
2352         } catch (Exception ex)
2353         {
2354           ex.printStackTrace();
2355         }
2356       }
2357     }
2358
2359     @Override
2360     public void paintComponent(Graphics g)
2361     {
2362       if (showMemoryUsage && g != null && df != null)
2363       {
2364         if (percentUsage < 20)
2365         {
2366           g.setColor(Color.red);
2367         }
2368         FontMetrics fm = g.getFontMetrics();
2369         if (fm != null)
2370         {
2371           g.drawString(MessageManager.formatMessage(
2372                   "label.memory_stats",
2373                   new Object[] { df.format(totalFreeMemory),
2374                       df.format(maxMemory), df.format(percentUsage) }), 10,
2375                   getHeight() - fm.getHeight());
2376         }
2377       }
2378     }
2379   }
2380
2381   /**
2382    * fixes stacking order after a modal dialog to ensure windows that should be
2383    * on top actually are
2384    */
2385   public void relayerWindows()
2386   {
2387
2388   }
2389
2390   protected JMenuItem groovyShell;
2391
2392   public void doGroovyCheck()
2393   {
2394     if (jalview.bin.Cache.groovyJarsPresent())
2395     {
2396       groovyShell = new JMenuItem();
2397       groovyShell.setText(MessageManager.getString("label.groovy_console"));
2398       groovyShell.addActionListener(new ActionListener()
2399       {
2400         @Override
2401         public void actionPerformed(ActionEvent e)
2402         {
2403           groovyShell_actionPerformed();
2404         }
2405       });
2406       toolsMenu.add(groovyShell);
2407       groovyShell.setVisible(true);
2408     }
2409   }
2410
2411   /**
2412    * Accessor method to quickly get all the AlignmentFrames loaded.
2413    * 
2414    * @return an array of AlignFrame, or null if none found
2415    */
2416   public static AlignFrame[] getAlignFrames()
2417   {
2418     if (Jalview.isHeadlessMode())
2419     {
2420       // Desktop.desktop is null in headless mode
2421       return new AlignFrame[] { currentAlignFrame };
2422     }
2423
2424     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2425
2426     if (frames == null)
2427     {
2428       return null;
2429     }
2430     List<AlignFrame> avp = new ArrayList<AlignFrame>();
2431     // REVERSE ORDER
2432     for (int i = frames.length - 1; i > -1; i--)
2433     {
2434       if (frames[i] instanceof AlignFrame)
2435       {
2436         avp.add((AlignFrame) frames[i]);
2437       }
2438       else if (frames[i] instanceof SplitFrame)
2439       {
2440         /*
2441          * Also check for a split frame containing an AlignFrame
2442          */
2443         GSplitFrame sf = (GSplitFrame) frames[i];
2444         if (sf.getTopFrame() instanceof AlignFrame)
2445         {
2446           avp.add((AlignFrame) sf.getTopFrame());
2447         }
2448         if (sf.getBottomFrame() instanceof AlignFrame)
2449         {
2450           avp.add((AlignFrame) sf.getBottomFrame());
2451         }
2452       }
2453     }
2454     if (avp.size() == 0)
2455     {
2456       return null;
2457     }
2458     AlignFrame afs[] = avp.toArray(new AlignFrame[avp.size()]);
2459     return afs;
2460   }
2461
2462   /**
2463    * Returns an array of any AppJmol frames in the Desktop (or null if none).
2464    * 
2465    * @return
2466    */
2467   public GStructureViewer[] getJmols()
2468   {
2469     JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2470
2471     if (frames == null)
2472     {
2473       return null;
2474     }
2475     List<GStructureViewer> avp = new ArrayList<GStructureViewer>();
2476     // REVERSE ORDER
2477     for (int i = frames.length - 1; i > -1; i--)
2478     {
2479       if (frames[i] instanceof AppJmol)
2480       {
2481         GStructureViewer af = (GStructureViewer) frames[i];
2482         avp.add(af);
2483       }
2484     }
2485     if (avp.size() == 0)
2486     {
2487       return null;
2488     }
2489     GStructureViewer afs[] = avp.toArray(new GStructureViewer[avp.size()]);
2490     return afs;
2491   }
2492
2493   /**
2494    * Add Groovy Support to Jalview
2495    */
2496   public void groovyShell_actionPerformed()
2497   {
2498     if (!jalview.bin.Cache.groovyJarsPresent())
2499     {
2500       throw new Error(
2501               MessageManager
2502                       .getString("error.implementation_error_cannot_create_groovyshell"));
2503     }
2504     try
2505     {
2506       openGroovyConsole();
2507     } catch (Exception ex)
2508     {
2509       jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
2510       JOptionPane.showInternalMessageDialog(Desktop.desktop,
2511
2512       MessageManager.getString("label.couldnt_create_groovy_shell"),
2513               MessageManager.getString("label.groovy_support_failed"),
2514               JOptionPane.ERROR_MESSAGE);
2515     }
2516   }
2517
2518   /**
2519    * Open the Groovy console, using reflection to avoid creating compile-time
2520    * dependency on Groovy libraries
2521    * 
2522    * @throws ClassNotFoundException
2523    * @throws NoSuchMethodException
2524    * @throws InstantiationException
2525    * @throws IllegalAccessException
2526    * @throws InvocationTargetException
2527    */
2528   void openGroovyConsole() throws ClassNotFoundException,
2529           NoSuchMethodException, InstantiationException,
2530           IllegalAccessException, InvocationTargetException
2531   {
2532     Class<?> gcClass = Desktop.class.getClassLoader().loadClass(
2533             "groovy.ui.Console");
2534     Constructor<?> gccons = gcClass.getConstructor();
2535     groovyConsole = gccons.newInstance();
2536
2537     /*
2538      * bind groovy variable 'Jalview' to the Desktop object
2539      */
2540     Method setvar = gcClass.getMethod("setVariable", new Class[] {
2541         String.class, Object.class });
2542     setvar.invoke(groovyConsole, new Object[] { "Jalview", this });
2543
2544     /*
2545      * start the console
2546      */
2547     Method run = gcClass.getMethod("run");
2548     run.invoke(groovyConsole);
2549
2550     /*
2551      * Allow only one console at a time, so that the AlignFrame menu option
2552      * 'Calculate | Run Groovy script' is unambiguous.
2553      * Disable 'new console', and enable 'Run script', when the console is 
2554      * opened, and the reverse when it is closed
2555      */
2556     Method getFrame = gcClass.getMethod("getFrame");
2557     Window window = (Window) getFrame.invoke(groovyConsole);
2558     window.addWindowListener(new WindowAdapter()
2559     {
2560       @Override
2561       public void windowClosed(WindowEvent e)
2562       {
2563         groovyShell.setEnabled(true);
2564         enableExecuteGroovy(false);
2565       }
2566     });
2567
2568     /*
2569      * if we got this far, enable 'Run Groovy' in AlignFrame menus
2570      * and disable opening a second console
2571      */
2572     groovyShell.setEnabled(false);
2573     enableExecuteGroovy(true);
2574   }
2575
2576   /**
2577    * Enable or disable 'Run Groovy script' in AlignFrame calculate menus
2578    * 
2579    * @param enabled
2580    */
2581   public void enableExecuteGroovy(boolean enabled)
2582   {
2583     AlignFrame[] alignFrames = getAlignFrames();
2584     if (alignFrames != null)
2585     {
2586       for (AlignFrame af : alignFrames)
2587       {
2588         af.setGroovyEnabled(enabled);
2589       }
2590     }
2591   }
2592
2593   /**
2594    * Progress bars managed by the IProgressIndicator method.
2595    */
2596   private Hashtable<Long, JPanel> progressBars;
2597
2598   private Hashtable<Long, IProgressIndicatorHandler> progressBarHandlers;
2599
2600   /*
2601    * (non-Javadoc)
2602    * 
2603    * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2604    */
2605   @Override
2606   public void setProgressBar(String message, long id)
2607   {
2608     if (progressBars == null)
2609     {
2610       progressBars = new Hashtable<Long, JPanel>();
2611       progressBarHandlers = new Hashtable<Long, IProgressIndicatorHandler>();
2612     }
2613
2614     if (progressBars.get(new Long(id)) != null)
2615     {
2616       JPanel panel = progressBars.remove(new Long(id));
2617       if (progressBarHandlers.contains(new Long(id)))
2618       {
2619         progressBarHandlers.remove(new Long(id));
2620       }
2621       removeProgressPanel(panel);
2622     }
2623     else
2624     {
2625       progressBars.put(new Long(id), addProgressPanel(message));
2626     }
2627   }
2628
2629   /*
2630    * (non-Javadoc)
2631    * 
2632    * @see jalview.gui.IProgressIndicator#registerHandler(long,
2633    * jalview.gui.IProgressIndicatorHandler)
2634    */
2635   @Override
2636   public void registerHandler(final long id,
2637           final IProgressIndicatorHandler handler)
2638   {
2639     if (progressBarHandlers == null
2640             || !progressBars.containsKey(new Long(id)))
2641     {
2642       throw new Error(
2643               MessageManager
2644                       .getString("error.call_setprogressbar_before_registering_handler"));
2645     }
2646     progressBarHandlers.put(new Long(id), handler);
2647     final JPanel progressPanel = progressBars.get(new Long(id));
2648     if (handler.canCancel())
2649     {
2650       JButton cancel = new JButton(
2651               MessageManager.getString("action.cancel"));
2652       final IProgressIndicator us = this;
2653       cancel.addActionListener(new ActionListener()
2654       {
2655
2656         @Override
2657         public void actionPerformed(ActionEvent e)
2658         {
2659           handler.cancelActivity(id);
2660           us.setProgressBar(MessageManager.formatMessage(
2661                   "label.cancelled_params",
2662                   new Object[] { ((JLabel) progressPanel.getComponent(0))
2663                           .getText() }), id);
2664         }
2665       });
2666       progressPanel.add(cancel, BorderLayout.EAST);
2667     }
2668   }
2669
2670   /**
2671    * 
2672    * @return true if any progress bars are still active
2673    */
2674   @Override
2675   public boolean operationInProgress()
2676   {
2677     if (progressBars != null && progressBars.size() > 0)
2678     {
2679       return true;
2680     }
2681     return false;
2682   }
2683
2684   /**
2685    * This will return the first AlignFrame holding the given viewport instance.
2686    * It will break if there are more than one AlignFrames viewing a particular
2687    * av.
2688    * 
2689    * @param viewport
2690    * @return alignFrame for viewport
2691    */
2692   public static AlignFrame getAlignFrameFor(AlignViewportI viewport)
2693   {
2694     if (desktop != null)
2695     {
2696       AlignmentPanel[] aps = getAlignmentPanels(viewport.getSequenceSetId());
2697       for (int panel = 0; aps != null && panel < aps.length; panel++)
2698       {
2699         if (aps[panel] != null && aps[panel].av == viewport)
2700         {
2701           return aps[panel].alignFrame;
2702         }
2703       }
2704     }
2705     return null;
2706   }
2707
2708   public VamsasApplication getVamsasApplication()
2709   {
2710     return v_client;
2711
2712   }
2713
2714   /**
2715    * flag set if jalview GUI is being operated programmatically
2716    */
2717   private boolean inBatchMode = false;
2718
2719   /**
2720    * check if jalview GUI is being operated programmatically
2721    * 
2722    * @return inBatchMode
2723    */
2724   public boolean isInBatchMode()
2725   {
2726     return inBatchMode;
2727   }
2728
2729   /**
2730    * set flag if jalview GUI is being operated programmatically
2731    * 
2732    * @param inBatchMode
2733    */
2734   public void setInBatchMode(boolean inBatchMode)
2735   {
2736     this.inBatchMode = inBatchMode;
2737   }
2738
2739   public void startServiceDiscovery()
2740   {
2741     startServiceDiscovery(false);
2742   }
2743
2744   public void startServiceDiscovery(boolean blocking)
2745   {
2746     boolean alive = true;
2747     Thread t0 = null, t1 = null, t2 = null;
2748     // JAL-940 - JALVIEW 1 services are now being EOLed as of JABA 2.1 release
2749     if (true)
2750     {
2751       // todo: changesupport handlers need to be transferred
2752       if (discoverer == null)
2753       {
2754         discoverer = new jalview.ws.jws1.Discoverer();
2755         // register PCS handler for desktop.
2756         discoverer.addPropertyChangeListener(changeSupport);
2757       }
2758       // JAL-940 - disabled JWS1 service configuration - always start discoverer
2759       // until we phase out completely
2760       (t0 = new Thread(discoverer)).start();
2761     }
2762
2763     if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
2764     {
2765       if (jalview.ws.jws2.Jws2Discoverer.getDiscoverer().isRunning())
2766       {
2767         jalview.ws.jws2.Jws2Discoverer.getDiscoverer().setAborted(true);
2768       }
2769       t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer().startDiscoverer(
2770               changeSupport);
2771
2772     }
2773     Thread t3 = null;
2774     {
2775       // TODO: do rest service discovery
2776     }
2777     if (blocking)
2778     {
2779       while (alive)
2780       {
2781         try
2782         {
2783           Thread.sleep(15);
2784         } catch (Exception e)
2785         {
2786         }
2787         alive = (t1 != null && t1.isAlive())
2788                 || (t2 != null && t2.isAlive())
2789                 || (t3 != null && t3.isAlive())
2790                 || (t0 != null && t0.isAlive());
2791       }
2792     }
2793   }
2794
2795   /**
2796    * called to check if the service discovery process completed successfully.
2797    * 
2798    * @param evt
2799    */
2800   protected void JalviewServicesChanged(PropertyChangeEvent evt)
2801   {
2802     if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
2803     {
2804       final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2805               .getErrorMessages();
2806       if (ermsg != null)
2807       {
2808         if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
2809         {
2810           if (serviceChangedDialog == null)
2811           {
2812             // only run if we aren't already displaying one of these.
2813             addDialogThread(serviceChangedDialog = new Runnable()
2814             {
2815               @Override
2816               public void run()
2817               {
2818
2819                 /*
2820                  * JalviewDialog jd =new JalviewDialog() {
2821                  * 
2822                  * @Override protected void cancelPressed() { // TODO
2823                  * Auto-generated method stub
2824                  * 
2825                  * }@Override protected void okPressed() { // TODO
2826                  * Auto-generated method stub
2827                  * 
2828                  * }@Override protected void raiseClosed() { // TODO
2829                  * Auto-generated method stub
2830                  * 
2831                  * } }; jd.initDialogFrame(new
2832                  * JLabel("<html><table width=\"450\"><tr><td>" + ermsg +
2833                  * "<br/>It may be that you have invalid JABA URLs in your web service preferences,"
2834                  * + " or mis-configured HTTP proxy settings.<br/>" +
2835                  * "Check the <em>Connections</em> and <em>Web services</em> tab of the"
2836                  * +
2837                  * " Tools->Preferences dialog box to change them.</td></tr></table></html>"
2838                  * ), true, true, "Web Service Configuration Problem", 450,
2839                  * 400);
2840                  * 
2841                  * jd.waitForInput();
2842                  */
2843                 JOptionPane
2844                         .showConfirmDialog(
2845                                 Desktop.desktop,
2846                                 new JLabel(
2847                                         "<html><table width=\"450\"><tr><td>"
2848                                                 + ermsg
2849                                                 + "</td></tr></table>"
2850                                                 + "<p>It may be that you have invalid JABA URLs<br/>in your web service preferences,"
2851                                                 + "<br>or as a command-line argument, or mis-configured HTTP proxy settings.</p>"
2852                                                 + "<p>Check the <em>Connections</em> and <em>Web services</em> tab<br/>of the"
2853                                                 + " Tools->Preferences dialog box to change them.</p></html>"),
2854                                 "Web Service Configuration Problem",
2855                                 JOptionPane.DEFAULT_OPTION,
2856                                 JOptionPane.ERROR_MESSAGE);
2857                 serviceChangedDialog = null;
2858
2859               }
2860             });
2861           }
2862         }
2863         else
2864         {
2865           Cache.log
2866                   .error("Errors reported by JABA discovery service. Check web services preferences.\n"
2867                           + ermsg);
2868         }
2869       }
2870     }
2871   }
2872
2873   private Runnable serviceChangedDialog = null;
2874
2875   /**
2876    * start a thread to open a URL in the configured browser. Pops up a warning
2877    * dialog to the user if there is an exception when calling out to the browser
2878    * to open the URL.
2879    * 
2880    * @param url
2881    */
2882   public static void showUrl(final String url)
2883   {
2884     showUrl(url, Desktop.instance);
2885   }
2886
2887   /**
2888    * Like showUrl but allows progress handler to be specified
2889    * 
2890    * @param url
2891    * @param progress
2892    *          (null) or object implementing IProgressIndicator
2893    */
2894   public static void showUrl(final String url,
2895           final IProgressIndicator progress)
2896   {
2897     new Thread(new Runnable()
2898     {
2899       @Override
2900       public void run()
2901       {
2902         try
2903         {
2904           if (progress != null)
2905           {
2906             progress.setProgressBar(MessageManager.formatMessage(
2907                     "status.opening_params", new Object[] { url }), this
2908                     .hashCode());
2909           }
2910           jalview.util.BrowserLauncher.openURL(url);
2911         } catch (Exception ex)
2912         {
2913           JOptionPane.showInternalMessageDialog(Desktop.desktop,
2914                   MessageManager
2915                           .getString("label.web_browser_not_found_unix"),
2916                   MessageManager.getString("label.web_browser_not_found"),
2917                   JOptionPane.WARNING_MESSAGE);
2918
2919           ex.printStackTrace();
2920         }
2921         if (progress != null)
2922         {
2923           progress.setProgressBar(null, this.hashCode());
2924         }
2925       }
2926     }).start();
2927   }
2928
2929   public static WsParamSetManager wsparamManager = null;
2930
2931   public static ParamManager getUserParameterStore()
2932   {
2933     if (wsparamManager == null)
2934     {
2935       wsparamManager = new WsParamSetManager();
2936     }
2937     return wsparamManager;
2938   }
2939
2940   /**
2941    * static hyperlink handler proxy method for use by Jalview's internal windows
2942    * 
2943    * @param e
2944    */
2945   public static void hyperlinkUpdate(HyperlinkEvent e)
2946   {
2947     if (e.getEventType() == EventType.ACTIVATED)
2948     {
2949       String url = null;
2950       try
2951       {
2952         url = e.getURL().toString();
2953         Desktop.showUrl(url);
2954       } catch (Exception x)
2955       {
2956         if (url != null)
2957         {
2958           if (Cache.log != null)
2959           {
2960             Cache.log.error("Couldn't handle string " + url + " as a URL.");
2961           }
2962           else
2963           {
2964             System.err.println("Couldn't handle string " + url
2965                     + " as a URL.");
2966           }
2967         }
2968         // ignore any exceptions due to dud links.
2969       }
2970
2971     }
2972   }
2973
2974   /**
2975    * single thread that handles display of dialogs to user.
2976    */
2977   ExecutorService dialogExecutor = Executors.newSingleThreadExecutor();
2978
2979   /**
2980    * flag indicating if dialogExecutor should try to acquire a permit
2981    */
2982   private volatile boolean dialogPause = true;
2983
2984   /**
2985    * pause the queue
2986    */
2987   private java.util.concurrent.Semaphore block = new Semaphore(0);
2988
2989   /*
2990    * groovy.ui.Console object - if Groovy jars are present and the 
2991    * user has activated the Groovy console. Use via reflection to
2992    * avoid compile-time dependency on Groovy libraries.
2993    */
2994   private static Object groovyConsole;
2995
2996   /**
2997    * add another dialog thread to the queue
2998    * 
2999    * @param prompter
3000    */
3001   public void addDialogThread(final Runnable prompter)
3002   {
3003     dialogExecutor.submit(new Runnable()
3004     {
3005       @Override
3006       public void run()
3007       {
3008         if (dialogPause)
3009         {
3010           try
3011           {
3012             block.acquire();
3013           } catch (InterruptedException x)
3014           {
3015           }
3016           ;
3017         }
3018         if (instance == null)
3019         {
3020           return;
3021         }
3022         try
3023         {
3024           SwingUtilities.invokeAndWait(prompter);
3025         } catch (Exception q)
3026         {
3027           Cache.log.warn("Unexpected Exception in dialog thread.", q);
3028         }
3029       }
3030     });
3031   }
3032
3033   public void startDialogQueue()
3034   {
3035     // set the flag so we don't pause waiting for another permit and semaphore
3036     // the current task to begin
3037     dialogPause = false;
3038     block.release();
3039   }
3040
3041   @Override
3042   protected void snapShotWindow_actionPerformed(ActionEvent e)
3043   {
3044     invalidate();
3045     File of;
3046     ImageMaker im = new jalview.util.ImageMaker(this, ImageMaker.TYPE.EPS,
3047             "View of Desktop", getWidth(), getHeight(), of = new File(
3048                     "Jalview_snapshot" + System.currentTimeMillis()
3049                             + ".eps"), "View of desktop", null, 0, false);
3050     try
3051     {
3052       paintAll(im.getGraphics());
3053       im.writeImage();
3054     } catch (Exception q)
3055     {
3056       Cache.log.error("Couldn't write snapshot to " + of.getAbsolutePath(),
3057               q);
3058       return;
3059     }
3060     Cache.log.info("Successfully written snapshot to file "
3061             + of.getAbsolutePath());
3062   }
3063
3064   /**
3065    * Explode the views in the given SplitFrame into separate SplitFrame windows.
3066    * This respects (remembers) any previous 'exploded geometry' i.e. the size
3067    * and location last time the view was expanded (if any). However it does not
3068    * remember the split pane divider location - this is set to match the
3069    * 'exploding' frame.
3070    * 
3071    * @param sf
3072    */
3073   public void explodeViews(SplitFrame sf)
3074   {
3075     AlignFrame oldTopFrame = (AlignFrame) sf.getTopFrame();
3076     AlignFrame oldBottomFrame = (AlignFrame) sf.getBottomFrame();
3077     List<? extends AlignmentViewPanel> topPanels = oldTopFrame
3078             .getAlignPanels();
3079     List<? extends AlignmentViewPanel> bottomPanels = oldBottomFrame
3080             .getAlignPanels();
3081     int viewCount = topPanels.size();
3082     if (viewCount < 2)
3083     {
3084       return;
3085     }
3086
3087     /*
3088      * Processing in reverse order works, forwards order leaves the first panels
3089      * not visible. I don't know why!
3090      */
3091     for (int i = viewCount - 1; i >= 0; i--)
3092     {
3093       /*
3094        * Make new top and bottom frames. These take over the respective
3095        * AlignmentPanel objects, including their AlignmentViewports, so the
3096        * cdna/protein relationships between the viewports is carried over to the
3097        * new split frames.
3098        * 
3099        * explodedGeometry holds the (x, y) position of the previously exploded
3100        * SplitFrame, and the (width, height) of the AlignFrame component
3101        */
3102       AlignmentPanel topPanel = (AlignmentPanel) topPanels.get(i);
3103       AlignFrame newTopFrame = new AlignFrame(topPanel);
3104       newTopFrame.setSize(oldTopFrame.getSize());
3105       newTopFrame.setVisible(true);
3106       Rectangle geometry = ((AlignViewport) topPanel.getAlignViewport())
3107               .getExplodedGeometry();
3108       if (geometry != null)
3109       {
3110         newTopFrame.setSize(geometry.getSize());
3111       }
3112
3113       AlignmentPanel bottomPanel = (AlignmentPanel) bottomPanels.get(i);
3114       AlignFrame newBottomFrame = new AlignFrame(bottomPanel);
3115       newBottomFrame.setSize(oldBottomFrame.getSize());
3116       newBottomFrame.setVisible(true);
3117       geometry = ((AlignViewport) bottomPanel.getAlignViewport())
3118               .getExplodedGeometry();
3119       if (geometry != null)
3120       {
3121         newBottomFrame.setSize(geometry.getSize());
3122       }
3123
3124       topPanel.av.setGatherViewsHere(false);
3125       bottomPanel.av.setGatherViewsHere(false);
3126       JInternalFrame splitFrame = new SplitFrame(newTopFrame,
3127               newBottomFrame);
3128       if (geometry != null)
3129       {
3130         splitFrame.setLocation(geometry.getLocation());
3131       }
3132       Desktop.addInternalFrame(splitFrame, sf.getTitle(), -1, -1);
3133     }
3134
3135     /*
3136      * Clear references to the panels (now relocated in the new SplitFrames)
3137      * before closing the old SplitFrame.
3138      */
3139     topPanels.clear();
3140     bottomPanels.clear();
3141     sf.close();
3142   }
3143
3144   /**
3145    * Gather expanded split frames, sharing the same pairs of sequence set ids,
3146    * back into the given SplitFrame as additional views. Note that the gathered
3147    * frames may themselves have multiple views.
3148    * 
3149    * @param source
3150    */
3151   public void gatherViews(GSplitFrame source)
3152   {
3153     /*
3154      * special handling of explodedGeometry for a view within a SplitFrame: - it
3155      * holds the (x, y) position of the enclosing SplitFrame, and the (width,
3156      * height) of the AlignFrame component
3157      */
3158     AlignFrame myTopFrame = (AlignFrame) source.getTopFrame();
3159     AlignFrame myBottomFrame = (AlignFrame) source.getBottomFrame();
3160     myTopFrame.viewport.setExplodedGeometry(new Rectangle(source.getX(),
3161             source.getY(), myTopFrame.getWidth(), myTopFrame.getHeight()));
3162     myBottomFrame.viewport.setExplodedGeometry(new Rectangle(source.getX(),
3163             source.getY(), myBottomFrame.getWidth(), myBottomFrame
3164                     .getHeight()));
3165     myTopFrame.viewport.setGatherViewsHere(true);
3166     myBottomFrame.viewport.setGatherViewsHere(true);
3167     String topViewId = myTopFrame.viewport.getSequenceSetId();
3168     String bottomViewId = myBottomFrame.viewport.getSequenceSetId();
3169
3170     JInternalFrame[] frames = desktop.getAllFrames();
3171     for (JInternalFrame frame : frames)
3172     {
3173       if (frame instanceof SplitFrame && frame != source)
3174       {
3175         SplitFrame sf = (SplitFrame) frame;
3176         AlignFrame topFrame = (AlignFrame) sf.getTopFrame();
3177         AlignFrame bottomFrame = (AlignFrame) sf.getBottomFrame();
3178         boolean gatherThis = false;
3179         for (int a = 0; a < topFrame.alignPanels.size(); a++)
3180         {
3181           AlignmentPanel topPanel = topFrame.alignPanels.get(a);
3182           AlignmentPanel bottomPanel = bottomFrame.alignPanels.get(a);
3183           if (topViewId.equals(topPanel.av.getSequenceSetId())
3184                   && bottomViewId.equals(bottomPanel.av.getSequenceSetId()))
3185           {
3186             gatherThis = true;
3187             topPanel.av.setGatherViewsHere(false);
3188             bottomPanel.av.setGatherViewsHere(false);
3189             topPanel.av.setExplodedGeometry(new Rectangle(sf.getLocation(),
3190                     topFrame.getSize()));
3191             bottomPanel.av.setExplodedGeometry(new Rectangle(sf
3192                     .getLocation(), bottomFrame.getSize()));
3193             myTopFrame.addAlignmentPanel(topPanel, false);
3194             myBottomFrame.addAlignmentPanel(bottomPanel, false);
3195           }
3196         }
3197
3198         if (gatherThis)
3199         {
3200           topFrame.getAlignPanels().clear();
3201           bottomFrame.getAlignPanels().clear();
3202           sf.close();
3203         }
3204       }
3205     }
3206
3207     /*
3208      * The dust settles...give focus to the tab we did this from.
3209      */
3210     myTopFrame.setDisplayedView(myTopFrame.alignPanel);
3211
3212   }
3213
3214   public static AlignFrame getCurrentAlignFrame()
3215   {
3216     return currentAlignFrame;
3217   }
3218
3219   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
3220   {
3221     Desktop.currentAlignFrame = currentAlignFrame;
3222   }
3223
3224   public static Object getGroovyConsole()
3225   {
3226     return groovyConsole;
3227   }
3228
3229 }