JAL-4059 Tidy getting the namespace, and save the namespace in the Jalview instance...
[jalview.git] / src / jalview / bin / Jalview.java
index dbc1d88..65ffcab 100755 (executable)
@@ -73,6 +73,8 @@ import jalview.bin.argparser.Arg.Opt;
 import jalview.bin.argparser.Arg.Type;
 import jalview.bin.argparser.ArgParser;
 import jalview.bin.argparser.BootstrapArgs;
+import jalview.bin.groovy.JalviewObject;
+import jalview.bin.groovy.JalviewObjectI;
 import jalview.ext.so.SequenceOntology;
 import jalview.gui.AlignFrame;
 import jalview.gui.Desktop;
@@ -98,6 +100,8 @@ import jalview.schemes.ColourSchemeI;
 import jalview.schemes.ColourSchemeProperty;
 import jalview.util.ChannelProperties;
 import jalview.util.HttpUtils;
+import jalview.util.IdUtils;
+import jalview.util.IdUtils.IdType;
 import jalview.util.LaunchUtils;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
@@ -118,7 +122,7 @@ import jalview.ws.jws2.Jws2Discoverer;
  * @author $author$
  * @version $Revision$
  */
-public class Jalview
+public class Jalview implements JalviewObjectI
 {
   static
   {
@@ -138,7 +142,7 @@ public class Jalview
 
   protected Commands cmds;
 
-  public static AlignFrame currentAlignFrame;
+  public AlignFrame currentAlignFrame = null;
 
   private ArgParser argparser = null;
 
@@ -204,7 +208,7 @@ public class Jalview
     public void addFetcher(final AlignFrame af,
             final Vector<String> dasSources)
     {
-      final long id = System.currentTimeMillis();
+      final long id = IdUtils.newId(IdType.PROGRESS);
       queued++;
       final FeatureFetcher us = this;
       new Thread(new Runnable()
@@ -305,6 +309,10 @@ public class Jalview
     {
       System.setSecurityManager(null);
     }
+    else
+    {
+      setJSNamespace();
+    }
 
     if (args == null || args.length == 0 || (args.length == 1
             && (args[0] == null || args[0].length() == 0)))
@@ -447,7 +455,7 @@ public class Jalview
       }
       else if (bootstrapArgs.contains(Arg.DEBUG))
       {
-        logLevel = "DEBUG";
+        logLevel = bootstrapArgs.getBoolean(Arg.DEBUG) ? "DEBUG" : "INFO";
       }
       if (logLevel == null && !(bootstrapProperties == null))
       {
@@ -551,9 +559,8 @@ public class Jalview
       if (aparser.contains("help") || aparser.contains("h"))
       {
         /*
-         * Now using new usage statement.
-        showUsage();
-        */
+         * Now using new usage statement. showUsage();
+         */
         Console.outPrintln(Arg.usage());
         Jalview.exit(null, ExitCode.OK);
       }
@@ -642,14 +649,12 @@ public class Jalview
     try
     {
       Console.initLogger();
-    } catch (
-
-    NoClassDefFoundError error)
+    } catch (NoClassDefFoundError error)
     {
       error.printStackTrace();
       String message = "\nEssential logging libraries not found."
               + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
-      Jalview.exit(message, ExitCode.OK);
+      Jalview.exit(message, ExitCode.NO_LOGGING);
     }
     desktop = null;
 
@@ -657,8 +662,8 @@ public class Jalview
       setLookAndFeel();
 
     /*
-     * configure 'full' SO model if preferences say to, else use the default (full SO)
-     * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
+     * configure 'full' SO model if preferences say to, else use the default (full
+     * SO) - as JS currently doesn't have OBO parsing, it must use 'Lite' version
      */
     boolean soDefault = !Platform.isJS();
     if (Cache.getDefault("USE_FULL_SO", soDefault))
@@ -837,38 +842,40 @@ public class Jalview
     }
 
     // Run Commands from cli
-    cmds = new Commands(argparser, headlessArg);
-    cmds.processArgs();
-    boolean commandsSuccess = cmds.argsWereParsed();
-
-    cliWarning();
-
-    if (commandsSuccess)
+    boolean commandsSuccess = false;
+    if (!(argparser.isMixedStyle() || argparser.isOldStyle()))
     {
-      if (headlessArg)
+      cmds = new Commands(argparser, headlessArg);
+      cmds.processArgs();
+      commandsSuccess = cmds.argsWereParsed();
+
+      if (commandsSuccess)
       {
-        if (argparser.getBoolean(Arg.NOQUIT))
+        if (headlessArg)
         {
-          Console.warn(
-                  "Completed " + Arg.HEADLESS.getName() + " commands, but "
-                          + Arg.NOQUIT + " is set so not quitting!");
-        }
-        else
-        {
-          Jalview.exit("Successfully completed commands in headless mode",
-                  ExitCode.OK);
+          if (argparser.getBoolean(Arg.NOQUIT))
+          {
+            Console.warn("Completed " + Arg.HEADLESS.getName()
+                    + " commands, but " + Arg.NOQUIT
+                    + " is set so not quitting!");
+          }
+          else
+          {
+            Jalview.exit("Successfully completed commands in headless mode",
+                    ExitCode.OK);
+          }
         }
+        Console.info("Successfully completed commands");
       }
-      Console.info("Successfully completed commands");
-    }
-    else
-    {
-      if (headlessArg)
+      else
       {
-        Jalview.exit("Error when running Commands in headless mode",
-                ExitCode.ERROR_RUNNING_COMMANDS);
+        if (headlessArg)
+        {
+          Jalview.exit("Error when running Commands in headless mode",
+                  ExitCode.ERROR_RUNNING_COMMANDS);
+        }
+        Console.warn("Error when running commands");
       }
-      Console.warn("Error when running commands");
     }
 
     // Check if JVM and compile version might cause problems and log if it
@@ -909,7 +916,7 @@ public class Jalview
         desktop.setProgressBar(
                 MessageManager
                         .getString("status.processing_commandline_args"),
-                progress = System.currentTimeMillis());
+                progress = IdUtils.newId(IdType.PROGRESS));
       }
       Console.outPrintln("CMD [-open " + file + "] executed successfully!");
 
