JAL-1551 JAL-3048 formatting
[jalview.git] / src / jalview / gui / Desktop.java
index bf729f6..774dd4c 100644 (file)
@@ -32,6 +32,7 @@ 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;
@@ -43,6 +44,7 @@ import jalview.util.ImageMaker;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
 import jalview.util.UrlConstants;
+import jalview.util.dialogrunner.RunResponse;
 import jalview.viewmodel.AlignmentViewport;
 import jalview.ws.params.ParamManager;
 import jalview.ws.utils.UrlDownloadClient;
@@ -68,8 +70,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.FocusEvent;
-import java.awt.event.FocusListener;
+import java.awt.event.InputEvent;
 import java.awt.event.KeyEvent;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
@@ -93,10 +94,13 @@ 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;
@@ -118,6 +122,8 @@ import javax.swing.event.InternalFrameEvent;
 import javax.swing.event.MenuEvent;
 import javax.swing.event.MenuListener;
 
+import org.stackoverflowusers.file.WindowsShortcut;
+
 /**
  * Jalview Desktop
  * 
@@ -188,6 +194,13 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   public static MyDesktopPane desktop;
 
+  public static MyDesktopPane getDesktop()
+  {
+    // BH 2018 could use currentThread() here as a reference to a
+    // Hashtable<Thread, MyDesktopPane> in JavaScript
+    return desktop;
+  }
+
   static int openFrameCount = 0;
 
   static final int xOffset = 30;
@@ -331,9 +344,8 @@ public class Desktop extends jalview.jbgui.GDesktop
   public Desktop()
   {
     /**
-     * A note to implementors. It is ESSENTIAL that any activities that might
-     * block are spawned off as threads rather than waited for during this
-     * constructor.
+     * A note to implementors. It is ESSENTIAL that any activities that might block
+     * are spawned off as threads rather than waited for during this constructor.
      */
     instance = this;
     doVamsasClientCheck();
@@ -346,10 +358,6 @@ public class Desktop extends jalview.jbgui.GDesktop
     boolean showjconsole = jalview.bin.Cache.getDefault("SHOW_JAVA_CONSOLE",
             false);
     desktop = new MyDesktopPane(selmemusage);
-    if (Platform.isAMac())
-    {
-      desktop.setDoubleBuffered(false);
-    }
     showMemusage.setSelected(selmemusage);
     desktop.setBackground(Color.white);
     getContentPane().setLayout(new BorderLayout());
@@ -362,8 +370,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(new DefaultDesktopManager()));
+    desktop.setDesktopManager(new MyDesktopManager(
+            (Platform.isWindows() ? new DefaultDesktopManager()
+                    : Platform.isAMac()
+                            ? new AquaInternalFrameManager(
+                                    desktop.getDesktopManager())
+                            : desktop.getDesktopManager())));
 
     Rectangle dims = getLastKnownDimensions("");
     if (dims != null)
@@ -373,33 +385,83 @@ public class Desktop extends jalview.jbgui.GDesktop
     else
     {
       Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
-      setBounds((screenSize.width - 900) / 2, (screenSize.height - 650) / 2,
-              900, 650);
+      int xPos = Math.max(5, (screenSize.width - 900) / 2);
+      int yPos = Math.max(5, (screenSize.height - 650) / 2);
+      setBounds(xPos, yPos, 900, 650);
     }
