JAL-2805 added Aptx factory method reading directly from a File
[jalview.git] / src / jalview / ext / archaeopteryx / AptxInit.java
index e8fa7d0..ba34213 100644 (file)
@@ -1,26 +1,24 @@
 package jalview.ext.archaeopteryx;
 
 import jalview.analysis.TreeBuilder;
-import jalview.datamodel.SequenceI;
-import jalview.ext.treeviewer.ExternalLoadedTreeAssociationI;
-import jalview.ext.treeviewer.ExternalTreeBuilderI;
-import jalview.ext.treeviewer.ExternalTreeFrame;
-import jalview.ext.treeviewer.ExternalTreeI;
-import jalview.ext.treeviewer.ExternalTreeNodeI;
-import jalview.ext.treeviewer.ExternalTreeViewerBindingI;
+import jalview.ext.forester.io.UtilityMethods;
+import jalview.ext.treeviewer.LoadedTreeAssociationI;
+import jalview.ext.treeviewer.LoadedTreeSequenceAssociation;
+import jalview.ext.treeviewer.TreeBuilderI;
+import jalview.ext.treeviewer.TreeFrameI;
+import jalview.ext.treeviewer.TreeI;
+import jalview.ext.treeviewer.TreeViewerUtils;
 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.io.InputStream;
 import java.net.MalformedURLException;
 import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
 
 import org.forester.archaeopteryx.AptxUtil;
 import org.forester.archaeopteryx.Configuration;
@@ -47,9 +45,19 @@ import org.forester.util.ForesterUtil;
  */
 public final class AptxInit
 {
+  public final static InputStream CONFIG_LOC = AptxInit.class
+
+          .getResourceAsStream("/_aptx_jalview_configuration_file.txt");
+
   public final static Configuration APTX_CONFIG = new Configuration(
-          "_aptx_jalview_configuration_file",
-            false, false, false);
+          CONFIG_LOC,
+          false, false);
+  // static
+  // {
+  // APTX_CONFIG.setBaseFontFamilyName(
+  // Desktop.instance.getFont().getFamily().replaceAll(" ", "_"));
+  // APTX_CONFIG.setBaseFontSize(Desktop.instance.getFont().getSize());
+  // }
 
   private final static boolean VALIDATE_PHYLOXML_XSD = APTX_CONFIG
           .isValidatePhyloXmlAgainstSchema();
@@ -66,24 +74,87 @@ public final class AptxInit
   private final static NHXParser.TAXONOMY_EXTRACTION TAXONOMY_EXTRACTION = APTX_CONFIG
           .getTaxonomyExtraction();
 
-  private static Map<ExternalTreeFrame, ExternalTreeViewerBindingI> activeAptx = new HashMap<>();
-
-
-
-  public static ExternalTreeFrame createInstanceFromCalculation(
+  public static TreeFrameI createInstanceFromCalculation(
           final TreeBuilder calculatedTree)
   {
-    ExternalTreeBuilderI aptxTreeBuilder = new AptxTreeBuilder(
+    TreeBuilderI aptxTreeBuilder = new AptxTreeBuilder(
             calculatedTree);
 
-    ExternalTreeI aptxTree = aptxTreeBuilder.buildTree();
+    TreeI aptxTree = aptxTreeBuilder.buildTree();
 
-    ExternalTreeFrame aptxApp = createAptxFrame(aptxTree,
+    TreeFrameI aptxApp = createAptxFrame(aptxTree,
             calculatedTree.getAvport(), null);
             
     return aptxApp;
   }
 
+  public static TreeFrameI[] createInstancesFromFile(File treeFile,
+          AlignmentViewport viewport)
+          throws FileNotFoundException, IOException
+  {
+    TreeFrameI[] aptxFrames = null;
+    if (UtilityMethods.canForesterReadFile(treeFile))
+    {
+
+      if (Desktop.instance != null)
+      {
+        Desktop.instance.startLoading(treeFile.getCanonicalPath());
+      }
+      boolean nhx_or_nexus = false;
+      final PhylogenyParser parser = ParserUtils
+              .createParserDependingOnFileType(treeFile,
+                      VALIDATE_PHYLOXML_XSD);
+      if (parser instanceof NHXParser)
+      {
+        nhx_or_nexus = true;
+        final NHXParser nhx = (NHXParser) parser;
+        nhx.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES);
+        nhx.setIgnoreQuotes(false);
+        nhx.setTaxonomyExtraction(TAXONOMY_EXTRACTION);
+      }
+      else if (parser instanceof NexusPhylogeniesParser)
+      {
+        nhx_or_nexus = true;
+        final NexusPhylogeniesParser nex = (NexusPhylogeniesParser) parser;
+        nex.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES);
+        nex.setIgnoreQuotes(false);
+      }
+      else if (parser instanceof PhyloXmlParser)
+      {
+        if (VALIDATE_PHYLOXML_XSD == false)
+        {
+          JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+                  MessageManager.getString("error.phyloxml_validation"),
+                  MessageManager.getString("label.file_open_error"),
+                  JvOptionPane.WARNING_MESSAGE);
+        }
+      }
+      Phylogeny[] trees = PhylogenyMethods.readPhylogenies(parser,
+              treeFile);
+      aptxFrames = new TreeFrameI[trees.length];
+
+      for (int i = 0; i < trees.length; i++)
+      {
+        Phylogeny aptxPhylogeny = trees[i];
+
+        if (nhx_or_nexus && INTERNAL_NUMBERS_AS_CONFIDENCE)
+        {
+          PhylogenyMethods
+                  .transferInternalNodeNamesToConfidence(aptxPhylogeny, "");
+        }
+        String treeTitle = treeFile.getName() + "[" + i + "]";
+        aptxPhylogeny.setName(treeTitle);
+        aptxFrames[i] = createAptxFrame(aptxPhylogeny, viewport, treeTitle);
+
+      }
+      if (Desktop.instance != null)
+      {
+        Desktop.instance.stopLoading();
+      }
+    }
+    return aptxFrames;
+  }
+
   /**
    * Refactored from Archaeopteryx.main
    * 
@@ -93,82 +164,18 @@ public final class AptxInit
    * @throws IOException
    * @throws FileNotFoundException
    */
