JAL-2799 rearranged AptxInit code
[jalview.git] / src / jalview / ext / archaeopteryx / AptxInit.java
index 107aeca..5a9fb12 100644 (file)
@@ -5,16 +5,29 @@ import jalview.datamodel.SequenceI;
 import jalview.ext.treeviewer.ExternalTreeBuilderI;
 import jalview.ext.treeviewer.ExternalTreeViewerBindingI;
 import jalview.gui.Desktop;
+import jalview.gui.JvOptionPane;
+import jalview.util.MessageManager;
 import jalview.viewmodel.AlignmentViewport;
 
 import java.awt.Dimension;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
 import java.net.URL;
 import java.util.Map;
 
+import org.forester.archaeopteryx.AptxUtil;
 import org.forester.archaeopteryx.Archaeopteryx;
+import org.forester.archaeopteryx.Configuration;
 import org.forester.archaeopteryx.MainFrame;
+import org.forester.io.parsers.PhylogenyParser;
+import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
+import org.forester.io.parsers.nhx.NHXParser;
+import org.forester.io.parsers.util.ParserUtils;
 import org.forester.phylogeny.Phylogeny;
+import org.forester.phylogeny.PhylogenyMethods;
 import org.forester.phylogeny.PhylogenyNode;
+import org.forester.util.ForesterUtil;
 
 /**
  * Static class for creating Archaeopteryx tree viewer instances from calculated
@@ -25,173 +38,144 @@ import org.forester.phylogeny.PhylogenyNode;
  */
 public final class AptxInit
 {
-  /**
-   * Test method, should generally not be used as it does not bind the tree to
-   * its alignment
-   * 
-   * @param aptxTrees
-   * @return
-   */
-  public static MainFrame createUnboundInstance(final Phylogeny aptxTree)
-  {
-    Phylogeny[] aptxTrees = { aptxTree };
-    return createAptxFrame(aptxTrees);
-  }
 
-  // public static MainFrame createInstance(final Phylogeny[] aptxTrees,
-  // AlignmentViewport jalviewAlignmentView)
-  // {
-  // return createAptxFrameInJalview(aptxTrees);
-  //
-  // }
-  //
-  // public static MainFrame createInstance(final Phylogeny aptxTree,
-  // final AlignmentViewport jalviewAlignmentView)
-  // {
-  // Phylogeny[] aptxTrees = { aptxTree }; // future possibility to load in
-  // // several trees simultaneously
-  // return createAptxFrameInJalview(aptxTrees);
-  //
-  // }
-
-  public static MainFrame createInstance(
+  private final static Configuration APTX_CONFIG = new Configuration(
+          "_aptx_jalview_configuration_file", false, false, false);
+
+  private final static boolean VALIDATE_PHYLOXML_XSD = APTX_CONFIG
+          .isValidatePhyloXmlAgainstSchema();
+
+  private final static boolean REPLACE_NHX_UNDERSCORES = APTX_CONFIG
+          .isReplaceUnderscoresInNhParsing();
+
+  private final static boolean INTERNAL_NUMBERS_AS_CONFIDENCE = APTX_CONFIG
+          .isInternalNumberAreConfidenceForNhParsing();
+
+  private final static boolean MIDPOINT_REROOT = APTX_CONFIG
+          .isMidpointReroot();
+
+  private final static NHXParser.TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION = APTX_CONFIG
+          .getTaxonomyExtraction();
+
+
+
+  public static MainFrame createInstanceFromCalculation(
           final TreeBuilder calculatedTree) // very dense method, to be split up
   {
     ExternalTreeBuilderI<Phylogeny, PhylogenyNode> aptxTreeBuilder = new AptxTreeBuilder(
             calculatedTree);
 
     Phylogeny aptxTree = aptxTreeBuilder.buildTree();
-    Phylogeny[] aptxTrees = { aptxTree }; // future possibility to load in
-                                          // several trees simultaneously
 
-    MainFrame aptxApp = createAptxFrame(aptxTrees);
+    MainFrame aptxApp = createAptxFrame(aptxTree,
+            calculatedTree.getAvport(), null);
             
-    bindNodesToJalviewSequences(aptxApp, calculatedTree.getAvport(),
-            aptxTreeBuilder.getAlignmentBoundNodes(),
-            aptxTreeBuilder.getNodesBoundAlignment());
-
-    return bindFrameToJalview(aptxApp);
-
+    return aptxApp;
   }
 
-  public static MainFrame createInstanceFromFile(String filePath,
+  /**
+   * Refactored from Archaeopteryx.main
+   * 
+   * @param filePath
+   * @param viewport
+   * @return
+   * @throws IOException
+   * @throws FileNotFoundException
+   */
+  public static MainFrame[] createInstancesFromFile(String filePath,
           AlignmentViewport viewport)
+          throws FileNotFoundException, IOException
   {
-    String[] AptxArgs = new String[] { "-c",
-        "_aptx_jalview_configuration_file", filePath };
-    MainFrame aptxApp = Archaeopteryx.main(AptxArgs);
-
-    LoadedTreeAssociation bindAptxNodes = new LoadedTreeAssociation(
-            viewport.getAlignment().getSequencesArray(),
-            aptxApp.getMainPanel().getCurrentTreePanel().getPhylogeny());
-
-    bindAptxNodes.associateLeavesToSequences();
-
-    bindNodesToJalviewSequences(aptxApp, viewport,
-            bindAptxNodes.getAlignmentWithNodes(),
-            bindAptxNodes.getNodesWithAlignment());
+    File treeFile = new File(filePath);
+    final String err = ForesterUtil.isReadableFile(treeFile);
+    if (!ForesterUtil.isEmpty(err))
+    {
+      JvOptionPane.showMessageDialog(Desktop.desktop, err,
+              MessageManager.getString("label.problem_reading_tree_file"),
+              JvOptionPane.WARNING_MESSAGE);
+    }
+    boolean nhx_or_nexus = false;
+    final PhylogenyParser p = ParserUtils.createParserDependingOnFileType(
+            treeFile, VALIDATE_PHYLOXML_XSD);
+    if (p instanceof NHXParser)
+    {
+      nhx_or_nexus = true;
+      final NHXParser nhx = (NHXParser) p;
+      nhx.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES);
+      nhx.setIgnoreQuotes(false);
+      nhx.setTaxonomyExtraction(TAXONOMY_EXTRACTION);
+    }
+    else if (p instanceof NexusPhylogeniesParser)
+    {
+      nhx_or_nexus = true;
+      final NexusPhylogeniesParser nex = (NexusPhylogeniesParser) p;
+      nex.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES);
+      nex.setIgnoreQuotes(false);
+    }
+//    else if (p instanceof PhyloXmlParser)
+//    {
+//      MainFrameApplication.warnIfNotPhyloXmlValidation(APTX_CONFIG);
+//    }
+    Phylogeny[] phylogenies = PhylogenyMethods.readPhylogenies(p, treeFile);
+    MainFrame[] aptxFrames = new MainFrame[phylogenies.length];
+    String treeTitle = treeFile.getName();
+
+    for (int i = 0; i < phylogenies.length; i++)
+      {
+      Phylogeny tree = phylogenies[i];
+
+      if (nhx_or_nexus && INTERNAL_NUMBERS_AS_CONFIDENCE)
+      {
+        PhylogenyMethods.transferInternalNodeNamesToConfidence(tree, "");
+      }
+
+      aptxFrames[i] = createAptxFrame(tree, viewport, treeTitle);
+    }
+
+    return aptxFrames;
+    }
+
+
+  public static MainFrame[] createInstancesFromUrl(URL treeUrl,
+          AlignmentViewport viewport)
+          throws FileNotFoundException, IOException, RuntimeException
+  {
+    
+    String treeTitle = treeUrl.getFile();
+    Phylogeny[] trees = AptxUtil.readPhylogeniesFromUrl(treeUrl,
+            VALIDATE_PHYLOXML_XSD,
+             REPLACE_NHX_UNDERSCORES, INTERNAL_NUMBERS_AS_CONFIDENCE,
+            TAXONOMY_EXTRACTION, MIDPOINT_REROOT);
+
+    MainFrame[] aptxFrames = new MainFrame[trees.length];
+    for (int i = 0; i < trees.length; i++)
+    {
+      Phylogeny tree = trees[i];
+      aptxFrames[i] = createAptxFrame(tree, viewport, treeTitle);
+    }
+
+    return aptxFrames;
 
-    return bindFrameToJalview(aptxApp);
   }
 
-  public static MainFrame createInstanceFromUrl(URL url)
-  {
-
-    return null;
-    // void readPhylogeniesFromURL() {
-    // URL url = null;
-    // Phylogeny[] phys = null;
-    // final String message = "Please enter a complete URL, for example
-    // \"http://purl.org/phylo/treebase/phylows/study/TB2:S15480?format=nexus\"";
-    // final String url_string = JOptionPane
-    // .showInputDialog( this,
-    // message,
-    // "Use URL/webservice to obtain a phylogeny",
-    // JOptionPane.QUESTION_MESSAGE );
-    // boolean nhx_or_nexus = false;
-    // if ( ( url_string != null ) && ( url_string.length() > 0 ) ) {
-    // try {
-    // url = new URL( url_string );
-    // PhylogenyParser parser = null;
-    // if ( url.getHost().toLowerCase().indexOf( "tolweb" ) >= 0 ) {
-    // parser = new TolParser();
-    // }
-    // else {
-    // parser = ParserUtils
-    // .createParserDependingOnUrlContents( url,
-    // getConfiguration().isValidatePhyloXmlAgainstSchema() );
-    // }
-    // if ( parser instanceof NexusPhylogeniesParser ) {
-    // nhx_or_nexus = true;
-    // }
-    // else if ( parser instanceof NHXParser ) {
-    // nhx_or_nexus = true;
-    // }
-    // if ( _mainpanel.getCurrentTreePanel() != null ) {
-    // _mainpanel.getCurrentTreePanel().setWaitCursor();
-    // }
-    // else {
-    // _mainpanel.setWaitCursor();
-    // }
-    // final PhylogenyFactory factory =
-    // ParserBasedPhylogenyFactory.getInstance();
-    // phys = factory.create( url.openStream(), parser );
-    // }
-    // catch ( final MalformedURLException e ) {
-    // JOptionPane.showMessageDialog( this,
-    // "Malformed URL: " + url + "\n" + e.getLocalizedMessage(),
-    // "Malformed URL",
-    // JOptionPane.ERROR_MESSAGE );
-    // }
-    // catch ( final IOException e ) {
-    // JOptionPane.showMessageDialog( this,
-    // "Could not read from " + url + "\n"
-    // + ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
-    // "Failed to read URL",
-    // JOptionPane.ERROR_MESSAGE );
-    // }
-    // catch ( final Exception e ) {
-    // JOptionPane.showMessageDialog( this,
-    // ForesterUtil.wordWrap( e.getLocalizedMessage(), 80 ),
-    // "Unexpected Exception",
-    // JOptionPane.ERROR_MESSAGE );
-    // }
-    // finally {
-    // if ( _mainpanel.getCurrentTreePanel() != null ) {
-    // _mainpanel.getCurrentTreePanel().setArrowCursor();
-    // }
-    // else {
-    // _mainpanel.setArrowCursor();
-    // }
-    // }
-    // if ( ( phys != null ) && ( phys.length > 0 ) ) {
-    // if ( nhx_or_nexus &&
-    // getOptions().isInternalNumberAreConfidenceForNhParsing() ) {
-    // for( final Phylogeny phy : phys ) {
-    // PhylogenyMethods.transferInternalNodeNamesToConfidence( phy, "" );
-    // }
-    // }
-    // AptxUtil.addPhylogeniesToTabs( phys,
-    // new File( url.getFile() ).getName(),
-    // new File( url.getFile() ).toString(),
-    // getConfiguration(),
-    // getMainPanel() );
-    // _mainpanel.getControlPanel().showWhole();
-    // }
-    // }
-    // activateSaveAllIfNeeded();
-    // System.gc();
-    // }
 
-  }
 
 
 
   public static MainFrame createAptxFrame(
-          final Phylogeny[] aptxTrees)
+          final Phylogeny aptxTree,
+          final AlignmentViewport jalviewAlignport, String treeTitle)
   {
-    MainFrame aptxApp = Archaeopteryx.createApplication(aptxTrees,
-            "_aptx_jalview_configuration_file", null);
+    MainFrame aptxApp = Archaeopteryx.createApplication(aptxTree,
+            APTX_CONFIG, treeTitle);
+    LoadedTreeAssociation bindAptxNodes = new LoadedTreeAssociation(
+            jalviewAlignport.getAlignment().getSequencesArray(), aptxTree);
+
+    bindAptxNodes.associateLeavesToSequences();
+    bindNodesToJalviewSequences(aptxApp, jalviewAlignport,
+            bindAptxNodes.getAlignmentWithNodes(),
+            bindAptxNodes.getNodesWithAlignment());
+    bindFrameToJalview(aptxApp);
     return aptxApp;
   }
 
@@ -223,4 +207,5 @@ public final class AptxInit
   }
 
 
+
 }