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