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