JAL-2871 JAL-2877 hideous attempt at seeing if non-static configuration
[jalview.git] / src / jalview / ext / archaeopteryx / AptxInit.java
index 3dc2e88..aa106c3 100644 (file)
@@ -1,6 +1,7 @@
 package jalview.ext.archaeopteryx;
 
 import jalview.analysis.TreeBuilder;
+import jalview.bin.Cache;
 import jalview.datamodel.SequenceI;
 import jalview.ext.treeviewer.ExternalTreeBuilderI;
 import jalview.ext.treeviewer.ExternalTreeViewerBindingI;
@@ -9,6 +10,7 @@ import jalview.gui.JvOptionPane;
 import jalview.util.MessageManager;
 import jalview.viewmodel.AlignmentViewport;
 
+import java.awt.Component;
 import java.awt.Dimension;
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -18,13 +20,17 @@ import java.net.URL;
 import java.util.HashMap;
 import java.util.Map;
 
+import javax.swing.JMenu;
+import javax.swing.JMenuBar;
+import javax.swing.JMenuItem;
+import javax.swing.JSeparator;
+
 import org.forester.archaeopteryx.AptxUtil;
 import org.forester.archaeopteryx.Archaeopteryx;
 import org.forester.archaeopteryx.Configuration;
 import org.forester.archaeopteryx.MainFrame;
 import org.forester.archaeopteryx.webservices.PhylogeniesWebserviceClient;
 import org.forester.archaeopteryx.webservices.WebserviceUtil;
-import org.forester.archaeopteryx.webservices.WebservicesManager;
 import org.forester.io.parsers.PhylogenyParser;
 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
 import org.forester.io.parsers.nhx.NHXParser;
@@ -48,24 +54,6 @@ import org.forester.util.ForesterUtil;
 public final class AptxInit
 {
 
-  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();
-
   private static Map<MainFrame, JalviewBinding> activeAptx = new HashMap<>();
 
 
@@ -97,6 +85,12 @@ public final class AptxInit
           AlignmentViewport viewport)
           throws FileNotFoundException, IOException
   {
+    Configuration APTX_CONFIG = new Configuration(Cache.getDefault(
+            "APTXCONFIG",
+            Desktop.instance.getClass()
+                    .getResource("/_aptx_jalview_configuration_file.txt")
+                    .toString()),
+            false, false, false);
     File treeFile = new File(filePath);
     final String err = ForesterUtil.isReadableFile(treeFile);
     if (!ForesterUtil.isEmpty(err))
@@ -112,30 +106,32 @@ public final class AptxInit
     }
     boolean nhx_or_nexus = false;
     final PhylogenyParser parser = ParserUtils.createParserDependingOnFileType(
-            treeFile, VALIDATE_PHYLOXML_XSD);
+                    treeFile,
+                    APTX_CONFIG.isValidatePhyloXmlAgainstSchema());
     if (parser instanceof NHXParser)
     {
       nhx_or_nexus = true;
       final NHXParser nhx = (NHXParser) parser;
-      nhx.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES);
+      nhx.setReplaceUnderscores(
+              APTX_CONFIG.isReplaceUnderscoresInNhParsing());
       nhx.setIgnoreQuotes(false);