-  public static ExternalTreeFrame[] createInstancesFromFile(
+  public static TreeFrameI[] createInstancesFromFile(
           String filePath,
           AlignmentViewport viewport)
           throws FileNotFoundException, IOException
   {
     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);
-    }
-
-    if (Desktop.instance != null)
-    {
-      Desktop.instance.startLoading(filePath);
-    }
-    boolean nhx_or_nexus = false;
-    final PhylogenyParser parser = ParserUtils
-            .createParserDependingOnFileType(
-            treeFile, VALIDATE_PHYLOXML_XSD);
-    if (parser instanceof NHXParser)
-    {
-      nhx_or_nexus = true;
-      final NHXParser nhx = (NHXParser) parser;
-      nhx.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES);
-      nhx.setIgnoreQuotes(false);
-      nhx.setTaxonomyExtraction(TAXONOMY_EXTRACTION);
-    }
-    else if (parser instanceof NexusPhylogeniesParser)
-    {
-      nhx_or_nexus = true;
-      final NexusPhylogeniesParser nex = (NexusPhylogeniesParser) parser;
-      nex.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES);
-      nex.setIgnoreQuotes(false);
-    }
-    else if (parser instanceof PhyloXmlParser)
-    {
-      if (VALIDATE_PHYLOXML_XSD == false)
-      {
-        JvOptionPane.showInternalMessageDialog(Desktop.desktop,
-                MessageManager.getString("error.phyloxml_validation"),
-                MessageManager.getString("label.file_open_error"),
-                                       JvOptionPane.WARNING_MESSAGE );
-      }
-    }
-    Phylogeny[] trees = PhylogenyMethods.readPhylogenies(parser,
-            treeFile);
-    ExternalTreeFrame[] aptxFrames = new ExternalTreeFrame[trees.length];
-
-
-    for (int i = 0; i < trees.length; i++)
-      {
-      Phylogeny aptxPhylogeny = trees[i];
-
-      if (nhx_or_nexus && INTERNAL_NUMBERS_AS_CONFIDENCE)
-      {
-        PhylogenyMethods.transferInternalNodeNamesToConfidence(aptxPhylogeny,
-                "");
-      }
-      String treeTitle = treeFile.getName() + "[" + i + "]";
-      aptxPhylogeny.setName(treeTitle);
-      Tree aptxTree = new Tree(aptxPhylogeny);
-      aptxFrames[i] = createAptxFrame(aptxTree, viewport, treeTitle);
+    return createInstancesFromFile(treeFile, viewport);
 
     }