-    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"));
+    /**
+     * BH 2018
+     * 
+     * @j2sNative
+     */
+    {
+
+      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"));
+
+      showConsole(showjconsole);
+
+      showNews.setVisible(false);
+
+      experimentalFeatures.setSelected(showExperimental());
+
+      getIdentifiersOrgData();
+
+      checkURLLinks();
+
+      // Spawn a thread that shows the splashscreen
+
+      SwingUtilities.invokeLater(new Runnable()
+      {
+        @Override
+        public void run()
+        {
+          new SplashScreen();
+        }
+      });
 
-    showConsole(showjconsole);
+      // Thread off a new instance of the file chooser - this reduces the time it
+      // takes to open it later on.
+      new Thread(new Runnable()
+      {
+        @Override
+        public void run()
+        {
+          Cache.log.debug("Filechooser init thread started.");
+          String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
+          JalviewFileChooser.forRead(Cache.getProperty("LAST_DIRECTORY"),
+                  fileFormat);
+          Cache.log.debug("Filechooser init thread finished.");
+        }
+      }).start();
+      // Add the service change listener
+      changeSupport.addJalviewPropertyChangeListener("services",
+              new PropertyChangeListener()
+              {
 
-    showNews.setVisible(false);
+                @Override
+                public void propertyChange(PropertyChangeEvent evt)
+                {
+                  Cache.log.debug("Firing service changed event for "
+                          + evt.getNewValue());
+                  JalviewServicesChanged(evt);
+                }
 
-    experimentalFeatures.setSelected(showExperimental());
+              });
 
-    getIdentifiersOrgData();
+    } // end BH 2018 ignore
 
-    checkURLLinks();
+    this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
 
     this.addWindowListener(new WindowAdapter()
     {
@@ -433,63 +495,6 @@ public class Desktop extends jalview.jbgui.GDesktop
     });
     desktop.addMouseListener(ma);
 
-    this.addFocusListener(new FocusListener()
-    {
-
-      @Override
-      public void focusLost(FocusEvent e)
-      {
-        // TODO Auto-generated method stub
-
-      }
-
-      @Override
-      public void focusGained(FocusEvent e)
-      {
-        Cache.log.debug("Relaying windows after focus gain");
-        // make sure that we sort windows properly after we gain focus
-        instance.relayerWindows();
-      }
-    });
-    this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
-    // Spawn a thread that shows the splashscreen
-    SwingUtilities.invokeLater(new Runnable()
-    {
-      @Override
-      public void run()
-      {
-        new SplashScreen();
-      }
-    });
-
-    // Thread off a new instance of the file chooser - this reduces the time it
-    // takes to open it later on.
-    new Thread(new Runnable()
-    {
-      @Override
-      public void run()
-      {
-        Cache.log.debug("Filechooser init thread started.");
-        String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
-        JalviewFileChooser.forRead(Cache.getProperty("LAST_DIRECTORY"),
-                fileFormat);
-        Cache.log.debug("Filechooser init thread finished.");
-      }
-    }).start();
-    // Add the service change listener
-    changeSupport.addJalviewPropertyChangeListener("services",
-            new PropertyChangeListener()
-            {
-
-              @Override
-              public void propertyChange(PropertyChangeEvent evt)
-              {
-                Cache.log.debug("Firing service changed event for "
-                        + evt.getNewValue());
-                JalviewServicesChanged(evt);
-              }
-
-            });
   }
 
   /**
@@ -529,20 +534,28 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   public void checkForNews()
   {
-    final Desktop me = this;
-    // Thread off the news reader, in case there are connection problems.
-    addDialogThread(new Runnable()
+
+    /**
+     * BH 2018
+     * 
+     * @j2sNative
+     */
     {
-      @Override
-      public void run()
+      final Desktop me = this;
+      // Thread off the news reader, in case there are connection problems.
+      addDialogThread(new Runnable()
       {
-        Cache.log.debug("Starting news thread.");
+        @Override
+        public void run()
+        {
+          Cache.log.debug("Starting news thread.");
 
-        jvnews = new BlogReader(me);
-        showNews.setVisible(true);
-        Cache.log.debug("Completed news thread.");
-      }
-    });
+          jvnews = new BlogReader(me);
+          showNews.setVisible(true);
+          Cache.log.debug("Completed news thread.");
+        }
+      });
+    }
   }
 
   public void getIdentifiersOrgData()
