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