-    if (Desktop.instance != null)
-    {
-      Desktop.instance.stopLoading();
-    }
-    return aptxFrames;
-    }
 
 
-  public static ExternalTreeFrame[] createInstancesFromUrl(URL treeUrl,
+  public static TreeFrameI[] createInstancesFromUrl(URL treeUrl,
           AlignmentViewport viewport)
           throws FileNotFoundException, IOException, RuntimeException
   {
@@ -183,12 +190,11 @@ public final class AptxInit
              REPLACE_NHX_UNDERSCORES, INTERNAL_NUMBERS_AS_CONFIDENCE,
             TAXONOMY_EXTRACTION, MIDPOINT_REROOT);
 
-    ExternalTreeFrame[] aptxFrames = new ExternalTreeFrame[trees.length];
+    TreeFrameI[] aptxFrames = new TreeFrameI[trees.length];
     for (int i = 0; i < trees.length; i++)
     {
       Phylogeny aptxTree = trees[i];
-      Tree jalviewTree = new Tree(aptxTree);
-      aptxFrames[i] = createAptxFrame(jalviewTree, viewport, treeTitle);
+      aptxFrames[i] = createAptxFrame(aptxTree, viewport, treeTitle);
     }
 
     if (Desktop.instance != null)
@@ -207,13 +213,14 @@ public final class AptxInit
    * @param viewport
    * @return
    */
-  public static ExternalTreeFrame[] createInstancesFromDb(
+  public static TreeFrameI[] createInstancesFromDb(
           PhylogeniesWebserviceClient treeDbClient, String identifier,
           AlignmentViewport viewport)
   {
 
     URL url = null;
     Phylogeny[] trees = null;
+    TreeFrameI[] aptxFrames = null;
 
     if ((identifier != null) && (identifier.trim().length() > 0))
     {
@@ -239,7 +246,7 @@ public final class AptxInit
                           { identifier }),
                   MessageManager.getString("label.invalid_url"),
                   JvOptionPane.ERROR_MESSAGE);
-          return new ExternalTreeFrame[0];
+          return new TreeFrameI[0];
         }
         identifier = id + "";
       }
@@ -317,6 +324,7 @@ public final class AptxInit
         // _main_frame.getMainPanel().setWaitCursor();
         // }
         trees = ForesterUtil.readPhylogeniesFromUrl(url, parser);
+        aptxFrames = new TreeFrameI[trees.length];
       } catch (final MalformedURLException e)
       {
         exception = true;
@@ -358,6 +366,7 @@ public final class AptxInit
       }
       if ((trees != null) && (trees.length > 0))
       {
+        int i = 0;
         for (final Phylogeny aptxTree : trees)
         {
           if (!aptxTree.isEmpty())
@@ -402,15 +411,14 @@ public final class AptxInit
             // _main_frame.getConfiguration(),
             // new File(url.getFile()).getName(), url.toString());
 
-            Tree jalviewTree = new Tree(aptxTree);
 
-            ExternalTreeFrame aptxApp = createAptxFrame(jalviewTree,
+            TreeFrameI aptxApp = createAptxFrame(aptxTree,
                     viewport,
                     url.getFile());
             String my_name_for_file = "";
-            if (!ForesterUtil.isEmpty(jalviewTree.getTreeName()))
+            if (!ForesterUtil.isEmpty(aptxTree.getName()))
             {
-              my_name_for_file = new String(jalviewTree.getTreeName())
+              my_name_for_file = new String(aptxTree.getName())
                       .replaceAll(" ", "_");
             }
             else if (aptxTree.getIdentifier() != null)
@@ -434,6 +442,7 @@ public final class AptxInit
             aptxApp.getTreeControls().displayEntireTree();
 
             aptxApp.checkMultipleTrees();
+            aptxFrames[i++] = aptxApp;
           }
         }
       }
@@ -468,93 +477,78 @@ public final class AptxInit
     {
       Desktop.instance.stopLoading();
     }
-    return null;
+    return aptxFrames;
 
 
   }
 
 
 