@@ -1252,6 +1259,8 @@ public class Jalview
       }
       desktop.setInBatchMode(false);
     }
+
+    cliWarning();
   }
 
   private static void setLookAndFeel()
@@ -1556,13 +1565,10 @@ public class Jalview
             ChannelProperties.getProperty("app_name"));
     System.setProperty("apple.laf.useScreenMenuBar", "true");
     /*
-     * broken native LAFs on (ARM?) macbooks
-    set = setQuaquaLookAndFeel();
-    if ((!set) || !UIManager.getLookAndFeel().getClass().toString()
-            .toLowerCase(Locale.ROOT).contains("quaqua"))
-    {
-      set = setVaquaLookAndFeel();
-    }
+     * broken native LAFs on (ARM?) macbooks set = setQuaquaLookAndFeel(); if
+     * ((!set) || !UIManager.getLookAndFeel().getClass().toString()
+     * .toLowerCase(Locale.ROOT).contains("quaqua")) { set = setVaquaLookAndFeel();
+     * }
      */
     set = setFlatLookAndFeel();
     return set;
@@ -1581,49 +1587,50 @@ public class Jalview
   }
 
   /*
-  private static void showUsage()
-  {
-    jalview.bin.Console.outPrintln(
-            "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
-                    + "-nodisplay\tRun Jalview without User Interface.\n"
-                    + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
-                    + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
-                    + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
-                    + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
-                    + "-features FILE\tUse the given file to mark features on the alignment.\n"
-                    + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
-                    + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
-                    + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
-                    + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
-                    + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
-                    + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
-                    + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
-                    + "-json FILE\tCreate alignment file FILE in JSON format.\n"
-                    + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
-                    + "-png FILE\tCreate PNG image FILE from alignment.\n"
-                    + "-svg FILE\tCreate SVG image FILE from alignment.\n"
-                    + "-html FILE\tCreate HTML file from alignment.\n"
-                    + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
-                    + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
-                    + "-eps FILE\tCreate EPS file FILE from alignment.\n"
-                    + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
-                    + "-noquestionnaire\tTurn off questionnaire check.\n"
-                    + "-nonews\tTurn off check for Jalview news.\n"
-                    + "-nousagestats\tTurn off analytics tracking for this session.\n"
-                    + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
-                    // +
-                    // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
-                    // after all other properties files have been read\n\t
-                    // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
-                    // passed in correctly)"
-                    + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
-                    + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
-                    + "-groovy FILE\tExecute groovy script in FILE, after all other arguments have been processed (if FILE is the text 'STDIN' then the file will be read from STDIN)\n"
-                    + "-jvmmempc=PERCENT\tOnly available with standalone executable jar or jalview.bin.Launcher. Limit maximum heap size (memory) to PERCENT% of total physical memory detected. This defaults to 90 if total physical memory can be detected. See https://www.jalview.org/help/html/memory.html for more details.\n"
-                    + "-jvmmemmax=MAXMEMORY\tOnly available with standalone executable jar or jalview.bin.Launcher. Limit maximum heap size (memory) to MAXMEMORY. MAXMEMORY can be specified in bytes, kilobytes(k), megabytes(m), gigabytes(g) or if you're lucky enough, terabytes(t). This defaults to 32g if total physical memory can be detected, or to 8g if total physical memory cannot be detected. See https://www.jalview.org/help/html/memory.html for more details.\n"
-                    + "\n~Read documentation in Application or visit https://www.jalview.org for description of Features and Annotations file~\n\n");
-  }
-  */
+   * private static void showUsage() { jalview.bin.Console.outPrintln(
+   * "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n" +
+   * "-nodisplay\tRun Jalview without User Interface.\n" +
+   * "-props FILE\tUse the given Jalview properties file instead of users default.\n"
+   * + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n" +
+   * "-annotations FILE\tAdd precalculated annotations to the alignment.\n" +
+   * "-tree FILE\tLoad the given newick format tree file onto the alignment\n" +
+   * "-features FILE\tUse the given file to mark features on the alignment.\n" +
+   * "-fasta FILE\tCreate alignment file FILE in Fasta format.\n" +
+   * "-clustal FILE\tCreate alignment file FILE in Clustal format.\n" +
+   * "-pfam FILE\tCreate alignment file FILE in PFAM format.\n" +
+   * "-msf FILE\tCreate alignment file FILE in MSF format.\n" +
+   * "-pileup FILE\tCreate alignment file FILE in Pileup format\n" +
+   * "-pir FILE\tCreate alignment file FILE in PIR format.\n" +
+   * "-blc FILE\tCreate alignment file FILE in BLC format.\n" +
+   * "-json FILE\tCreate alignment file FILE in JSON format.\n" +
+   * "-jalview FILE\tCreate alignment file FILE in Jalview format.\n" +
+   * "-png FILE\tCreate PNG image FILE from alignment.\n" +
+   * "-svg FILE\tCreate SVG image FILE from alignment.\n" +
+   * "-html FILE\tCreate HTML file from alignment.\n" +
+   * "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n" +
+   * "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n" +
+   * "-eps FILE\tCreate EPS file FILE from alignment.\n" +
+   * "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
+   * + "-noquestionnaire\tTurn off questionnaire check.\n" +
+   * "-nonews\tTurn off check for Jalview news.\n" +
+   * "-nousagestats\tTurn off analytics tracking for this session.\n" +
+   * "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
+   * // + // "-setprop PROPERTY=VALUE\tSet the given Jalview property, // after
+   * all other properties files have been read\n\t // (quote the 'PROPERTY=VALUE'
+   * pair to ensure spaces are // passed in correctly)" +
+   * "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
+   * +
+   * "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
+   * +
+   * "-groovy FILE\tExecute groovy script in FILE, after all other arguments have been processed (if FILE is the text 'STDIN' then the file will be read from STDIN)\n"
+   * +
+   * "-jvmmempc=PERCENT\tOnly available with standalone executable jar or jalview.bin.Launcher. Limit maximum heap size (memory) to PERCENT% of total physical memory detected. This defaults to 90 if total physical memory can be detected. See https://www.jalview.org/help/html/memory.html for more details.\n"
+   * +
+   * "-jvmmemmax=MAXMEMORY\tOnly available with standalone executable jar or jalview.bin.Launcher. Limit maximum heap size (memory) to MAXMEMORY. MAXMEMORY can be specified in bytes, kilobytes(k), megabytes(m), gigabytes(g) or if you're lucky enough, terabytes(t). This defaults to 32g if total physical memory can be detected, or to 8g if total physical memory cannot be detected. See https://www.jalview.org/help/html/memory.html for more details.\n"
+   * +
+   * "\n~Read documentation in Application or visit https://www.jalview.org for description of Features and Annotations file~\n\n"
+   * ); }
+   */
 
   private static void startUsageStats(final Desktop desktop)
   {
@@ -1632,9 +1639,8 @@ public class Jalview
      */
     PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
             "USAGESTATS",
-            MessageManager.getString("prompt.plausible_analytics_title"),
-            MessageManager.getString("prompt.plausible_analytics"),
-            new Runnable()
+            MessageManager.getString("prompt.analytics_title"),
+            MessageManager.getString("prompt.analytics"), new Runnable()
             {
               @Override
               public void run()
@@ -1752,12 +1758,11 @@ public class Jalview
     }
     try
     {
+      JalviewObjectI j = new JalviewObject(this);
       Map<String, java.lang.Object> vbinding = new HashMap<>();
-      vbinding.put("Jalview", this);
-      if (af != null)
-      {
-        vbinding.put("currentAlFrame", af);
-      }
+      vbinding.put(JalviewObjectI.jalviewObjectName, j);
+      vbinding.put(JalviewObjectI.currentAlFrameName,
+              af != null ? af : getCurrentAlignFrame());
       Binding gbinding = new Binding(vbinding);
       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
       gse.run(sfile.toString(), gbinding);
@@ -1773,7 +1778,6 @@ public class Jalview
               .errPrintln("Exception Whilst trying to execute file " + sfile
                       + " as a groovy script.");
       e.printStackTrace(System.err);
-
     }
   }
 
