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