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