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