added bugfix todo
[jalview.git] / src / jalview / bin / JalviewLite.java
index 2a715a6..4d45f8c 100755 (executable)
@@ -22,6 +22,7 @@ import java.applet.*;
 
 import java.awt.*;
 import java.awt.event.*;
+import java.util.*;
 
 import jalview.appletgui.*;
 import jalview.datamodel.*;
@@ -42,16 +43,22 @@ public class JalviewLite
   ///////////////////////////////////////////
   //The following public methods maybe called
   //externally, eg via javascript in HTML page
-
+  /**
+   * @return list of selected sequences separated by "¬"
+   */
   public String getSelectedSequences()
   {
+    return getSelectedSequencesFrom(getDefaultTargetFrame());
+  }
+  public String getSelectedSequencesFrom(AlignFrame alf)
+  {
     StringBuffer result = new StringBuffer("");
 
-    if (initialAlignFrame.viewport.getSelectionGroup() != null)
+    if (alf.viewport.getSelectionGroup() != null)
     {
-      SequenceI[] seqs = initialAlignFrame.viewport.getSelectionGroup().
+      SequenceI[] seqs = alf.viewport.getSelectionGroup().
           getSequencesInOrder(
-              initialAlignFrame.viewport.getAlignment());
+                  alf.viewport.getAlignment());
 
       for (int i = 0; i < seqs.length; i++)
       {
@@ -61,20 +68,27 @@ public class JalviewLite
 
     return result.toString();
   }
-
+  
   public String getAlignment(String format)
   {
-    return getAlignment(format, "true");
+    return getAlignmentFrom(getDefaultTargetFrame(), format, "true");
+  }
+  public String getAlignmentFrom(AlignFrame alf, String format)
+  {
+    return getAlignmentFrom(alf, format, "true");
   }
-
   public String getAlignment(String format, String suffix)
   {
+    return getAlignmentFrom(getDefaultTargetFrame(), format, suffix);
+  }
+  public String getAlignmentFrom(AlignFrame alf, String format, String suffix)
+  {
     try
     {
       boolean seqlimits = suffix.equalsIgnoreCase("true");
 
       String reply = new AppletFormatAdapter().formatSequences(format,
-          currentAlignFrame.viewport.getAlignment(), seqlimits);
+          alf.viewport.getAlignment(), seqlimits);
       return reply;
     }
     catch (Exception ex)
@@ -86,30 +100,63 @@ public class JalviewLite
 
   public void loadAnnotation(String annotation)
   {
+    loadAnnotationFrom(getDefaultTargetFrame(), annotation);
+  }
+  public void loadAnnotationFrom(AlignFrame alf, String annotation)
+  {
     if (new AnnotationFile().readAnnotationFile(
-        currentAlignFrame.getAlignViewport().getAlignment(), annotation,
+        alf.getAlignViewport().getAlignment(), annotation,
         AppletFormatAdapter.PASTE))
     {
-      currentAlignFrame.alignPanel.fontChanged();
-      currentAlignFrame.alignPanel.setScrollValues(0, 0);
+      alf.alignPanel.fontChanged();
+      alf.alignPanel.setScrollValues(0, 0);
     }
     else
     {
-      currentAlignFrame.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
+      alf.parseFeaturesFile(annotation, AppletFormatAdapter.PASTE);
     }
   }
 
   public String getFeatures(String format)
   {
-    return currentAlignFrame.outputFeatures(false, format);
+    return getFeaturesFrom(getDefaultTargetFrame(), format);
+  }
+  public String getFeaturesFrom(AlignFrame alf, String format)
+  {
+    return alf.outputFeatures(false, format);
   }
-
   public String getAnnotation()
   {
-    return currentAlignFrame.outputAnnotations(false);
+    return getAnnotationFrom(getDefaultTargetFrame());
+  }
+  public String getAnnotationFrom(AlignFrame alf)
+  {
+    return alf.outputAnnotations(false);
+  }
+  public AlignFrame newView()
+  {
+    return newViewFrom(getDefaultTargetFrame());
+  }
+  public AlignFrame newView(String name)
+  {
+    return newViewFrom(getDefaultTargetFrame(), name);
   }
 
-  public void loadAlignment(String text, String title)
+  public AlignFrame newViewFrom(AlignFrame alf)
+  {
+    return alf.newView(null);
+  }
+  public AlignFrame newViewFrom(AlignFrame alf, String name)
+  {
+    return alf.newView(name);
+  }
+  /**
+   * 
+   * @param text alignment file as a string
+   * @param title window title 
+   * @return null or new alignment frame
+   */
+  public AlignFrame loadAlignment(String text, String title)
   {
     Alignment al = null;
     String format = new IdentifyFile().Identify(text, AppletFormatAdapter.PASTE);
@@ -120,13 +167,14 @@ public class JalviewLite
                                               format);
       if (al.getHeight() > 0)
       {
-        new AlignFrame(al, this, title, false);
+        return new AlignFrame(al, this, title, false);
       }
     }
     catch (java.io.IOException ex)
     {
       ex.printStackTrace();
     }
