JAL-3253 ApplicationSingletonProvider replaces Instance
[jalview.git] / src / jalview / bin / Jalview.java
index 9e3382a..402f9bf 100755 (executable)
  */
 package jalview.bin;
 
-import jalview.analysis.AlignmentSorter;
-import jalview.analysis.scoremodels.ScoreModels;
-import jalview.api.StructureSelectionManagerProvider;
-import jalview.ext.ensembl.EnsemblInfo;
+import jalview.api.AlignViewportI;
+import jalview.api.JalviewApp;
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
+import jalview.datamodel.PDBEntry;
+import jalview.datamodel.SequenceI;
 import jalview.ext.so.SequenceOntology;
-import jalview.fts.service.pdb.PDBFTSRestClient;
-import jalview.fts.service.uniprot.UniProtFTSRestClient;
 import jalview.gui.AlignFrame;
 import jalview.gui.Desktop;
+import jalview.gui.Preferences;
 import jalview.gui.PromptUserConfig;
-import jalview.httpserver.HttpServer;
 import jalview.io.AppletFormatAdapter;
 import jalview.io.BioJsHTMLOutput;
 import jalview.io.DataSourceType;
@@ -42,23 +41,12 @@ import jalview.io.HtmlSvgOutput;
 import jalview.io.IdentifyFile;
 import jalview.io.NewickFile;
 import jalview.io.gff.SequenceOntologyFactory;
-import jalview.io.gff.SequenceOntologyI;
-import jalview.rest.RestHandler;
 import jalview.schemes.ColourSchemeI;
 import jalview.schemes.ColourSchemeProperty;
-import jalview.structure.StructureImportSettings;
-import jalview.structure.StructureSelectionManager;
-import jalview.urls.IdOrgSettings;
 import jalview.util.MessageManager;
 import jalview.util.Platform;
-import jalview.ws.SequenceFetcher;
-import jalview.ws.jws1.Discoverer;
 import jalview.ws.jws2.Jws2Discoverer;
-import jalview.ws.jws2.jabaws2.Jws2InstanceFactory;
-import jalview.ws.rest.RestClient;
-import jalview.ws.sifts.SiftsSettings;
 
-import java.awt.Color;
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileOutputStream;
@@ -76,7 +64,6 @@ import java.security.PermissionCollection;
 import java.security.Permissions;
 import java.security.Policy;
 import java.util.HashMap;
-import java.util.IdentityHashMap;
 import java.util.Map;
 import java.util.Vector;
 import java.util.logging.ConsoleHandler;
@@ -104,56 +91,39 @@ import groovy.util.GroovyScriptEngine;
  * @author $author$
  * @version $Revision$
  */
