Merge branch 'Jalview-JS/develop' into merge_js_develop
[jalview.git] / src / jalview / gui / Desktop.java
index d11813d..88c94f6 100644 (file)
@@ -59,8 +59,11 @@ 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;
@@ -121,9 +124,9 @@ import jalview.util.BrowserLauncher;
 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;
 
@@ -163,6 +166,7 @@ public class Desktop extends GDesktop
 
   public static HashMap<String, FileWriter> savingFiles = new HashMap<String, FileWriter>();
 
+  @SuppressWarnings("deprecation")
   private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
 
   /**
@@ -176,6 +180,7 @@ public class Desktop extends GDesktop
    * @param listener
    * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.beans.PropertyChangeListener)
    */
+  @Deprecated
   public void addJalviewPropertyChangeListener(
           PropertyChangeListener listener)
   {
@@ -188,6 +193,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 +206,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)
   {
@@ -482,50 +489,53 @@ public class Desktop extends GDesktop
 
         experimentalFeatures.setSelected(showExperimental());
 
+        if (Jalview.isInteractive())
+        {
+          // disabled for SeqCanvasTest
+          checkURLLinks();
 
-        checkURLLinks();
-
-        // Spawn a thread that shows the splashscreen
+          // Spawn a thread that shows the splashscreen
 
-        SwingUtilities.invokeLater(new Runnable()
-        {
-          @Override
-          public void run()
+          SwingUtilities.invokeLater(new Runnable()
           {
-            new SplashScreen(true);
-          }
-        });
+            @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));
 
       this.addWindowListener(new WindowAdapter()
@@ -659,8 +669,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();
@@ -768,69 +778,82 @@ 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 that is allowed to be resized,
+//   * has a minimum size of 300px and might or might not be visible
+//   * 
+//   * @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
+//   */
+//  @Deprecated
+//  public static synchronized void addInternalFrame(
+//          final JInternalFrame frame, String title, boolean makeVisible,
+//          int w, int h)
+//  {
+//    // textbox, web services, sequenceFetcher, featureSettings
+//    getInstance().addFrame(frame, title, makeVisible, w, h,
+//            FRAME_ALLOW_RESIZE, FRAME_SET_MIN_SIZE_300);
+//  }
+//
+//  /**
+//   * Add an internal frame to the Jalview desktop that is visible, has a minimum
+//   * size of 300px, and may or may not be resizable
+//   * 
+//   * @param frame
+//   *          Frame to show
+//   * @param title
+//   *          Visible Title
+//   * @param w
+//   *          width
+//   * @param h
+//   *          height
+//   * @param resizable
+//   *          Allow resize
+//   */
+//  @Deprecated
+//  public static synchronized void addInternalFrame(
+//          final JInternalFrame frame, String title, int w, int h,
+//          boolean resizable)
+//  {
+//    // annotation, font, calculation, user-defined colors
+//    getInstance().addFrame(frame, title, FRAME_MAKE_VISIBLE, w, h,
+//            resizable, FRAME_SET_MIN_SIZE_300);
+//  }
 
   /**
-   * Add an internal frame to the Jalview desktop
+   * 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
    * @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
-   * 
-   * @param frame
-   *          Frame to show
-   * @param title
-   *          Visible Title
-   * @param w
-   *          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
@@ -852,40 +875,51 @@ 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
+    // 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.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);
+  }
 
-    openFrameCount++;
+  // 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,
       // hence,
@@ -894,6 +928,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));
+        
       }
     }
 
@@ -903,7 +941,6 @@ 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,
@@ -914,14 +951,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)
           {
@@ -1016,7 +1053,7 @@ public class Desktop extends GDesktop
     KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
             InputEvent.CTRL_DOWN_MASK);
     KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
-            ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx());
+            Platform.SHORTCUT_KEY_MASK);
 
     InputMap inputMap = frame
             .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
@@ -1311,8 +1348,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);
   }
 
   /*
@@ -1577,7 +1615,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();
@@ -1808,7 +1847,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[]
@@ -1961,7 +2000,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();
 
@@ -2328,7 +2367,7 @@ public class Desktop extends GDesktop
       return new AlignFrame[] { Jalview.getInstance().currentAlignFrame };
     }
 
-    JInternalFrame[] frames =  getDesktopPane().getAllFrames();
+    JInternalFrame[] frames = getDesktopPane().getAllFrames();
 
     if (frames == null)
     {
@@ -2467,12 +2506,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()
     {
@@ -2545,6 +2582,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)
@@ -2610,7 +2654,7 @@ public class Desktop extends GDesktop
    */
   public static AlignFrame getAlignFrameFor(AlignViewportI viewport)
   {
-    if ( getDesktopPane() != null)
+    if (getDesktopPane() != null)
     {
       AlignmentPanel[] aps = getAlignmentPanels(
               viewport.getSequenceSetId());
@@ -2664,10 +2708,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)
@@ -2678,31 +2725,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());
       }
     }
   }
@@ -2716,8 +2762,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))
@@ -2821,7 +2869,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"),
@@ -2924,7 +2972,7 @@ public class Desktop extends GDesktop
         {
           return;
         }
-       try
+        try
         {
           SwingUtilities.invokeAndWait(prompter);
         } catch (Exception q)