JAL-3811 document SHOW_JWS2_SERVICES user preference and provide new menu option...
[jalview.git] / src / jalview / gui / Desktop.java
index 5ee9150..f06adc4 100644 (file)
  */
 package jalview.gui;
 
-import static jalview.util.UrlConstants.SEQUENCE_ID;
-
 import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
 import jalview.bin.Cache;
 import jalview.bin.Jalview;
+import jalview.io.BackupFiles;
 import jalview.io.DataSourceType;
 import jalview.io.FileFormat;
 import jalview.io.FileFormatException;
 import jalview.io.FileFormatI;
 import jalview.io.FileFormats;
 import jalview.io.FileLoader;
+import jalview.io.FormatAdapter;
 import jalview.io.IdentifyFile;
 import jalview.io.JalviewFileChooser;
 import jalview.io.JalviewFileView;
 import jalview.jbgui.GSplitFrame;
 import jalview.jbgui.GStructureViewer;
+import jalview.project.Jalview2XML;
 import jalview.structure.StructureSelectionManager;
 import jalview.urls.IdOrgSettings;
 import jalview.util.ImageMaker;
@@ -68,6 +69,7 @@ import java.awt.dnd.DropTargetEvent;
 import java.awt.dnd.DropTargetListener;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
+import java.awt.event.InputEvent;
 import java.awt.event.KeyEvent;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
@@ -75,12 +77,12 @@ import java.awt.event.WindowAdapter;
 import java.awt.event.WindowEvent;
 import java.beans.PropertyChangeEvent;
 import java.beans.PropertyChangeListener;
-import java.io.BufferedInputStream;
 import java.io.File;
-import java.io.FileOutputStream;
+import java.io.FileWriter;
 import java.io.IOException;
 import java.net.URL;
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.Hashtable;
 import java.util.List;
 import java.util.ListIterator;
@@ -91,16 +93,18 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.Semaphore;
 
 import javax.swing.AbstractAction;
+import javax.swing.Action;
+import javax.swing.ActionMap;
 import javax.swing.Box;
 import javax.swing.BoxLayout;
 import javax.swing.DefaultDesktopManager;
 import javax.swing.DesktopManager;
+import javax.swing.InputMap;
 import javax.swing.JButton;
 import javax.swing.JCheckBox;
 import javax.swing.JComboBox;
 import javax.swing.JComponent;
 import javax.swing.JDesktopPane;
-import javax.swing.JFrame;
 import javax.swing.JInternalFrame;
 import javax.swing.JLabel;
 import javax.swing.JMenuItem;
@@ -113,8 +117,8 @@ import javax.swing.event.HyperlinkEvent;
 import javax.swing.event.HyperlinkEvent.EventType;
 import javax.swing.event.InternalFrameAdapter;
 import javax.swing.event.InternalFrameEvent;
-import javax.swing.event.MenuEvent;
-import javax.swing.event.MenuListener;
+
+import org.stackoverflowusers.file.WindowsShortcut;
 
 /**
  * Jalview Desktop
@@ -137,6 +141,10 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   private static final String EXPERIMENTAL_FEATURES = "EXPERIMENTAL_FEATURES";
 
+  protected static final String CONFIRM_KEYBOARD_QUIT = "CONFIRM_KEYBOARD_QUIT";
+
+  public static HashMap<String, FileWriter> savingFiles = new HashMap<String, FileWriter>();
+
   private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
 
   /**
@@ -334,18 +342,53 @@ public class Desktop extends jalview.jbgui.GDesktop
      * constructor.
      */
     instance = this;
-    doVamsasClientCheck();
 
     doConfigureStructurePrefs();
     setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
-    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+    /*
+    if (!Platform.isAMac())
+    {
+      // this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+    }
+    else
+    {
+     this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
+    }
+    */
+
+    try
+    {
+      APQHandlers.setAPQHandlers(this);
+    } catch (Exception e)
+    {
+      System.out.println("Cannot set APQHandlers");
+      // e.printStackTrace();
+    } catch (Throwable t)
+    {
+      System.out.println("Cannot set APQHandlers");
+      // t.printStackTrace();
+    }
+
+
+    addWindowListener(new WindowAdapter()
+    {
+
+      @Override
+      public void windowClosing(WindowEvent ev)
+      {
+        quit();
+      }
+    });
+
     boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",
             false);
+
     boolean showjconsole = jalview.bin.Cache.getDefault("SHOW_JAVA_CONSOLE",
             false);
     desktop = new MyDesktopPane(selmemusage);
     showMemusage.setSelected(selmemusage);
     desktop.setBackground(Color.white);
+
     getContentPane().setLayout(new BorderLayout());
     // alternate config - have scrollbars - see notes in JAL-153
     // JScrollPane sp = new JScrollPane();
@@ -356,13 +399,12 @@ public class Desktop extends jalview.jbgui.GDesktop
 
     // This line prevents Windows Look&Feel resizing all new windows to maximum
     // if previous window was maximised
-    desktop.setDesktopManager(
-            new MyDesktopManager(
-                    (Platform.isWindows() ? new DefaultDesktopManager()
-                            : Platform.isAMac()
-                                    ? new AquaInternalFrameManager(
-                                            desktop.getDesktopManager())
-                                    : desktop.getDesktopManager())));
+    desktop.setDesktopManager(new MyDesktopManager(
+            (Platform.isWindows() ? new DefaultDesktopManager()
+                    : Platform.isAMac()
+                            ? new AquaInternalFrameManager(
+                                    desktop.getDesktopManager())
+                            : desktop.getDesktopManager())));
 
     Rectangle dims = getLastKnownDimensions("");
     if (dims != null)
@@ -377,18 +419,7 @@ public class Desktop extends jalview.jbgui.GDesktop
     }
     jconsole = new Console(this, showjconsole);
     // add essential build information