@@ -1787,30 +1791,32 @@ public class Jalview
     return false;
   }
 
+  @Override
   public AlignFrame[] getAlignFrames()
   {
     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
-            : Desktop.getAlignFrames();
-
+            : Desktop.getDesktopAlignFrames();
   }
 
   /**
    * jalview.bin.Jalview.quit() will just run the non-GUI shutdownHook and exit
    */
+  @Override
   public void quit()
   {
     // System.exit will run the shutdownHook first
     Jalview.exit("Quitting now. Bye!", ExitCode.OK);
   }
 
-  public static AlignFrame getCurrentAlignFrame()
+  @Override
+  public AlignFrame getCurrentAlignFrame()
   {
-    return Jalview.currentAlignFrame;
+    return currentAlignFrame;
   }
 
-  public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
+  public void setCurrentAlignFrame(AlignFrame af)
   {
-    Jalview.currentAlignFrame = currentAlignFrame;
+    this.currentAlignFrame = af;
   }
 
   public Commands getCommands()
@@ -1862,7 +1868,7 @@ public class Jalview
     // only add new ones to the end of the list (to preserve ordinal values)
     OK, FILE_NOT_FOUND, FILE_NOT_READABLE, NO_FILES, INVALID_FORMAT,
     INVALID_ARGUMENT, INVALID_VALUE, MIXED_CLI_ARGUMENTS,
