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