JAL-3949 Complete new abstracted logging framework in jalview.log. Updated log calls...
[jalview.git] / src / jalview / ext / jmol / JalviewJmolBinding.java
index 08ea052..f133f20 100644 (file)
@@ -31,6 +31,8 @@ import java.util.Map;
 import java.util.StringTokenizer;
 import java.util.Vector;
 
+import javax.swing.SwingUtilities;
+
 import org.jmol.adapter.smarter.SmarterJmolAdapter;
 import org.jmol.api.JmolAppConsoleInterface;
 import org.jmol.api.JmolSelectionListener;
@@ -39,9 +41,14 @@ import org.jmol.api.JmolViewer;
 import org.jmol.c.CBK;
 import org.jmol.viewer.Viewer;
 
+import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureRenderer;
+import jalview.api.FeatureSettingsModelI;
+import jalview.api.SequenceRenderer;
+import jalview.bin.Cache;
 import jalview.datamodel.PDBEntry;
 import jalview.datamodel.SequenceI;
+import jalview.gui.AppJmol;
 import jalview.gui.IProgressIndicator;
 import jalview.gui.StructureViewer.ViewerType;
 import jalview.io.DataSourceType;
@@ -51,6 +58,8 @@ import jalview.structure.StructureCommand;
 import jalview.structure.StructureCommandI;
 import jalview.structure.StructureSelectionManager;
 import jalview.structures.models.AAStructureBindingModel;
+import jalview.ws.dbsources.Pdb;
+import javajs.util.BS;
 
 public abstract class JalviewJmolBinding extends AAStructureBindingModel
         implements JmolStatusListener, JmolSelectionListener,
@@ -82,8 +91,8 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
     setStructureCommands(new JmolCommands());
     /*
      * viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter(),
-     * "jalviewJmol", ap.av.applet .getDocumentBase(),
-     * ap.av.applet.getCodeBase(), "", this);
+     * "jalviewJmol", ap.av.applet .getDocumentBase(), ap.av.applet.getCodeBase(),
+     * "", this);
      * 
      * jmolpopup = JmolPopup.newJmolPopup(viewer, true, "Jmol", true);
      */
@@ -111,14 +120,13 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
     return getViewerTitle("Jmol", true);
   }
 
-  public void closeViewer()
+  private String jmolScript(String script)
   {
-    // remove listeners for all structures in viewer
-    getSsm().removeStructureViewerListener(this, this.getStructureFiles());
-    jmolViewer.dispose();
-    lastCommand = null;
-    jmolViewer = null;
-    releaseUIResources();
+    Cache.debug(">>Jmol>> " + script);
+    String s = jmolViewer.evalStringQuiet(script); // scriptWait(script); BH
+    Cache.debug("<<Jmol<< " + s);
+
+    return s;
   }
 
   @Override
@@ -133,7 +141,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
     jmolHistory(false);
     if (lastCommand == null || !lastCommand.equals(cmd))
     {
-      jmolViewer.evalStringQuiet(cmd + "\n");
+      jmolScript(cmd + "\n");
     }
     jmolHistory(true);
     lastCommand = cmd;
@@ -201,8 +209,8 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
       for (int i = 0; i < modelCount; ++i)
       {
         /*
-         * defensive check for null as getModelFileName can return null
-         * even when model count ms.mc is > 0
+         * defensive check for null as getModelFileName can return null even when model
+         * count ms.mc is > 0
          */
         filePath = jmolViewer.ms.getModelFileName(i);
         if (filePath != null && !mset.contains(filePath))
@@ -210,7 +218,10 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
           mset.add(filePath);
         }
       }
-      modelFileNames = mset.toArray(new String[mset.size()]);
+      if (!mset.isEmpty())
+      {
+        modelFileNames = mset.toArray(new String[mset.size()]);
+      }
     }
 
     return modelFileNames;
@@ -245,7 +256,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
     {
       if (resetLastRes.length() > 0)
       {
-        jmolViewer.evalStringQuiet(resetLastRes.toString());
+        jmolScript(resetLastRes.toString());
         resetLastRes.setLength(0);
       }
       for (AtomSpec atom : atoms)
@@ -284,7 +295,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
     resetLastRes.append(selection).append(";wireframe 0;").append(selection)
             .append(" and not hetero; spacefill 0;");
 
-    jmolViewer.evalStringQuiet(cmd.toString());
+    jmolScript(cmd.toString());
     jmolHistory(true);
   }
 
@@ -292,7 +303,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
 
   private void jmolHistory(boolean enable)
   {
-    jmolViewer.evalStringQuiet("History " + ((debug || enable) ? "on" : "off"));
+    jmolScript("History " + ((debug || enable) ? "on" : "off"));
   }
 
   public void loadInline(String string)
@@ -392,8 +403,8 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
     }
 
     /*
-     * highlight position on alignment(s); if some text is returned, 
-     * show this as a second line on the structure hover tooltip
+     * highlight position on alignment(s); if some text is returned, show this as a
+     * second line on the structure hover tooltip
      */
     String label = getSsm().mouseOverStructure(pdbResNum, chainId,
             pdbfilename);