+    return null;
   }
 
   ////////////////////////////////////////////////
@@ -140,34 +188,51 @@ public class JalviewLite
   String file = "No file";
   Button launcher = new Button("Start Jalview");
 
-  //The currentAlignFrame is static, it will change
-  //if and when the user selects a new window
+  /**
+   * The currentAlignFrame is static, it will change
+   * if and when the user selects a new window.
+   * Note that it will *never* point back to the embedded AlignFrame 
+   * if the applet is started as embedded on the page and then afterwards a new view is created.
+   */
   public static AlignFrame currentAlignFrame;
 
-  //This is the first frame to be displayed, and does not change
+  /** 
+   * This is the first frame to be displayed, and does not change.
+   * API calls will default to this instance if currentAlignFrame is null.
+   */
   AlignFrame initialAlignFrame;
 
   boolean embedded = false;
 
   public boolean jmolAvailable = false;
+  public static boolean debug;
 
   /**
    * init method for Jalview Applet
    */
   public void init()
   {
-    try
+    String dbg = getParameter("debug");
+    if (dbg!=null)
     {
-      Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter",
-                    true, Thread.currentThread().getContextClassLoader());
-
-      jmolAvailable = true;
+      debug = dbg.toLowerCase().equals("true");
     }
-    catch (java.lang.ClassNotFoundException ex)
+    /**
+     * get the separator parameter if present
+     */
+    String sep = getParameter("separator");
+    if (sep!=null)
     {
-      System.out.println("Jmol not found - Using MCview for structures");
+      if (sep.length()>0)
+      {      separator = sep;
+        if (debug)
+        {
+          System.err.println("Separator set to '"+separator+"'");
+        }
+      } else {
+        throw new Error("Invalid separator parameter - must be non-zero length");
+      }
     }
-
     int r = 255;
     int g = 255;
     int b = 255;
@@ -215,6 +280,9 @@ public class JalviewLite
       }
     }
 
+    LoadJmolThread jmolAvailable = new LoadJmolThread();
+    jmolAvailable.start();
+
     final JalviewLite applet = this;
     if (getParameter("embedded") != null
         && getParameter("embedded").equalsIgnoreCase("true"))
@@ -244,33 +312,6 @@ public class JalviewLite
     }
   }
 
-  public static void main(String[] args)
-  {
-    if (args.length != 1)
-    {
-      System.out.println("\nUsage: java -jar jalviewApplet.jar fileName\n");
-      System.exit(1);
-    }
-
-    String format = new jalview.io.IdentifyFile().Identify(args[0],
-        AppletFormatAdapter.FILE);
-
-    Alignment al = null;
-    try
-    {
-      al = new AppletFormatAdapter().readFile(args[0], AppletFormatAdapter.FILE,
-                                              format);
-    }
-    catch (java.io.IOException ex)
-    {
-      ex.printStackTrace();
-    }
-    if ( (al != null) && (al.getHeight() > 0))
-    {
-      AlignFrame af = new AlignFrame(al, null, args[0], false);
-      af.statusBar.setText("Successfully loaded file " + args[0]);
-    }
-  }
 
   /**
    * Initialises and displays a new java.awt.Frame
@@ -302,18 +343,44 @@ public class JalviewLite
         }
         lastFrameX -= 40;
         lastFrameY -= 40;
+        if (frame instanceof EmbmenuFrame)
+        {
+          ((EmbmenuFrame) frame).destroyMenus();
+        }
         frame.setMenuBar(null);
         frame.dispose();
       }
-
+      
       public void windowActivated(WindowEvent e)
       {
         if (frame instanceof AlignFrame)
         {
           currentAlignFrame = (AlignFrame) frame;
+          if (debug)
+          {
+            System.err.println("Activated window "+frame);
+          }
         }
+        // be good.
+        super.windowActivated(e);
       }
-
+      /* Probably not necessary to do this - see TODO above.
+       * (non-Javadoc)
+       * @see java.awt.event.WindowAdapter#windowDeactivated(java.awt.event.WindowEvent)
+       *
+      public void windowDeactivated(WindowEvent e)
+      {
+        if (currentAlignFrame == frame)
+        {
+          currentAlignFrame = null;
+          if (debug)
+          {
+            System.err.println("Deactivated window "+frame);
+          }
+        }
+        super.windowDeactivated(e);
+      }
+       */
     });
     frame.setVisible(true);
   }
