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