-    jconsole.setHeader(
-            "Jalview Version: " + jalview.bin.Cache.getProperty("VERSION")
-                    + "\n" + "Jalview Installation: "
-                    + jalview.bin.Cache.getDefault("INSTALLATION",
-                            "unknown")
-                    + "\n" + "Build Date: "
-                    + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown")
-                    + "\n" + "Java version: "
-                    + System.getProperty("java.version") + "\n"
-                    + System.getProperty("os.arch") + " "
-                    + System.getProperty("os.name") + " "
-                    + System.getProperty("os.version"));
+    jconsole.setHeader(jalview.bin.Cache.getVersionDetailsForConsole());
 
     showConsole(showjconsole);
 
@@ -512,7 +543,7 @@ public class Desktop extends jalview.jbgui.GDesktop
   {
     final Desktop me = this;
     // Thread off the news reader, in case there are connection problems.
-    addDialogThread(new Runnable()
+    new Thread(new Runnable()
     {
       @Override
       public void run()
@@ -523,13 +554,13 @@ public class Desktop extends jalview.jbgui.GDesktop
         showNews.setVisible(true);
         Cache.log.debug("Completed news thread.");
       }
-    });
+    }).start();
   }
 
   public void getIdentifiersOrgData()
   {
     // Thread off the identifiers fetcher
-    addDialogThread(new Runnable()
+    new Thread(new Runnable()
     {
       @Override
       public void run()
@@ -546,7 +577,8 @@ public class Desktop extends jalview.jbgui.GDesktop
                   + e.getMessage());
         }
       }
-    });
+    }).start();
+    ;
   }
 
   @Override
@@ -638,46 +670,6 @@ public class Desktop extends jalview.jbgui.GDesktop
     return null;
   }
 
-  private void doVamsasClientCheck()
-  {
-    if (jalview.bin.Cache.vamsasJarsPresent())
-    {
-      setupVamsasDisconnectedGui();
-      VamsasMenu.setVisible(true);
-      final Desktop us = this;
-      VamsasMenu.addMenuListener(new MenuListener()
-      {
-        // this listener remembers when the menu was first selected, and
-        // doesn't rebuild the session list until it has been cleared and
-        // reselected again.
-        boolean refresh = true;
-
-        @Override
-        public void menuCanceled(MenuEvent e)
-        {
-          refresh = true;
-        }
-
-        @Override
-        public void menuDeselected(MenuEvent e)
-        {
-          refresh = true;
-        }
-
-        @Override
-        public void menuSelected(MenuEvent e)
-        {
-          if (refresh)
-          {
-            us.buildVamsasStMenu();
-            refresh = false;
-          }
-        }
-      });
-      vamsasStart.setVisible(true);
-    }
-  }
-
   void showPasteMenu(int x, int y)
   {
     JPopupMenu popup = new JPopupMenu();
@@ -900,8 +892,6 @@ public class Desktop extends jalview.jbgui.GDesktop
           menuItem.removeActionListener(menuItem.getActionListeners()[0]);
         }
         windowMenu.remove(menuItem);
-
-        System.gc();
       };
     });
 
@@ -921,6 +911,8 @@ public class Desktop extends jalview.jbgui.GDesktop
       }
     });
 
+    setKeyBindings(frame);
+
     desktop.add(frame);
 
     windowMenu.add(menuItem);
@@ -935,11 +927,47 @@ public class Desktop extends jalview.jbgui.GDesktop
     } catch (java.lang.ClassCastException cex)
     {
       Cache.log.warn(
-              "Squashed a possible GUI implementation error. If you can recreate this, please look at http://issues.jalview.org/browse/JAL-869",
+              "Squashed a possible GUI implementation error. If you can recreate this, please look at https://issues.jalview.org/browse/JAL-869",
               cex);
     }
   }
 
+  /**
+   * Add key bindings to a JInternalFrame so that Ctrl-W and Cmd-W will close
+   * the window
+   * 
+   * @param frame
+   */
+  private static void setKeyBindings(JInternalFrame frame)
+  {
+    @SuppressWarnings("serial")
+    final Action closeAction = new AbstractAction()
+    {
+      @Override
+      public void actionPerformed(ActionEvent e)
+      {
+        frame.dispose();
+      }
+    };
+
+    /*
+     * set up key bindings for Ctrl-W and Cmd-W, with the same (Close) action
+     */
+    KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
+            InputEvent.CTRL_DOWN_MASK);
+    KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
+            jalview.util.ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx());
+
+    InputMap inputMap = frame
+            .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
+    String ctrlW = ctrlWKey.toString();
+    inputMap.put(ctrlWKey, ctrlW);
+    inputMap.put(cmdWKey, ctrlW);
+
+    ActionMap actionMap = frame.getActionMap();
+    actionMap.put(ctrlW, closeAction);
+  }
+
   @Override
   public void lostOwnership(Clipboard clipboard, Transferable contents)
   {
@@ -1042,7 +1070,7 @@ public class Desktop extends jalview.jbgui.GDesktop
   {
     String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
     JalviewFileChooser chooser = JalviewFileChooser
-            .forRead(Cache.getProperty("LAST_DIRECTORY"), fileFormat);
+            .forRead(Cache.getProperty("LAST_DIRECTORY"), fileFormat, BackupFiles.getEnabled());
 
     chooser.setFileView(new JalviewFileView());
     chooser.setDialogTitle(
@@ -1107,7 +1135,7 @@ public class Desktop extends jalview.jbgui.GDesktop
     panel.add(history);
     history.setPreferredSize(new Dimension(400, 20));
     history.setEditable(true);
-    history.addItem("http://www.");
+    history.addItem("https://www.");
 
     String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
 
@@ -1284,9 +1312,10 @@ public class Desktop extends jalview.jbgui.GDesktop
       message.append("<h1><strong>Version: "
               + jalview.bin.Cache.getProperty("VERSION")
               + "</strong></h1>");
-      message.append("<strong>Last Updated: <em>"
+      message.append("<strong>Built: <em>"
               + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown")
-              + "</em></strong>");
+              + "</em> from " + jalview.bin.Cache.getBuildDetailsForSplash()
+              + "</strong>");
 
     }
     else
@@ -1301,7 +1330,8 @@ public class Desktop extends jalview.jbgui.GDesktop
     if (jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking")
             .equals("Checking"))
     {
-      message.append("<br>...Checking latest version...</br>");
+      // JBP removed this message for 2.11: May be reinstated in future version
+      // message.append("<br>...Checking latest version...</br>");
     }
     else if (!jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking")
             .equals(jalview.bin.Cache.getProperty("VERSION")))
@@ -1321,7 +1351,7 @@ public class Desktop extends jalview.jbgui.GDesktop
                       "..Checking..")
               + " is available for download from "
               + jalview.bin.Cache.getDefault("www.jalview.org",
-                      "http://www.jalview.org")
+                      "https://www.jalview.org")
               + " !!");
       if (red)
       {
@@ -1332,7 +1362,7 @@ public class Desktop extends jalview.jbgui.GDesktop
             "AUTHORFNAMES",
             "The Jalview Authors (See AUTHORS file for current list)")
             + "<br><br>Development managed by The Barton Group, University of Dundee, Scotland, UK.<br>"
