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