-      nhx.setTaxonomyExtraction(TAXONOMY_EXTRACTION);
+      nhx.setTaxonomyExtraction(APTX_CONFIG.getTaxonomyExtraction());
     }
     else if (parser instanceof NexusPhylogeniesParser)
     {
       nhx_or_nexus = true;
       final NexusPhylogeniesParser nex = (NexusPhylogeniesParser) parser;
-      nex.setReplaceUnderscores(REPLACE_NHX_UNDERSCORES);
+      nex.setReplaceUnderscores(
+              APTX_CONFIG.isReplaceUnderscoresInNhParsing());
       nex.setIgnoreQuotes(false);
     }
     else if (parser instanceof PhyloXmlParser)
     {
-      if ( VALIDATE_PHYLOXML_XSD ) {
-        JvOptionPane.showInternalMessageDialog( null,
-                                       ForesterUtil.wordWrap(
-                                                              "phyloXML XSD-based validation is turned off [enable with line 'validate_against_phyloxml_xsd_schem: true' in configuration file]",
-                                                              80 ),
-                                       "Warning",
+      if (APTX_CONFIG.isValidatePhyloXmlAgainstSchema() == false)
+      {
+        JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+                MessageManager.getString("error.phyloxml_validation"),
+                MessageManager.getString("label.file_open_error"),
                                        JvOptionPane.WARNING_MESSAGE );
       }
     }
@@ -147,7 +143,8 @@ public final class AptxInit
       {
       Phylogeny tree = trees[i];
 
-      if (nhx_or_nexus && INTERNAL_NUMBERS_AS_CONFIDENCE)
+      if (nhx_or_nexus
+              && APTX_CONFIG.isInternalNumberAreConfidenceForNhParsing())
       {
         PhylogenyMethods.transferInternalNodeNamesToConfidence(tree, "");
       }
@@ -168,16 +165,23 @@ public final class AptxInit
           AlignmentViewport viewport)
           throws FileNotFoundException, IOException, RuntimeException
   {
-    
+    Configuration APTX_CONFIG = new Configuration(Cache.getDefault(
+            "APTXCONFIG",
+            Desktop.instance.getClass()
+                    .getResource("/_aptx_jalview_configuration_file.txt")
+                    .toString()),
+            false, false, false);
     String treeTitle = treeUrl.getFile();
     if (Desktop.instance != null)
     {
       Desktop.instance.startLoading(treeTitle);
     }
     Phylogeny[] trees = AptxUtil.readPhylogeniesFromUrl(treeUrl,
-            VALIDATE_PHYLOXML_XSD,
-             REPLACE_NHX_UNDERSCORES, INTERNAL_NUMBERS_AS_CONFIDENCE,
-            TAXONOMY_EXTRACTION, MIDPOINT_REROOT);
+            APTX_CONFIG.isValidatePhyloXmlAgainstSchema(),
+            APTX_CONFIG.isReplaceUnderscoresInNhParsing(),
+            APTX_CONFIG.isInternalNumberAreConfidenceForNhParsing(),
+            APTX_CONFIG.getTaxonomyExtraction(),
+            APTX_CONFIG.isMidpointReroot());
 
     MainFrame[] aptxFrames = new MainFrame[trees.length];
     for (int i = 0; i < trees.length; i++)
@@ -202,22 +206,18 @@ public final class AptxInit
    * @param viewport
    * @return
    */
-  public static MainFrame[] createInstancesFromDb(int databaseIndex,
-          AlignmentViewport viewport, String defaultIdentifier)
+  public static MainFrame[] createInstancesFromDb(
+          PhylogeniesWebserviceClient treeDbClient, String identifier,
+          AlignmentViewport viewport)
   {
-
+    Configuration APTX_CONFIG = new Configuration(Cache.getDefault(
+            "APTXCONFIG",
+            Desktop.instance.getClass()
+                    .getResource("/_aptx_jalview_configuration_file.txt")
+                    .toString()),
+            false, false, false);
     URL url = null;
     Phylogeny[] trees = null;
-    final WebservicesManager webservices_manager = WebservicesManager
-            .getInstance();
-    final PhylogeniesWebserviceClient client = webservices_manager
-            .getAvailablePhylogeniesWebserviceClient(databaseIndex);
-    String identifier = JvOptionPane.showInternalInputDialog(
-            Desktop.desktop,
-            client.getInstructions() + "\n(Reference: "
-                    + client.getReference() + ")",
-            client.getDescription(), JvOptionPane.QUESTION_MESSAGE, null,
-            null, defaultIdentifier).toString();
 
     if ((identifier != null) && (identifier.trim().length() > 0))
     {
@@ -227,7 +227,7 @@ public final class AptxInit
       }
 
       identifier = identifier.trim();
-      if (client.isQueryInteger())
+      if (treeDbClient.isQueryInteger())
       {
         identifier = identifier.replaceAll("^\\D+", "");
 
@@ -238,8 +238,11 @@ public final class AptxInit
         } catch (final NumberFormatException e)
         {
           JvOptionPane.showInternalMessageDialog(Desktop.desktop,
-                  "Identifier is expected to be a number",
-                  "Can not open URL", JvOptionPane.ERROR_MESSAGE);
+                  MessageManager.formatMessage(
+                          "error.database_id_has_letters", new String[]
+                          { identifier }),
+                  MessageManager.getString("label.invalid_url"),
+                  JvOptionPane.ERROR_MESSAGE);
           return new MainFrame[0];
         }
         identifier = id + "";
@@ -247,12 +250,12 @@ public final class AptxInit
       boolean exception = false;
       try
       {
-        String url_str = client.getUrl();
+        String url_str = treeDbClient.getUrl();
         url_str = url_str.replaceFirst(
                 PhylogeniesWebserviceClient.QUERY_PLACEHOLDER, identifier);
         url = new URL(url_str);
         PhylogenyParser parser = null;
-        switch (client.getReturnFormat())
+        switch (treeDbClient.getReturnFormat())
         {
         case TOL_XML_RESPONSE:
           parser = new TolParser();
@@ -306,7 +309,7 @@ public final class AptxInit
           break;
         default:
           throw new IllegalArgumentException(
-                  "unknown format: " + client.getReturnFormat());
+                  "unknown format: " + treeDbClient.getReturnFormat());
         }
         //
         // if (_main_frame.getMainPanel().getCurrentTreePanel() != null)
@@ -322,26 +325,32 @@ public final class AptxInit
       {
         exception = true;
         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
-                "Malformed URL: " + url + "\n" + e.getLocalizedMessage(),
-                "Malformed URL", JvOptionPane.ERROR_MESSAGE);
+                MessageManager.formatMessage(
+                        "exception.unable_to_launch_url", new String[]
+                        { url.toString() }),
+                MessageManager.getString("label.invalid_url"),
+                JvOptionPane.ERROR_MESSAGE);
+        System.err.println(e.getLocalizedMessage());
       } catch (final IOException e)
       {
         exception = true;
         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
                 "Could not read from " + url + "\n"
                         + e.getLocalizedMessage(),
-                "Failed to read tree from " + client.getName() + " for "
+                "Failed to read tree from " + treeDbClient.getName() + " for "
                         + identifier,
                 JvOptionPane.ERROR_MESSAGE);
