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