-public class Jalview
+public class Jalview implements ApplicationSingletonI
 {
-  static
+
+  public static Jalview getInstance()
   {
-    Platform.getURLCommandArguments();
+    return (Jalview) ApplicationSingletonProvider
+            .getInstance(Jalview.class);
   }
 
-  private boolean headless;
-
-  public static boolean isHeadlessMode()
+  private Jalview()
   {
-    return getInstance().headless;
   }
 
-  /**
-   * singleton instance of this class in Java only
-   */
-
-  private static Jalview instance;
-
-  public static Jalview getInstance()
+  static
   {
-    Jalview j;
-    @SuppressWarnings("unused")
-    ThreadGroup g = Thread.currentThread().getThreadGroup();
-    /**
-     * @j2sNative j = g._jalviewInstance;
-     */
-    {
-      j = instance;
-    }
-    return j;
+    Platform.getURLCommandArguments();
   }
 
-  private static void setInstance(Jalview j)
+  private boolean headless;
+
+  public static boolean isHeadlessMode()
   {
-    @SuppressWarnings("unused")
-    ThreadGroup g = Thread.currentThread().getThreadGroup();
-    /**
-     * @j2sNative g._jalviewInstance = j;
-     */
-    {
-      instance = j;
-    }
+    return getInstance().headless;
   }
 
   private Desktop desktop;
 
   private AlignFrame currentAlignFrame;
 
+  public boolean isJavaAppletTag;
+
+  public String appletResourcePath;
+
   public static AlignFrame getCurrentAlignFrame()
   {
     return getInstance().currentAlignFrame;
@@ -260,7 +230,6 @@ public class Jalview
   public static void main(String[] args)
   {
     // setLogging(); // BH - for event debugging in JavaScript
-    setInstance(new Jalview());
     getInstance().doMain(args);
   }
 
@@ -325,19 +294,32 @@ public class Jalview
 
     String usrPropsFile = aparser.getValue(ArgsParser.PROPS);
     Cache.loadProperties(usrPropsFile);
-    if (usrPropsFile != null)
+    if (Platform.isJS())
     {
+      isJavaAppletTag = aparser.isApplet();
+      if (isJavaAppletTag)
+      {
+        Preferences.setAppletDefaults();
+        Cache.loadProperties(usrPropsFile); // again, because we
+        // might be changing defaults here?
+      }
       System.out.println(
-              "CMD [-props " + usrPropsFile + "] executed successfully!");
+              "<Applet> found: " + aparser.getValue("Info.j2sAppletID"));
+      appletResourcePath = aparser.getValue("Info.resourcePath");
     }
-
-    if (!Platform.isJS())
+    else
     /**
      * Java only
      * 
      * @j2sIgnore
      */
     {
+      if (usrPropsFile != null)
+      {
+        System.out.println(
+                "CMD [-props " + usrPropsFile + "] executed successfully!");
+      }
+
       if (aparser.contains("help") || aparser.contains("h"))
       {
         showUsage();
@@ -358,7 +340,7 @@ public class Jalview
       {
         try
         {
-          Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
+          Jws2Discoverer.getInstance().setPreferredUrl(jabawsUrl);
           System.out.println(
                   "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
         } catch (MalformedURLException e)
@@ -455,12 +437,12 @@ public class Jalview
      */
     if (Cache.getDefault("USE_FULL_SO", false))
     {
-      SequenceOntologyFactory.setInstance(new SequenceOntology());
+      SequenceOntologyFactory.setSequenceOntology(new SequenceOntology());
     }
 
     if (!headless)
     {
-      desktop = new Desktop();
+      desktop = Desktop.getInstance();
       desktop.setInBatchMode(true); // indicate we are starting up
       desktop.setVisible(true);
 
@@ -780,94 +762,103 @@ public class Jalview
                   + "] executed successfully!");
           groovyscript = null;
         }
-        String imageName = "unnamed.png";
-        while (aparser.getSize() > 1)
+
+        if (isJavaAppletTag)
+        {
+          loadAppletParams(aparser, af);
+        }
+        else
         {
-          // PNG filename
-          // SVG filename
-          // HTML filename
-          // biojsmsa filename
-          String outputFormat = aparser.nextValue();
-          file = aparser.nextValue();
-
-          if (outputFormat.equalsIgnoreCase("png"))
-          {
-            af.createPNG(new File(file));
-            imageName = (new File(file)).getName();
-            System.out.println("Creating PNG image: " + file);
-            continue;
-          }
-          else if (outputFormat.equalsIgnoreCase("svg"))
-          {
-            File imageFile = new File(file);
-            imageName = imageFile.getName();
-            af.createSVG(imageFile);
-            System.out.println("Creating SVG image: " + file);
-            continue;
-          }
-          else if (outputFormat.equalsIgnoreCase("html"))
-          {
-            File imageFile = new File(file);
-            imageName = imageFile.getName();
-            HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
-            htmlSVG.exportHTML(file);
 
-            System.out.println("Creating HTML image: " + file);
-            continue;
-          }
-          else if (outputFormat.equalsIgnoreCase("biojsmsa"))
+          String imageName = "unnamed.png";
+          while (aparser.getSize() > 1)
           {
-            if (file == null)
+            // PNG filename
+            // SVG filename
+            // HTML filename
+            // biojsmsa filename
+            String outputFormat = aparser.nextValue();
+            file = aparser.nextValue();
+
+            if (outputFormat.equalsIgnoreCase("png"))
             {
-              System.err.println("The output html file must not be null");
-              return;
+              af.createPNG(new File(file));
+              imageName = (new File(file)).getName();
+              System.out.println("Creating PNG image: " + file);
+              continue;
             }
-            try
+            else if (outputFormat.equalsIgnoreCase("svg"))
             {
-              BioJsHTMLOutput.refreshVersionInfo(
-                      BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
-            } catch (URISyntaxException e)
+              File imageFile = new File(file);
+              imageName = imageFile.getName();
+              af.createSVG(imageFile);
+              System.out.println("Creating SVG image: " + file);
+              continue;
+            }
+            else if (outputFormat.equalsIgnoreCase("html"))
             {
-              e.printStackTrace();
+              File imageFile = new File(file);
+              imageName = imageFile.getName();
+              HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
+              htmlSVG.exportHTML(file);
+
+              System.out.println("Creating HTML image: " + file);
+              continue;
+            }
+            else if (outputFormat.equalsIgnoreCase("biojsmsa"))
+            {
+              if (file == null)
+              {
+                System.err.println("The output html file must not be null");
+                return;
+              }
+              try
+              {
+                BioJsHTMLOutput.refreshVersionInfo(
+                        BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
+              } catch (URISyntaxException e)
+              {
+                e.printStackTrace();
+              }
+              BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
+              bjs.exportHTML(file);
+              System.out.println(
+                      "Creating BioJS MSA Viwer HTML file: " + file);
+              continue;
+            }
+            else if (outputFormat.equalsIgnoreCase("imgMap"))
+            {
+              af.createImageMap(new File(file), imageName);
+              System.out.println("Creating image map: " + file);
+              continue;
+            }
+            else if (outputFormat.equalsIgnoreCase("eps"))
+            {
+              File outputFile = new File(file);
+              System.out.println(
+                      "Creating EPS file: " + outputFile.getAbsolutePath());
+              af.createEPS(outputFile);
+              continue;
+            }
+
+            af.saveAlignment(file, format);
+            if (af.isSaveAlignmentSuccessful())
+            {
+              System.out.println("Written alignment in " + format
+                      + " format to " + file);
+            }
+            else
+            {
+              System.out.println("Error writing file " + file + " in "
+                      + format + " format!!");
             }
-            BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
-            bjs.exportHTML(file);
-            System.out
-                    .println("Creating BioJS MSA Viwer HTML file: " + file);
-            continue;
-          }
-          else if (outputFormat.equalsIgnoreCase("imgMap"))
-          {
-            af.createImageMap(new File(file), imageName);
-            System.out.println("Creating image map: " + file);
-            continue;
-          }
-          else if (outputFormat.equalsIgnoreCase("eps"))
-          {
-            File outputFile = new File(file);
-            System.out.println(
-                    "Creating EPS file: " + outputFile.getAbsolutePath());
-            af.createEPS(outputFile);
-            continue;
-          }
 
-          af.saveAlignment(file, format);
-          if (af.isSaveAlignmentSuccessful())
-          {
-            System.out.println("Written alignment in " + format
-                    + " format to " + file);
           }
-          else
+
+          while (aparser.getSize() > 0)
           {
-            System.out.println("Error writing file " + file + " in "
-                    + format + " format!!");
+            System.out.println("Unknown arg: " + aparser.nextValue());
           }
-
-        }
-
-        while (aparser.getSize() > 0)
-        {
-          System.out.println("Unknown arg: " + aparser.nextValue());
         }
       }
     }
@@ -1169,46 +1160,132 @@ public class Jalview
     }
   }
 
-  // singleton instances
+  /**
+   * Get the SwingJS applet ID and combine that with the frameType
+   * 
+   * @param frameType
+   *          "alignment", "desktop", etc., or null
+   * @return
+   */
+  public static String getAppID(String frameType)
+  {
+    String id = Cache.getProperty("Info.j2sAppletID");
+    if (id == null)
+    {
+      id = "jalview";
+    }
+    return id + (frameType == null ? "" : "-" + frameType);
+  }
 
-  public Cache cache;
+  private void loadAppletParams(ArgsParser aparser, AlignFrame af)
+  {
+    Jalview me = this;
+    JalviewApp app = new JalviewApp()
+    {
 
-  public AlignmentSorter alignmentSorter;
 
-  public EnsemblInfo ensemblInfo;
+      @Override
+      public String getParameter(String name)
+      {
+        return aparser.getAppletValue(name, null);
+      }
 
-  public HttpServer httpServer;
+      @Override
+      public boolean getDefaultParameter(String name, boolean def)
+      {
+        String stn;
+        return ((stn = getParameter(name)) == null ? def
+                : "true".equalsIgnoreCase(stn));
+      }
 
-  public IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager> structureSelections;
+      @Override
+      public URL getDocumentBase()
+      {
+        return Platform.getDocumentBase();
+      }
+
+      @Override
+      public URL getCodeBase()
+      {
+        return Platform.getCodeBase();
+      }
+
+      @Override
+      public AlignViewportI getViewport()
+      {
+        return Jalview.getCurrentAlignFrame().getViewport();
+      }
+
+      @Override
+      public boolean loadScoreFile(String sScoreFile) throws IOException
+      {
+        Jalview.getCurrentAlignFrame().loadJalviewDataFile(sScoreFile, null,
+                null, null);
+        return true;
+      }
+
+      @Override
+      public boolean parseFeaturesFile(String filename,
+              DataSourceType protocol)
+      {
+        return af.parseFeaturesFile(filename, protocol);
+      }
+
+      @Override
+      public void loadTree(NewickFile fin, String treeFile)
+              throws IOException
+      {
+        // n/a -- already done
+      }
 
-  public PDBFTSRestClient pdbFTSRestClient;
+      @Override
+      public void setAlignPdbStructures(boolean defaultParameter)
+      {
+        // TODO Auto-generated method stub
 
-  public RestHandler restHandler;
+      }
 
-  public ScoreModels scoreModels;
+      @Override
+      public void newStructureView(PDBEntry pdb, SequenceI[] seqs,
+              String[] chains, DataSourceType protocol)
+      {
+        // TODO Auto-generated method stub
 
-  public SequenceFetcher sequenceFetcher;
+      }
 
-  public SequenceOntologyI sequenceOntology;
+      @Override
+      public void alignedStructureView(PDBEntry[] pdb, SequenceI[][] seqs,
+              String[][] chains, String[] protocols)
+      {
+        // TODO Auto-generated method stub
 
-  public UniProtFTSRestClient uniprotFTSRestClient;
+      }
 
-  public StructureSelectionManager nullProvider;
+      @Override
+      public void updateForLoader()
+      {
+        // TODO Auto-generated method stub
 
-  public Color[] rnaHelices = null;
+      }
 
-  public StructureImportSettings structureImportSettings;
+      @Override
+      public void setFeatureGroupState(String[] groups, boolean state)
+      {
+        // TODO Auto-generated method stub
 
-  public IdOrgSettings idOrgSettings;
+      }
 
-  public SiftsSettings siftsSettings;
+      @Override
+      public void newFeatureSettings()
+      {
+        // TODO Auto-generated method stub
 
-  public RestClient restClient;
+      }
 
-  public Jws2Discoverer j2s2discoverer;
+    };
 
-  public Jws2InstanceFactory jws2InstanceFactory;
+    new JalviewAppLoader(true).load(app);
 
-  public Discoverer discoverer;
+  }
 
 }