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