Merge commit 'alpha/update_2_12_for_2_11_2_series_merge^2' into HEAD
[jalview.git] / src / jalview / gui / Desktop.java
index 423c62a..f35a6a8 100644 (file)
  */
 package jalview.gui;
 
+import java.util.Locale;
 import java.awt.BorderLayout;
 import java.awt.Color;
 import java.awt.Dimension;
 import java.awt.FontMetrics;
 import java.awt.Graphics;
+import java.awt.Graphics2D;
 import java.awt.GridLayout;
 import java.awt.Point;
 import java.awt.Rectangle;
@@ -47,20 +49,26 @@ import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
 import java.awt.event.WindowAdapter;
 import java.awt.event.WindowEvent;
+import java.awt.geom.AffineTransform;
 import java.beans.PropertyChangeEvent;
 import java.beans.PropertyChangeListener;
 import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
+import java.lang.reflect.Field;
 import java.net.URL;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Hashtable;
 import java.util.List;
 import java.util.ListIterator;
 import java.util.Vector;
+import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.FutureTask;
 import java.util.concurrent.Semaphore;
 
 import javax.swing.AbstractAction;
@@ -118,12 +126,14 @@ import jalview.project.Jalview2XML;
 import jalview.structure.StructureSelectionManager;
 import jalview.urls.IdOrgSettings;
 import jalview.util.BrowserLauncher;
+import jalview.util.ChannelProperties;
 import jalview.util.ImageMaker.TYPE;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
 import jalview.util.ShortcutKeyMaskExWrapper;
 import jalview.util.UrlConstants;
 import jalview.viewmodel.AlignmentViewport;
+import jalview.ws.WSDiscovererI;
 import jalview.ws.params.ParamManager;
 import jalview.ws.utils.UrlDownloadClient;
 
@@ -140,12 +150,27 @@ public class Desktop extends GDesktop
         StructureSelectionManagerProvider, ApplicationSingletonI
 
 {
-  private static final String CITATION = "<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>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"
-          + "<br>Bioinformatics doi: 10.1093/bioinformatics/btp033";
+  private static final String CITATION;
+  static {
+    URL bg_logo_url = ChannelProperties.getImageURL("bg_logo." + String.valueOf(SplashScreen.logoSize));
+    URL uod_logo_url = ChannelProperties.getImageURL("uod_banner." + String.valueOf(SplashScreen.logoSize));
+    boolean logo = (bg_logo_url != null || uod_logo_url != null);
+    StringBuilder sb = new StringBuilder();
+    sb.append("<br><br>Development managed by The Barton Group, University of Dundee, Scotland, UK.");
+    if (logo) {
+      sb.append("<br>");
+    }
+    sb.append(bg_logo_url == null ? "" : "<img alt=\"Barton Group logo\" src=\"" + bg_logo_url.toString() + "\">");
+    sb.append(uod_logo_url == null ? ""
+        : "&nbsp;<img alt=\"University of Dundee shield\" src=\"" + uod_logo_url.toString() + "\">");
+    sb.append(
+        "<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");
+    sb.append("<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"
+        + "<br>Bioinformatics doi: 10.1093/bioinformatics/btp033");
+    CITATION = sb.toString();
+  }
 
   private static final String DEFAULT_AUTHORS = "The Jalview Authors (See AUTHORS file for current list)";
 
@@ -163,8 +188,10 @@ public class Desktop extends GDesktop
 
   public static HashMap<String, FileWriter> savingFiles = new HashMap<String, FileWriter>();
 
+  @SuppressWarnings("deprecation")
   private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
 
+  public static boolean nosplash = false;
   /**
    * news reader - null if it was never started.
    */
@@ -176,6 +203,7 @@ public class Desktop extends GDesktop
    * @param listener
    * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.beans.PropertyChangeListener)
    */
+  @Deprecated
   public void addJalviewPropertyChangeListener(
           PropertyChangeListener listener)
   {
@@ -188,6 +216,7 @@ public class Desktop extends GDesktop
    * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.lang.String,
    *      java.beans.PropertyChangeListener)
    */
+  @Deprecated
   public void addJalviewPropertyChangeListener(String propertyName,
           PropertyChangeListener listener)
   {
@@ -200,6 +229,7 @@ public class Desktop extends GDesktop
    * @see jalview.gui.JalviewChangeSupport#removeJalviewPropertyChangeListener(java.lang.String,
    *      java.beans.PropertyChangeListener)
    */
