JAL-3056 suppress menu options, and repoint Help, for JalviewJS
[jalview.git] / src / jalview / gui / Desktop.java
index b3a82bd..564f04a 100644 (file)
@@ -26,6 +26,7 @@ import jalview.api.AlignViewportI;
 import jalview.api.AlignmentViewPanel;
 import jalview.bin.Cache;
 import jalview.bin.Jalview;
+import jalview.gui.ImageExporter.ImageWriterI;
 import jalview.io.DataSourceType;
 import jalview.io.FileFormat;
 import jalview.io.FileFormatException;
@@ -40,10 +41,12 @@ import jalview.jbgui.GSplitFrame;
 import jalview.jbgui.GStructureViewer;
 import jalview.structure.StructureSelectionManager;
 import jalview.urls.IdOrgSettings;
-import jalview.util.ImageMaker;
+import jalview.util.BrowserLauncher;
+import jalview.util.ImageMaker.TYPE;
 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;
@@ -105,7 +108,6 @@ import javax.swing.JCheckBox;
 import javax.swing.JComboBox;
 import javax.swing.JComponent;
 import javax.swing.JDesktopPane;
-import javax.swing.JFileChooser;
 import javax.swing.JFrame;
 import javax.swing.JInternalFrame;
 import javax.swing.JLabel;
@@ -344,9 +346,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();
@@ -371,13 +372,12 @@ public class Desktop extends jalview.jbgui.GDesktop
 
     // This line prevents Windows Look&Feel resizing all new windows to maximum
     // if previous window was maximised
-    desktop.setDesktopManager(
-            new MyDesktopManager(
-                    (Platform.isWindows() ? new DefaultDesktopManager()
-                            : Platform.isAMac()
-                                    ? new AquaInternalFrameManager(
-                                            desktop.getDesktopManager())
-                                    : desktop.getDesktopManager())));
+    desktop.setDesktopManager(new MyDesktopManager(
+            (Platform.isWindows() ? new DefaultDesktopManager()
+                    : Platform.isAMac()
+                            ? new AquaInternalFrameManager(
+                                    desktop.getDesktopManager())
+                            : desktop.getDesktopManager())));
 
     Rectangle dims = getLastKnownDimensions("");
     if (dims != null)
@@ -543,10 +543,10 @@ public class Desktop extends jalview.jbgui.GDesktop
      * @j2sNative
      */
     {
-    final Desktop me = this;
-    // Thread off the news reader, in case there are connection problems.
-    addDialogThread(new Runnable()
-    {
+      final Desktop me = this;
+      // Thread off the news reader, in case there are connection problems.
+      addDialogThread(new Runnable()
+      {
         @Override
         public void run()
         {
@@ -556,7 +556,7 @@ public class Desktop extends jalview.jbgui.GDesktop
           showNews.setVisible(true);
           Cache.log.debug("Completed news thread.");
         }
-    });
+      });
     }
   }
 
@@ -983,8 +983,8 @@ public class Desktop extends jalview.jbgui.GDesktop
   }
 
   /**
-   * Add key bindings to a JInternalFrame so that Ctrl-W and Cmd-W will close
-   * the window
+   * Add key bindings to a JInternalFrame so that Ctrl-W and Cmd-W will close the
+   * window
    * 
    * @param frame
    */
@@ -1129,7 +1129,7 @@ public class Desktop extends jalview.jbgui.GDesktop
             MessageManager.getString("label.open_local_file"));
     chooser.setToolTipText(MessageManager.getString("action.open"));
 