@@ -343,9 +410,29 @@ public class JalviewLite
       g.drawString("Jalview Applet", 50, this.getSize().height / 2 - 30);
       g.drawString("Loading Data...", 50, this.getSize().height / 2);
     }
+  }
+
 
+  class LoadJmolThread extends Thread
+  {
+    public void run()
+    {
+      try
+      {
+        if (!System.getProperty("java.version").startsWith("1.1"))
+        {
+          Class.forName("org.jmol.adapter.smarter.SmarterJmolAdapter");
+          jmolAvailable = true;
+        }
+      }
+      catch (java.lang.ClassNotFoundException ex)
+      {
+        System.out.println("Jmol not available - Using MCview for structures");
+      }
+    }
   }
 
+
   class LoadingThread
       extends Thread
   {
@@ -357,6 +444,10 @@ public class JalviewLite
     public LoadingThread(String _file,
                          JalviewLite _applet)
     {
+      if (applet.debug)
+      {
+        System.err.println("Loading thread started with:\n>>file\n"+_file+">>endfile");
+      }
       file = _file;
       if (file.startsWith("PASTE"))
       {
@@ -372,12 +463,25 @@ public class JalviewLite
         file = addProtocol(file);
         protocol = AppletFormatAdapter.URL;
       }
+      if (applet.debug)
+      {
+        System.err.println("Protocol identified as '"+protocol+"'");
+      }
       format = new jalview.io.IdentifyFile().Identify(file, protocol);
+      if (applet.debug)
+      {
+        System.err.println("File identified as '"+format+"'");
+      }
       applet = _applet;
     }
 
     public void run()
     {
+      startLoading();
+    }
+
+    private void startLoading()
+    {
       Alignment al = null;
       try
       {
@@ -390,18 +494,18 @@ public class JalviewLite
       }
       if ( (al != null) && (al.getHeight() > 0))
       {
-        currentAlignFrame = new AlignFrame(al,
+        initialAlignFrame =  new AlignFrame(al,
                                            applet,
                                            file,
                                            embedded);
+        // update the focus.
+        currentAlignFrame = initialAlignFrame;
 
         if (protocol == jalview.io.AppletFormatAdapter.PASTE)
         {
           currentAlignFrame.setTitle("Sequences from " + getDocumentBase());
         }
 
-        initialAlignFrame = currentAlignFrame;
-
         currentAlignFrame.statusBar.setText("Successfully loaded file " + file);
 
         String treeFile = applet.getParameter("tree");
@@ -505,43 +609,129 @@ public class JalviewLite
           }
         }
 
+        /*
+         <param name="PDBfile" value="1gaq.txt PDB|1GAQ|1GAQ|A PDB|1GAQ|1GAQ|B PDB|1GAQ|1GAQ|C">
 
-        param = getParameter("PDBFILE");
-        if (param != null)
-        {
+         <param name="PDBfile2" value="1gaq.txt A=SEQA B=SEQB C=SEQB">
 
-          PDBEntry pdb = new PDBEntry();
+         <param name="PDBfile3" value="1q0o Q45135_9MICO">
+        */
 
-          if (!inArchive(param) || jmolAvailable)
+
+        int pdbFileCount = 0;
+        do{
+          if (pdbFileCount > 0)
+            param = getParameter("PDBFILE" + pdbFileCount);
+          else
+            param = getParameter("PDBFILE");
+
+          if (param != null)
           {
-            param = addProtocol(param);
-          }
+            PDBEntry pdb = new PDBEntry();
 
-          pdb.setFile(param);
+            String seqstring;
+            SequenceI[] seqs = null;
+            String [] chains = null;
 
-          String sequence = applet.getParameter("PDBSEQ");
+            StringTokenizer st = new StringTokenizer(param, " ");
 
-          if (sequence != null)
-          {
-            if (jmolAvailable)
-              new jalview.appletgui.AppletJmol(pdb,
-                                               new SequenceI[]
-                                               { (Sequence) currentAlignFrame.
-                                               getAlignViewport().getAlignment().
-                                               findName(sequence)},
-                                               currentAlignFrame.alignPanel,
-                                               protocol);
+            if (st.countTokens() < 2)
+            {
+              String sequence = applet.getParameter("PDBSEQ");
+              if (sequence != null)
+                seqs = new SequenceI[]
+                    {
+                    (Sequence) currentAlignFrame.
+                    getAlignViewport().getAlignment().
+                    findName(sequence)};
+
+            }
+            else
+            {
+              param = st.nextToken();
+              Vector tmp = new Vector();
+              Vector tmp2 = new Vector();
+
+              while (st.hasMoreTokens())
+              {
+                seqstring = st.nextToken();
+                StringTokenizer st2 = new StringTokenizer(seqstring,"=");
+                if(st2.countTokens()>1)
+                {
+                  //This is the chain
+                  tmp2.addElement(st2.nextToken());
+                  seqstring = st2.nextToken();
+                }
+                tmp.addElement( (Sequence) currentAlignFrame.
+                                 getAlignViewport().getAlignment().
+                                 findName(seqstring));
+              }
+
+              seqs = new SequenceI[tmp.size()];
+              tmp.copyInto(seqs);
+              if(tmp2.size()==tmp.size())
+              {
+                chains = new String[tmp2.size()];
+                tmp2.copyInto(chains);
+              }
+            }
+
+            if (inArchive(param) && !jmolAvailable)
+            {
+              protocol = AppletFormatAdapter.CLASSLOADER;
+            }
             else
+            {
+              protocol = AppletFormatAdapter.URL;
+              param = addProtocol(param);
+            }
+
+            pdb.setFile(param);
 
-              new MCview.AppletPDBViewer(pdb,
-                                         new SequenceI[]
-                                         { (Sequence) currentAlignFrame.
-                                         getAlignViewport().getAlignment().
-                                         findName(sequence)},
-                                         currentAlignFrame.alignPanel,
-                                         protocol);
+            if(seqs!=null)
+            {
+              for (int i = 0; i < seqs.length; i++)
+              {
+                ( (Sequence) seqs[i]).addPDBId(pdb);
+              }
+
+              if (jmolAvailable)
+              {
+                new jalview.appletgui.AppletJmol(pdb,
+                                                 seqs,
+                                                 chains,
+                                                 currentAlignFrame.alignPanel,
+                                                 protocol);
+                lastFrameX += 40;
+                lastFrameY+=40;
+              }
+              else
+                    new MCview.AppletPDBViewer(pdb,
+                                           seqs,
+                                           chains,
+                                           currentAlignFrame.alignPanel,
+                                           protocol);
+            }
           }
 
+          pdbFileCount++;
+        }
+        while(pdbFileCount < 10);
+        
+        /////////////////////////////
+        // modify display of features
+        //
+        // hide specific groups
+        param = getParameter("hidefeaturegroups");
+        if (param != null)
+        {
+          applet.setFeatureGroupState(param, false);
+        }
+        // show specific groups
+        param = getParameter("showfeaturegroups");
+        if (param != null)
+        {
+          applet.setFeatureGroupState(param, true);
         }
       }
       else
@@ -582,4 +772,170 @@ public class JalviewLite
       return file;
     }
   }