-
-
-  public static ExternalTreeFrame createAptxFrame(
-          final ExternalTreeI aptxTree,
-          final AlignmentViewport jalviewAlignport, String treeTitle)
+  public static TreeFrameI createAptxFrame(TreeI aptxTree,
+          AlignmentViewport jalviewAlignport, String treeTitle)
   {
-    if (APTX_CONFIG == null || APTX_CONFIG.isCouldReadConfigFile() == false)
-    {
-      int keepGoing = JvOptionPane.showConfirmDialog(Desktop.desktop,
-              MessageManager.getString("label.aptx_config_not_found"),
-              MessageManager.formatMessage("label.couldnt_locate",
-                      new String[]
-                      { "_aptx_jalview_configuration_file" }),
-              JvOptionPane.YES_NO_CANCEL_OPTION);
-
-      if (keepGoing == JvOptionPane.CANCEL_OPTION
-              || keepGoing == JvOptionPane.CLOSED_OPTION
-              || keepGoing == JvOptionPane.NO_OPTION)
-      {
-        return null;
-      }
-
-    }
-    ExternalTreeFrame aptxApp = aptxTree.createInstanceFromTree(treeTitle);
-
-    ExternalLoadedTreeAssociationI bindAptxNodes = new LoadedTreeSequenceAssociation(
-            jalviewAlignport.getAlignment().getSequencesArray(), aptxTree);
+    validateConfig(APTX_CONFIG);
+    TreeFrameI aptxApp = aptxTree
+            .createTreeViewerFromTree(treeTitle);
+    TreeI jalviewTree = aptxApp.getTree();
+    LoadedTreeAssociationI bindAptxNodes = new LoadedTreeSequenceAssociation(
+            jalviewAlignport.getAlignment().getSequencesArray(),
+            jalviewTree);
     bindAptxNodes.associateLeavesToSequences();
 
-    bindNodesToJalviewSequences(aptxApp, jalviewAlignport,
+    TreeViewerUtils.associateNodesWithJalviewSequences(aptxApp, jalviewAlignport,
             bindAptxNodes.getAlignmentWithNodes(),
             bindAptxNodes.getNodesWithAlignment());
-    bindTreeViewFrameToJalview(aptxApp);
+    TreeViewerUtils.addTreeViewFrameToJalview(aptxApp);
 
     // adaptAptxGui(aptxApp); //moved to AptxFrame
     return aptxApp;
   }
 
 
-  public static ExternalTreeViewerBindingI bindNodesToJalviewSequences(
-          final ExternalTreeFrame aptxApp,
-          final AlignmentViewport jalviewAlignViewport,
-          final Map<SequenceI, ExternalTreeNodeI> alignMappedToNodes,
-          final Map<ExternalTreeNodeI, SequenceI> nodesMappedToAlign)
+  protected static TreeFrameI createAptxFrame(
+          final Phylogeny aptxTree,
+          final AlignmentViewport jalviewAlignport, String treeTitle)
   {
-    JalviewBinding treeBinding = new JalviewBinding(aptxApp,
-            jalviewAlignViewport,
-            alignMappedToNodes, nodesMappedToAlign);
-    activeAptx.put(aptxApp, treeBinding);
-    return treeBinding;
-  }
+    validateConfig(APTX_CONFIG);
+    TreeFrameI aptxApp = new AptxFrame(aptxTree, APTX_CONFIG,
+            treeTitle);
+    TreeI jalviewTree = aptxApp.getTree();
+    LoadedTreeAssociationI bindAptxNodes = new LoadedTreeSequenceAssociation(
+            jalviewAlignport.getAlignment().getSequencesArray(),
+            jalviewTree);
+    bindAptxNodes.associateLeavesToSequences();
 
+    TreeViewerUtils.associateNodesWithJalviewSequences(aptxApp, jalviewAlignport,
+            bindAptxNodes.getAlignmentWithNodes(),
+            bindAptxNodes.getNodesWithAlignment());
+    TreeViewerUtils.addTreeViewFrameToJalview(aptxApp);
 
-  public static ExternalTreeFrame bindTreeViewFrameToJalview(
-          final ExternalTreeFrame aptxApp)
-  {
-    int width = 400;
-    int height = 550;
-    aptxApp.setMinimumSize(new Dimension(width, height));
-    // aptxApp.setFont(Desktop.instance.getFont());
-    // aptxApp.getMainPanel().setFont(Desktop.instance.getFont());
-    String frameTitle = MessageManager.getString("label.aptx_title");
-    File treeFile = aptxApp.getTreePanel().getTreeFile();
-    if (treeFile != null)
-    {
-      frameTitle += MessageManager.formatMessage("label.aptx_title_append",
-              new String[]
-              { treeFile.getAbsolutePath() });
-    }
-    Desktop.addInternalFrame(aptxApp, frameTitle, true, width, height, true,
-            true);
+    // adaptAptxGui(aptxApp); //moved to AptxFrame
     return aptxApp;
-
   }
 
 
-
-  public static Map<ExternalTreeFrame, ExternalTreeViewerBindingI> getAllAptxFrames()
+  private static boolean validateConfig(Configuration aptxConfig)
   {
-    return activeAptx;
+    if (aptxConfig == null || aptxConfig.isCouldReadConfigFile() == false)
+    {
+      int keepGoing = JvOptionPane.showConfirmDialog(Desktop.desktop,
+              MessageManager.getString("label.aptx_config_not_found"),
+              MessageManager.formatMessage("label.couldnt_locate",
+                      new String[]
+                      { "_aptx_jalview_configuration_file" }),
+              JvOptionPane.YES_NO_CANCEL_OPTION);
+
+      if (keepGoing == JvOptionPane.CANCEL_OPTION
+              || keepGoing == JvOptionPane.CLOSED_OPTION
+              || keepGoing == JvOptionPane.NO_OPTION)
+      {
+        return false;
+      }
+
+    }
+    return true;
   }