-    chooser.setCallback(new Runnable()
+    chooser.response(new RunResponse(JalviewFileChooser.APPROVE_OPTION)
     {
 
       @Override
@@ -1160,14 +1160,7 @@ public class Desktop extends jalview.jbgui.GDesktop
         new FileLoader().LoadFile(viewport, selectedFile,
                 DataSourceType.FILE, format);
       }
-    });
-
-    int value = chooser.showOpenDialog(this);
-    if (value == JFileChooser.APPROVE_OPTION)
-    {
-      chooser.getCallback().run();
-    }
-
+    }).openDialog(this);
   }
 
   /**
@@ -1215,9 +1208,8 @@ public class Desktop extends jalview.jbgui.GDesktop
 
     String dialogOption = "label.input_alignment_from_url";
     desktop.dialogData = new Object[] { dialogOption, viewport, history };
-    desktop.onDialogReturn(
-            JvOptionPane.showInternalConfirmDialog(desktop, panel,
-            MessageManager.getString(dialogOption),
+    desktop.onDialogReturn(JvOptionPane.showInternalConfirmDialog(desktop,
+            panel, MessageManager.getString(dialogOption),
             JvOptionPane.OK_CANCEL_OPTION));
 
     // no code may follow this, as SwingJS will not block
@@ -1227,7 +1219,6 @@ public class Desktop extends jalview.jbgui.GDesktop
 
   }
 
-
   /**
    * Opens the CutAndPaste window for the user to paste an alignment in to
    * 
@@ -1387,19 +1378,24 @@ public class Desktop extends jalview.jbgui.GDesktop
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Action on requesting Help documentation
    */
   @Override
-  public void documentationMenuItem_actionPerformed(ActionEvent e)
+  public void documentationMenuItem_actionPerformed()
   {
     try
     {
-      Help.showHelpWindow();
+      if (Jalview.isJS())
+      {
+        BrowserLauncher.openURL("http://www.jalview.org/help.html");
+      }
+      else
+      {
+        Help.showHelpWindow();
+      }
     } catch (Exception ex)
     {
+      System.err.println("Error opening help: " + ex.getMessage());
     }
   }
 
@@ -1603,16 +1599,12 @@ public class Desktop extends jalview.jbgui.GDesktop
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Prompts the user to choose a file and then saves the Jalview state as a
+   * Jalview project file
    */
   @Override
-  public void saveState_actionPerformed(ActionEvent e)
+  public void saveState_actionPerformed()
   {
-    // TODO: JAL-3048 not needed for Jalview-JS
-
     JalviewFileChooser chooser = new JalviewFileChooser("jvp",
             "Jalview Project");
 
@@ -1678,16 +1670,11 @@ public class Desktop extends jalview.jbgui.GDesktop
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Prompts the user to choose a file and loads in as a Jalview project file
    */
   @Override
-  public void loadState_actionPerformed(ActionEvent e)
+  public void loadState_actionPerformed()
   {
-    // TODO: JAL-3048 not needed for Jalview-JS
-
     JalviewFileChooser chooser = new JalviewFileChooser(
             Cache.getProperty("LAST_DIRECTORY"), new String[]
             { "jvp", "jar" },
@@ -1949,9 +1936,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
    */
@@ -2452,8 +2439,7 @@ 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
    */
@@ -2467,6 +2453,7 @@ public class Desktop extends jalview.jbgui.GDesktop
     @Override
     public void propertyChange(PropertyChangeEvent event)
     {
+      // TODO this is obsolete with JAL-3048 - delete?
       Object val = event.getNewValue();
       String name = event.getPropertyName();
       System.out.println(name);
@@ -2490,14 +2477,6 @@ public class Desktop extends jalview.jbgui.GDesktop
           return;
         }
         break;
-      case "javax.swing.ColorChooserDialog":
-        switch (name)
-        {
-        case "SelectedColor":
-          onDialogReturn(val);
-          return;
-        }
-        break;
       case "javax.swing.JFileChooser":
         switch (name)
         {
@@ -2523,9 +2502,7 @@ public class Desktop extends jalview.jbgui.GDesktop
         dialogData[0] = value;
         ((Runnable) dialogData[1]).run();
         break;
-      case "label.select_feature_colour":
-        ((FeatureRenderer) dialogData[1]).processColorDialog((Color) value);
-        break;
+      default:
       }
     }
 
@@ -2587,7 +2564,7 @@ public class Desktop extends jalview.jbgui.GDesktop
             JvOptionPane.showInternalMessageDialog(Desktop.desktop,
                     MessageManager.formatMessage("label.couldnt_locate",
                             new Object[]
-                    { url }),
+                            { url }),
                     MessageManager.getString("label.url_not_found"),
                     JvOptionPane.WARNING_MESSAGE);
 
@@ -2698,7 +2675,6 @@ public class Desktop extends jalview.jbgui.GDesktop
     }
   }
 