@@ -429,8 +440,8 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
 
   /*
    * { if (history != null && strStatus != null &&
-   * !strStatus.equals("Script completed")) { history.append("\n" + strStatus);
-   * } }
+   * !strStatus.equals("Script completed")) { history.append("\n" + strStatus); }
+   * }
    */
 
   public void notifyAtomPicked(int atomIndex, String strInfo,
@@ -438,7 +449,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
   {
     /**
      * this implements the toggle label behaviour copied from the original
-     * structure viewer, MCView
+     * structure viewer, mc_view
      */
     if (strData != null)
     {
@@ -469,7 +480,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
 
     if (!atomsPicked.contains(picked))
     {
-      jmolViewer.evalStringQuiet("select " + picked + ";label %n %r:%c");
+      jmolScript("select " + picked + ";label %n %r:%c");
       atomsPicked.addElement(picked);
     }
     else
@@ -491,6 +502,28 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
   @Override
   public void notifyCallback(CBK type, Object[] data)
   {
+    /*
+     * ensure processed in AWT thread to avoid risk of deadlocks
+     */
+    SwingUtilities.invokeLater(new Runnable()
+    {
+
+      @Override
+      public void run()
+      {
+        processCallback(type, data);
+      }
+    });
+  }
+
+  /**
+   * Processes one callback notification from Jmol
+   * 
+   * @param type
+   * @param data
+   */
+  protected void processCallback(CBK type, Object[] data)
+  {
     try
     {
       switch (type)
@@ -592,6 +625,11 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
     modelFileNames = null;
     boolean notifyLoaded = false;
     String[] modelfilenames = getStructureFiles();
+    if (modelfilenames == null)
+    {
+      // Jmol is still loading files!
+      return;
+    }
     // first check if we've lost any structures
     if (oldmodels != null && oldmodels.length > 0)
     {
@@ -655,8 +693,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
           // see JAL-623 - need method of matching pasted data up
           {
             pdb = getSsm().setMapping(getSequence()[pe], getChains()[pe],
-                    pdbfile, DataSourceType.PASTE,
-                    getIProgressIndicator());
+                    pdbfile, DataSourceType.PASTE, getIProgressIndicator());
             getPdbEntry(modelnum).setFile("INLINE" + pdb.getId());
             matches = true;
             foundEntry = true;
@@ -724,7 +761,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
     // }
     if (!isLoadingFromArchive())
     {
-      jmolViewer.evalStringQuiet(
+      jmolScript(
               "model *; select backbone;restrict;cartoon;wireframe off;spacefill off");
     }
     // register ourselves as a listener and notify the gui that it needs to
@@ -735,7 +772,9 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
       FeatureRenderer fr = getFeatureRenderer(null);
       if (fr != null)
       {
-        fr.featuresAdded();
+        FeatureSettingsModelI colours = new Pdb().getFeatureColourScheme();
+        ((AppJmol) getViewer()).getAlignmentPanel().av
+                .applyFeaturesStyle(colours);
       }
       refreshGUI();
       loadNotifiesHandled++;
@@ -764,8 +803,7 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
   public abstract void sendConsoleEcho(String strEcho); /*
                                                          * { showConsole(true);
                                                          * 
-                                                         * history.append("\n" +
-                                                         * strEcho); }
+                                                         * history.append("\n" + strEcho); }
                                                          */
 
   // /End JmolStatusListener
@@ -789,7 +827,9 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
 
   public void showHelp()
   {
-    showUrl("http://jmol.sourceforge.net/docs/JmolUserGuide/", "jmolHelp");
+    showUrl("http://wiki.jmol.org"
+    // BH 2018 "http://jmol.sourceforge.net/docs/JmolUserGuide/"
+            , "jmolHelp");
   }
 
   /**
@@ -806,7 +846,16 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
    */
   public abstract void showConsole(boolean show);
 
+  public static Viewer getJmolData(JmolParser jmolParser)
+  {
+    return (Viewer) JmolViewer.allocateViewer(null, null, null, null, null,
+            "-x -o -n", jmolParser);
+  }
+
   /**
+   * 
+   * 
+   * 
    * @param renderPanel
    * @param jmolfileio
    *          - when true will initialise jmol's file IO system (should be false
@@ -837,13 +886,16 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
    * @param consolePanel
    *          - panel to contain Jmol console
    * @param buttonsToShow
-   *          - buttons to show on the console, in ordr
+   *          - buttons to show on the console, in order
    */
   public void allocateViewer(Container renderPanel, boolean jmolfileio,
           String htmlName, URL documentBase, URL codeBase,
           String commandOptions, final Container consolePanel,
           String buttonsToShow)
   {
+
+    System.err.println("Allocating Jmol Viewer: " + commandOptions);
+
     if (commandOptions == null)
     {
       commandOptions = "";
@@ -855,7 +907,15 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
 
     jmolViewer.setJmolStatusListener(this); // extends JmolCallbackListener
 
-    console = createJmolConsole(consolePanel, buttonsToShow);
+    try
+    {
+      console = createJmolConsole(consolePanel, buttonsToShow);
+    } catch (Throwable e)
+    {
+      System.err.println("Could not create Jmol application console. "
+              + e.getMessage());
+      e.printStackTrace();
+    }
     if (consolePanel != null)
     {
       consolePanel.addComponentListener(this);
@@ -867,6 +927,9 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
   protected abstract JmolAppConsoleInterface createJmolConsole(
           Container consolePanel, String buttonsToShow);
 
+  // BH 2018 -- Jmol console is not working due to problems with styled
+  // documents.
+
   protected org.jmol.api.JmolAppConsoleInterface console = null;
 
   @Override
@@ -970,4 +1033,23 @@ public abstract class JalviewJmolBinding extends AAStructureBindingModel
   {
     return ".spt";
   }
+
+  @Override
+  public void selectionChanged(BS arg0)
+  {
+    // TODO Auto-generated method stub
+
+  }
+
+  @Override
+  public SequenceRenderer getSequenceRenderer(AlignmentViewPanel avp)
+  {
+    return new jalview.gui.SequenceRenderer(avp.getAlignViewport());
+  }
+
+  @Override
+  public String getHelpURL()
+  {
+    return "http://wiki.jmol.org"; // BH 2018
+  }
 }