@@ -576,6 +589,12 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   void showNews(boolean visible)
   {
+    /**
+     * BH 2018
+     * 
+     * @j2sNative
+     * 
+     */
     {
       Cache.log.debug((visible ? "Showing" : "Hiding") + " news.");
       showNews.setSelected(visible);
@@ -659,7 +678,8 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   private void doVamsasClientCheck()
   {
-    if (jalview.bin.Cache.vamsasJarsPresent())
+    if (/** @j2sNative false && */ // BH 2018
+    jalview.bin.Cache.vamsasJarsPresent())
     {
       setupVamsasDisconnectedGui();
       VamsasMenu.setVisible(true);
@@ -868,13 +888,9 @@ public class Desktop extends jalview.jbgui.GDesktop
     frame.setResizable(resizable);
     frame.setMaximizable(resizable);
     frame.setIconifiable(resizable);
-    if (Platform.isAMac())
-    {
-      frame.setIconifiable(false);
-      frame.setFrameIcon(null);
-      // frame.setDesktopIcon(null);
-      frame.setDoubleBuffered(false);
-    }
+    frame.setOpaque(/** @j2sNative true || */
+            false);
+
     if (frame.getX() < 1 && frame.getY() < 1)
     {
       frame.setLocation(xOffset * openFrameCount,
@@ -894,6 +910,10 @@ public class Desktop extends jalview.jbgui.GDesktop
         JInternalFrame itf = desktop.getSelectedFrame();
         if (itf != null)
         {
+          if (itf instanceof AlignFrame)
+          {
+            Jalview.setCurrentAlignFrame((AlignFrame) itf);
+          }
           itf.requestFocus();
         }
       }
@@ -920,16 +940,6 @@ public class Desktop extends jalview.jbgui.GDesktop
           menuItem.removeActionListener(menuItem.getActionListeners()[0]);
         }
         windowMenu.remove(menuItem);
-        JInternalFrame itf = desktop.getSelectedFrame();
-        if (itf != null)
-        {
-          itf.requestFocus();
-          if (itf instanceof AlignFrame)
-          {
-            Jalview.setCurrentAlignFrame((AlignFrame) itf);
-          }
-        }
-        System.gc();
       };
     });
 
@@ -949,6 +959,8 @@ public class Desktop extends jalview.jbgui.GDesktop
       }
     });
 
+    setKeyBindings(frame);
+
     desktop.add(frame);
 
     windowMenu.add(menuItem);
@@ -968,6 +980,42 @@ public class Desktop extends jalview.jbgui.GDesktop
     }
   }
 
+  /**
+   * 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,
+            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
+
+    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)
   {
@@ -1013,8 +1061,8 @@ public class Desktop extends jalview.jbgui.GDesktop
     // Java's Transferable for native dnd
     evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
     Transferable t = evt.getTransferable();
-    List<String> files = new ArrayList<String>();
-    List<DataSourceType> protocols = new ArrayList<DataSourceType>();
+    List<Object> files = new ArrayList<>();
+    List<DataSourceType> protocols = new ArrayList<>();
 
     try
     {
@@ -1031,13 +1079,15 @@ public class Desktop extends jalview.jbgui.GDesktop
       {
         for (int i = 0; i < files.size(); i++)
         {
-          String file = files.get(i).toString();
+          // BH 2018 File or String
+          Object file = files.get(i);
+          String fileName = file.toString();
           DataSourceType protocol = (protocols == null)
                   ? DataSourceType.FILE
                   : protocols.get(i);
           FileFormatI format = null;
 
-          if (file.endsWith(".jar"))
+          if (fileName.endsWith(".jar"))
           {
             format = FileFormat.Jalview;
 
@@ -1047,7 +1097,7 @@ public class Desktop extends jalview.jbgui.GDesktop
             format = new IdentifyFile().identify(file, protocol);
           }
 
-          new FileLoader().LoadFile(file, protocol, format);
+          new FileLoader().LoadFile(null, file, protocol, format);
 
         }
       } catch (Exception ex)
@@ -1069,7 +1119,7 @@ public class Desktop extends jalview.jbgui.GDesktop
   public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
   {
     String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
-    JalviewFileChooser chooser = JalviewFileChooser
+    final JalviewFileChooser chooser = JalviewFileChooser
             .forRead(Cache.getProperty("LAST_DIRECTORY"), fileFormat);
 
     chooser.setFileView(new JalviewFileView());
@@ -1077,42 +1127,38 @@ public class Desktop extends jalview.jbgui.GDesktop
             MessageManager.getString("label.open_local_file"));
     chooser.setToolTipText(MessageManager.getString("action.open"));
 
-    int value = chooser.showOpenDialog(this);
-
-    if (value == JalviewFileChooser.APPROVE_OPTION)
+    chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
     {
-      String choice = chooser.getSelectedFile().getPath();
-      Cache.setProperty("LAST_DIRECTORY",
-              chooser.getSelectedFile().getParent());
-
-      FileFormatI format = chooser.getSelectedFormat();
 
-      /*
-       * Call IdentifyFile to verify the file contains what its extension implies.
-       * Skip this step for dynamically added file formats, because
-       * IdentifyFile does not know how to recognise them.
-       */
-      if (FileFormats.getInstance().isIdentifiable(format))
+      @Override
+      public void run()
       {
-        try
-        {
-          format = new IdentifyFile().identify(choice, DataSourceType.FILE);
-        } catch (FileFormatException e)
+        File selectedFile = chooser.getSelectedFile();
+        Cache.setProperty("LAST_DIRECTORY", selectedFile.getParent());
+
+        FileFormatI format = chooser.getSelectedFormat();
+
+        /*
+         * Call IdentifyFile to verify the file contains what its extension implies.
+         * Skip this step for dynamically added file formats, because
+         * IdentifyFile does not know how to recognise them.
+         */
+        if (FileFormats.getInstance().isIdentifiable(format))
         {
-          // format = null; //??
+          try
+          {
+            format = new IdentifyFile().identify(selectedFile,
+                    DataSourceType.FILE);
+          } catch (FileFormatException e)
+          {
+            // format = null; //??
+          }
         }
-      }
 
