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