-            + "<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"
+            + "<br><br>For help, see the FAQ at <a href=\"https://www.jalview.org/faq\">www.jalview.org/faq</a> and/or join the jalview-discuss@jalview.org mailing list"
             + "<br><br>If  you use Jalview, please cite:"
             + "<br>Waterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
             + "<br>Jalview Version 2 - a multiple sequence alignment editor and analysis workbench"
@@ -1374,10 +1404,6 @@ public class Desktop extends jalview.jbgui.GDesktop
     }
     Jalview.setCurrentAlignFrame(null);
     System.out.println("ALL CLOSED");
-    if (v_client != null)
-    {
-      // TODO clear binding to vamsas document objects on close_all
-    }
 
     /*
      * reset state of singleton objects as appropriate (clear down session state
@@ -1389,7 +1415,6 @@ public class Desktop extends jalview.jbgui.GDesktop
     {
       ssm.resetAll();
     }
-    System.gc();
   }
 
   @Override
@@ -1556,28 +1581,49 @@ public class Desktop extends jalview.jbgui.GDesktop
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Shows a file chooser dialog and writes out the current session as a Jalview
+   * project file
    */
   @Override
-  public void saveState_actionPerformed(ActionEvent e)
+  public void saveState_actionPerformed()
   {
-    JalviewFileChooser chooser = new JalviewFileChooser("jvp",
-            "Jalview Project");
+    saveState_actionPerformed(false);
+  }
 
-    chooser.setFileView(new JalviewFileView());
-    chooser.setDialogTitle(MessageManager.getString("label.save_state"));
+  public void saveState_actionPerformed(boolean saveAs)
+  {
+    java.io.File projectFile = getProjectFile();
+    // autoSave indicates we already have a file and don't need to ask
+    boolean autoSave = projectFile != null && !saveAs
+            && BackupFiles.getEnabled();
 
-    int value = chooser.showSaveDialog(this);
+    // System.out.println("autoSave="+autoSave+", projectFile='"+projectFile+"',
+    // saveAs="+saveAs+", Backups
+    // "+(BackupFiles.getEnabled()?"enabled":"disabled"));
 
-    if (value == JalviewFileChooser.APPROVE_OPTION)
+    boolean approveSave = false;
+    if (!autoSave)
     {
-      final Desktop me = this;
-      final java.io.File choice = chooser.getSelectedFile();
-      setProjectFile(choice);
+      JalviewFileChooser chooser = new JalviewFileChooser("jvp",
+              "Jalview Project");
+
+      chooser.setFileView(new JalviewFileView());
+      chooser.setDialogTitle(MessageManager.getString("label.save_state"));
+
+      int value = chooser.showSaveDialog(this);
+
+      if (value == JalviewFileChooser.APPROVE_OPTION)
+      {
+        projectFile = chooser.getSelectedFile();
+        setProjectFile(projectFile);
+        approveSave = true;
+      }
+    }
 
+    if (approveSave || autoSave)
+    {
+      final Desktop me = this;
+      final java.io.File chosenFile = projectFile;
       new Thread(new Runnable()
       {
         @Override
@@ -1586,38 +1632,47 @@ public class Desktop extends jalview.jbgui.GDesktop
           // TODO: refactor to Jalview desktop session controller action.
           setProgressBar(MessageManager.formatMessage(
                   "label.saving_jalview_project", new Object[]
-                  { choice.getName() }), choice.hashCode());
+                  { chosenFile.getName() }), chosenFile.hashCode());
           jalview.bin.Cache.setProperty("LAST_DIRECTORY",
-                  choice.getParent());
+                  chosenFile.getParent());
           // TODO catch and handle errors for savestate
           // TODO prevent user from messing with the Desktop whilst we're saving
           try
           {
-            new Jalview2XML().saveState(choice);
+            BackupFiles backupfiles = new BackupFiles(chosenFile);
+
+            new Jalview2XML().saveState(backupfiles.getTempFile());
+
+            backupfiles.setWriteSuccess(true);
+            backupfiles.rollBackupsAndRenameTempFile();
           } catch (OutOfMemoryError oom)
           {
-            new OOMWarning(
-                    "Whilst saving current state to " + choice.getName(),
-                    oom);
+            new OOMWarning("Whilst saving current state to "
+                    + chosenFile.getName(), oom);
           } catch (Exception ex)
           {
-            Cache.log.error(
-                    "Problems whilst trying to save to " + choice.getName(),
-                    ex);
+            Cache.log.error("Problems whilst trying to save to "
+                    + chosenFile.getName(), ex);
             JvOptionPane.showMessageDialog(me,
                     MessageManager.formatMessage(
                             "label.error_whilst_saving_current_state_to",
                             new Object[]
-                            { choice.getName() }),
+                            { chosenFile.getName() }),
                     MessageManager.getString("label.couldnt_save_project"),
                     JvOptionPane.WARNING_MESSAGE);
           }