-      if (viewport != null)
-      {
-        new FileLoader().LoadFile(viewport, choice, DataSourceType.FILE,
-                format);
+        new FileLoader().LoadFile(viewport, selectedFile,
+                DataSourceType.FILE, format);
       }
-      else
-      {
-        new FileLoader().LoadFile(choice, DataSourceType.FILE, format);
-      }
-    }
+    }).openDialog(this);
   }
 
   /**
@@ -1128,8 +1174,8 @@ public class Desktop extends jalview.jbgui.GDesktop
     // for viewing
     JLabel label = new JLabel(
             MessageManager.getString("label.input_file_url"));
-    final JComboBox history = new JComboBox();
 
+    JComboBox history = new JComboBox();
     JPanel panel = new JPanel(new GridLayout(2, 1));
     panel.add(label);
     panel.add(history);
@@ -1151,64 +1197,24 @@ public class Desktop extends jalview.jbgui.GDesktop
       }
     }
 
-    int reply = JvOptionPane.showInternalConfirmDialog(desktop, panel,
-            MessageManager.getString("label.input_alignment_from_url"),
-            JvOptionPane.OK_CANCEL_OPTION);
+    // BH 2018 -- providing a callback for SwingJS
+    // dialogOption is just a simple way to provide
+    // context for the modal-like response.
+    // The only requirement is that desktop implement
+    // PropertyChangeListener, which is used already in Java
+    // for changes in input value and such within the dialogs.
 
-    if (reply != JvOptionPane.OK_OPTION)
-    {
-      return;
-    }
+    String dialogOption = "label.input_alignment_from_url";
+    desktop.dialogData = new Object[] { dialogOption, viewport, history };
+    desktop.onDialogReturn(JvOptionPane.showInternalConfirmDialog(desktop,
+            panel, MessageManager.getString(dialogOption),
+            JvOptionPane.OK_CANCEL_OPTION));
 
-    String url = history.getSelectedItem().toString();
+    // no code may follow this, as SwingJS will not block
+    // callback in JavaScript comes via a property change event,
+    // thus going into desktop.onDialogReturn(int) just the same as
+    // in Java.
 
-    if (url.toLowerCase().endsWith(".jar"))
-    {
-      if (viewport != null)
-      {
-        new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
-                FileFormat.Jalview);
-      }
-      else
-      {
-        new FileLoader().LoadFile(url, DataSourceType.URL,
-                FileFormat.Jalview);
-      }
-    }
-    else
-    {
-      FileFormatI format = null;
-      try
-      {
-        format = new IdentifyFile().identify(url, DataSourceType.URL);
-      } catch (FileFormatException e)
-      {
-        // TODO revise error handling, distinguish between
-        // URL not found and response not valid
-      }
-
-      if (format == null)
-      {
-        JvOptionPane.showInternalMessageDialog(Desktop.desktop,
-                MessageManager.formatMessage("label.couldnt_locate",
-                        new Object[]
-                        { url }),
-                MessageManager.getString("label.url_not_found"),
-                JvOptionPane.WARNING_MESSAGE);
-
-        return;
-      }
-
-      if (viewport != null)
-      {
-        new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
-                format);
-      }
-      else
-      {
-        new FileLoader().LoadFile(url, DataSourceType.URL, format);
-      }
-    }
   }
 
   /**
@@ -1417,7 +1423,6 @@ public class Desktop extends jalview.jbgui.GDesktop
     {
       ssm.resetAll();
     }
-    System.gc();
   }
 
   @Override
@@ -1487,11 +1492,14 @@ public class Desktop extends jalview.jbgui.GDesktop
    */
   void showConsole(boolean selected)
   {
-    showConsole.setSelected(selected);
     // TODO: decide if we should update properties file
-    Cache.setProperty("SHOW_JAVA_CONSOLE",
-            Boolean.valueOf(selected).toString());
-    jconsole.setVisible(selected);
+    if (jconsole != null) // BH 2018
+    {
+      showConsole.setSelected(selected);
+      Cache.setProperty("SHOW_JAVA_CONSOLE",
+              Boolean.valueOf(selected).toString());
+      jconsole.setVisible(selected);
+    }
   }
 
   void reorderAssociatedWindows(boolean minimize, boolean close)
