JAL-2403 ScoreModelI now DistanceModelI, ScoreMatrix delegate of
[jalview.git] / src / jalview / gui / AlignFrame.java
index 3c0569e..5f0e5d3 100644 (file)
@@ -24,6 +24,7 @@ import jalview.analysis.AlignmentSorter;
 import jalview.analysis.AlignmentUtils;
 import jalview.analysis.CrossRef;
 import jalview.analysis.Dna;
+import jalview.analysis.NJTree;
 import jalview.analysis.ParseProperties;
 import jalview.analysis.SequenceIdMatcher;
 import jalview.api.AlignExportSettingI;
@@ -34,7 +35,7 @@ import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureSettingsControllerI;
 import jalview.api.SplitContainerI;
 import jalview.api.ViewStyleI;
-import jalview.api.analysis.ScoreModelI;
+import jalview.api.analysis.DistanceModelI;
 import jalview.bin.Cache;
 import jalview.bin.Jalview;
 import jalview.commands.CommandI;
@@ -67,7 +68,9 @@ import jalview.io.BioJsHTMLOutput;
 import jalview.io.DataSourceType;
 import jalview.io.FileFormat;
 import jalview.io.FileFormatI;
+import jalview.io.FileFormats;
 import jalview.io.FileLoader;
+import jalview.io.FileParse;
 import jalview.io.FormatAdapter;
 import jalview.io.HtmlSvgOutput;
 import jalview.io.IdentifyFile;
@@ -76,12 +79,12 @@ import jalview.io.JalviewFileChooser;
 import jalview.io.JalviewFileView;
 import jalview.io.JnetAnnotationMaker;
 import jalview.io.NewickFile;
+import jalview.io.ScoreMatrixFile;
 import jalview.io.TCoffeeScoreFile;
 import jalview.jbgui.GAlignFrame;
 import jalview.schemes.ColourSchemeI;
 import jalview.schemes.ColourSchemes;
 import jalview.schemes.ResidueColourScheme;
-import jalview.schemes.ResidueProperties;
 import jalview.schemes.TCoffeeColourScheme;
 import jalview.util.MessageManager;
 import jalview.viewmodel.AlignmentViewport;
@@ -118,6 +121,8 @@ import java.awt.print.PageFormat;
 import java.awt.print.PrinterJob;
 import java.beans.PropertyChangeEvent;
 import java.io.File;
+import java.io.FileWriter;
+import java.io.PrintWriter;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -357,7 +362,15 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
 
     setMenusFromViewport(viewport);
     buildSortByAnnotationScoresMenu();
-    buildTreeMenu();
+    calculateTree.addActionListener(new ActionListener()
+    {
+
+      @Override
+      public void actionPerformed(ActionEvent e)
+      {
+        new TreeChooser(AlignFrame.this);
+      }
+    });
     buildColourMenu();
 
     if (Desktop.desktop != null)
@@ -842,7 +855,8 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     showReverse.setVisible(nucleotide);
     showReverseComplement.setVisible(nucleotide);
     conservationMenuItem.setEnabled(!nucleotide);