-          setProgressBar(null, choice.hashCode());
+          setProgressBar(null, chosenFile.hashCode());
         }
       }).start();
     }
   }
 
+  @Override
+  public void saveAsState_actionPerformed(ActionEvent e)
+  {
+    saveState_actionPerformed(true);
+  }
+
   private void setProjectFile(File choice)
   {
     this.projectFile = choice;
@@ -1629,20 +1684,19 @@ public class Desktop extends jalview.jbgui.GDesktop
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Shows a file chooser dialog and tries to read in the selected file as a
+   * Jalview project
    */
   @Override
-  public void loadState_actionPerformed(ActionEvent e)
+  public void loadState_actionPerformed()
   {
+    final String[] suffix = new String[] { "jvp", "jar" };
+    final String[] desc = new String[] { "Jalview Project",
+        "Jalview Project (old)" };
     JalviewFileChooser chooser = new JalviewFileChooser(
-            Cache.getProperty("LAST_DIRECTORY"), new String[]
-            { "jvp", "jar" },
-            new String[]
-            { "Jalview Project", "Jalview Project (old)" },
-            "Jalview Project");
+            Cache.getProperty("LAST_DIRECTORY"), suffix, desc,
+            "Jalview Project", true, BackupFiles.getEnabled()); // last two booleans: allFiles,
+                                            // allowBackupFiles
     chooser.setFileView(new JalviewFileView());
     chooser.setDialogTitle(MessageManager.getString("label.restore_state"));
 
@@ -1869,11 +1923,28 @@ public class Desktop extends jalview.jbgui.GDesktop
       return;
     }
 