+  /**
+   * @return the default alignFrame acted on by the public applet methods.
+   * May return null with an error message on System.err indicating the fact. 
+   */
+  protected AlignFrame getDefaultTargetFrame()
+  {
+    if (currentAlignFrame!=null)
+    {
+      return currentAlignFrame;
+    }
+    if (initialAlignFrame!=null)
+    {
+      return initialAlignFrame;
+    }
+    System.err.println("Implementation error: Jalview Applet API cannot work out which AlignFrame to use.");
+    return null;
+  }
+  /**
+   * separator used for separatorList
+   */
+  protected String separator = "|"; // this is a safe(ish) separator - tabs don't work for firefox
+  /**
+   * parse the string into a list
+   * @param list
+   * @return elements separated by separator
+   */
+  public String[] separatorListToArray(String list)
+  {
+    int seplen = separator.length();
+    if (list==null || list.equals(""))
+      return null;
+    java.util.Vector jv = new Vector();
+    int cp=0,pos;
+    while ((pos=list.indexOf(separator,cp))>cp)
+    {
+      jv.addElement(list.substring(cp,pos));
+      cp = pos+seplen;
+    }
+    if (cp<list.length())
+    {
+      jv.addElement(list.substring(cp));
+    }
+    if (jv.size()>0)
+    { String[] v = new String[jv.size()];
+      for (int i=0; i<v.length; i++)
+      {
+        v[i] = (String) jv.elementAt(i);
+      }
+      jv.removeAllElements();
+      if (debug)
+      {
+        System.err.println("Array from '"+separator+"' separated List:\n"+v.length);
+        for (int i=0; i<v.length;i++)
+        {
+          System.err.println("item "+i+" '"+v[i]+"'");
+        }
+      }
+      return v;
+    }
+    if (debug)
+    {
+      System.err.println("Empty Array from '"+separator+"' separated List");
+    }
+    return null;
+  }
+  /**
+   * concatenate the list with separator
+   * @param list
+   * @return concatenated string
+   */
+  public String arrayToSeparatorList(String[] list)
+  {
+    StringBuffer v = new StringBuffer();
+    if (list!=null)
+    {
+      for (int i=0,iSize=list.length-1;i<iSize;i++)
+      { 
+        if (list[i]!=null)
+        {  
+          v.append(list[i]); 
+        }
+        v.append(separator);
+      }
+      if (list[list.length-1]!=null)
+      { v.append(list[list.length-1]);
+      }
+      if (debug)
+      {
+        System.err.println("Returning '"+separator+"' separated List:\n");
+        System.err.println(v);
+      }
+      return v.toString();
+    }
+    if (debug)
+    {
+      System.err.println("Returning empty '"+separator+"' separated List\n");
+    }
+    return "";
+  }
+  /**
+   * @return
+   * @see jalview.appletgui.AlignFrame#getFeatureGroups()
+   */
+  public String getFeatureGroups()
+  {
+    String lst = arrayToSeparatorList(getDefaultTargetFrame().getFeatureGroups());
+    return lst;
+  }
+  /**
+   * @param alf alignframe to get feature groups on
+   * @return
+   * @see jalview.appletgui.AlignFrame#getFeatureGroups()
+   */
+  public String getFeatureGroupsOn(AlignFrame alf)
+  {
+    String lst = arrayToSeparatorList(alf.getFeatureGroups());
+    return lst;
+  }
+  /**
+   * @param visible
+   * @return
+   * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
+   */
+  public String getFeatureGroupsOfState(boolean visible)
+  {
+    return arrayToSeparatorList(getDefaultTargetFrame().getFeatureGroupsOfState(visible));
+  }
+  /**
+   * @param alf align frame to get groups of state visible
+   * @param visible
+   * @return
+   * @see jalview.appletgui.AlignFrame#getFeatureGroupsOfState(boolean)
+   */
+  public String getFeatureGroupsOfStateOn(AlignFrame alf, boolean visible)
+  {
+    return arrayToSeparatorList(alf.getFeatureGroupsOfState(visible));
+  }  /**
+   * @param groups tab separated list of group names 
+   * @param state true or false
+   * @see jalview.appletgui.AlignFrame#setFeatureGroupState(java.lang.String[], boolean)
+   */
+  public void setFeatureGroupStateOn(AlignFrame alf, String groups, boolean state)
+  {
+    boolean st = state;//!(state==null || state.equals("") || state.toLowerCase().equals("false"));
+    alf.setFeatureGroupState(separatorListToArray(groups), st);
+  }
+  public void setFeatureGroupState(String groups, boolean state)
+  {
+    setFeatureGroupStateOn(getDefaultTargetFrame(), groups, state);
+  }
+  /**
+   * List separator string
+   * @return the separator
+   */
+  public String getSeparator()
+  {
+    return separator;
+  }
+  /**
+   * List separator string
+   * @param separator the separator to set
+   */
+  public void setSeparator(String separator)
+  {
+    this.separator = separator;
+  }
 }