-    modifyConservation.setEnabled(!nucleotide);
+    modifyConservation.setEnabled(!nucleotide
+            && conservationMenuItem.isSelected());
     showGroupConservation.setEnabled(!nucleotide);
 
     showComplementMenuItem.setText(nucleotide ? MessageManager
@@ -873,7 +887,9 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     padGapsMenuitem.setSelected(av.isPadGaps());
     colourTextMenuItem.setSelected(av.isShowColourText());
     abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
+    modifyPID.setEnabled(abovePIDThreshold.isSelected());
     conservationMenuItem.setSelected(av.getConservationSelected());
+    modifyConservation.setEnabled(conservationMenuItem.isSelected());
     seqLimits.setSelected(av.getShowJVSuffix());
     idRightAlign.setSelected(av.isRightAlignIds());
     centreColumnLabelsMenuItem.setState(av.isCentreColumnLabels());
@@ -1094,7 +1110,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   public void saveAs_actionPerformed(ActionEvent e)
   {
     String format = currentFileFormat == null ? null : currentFileFormat
-            .toString();
+            .getName();
     JalviewFileChooser chooser = JalviewFileChooser.forWrite(
             Cache.getProperty("LAST_DIRECTORY"), format);
 
@@ -1128,8 +1144,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
 
       fileName = chooser.getSelectedFile().getPath();
 
-      Cache.setProperty("DEFAULT_FILE_FORMAT",
-              currentFileFormat.toString());
+      Cache.setProperty("DEFAULT_FILE_FORMAT", currentFileFormat.getName());
 
       Cache.setProperty("LAST_DIRECTORY", fileName);
       saveAlignment(fileName, currentFileFormat);
@@ -1159,17 +1174,6 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     }
     else
     {
-      // if (!jalview.io.AppletFormatAdapter.isValidFormat(format, true))
-      // {
-      // warningMessage("Cannot save file " + fileName + " using format "
-      // + format, "Alignment output format not supported");
-      // if (!Jalview.isHeadlessMode())
-      // {
-      // saveAs_actionPerformed(null);
-      // }
-      // return false;
-      // }
-
       AlignmentExportData exportData = getAlignmentForExport(format,
               viewport, null);
       if (exportData.getSettings().isCancelled())
@@ -1194,15 +1198,14 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
       {
         try
         {
-          java.io.PrintWriter out = new java.io.PrintWriter(
-                  new java.io.FileWriter(file));
+          PrintWriter out = new PrintWriter(new FileWriter(file));
 
           out.print(output);
           out.close();
           this.setTitle(file);
           statusBar.setText(MessageManager.formatMessage(
                   "label.successfully_saved_to_file_in_format",
-                  new Object[] { fileName, format }));
+                  new Object[] { fileName, format.getName() }));
         } catch (Exception ex)
         {
           success = false;
@@ -1247,8 +1250,8 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   @Override
   protected void outputText_actionPerformed(ActionEvent e)
   {
-
-    FileFormatI fileFormat = FileFormat.forName(e.getActionCommand());
+    FileFormatI fileFormat = FileFormats.getInstance().forName(
+            e.getActionCommand());
     AlignmentExportData exportData = getAlignmentForExport(fileFormat,
             viewport, null);
     if (exportData.getSettings().isCancelled())
@@ -1261,8 +1264,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     {
       FileFormatI format = fileFormat;
       cap.setText(new FormatAdapter(alignPanel, exportData.getSettings())
-              .formatSequences(format,
-                      exportData.getAlignment(),
+              .formatSequences(format, exportData.getAlignment(),
                       exportData.getOmitHidden(),
                       exportData.getStartEndPostions(),
                       viewport.getColumnSelection()));
@@ -1853,8 +1855,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     }
 
     String output = new FormatAdapter().formatSequences(FileFormat.Fasta,
-            seqs,
-            omitHidden, null);
+            seqs, omitHidden, null);
 
     StringSelection ss = new StringSelection(output);
 
@@ -3307,11 +3308,12 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
    * colour scheme to all groups. If unchecked, groups may have their own
    * independent colour schemes.
    * 
+   * @param selected
    */
   @Override
-  protected void applyToAllGroups_actionPerformed()
+  public void applyToAllGroups_actionPerformed(boolean selected)
   {
-    viewport.setColourAppliesToAllGroups(applyToAllGroups.isSelected());
+    viewport.setColourAppliesToAllGroups(selected);
   }
 
   /**
@@ -3353,19 +3355,6 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     if (cs != null)
     {
       ColourMenuHelper.setColourSelected(colourMenu, cs.getSchemeName());
-      // Make sure viewport is up to date w.r.t. any sliders
-      if (viewport.getAbovePIDThreshold())
-      {
-        int threshold = SliderPanel.setPIDSliderSource(alignPanel, cs,
-                "Background");
-        viewport.setThreshold(threshold);
-      }
-
-      if (viewport.getConservationSelected())
-      {
-        cs.setConservationInc(SliderPanel.setConservationSlider(alignPanel,
-                cs, "Background"));
-      }
     }
 
     viewport.setGlobalColourScheme(cs);
@@ -3374,77 +3363,71 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Show the PID threshold slider panel
    */
   @Override
   protected void modifyPID_actionPerformed()
   {
-    if (viewport.getAbovePIDThreshold()
-            && viewport.getGlobalColourScheme() != null)
-    {
-      SliderPanel.setPIDSliderSource(alignPanel,
-              viewport.getGlobalColourScheme(), "Background");
-      SliderPanel.showPIDSlider();
-    }
+    SliderPanel.setPIDSliderSource(alignPanel,
+            viewport.getResidueShading(), alignPanel.getViewName());
+    SliderPanel.showPIDSlider();
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Show the Conservation slider panel
    */
   @Override
   protected void modifyConservation_actionPerformed()
   {
-    if (viewport.getConservationSelected()
-            && viewport.getGlobalColourScheme() != null)
-    {
-      SliderPanel.setConservationSlider(alignPanel,
-              viewport.getGlobalColourScheme(), "Background");
-      SliderPanel.showConservationSlider();
-    }
+    SliderPanel.setConservationSlider(alignPanel,
+            viewport.getResidueShading(), alignPanel.getViewName());
+    SliderPanel.showConservationSlider();
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Action on selecting or deselecting (Colour) By Conservation
    */
   @Override
-  protected void conservationMenuItem_actionPerformed()
+  public void conservationMenuItem_actionPerformed(boolean selected)
   {
-    viewport.setConservationSelected(conservationMenuItem.isSelected());
-
-    viewport.setAbovePIDThreshold(false);
-    abovePIDThreshold.setSelected(false);
+    modifyConservation.setEnabled(selected);
+    viewport.setConservationSelected(selected);
+    viewport.getResidueShading().setConservationApplied(selected);
 
     changeColour(viewport.getGlobalColourScheme());
-
-    modifyConservation_actionPerformed();
+    if (selected)
+    {
+      modifyConservation_actionPerformed();
+    }
+    else
+    {
+      SliderPanel.hideConservationSlider();
+    }
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Action on selecting or deselecting (Colour) Above PID Threshold
    */
   @Override
-  public void abovePIDThreshold_actionPerformed()
+  public void abovePIDThreshold_actionPerformed(boolean selected)
   {
-    viewport.setAbovePIDThreshold(abovePIDThreshold.isSelected());
-
-    conservationMenuItem.setSelected(false);
-    viewport.setConservationSelected(false);
+    modifyPID.setEnabled(selected);
+    viewport.setAbovePIDThreshold(selected);
+    if (!selected)
+    {
+      viewport.getResidueShading().setThreshold(0,
+              viewport.isIgnoreGapsConsensus());
+    }
 
     changeColour(viewport.getGlobalColourScheme());
-
-    modifyPID_actionPerformed();
+    if (selected)
+    {
+      modifyPID_actionPerformed();
+    }
+    else
+    {
+      SliderPanel.hidePIDSlider();
+    }
   }
 
   /**
@@ -3607,54 +3590,6 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   /**
    * DOCUMENT ME!
    * 
-   * @param e
-   *          DOCUMENT ME!
-   */
-  @Override
-  public void averageDistanceTreeMenuItem_actionPerformed(ActionEvent e)
-  {
-    newTreePanel("AV", "PID", "Average distance tree using PID");
-  }
-
-  /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
-   */
-  @Override
-  public void neighbourTreeMenuItem_actionPerformed(ActionEvent e)
-  {
-    newTreePanel("NJ", "PID", "Neighbour joining tree using PID");
-  }
-
-  /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
-   */
-  @Override
-  protected void njTreeBlosumMenuItem_actionPerformed(ActionEvent e)
-  {
-    newTreePanel("NJ", "BL", "Neighbour joining tree using BLOSUM62");
-  }
-
-  /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
-   */
-  @Override
-  protected void avTreeBlosumMenuItem_actionPerformed(ActionEvent e)
-  {
-    newTreePanel("AV", "BL", "Average distance tree using BLOSUM62");
-  }
-
-  /**
-   * DOCUMENT ME!
-   * 
    * @param type
    *          DOCUMENT ME!
    * @param pwType
@@ -3861,48 +3796,10 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
    * call. Listeners are added to remove the menu item when the treePanel is
    * closed, and adjust the tree leaf to sequence mapping when the alignment is
    * modified.
-   * 
-   * @param treePanel
-   *          Displayed tree window.
-   * @param title
-   *          SortBy menu item title.
    */
   @Override
-  public void buildTreeMenu()
+  public void buildTreeSortMenu()
   {
-    calculateTree.removeAll();
-    // build the calculate menu
-
-    for (final String type : new String[] { "NJ", "AV" })
-    {
-      String treecalcnm = MessageManager.getString("label.tree_calc_"
-              + type.toLowerCase());
-      for (final String pwtype : ResidueProperties.scoreMatrices.keySet())
-      {
-        JMenuItem tm = new JMenuItem();
-        ScoreModelI sm = ResidueProperties.scoreMatrices.get(pwtype);
-        if (sm.isDNA() == viewport.getAlignment().isNucleotide()
-                || sm.isProtein() == !viewport.getAlignment()
-                        .isNucleotide())
-        {
-          String smn = MessageManager.getStringOrReturn(
-                  "label.score_model_", sm.getName());
-          final String title = MessageManager.formatMessage(
-                  "label.treecalc_title", treecalcnm, smn);
-          tm.setText(title);//
-          tm.addActionListener(new java.awt.event.ActionListener()
-          {
-            @Override
-            public void actionPerformed(ActionEvent e)
-            {
-              newTreePanel(type, pwtype, title);
-            }
-          });
-          calculateTree.add(tm);
-        }
-
-      }
-    }
     sortByTreeMenu.removeAll();
 
     List<Component> comps = PaintRefresher.components.get(viewport
@@ -4129,7 +4026,7 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
 
       if (nf.getTree() != null)
       {
-        tp = new TreePanel(alignPanel, "FromFile", title, nf, input);
+        tp = new TreePanel(alignPanel, NJTree.FROM_FILE, title, nf, input);
 
         tp.setSize(w, h);
 
@@ -4711,10 +4608,13 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
   }
 
   /**
-   * Attempt to load a "dropped" file or URL string: First by testing whether
-   * it's an Annotation file, then a JNet file, and finally a features file. If
-   * all are false then the user may have dropped an alignment file onto this
-   * AlignFrame.
+   * Attempt to load a "dropped" file or URL string, by testing in turn for
+   * <ul>
+   * <li>an Annotation file</li>
+   * <li>a JNet file</li>
+   * <li>a features file</li>
+   * <li>else try to interpret as an alignment file</li>
+   * </ul>
    * 
    * @param file
    *          either a filename or a URL string.
@@ -4788,10 +4688,20 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
           {
             format = new IdentifyFile().identify(file, sourceType);
           }
-          if (FileFormat.Jnet.equals(format))
+          if (FileFormat.ScoreMatrix == format)
+          {
+            ScoreMatrixFile sm = new ScoreMatrixFile(new FileParse(file,
+                    sourceType));
+            sm.parse();
+            // todo: i18n this message
+            statusBar
+                    .setText(MessageManager.formatMessage(
+                            "label.successfully_loaded_matrix",
+                            sm.getMatrixName()));
+          }
+          else if (FileFormat.Jnet.equals(format))
           {
-            JPredFile predictions = new JPredFile(
-                    file, sourceType);
+            JPredFile predictions = new JPredFile(file, sourceType);
             new JnetAnnotationMaker();
             JnetAnnotationMaker.add_annotation(predictions,
                     viewport.getAlignment(), 0, false);
@@ -4861,6 +4771,28 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     }
 
     /*
+     * 'focus' any colour slider that is open to the selected viewport
+     */
+    if (viewport.getConservationSelected())
+    {
+      SliderPanel.setConservationSlider(alignPanel,
+              viewport.getResidueShading(), alignPanel.getViewName());
+    }
+    else
+    {
+      SliderPanel.hideConservationSlider();
+    }
+    if (viewport.getAbovePIDThreshold())
+    {
+      SliderPanel.setPIDSliderSource(alignPanel,
+              viewport.getResidueShading(), alignPanel.getViewName());
+    }
+    else
+    {
+      SliderPanel.hidePIDSlider();
+    }
+
+    /*
      * If there is a frame linked to this one in a SplitPane, switch it to the
      * same view tab index. No infinite recursion of calls should happen, since
      * tabSelectionChanged() should not get invoked on setting the selected
@@ -5699,17 +5631,18 @@ public class AlignFrame extends GAlignFrame implements DropTargetListener,
     colourMenu.add(modifyPID);
     colourMenu.add(annotationColour);
 
-    /*
-     * select the default colour for the alignment (this may be
-     * overridden later)
-     */
-    boolean nucleotide = viewport.getAlignment().isNucleotide();
-    String defaultColourScheme = Cache.getDefault(
-            nucleotide ? Preferences.DEFAULT_COLOUR_NUC
-                    : Preferences.DEFAULT_COLOUR_PROT,
-            ResidueColourScheme.NONE);
+    ColourSchemeI colourScheme = viewport.getGlobalColourScheme();
+    String schemeName = colourScheme == null ? null : colourScheme
+            .getSchemeName();
+
+    ColourMenuHelper.setColourSelected(colourMenu, schemeName);
+  }
 
-    ColourMenuHelper.setColourSelected(colourMenu, defaultColourScheme);
+  public void newTreePanel(String treeType, DistanceModelI sm)
+  {
+    String scoreModelName = sm.getName();
+    final String ttl = TreePanel.getPanelTitle(treeType, scoreModelName);
+    newTreePanel(treeType, scoreModelName, ttl);
   }
 }