@@ -1592,6 +1600,8 @@ public class Desktop extends jalview.jbgui.GDesktop
   @Override
   public void saveState_actionPerformed(ActionEvent e)
   {
+    // TODO: JAL-3048 not needed for Jalview-JS
+
     JalviewFileChooser chooser = new JalviewFileChooser("jvp",
             "Jalview Project");
 
@@ -1665,6 +1675,8 @@ public class Desktop extends jalview.jbgui.GDesktop
   @Override
   public void loadState_actionPerformed(ActionEvent e)
   {
+    // TODO: JAL-3048 not needed for Jalview-JS
+
     JalviewFileChooser chooser = new JalviewFileChooser(
             Cache.getProperty("LAST_DIRECTORY"), new String[]
             { "jvp", "jar" },
@@ -1722,9 +1734,9 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   JPanel progressPanel;
 
-  ArrayList<JPanel> fileLoadingPanels = new ArrayList<JPanel>();
+  ArrayList<JPanel> fileLoadingPanels = new ArrayList<>();
 
-  public void startLoading(final String fileName)
+  public void startLoading(final Object fileName)
   {
     if (fileLoadingCount == 0)
     {
@@ -1814,7 +1826,7 @@ public class Desktop extends jalview.jbgui.GDesktop
       // TODO: verify that frames are recoverable when in headless mode
       return null;
     }
-    List<AlignmentPanel> aps = new ArrayList<AlignmentPanel>();
+    List<AlignmentPanel> aps = new ArrayList<>();
     AlignFrame[] frames = getAlignFrames();
     if (frames == null)
     {
@@ -1849,7 +1861,7 @@ public class Desktop extends jalview.jbgui.GDesktop
    */
   public static AlignmentViewport[] getViewports(String sequenceSetId)
   {
-    List<AlignmentViewport> viewp = new ArrayList<AlignmentViewport>();
+    List<AlignmentViewport> viewp = new ArrayList<>();
     if (desktop != null)
     {
       AlignFrame[] frames = Desktop.getAlignFrames();
@@ -1926,9 +1938,9 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   /**
    * Gather expanded views (separate AlignFrame's) with the same sequence set
-   * identifier back in to this frame as additional views, and close the
-   * expanded views. Note the expanded frames may themselves have multiple
-   * views. We take the lot.
+   * identifier back in to this frame as additional views, and close the expanded
+   * views. Note the expanded frames may themselves have multiple views. We take
+   * the lot.
    * 
    * @param source
    */
@@ -1972,6 +1984,8 @@ public class Desktop extends jalview.jbgui.GDesktop
   @Override
   public void vamsasImport_actionPerformed(ActionEvent e)
   {
+    // TODO: JAL-3048 not needed for Jalview-JS
+
     if (v_client == null)
     {
       // Load and try to start a session.
@@ -2248,6 +2262,8 @@ public class Desktop extends jalview.jbgui.GDesktop
   @Override
   public void vamsasSave_actionPerformed(ActionEvent e)
   {
+    // TODO: JAL-3048 not needed for Jalview-JS
+
     if (v_client != null)
     {
       // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
@@ -2351,7 +2367,8 @@ public class Desktop extends jalview.jbgui.GDesktop
       @Override
       public void run()
       {
-        if (Cache.getDefault("CHECKURLLINKS", true))
+        if (/** @j2sNative false && */ // BH 2018
+        Cache.getDefault("CHECKURLLINKS", true))
         {
           // check what the actual links are - if it's just the default don't
           // bother with the warning
@@ -2362,12 +2379,12 @@ public class Desktop extends jalview.jbgui.GDesktop
           // SEQUENCE_ID which is not the default EMBL_EBI link
           ListIterator<String> li = links.listIterator();
           boolean check = false;
-          List<JLabel> urls = new ArrayList<JLabel>();
+          List<JLabel> urls = new ArrayList<>();
           while (li.hasNext())
           {
             String link = li.next();
             if (link.contains(SEQUENCE_ID)
-                    && !link.equals(UrlConstants.DEFAULT_STRING))
+                    && !UrlConstants.isDefaultString(link))
             {
               check = true;
               int barPos = link.indexOf("|");
@@ -2424,14 +2441,163 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   /**
    * Proxy class for JDesktopPane which optionally displays the current memory
-   * usage and highlights the desktop area with a red bar if free memory runs
-   * low.
+   * usage and highlights the desktop area with a red bar if free memory runs low.
    * 
    * @author AMW
    */
-  public class MyDesktopPane extends JDesktopPane implements Runnable
+  public class MyDesktopPane extends JDesktopPane
+          implements Runnable, PropertyChangeListener
   {
 
+    public Object[] dialogData;
+
+    // @Override
+    @Override
+    public void propertyChange(PropertyChangeEvent event)
+    {
+      Object val = event.getNewValue();
+      String name = event.getPropertyName();
+      System.out.println(name);
+      switch (event.getSource().getClass().getName())
+      {
+      case "javax.swing.JOptionPane":
+        switch (name)
+        {
+        case "inputValue":
+          onDialogReturn(val);
+          return;
+        case "value":
+          if (val instanceof Integer)
+          {
+            onDialogReturn(((Integer) val).intValue());
+          }
+          else
+          {
+            onDialogReturn(val);
+          }
+          return;
+        }
+        break;
+      case "javax.swing.ColorChooserDialog":
+        switch (name)
+        {
+        case "SelectedColor":
+          onDialogReturn(val);
+          return;
+        }
+        break;
+      case "javax.swing.JFileChooser":
+        switch (name)
+        {
+        case "SelectedFile":
+          // in JavaScript, this File object will have a _bytes property,
+          // because the file data has already been loaded
+          onDialogReturn(new Object[] { (File) val });
+          return;
+        }
+        break;
+      }
+      System.out.println(event.getSource().getClass().getName() + " "
+              + event.getPropertyName() + ": " + event.getNewValue());
+    }
+
+    // JSCOmponent.DialogCaller interface
+    void onDialogReturn(Object value)
+    {
+      switch ((String) dialogData[0])
+      {
+      case "SelectedFile":
+      case "runnable":
+        dialogData[0] = value;
+        ((Runnable) dialogData[1]).run();
+        break;
+      case "label.select_feature_colour":
+        ((FeatureRenderer) dialogData[1]).processColorDialog((Color) value);
+        break;
+      }
+    }
+
+    // JSCOmponent.DialogCaller interface
+    void onDialogReturn(int value)
+    {
+      if (value != Math.floor(value))
+      {
+        // in JavaScript, this will be NaN, oddly enough
+        return;
+      }
+
+      switch ((String) dialogData[0])
+      {
+      case "runnable":
+        dialogData[0] = Integer.valueOf(value);
+        ((Runnable) dialogData[1]).run();
+        break;
+      case "label.input_alignment_from_url":
+        // reconstruct the parameter data
+        int reply = value;
+        AlignViewport viewport = (AlignViewport) dialogData[1];
+        JComboBox history = (JComboBox) dialogData[2];
+        // the rest of this is unchangaed
+        if (reply != JvOptionPane.OK_OPTION)
+        {
+          return;
+        }
+
+        String url = history.getSelectedItem().toString();
+
+        if (url.toLowerCase().endsWith(".jar"))
+        {
+          if (viewport != null)
+          {
+            new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
+                    FileFormat.Jalview);
+          }
+          else
+          {
+            new FileLoader().LoadFile(url, DataSourceType.URL,
+                    FileFormat.Jalview);
+          }
+        }
+        else
+        {
+          FileFormatI format = null;
+          try
+          {
+            format = new IdentifyFile().identify(url, DataSourceType.URL);
+          } catch (FileFormatException e)
+          {
+            // TODO revise error handling, distinguish between
+            // URL not found and response not valid
+          }
+
+          if (format == null)
+          {
+            JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+                    MessageManager.formatMessage("label.couldnt_locate",
+                            new Object[]
+                            { url }),
+                    MessageManager.getString("label.url_not_found"),
+                    JvOptionPane.WARNING_MESSAGE);
+
+            return;
+          }
+
+          if (viewport != null)
+          {
+            new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
+                    format);
+          }
+          else
+          {
+            new FileLoader().LoadFile(url, DataSourceType.URL, format);
+          }
+        }
+
+        break;
+      }
+
+    }
+
     private static final float ONE_MB = 1048576f;
 
     boolean showMemoryUsage = false;
@@ -2456,6 +2622,7 @@ public class Desktop extends jalview.jbgui.GDesktop
         Thread worker = new Thread(this);
         worker.start();
       }
+      repaint();
     }
 
     public boolean isShowMemoryUsage()
@@ -2520,15 +2687,6 @@ public class Desktop extends jalview.jbgui.GDesktop
   }
 
   /**
-   * fixes stacking order after a modal dialog to ensure windows that should be
-   * on top actually are
-   */
-  public void relayerWindows()
-  {
-
-  }
-
-  /**
    * Accessor method to quickly get all the AlignmentFrames loaded.
    * 
    * @return an array of AlignFrame, or null if none found
@@ -2547,7 +2705,7 @@ public class Desktop extends jalview.jbgui.GDesktop
     {
       return null;
     }
-    List<AlignFrame> avp = new ArrayList<AlignFrame>();
+    List<AlignFrame> avp = new ArrayList<>();
     // REVERSE ORDER
     for (int i = frames.length - 1; i > -1; i--)
     {
@@ -2592,7 +2750,7 @@ public class Desktop extends jalview.jbgui.GDesktop
     {
       return null;
     }
-    List<GStructureViewer> avp = new ArrayList<GStructureViewer>();
+    List<GStructureViewer> avp = new ArrayList<>();
     // REVERSE ORDER
     for (int i = frames.length - 1; i > -1; i--)
     {
@@ -2675,8 +2833,8 @@ public class Desktop extends jalview.jbgui.GDesktop
   }
 
   /**
-   * Bind Ctrl/Cmd-Q to Quit - for reset as Groovy Console takes over this
-   * binding when opened
+   * Bind Ctrl/Cmd-Q to Quit - for reset as Groovy Console takes over this binding
+   * when opened
    */
   protected void addQuitHandler()
   {
@@ -2735,8 +2893,8 @@ public class Desktop extends jalview.jbgui.GDesktop
   {
     if (progressBars == null)
     {
-      progressBars = new Hashtable<Long, JPanel>();
-      progressBarHandlers = new Hashtable<Long, IProgressIndicatorHandler>();
+      progressBars = new Hashtable<>();
+      progressBarHandlers = new Hashtable<>();
     }
 
     if (progressBars.get(new Long(id)) != null)
@@ -2809,9 +2967,8 @@ public class Desktop extends jalview.jbgui.GDesktop
   }
 
   /**
-   * This will return the first AlignFrame holding the given viewport instance.
-   * It will break if there are more than one AlignFrames viewing a particular
-   * av.
+   * This will return the first AlignFrame holding the given viewport instance. It
+   * will break if there are more than one AlignFrames viewing a particular av.
    * 
    * @param viewport
    * @return alignFrame for viewport
@@ -3177,8 +3334,8 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   /**
    * Explode the views in the given SplitFrame into separate SplitFrame windows.
-   * This respects (remembers) any previous 'exploded geometry' i.e. the size
-   * and location last time the view was expanded (if any). However it does not
+   * This respects (remembers) any previous 'exploded geometry' i.e. the size and
+   * location last time the view was expanded (if any). However it does not
    * remember the split pane divider location - this is set to match the
    * 'exploding' frame.
    * 
@@ -3329,13 +3486,87 @@ public class Desktop extends jalview.jbgui.GDesktop
     return groovyConsole;
   }
 
-  public static void transferFromDropTarget(List<String> files,
+  /**
+   * 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<Object> files,
           List<DataSourceType> protocols, DropTargetDropEvent evt,
           Transferable t) throws Exception
   {
 
+    // BH 2018 changed List<String> to List<Object> to allow for File from SwingJS
+
+    // DataFlavor[] flavors = t.getTransferDataFlavors();
+    // for (int i = 0; i < flavors.length; i++) {
+    // if (flavors[i].isFlavorJavaFileListType()) {
+    // evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
+    // List<File> list = (List<File>) t.getTransferData(flavors[i]);
+    // for (int j = 0; j < list.size(); j++) {
+    // File file = (File) list.get(j);
+    // byte[] data = getDroppedFileBytes(file);
+    // fileName.setText(file.getName() + " - " + data.length + " " +
+    // evt.getLocation());
+    // JTextArea target = (JTextArea) ((DropTarget) evt.getSource()).getComponent();
+    // target.setText(new String(data));
+    // }
+    // dtde.dropComplete(true);
+    // return;
+    // }
+    //
+
     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
@@ -3343,7 +3574,7 @@ public class Desktop extends jalview.jbgui.GDesktop
       for (Object file : (List) t
               .getTransferData(DataFlavor.javaFileListFlavor))
       {
-        files.add(((File) file).toString());
+        files.add(file);
         protocols.add(DataSourceType.FILE);
       }
     }
@@ -3363,63 +3594,116 @@ 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("#"))
+        while (protocols.size() < files.size())
         {
-          // the line is a comment (as per the RFC 2483)
-          continue;
+          Cache.log.debug("Adding missing FILE protocol for "
+                  + files.get(protocols.size()));
+          protocols.add(DataSourceType.FILE);
         }
-        java.net.URI uri = new java.net.URI(s);
-        if (uri.getScheme().toLowerCase().startsWith("http"))
+        for (java.util.StringTokenizer st = new java.util.StringTokenizer(
+                data, "\r\n"); st.hasMoreTokens();)
         {
-          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());
+          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).toString().toLowerCase();
+        if (protocols.get(f).equals(DataSourceType.FILE)
+                && (source.endsWith(".lnk") || source.endsWith(".url")
+                        || source.endsWith(".site")))
+        {
+          try
+          {
+            Object obj = files.get(f);
+            File lf = (obj instanceof File ? (File) obj
+                    : new File((String) obj));
+            // 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);
+          }
         }
       }
     }
@@ -3434,4 +3718,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;
+  }
 }