+  @Deprecated
   public void removeJalviewPropertyChangeListener(String propertyName,
           PropertyChangeListener listener)
   {
@@ -378,6 +408,7 @@ public class Desktop extends GDesktop
    */
   private Desktop()
   {
+    super();
     Cache.initLogger();
     try
     {
@@ -388,36 +419,66 @@ public class Desktop extends GDesktop
        */
 
       doConfigureStructurePrefs();
-      setTitle("Jalview " + Cache.getProperty("VERSION"));
-      /*
-      if (!Platform.isAMac())
-      {
-      // this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
-      }
-      else
-      {
-       this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
-      }
-      */
+    setTitle(ChannelProperties.getProperty("app_name") + " " + Cache.getProperty("VERSION"));
 
-      try
-      {
-        APQHandlers.setAPQHandlers(this);
-      } catch (Throwable t)
-      {
-        System.out.println("Error setting APQHandlers: " + t.toString());
-        // t.printStackTrace();
+    /**
+     * Set taskbar "grouped windows" name for linux desktops (works in GNOME and
+     * KDE). This uses sun.awt.X11.XToolkit.awtAppClassName which is not officially
+     * documented or guaranteed to exist, so we access it via reflection. There
+     * appear to be unfathomable criteria about what this string can contain, and it
+     * if doesn't meet those criteria then "java" (KDE) or "jalview-bin-Jalview"
+     * (GNOME) is used. "Jalview", "Jalview Develop" and "Jalview Test" seem okay,
+     * but "Jalview non-release" does not. The reflection access may generate a
+     * warning: WARNING: An illegal reflective access operation has occurred
+     * WARNING: Illegal reflective access by jalview.gui.Desktop () to field
+     * sun.awt.X11.XToolkit.awtAppClassName which I don't think can be avoided.
+     */
+    if (Platform.isLinux()) {
+      try {
+        Toolkit xToolkit = Toolkit.getDefaultToolkit();
+        Field[] declaredFields = xToolkit.getClass().getDeclaredFields();
+        Field awtAppClassNameField = null;
+
+        if (Arrays.stream(declaredFields).anyMatch(f -> f.getName().equals("awtAppClassName"))) {
+          awtAppClassNameField = xToolkit.getClass().getDeclaredField("awtAppClassName");
+        }
+
+        String title = ChannelProperties.getProperty("app_name");
+        if (awtAppClassNameField != null) {
+          awtAppClassNameField.setAccessible(true);
+          awtAppClassNameField.set(xToolkit, title);
+        } else {
+          Cache.log.debug("XToolkit: awtAppClassName not found");
+        }
+      } catch (Exception e) {
+        Cache.debug("Error setting awtAppClassName");
+        Cache.trace(Cache.getStackTraceString(e));
       }
+    }
 
-      addWindowListener(new WindowAdapter()
-      {
+    /**
+     * APQHandlers sets handlers for About, Preferences and Quit actions peculiar to
+     * macOS's application menu. APQHandlers will check to see if a handler is
+     * supported before setting it.
+     */
+    try {
+      APQHandlers.setAPQHandlers(this);
+    } catch (Exception e) {
+      System.out.println("Cannot set APQHandlers");
+      // e.printStackTrace();
+    } catch (Throwable t) {
+      Cache.warn("Error setting APQHandlers: " + t.toString());
+      Cache.trace(Cache.getStackTraceString(t));
+    }
+    setIconImages(ChannelProperties.getIconList());
 
-        @Override
-        public void windowClosing(WindowEvent ev)
-        {
-          quit();
-        }
-      });
+    addWindowListener(new WindowAdapter() {
+
+      @Override
+      public void windowClosing(WindowEvent ev) {
+        quit();
+      }
+    });
 
       boolean selmemusage = Cache.getDefault("SHOW_MEMUSAGE", false);
 
@@ -442,6 +503,7 @@ public class Desktop extends GDesktop
       getContentPane().add(desktopPane, BorderLayout.CENTER);
       desktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
 
+
       // This line prevents Windows Look&Feel resizing all new windows to
       // maximum
       // if previous window was maximised
@@ -476,53 +538,59 @@ public class Desktop extends GDesktop
         jconsole.setHeader(Cache.getVersionDetailsForConsole());
         showConsole(showjconsole);
 
-        showNews.setVisible(false);
+        showNews.setVisible(false); // not sure if we should only do this for interactive session?
 
         experimentalFeatures.setSelected(showExperimental());
 
         getIdentifiersOrgData();
 
-        checkURLLinks();
-
-        // Spawn a thread that shows the splashscreen
-
-        SwingUtilities.invokeLater(new Runnable()
-        {
-          @Override
-          public void run()
-          {
-            new SplashScreen(true);
+        if (Jalview.isInteractive())
+        {
+          // disabled for SeqCanvasTest
+          checkURLLinks();
+
+          // Spawn a thread that shows the splashscreen
+          if (!nosplash) {
+          SwingUtilities.invokeLater(new Runnable()
+           {
+             @Override
+             public void run()
+             {
+               new SplashScreen(true);
+             }
+           });
           }
-        });
 
-        // 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()
+          // Thread off a new instance of the file chooser - this reduces the
+          // time
+          // it
+          // takes to open it later on.
+          new Thread(new Runnable()
           {
-            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)
+            @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()
                   {
-                    Cache.log.debug("Firing service changed event for "
-                            + evt.getNewValue());
-                    JalviewServicesChanged(evt);
-                  }
-                });
+
+                    @Override
+                    public void propertyChange(PropertyChangeEvent evt)
+                    {
+                      Cache.log.debug("Firing service changed event for "
+                              + evt.getNewValue());
+                      JalviewServicesChanged(evt);
+                    }
+                  });
+        }
       }
 
       this.setDropTarget(new java.awt.dnd.DropTarget(desktopPane, this));
@@ -547,7 +615,6 @@ public class Desktop extends GDesktop
             showPasteMenu(evt.getX(), evt.getY());
           }
         }
