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