getContentPane().add alignmentProperties popup.
[jalview.git] / src / jalview / gui / AlignFrame.java
index c0271ac..edd8cec 100755 (executable)
@@ -112,8 +112,6 @@ public class AlignFrame
 
   void init()
   {
-    this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
-
     if (viewport.conservation == null)
     {
       BLOSUM62Colour.setEnabled(false);
@@ -137,6 +135,7 @@ public class AlignFrame
 
     if (Desktop.desktop != null)
    {
+     this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
      addServiceListeners();
      setGUINucleotide(viewport.alignment.isNucleotide());
    }
@@ -170,12 +169,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())
           {
@@ -849,7 +851,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 +911,8 @@ public class AlignFrame
     new AnnotationExporter().exportAnnotations(
       alignPanel,
         viewport.showAnnotation ? viewport.alignment.getAlignmentAnnotation() : null,
-      viewport.alignment.getGroups()
+      viewport.alignment.getGroups(),
+      ((Alignment)viewport.alignment).alignmentProperties
         );
   }
 
@@ -962,7 +965,7 @@ public class AlignFrame
             PaintRefresher.RemoveComponent(ap.seqPanel.seqCanvas);
             PaintRefresher.RemoveComponent(ap.idPanel.idCanvas);
             PaintRefresher.RemoveComponent(ap);
-            ap.av.alignment.destroyAlignment();
+            ap.av.alignment = null;
           }
         }
         else
@@ -973,7 +976,7 @@ public class AlignFrame
           PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
           PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
           PaintRefresher.RemoveComponent(alignPanel);
-          alignPanel.av.alignment.destroyAlignment();
+          viewport.alignment = null;
           alignPanel = null;
           viewport = null;
 
@@ -1307,7 +1310,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;
 
@@ -1405,6 +1408,7 @@ public class AlignFrame
    */
   void paste(boolean newAlignment)
   {
+    boolean externalPaste=true;
     try
     {
       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
@@ -1447,102 +1451,149 @@ 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)
+       {
+         alignPanel.annotationPanel.adjustPanelHeight();
+       }
+       viewport.firePropertyChange("alignment", null, alignment.getSequences());
+     } else {
        AlignFrame af = new AlignFrame(alignment, DEFAULT_WIDTH, DEFAULT_HEIGHT);
        String newtitle = new String("Copied sequences");
 
@@ -1561,14 +1612,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,
@@ -2212,6 +2267,51 @@ 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).alignmentProperties != null)
+    {
+      Hashtable props = ((Alignment)viewport.alignment).alignmentProperties;
+      Enumeration en = props.keys();
+      contents.append("<br><br><table border=\"1\">");
+      while(en.hasMoreElements())
+      {
+        String key = en.nextElement().toString();
+        contents.append("<tr><td>"+key+"</td><td>"+props.get(key)+"</td></tr>");
+      }
+      contents.append("</table>");
+    }
+    editPane.setText(contents.toString()+"</html>");
+    JInternalFrame frame = new JInternalFrame();
+    frame.getContentPane().add(editPane);
+
+    Desktop.instance.addInternalFrame(frame,"Alignment Properties: "+getTitle(),500,400);
+  }
+
+
   /**
    * DOCUMENT ME!
    *
@@ -3265,7 +3365,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));
@@ -3273,7 +3373,7 @@ public class AlignFrame
     }
     else
     {
-      this.webService.removeAll();
+      resetWebServiceMenu();
       this.webService.add(this.webServiceNoServices);
     }
     // TODO: add in rediscovery function
@@ -3281,6 +3381,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.io.DBRefFetcher(
+                alignPanel.av.getSequenceSelection(),
+                alignPanel.alignFrame).fetchDBRefs(false);
+      }
+
+    });
+  }
+
  /* public void vamsasStore_actionPerformed(ActionEvent e)
   {
     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
@@ -3302,13 +3427,12 @@ public class AlignFrame
 
 
 
-
 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 {