-
         @Override
         public void mouseReleased(MouseEvent evt)
         {
@@ -581,34 +648,25 @@ public class Desktop extends GDesktop
   public void doConfigureStructurePrefs()
   {
     // configure services
-    StructureSelectionManager ssm = StructureSelectionManager
-            .getStructureSelectionManager(this);
-    if (Cache.getDefault(Preferences.ADD_SS_ANN, true))
-    {
-      ssm.setAddTempFacAnnot(
-              Cache.getDefault(Preferences.ADD_TEMPFACT_ANN, true));
-      ssm.setProcessSecondaryStructure(
-              Cache.getDefault(Preferences.STRUCT_FROM_PDB, true));
-      ssm.setSecStructServices(
-              Cache.getDefault(Preferences.USE_RNAVIEW, true));
-    }
-    else
-    {
+    StructureSelectionManager ssm = StructureSelectionManager.getStructureSelectionManager(this);
+    if (Cache.getDefault(Preferences.ADD_SS_ANN, true)) {
+      ssm.setAddTempFacAnnot(Cache.getDefault(Preferences.ADD_TEMPFACT_ANN, true));
+      ssm.setProcessSecondaryStructure(Cache.getDefault(Preferences.STRUCT_FROM_PDB, true));
+      // JAL-3915 - RNAView is no longer an option so this has no effect
+      ssm.setSecStructServices(Cache.getDefault(Preferences.USE_RNAVIEW, false));
+    } else {
       ssm.setAddTempFacAnnot(false);
       ssm.setProcessSecondaryStructure(false);
       ssm.setSecStructServices(false);
     }
   }
 
-  public void checkForNews()
-  {
+  public void checkForNews() {
     final Desktop me = this;
     // Thread off the news reader, in case there are connection problems.
-    new Thread(new Runnable()
-    {
+    new Thread(new Runnable() {
       @Override
-      public void run()
-      {
+      public void run() {
         Cache.log.debug("Starting news thread.");
         jvnews = new BlogReader(me);
         showNews.setVisible(true);
@@ -617,32 +675,25 @@ public class Desktop extends GDesktop
     }).start();
   }
 
-  public void getIdentifiersOrgData()
-  {
-    // Thread off the identifiers fetcher
-    new Thread(new Runnable()
-    {
-      @Override
-      public void run()
-      {
-        Cache.log.debug("Downloading data from identifiers.org");
-        try
-        {
-          UrlDownloadClient.download(IdOrgSettings.getUrl(),
-                  IdOrgSettings.getDownloadLocation());
-        } catch (IOException e)
-        {
-          Cache.log.debug("Exception downloading identifiers.org data"
-                  + e.getMessage());
+  public void getIdentifiersOrgData() {
+    if (Cache.getProperty("NOIDENTIFIERSSERVICE") == null) {
+      // Thread off the identifiers fetcher
+      new Thread(new Runnable() {
+        @Override
+        public void run() {
+          Cache.log.debug("Downloading data from identifiers.org");
+          try {
+            UrlDownloadClient.download(IdOrgSettings.getUrl(), IdOrgSettings.getDownloadLocation());
+          } catch (IOException e) {
+            Cache.log.debug("Exception downloading identifiers.org data" + e.getMessage());
+          }
         }
-      }
-    }).start();
-
+      }).start();
+    }
   }
 
   @Override
-  protected void showNews_actionPerformed(ActionEvent e)
-  {
+  protected void showNews_actionPerformed(ActionEvent e) {
     showNews(showNews.isSelected());
   }
 
@@ -658,8 +709,8 @@ public class Desktop extends GDesktop
         public void run()
         {
           long now = System.currentTimeMillis();
-          setProgressBar(
-                  MessageManager.getString("status.refreshing_news"), now);
+          setProgressBar(MessageManager.getString("status.refreshing_news"),
+                  now);
           jvnews.refreshNews();
           setProgressBar(null, now);
           jvnews.showNews();
@@ -684,39 +735,30 @@ public class Desktop extends GDesktop
     String y = Cache.getProperty(windowName + "SCREEN_Y");
     String width = Cache.getProperty(windowName + "SCREEN_WIDTH");
     String height = Cache.getProperty(windowName + "SCREEN_HEIGHT");
-    if ((x != null) && (y != null) && (width != null) && (height != null))
-    {
-      int ix = Integer.parseInt(x), iy = Integer.parseInt(y),
-              iw = Integer.parseInt(width), ih = Integer.parseInt(height);
-      if (Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
-      {
+    if ((x != null) && (y != null) && (width != null) && (height != null)) {
+      int ix = Integer.parseInt(x), iy = Integer.parseInt(y), iw = Integer.parseInt(width),
+          ih = Integer.parseInt(height);
+      if (Cache.getProperty("SCREENGEOMETRY_WIDTH") != null) {
         // attempt #1 - try to cope with change in screen geometry - this
         // version doesn't preserve original jv aspect ratio.
         // take ratio of current screen size vs original screen size.
-        double sw = ((1f * screenSize.width) / (1f * Integer
-                .parseInt(Cache.getProperty("SCREENGEOMETRY_WIDTH"))));
-        double sh = ((1f * screenSize.height) / (1f * Integer
-                .parseInt(Cache.getProperty("SCREENGEOMETRY_HEIGHT"))));
+        double sw = ((1f * screenSize.width) / (1f * Integer.parseInt(Cache.getProperty("SCREENGEOMETRY_WIDTH"))));
+        double sh = ((1f * screenSize.height) / (1f * Integer.parseInt(Cache.getProperty("SCREENGEOMETRY_HEIGHT"))));
         // rescale the bounds depending upon the current screen geometry.
         ix = (int) (ix * sw);
         iw = (int) (iw * sw);
         iy = (int) (iy * sh);
         ih = (int) (ih * sh);
-        while (ix >= screenSize.width)
-        {
-          Cache.log.debug(
-                  "Window geometry location recall error: shifting horizontal to within screenbounds.");
+        while (ix >= screenSize.width) {
+          Cache.log.debug("Window geometry location recall error: shifting horizontal to within screenbounds.");
           ix -= screenSize.width;
         }
-        while (iy >= screenSize.height)
-        {
-          Cache.log.debug(
-                  "Window geometry location recall error: shifting vertical to within screenbounds.");
+        while (iy >= screenSize.height) {
+          Cache.log.debug("Window geometry location recall error: shifting vertical to within screenbounds.");
           iy -= screenSize.height;
         }
-        Cache.log.debug(
-                "Got last known dimensions for " + windowName + ": x:" + ix
-                        + " y:" + iy + " width:" + iw + " height:" + ih);
+        Cache.log.debug("Got last known dimensions for " + windowName + ": x:" + ix + " y:" + iy + " width:" + iw
+            + " height:" + ih);
       }
       // return dimensions for new instance
       return new Rectangle(ix, iy, iw, ih);
@@ -767,48 +809,11 @@ public class Desktop extends GDesktop
     }
   }
 
-  /**
-   * Adds and opens the given frame to the desktop
-   * 
-   * @param frame
-   *          Frame to show
-   * @param title
-   *          Visible Title
-   * @param w
-   *          width
-   * @param h
-   *          height
-   */
-  public static synchronized void addInternalFrame(
-          final JInternalFrame frame, String title, int w, int h)
-  {
-    addInternalFrame(frame, title, true, w, h, true, false);
-  }
 
-  /**
-   * Add an internal frame to the Jalview desktop
-   * 
-   * @param frame
-   *          Frame to show
-   * @param title
-   *          Visible Title
-   * @param makeVisible
-   *          When true, display frame immediately, otherwise, caller must call
-   *          setVisible themselves.
-   * @param w
-   *          width
-   * @param h
-   *          height
-   */
-  public static synchronized void addInternalFrame(
-          final JInternalFrame frame, String title, boolean makeVisible,
-          int w, int h)
-  {
-    addInternalFrame(frame, title, makeVisible, w, h, true, false);
-  }
 
   /**
-   * Add an internal frame to the Jalview desktop and make it visible
+   * Adds and opens the given frame to the desktop that is visible, allowed to
+   * resize, and has a 300px minimum width.
    * 
    * @param frame
    *          Frame to show
@@ -818,18 +823,19 @@ public class Desktop extends GDesktop
    *          width
    * @param h
    *          height
-   * @param resizable
-   *          Allow resize
    */
   public static synchronized void addInternalFrame(
-          final JInternalFrame frame, String title, int w, int h,
-          boolean resizable)
+          final JInternalFrame frame, String title, int w, int h)
   {
-    addInternalFrame(frame, title, true, w, h, resizable, false);
+    // 58 classes
+    
+    addInternalFrame(frame, title, Desktop.FRAME_MAKE_VISIBLE, w, h, 
+            FRAME_ALLOW_RESIZE, FRAME_SET_MIN_SIZE_300);
   }
 
   /**
-   * Add an internal frame to the Jalview desktop
+   * Add an internal frame to the Jalview desktop that may optionally be
+   * visible, resizable, and allowed to be any size
    * 
    * @param frame
    *          Frame to show
@@ -851,39 +857,53 @@ public class Desktop extends GDesktop
           final JInternalFrame frame, String title, boolean makeVisible,
           int w, int h, boolean resizable, boolean ignoreMinSize)
   {
+    // 15 classes call this method directly.
     
-    getInstance().addFrame(frame, title, makeVisible, w, h, resizable, ignoreMinSize);
-  }
-  
-    private void addFrame(JInternalFrame frame, String title,
-          boolean makeVisible, int w, int h, boolean resizable,
-          boolean ignoreMinSize)
-  {
-      // TODO: allow callers to determine X and Y position of frame (eg. via
-      // bounds object).
-      // TODO: consider fixing method to update entries in the window submenu with
-      // the current window title
 
-      frame.setTitle(title);
-      if (frame.getWidth() < 1 || frame.getHeight() < 1)
+    // TODO: allow callers to determine X and Y position of frame (eg. via
+    // bounds object).
+    // TODO: consider fixing method to update entries in the window submenu with
+    // the current window title
+
+    frame.setTitle(title);
+    if (frame.getWidth() < 1 || frame.getHeight() < 1)
     {
       frame.setSize(w, h);
     }
-    // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
-    // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
-    // IF JALVIEW IS RUNNING HEADLESS
-    // ///////////////////////////////////////////////
-    if (Jalview.isHeadlessMode())
-    {
-      return;
-    }
+    if (getInstance() != null)
+      getInstance().addFrame(frame, makeVisible, resizable,
+            ignoreMinSize);
+  }
+
+  // These can now by put into a single int flag, if desired:
+  
+  public final static boolean FRAME_MAKE_VISIBLE = true;
+
+  public final static boolean FRAME_NOT_VISIBLE = false;
+
+  public final static boolean FRAME_ALLOW_RESIZE = true;
+
+  public final static boolean FRAME_NOT_RESIZABLE = false;
+
+  public final static boolean FRAME_ALLOW_ANY_SIZE = true;
+
+  public final static boolean FRAME_SET_MIN_SIZE_300 = false;
+  
+  private void addFrame(JInternalFrame frame,
+          boolean makeVisible, boolean resizable,
+          boolean ignoreMinSize)
+  {
 
     openFrameCount++;
 
+    
+    boolean isEmbedded = (Platform.getEmbeddedAttribute(frame, "id") != null);
+    boolean hasEmbeddedSize = (Platform.getDimIfEmbedded(frame, -1, -1) != null);
+    // Web page embedding allows us to ignore minimum size
+    ignoreMinSize |= hasEmbeddedSize;
+    
     if (!ignoreMinSize)
     {
-      frame.setMinimumSize(
-              new Dimension(DEFAULT_MIN_WIDTH, DEFAULT_MIN_HEIGHT));
 
       // Set default dimension for Alignment Frame window.
       // The Alignment Frame window could be added from a number of places,
@@ -893,6 +913,10 @@ public class Desktop extends GDesktop
       {
         frame.setMinimumSize(new Dimension(ALIGN_FRAME_DEFAULT_MIN_WIDTH,
                 ALIGN_FRAME_DEFAULT_MIN_HEIGHT));
+      } else {
+        frame.setMinimumSize(
+                new Dimension(DEFAULT_MIN_WIDTH, DEFAULT_MIN_HEIGHT));
+        
       }
     }
 
@@ -902,7 +926,7 @@ public class Desktop extends GDesktop
     frame.setMaximizable(resizable);
     frame.setIconifiable(resizable);
     frame.setOpaque(Platform.isJS());
-    boolean isEmbedded = (Platform.getDimIfEmbedded(frame, -1, -1) != null);
+
     if (!isEmbedded && frame.getX() < 1 && frame.getY() < 1)
     {
       frame.setLocation(xOffset * openFrameCount,
@@ -913,14 +937,14 @@ public class Desktop extends GDesktop
      * add an entry for the new frame in the Window menu 
      * (and remove it when the frame is closed)
      */
-    final JMenuItem menuItem = new JMenuItem(title);
+    final JMenuItem menuItem = new JMenuItem(frame.getTitle());
     frame.addInternalFrameListener(new InternalFrameAdapter()
     {
       @Override
       public void internalFrameActivated(InternalFrameEvent evt)
       {
         JInternalFrame itf = getDesktopPane().getSelectedFrame();
-       if (itf != null)
+        if (itf != null)
         {
           if (itf instanceof AlignFrame)
           {
@@ -1012,10 +1036,8 @@ public class Desktop extends GDesktop
     /*
      * 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,
-            ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx());
+    KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK);
+    KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx());
 
     InputMap inputMap = frame
             .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
@@ -1234,26 +1256,16 @@ public class Desktop extends GDesktop
       public void run()
       {
         @SuppressWarnings("unchecked")
-        String url = (history instanceof JTextField
-                ? ((JTextField) history).getText()
-                : ((JComboBox<String>) history).getSelectedItem()
-                        .toString());
-
-        if (url.toLowerCase().endsWith(".jar"))
-        {
-          if (viewport != null)
-          {
-            new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
-                    FileFormat.Jalview);
+        String url = (history instanceof JTextField ? ((JTextField) history).getText()
+            : ((JComboBox<String>) history).getEditor().getItem().toString().trim());
+
+        if (url.toLowerCase(Locale.ROOT).endsWith(".jar")) {
+          if (viewport != null) {
+            new FileLoader().LoadFile(viewport, url, DataSourceType.URL, FileFormat.Jalview);
+          } else {
+            new FileLoader().LoadFile(url, DataSourceType.URL, FileFormat.Jalview);
           }
-          else
-          {
-            new FileLoader().LoadFile(url, DataSourceType.URL,
-                    FileFormat.Jalview);
-          }
-        }
-        else
-        {
+        } else {
           FileFormatI format = null;
           try
           {
@@ -1310,8 +1322,9 @@ public class Desktop extends GDesktop
     CutAndPasteTransfer cap = new CutAndPasteTransfer();
     cap.setForInput(viewPanel);
     addInternalFrame(cap,
-            MessageManager.getString("label.cut_paste_alignmen_file"), true,
-            600, 500);
+            MessageManager.getString("label.cut_paste_alignmen_file"),
+            FRAME_MAKE_VISIBLE, 600, 500, FRAME_ALLOW_RESIZE,
+            FRAME_SET_MIN_SIZE_300);
   }
 
   /*
@@ -1392,39 +1405,28 @@ public class Desktop extends GDesktop
   public String getAboutMessage()
   {
     StringBuilder message = new StringBuilder(1024);
-    message.append("<h1><strong>Version: ")
-            .append(Cache.getProperty("VERSION")).append("</strong></h1>")
-            .append("<strong>Built: <em>")
-            .append(Cache.getDefault("BUILD_DATE", "unknown"))
-            .append("</em> from ").append(Cache.getBuildDetailsForSplash())
-            .append("</strong>");
+    message.append("<div style=\"font-family: sans-serif;\">").append("<h1><strong>Version: ")
+        .append(Cache.getProperty("VERSION")).append("</strong></h1>").append("<strong>Built: <em>")
+        .append(Cache.getDefault("BUILD_DATE", "unknown")).append("</em> from ")
+        .append(Cache.getBuildDetailsForSplash()).append("</strong>");
 
     String latestVersion = Cache.getDefault("LATEST_VERSION", "Checking");
-    if (latestVersion.equals("Checking"))
-    {
+    if (latestVersion.equals("Checking")) {
       // JBP removed this message for 2.11: May be reinstated in future version
       // message.append("<br>...Checking latest version...</br>");
-    }
-    else if (!latestVersion.equals(Cache.getProperty("VERSION")))
-    {
+    } else if (!latestVersion.equals(Cache.getProperty("VERSION"))) {
       boolean red = false;
-      if (Cache.getProperty("VERSION").toLowerCase()
-              .indexOf("automated build") == -1)
-      {
+      if (Cache.getProperty("VERSION").toLowerCase(Locale.ROOT).indexOf("automated build") == -1) {
         red = true;
         // Displayed when code version and jnlp version do not match and code
         // version is not a development build
         message.append("<div style=\"color: #FF0000;font-style: bold;\">");
       }
 
-      message.append("<br>!! Version ")
-              .append(Cache.getDefault("LATEST_VERSION", "..Checking.."))
-              .append(" is available for download from ")
-              .append(Cache.getDefault("www.jalview.org",
-                      "http://www.jalview.org"))
-              .append(" !!");
-      if (red)
-      {
+      message.append("<br>!! Version ").append(Cache.getDefault("LATEST_VERSION", "..Checking.."))
+          .append(" is available for download from ")
+          .append(Cache.getDefault("www.jalview.org", "https://www.jalview.org")).append(" !!");
+      if (red) {
         message.append("</div>");
       }
     }
@@ -1432,6 +1434,7 @@ public class Desktop extends GDesktop
     message.append(Cache.getDefault("AUTHORFNAMES", DEFAULT_AUTHORS));
     message.append(CITATION);
 
+    message.append("</div>");
     return message.toString();
   }
 
@@ -1439,15 +1442,11 @@ public class Desktop extends GDesktop
    * Action on requesting Help documentation
    */
   @Override
-  public void documentationMenuItem_actionPerformed()
-  {
-    try
-    {
-      if (Platform.isJS())
-      {
-        BrowserLauncher.openURL("http://www.jalview.org/help.html");
-      }
-      else
+  public void documentationMenuItem_actionPerformed() {
+    try {
+      if (Platform.isJS()) {
+        BrowserLauncher.openURL("https://www.jalview.org/help.html");
+      } else
       /**
        * Java only
        * 
@@ -1456,8 +1455,7 @@ public class Desktop extends GDesktop
       {
         Help.showHelpWindow();
       }
-    } catch (Exception ex)
-    {
+    } catch (Exception ex) {
       System.err.println("Error opening help: " + ex.getMessage());
     }
   }
@@ -1576,7 +1574,8 @@ public class Desktop extends GDesktop
       return;
     }
 
-    AlignmentViewport source = null, target = null;
+    AlignViewportI source = null;
+    AlignViewportI target = null;
     if (frames[0] instanceof AlignFrame)
     {
       source = ((AlignFrame) frames[0]).getCurrentView();
@@ -1652,9 +1651,8 @@ public class Desktop extends GDesktop
    *          DOCUMENT ME!
    */
   @Override
-  protected void preferences_actionPerformed(ActionEvent e)
-  {
-    new Preferences();
+  protected void preferences_actionPerformed(ActionEvent e) {
+    Preferences.openPreferences();
   }
 
   /**
@@ -1696,9 +1694,7 @@ public class Desktop extends GDesktop
         approveSave = true;
       }
     }
-
-    if (approveSave || autoSave)
-    {
+    if (approveSave || autoSave) {
       final Desktop me = this;
       final java.io.File chosenFile = projectFile;
       new Thread(new Runnable()
@@ -1807,7 +1803,7 @@ public class Desktop extends GDesktop
             {
               Cache.log.error(
                       "Problems whilst loading project from " + choice, ex);
-              JvOptionPane.showMessageDialog( getDesktopPane(),
+              JvOptionPane.showMessageDialog(getDesktopPane(),
                       MessageManager.formatMessage(
                               "label.error_whilst_loading_project_from",
                               new Object[]
@@ -1817,10 +1813,9 @@ public class Desktop extends GDesktop
                       JvOptionPane.WARNING_MESSAGE);
             }
           }
-        }).start();
+        }, "Project Loader").start();
       }
     });
-
     chooser.showOpenDialog(this);
   }
 
@@ -1960,7 +1955,7 @@ public class Desktop extends GDesktop
   public static AlignmentViewport[] getViewports(String sequenceSetId)
   {
     List<AlignmentViewport> viewp = new ArrayList<>();
-    if ( getDesktopPane() != null)
+    if (getDesktopPane() != null)
     {
       AlignFrame[] frames = getAlignFrames();
 
@@ -2312,6 +2307,8 @@ public class Desktop extends GDesktop
                   10, getHeight() - fm.getHeight());
         }
       }
+      // output debug scale message. Important for jalview.bin.HiDPISettingTest2
+      Desktop.debugScaleMessage(Desktop.getDesktop().getGraphics());
     }
   }
 
@@ -2327,7 +2324,7 @@ public class Desktop extends GDesktop
       return new AlignFrame[] { Jalview.getInstance().currentAlignFrame };
     }
 
-    JInternalFrame[] frames =  getDesktopPane().getAllFrames();
+    JInternalFrame[] frames = getDesktopPane().getAllFrames();
 
     if (frames == null)
     {
@@ -2466,12 +2463,10 @@ public class Desktop extends GDesktop
    */
   protected void addQuitHandler()
   {
-    getRootPane()
-            .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
-                    KeyStroke
-                            .getKeyStroke(KeyEvent.VK_Q,
-                                    jalview.util.ShortcutKeyMaskExWrapper
-                                            .getMenuShortcutKeyMaskEx()),
+
+    getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
+            .put(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
+                    Platform.SHORTCUT_KEY_MASK),
                     "Quit");
     getRootPane().getActionMap().put("Quit", new AbstractAction()
     {
@@ -2544,6 +2539,13 @@ public class Desktop extends GDesktop
       progressBars.put(Long.valueOf(id), addProgressPanel(message));
     }
   }
+  
+  @Override
+  public void removeProgressBar(long id)
+  {
+    //TODO
+    throw new UnsupportedOperationException("not implemented");
+  }
 
   /*
    * (non-Javadoc)
@@ -2609,7 +2611,7 @@ public class Desktop extends GDesktop
    */
   public static AlignFrame getAlignFrameFor(AlignViewportI viewport)
   {
-    if ( getDesktopPane() != null)
+    if (getDesktopPane() != null)
     {
       AlignmentPanel[] aps = getAlignmentPanels(
               viewport.getSequenceSetId());
@@ -2663,10 +2665,13 @@ public class Desktop extends GDesktop
 
   public void startServiceDiscovery(boolean blocking)
   {
-    boolean alive = true;
-    Thread t0 = null, t1 = null, t2 = null;
+    System.out.println("Starting service discovery");
+    var tasks = new ArrayList<Future<?>>();
     // JAL-940 - JALVIEW 1 services are now being EOLed as of JABA 2.1 release
-    if (true)
+
+    System.out.println("loading services");
+    
+    /** @j2sIgnore */
     {
       // todo: changesupport handlers need to be transferred
       if (discoverer == null)
@@ -2677,31 +2682,30 @@ public class Desktop extends GDesktop
       }
       // JAL-940 - disabled JWS1 service configuration - always start discoverer
       // until we phase out completely
-      (t0 = new Thread(discoverer)).start();
+      var f = new FutureTask<Void>(discoverer, null);
+      new Thread(f).start();
+      tasks.add(f);
     }
 
     if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
     {
-      t2 = jalview.ws.jws2.Jws2Discoverer.getInstance()
-              .startDiscoverer(changeSupport);
+      tasks.add(jalview.ws.jws2.Jws2Discoverer.getInstance().startDiscoverer());
     }
-    Thread t3 = null;
+    if (Cache.getDefault("SHOW_SLIVKA_SERVICES", true))
     {
-      // TODO: do rest service discovery
+      tasks.add(jalview.ws.slivkaws.SlivkaWSDiscoverer.getInstance().startDiscoverer());
     }
     if (blocking)
     {
-      while (alive)
-      {
+      for (Future<?> task : tasks) {
         try
         {
-          Thread.sleep(15);
+          // block until all discovery tasks are done
+          task.get();
         } catch (Exception e)
         {
+          e.printStackTrace();
         }
-        alive = (t1 != null && t1.isAlive()) || (t2 != null && t2.isAlive())
-                || (t3 != null && t3.isAlive())
-                || (t0 != null && t0.isAlive());
       }
     }
   }
@@ -2715,8 +2719,10 @@ public class Desktop extends GDesktop
   {
     if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
     {
-      final String ermsg = jalview.ws.jws2.Jws2Discoverer.getInstance()
-              .getErrorMessages();
+      final WSDiscovererI discoverer = jalview.ws.jws2.Jws2Discoverer
+          .getInstance();
+      final String ermsg = discoverer.getErrorMessages();
+      // CONFLICT:ALT:?     final String ermsg = jalview.ws.jws2.Jws2Discoverer.getInstance()
       if (ermsg != null)
       {
         if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
@@ -2820,7 +2826,7 @@ public class Desktop extends GDesktop
           jalview.util.BrowserLauncher.openURL(url);
         } catch (Exception ex)
         {
-          JvOptionPane.showInternalMessageDialog( getDesktopPane(),
+          JvOptionPane.showInternalMessageDialog(getDesktopPane(),
                   MessageManager
                           .getString("label.web_browser_not_found_unix"),
                   MessageManager.getString("label.web_browser_not_found"),
@@ -2923,7 +2929,7 @@ public class Desktop extends GDesktop
         {
           return;
         }
-       try
+        try
         {
           SwingUtilities.invokeAndWait(prompter);
         } catch (Exception q)
@@ -3402,4 +3408,29 @@ public class Desktop extends GDesktop
     return result;
   }
 
+  public static final String debugScaleMessage = "Desktop graphics transform scale=";
+
+  private static boolean debugScaleMessageDone = false;
+
+  public static void debugScaleMessage(Graphics g) {
+    if (debugScaleMessageDone) {
+      return;
+    }
+    // output used by tests to check HiDPI scaling settings in action
+    try {
+      Graphics2D gg = (Graphics2D) g;
+      if (gg != null) {
+        AffineTransform t = gg.getTransform();
+        double scaleX = t.getScaleX();
+        double scaleY = t.getScaleY();
+        Cache.debug(debugScaleMessage + scaleX + " (X)");
+        Cache.debug(debugScaleMessage + scaleY + " (Y)");
+        debugScaleMessageDone = true;
+      } else {
+        Cache.debug("Desktop graphics null");
+      }
+    } catch (Exception e) {
+      Cache.debug(Cache.getStackTraceString(e));
+    }
+  }
 }