-
   /**
    * Accessor method to quickly get all the AlignmentFrames loaded.
    * 
@@ -2846,8 +2822,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()
   {
@@ -2980,9 +2956,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
@@ -3322,34 +3297,45 @@ public class Desktop extends jalview.jbgui.GDesktop
     block.release();
   }
 
+  /**
+   * Outputs an image of the desktop to file in EPS format, after prompting the
+   * user for choice of Text or Lineart character rendering (unless a preference
+   * has been set). The file name is generated as
+   * 
+   * <pre>
+   * Jalview_snapshot_nnnnn.eps where nnnnn is the current timestamp in milliseconds
+   * </pre>
+   */
   @Override
   protected void snapShotWindow_actionPerformed(ActionEvent e)
   {
+    // currently the menu option to do this is not shown
     invalidate();
-    File of;
-    ImageMaker im = new jalview.util.ImageMaker(
-            this, ImageMaker.TYPE.EPS, "View of Desktop", getWidth(),
-            getHeight(), of = new File("Jalview_snapshot"
-                    + System.currentTimeMillis() + ".eps"),
-            "View of desktop", null, 0, false);
-    try
-    {
-      paintAll(im.getGraphics());
-      im.writeImage();
-    } catch (Exception q)
+
+    int width = getWidth();
+    int height = getHeight();
+    File of = new File(
+            "Jalview_snapshot_" + System.currentTimeMillis() + ".eps");
+    ImageWriterI writer = new ImageWriterI()
     {
-      Cache.log.error("Couldn't write snapshot to " + of.getAbsolutePath(),
-              q);
-      return;
-    }
-    Cache.log.info("Successfully written snapshot to file "
-            + of.getAbsolutePath());
+      @Override
+      public void exportImage(Graphics g) throws Exception
+      {
+        paintAll(g);
+        Cache.log.info("Successfully written snapshot to file "
+                + of.getAbsolutePath());
+      }
+    };
+    String title = "View of desktop";
+    ImageExporter exporter = new ImageExporter(writer, null, TYPE.EPS,
+            title);
+    exporter.doExport(of, this, width, height, title);
   }
 
   /**
    * 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.
    * 
@@ -3519,25 +3505,26 @@ public class Desktop extends jalview.jbgui.GDesktop
           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[] 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"), urlFlavour = null;
@@ -3555,15 +3542,15 @@ public class Desktop extends jalview.jbgui.GDesktop
 
       try
       {
-      java.net.URL url = (URL) t.getTransferData(urlFlavour);
+        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));
+        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
@@ -3574,7 +3561,7 @@ public class Desktop extends jalview.jbgui.GDesktop
                     "Please ignore plist error - occurs due to problem with java 8 on OSX");
           }
           ;
-      }
+        }
       } catch (Throwable ex)
       {
         Cache.log.debug("URL drop handler failed.", ex);
@@ -3698,9 +3685,11 @@ public class Desktop extends jalview.jbgui.GDesktop
                 && (source.endsWith(".lnk") || source.endsWith(".url")
                         || source.endsWith(".site")))
         {
-          try {
+          try
+          {
             Object obj = files.get(f);
-            File lf = (obj instanceof File ? (File) obj : new File((String) obj));
+            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);
@@ -3709,10 +3698,11 @@ public class Desktop extends jalview.jbgui.GDesktop
             files.set(f, fullname);
             Cache.log.debug("Parsed real filename " + fullname
                     + " to extract protocol: " + protocols.get(f));
-          }
-          catch (Exception ex)
+          } catch (Exception ex)
           {
-            Cache.log.error("Couldn't parse "+files.get(f)+" as a link file.",ex);
+            Cache.log.error(
+                    "Couldn't parse " + files.get(f) + " as a link file.",
+                    ex);
           }
         }
       }
@@ -3730,10 +3720,10 @@ public class Desktop extends jalview.jbgui.GDesktop
   }
 
   /**
-   * 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.
+   * 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