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