+    // FIXME: ideally should use UI interface API
+    FeatureSettings viewFeatureSettings = (af.featureSettings != null
+            && af.featureSettings.isOpen())
+            ? af.featureSettings
+            : null;
+    Rectangle fsBounds = af.getFeatureSettingsGeometry();
     for (int i = 0; i < size; i++)
     {
       AlignmentPanel ap = af.alignPanels.get(i);
+
       AlignFrame newaf = new AlignFrame(ap);
 
+      // transfer reference for existing feature settings to new alignFrame
+      if (ap == af.alignPanel)
+      {
+        if (viewFeatureSettings != null && viewFeatureSettings.fr.ap == ap)
+        {
+          newaf.featureSettings = viewFeatureSettings;
+        }
+        newaf.setFeatureSettingsGeometry(fsBounds);
+      }
+
       /*
        * Restore the view's last exploded frame geometry if known. Multiple
        * views from one exploded frame share and restore the same (frame)
@@ -1889,8 +1960,17 @@ public class Desktop extends jalview.jbgui.GDesktop
 
       addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
               AlignFrame.DEFAULT_HEIGHT);
+      // and materialise a new feature settings dialog instance for the new alignframe
+      // (closes the old as if 'OK' was pressed)
+      if (ap == af.alignPanel && newaf.featureSettings != null
+              && newaf.featureSettings.isOpen()
+              && af.alignPanel.getAlignViewport().isShowSequenceFeatures())
+      {
+        newaf.showFeatureSettingsUI();
+      }
     }
 
+    af.featureSettings = null;
     af.alignPanels.clear();
     af.closeMenuItem_actionPerformed(true);
 
@@ -1910,7 +1990,6 @@ public class Desktop extends jalview.jbgui.GDesktop
     source.viewport.setExplodedGeometry(source.getBounds());
     JInternalFrame[] frames = desktop.getAllFrames();
     String viewId = source.viewport.getSequenceSetId();
-
     for (int t = 0; t < frames.length; t++)
     {
       if (frames[t] instanceof AlignFrame && frames[t] != source)
@@ -1931,370 +2010,33 @@ public class Desktop extends jalview.jbgui.GDesktop
 
         if (gatherThis)
         {
-          af.alignPanels.clear();
-          af.closeMenuItem_actionPerformed(true);
-        }
-      }
-    }
-
-  }
-
-  jalview.gui.VamsasApplication v_client = null;
-
-  @Override
-  public void vamsasImport_actionPerformed(ActionEvent e)
-  {
-    if (v_client == null)
-    {
-      // Load and try to start a session.
-      JalviewFileChooser chooser = new JalviewFileChooser(
-              jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
-
-      chooser.setFileView(new JalviewFileView());
-      chooser.setDialogTitle(
-              MessageManager.getString("label.open_saved_vamsas_session"));
-      chooser.setToolTipText(MessageManager.getString(
-              "label.select_vamsas_session_opened_as_new_vamsas_session"));
-
-      int value = chooser.showOpenDialog(this);
-
-      if (value == JalviewFileChooser.APPROVE_OPTION)
-      {
-        String fle = chooser.getSelectedFile().toString();
-        if (!vamsasImport(chooser.getSelectedFile()))
-        {
-          JvOptionPane.showInternalMessageDialog(Desktop.desktop,
-                  MessageManager.formatMessage(
-                          "label.couldnt_import_as_vamsas_session",
-                          new Object[]
-                          { fle }),
-                  MessageManager
-                          .getString("label.vamsas_document_import_failed"),
-                  JvOptionPane.ERROR_MESSAGE);
-        }
-      }
-    }
-    else
-    {
-      jalview.bin.Cache.log.error(
-              "Implementation error - load session from a running session is not supported.");
-    }
-  }
-
-  /**
-   * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
-   * 
-   * @param file
-   * @return true if import was a success and a session was started.
-   */
-  public boolean vamsasImport(URL url)
-  {
-    // TODO: create progress bar
-    if (v_client != null)
-    {
-
-      jalview.bin.Cache.log.error(
-              "Implementation error - load session from a running session is not supported.");
-      return false;
-    }
-
-    try
-    {
-      // copy the URL content to a temporary local file
-      // TODO: be a bit cleverer here with nio (?!)
-      File file = File.createTempFile("vdocfromurl", ".vdj");
-      FileOutputStream fos = new FileOutputStream(file);
-      BufferedInputStream bis = new BufferedInputStream(url.openStream());
-      byte[] buffer = new byte[2048];
-      int ln;
-      while ((ln = bis.read(buffer)) > -1)
-      {
-        fos.write(buffer, 0, ln);
-      }
-      bis.close();
-      fos.close();
-      v_client = new jalview.gui.VamsasApplication(this, file,
-              url.toExternalForm());
-    } catch (Exception ex)
-    {
-      jalview.bin.Cache.log.error(
-              "Failed to create new vamsas session from contents of URL "
-                      + url,
-              ex);
-      return false;
-    }
-    setupVamsasConnectedGui();
-    v_client.initial_update(); // TODO: thread ?
-    return v_client.inSession();
-  }
-
-  /**
-   * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
-   * 
-   * @param file
-   * @return true if import was a success and a session was started.
-   */
-  public boolean vamsasImport(File file)
-  {
-    if (v_client != null)
-    {
-
-      jalview.bin.Cache.log.error(
-              "Implementation error - load session from a running session is not supported.");
-      return false;
-    }
-
-    setProgressBar(MessageManager.formatMessage(
-            "status.importing_vamsas_session_from", new Object[]
-            { file.getName() }), file.hashCode());
-    try
-    {
-      v_client = new jalview.gui.VamsasApplication(this, file, null);
-    } catch (Exception ex)
-    {
-      setProgressBar(MessageManager.formatMessage(
-              "status.importing_vamsas_session_from", new Object[]
-              { file.getName() }), file.hashCode());
-      jalview.bin.Cache.log.error(
-              "New vamsas session from existing session file failed:", ex);
-      return false;
-    }
-    setupVamsasConnectedGui();
-    v_client.initial_update(); // TODO: thread ?
-    setProgressBar(MessageManager.formatMessage(
-            "status.importing_vamsas_session_from", new Object[]
-            { file.getName() }), file.hashCode());
-    return v_client.inSession();
-  }
-
-  public boolean joinVamsasSession(String mysesid)
-  {
-    if (v_client != null)
-    {
-      throw new Error(MessageManager
-              .getString("error.try_join_vamsas_session_another"));
-    }
-    if (mysesid == null)
-    {
-      throw new Error(
-              MessageManager.getString("error.invalid_vamsas_session_id"));
-    }
-    v_client = new VamsasApplication(this, mysesid);
-    setupVamsasConnectedGui();
-    v_client.initial_update();
-    return (v_client.inSession());
-  }
-
-  @Override
-  public void vamsasStart_actionPerformed(ActionEvent e)
-  {
-    if (v_client == null)
-    {
-      // Start a session.
-      // we just start a default session for moment.
-      /*
-       * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
-       * getProperty("LAST_DIRECTORY"));
-       * 
-       * chooser.setFileView(new JalviewFileView());
-       * chooser.setDialogTitle("Load Vamsas file");
-       * chooser.setToolTipText("Import");
-       * 
-       * int value = chooser.showOpenDialog(this);
-       * 
-       * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
-       * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
-       */
-      v_client = new VamsasApplication(this);
-      setupVamsasConnectedGui();
-      v_client.initial_update(); // TODO: thread ?
-    }
-    else
-    {
-      // store current data in session.
-      v_client.push_update(); // TODO: thread
-    }
-  }
-
-  protected void setupVamsasConnectedGui()
-  {
-    vamsasStart.setText(MessageManager.getString("label.session_update"));
-    vamsasSave.setVisible(true);
-    vamsasStop.setVisible(true);
-    vamsasImport.setVisible(false); // Document import to existing session is
-    // not possible for vamsas-client-1.0.
-  }
-
-  protected void setupVamsasDisconnectedGui()
-  {
-    vamsasSave.setVisible(false);
-    vamsasStop.setVisible(false);
-    vamsasImport.setVisible(true);
-    vamsasStart
-            .setText(MessageManager.getString("label.new_vamsas_session"));
-  }
-
-  @Override
-  public void vamsasStop_actionPerformed(ActionEvent e)
-  {
-    if (v_client != null)
-    {
-      v_client.end_session();
-      v_client = null;
-      setupVamsasDisconnectedGui();
-    }
-  }
-
-  protected void buildVamsasStMenu()
-  {
-    if (v_client == null)
-    {
-      String[] sess = null;
-      try
-      {
-        sess = VamsasApplication.getSessionList();
-      } catch (Exception e)
-      {
-        jalview.bin.Cache.log.warn("Problem getting current sessions list.",
-                e);
-        sess = null;
-      }
-      if (sess != null)
-      {
-        jalview.bin.Cache.log.debug(
-                "Got current sessions list: " + sess.length + " entries.");
-        VamsasStMenu.removeAll();
-        for (int i = 0; i < sess.length; i++)
-        {
-          JMenuItem sessit = new JMenuItem();
-          sessit.setText(sess[i]);
-          sessit.setToolTipText(MessageManager
-                  .formatMessage("label.connect_to_session", new Object[]
-                  { sess[i] }));
-          final Desktop dsktp = this;
-          final String mysesid = sess[i];
-          sessit.addActionListener(new ActionListener()
+          if (af.featureSettings != null && af.featureSettings.isOpen())
           {
-
-            @Override
-            public void actionPerformed(ActionEvent e)
+            if (source.featureSettings == null)
             {
-              if (dsktp.v_client == null)
-              {
-                Thread rthr = new Thread(new Runnable()
-                {
-
-                  @Override
-                  public void run()
-                  {
-                    dsktp.v_client = new VamsasApplication(dsktp, mysesid);
-                    dsktp.setupVamsasConnectedGui();
-                    dsktp.v_client.initial_update();
-                  }
-
-                });
-                rthr.start();
-              }
-            };
-          });
-          VamsasStMenu.add(sessit);
+              // preserve the feature settings geometry for this frame
+              source.featureSettings = af.featureSettings;
+              source.setFeatureSettingsGeometry(
+                      af.getFeatureSettingsGeometry());
+            }
+            else
+            {
+              // close it and forget
+              af.featureSettings.close();
+            }
+          }
+          af.alignPanels.clear();
+          af.closeMenuItem_actionPerformed(true);
         }
-        // don't show an empty menu.
-        VamsasStMenu.setVisible(sess.length > 0);
-
-      }
-      else
-      {
-        jalview.bin.Cache.log.debug("No current vamsas sessions.");
-        VamsasStMenu.removeAll();
-        VamsasStMenu.setVisible(false);
       }
     }