+        System.err.println(e.getLocalizedMessage());
       } catch (final NumberFormatException e)
       {
         exception = true;
         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
                 "Could not read from " + url + "\n"
                         + e.getLocalizedMessage(),
-                "Failed to read tree from " + client.getName() + " for "
+                "Failed to read tree from " + treeDbClient.getName() + " for "
                         + identifier,
                 JvOptionPane.ERROR_MESSAGE);
+        System.err.println(e.getLocalizedMessage());
       } catch (final Exception e)
       {
         exception = true;
@@ -349,16 +358,7 @@ public final class AptxInit
         JvOptionPane.showInternalMessageDialog(Desktop.desktop,
                 e.getLocalizedMessage(), "Unexpected Exception",
                 JvOptionPane.ERROR_MESSAGE);
-      } finally
-      {
-        // if (_main_frame.getCurrentTreePanel() != null)
-        // {
-        // _main_frame.getCurrentTreePanel().setArrowCursor();
-        // }
-        // else
-        // {
-        // _main_frame.getMainPanel().setArrowCursor();
-        // }
+        System.err.println(e.getLocalizedMessage());
       }
       if ((trees != null) && (trees.length > 0))
       {
@@ -366,16 +366,16 @@ public final class AptxInit
         {
           if (!phylogeny.isEmpty())
           {
-            if (client.getName().equals(WebserviceUtil.TREE_FAM_NAME))
+            if (treeDbClient.getName().equals(WebserviceUtil.TREE_FAM_NAME))
             {
               phylogeny.setRerootable(false);
               phylogeny.setRooted(true);
             }
-            if (client.getProcessingInstructions() != null)
+            if (treeDbClient.getProcessingInstructions() != null)
             {
               try
               {
-                WebserviceUtil.processInstructions(client, phylogeny);
+                WebserviceUtil.processInstructions(treeDbClient, phylogeny);
               } catch (final PhyloXmlDataFormatException e)
               {
                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
@@ -383,12 +383,12 @@ public final class AptxInit
                         JvOptionPane.ERROR_MESSAGE);
               }
             }
-            if (client.getNodeField() != null)
+            if (treeDbClient.getNodeField() != null)
             {
               try
               {
                 PhylogenyMethods.transferNodeNameToField(phylogeny,
-                        client.getNodeField(), false);
+                        treeDbClient.getNodeField(), false);
               } catch (final PhyloXmlDataFormatException e)
               {
                 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
@@ -397,7 +397,7 @@ public final class AptxInit
               }
             }
             phylogeny.setIdentifier(
-                    new Identifier(identifier, client.getName()));
+                    new Identifier(identifier, treeDbClient.getName()));
             // _main_frame.getJMenuBar().remove(_main_frame.getHelpMenu());
             // _main_frame.getMenuBarOfMainFrame()
             // .add(_main_frame.getHelpMenu());