-    ERROR_RUNNING_COMMANDS;
+    ERROR_RUNNING_COMMANDS, NO_LOGGING, GROOVY_ERROR;
   }
 
   /******************************
@@ -2041,8 +2047,8 @@ public class Jalview
               j.getArgParser().getMixedExamples());
       String quit = MessageManager.getString("action.quit");
 
-      Desktop.instance.nonBlockingDialog(title, warning, quit,
-              JvOptionPane.WARNING_MESSAGE, false, true);
+      Desktop.instance.nonBlockingDialog(title, warning, null, quit,
+              JvOptionPane.WARNING_MESSAGE, false, false, true, 30000);
 
       Jalview.exit(
               "Exiting due to mixed old and new command line arguments.",
@@ -2060,14 +2066,14 @@ public class Jalview
     if (oldStyle)
     {
       String warning = MessageManager
-              .getString("warning.using_old_command_line_arguments")
-              + "https://www.jalview.org/help/html/features/commandline.html";
+              .getString("warning.using_old_command_line_arguments");
+      String url = "<a href=\"https://www.jalview.org/help/html/features/commandline.html\">https://www.jalview.org/help/html/features/commandline.html</a>";
       if (Desktop.instance != null)
       {
         String cont = MessageManager.getString("label.continue");
 
-        Desktop.instance.nonBlockingDialog(32, 2, title, warning, cont,
-                JvOptionPane.WARNING_MESSAGE, false, false);
+        Desktop.instance.nonBlockingDialog(title, warning, url, cont,
+                JvOptionPane.WARNING_MESSAGE, false, true, true, 30000);
       }
     }
     if (j.getCommands() != null && j.getCommands().getErrors().size() > 0)
@@ -2077,11 +2083,68 @@ public class Jalview
         String message = MessageManager
                 .getString("warning.the_following_errors");
         String ok = MessageManager.getString("action.ok");
-        Desktop.instance.nonBlockingDialog(60, 16, title,
-                message + "\n" + j.getCommands().errorsToString(), ok,
-                JvOptionPane.WARNING_MESSAGE, true, true);
+        int shortest = 60;
+        List<String> errors = j.getCommands().getErrors();
+        for (int i = 0; i < errors.size(); i++)
+        {
+          shortest = Math.min(shortest, errors.get(i).length());
+        }
+        Desktop.instance.nonBlockingDialog(
+                Math.max(message.length(), Math.min(60, shortest)),
+                Math.min(errors.size(), 20), title, message,
+                j.getCommands().errorsToString(), ok,
+                JvOptionPane.WARNING_MESSAGE, true, false, true, -1);
       }
     }
   }
 
+  /**
+   * Namespace (if set) by JalviewJS
+   */
+  private String JSNamespace = null;
+
+  private void setJSNamespace(String ns)
+  {
+    if (!Platform.isJS())
+    {
+      return;
+    }
+    Console.outPrintln("JSNamespace set to '" + ns + "'");
+    JSNamespace = ns;
+  }
+
+  public String getJSNamespace()
+  {
+    return JSNamespace;
+  }
+
+  public void setJSNamespace()
+  {
+    if (!Platform.isJS())
+    {
+      return;
+    }
+    String ns = null;
+    /**
+     * @j2sNative var namespace = J2S.thisApplet.__Info.namespace;
+     * 
+     *            if (namespace === undefined)
+     * 
+     *            {
+     * 
+     *            System.out.println("No namespace given");
+     * 
+     *            }
+     * 
+     *            else
+     * 
+     *            {
+     * 
+     *            ns = namespace;
+     * 
+     *            }
+     */
+    setJSNamespace(ns);
+  }
+
 }