-    else
-    {
-      // Not interested in the content. Just hide ourselves.
-      VamsasStMenu.setVisible(false);
-    }
-  }
-
-  @Override
-  public void vamsasSave_actionPerformed(ActionEvent e)
-  {
-    if (v_client != null)
+    // refresh the feature setting UI for the source frame if it exists
+    if (source.featureSettings != null
+            && source.featureSettings.isOpen())
     {
-      // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
-      JalviewFileChooser chooser = new JalviewFileChooser("vdj",
-              "Vamsas Document");
-
-      chooser.setFileView(new JalviewFileView());
-      chooser.setDialogTitle(MessageManager
-              .getString("label.save_vamsas_document_archive"));
-
-      int value = chooser.showSaveDialog(this);
-
-      if (value == JalviewFileChooser.APPROVE_OPTION)
-      {
-        java.io.File choice = chooser.getSelectedFile();
-        JPanel progpanel = addProgressPanel(MessageManager
-                .formatMessage("label.saving_vamsas_doc", new Object[]
-                { choice.getName() }));
-        Cache.setProperty("LAST_DIRECTORY", choice.getParent());
-        String warnmsg = null;
-        String warnttl = null;
-        try
-        {
-          v_client.vclient.storeDocument(choice);
-        } catch (Error ex)
-        {
-          warnttl = "Serious Problem saving Vamsas Document";
-          warnmsg = ex.toString();
-          jalview.bin.Cache.log
-                  .error("Error Whilst saving document to " + choice, ex);
-
-        } catch (Exception ex)
-        {
-          warnttl = "Problem saving Vamsas Document.";
-          warnmsg = ex.toString();
-          jalview.bin.Cache.log.warn(
-                  "Exception Whilst saving document to " + choice, ex);
-
-        }
-        removeProgressPanel(progpanel);
-        if (warnmsg != null)
-        {
-          JvOptionPane.showInternalMessageDialog(Desktop.desktop,
-
-                  warnmsg, warnttl, JvOptionPane.ERROR_MESSAGE);
-        }
-      }
+      source.showFeatureSettingsUI();
     }
-  }
-
-  JPanel vamUpdate = null;
-
-  /**
-   * hide vamsas user gui bits when a vamsas document event is being handled.
-   * 
-   * @param b
-   *          true to hide gui, false to reveal gui
-   */
-  public void setVamsasUpdate(boolean b)
-  {
-    Cache.log.debug("Setting gui for Vamsas update "
-            + (b ? "in progress" : "finished"));
 
-    if (vamUpdate != null)
-    {
-      this.removeProgressPanel(vamUpdate);
-    }
-    if (b)
-    {
-      vamUpdate = this.addProgressPanel(
-              MessageManager.getString("label.updating_vamsas_session"));
-    }
-    vamsasStart.setVisible(!b);
-    vamsasStop.setVisible(!b);
-    vamsasSave.setVisible(!b);
   }
 
   public JInternalFrame[] getAllFrames()