@@ -426,8 +426,8 @@ public final class AptxInit
               my_name_for_file = new String(
                       sb.toString().replaceAll(" ", "_"));
             }
-            // _main_frame.getMainPanel().getCurrentTreePanel()
-            // .setTreeFile(new File(my_name_for_file));
+            aptxApp.getMainPanel().getCurrentTreePanel()
+                    .setTreeFile(new File(my_name_for_file));
             AptxUtil.lookAtSomeTreePropertiesForAptxControlSettings(
                     phylogeny, aptxApp.getMainPanel().getControlPanel(),
                     APTX_CONFIG);
@@ -437,7 +437,7 @@ public final class AptxInit
           }
         }
       }
-      else if (!exception)
+      else if (!exception) // ..what?
       {
         JvOptionPane.showMessageDialog(null,
                 ForesterUtil.wordWrap(
@@ -481,9 +481,33 @@ public final class AptxInit
           final Phylogeny aptxTree,
           final AlignmentViewport jalviewAlignport, String treeTitle)
   {
+    Configuration APTX_CONFIG = new Configuration(Cache.getDefault(
+            "APTXCONFIG",
+            Desktop.instance.getClass()
+                    .getResource("/_aptx_jalview_configuration_file.txt")
+                    .toString()),
+            false, false, false);
+    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;
+      }
+
+    }
     MainFrame aptxApp = Archaeopteryx.createApplication(aptxTree,
             APTX_CONFIG, treeTitle);
 
+
     LoadedTreeSequenceAssociation bindAptxNodes = new LoadedTreeSequenceAssociation(
             jalviewAlignport.getAlignment().getSequencesArray(), aptxTree);
     bindAptxNodes.associateLeavesToSequences();
@@ -493,15 +517,10 @@ public final class AptxInit
             bindAptxNodes.getNodesWithAlignment());
     bindTreeViewFrameToJalview(aptxApp);
 
+    adaptAptxGui(aptxApp);
     return aptxApp;
   }
 
-  // private static void addPartitioningSlider(MainFrame aptxFrame)
-  // {
-  // JSlider slider = new JSlider();
-  //
-  //
-  // }
 
   public static ExternalTreeViewerBindingI<?> bindNodesToJalviewSequences(
           final MainFrame aptxApp,
@@ -540,6 +559,73 @@ public final class AptxInit
 
   }
 
+  /**
+   * Hides certain redundant Archaeopteryx GUI elements such as the menu items
+   * for reading in trees and adds extra items related to Jalview such as the
+   * tree sorting item.
+   * 
+   * 
+   * @param aptxFrame
+   */
+  private static void adaptAptxGui(MainFrame aptxFrame)
+  {
+    JMenuBar frameBar = aptxFrame.getJMenuBar();
+
+    for (int i = 0; i < frameBar.getMenuCount();i++) {
+      JMenu menu = frameBar.getMenu(i);
+
+      if (menu.getText().contains("File"))
+      {
+        // hide all "Read from ..." and "New" menu items and any Separators that
+        // come directly after them
+        Component previousMenuItem = null;
+        for (Component menuItem : menu.getMenuComponents()) {
+          if (previousMenuItem instanceof JMenuItem)
+          {
+            if (((JMenuItem) previousMenuItem).getText().startsWith("Read")
+                    || ((JMenuItem) previousMenuItem).getText()
+                            .startsWith("New"))
+            {
+              previousMenuItem.setVisible(false);
+
+              if (menuItem instanceof JSeparator)
+              {
+                menuItem.setVisible(false);
+              }
+            }
+          }
+          previousMenuItem = menuItem;
+        }
+      }
+      else if (menu.getText().contains("Inference"))
+      {
+        menu.setVisible(false);
+      }
+      else if (menu.getText().contains("View"))
+      {
+        menu.addSeparator();
+        JMenuItem sortByTree = new JMenuItem("Sort alignment by tree");
+        JMenuItem refreshJalview = new JMenuItem(
+                "Filter alignment to show only currently visible sequences");
+
+        refreshJalview.setFont(menu.getFont());
+
+        menu.add(sortByTree);
+        menu.add(refreshJalview);
+
+        sortByTree.setFont(menu.getFont());
+        sortByTree.setVisible(false); // don't show unless it's actually
+        // possible
+
+        refreshJalview.addActionListener(activeAptx.get(aptxFrame));
+
+
+      }
+
+    }
+    aptxFrame.validate();
+  }
+
   public static Map<MainFrame, JalviewBinding> getAllAptxFrames()
   {
     return activeAptx;