ensure current dataset reference is passed to the crossReference search method
[jalview.git] / src / jalview / gui / AlignFrame.java
index 0756e2d..6302efb 100755 (executable)
@@ -28,6 +28,7 @@ import java.awt.dnd.*;
 import java.awt.event.*;
 import java.awt.print.*;
 import javax.swing.*;
+import javax.swing.event.MenuEvent;
 
 import jalview.analysis.*;
 import jalview.commands.*;
@@ -112,8 +113,6 @@ public class AlignFrame
 
   void init()
   {
-    this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
-
     if (viewport.conservation == null)
     {
       BLOSUM62Colour.setEnabled(false);
@@ -137,12 +136,13 @@ public class AlignFrame
 
     if (Desktop.desktop != null)
    {
+     this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
      addServiceListeners();
      setGUINucleotide(viewport.alignment.isNucleotide());
    }
 
    setMenusFromViewport(viewport);
-
+   buildSortByAnnotationScoresMenu();
    if (viewport.wrapAlignment)
    {
      wrapMenuItem_actionPerformed(null);
@@ -170,12 +170,15 @@ public class AlignFrame
       {
         public void keyPressed(KeyEvent evt)
         {
-          if (viewport.cursorMode
-              && evt.getKeyCode() >= KeyEvent.VK_0
-              && evt.getKeyCode() <= KeyEvent.VK_9)
-          {
+          if (viewport.cursorMode &&
+              ( (evt.getKeyCode() >= KeyEvent.VK_0 &&
+                 evt.getKeyCode() <= KeyEvent.VK_9)
+               ||
+               (evt.getKeyCode() >= KeyEvent.VK_NUMPAD0 &&
+                evt.getKeyCode() <= KeyEvent.VK_NUMPAD9)
+              )
+              && Character.isDigit(evt.getKeyChar()))
             alignPanel.seqPanel.numberPressed(evt.getKeyChar());
-          }
 
           switch (evt.getKeyCode())
           {
@@ -495,14 +498,17 @@ public class AlignFrame
     showTranslation.setVisible( nucleotide );
     conservationMenuItem.setEnabled( !nucleotide );
     modifyConservation.setEnabled(   !nucleotide );
-
+    
     //Remember AlignFrame always starts as protein
     if(!nucleotide)
     {
       calculateMenu.remove(calculateMenu.getItemCount()-2);
     }
+    setShowProductsEnabled();
   }
 
+
+
   /**
    * Need to call this method when tabs are selected for multiple views,
    * or when loading from Jalview2XML.java
@@ -687,9 +693,9 @@ public class AlignFrame
     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
         getProperty( "LAST_DIRECTORY"),
         new String[]
-        { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc","jar" },
+        { "fa, fasta, fastq", "aln", "pfam", "msf", "pir", "blc","amsa","jar" },
         new String[]
-        { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "Jalview" },
+        { "Fasta", "Clustal", "PFAM", "MSF", "PIR", "BLC", "AMSA", "Jalview" },
         currentFileFormat,
         false);
 
@@ -720,7 +726,7 @@ public class AlignFrame
 
       jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
 
-      saveAlignment(fileName, currentFileFormat);
+      saveAlignment(fileName, currentFileFormat.substring(0,currentFileFormat.indexOf(" ")));
     }
   }
 
@@ -763,11 +769,12 @@ public class AlignFrame
           omitHidden = viewport.getViewAsString(false);
       }
       }
+      FormatAdapter f = new FormatAdapter();
 
-      String output = new FormatAdapter().formatSequences(
+      String output = f.formatSequences(
           format,
-          viewport.alignment.getSequencesArray(),
-          omitHidden);
+          (Alignment) viewport.alignment, // class cast exceptions will occur in the distant future
+          omitHidden, f.getCacheSuffixDefault(format));
 
       if (output == null)
       {
@@ -838,7 +845,7 @@ public class AlignFrame
 
     cap.setText(new FormatAdapter().formatSequences(
         e.getActionCommand(),
-        viewport.alignment.getSequencesArray(),
+        viewport.alignment,
         omitHidden));
   }
 
@@ -849,7 +856,7 @@ public class AlignFrame
    */
   protected void htmlMenuItem_actionPerformed(ActionEvent e)
   {
-    new HTMLOutput(viewport,
+    new HTMLOutput(alignPanel,
                    alignPanel.seqPanel.seqCanvas.getSequenceRenderer(),
         alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
   }
@@ -909,7 +916,8 @@ public class AlignFrame
     new AnnotationExporter().exportAnnotations(
       alignPanel,
         viewport.showAnnotation ? viewport.alignment.getAlignmentAnnotation() : null,
-      viewport.alignment.getGroups()
+      viewport.alignment.getGroups(),
+      ((Alignment)viewport.alignment).alignmentProperties
         );
   }
 
@@ -957,9 +965,12 @@ public class AlignFrame
           for (int i = 0; i < alignPanels.size(); i++)
           {
             AlignmentPanel ap = (AlignmentPanel) alignPanels.elementAt(i);
+            jalview.structure.StructureSelectionManager.getStructureSelectionManager()
+                .removeStructureViewerListener(ap.seqPanel, null);
             PaintRefresher.RemoveComponent(ap.seqPanel.seqCanvas);
             PaintRefresher.RemoveComponent(ap.idPanel.idCanvas);
             PaintRefresher.RemoveComponent(ap);
+            ap.av.alignment = null;
           }
         }
         else
@@ -970,6 +981,7 @@ public class AlignFrame
           PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
           PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
           PaintRefresher.RemoveComponent(alignPanel);
+          viewport.alignment = null;
           alignPanel = null;
           viewport = null;
 
@@ -1041,8 +1053,28 @@ public class AlignFrame
     }
   }
 
-
-
+  /**
+   *
+   * @return alignment objects for all views
+   */
+  AlignmentI[] getViewAlignments()
+  {
+    if (alignPanels!=null)
+    {
+      Enumeration e = alignPanels.elements();
+      AlignmentI[] als = new AlignmentI[alignPanels.size()];
+      for (int i=0; e.hasMoreElements(); i++)
+      {
+        als[i] = ((AlignmentPanel) e.nextElement()).av.getAlignment();
+      }
+      return als;
+    }
+    if (viewport!=null)
+    {
+      return new AlignmentI[] { viewport.alignment };
+    }
+    return null;
+  }
   /**
    * DOCUMENT ME!
    *
@@ -1050,9 +1082,11 @@ public class AlignFrame
    */
   protected void undoMenuItem_actionPerformed(ActionEvent e)
   {
+    if (viewport.historyList.empty())
+      return;
     CommandI command = (CommandI)viewport.historyList.pop();
     viewport.redoList.push(command);
-    command.undoCommand();
+    command.undoCommand(getViewAlignments());
 
     AlignViewport originalSource = getOriginatingSource(command);
     updateEditMenuBar();
@@ -1080,7 +1114,7 @@ public class AlignFrame
 
     CommandI command = (CommandI) viewport.redoList.pop();
     viewport.historyList.push(command);
-    command.doCommand();
+    command.doCommand(getViewAlignments());
 
     AlignViewport originalSource = getOriginatingSource(command);
     updateEditMenuBar();
@@ -1203,14 +1237,6 @@ public class AlignFrame
 
   synchronized void slideSequences(boolean right, int size)
   {
-    if(viewport.hasHiddenColumns)
-    {
-      JOptionPane.showInternalMessageDialog(Desktop.desktop,
-          "Slide Sequences not available with hidden columns",
-          "Slide Sequence not Available",
-          JOptionPane.WARNING_MESSAGE);
-      return;
-    }
     Vector sg = new Vector();
     if(viewport.cursorMode)
     {
@@ -1297,7 +1323,7 @@ public class AlignFrame
 
     repaint();
   }
-  
+
 
   /**
    * DOCUMENT ME!
@@ -1311,7 +1337,7 @@ public class AlignFrame
     {
       return;
     }
-
+    //  TODO: preserve the ordering of displayed alignment annotation in any internal paste (particularly sequence associated annotation)
     SequenceI [] seqs = viewport.getSelectionAsNewSequence();
     String[] omitHidden = null;
 
@@ -1409,6 +1435,7 @@ public class AlignFrame
    */
   void paste(boolean newAlignment)
   {
+    boolean externalPaste=true;
     try
     {
       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
@@ -1451,102 +1478,175 @@ public class AlignFrame
       }
 
       SequenceI[] sequences;
-
+      boolean annotationAdded = false;
+      AlignmentI alignment = null;
 
      if(Desktop.jalviewClipboard!=null)
      {
        // The clipboard was filled from within Jalview, we must use the sequences
        // And dataset from the copied alignment
-       sequences = (SequenceI[])Desktop.jalviewClipboard[0];
+       SequenceI[] newseq = (SequenceI[])Desktop.jalviewClipboard[0];
+       // be doubly sure that we create *new* sequence objects.
+       sequences = new SequenceI[newseq.length];
+       for (int i=0;i<newseq.length;i++) {
+         sequences[i] = new Sequence(newseq[i]);
+       }
+       alignment = new Alignment(sequences);
+       externalPaste = false;
      }
      else
      {
-        sequences = new FormatAdapter().readFile(str, "Paste", format).
-            getSequencesArray();
+       // parse the clipboard as an alignment.
+       alignment = new FormatAdapter().readFile(str, "Paste", format);
+       sequences = alignment.getSequencesArray();
      }
 
-     AlignmentI alignment = null;
+     int alwidth=0;
 
-      if (newAlignment)
-      {
-          alignment = new Alignment(sequences);
+     if (newAlignment)
+     {
 
-          if (Desktop.jalviewClipboard != null)
-        {
-            alignment.setDataset( (Alignment) Desktop.jalviewClipboard[1]);
-        }
-          else
-        {
-            alignment.setDataset(null);
-      }
-      }
-      else
-      {
-        alignment = viewport.getAlignment();
+       if (Desktop.jalviewClipboard != null)
+       {
+         // dataset is inherited
+         alignment.setDataset( (Alignment) Desktop.jalviewClipboard[1]);
+       }
+       else
+       {
+         // new dataset is constructed
+         alignment.setDataset(null);
+       }
+       alwidth = alignment.getWidth()+1;
+     }
+     else
+     {
+       AlignmentI pastedal = alignment; // preserve pasted alignment object
+       // Add pasted sequences and dataset into existing alignment.
+       alignment = viewport.getAlignment();
+       alwidth = alignment.getWidth()+1;
+        // decide if we need to import sequences from an existing dataset
+        boolean importDs = Desktop.jalviewClipboard != null
+                && Desktop.jalviewClipboard[1] != alignment.getDataset();
+        // importDs==true instructs us to copy over new dataset sequences from
+        // an existing alignment
+        Vector newDs = (importDs) ? new Vector() : null; // used to create
+                                                          // minimum dataset set
 
-        //!newAlignment
-        SequenceI [] newseqs = new SequenceI[sequences.length];
         for (int i = 0; i < sequences.length; i++)
         {
-          newseqs[i] = new Sequence(sequences[i].getName(),
-                                    sequences[i].getSequence(),
-                                    sequences[i].getStart(),
-              sequences[i].getEnd());
-
-          alignment.addSequence(newseqs[i]);
+          if (importDs)
+          {
+            newDs.addElement(null);
+          }
+          SequenceI ds = sequences[i].getDatasetSequence(); // null for a simple
+                                                            // paste
+          if (importDs && ds != null)
+          {
+            if (!newDs.contains(ds))
+            {
+              newDs.setElementAt(ds, i);
+              ds = new Sequence(ds);
+              // update with new dataset sequence
+              sequences[i].setDatasetSequence(ds);
+            }
+            else
+            {
+              ds = sequences[newDs.indexOf(ds)].getDatasetSequence();
+            }
+          }
+          else
+          {
+            // copy and derive new dataset sequence
+            sequences[i] = sequences[i].deriveSequence();
+            alignment.getDataset().addSequence(sequences[i].getDatasetSequence());
+            // TODO: avoid creation of duplicate dataset sequences with a
+            // 'contains' method using SequenceI.equals()/SequenceI.contains()
+          }
+          alignment.addSequence(sequences[i]); // merges dataset
         }
-
-        /*
-         //ADD HISTORY ITEM
-         */
-        addHistoryItem(new EditCommand(
-            "Add sequences",
-            EditCommand.PASTE,
-            newseqs,
-            0,
-            alignment.getWidth(),
-            alignment)
-            );
-
-
-        viewport.setEndSeq(alignment.getHeight());
-        alignment.getWidth();
-        viewport.firePropertyChange("alignment", null, alignment.getSequences());
-      }
-
-
-
-      // Add any annotations attached to sequences
-      for (int i = 0; i < sequences.length; i++)
+        if (newDs != null)
+        {
+          newDs.clear(); // tidy up
+        }
+        if (pastedal.getAlignmentAnnotation()!=null) {
+          // Add any annotation attached to alignment.
+          AlignmentAnnotation[] alann = pastedal.getAlignmentAnnotation();
+          for (int i=0; i<alann.length; i++)
+          {
+            annotationAdded=true;
+            if (alann[i].sequenceRef==null && !alann[i].autoCalculated) {
+              AlignmentAnnotation newann = new AlignmentAnnotation(alann[i]);
+              newann.padAnnotation(alwidth);
+              alignment.addAnnotation(newann);
+            }
+          }
+        }
+     }
+     if (!newAlignment) {
+       ///////
+       // ADD HISTORY ITEM
+       //
+       addHistoryItem(new EditCommand(
+               "Add sequences",
+               EditCommand.PASTE,
+               sequences,
+               0,
+               alignment.getWidth(),
+               alignment)
+              );
+     }
+     // Add any annotations attached to sequences
+     for (int i = 0; i < sequences.length; i++)
      {
        if (sequences[i].getAnnotation() != null)
        {
          for (int a = 0; a < sequences[i].getAnnotation().length; a++)
          {
-           AlignmentAnnotation newAnnot =
-               new AlignmentAnnotation(
-                   sequences[i].getAnnotation()[a].label,
-                   sequences[i].getAnnotation()[a].description,
-                   sequences[i].getAnnotation()[a].annotations,
-                   sequences[i].getAnnotation()[a].graphMin,
-                   sequences[i].getAnnotation()[a].graphMax,
-                   sequences[i].getAnnotation()[a].graph);
-
-           sequences[i].getAnnotation()[a] = newAnnot;
-           newAnnot.sequenceMapping = sequences[i].getAnnotation()[a].
-               sequenceMapping;
-           newAnnot.sequenceRef = sequences[i];
-           newAnnot.adjustForAlignment();
-           alignment.addAnnotation(newAnnot);
-           alignment.setAnnotationIndex(newAnnot, a);
+           annotationAdded=true;
+           sequences[i].getAnnotation()[a].adjustForAlignment();
+           sequences[i].getAnnotation()[a].padAnnotation(alwidth);
+           alignment.addAnnotation(sequences[i].getAnnotation()[a]); // annotation was duplicated earlier
+           alignment.setAnnotationIndex(sequences[i].getAnnotation()[a], a);
          }
-
-         alignPanel.annotationPanel.adjustPanelHeight();
        }
      }
+     if (!newAlignment) {
 
-     if(newAlignment)
-     {
+       // propagate alignment changed.
+       viewport.setEndSeq(alignment.getHeight());
+       if (annotationAdded)
+       {
+         // Duplicate sequence annotation in all views.
+         AlignmentI[] alview = this.getViewAlignments();
+         for (int i = 0; i < sequences.length; i++)
+         {
+           AlignmentAnnotation sann[] = sequences[i].getAnnotation();
+           if (sann == null)
+             continue;
+           for (int avnum=0;avnum<alview.length; avnum++)
+           {
+             if (alview[avnum]!=alignment)
+             {
+               // duplicate in a view other than the one with input focus
+               int avwidth = alview[avnum].getWidth()+1;
+               // this relies on sann being preserved after we 
+               // modify the sequence's annotation array for each duplication
+               for (int a=0; a<sann.length; a++)
+               {
+                 AlignmentAnnotation newann = new AlignmentAnnotation(sann[a]);
+                 sequences[i].addAlignmentAnnotation(newann);
+                 newann.padAnnotation(avwidth);
+                 alview[avnum].addAnnotation(newann); // annotation was duplicated earlier
+                 alview[avnum].setAnnotationIndex(newann, a);
+               }
+             }
+           }
+         }
+         buildSortByAnnotationScoresMenu();
+       }
+       viewport.firePropertyChange("alignment", null, alignment.getSequences());
+
+     } else {
        AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH, DEFAULT_HEIGHT);
        String newtitle = new String("Copied sequences");
 
@@ -1565,14 +1665,18 @@ public class AlignFrame
        af.alignPanel.seqPanel.seqCanvas.getFeatureRenderer().transferSettings(
            alignPanel.seqPanel.seqCanvas.getFeatureRenderer());
 
-
-       if (title.startsWith("Copied sequences"))
-       {
-         newtitle = title;
-       }
-       else
-       {
-         newtitle = newtitle.concat("- from " + title);
+       // TODO: maintain provenance of an alignment, rather than just make the title a concatenation of operations.
+       if (!externalPaste) {
+         if (title.startsWith("Copied sequences"))
+         {
+           newtitle = title;
+         }
+         else
+         {
+           newtitle = newtitle.concat("- from " + title);
+         }
+       } else {
+         newtitle = new String("Pasted sequences");
        }
 
        Desktop.addInternalFrame(af, newtitle, DEFAULT_WIDTH,
@@ -1970,6 +2074,8 @@ public class AlignFrame
     AlignmentPanel newap =
         new Jalview2XML().copyAlignPanel(alignPanel, true);
 
+    newap.av.gatherViewsHere = false;
+
     if (viewport.viewName == null)
     {
       viewport.viewName = "Original";
@@ -2214,6 +2320,65 @@ public class AlignFrame
     alignPanel.setAnnotationVisible(annotationPanelMenuItem.isSelected());
   }
 
+  public void alignmentProperties()
+  {
+    JEditorPane editPane = new JEditorPane("text/html","");
+    editPane.setEditable(false);
+    StringBuffer contents = new StringBuffer("<html>");
+
+    float avg  = 0;
+    int min=Integer.MAX_VALUE, max=0;
+    for(int i=0; i<viewport.alignment.getHeight(); i++)
+    {
+      int size = viewport.alignment.getSequenceAt(i).getEnd()
+          -viewport.alignment.getSequenceAt(i).getStart();
+      avg += size;
+      if(size>max)
+        max = size;
+      if(size<min)
+        min = size;
+    }
+    avg = avg/(float)viewport.alignment.getHeight();
+
+    contents.append("<br>Sequences: "+ viewport.alignment.getHeight());
+    contents.append("<br>Minimum Sequence Length: "+min);
+    contents.append("<br>Maximum Sequence Length: "+max);
+    contents.append("<br>Average Length: "+(int)avg);
+
+    if (((Alignment)viewport.alignment).getProperties() != null)
+    {
+      Hashtable props = ((Alignment)viewport.alignment).getProperties();
+      Enumeration en = props.keys();
+      contents.append("<br><br><table border=\"1\">");
+      while(en.hasMoreElements())
+      {
+        String key = en.nextElement().toString();
+        StringBuffer val = new StringBuffer();
+        String vals = props.get(key).toString();
+        int pos=0, npos;
+        do {
+          npos = vals.indexOf("\n",pos);
+          if (npos==-1)
+          {
+            val.append(vals.substring(pos));
+          } else {
+            val.append(vals.substring(pos, npos));
+            val.append("<br>");
+          }
+          pos = npos+1;
+        } while (npos!=-1);
+        contents.append("<tr><td>"+key+"</td><td>"+val+"</td></tr>");
+      }
+      contents.append("</table>");
+    }
+    editPane.setText(contents.toString()+"</html>");
+    JInternalFrame frame = new JInternalFrame();
+    frame.getContentPane().add(new JScrollPane(editPane));
+
+    Desktop.instance.addInternalFrame(frame,"Alignment Properties: "+getTitle(),500,400);
+  }
+
+
   /**
    * DOCUMENT ME!
    *
@@ -2720,7 +2885,6 @@ public class AlignFrame
 
     alignPanel.paintAlignment(true);
   }
-
   /**
    * DOCUMENT ME!
    *
@@ -2938,6 +3102,73 @@ public class AlignFrame
       }
     });
   }
+  /**
+   * Add a new sort by annotation score menu item
+   * @param sort the menu to add the option to
+   * @param scoreLabel the label used to retrieve scores for each sequence on the alignment
+   */
+  public void addSortByAnnotScoreMenuItem(JMenu sort, final String scoreLabel)
+  {
+    final JMenuItem item = new JMenuItem(scoreLabel);
+    sort.add(item);
+    item.addActionListener(new java.awt.event.ActionListener()
+    {
+      public void actionPerformed(ActionEvent e)
+      {
+        SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
+        AlignmentSorter.sortByAnnotationScore(scoreLabel, viewport.getAlignment());
+        addHistoryItem(new OrderCommand("Sort by "+scoreLabel, oldOrder, viewport.alignment));
+        alignPanel.paintAlignment(true);
+      }
+    });
+  }
+  /**
+   * last hash for alignment's annotation array - used to minimise cost of rebuild.
+   */
+  protected int _annotationScoreVectorHash;
+  /**
+   * search the alignment and rebuild the sort by annotation score submenu
+   * the last alignment annotation vector hash is stored to minimize
+   * cost of rebuilding in subsequence calls.
+   *
+   */
+  public void buildSortByAnnotationScoresMenu()
+  {
+    if(viewport.alignment.getAlignmentAnnotation()==null)
+    {
+      return;
+    }
+
+    if (viewport.alignment.getAlignmentAnnotation().hashCode()!=_annotationScoreVectorHash)
+    {
+      sortByAnnotScore.removeAll();
+      // almost certainly a quicker way to do this - but we keep it simple
+      Hashtable scoreSorts=new Hashtable();
+      AlignmentAnnotation aann[];
+      Enumeration sq = viewport.alignment.getSequences().elements();
+      while (sq.hasMoreElements())
+      {
+        aann = ((SequenceI) sq.nextElement()).getAnnotation();
+        for (int i=0;aann!=null && i<aann.length; i++)
+        {
+          if (aann[i].hasScore() && aann[i].sequenceRef!=null)
+          {
+            scoreSorts.put(aann[i].label, aann[i].label);
+          }
+        }
+      }
+      Enumeration labels = scoreSorts.keys();
+      while (labels.hasMoreElements())
+      {
+        addSortByAnnotScoreMenuItem(sortByAnnotScore, (String) labels.nextElement());
+      }
+      sortByAnnotScore.setVisible(scoreSorts.size()>0);
+      scoreSorts.clear();
+
+      _annotationScoreVectorHash =
+          viewport.alignment.getAlignmentAnnotation().hashCode();
+    }
+  }
 
   /**
    * Maintain the Order by->Displayed Tree menu.
@@ -3267,7 +3498,7 @@ public class AlignFrame
         }
         wsmenu.add(secstrmenu);
       }
-      this.webService.removeAll();
+      resetWebServiceMenu();
       for (int i = 0, j = wsmenu.size(); i < j; i++)
       {
         webService.add( (JMenu) wsmenu.get(i));
@@ -3275,7 +3506,7 @@ public class AlignFrame
     }
     else
     {
-      this.webService.removeAll();
+      resetWebServiceMenu();
       this.webService.add(this.webServiceNoServices);
     }
     // TODO: add in rediscovery function
@@ -3283,6 +3514,31 @@ public class AlignFrame
     // TODO: group services by location as well as function.
   }
 
+
+  /**
+   * empty the web service menu and add any ad-hoc functions
+   * not dynamically discovered.
+   *
+   */
+  private void resetWebServiceMenu()
+  {
+    webService.removeAll();
+    // Temporary hack - DBRef Fetcher always top level ws entry.
+    JMenuItem rfetch = new JMenuItem("Fetch DB References");
+    rfetch.setToolTipText("Retrieve and parse uniprot records for the alignment or the currently selected sequences");
+    webService.add(rfetch);
+    rfetch.addActionListener(new ActionListener() {
+
+      public void actionPerformed(ActionEvent e)
+      {
+        new jalview.ws.DBRefFetcher(
+                alignPanel.av.getSequenceSelection(),
+                alignPanel.alignFrame).fetchDBRefs(false);
+      }
+
+    });
+  }
+
  /* public void vamsasStore_actionPerformed(ActionEvent e)
   {
     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
@@ -3301,27 +3557,153 @@ public class AlignFrame
       vs.storeJalview( chooser.getSelectedFile().getAbsolutePath(), this);
     }
   }*/
+  /**
+   * prototype of an automatically enabled/disabled analysis function
+   *
+   */
+  protected void setShowProductsEnabled()
+  {
+    SequenceI [] selection = viewport.getSequenceSelection();
+    if (canShowProducts(selection, viewport.getSelectionGroup()!=null, viewport.getAlignment().getDataset()))
+    {
+      showProducts.setEnabled(true);
+      
+    } else {
+      showProducts.setEnabled(false);
+    }
+  }
+  /**
+   * search selection for sequence xRef products and build the
+   * show products menu.
+   * @param selection
+   * @param dataset
+   * @return true if showProducts menu should be enabled.
+   */
+  public boolean canShowProducts(SequenceI[] selection, boolean isRegionSelection, Alignment dataset)
+  {
+    boolean showp=false;
+    try {
+      showProducts.removeAll();
+      final boolean dna = viewport.getAlignment().isNucleotide();
+      final Alignment ds = dataset;
+      String[] ptypes = CrossRef.findSequenceXrefTypes(dna, selection, dataset);
+      //Object[] prods = CrossRef.buildXProductsList(viewport.getAlignment().isNucleotide(), selection, dataset, true);
+      final SequenceI[] sel = selection;
+      for (int t=0; ptypes!=null && t<ptypes.length; t++)
+      {
+        showp=true;
+        final boolean isRegSel = isRegionSelection;
+        final AlignFrame af = this;
+        final String source = ptypes[t];
+        JMenuItem xtype = new JMenuItem(ptypes[t]);
+        xtype.addActionListener(new ActionListener() {
+
+          public void actionPerformed(ActionEvent e)
+          {
+            af.showProductsFor(sel, ds, isRegSel, dna, source);
+          }
+          
+        });
+        showProducts.add(xtype);
+      }
+      showProducts.setVisible(showp);
+      showProducts.setEnabled(showp);
+    } catch (Exception e)
+    {
+      jalview.bin.Cache.log.warn("canTranslate threw an exception - please report to help@jalview.org",e);
+     return false;
+    }
+    return showp;
+  }
+protected void showProductsFor(SequenceI[] sel, Alignment ds, boolean isRegSel, boolean dna, String source)
+  {
+  ds = this.getViewport().alignment.getDataset(); // update our local dataset reference
+  Alignment prods = CrossRef.findXrefSequences(sel, dna, source, ds);
+  if (prods!=null)
+  {
+    SequenceI[] sprods = new SequenceI[prods.getHeight()];
+    for (int s=0; s<sprods.length;s++)
+    {
+      sprods[s] = (prods.getSequenceAt(s)).deriveSequence();
+      if (ds.getSequences()==null || !ds.getSequences().contains(sprods[s].getDatasetSequence()))
+        ds.addSequence(sprods[s].getDatasetSequence());
+    }
+    Alignment al = new Alignment(sprods);
+    AlignedCodonFrame[] cf = prods.getCodonFrames();
+    for (int s=0; cf!=null && s<cf.length; s++)
+    {
+      al.addCodonFrame(cf[s]);
+      cf[s] = null;
+    }
+    al.setDataset(ds);
+    AlignFrame naf = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
+    String newtitle =""+((dna) ? "Proteins " : "Nucleotides ") + " for "+((isRegSel) ? "selected region of " : "")
+            + getTitle();
+    Desktop.addInternalFrame(naf, newtitle, DEFAULT_WIDTH,
+            DEFAULT_HEIGHT);
+  } else {
+    System.err.println("No Sequences generated for xRef type "+source);
+  }
+  }
 
 
+public boolean canShowTranslationProducts(SequenceI[] selection, AlignmentI alignment)
+{
+  // old way
+  try {
+      return (jalview.analysis.Dna.canTranslate(selection, viewport.getViewAsVisibleContigs(true)));
+  } catch (Exception e)
+  {
+    jalview.bin.Cache.log.warn("canTranslate threw an exception - please report to help@jalview.org",e);
+   return false;
+  }
+}
 
+public void showProducts_actionPerformed(ActionEvent e)
+{
+  ///////////////////////////////
+  // Collect Data to be translated/transferred
+  
+  SequenceI [] selection = viewport.getSequenceSelection();
+  AlignmentI al  = null;
+  try {
+      al = jalview.analysis.Dna.CdnaTranslate(selection, viewport.getViewAsVisibleContigs(true),
+          viewport.getGapCharacter(), viewport.getAlignment().getDataset());
+    } catch (Exception ex) {
+      al = null;
+      jalview.bin.Cache.log.debug("Exception during translation.",ex);
+    }
+    if (al==null)
+    {
+      JOptionPane.showMessageDialog(Desktop.desktop,
+          "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
+          "Translation Failed",
+          JOptionPane.WARNING_MESSAGE);
+    } else {
+      AlignFrame af = new AlignFrame(al, DEFAULT_WIDTH, DEFAULT_HEIGHT);
+      Desktop.addInternalFrame(af, "Translation of "+this.getTitle(),
+                               DEFAULT_WIDTH,
+                               DEFAULT_HEIGHT);
+    }
+  }
 
 public void showTranslation_actionPerformed(ActionEvent e)
 {
   ///////////////////////////////
   // Collect Data to be translated/transferred
-    
-  SequenceI [] selection = viewport.getSelectionAsNewSequence();
+
+  SequenceI [] selection = viewport.getSequenceSelection();
   String [] seqstring = viewport.getViewAsString(true);
   AlignmentI al  = null;
   try {
-    al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring, viewport.getViewAsVisibleContigs(true), 
-        viewport.getGapCharacter(), viewport.alignment.getAlignmentAnnotation(), 
-        viewport.alignment.getWidth());
+    al = jalview.analysis.Dna.CdnaTranslate(selection, seqstring, viewport.getViewAsVisibleContigs(true),
+        viewport.getGapCharacter(), viewport.alignment.getAlignmentAnnotation(),
+        viewport.alignment.getWidth(), viewport.getAlignment().getDataset());
   } catch (Exception ex) {
     al = null;
     jalview.bin.Cache.log.debug("Exception during translation.",ex);
   }
-  if (al==null)   
+  if (al==null)
   {
     JOptionPane.showMessageDialog(Desktop.desktop,
         "Please select at least three bases in at least one sequence in order to perform a cDNA translation.",
@@ -3484,6 +3866,7 @@ public void drop(DropTargetDropEvent evt)
       {
         // (isAnnotation)
         alignPanel.adjustAnnotationHeight();
+        buildSortByAnnotationScoresMenu();
       }
 
     }
@@ -3525,6 +3908,19 @@ public void drop(DropTargetDropEvent evt)
   {
     return viewport;
   }
+
+
+  /**
+   * Open the dialog for regex description parsing.
+   */
+  protected void extractScores_actionPerformed(ActionEvent e)
+  {
+    ParseProperties pp = new jalview.analysis.ParseProperties(viewport.alignment);
+    if (pp.getScoresFromDescription("col", "score column ", "\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)\\W+([-+]?\\d*\\.?\\d*e?-?\\d*)")>0)
+    {
+      buildSortByAnnotationScoresMenu();
+    }
+  }
 }
 
 class PrintThread