@@ -2338,7 +2080,7 @@ public class Desktop extends jalview.jbgui.GDesktop
           while (li.hasNext())
           {
             String link = li.next();
-            if (link.contains(SEQUENCE_ID)
+            if (link.contains(jalview.util.UrlConstants.SEQUENCE_ID)
                     && !UrlConstants.isDefaultString(link))
             {
               check = true;
@@ -2492,7 +2234,6 @@ public class Desktop extends jalview.jbgui.GDesktop
     }
   }
 
-
   /**
    * Accessor method to quickly get all the AlignmentFrames loaded.
    * 
@@ -2647,7 +2388,7 @@ public class Desktop extends jalview.jbgui.GDesktop
   {
     getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
             .put(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
-                    Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
+                    jalview.util.ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx()),
                     "Quit");
     getRootPane().getActionMap().put("Quit", new AbstractAction()
     {
@@ -2704,18 +2445,18 @@ public class Desktop extends jalview.jbgui.GDesktop
       progressBarHandlers = new Hashtable<>();
     }
 
-    if (progressBars.get(new Long(id)) != null)
+    if (progressBars.get(Long.valueOf(id)) != null)
     {
-      JPanel panel = progressBars.remove(new Long(id));
-      if (progressBarHandlers.contains(new Long(id)))
+      JPanel panel = progressBars.remove(Long.valueOf(id));
+      if (progressBarHandlers.contains(Long.valueOf(id)))
       {
-        progressBarHandlers.remove(new Long(id));
+        progressBarHandlers.remove(Long.valueOf(id));
       }
       removeProgressPanel(panel);
     }
     else
     {
-      progressBars.put(new Long(id), addProgressPanel(message));
+      progressBars.put(Long.valueOf(id), addProgressPanel(message));
     }
   }
 
@@ -2730,13 +2471,13 @@ public class Desktop extends jalview.jbgui.GDesktop
           final IProgressIndicatorHandler handler)
   {
     if (progressBarHandlers == null
-            || !progressBars.containsKey(new Long(id)))
+            || !progressBars.containsKey(Long.valueOf(id)))
     {
       throw new Error(MessageManager.getString(
               "error.call_setprogressbar_before_registering_handler"));
     }
-    progressBarHandlers.put(new Long(id), handler);
-    final JPanel progressPanel = progressBars.get(new Long(id));
+    progressBarHandlers.put(Long.valueOf(id), handler);
+    final JPanel progressPanel = progressBars.get(Long.valueOf(id));
     if (handler.canCancel())
     {
       JButton cancel = new JButton(
@@ -2800,7 +2541,8 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   public VamsasApplication getVamsasApplication()
   {
-    return v_client;
+    // TODO: JAL-3311 remove remaining code from Jalview relating to VAMSAS
+    return null;
 
   }
 
@@ -2829,13 +2571,36 @@ public class Desktop extends jalview.jbgui.GDesktop
     this.inBatchMode = inBatchMode;
   }
 
+  /**
+   * start service discovery and wait till it is done
+   */
   public void startServiceDiscovery()
   {
     startServiceDiscovery(false);
   }
 
+  /**
+   * start service discovery threads - blocking or non-blocking
+   * 
+   * @param blocking
+   */
   public void startServiceDiscovery(boolean blocking)
   {
+    startServiceDiscovery(blocking,false);
+  }
+
+  /**
+   * start service discovery threads
+   * 
+   * @param blocking
+   *          - false means call returns immediately
+   * @param ignore_SHOW_JWS2_SERVICES_preference
+   *          - when true JABA services are discovered regardless of user's JWS2
+   *          discovery preference setting
+   */
+  public void startServiceDiscovery(boolean blocking,
+          boolean ignore_SHOW_JWS2_SERVICES_preference)
+  {
     boolean alive = true;
     Thread t0 = null, t1 = null, t2 = null;
     // JAL-940 - JALVIEW 1 services are now being EOLed as of JABA 2.1 release
@@ -2853,7 +2618,8 @@ public class Desktop extends jalview.jbgui.GDesktop
       (t0 = new Thread(discoverer)).start();
     }
 
-    if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
+    if (ignore_SHOW_JWS2_SERVICES_preference
+            || Cache.getDefault("SHOW_JWS2_SERVICES", true))
     {
       t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
               .startDiscoverer(changeSupport);
@@ -3294,13 +3060,67 @@ public class Desktop extends jalview.jbgui.GDesktop
     return groovyConsole;
   }
 
+  /**
+   * handles the payload of a drag and drop event.
+   * 
+   * TODO refactor to desktop utilities class
+   * 
+   * @param files
+   *          - Data source strings extracted from the drop event
+   * @param protocols
+   *          - protocol for each data source extracted from the drop event
+   * @param evt
+   *          - the drop event
+   * @param t
+   *          - the payload from the drop event
+   * @throws Exception
+   */
   public static void transferFromDropTarget(List<String> files,
           List<DataSourceType> protocols, DropTargetDropEvent evt,
           Transferable t) throws Exception
   {
 
     DataFlavor uriListFlavor = new DataFlavor(
-            "text/uri-list;class=java.lang.String");
+            "text/uri-list;class=java.lang.String"), urlFlavour = null;
+    try
+    {
+      urlFlavour = new DataFlavor(
+              "application/x-java-url; class=java.net.URL");
+    } catch (ClassNotFoundException cfe)
+    {
+      Cache.log.debug("Couldn't instantiate the URL dataflavor.", cfe);
+    }
+
+    if (urlFlavour != null && t.isDataFlavorSupported(urlFlavour))
+    {
+
+      try
+      {
+        java.net.URL url = (URL) t.getTransferData(urlFlavour);
+        // nb: java 8 osx bug https://bugs.openjdk.java.net/browse/JDK-8156099
+        // means url may be null.
+        if (url != null)
+        {
+          protocols.add(DataSourceType.URL);
+          files.add(url.toString());
+          Cache.log.debug("Drop handled as URL dataflavor "
+                  + files.get(files.size() - 1));
+          return;
+        }
+        else
+        {
+          if (Platform.isAMac())
+          {
+            System.err.println(
+                    "Please ignore plist error - occurs due to problem with java 8 on OSX");
+          }
+          ;
+        }
+      } catch (Throwable ex)
+      {
+        Cache.log.debug("URL drop handler failed.", ex);
+      }
+    }
     if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
     {
       // Works on Windows and MacOSX
@@ -3328,63 +3148,114 @@ public class Desktop extends jalview.jbgui.GDesktop
         // fallback to text: workaround - on OSX where there's a JVM bug
         Cache.log.debug("standard URIListFlavor failed. Trying text");
         // try text fallback
-        data = (String) t.getTransferData(
-                new DataFlavor("text/plain;class=java.lang.String"));
-        if (Cache.log.isDebugEnabled())
+        DataFlavor textDf = new DataFlavor(
+                "text/plain;class=java.lang.String");
+        if (t.isDataFlavorSupported(textDf))
         {
-          Cache.log.debug("fallback returned " + data);
+          data = (String) t.getTransferData(textDf);
         }
+
+        Cache.log.debug("Plain text drop content returned "
+                + (data == null ? "Null - failed" : data));
+
       }
-      while (protocols.size() < files.size())
-      {
-        Cache.log.debug("Adding missing FILE protocol for "
-                + files.get(protocols.size()));
-        protocols.add(DataSourceType.FILE);
-      }
-      for (java.util.StringTokenizer st = new java.util.StringTokenizer(
-              data, "\r\n"); st.hasMoreTokens();)
+      if (data != null)
       {
-        added = true;
-        String s = st.nextToken();
-        if (s.startsWith("#"))
-        {
-          // the line is a comment (as per the RFC 2483)
-          continue;
-        }
-        java.net.URI uri = new java.net.URI(s);
-        if (uri.getScheme().toLowerCase().startsWith("http"))
+        while (protocols.size() < files.size())
         {
-          protocols.add(DataSourceType.URL);
-          files.add(uri.toString());
+          Cache.log.debug("Adding missing FILE protocol for "
+                  + files.get(protocols.size()));
+          protocols.add(DataSourceType.FILE);
         }
-        else
+        for (java.util.StringTokenizer st = new java.util.StringTokenizer(
+                data, "\r\n"); st.hasMoreTokens();)
         {
-          // otherwise preserve old behaviour: catch all for file objects
-          java.io.File file = new java.io.File(uri);
-          protocols.add(DataSourceType.FILE);
-          files.add(file.toString());
+          added = true;
+          String s = st.nextToken();
+          if (s.startsWith("#"))
+          {
+            // the line is a comment (as per the RFC 2483)
+            continue;
+          }
+          java.net.URI uri = new java.net.URI(s);
+          if (uri.getScheme().toLowerCase().startsWith("http"))
+          {
+            protocols.add(DataSourceType.URL);
+            files.add(uri.toString());
+          }
+          else
+          {
+            // otherwise preserve old behaviour: catch all for file objects
+            java.io.File file = new java.io.File(uri);
+            protocols.add(DataSourceType.FILE);
+            files.add(file.toString());
+          }
         }
       }
+
       if (Cache.log.isDebugEnabled())
       {
         if (data == null || !added)
         {
-          Cache.log.debug(
-                  "Couldn't resolve drop data. Here are the supported flavors:");
-          for (DataFlavor fl : t.getTransferDataFlavors())
+
+          if (t.getTransferDataFlavors() != null
+                  && t.getTransferDataFlavors().length > 0)
           {
             Cache.log.debug(
-                    "Supported transfer dataflavor: " + fl.toString());
-            Object df = t.getTransferData(fl);
-            if (df != null)
-            {
-              Cache.log.debug("Retrieves: " + df);
-            }
-            else
+                    "Couldn't resolve drop data. Here are the supported flavors:");
+            for (DataFlavor fl : t.getTransferDataFlavors())
             {
-              Cache.log.debug("Retrieved nothing");
+              Cache.log.debug(
+                      "Supported transfer dataflavor: " + fl.toString());
+              Object df = t.getTransferData(fl);
+              if (df != null)
+              {
+                Cache.log.debug("Retrieves: " + df);
+              }
+              else
+              {
+                Cache.log.debug("Retrieved nothing");
+              }
             }
           }
+          else
+          {
+            Cache.log.debug("Couldn't resolve dataflavor for drop: "
+                    + t.toString());
+          }
+        }
+      }
+    }
+    if (Platform.isWindows())
+
+    {
+      Cache.log.debug("Scanning dropped content for Windows Link Files");
+
+      // resolve any .lnk files in the file drop
+      for (int f = 0; f < files.size(); f++)
+      {
+        String source = files.get(f).toLowerCase();
+        if (protocols.get(f).equals(DataSourceType.FILE)
+                && (source.endsWith(".lnk") || source.endsWith(".url")
+                        || source.endsWith(".site")))
+        {
+          try
+          {
+            File lf = new File(files.get(f));
+            // process link file to get a URL
+            Cache.log.debug("Found potential link file: " + lf);
+            WindowsShortcut wscfile = new WindowsShortcut(lf);
+            String fullname = wscfile.getRealFilename();
+            protocols.set(f, FormatAdapter.checkProtocol(fullname));
+            files.set(f, fullname);
+            Cache.log.debug("Parsed real filename " + fullname
+                    + " to extract protocol: " + protocols.get(f));
+          } catch (Exception ex)
+          {
+            Cache.log.error(
+                    "Couldn't parse " + files.get(f) + " as a link file.",
+                    ex);
+          }
         }
       }
     }
@@ -3399,4 +3270,41 @@ public class Desktop extends jalview.jbgui.GDesktop
   {
     Cache.setProperty(EXPERIMENTAL_FEATURES, Boolean.toString(selected));
   }
+
+  /**
+   * Answers a (possibly empty) list of any structure viewer frames (currently
+   * for either Jmol or Chimera) which are currently open. This may optionally
+   * be restricted to viewers of a specified class, or viewers linked to a
+   * specified alignment panel.
+   * 
+   * @param apanel
+   *          if not null, only return viewers linked to this panel
+   * @param structureViewerClass
+   *          if not null, only return viewers of this class
+   * @return
+   */
+  public List<StructureViewerBase> getStructureViewers(
+          AlignmentPanel apanel,
+          Class<? extends StructureViewerBase> structureViewerClass)
+  {
+    List<StructureViewerBase> result = new ArrayList<>();
+    JInternalFrame[] frames = Desktop.instance.getAllFrames();
+
+    for (JInternalFrame frame : frames)
+    {
+      if (frame instanceof StructureViewerBase)
+      {
+        if (structureViewerClass == null
+                || structureViewerClass.isInstance(frame))
+        {
+          if (apanel == null
+                  || ((StructureViewerBase) frame).isLinkedWith(apanel))
+          {
+            result.add((StructureViewerBase) frame);
+          }
+        }
+      }
+    }
+    return result;
+  }
 }