getContentPane().add alignmentProperties popup.
[jalview.git] / src / jalview / gui / AlignFrame.java
index 27503f9..edd8cec 100755 (executable)
@@ -1,6 +1,6 @@
 /*
  * Jalview - A Sequence Alignment Editor and Viewer
- * Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
+ * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
  *
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
@@ -24,19 +24,18 @@ import java.util.*;
 
 import java.awt.*;
 import java.awt.datatransfer.*;
+import java.awt.dnd.*;
 import java.awt.event.*;
 import java.awt.print.*;
 import javax.swing.*;
 
 import jalview.analysis.*;
+import jalview.commands.*;
 import jalview.datamodel.*;
 import jalview.io.*;
 import jalview.jbgui.*;
 import jalview.schemes.*;
-import jalview.util.ShiftList;
 import jalview.ws.*;
-import java.awt.dnd.*;
-import org.biojava.dasobert.eventmodel.*;
 
 /**
  * DOCUMENT ME!
@@ -45,7 +44,7 @@ import org.biojava.dasobert.eventmodel.*;
  * @version $Revision$
  */
 public class AlignFrame
-    extends GAlignFrame implements DropTargetListener, FeatureListener
+    extends GAlignFrame implements DropTargetListener
 {
   /** DOCUMENT ME!! */
   public static final int DEFAULT_WIDTH = 700;
@@ -53,17 +52,17 @@ public class AlignFrame
   /** DOCUMENT ME!! */
   public static final int DEFAULT_HEIGHT = 500;
   public AlignmentPanel alignPanel;
-  AlignViewport viewport;
 
+  AlignViewport viewport;
 
   Vector alignPanels = new Vector();
 
 
   /** DOCUMENT ME!! */
-  public String currentFileFormat = null;
-  Stack historyList = new Stack();
-  Stack redoList = new Stack();
-  private int treeCount = 0;
+  String currentFileFormat = null;
+
+  String fileName = null;
+
 
   /**
    * Creates a new AlignFrame object.
@@ -94,7 +93,7 @@ public class AlignFrame
       al.setDataset(null);
     }
 
-    addAlignmentPanel(alignPanel);
+    addAlignmentPanel(alignPanel, true);
     init();
   }
 
@@ -107,104 +106,81 @@ public class AlignFrame
   {
     viewport = ap.av;
     alignPanel = ap;
-    addAlignmentPanel(ap);
+    addAlignmentPanel(ap, false);
     init();
   }
 
   void init()
   {
-    this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
-
-    if (viewport.hconsensus == null)
+    if (viewport.conservation == null)
     {
-      //Out of memory calculating consensus.
       BLOSUM62Colour.setEnabled(false);
-      PIDColour.setEnabled(false);
       conservationMenuItem.setEnabled(false);
       modifyConservation.setEnabled(false);
-      abovePIDThreshold.setEnabled(false);
-      modifyPID.setEnabled(false);
+    //  PIDColour.setEnabled(false);
+    //  abovePIDThreshold.setEnabled(false);
+    //  modifyPID.setEnabled(false);
     }
 
     String sortby = jalview.bin.Cache.getDefault("SORT_ALIGNMENT", "No sort");
 
     if (sortby.equals("Id"))
+    {
       sortIDMenuItem_actionPerformed(null);
+    }
     else if (sortby.equals("Pairwise Identity"))
+    {
       sortPairwiseMenuItem_actionPerformed(null);
+    }
 
     if (Desktop.desktop != null)
    {
+     this.setDropTarget(new java.awt.dnd.DropTarget(this, this));
      addServiceListeners();
      setGUINucleotide(viewport.alignment.isNucleotide());
    }
 
-   if (jalview.bin.Cache.getDefault("WRAP_ALIGNMENT", false))
+   setMenusFromViewport(viewport);
+
+   if (viewport.wrapAlignment)
    {
-     wrapMenuItem.setSelected(true);
      wrapMenuItem_actionPerformed(null);
    }
 
+    if (jalview.bin.Cache.getDefault("SHOW_OVERVIEW",false))
+    {
+      this.overviewMenuItem_actionPerformed(null);
+    }
+
    addKeyListener();
+
+  }
+
+  public void setFileName(String file, String format)
+  {
+     fileName = file;
+     currentFileFormat = format;
+     reload.setEnabled(true);
   }
 
   void addKeyListener()
   {
-      final AlignFrame af = this;
       addKeyListener(new KeyAdapter()
       {
         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())
           {
-            case KeyEvent.VK_V:
-              if (!evt.isControlDown())
-              {
-                AlignmentI al;
-                if(viewport.hasHiddenRows)
-                {
-                  al = viewport.alignment.getHiddenSequences().getFullAlignment();
-                }
-                else
-                  al = new Alignment(viewport.alignment.getSequencesArray());
-
-                AlignViewport newview = new AlignViewport(al);
-
-                AlignmentPanel copy = new AlignmentPanel(af, newview);
-
-                if(viewport.viewName==null)
-                  viewport.viewName="View 1";
-
-                copy.av.sequenceSetID = viewport.getSequenceSetId();
-                copy.av.viewName = "View " +
-                    (Desktop.getViewCount(viewport.getSequenceSetId())+1);
-
-
-                addAlignmentPanel(copy);
-                PaintRefresher.Register(copy, viewport.getSequenceSetId());
-                PaintRefresher.Register(alignPanel,
-                                        viewport.getSequenceSetId());
-
-              }
-              break;
-            case KeyEvent.VK_G:
-              Desktop.instance.gatherViews(af);
-              break;
-
-            case KeyEvent.VK_X:
-              if (!evt.isControlDown())
-              {
-                Desktop.instance.explodeViews(af);
-              }
-              break;
-
 
             case 27: // escape key
               deselectAllSequenceMenuItem_actionPerformed(null);
@@ -212,35 +188,36 @@ public class AlignFrame
               break;
 
             case KeyEvent.VK_DOWN:
+             if (evt.isAltDown() || !viewport.cursorMode)
+              moveSelectedSequences(false);
               if (viewport.cursorMode)
-              {
                 alignPanel.seqPanel.moveCursor(0, 1);
-              }
-              else
-                moveSelectedSequences(false);
               break;
 
             case KeyEvent.VK_UP:
+            if (evt.isAltDown() || !viewport.cursorMode)
+              moveSelectedSequences(true);
               if (viewport.cursorMode)
-              {
                 alignPanel.seqPanel.moveCursor(0, -1);
-              }
-              else
-                moveSelectedSequences(true);
+
               break;
 
             case KeyEvent.VK_LEFT:
-              if (viewport.cursorMode)
-              {
+            if (evt.isAltDown() || !viewport.cursorMode)
+              slideSequences(false,
+                             alignPanel.seqPanel.getKeyboardNo1());
+            else
                 alignPanel.seqPanel.moveCursor( -1, 0);
-              }
+
+
               break;
 
             case KeyEvent.VK_RIGHT:
-              if (viewport.cursorMode)
-              {
+            if (evt.isAltDown() || !viewport.cursorMode)
+              slideSequences(true,
+                             alignPanel.seqPanel.getKeyboardNo1());
+            else
                 alignPanel.seqPanel.moveCursor(1, 0);
-              }
               break;
 
             case KeyEvent.VK_SPACE:
@@ -259,9 +236,11 @@ public class AlignFrame
                 cut_actionPerformed(null);
               }
               else
+            {
                 alignPanel.seqPanel.deleteGapAtCursor(evt.isControlDown()
                                            || evt.isShiftDown()
                                            || evt.isAltDown());
+            }
 
               break;
 
@@ -344,14 +323,17 @@ public class AlignFrame
               SequenceGroup sg = viewport.getSelectionGroup();
               if (toggleSeqs)
               {
-                if (sg != null && sg.getSize(false) != viewport.alignment.getHeight())
+                if (sg != null && sg.getSize() != viewport.alignment.getHeight())
                 {
                   hideSelSequences_actionPerformed(null);
                   hide = true;
                 }
-                else if (! (toggleCols && viewport.colSel.getSelected().size() > 0))
+              else if (! (toggleCols &&
+                          viewport.colSel.getSelected().size() > 0))
+              {
                   showAllSeqs_actionPerformed(null);
               }
+            }
 
               if (toggleCols)
               {
@@ -359,44 +341,77 @@ public class AlignFrame
                 {
                   hideSelColumns_actionPerformed(null);
                   if (!toggleSeqs)
+                {
                     viewport.selectionGroup = sg;
                 }
+              }
                 else if (!hide)
+              {
                   showAllColumns_actionPerformed(null);
               }
+            }
               break;
             }
             case KeyEvent.VK_PAGE_UP:
               if (viewport.wrapAlignment)
+            {
                 alignPanel.scrollUp(true);
+            }
               else
+            {
                 alignPanel.setScrollValues(viewport.startRes,
                                            viewport.startSeq
                                            - viewport.endSeq + viewport.startSeq);
+            }
               break;
             case KeyEvent.VK_PAGE_DOWN:
               if (viewport.wrapAlignment)
+            {
                 alignPanel.scrollUp(false);
+            }
               else
+            {
                 alignPanel.setScrollValues(viewport.startRes,
                                            viewport.startSeq
                                            + viewport.endSeq - viewport.startSeq);
+            }
               break;
-
-
           }
         }
+
+      public void keyReleased(KeyEvent evt)
+      {
+        switch(evt.getKeyCode())
+        {
+          case KeyEvent.VK_LEFT:
+            if (evt.isAltDown() || !viewport.cursorMode)
+              viewport.firePropertyChange("alignment", null,
+                                          viewport.getAlignment().getSequences());
+            break;
+
+          case KeyEvent.VK_RIGHT:
+            if (evt.isAltDown() || !viewport.cursorMode)
+              viewport.firePropertyChange("alignment", null,
+                                          viewport.getAlignment().getSequences());
+            break;
+        }
+      }
       });
   }
 
 
-  public void addAlignmentPanel(final AlignmentPanel ap)
+  public void addAlignmentPanel(final AlignmentPanel ap,
+                                boolean newPanel)
   {
+    ap.alignFrame = this;
+
     alignPanels.addElement(ap);
 
+    PaintRefresher.Register(ap, ap.av.getSequenceSetId());
+
     int aSize = alignPanels.size();
 
-   tabbedPane.setVisible(aSize>1 || ap.av.viewName!=null);
+    tabbedPane.setVisible(aSize>1 || ap.av.viewName!=null);
 
     if (aSize == 1 && ap.av.viewName==null)
     {
@@ -406,34 +421,36 @@ public class AlignFrame
     {
       if (aSize == 2)
       {
-        AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
-        tabbedPane.addTab(first.av.viewName==null?"Original":first.av.viewName,first);
-
-        this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
+        setInitialTabVisible();
       }
 
-      tabbedPane.addTab(ap.av.viewName==null?"Original":ap.av.viewName, ap);
-    }
-
-    ap.av.updateConsensus(ap);
-    ap.av.updateConservation(ap);
+      expandViews.setEnabled(true);
+      gatherViews.setEnabled(true);
+      tabbedPane.addTab(ap.av.viewName, ap);
 
+      ap.setVisible(false);
+    }
 
-    ap.av.addPropertyChangeListener(new PropertyChangeListener()
+    if(newPanel)
     {
-     public void propertyChange(PropertyChangeEvent evt)
-     {
-       if (evt.getPropertyName().equals("alignment"))
-       {
-         PaintRefresher.Refresh(ap, ap.av.getSequenceSetId());
-         alignmentChanged();
-       }
-     }
-   });
-
+      if (ap.av.padGaps)
+      {
+        ap.av.alignment.padGaps();
+      }
+      ap.av.updateConservation(ap);
+      ap.av.updateConsensus(ap);
+    }
   }
 
-
+  public void setInitialTabVisible()
+  {
+    expandViews.setEnabled(true);
+    gatherViews.setEnabled(true);
+    tabbedPane.setVisible(true);
+    AlignmentPanel first = (AlignmentPanel) alignPanels.firstElement();
+    tabbedPane.addTab(first.av.viewName,first);
+    this.getContentPane().add(tabbedPane, BorderLayout.CENTER);
+  }
 
 
   public AlignViewport getViewport()
@@ -469,7 +486,7 @@ public class AlignFrame
       {
         // System.out.println("deregistering discoverer listener");
         Desktop.discoverer.removePropertyChangeListener(thisListener);
-        closeMenuItem_actionPerformed(null);
+        closeMenuItem_actionPerformed(true);
       }
       ;
     });
@@ -478,10 +495,8 @@ public class AlignFrame
   public void setGUINucleotide(boolean nucleotide)
   {
     showTranslation.setVisible( nucleotide );
-    //sequenceFeatures.setVisible(!nucleotide );
-    //featureSettings.setVisible( !nucleotide );
-    conservationMenuItem.setVisible( !nucleotide );
-    modifyConservation.setVisible(   !nucleotide );
+    conservationMenuItem.setEnabled( !nucleotide );
+    modifyConservation.setEnabled(   !nucleotide );
 
     //Remember AlignFrame always starts as protein
     if(!nucleotide)
@@ -490,23 +505,46 @@ public class AlignFrame
     }
   }
 
-  public void comeBackLater(FeatureEvent evt)
-  {}
+  /**
+   * Need to call this method when tabs are selected for multiple views,
+   * or when loading from Jalview2XML.java
+   * @param av AlignViewport
+   */
+  void setMenusFromViewport(AlignViewport av)
+  {
+    padGapsMenuitem.setSelected(av.padGaps);
+    colourTextMenuItem.setSelected(av.showColourText);
+    abovePIDThreshold.setSelected(av.getAbovePIDThreshold());
+    conservationMenuItem.setSelected(av.getConservationSelected());
+    seqLimits.setSelected(av.getShowJVSuffix());
+    idRightAlign.setSelected(av.rightAlignIds);
+    renderGapsMenuItem.setSelected(av.renderGaps);
+    wrapMenuItem.setSelected(av.wrapAlignment);
+    scaleAbove.setVisible(av.wrapAlignment);
+    scaleLeft.setVisible(av.wrapAlignment);
+    scaleRight.setVisible(av.wrapAlignment);
+    annotationPanelMenuItem.setState(av.showAnnotation);
+    viewBoxesMenuItem.setSelected(av.showBoxes);
+    viewTextMenuItem.setSelected(av.showText);
+
+    setColourSelected(ColourSchemeProperty.
+                      getColourName(av.getGlobalColourScheme()));
+
+    showSeqFeatures.setSelected(av.showSequenceFeatures);
+    hiddenMarkers.setState(av.showHiddenMarkers);
+    applyToAllGroups.setState(av.colourAppliesToAllGroups);
 
-  public void newFeatures(FeatureEvent evt)
-  {
-    if (evt.getFeatures().length > 0)
-    {
-      alignPanel.seqPanel.seqCanvas.fr.featuresAdded();
-      alignPanel.repaint();
-    }
+    updateEditMenuBar();
   }
 
+
   Hashtable progressBars;
   public void setProgressBar(String message, long id)
   {
     if(progressBars == null)
+    {
       progressBars = new Hashtable();
+    }
 
     JPanel progressPanel;
     GridLayout layout = (GridLayout) statusPanel.getLayout();
@@ -517,7 +555,9 @@ public class AlignFrame
        progressBars.remove( progressPanel );
        progressPanel = null;
        if(message!=null)
+      {
          statusBar.setText(message);
+      }
 
        layout.setRows(layout.getRows() - 1);
      }
@@ -541,6 +581,8 @@ public class AlignFrame
   }
 
 
+
+
   /*
    Added so Castor Mapping file can obtain Jalview Version
   */
@@ -565,6 +607,52 @@ public class AlignFrame
     Desktop.instance.inputLocalFileMenuItem_actionPerformed(viewport);
   }
 
+  public void reload_actionPerformed(ActionEvent e)
+  {
+    if(fileName!=null)
+    {
+      if(currentFileFormat.equals("Jalview"))
+      {
+        JInternalFrame [] frames = Desktop.desktop.getAllFrames();
+        for(int i=0; i<frames.length; i++)
+        {
+          if (frames[i] instanceof AlignFrame
+              && frames[i] != this
+              && ( (AlignFrame) frames[i]).fileName.equals(fileName))
+          {
+            try
+            {
+              frames[i].setSelected(true);
+              Desktop.instance.closeAssociatedWindows();
+          }
+            catch (java.beans.PropertyVetoException ex)
+            {}
+          }
+
+        }
+        Desktop.instance.closeAssociatedWindows();
+
+        FileLoader loader = new FileLoader();
+        String protocol = fileName.startsWith("http:")? "URL":"File";
+        loader.LoadFile(viewport, fileName, protocol, currentFileFormat);
+      }
+      else
+      {
+        Rectangle bounds = this.getBounds();
+
+        FileLoader loader = new FileLoader();
+        String protocol = fileName.startsWith("http:") ? "URL" : "File";
+        AlignFrame newframe =
+            loader.LoadFileWaitTillLoaded(fileName, protocol, currentFileFormat);
+
+        newframe.setBounds(bounds);
+
+        this.closeMenuItem_actionPerformed(true);
+      }
+    }
+  }
+
+
   public void addFromText_actionPerformed(ActionEvent e)
   {
     Desktop.instance.inputTextboxMenuItem_actionPerformed(viewport);
@@ -575,12 +663,28 @@ public class AlignFrame
     Desktop.instance.inputURLMenuItem_actionPerformed(viewport);
   }
 
+
+  public void save_actionPerformed(ActionEvent e)
+  {
+    if(fileName==null
+       || currentFileFormat==null
+       || fileName.startsWith("http")
+        )
+    {
+      saveAs_actionPerformed(null);
+    }
+    else
+    {
+      saveAlignment(fileName, currentFileFormat);
+  }
+  }
+
   /**
    * DOCUMENT ME!
    *
    * @param e DOCUMENT ME!
    */
-  public void saveAlignmentMenu_actionPerformed(ActionEvent e)
+  public void saveAs_actionPerformed(ActionEvent e)
   {
     JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
         getProperty( "LAST_DIRECTORY"),
@@ -601,7 +705,6 @@ public class AlignFrame
     if (value == JalviewFileChooser.APPROVE_OPTION)
     {
         currentFileFormat = chooser.getSelectedFormat();
-
         if (currentFileFormat == null)
         {
           JOptionPane.showInternalMessageDialog(Desktop.desktop,
@@ -612,18 +715,21 @@ public class AlignFrame
           return;
         }
 
+        fileName = chooser.getSelectedFile().getPath();
+
       jalview.bin.Cache.setProperty("DEFAULT_FILE_FORMAT",
                                     currentFileFormat);
 
-      String choice = chooser.getSelectedFile().getPath();
-      jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice);
+      jalview.bin.Cache.setProperty("LAST_DIRECTORY", fileName);
 
-      saveAlignment(choice, currentFileFormat);
+      saveAlignment(fileName, currentFileFormat);
     }
   }
 
   public boolean saveAlignment(String file, String format)
   {
+    boolean success = true;
+
     if (format.equalsIgnoreCase("Jalview"))
     {
       String shortName = title;
@@ -634,10 +740,12 @@ public class AlignFrame
             java.io.File.separatorChar) + 1);
       }
 
-      new Jalview2XML().SaveAlignment(this, file, shortName);
+      success = new Jalview2XML().SaveAlignment(this, file, shortName);
+
+      statusBar.setText("Successfully saved to file: "
+                          +fileName+" in "
+                          +format +" format.");
 
-      // USE Jalview2XML to save this file
-      return true;
     }
     else
     {
@@ -653,8 +761,10 @@ public class AlignFrame
             JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
 
         if (reply == JOptionPane.YES_OPTION)
+        {
           omitHidden = viewport.getViewAsString(false);
       }
+      }
 
       String output = new FormatAdapter().formatSequences(
           format,
@@ -663,25 +773,39 @@ public class AlignFrame
 
       if (output == null)
       {
-        return false;
+        success = false;
       }
-
-      try
-      {
-        java.io.PrintWriter out = new java.io.PrintWriter(
-            new java.io.FileWriter(file));
-
-        out.print(output);
-        out.close();
-        this.setTitle(file);
-        return true;
-      }
-      catch (Exception ex)
+      else
       {
-        ex.printStackTrace();
+        try
+        {
+          java.io.PrintWriter out = new java.io.PrintWriter(
+              new java.io.FileWriter(file));
+
+          out.print(output);
+          out.close();
+          this.setTitle(file);
+          statusBar.setText("Successfully saved to file: "
+                            + fileName + " in "
+                            + format + " format.");
+        }
+        catch (Exception ex)
+        {
+          success = false;
+          ex.printStackTrace();
+        }
       }
     }
-    return false;
+
+    if (!success)
+    {
+      JOptionPane.showInternalMessageDialog(
+          this, "Couldn't save file: " + fileName,
+          "Error Saving File",
+          JOptionPane.WARNING_MESSAGE);
+    }
+
+    return success;
   }
 
   /**
@@ -708,6 +832,7 @@ public class AlignFrame
     }
 
     CutAndPasteTransfer cap = new CutAndPasteTransfer();
+    cap.setForInput(null);
     Desktop.addInternalFrame(cap,
                              "Alignment output - " + e.getActionCommand(), 600,
                              500);
@@ -726,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());
   }
@@ -756,6 +881,13 @@ public class AlignFrame
     alignPanel.makeEPS(f);
   }
 
+
+  public void pageSetup_actionPerformed(ActionEvent e)
+  {
+    PrinterJob printJob = PrinterJob.getPrinterJob();
+    PrintThread.pf = printJob.pageDialog(printJob.defaultPage());
+  }
+
   /**
    * DOCUMENT ME!
    *
@@ -764,7 +896,7 @@ public class AlignFrame
   public void printMenuItem_actionPerformed(ActionEvent e)
   {
     //Putting in a thread avoids Swing painting problems
-    PrintThread thread = new PrintThread();
+    PrintThread thread = new PrintThread(alignPanel);
     thread.start();
   }
 
@@ -778,7 +910,9 @@ public class AlignFrame
   {
     new AnnotationExporter().exportAnnotations(
       alignPanel,
-      viewport.alignment.getAlignmentAnnotation()
+        viewport.showAnnotation ? viewport.alignment.getAlignmentAnnotation() : null,
+      viewport.alignment.getGroups(),
+      ((Alignment)viewport.alignment).alignmentProperties
         );
   }
 
@@ -810,22 +944,62 @@ public class AlignFrame
    *
    * @param e DOCUMENT ME!
    */
-  public void closeMenuItem_actionPerformed(ActionEvent e)
+  public void closeMenuItem_actionPerformed(boolean closeAllTabs)
   {
+    if(alignPanels!=null && alignPanels.size()<2)
+    {
+      closeAllTabs = true;
+    }
+
     try
     {
-      for(int i=0; i<alignPanels.size(); i++)
+      if(alignPanels!=null)
       {
-        AlignmentPanel ap = (AlignmentPanel)alignPanels.elementAt(i);
-        PaintRefresher.RemoveComponent(ap.seqPanel.seqCanvas);
-        PaintRefresher.RemoveComponent(ap.idPanel.idCanvas);
-        PaintRefresher.RemoveComponent(ap);
+        if (closeAllTabs)
+        {
+          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
+        {
+          int index = tabbedPane.getSelectedIndex();
+
+          alignPanels.removeElement(alignPanel);
+          PaintRefresher.RemoveComponent(alignPanel.seqPanel.seqCanvas);
+          PaintRefresher.RemoveComponent(alignPanel.idPanel.idCanvas);
+          PaintRefresher.RemoveComponent(alignPanel);
+          viewport.alignment = null;
+          alignPanel = null;
+          viewport = null;
+
+          tabbedPane.removeTabAt(index);
+          tabbedPane.validate();
+
+          if(index==tabbedPane.getTabCount())
+          {
+            index --;
+          }
+
+          this.tabSelectionChanged(index);
+        }
       }
 
-      this.setClosed(true);
+      if (closeAllTabs)
+      {
+        this.setClosed(true);
+    }
     }
     catch (Exception ex)
     {
+      ex.printStackTrace();
     }
   }
 
@@ -835,12 +1009,12 @@ public class AlignFrame
    */
   void updateEditMenuBar()
   {
-  /*  if (historyList.size() > 0)
+
+    if (viewport.historyList.size() > 0)
     {
       undoMenuItem.setEnabled(true);
-
-      HistoryItem hi = (HistoryItem) historyList.peek();
-      undoMenuItem.setText("Undo " + hi.getDescription());
+      CommandI command = (CommandI) viewport.historyList.peek();
+      undoMenuItem.setText("Undo " + command.getDescription());
     }
     else
     {
@@ -848,32 +1022,34 @@ public class AlignFrame
       undoMenuItem.setText("Undo");
     }
 
-    if (redoList.size() > 0)
+    if (viewport.redoList.size() > 0)
     {
       redoMenuItem.setEnabled(true);
 
-      HistoryItem hi = (HistoryItem) redoList.peek();
-      redoMenuItem.setText("Redo " + hi.getDescription());
+      CommandI command = (CommandI) viewport.redoList.peek();
+      redoMenuItem.setText("Redo " + command.getDescription());
     }
     else
     {
       redoMenuItem.setEnabled(false);
       redoMenuItem.setText("Redo");
-    }*/
+    }
   }
 
-  /**
-   * DOCUMENT ME!
-   *
-   * @param hi DOCUMENT ME!
-   */
-  public void addHistoryItem(HistoryItem hi)
+
+  public void addHistoryItem(CommandI command)
   {
-    historyList.push(hi);
-    redoList.clear();
-    updateEditMenuBar();
+    if(command.getSize()>0)
+    {
+      viewport.historyList.push(command);
+      viewport.redoList.clear();
+      updateEditMenuBar();
+      viewport.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
+    }
   }
 
+
+
   /**
    * DOCUMENT ME!
    *
@@ -881,13 +1057,20 @@ public class AlignFrame
    */
   protected void undoMenuItem_actionPerformed(ActionEvent e)
   {
-    HistoryItem nh,hi = (HistoryItem) historyList.pop();
-    redoList.push(nh=new HistoryItem(hi.getDescription(), viewport.alignment,
-                                  HistoryItem.HIDE));
-    if (hi.alColumnChanges!=null)
-      nh.alColumnChanges = hi.alColumnChanges.getInverse();
-    restoreHistoryItem(hi);
-    viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences());
+    CommandI command = (CommandI)viewport.historyList.pop();
+    viewport.redoList.push(command);
+    command.undoCommand();
+
+    AlignViewport originalSource = getOriginatingSource(command);
+    updateEditMenuBar();
+
+    if(originalSource!=null)
+    {
+      originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
+      originalSource.firePropertyChange("alignment",
+                                        null,
+                                        originalSource.alignment.getSequences());
+    }
   }
 
   /**
@@ -897,26 +1080,67 @@ public class AlignFrame
    */
   protected void redoMenuItem_actionPerformed(ActionEvent e)
   {
-    HistoryItem nh,hi = (HistoryItem) redoList.pop();
-    historyList.push(nh=new HistoryItem(hi.getDescription(), viewport.alignment,
-        HistoryItem.HIDE));
-    if (hi.alColumnChanges!=null)
-      nh.alColumnChanges=hi.alColumnChanges.getInverse();
-    restoreHistoryItem(hi);
+    if(viewport.redoList.size()<1)
+    {
+      return;
+    }
+
+    CommandI command = (CommandI) viewport.redoList.pop();
+    viewport.historyList.push(command);
+    command.doCommand();
+
+    AlignViewport originalSource = getOriginatingSource(command);
     updateEditMenuBar();
-    viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences());
+
+    if(originalSource!=null)
+    {
+      originalSource.hasHiddenColumns = viewport.colSel.getHiddenColumns() != null;
+      originalSource.firePropertyChange("alignment",
+                                        null,
+                                        originalSource.alignment.getSequences());
+    }
   }
 
-  // used by undo and redo
-  void restoreHistoryItem(HistoryItem hi)
+  AlignViewport getOriginatingSource(CommandI command)
   {
+    AlignViewport originalSource = null;
+    //For sequence removal and addition, we need to fire
+   //the property change event FROM the viewport where the
+   //original alignment was altered
+    AlignmentI al=null;
+    if (command instanceof EditCommand)
+    {
+      EditCommand editCommand = (EditCommand) command;
+      al = editCommand.getAlignment();
+      Vector comps = (Vector) PaintRefresher.components
+          .get(viewport.getSequenceSetId());
+
+      for (int i = 0; i < comps.size(); i++)
+      {
+        if (comps.elementAt(i) instanceof AlignmentPanel)
+        {
+          if (al == ( (AlignmentPanel) comps.elementAt(i)).av.alignment)
+          {
+            originalSource = ( (AlignmentPanel) comps.elementAt(i)).av;
+            break;
+          }
+        }
+      }
+    }
 
-    hi.restore(viewport.getColumnSelection());
+    if (originalSource == null)
+    {
+      //The original view is closed, we must validate
+      //the current view against the closed view first
+      if (al != null)
+      {
+        PaintRefresher.validateSequences(al, viewport.alignment);
+      }
 
-    updateEditMenuBar();
+      originalSource = viewport;
+    }
 
-    viewport.firePropertyChange("alignment", null,
-                                viewport.getAlignment().getSequences());
+    return originalSource;
   }
 
   /**
@@ -939,14 +1163,14 @@ public class AlignFrame
       {
         SequenceI seq = viewport.alignment.getSequenceAt(i);
 
-        if (!sg.getSequences(false).contains(seq))
+        if (!sg.getSequences(null).contains(seq))
         {
           continue;
         }
 
         SequenceI temp = viewport.alignment.getSequenceAt(i - 1);
 
-        if (sg.getSequences(false).contains(temp))
+        if (sg.getSequences(null).contains(temp))
         {
           continue;
         }
@@ -961,14 +1185,14 @@ public class AlignFrame
       {
         SequenceI seq = viewport.alignment.getSequenceAt(i);
 
-        if (!sg.getSequences(false).contains(seq))
+        if (!sg.getSequences(null).contains(seq))
         {
           continue;
         }
 
         SequenceI temp = viewport.alignment.getSequenceAt(i + 1);
 
-        if (sg.getSequences(false).contains(temp))
+        if (sg.getSequences(null).contains(temp))
         {
           continue;
         }
@@ -978,11 +1202,102 @@ public class AlignFrame
       }
     }
 
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
 
 
+
+  synchronized void slideSequences(boolean right, int size)
+  {
+    Vector sg = new Vector();
+    if(viewport.cursorMode)
+    {
+      sg.addElement(viewport.alignment.getSequenceAt(
+          alignPanel.seqPanel.seqCanvas.cursorY));
+    }
+    else if(viewport.getSelectionGroup()!=null
+        && viewport.getSelectionGroup().getSize()!=viewport.alignment.getHeight())
+   {
+     sg = viewport.getSelectionGroup().getSequences(
+         viewport.hiddenRepSequences);
+   }
+
+    if(sg.size()<1)
+    {
+      return;
+    }
+
+    Vector invertGroup = new Vector();
+
+    for (int i = 0; i < viewport.alignment.getHeight(); i++)
+    {
+      if(!sg.contains(viewport.alignment.getSequenceAt(i)))
+         invertGroup.add(viewport.alignment.getSequenceAt(i));
+    }
+
+    SequenceI[] seqs1 = new SequenceI[sg.size()];
+    for (int i = 0; i < sg.size(); i++)
+      seqs1[i] = (SequenceI) sg.elementAt(i);
+
+    SequenceI[] seqs2 = new SequenceI[invertGroup.size()];
+    for (int i = 0; i < invertGroup.size(); i++)
+      seqs2[i] = (SequenceI) invertGroup.elementAt(i);
+
+    SlideSequencesCommand ssc;
+    if (right)
+      ssc = new SlideSequencesCommand("Slide Sequences",
+                                      seqs2, seqs1, size,
+                                      viewport.getGapCharacter()
+          );
+    else
+      ssc = new SlideSequencesCommand("Slide Sequences",
+                                      seqs1, seqs2, size,
+                                      viewport.getGapCharacter()
+          );
+
+    int groupAdjustment = 0;
+    if (ssc.getGapsInsertedBegin() && right)
+    {
+      if (viewport.cursorMode)
+        alignPanel.seqPanel.moveCursor(size, 0);
+      else
+        groupAdjustment = size;
+    }
+    else if (!ssc.getGapsInsertedBegin() && !right)
+    {
+      if (viewport.cursorMode)
+        alignPanel.seqPanel.moveCursor( -size, 0);
+      else
+        groupAdjustment = -size;
+    }
+
+    if (groupAdjustment != 0)
+    {
+      viewport.getSelectionGroup().setStartRes(
+          viewport.getSelectionGroup().getStartRes() + groupAdjustment);
+      viewport.getSelectionGroup().setEndRes(
+          viewport.getSelectionGroup().getEndRes() + groupAdjustment);
+    }
+
+
+    boolean appendHistoryItem = false;
+    if(viewport.historyList!=null
+       && viewport.historyList.size()>0
+      && viewport.historyList.peek() instanceof SlideSequencesCommand)
+    {
+      appendHistoryItem = ssc.appendSlideCommand(
+          (SlideSequencesCommand)viewport.historyList.peek())
+          ;
+    }
+
+    if(!appendHistoryItem)
+      addHistoryItem(ssc);
+
+    repaint();
+  }
+
+
   /**
    * DOCUMENT ME!
    *
@@ -995,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;
 
@@ -1013,6 +1328,7 @@ public class AlignFrame
 
     try
     {
+      jalview.gui.Desktop.internalCopy = true;
       //Its really worth setting the clipboard contents
       //to empty before setting the large StringSelection!!
       Toolkit.getDefaultToolkit().getSystemClipboard()
@@ -1045,19 +1361,21 @@ public class AlignFrame
     {
       hiddenColumns =new Vector();
       int hiddenOffset = viewport.getSelectionGroup().getStartRes();
-      for(int i=0; i<viewport.getColumnSelection().getHiddenColumns().size(); i++)
+      for (int i = 0; i < viewport.getColumnSelection().getHiddenColumns().size();
+           i++)
       {
         int[] region = (int[])
             viewport.getColumnSelection().getHiddenColumns().elementAt(i);
 
-        hiddenColumns.addElement(new int[]{region[0]-hiddenOffset,
+        hiddenColumns.addElement(new int[]
+                                 {region[0] - hiddenOffset,
                           region[1]-hiddenOffset});
       }
     }
 
-
-
-    Desktop.jalviewClipboard = new Object[]{ seqs,
+    Desktop.jalviewClipboard = new Object[]
+        {
+        seqs,
         viewport.alignment.getDataset(),
         hiddenColumns};
     statusBar.setText("Copied "+seqs.length+" sequences to clipboard.");
@@ -1080,8 +1398,6 @@ public class AlignFrame
    */
   protected void pasteThis_actionPerformed(ActionEvent e)
   {
-    addHistoryItem(new HistoryItem("Paste Sequences", viewport.alignment,
-                                   HistoryItem.PASTE));
     paste(false);
   }
 
@@ -1092,6 +1408,7 @@ public class AlignFrame
    */
   void paste(boolean newAlignment)
   {
+    boolean externalPaste=true;
     try
     {
       Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
@@ -1107,7 +1424,9 @@ public class AlignFrame
       {
         str = (String) contents.getTransferData(DataFlavor.stringFlavor);
         if (str.length() < 1)
+        {
           return;
+        }
 
         format = new IdentifyFile().Identify(str, "Paste");
 
@@ -1132,86 +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);
+       // 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
         for (int i = 0; i < sequences.length; i++)
         {
-          Sequence newseq = new Sequence(sequences[i].getName(),
-              sequences[i].getSequence(), sequences[i].getStart(),
-              sequences[i].getEnd());
-
-          alignment.addSequence(newseq);
-          PaintRefresher.Refresh(alignPanel,
-                                 alignPanel.av.getSequenceSetId(),
-                                 null,newseq);
+          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
+        }
+        if (newDs != null)
+        {
+          newDs.clear(); // tidy up
         }
-
-
-        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 (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");
 
@@ -1230,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,
@@ -1273,46 +1659,49 @@ public class AlignFrame
    *
    * @param e DOCUMENT ME!
    */
-  protected void delete_actionPerformed(ActionEvent e)
+  protected void delete_actionPerformed(ActionEvent evt)
   {
 
-    if (viewport.getSelectionGroup() == null)
+    SequenceGroup sg = viewport.getSelectionGroup();
+    if (sg == null)
     {
       return;
     }
 
-
-    SequenceGroup sg = viewport.getSelectionGroup();
+    Vector seqs = new Vector();
+    SequenceI seq;
+    for (int i = 0; i < sg.getSize(); i++)
+    {
+      seq = sg.getSequenceAt(i);
+      seqs.addElement(seq);
+    }
 
 
-    addHistoryItem(new HistoryItem("Delete Sequences", viewport.alignment,
-                                   HistoryItem.HIDE));
+   // If the cut affects all sequences, remove highlighted columns
+   if (sg.getSize() == viewport.alignment.getHeight())
+   {
+     viewport.getColumnSelection().removeElements(sg.getStartRes(),
+         sg.getEndRes() + 1);
+   }
 
 
-    for (int i = 0; i < sg.getSize(false); i++)
+    SequenceI [] cut = new SequenceI[seqs.size()];
+    for(int i=0; i<seqs.size(); i++)
     {
-      SequenceI seq = sg.getSequenceAt(i);
-      int index = viewport.getAlignment().findIndex(seq);
+      cut[i] = (SequenceI)seqs.elementAt(i);
+    }
 
-      seq.deleteChars(sg.getStartRes(), sg.getEndRes() + 1);
 
-      // If the cut affects all sequences, remove highlighted columns
-      if (sg.getSize(false) == viewport.alignment.getHeight())
-      {
-        viewport.getColumnSelection().removeElements(sg.getStartRes(),
-            sg.getEndRes() + 1);
-      }
+    /*
+    //ADD HISTORY ITEM
+    */
+    addHistoryItem(new EditCommand("Cut Sequences",
+                                      EditCommand.CUT,
+                                      cut,
+                                      sg.getStartRes(),
+                                      sg.getEndRes()-sg.getStartRes()+1,
+                                      viewport.alignment));
 
-      if (seq.getSequence().length() < 1)
-      {
-        viewport.getAlignment().deleteSequence(seq);
-        PaintRefresher.Refresh(alignPanel,alignPanel.av.getSequenceSetId(),seq,null);
-      }
-      else
-      {
-        viewport.getAlignment().getSequences().setElementAt(seq, index);
-      }
-    }
 
     viewport.setSelectionGroup(null);
     viewport.alignment.deleteGroup(sg);
@@ -1320,8 +1709,6 @@ public class AlignFrame
     viewport.firePropertyChange("alignment", null,
                                   viewport.getAlignment().getSequences());
 
-
-
     if (viewport.getAlignment().getHeight() < 1)
     {
       try
@@ -1342,9 +1729,10 @@ public class AlignFrame
   protected void deleteGroups_actionPerformed(ActionEvent e)
   {
     viewport.alignment.deleteAllGroups();
+    viewport.sequenceColours = null;
     viewport.setSelectionGroup(null);
     PaintRefresher.Refresh(this, viewport.getSequenceSetId());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1364,7 +1752,7 @@ public class AlignFrame
 
     sg.setEndRes(viewport.alignment.getWidth() - 1);
     viewport.setSelectionGroup(sg);
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
     PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
   }
 
@@ -1385,8 +1773,8 @@ public class AlignFrame
     viewport.setSelectionGroup(null);
     alignPanel.seqPanel.seqCanvas.highlightSearchResults(null);
     alignPanel.idPanel.idCanvas.searchResults = null;
-    alignPanel.repaint();
-    PaintRefresher.Refresh(this, viewport.getSequenceSetId());
+    alignPanel.paintAlignment(true);
+    PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
   }
 
   /**
@@ -1411,13 +1799,15 @@ public class AlignFrame
       sg.addOrRemove(viewport.getAlignment().getSequenceAt(i), false);
     }
 
-    PaintRefresher.Refresh(this, viewport.getSequenceSetId());
+    alignPanel.paintAlignment(true);
+
+    PaintRefresher.Refresh(alignPanel, viewport.getSequenceSetId());
   }
 
   public void invertColSel_actionPerformed(ActionEvent e)
   {
     viewport.invertColumnSelection();
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
 
@@ -1428,37 +1818,7 @@ public class AlignFrame
    */
   public void remove2LeftMenuItem_actionPerformed(ActionEvent e)
   {
-    ColumnSelection colSel = viewport.getColumnSelection();
-
-    if (colSel.size() > 0)
-    {
-      HistoryItem edit;
-      addHistoryItem(edit=new HistoryItem("Remove Left", viewport.alignment,
-                                     HistoryItem.HIDE));
-
-      int min = colSel.getMin();
-      viewport.getAlignment().trimLeft(min);
-      colSel.compensateForEdit(0, min);
-      edit.addShift(0,min);
-      if (viewport.getSelectionGroup() != null)
-      {
-        viewport.getSelectionGroup().adjustForRemoveLeft(min);
-      }
-
-      Vector groups = viewport.alignment.getGroups();
-
-      for (int i = 0; i < groups.size(); i++)
-      {
-        SequenceGroup sg = (SequenceGroup) groups.get(i);
-
-        if (!sg.adjustForRemoveLeft(min))
-        {
-          viewport.alignment.deleteGroup(sg);
-        }
-      }
-
-      viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences());
-    }
+    trimAlignment(true);
   }
 
   /**
@@ -1468,21 +1828,64 @@ public class AlignFrame
    */
   public void remove2RightMenuItem_actionPerformed(ActionEvent e)
   {
+      trimAlignment(false);
+  }
+
+  void trimAlignment(boolean trimLeft)
+  {
     ColumnSelection colSel = viewport.getColumnSelection();
+    int column;
 
     if (colSel.size() > 0)
     {
-      addHistoryItem(new HistoryItem("Remove Right", viewport.alignment,
-                                     HistoryItem.HIDE));
+      if(trimLeft)
+      {
+        column = colSel.getMin();
+      }
+      else
+      {
+        column = colSel.getMax();
+      }
+
+      SequenceI [] seqs;
+      if(viewport.getSelectionGroup()!=null)
+      {
+        seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
+            hiddenRepSequences);
+      }
+      else
+      {
+        seqs = viewport.alignment.getSequencesArray();
+      }
+
 
-      int max = colSel.getMax();
-      viewport.getAlignment().trimRight(max);
-      // TODO: delete hidden column entries in colSel to right of max
-      // TODO: record hidden columns in history for undo.
-      if (viewport.getSelectionGroup() != null)
+      TrimRegionCommand trimRegion;
+      if(trimLeft)
       {
-        viewport.getSelectionGroup().adjustForRemoveRight(max);
+        trimRegion = new TrimRegionCommand("Remove Left",
+                                    TrimRegionCommand.TRIM_LEFT,
+                                    seqs,
+                                    column,
+                                    viewport.alignment,
+                                    viewport.colSel,
+                                    viewport.selectionGroup);
+        viewport.setStartRes(0);
       }
+     else
+     {
+       trimRegion = new TrimRegionCommand("Remove Right",
+                                   TrimRegionCommand.TRIM_RIGHT,
+                                   seqs,
+                                   column,
+                                   viewport.alignment,
+                                   viewport.colSel,
+                                   viewport.selectionGroup);
+     }
+
+     statusBar.setText("Removed "+trimRegion.getSize()+" columns.");
+
+
+      addHistoryItem(trimRegion);
 
       Vector groups = viewport.alignment.getGroups();
 
@@ -1490,13 +1893,15 @@ public class AlignFrame
       {
         SequenceGroup sg = (SequenceGroup) groups.get(i);
 
-        if (!sg.adjustForRemoveRight(max))
+        if ( (trimLeft && !sg.adjustForRemoveLeft(column))
+            || (!trimLeft && !sg.adjustForRemoveRight(column)))
         {
           viewport.alignment.deleteGroup(sg);
         }
       }
 
-      viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences());
+      viewport.firePropertyChange("alignment", null,
+                                  viewport.getAlignment().getSequences());
     }
   }
 
@@ -1507,21 +1912,44 @@ public class AlignFrame
    */
   public void removeGappedColumnMenuItem_actionPerformed(ActionEvent e)
   {
-    HistoryItem edit;
-    addHistoryItem(edit=new HistoryItem("Remove Gapped Columns",
-                                   viewport.alignment, HistoryItem.HIDE));
+    int start = 0, end = viewport.alignment.getWidth()-1;
+
+    SequenceI[] seqs;
+    if (viewport.getSelectionGroup() != null)
+    {
+      seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
+          hiddenRepSequences);
+      start = viewport.getSelectionGroup().getStartRes();
+      end = viewport.getSelectionGroup().getEndRes();
+    }
+    else
+    {
+      seqs = viewport.alignment.getSequencesArray();
+    }
+
+
+    RemoveGapColCommand removeGapCols =
+        new RemoveGapColCommand("Remove Gapped Columns",
+                                seqs,
+                                start, end,
+                                viewport.alignment);
+
+    addHistoryItem(removeGapCols);
+
+    statusBar.setText("Removed "+removeGapCols.getSize()+" empty columns.");
 
     //This is to maintain viewport position on first residue
     //of first sequence
     SequenceI seq = viewport.alignment.getSequenceAt(0);
     int startRes = seq.findPosition(viewport.startRes);
-    ShiftList shifts;
-    viewport.getAlignment().removeGaps(shifts=new ShiftList());
-    edit.alColumnChanges=shifts.getInverse();
-    if (viewport.hasHiddenColumns)
-      viewport.getColumnSelection().compensateForEdits(shifts);
-    viewport.setStartRes(seq.findIndex(startRes)-1);
-   viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences());
+   // ShiftList shifts;
+   // viewport.getAlignment().removeGaps(shifts=new ShiftList());
+   // edit.alColumnChanges=shifts.getInverse();
+   // if (viewport.hasHiddenColumns)
+   //   viewport.getColumnSelection().compensateForEdits(shifts);
+   viewport.setStartRes(seq.findIndex(startRes)-1);
+    viewport.firePropertyChange("alignment", null,
+                                viewport.getAlignment().getSequences());
 
   }
 
@@ -1532,147 +1960,36 @@ public class AlignFrame
    */
   public void removeAllGapsMenuItem_actionPerformed(ActionEvent e)
   {
-    // TODO: hidden regions should not be touched by removeAllGaps - a minimal number of gaps will remain in alignment segments containing uneven length subsequences
-    // TODO: columnSelection.compensateforedits should be called (and passed to history item)
-    addHistoryItem(new HistoryItem("Remove Gaps", viewport.alignment,
-                                   HistoryItem.HIDE));
+    int start = 0, end = viewport.alignment.getWidth()-1;
 
-    //This is to maintain viewport position on first residue
-    //of first sequence
-    SequenceI seq = viewport.alignment.getSequenceAt(0);
-    int startRes = seq.findPosition(viewport.startRes);
-
-
-    SequenceI current;
-
-    Vector seqs = null;
-
-    int start = 0;
-    int end = viewport.alignment.getWidth();
-
-    if (viewport.getSelectionGroup() != null
-        && viewport.getSelectionGroup().getSequences(true) != null
-        && viewport.getSelectionGroup().getSize(true) > 0)
+    SequenceI[] seqs;
+    if (viewport.getSelectionGroup() != null)
     {
-      seqs = viewport.getSelectionGroup().getSequences(true);
+      seqs = viewport.getSelectionGroup().getSequencesAsArray(viewport.
+          hiddenRepSequences);
       start = viewport.getSelectionGroup().getStartRes();
-      end = viewport.getSelectionGroup().getEndRes()+1;
+      end = viewport.getSelectionGroup().getEndRes();
     }
     else
     {
-      seqs = viewport.alignment.getSequences();
+      seqs = viewport.alignment.getSequencesArray();
     }
-    /* Commented out regions below are partial implementation of todo above.
-       * divide start,end into visible chunks, and for each:
-      int diff=end-start+1;
-      int diffmax=0;
-      int dr[] = new int[seqs.size()];
-      */
-     for (int i = 0; i < seqs.size(); i++)
-     {
-       current = (SequenceI) seqs.elementAt(i);
-       //dr[i]=
-       current.removeGaps(start, end);
-       /*if (d<diff) // can only shift
-         diff=d;
-       if (diffmax<d)
-         diffmax=d;
-         */
-     }
-     /* // after the end of each chunk -
-      * if (diff>0) {
-      // record shift for history.
-       editgaps.addShift(start, diff);
-       if (viewport.hasHiddenColumns && diffmax>diff) {
-       // pad sequence
-        StringBuffer gaps=new StringBuffer(diffmax);
-        for (int i=0,j=diffmax-diff; i<j; i++)
-        gaps.append(viewport.getGapCharacter());
-        for (int i=0, j=seqs.size(); i<j; i++) {
-        current = (SequenceI) seqs.elementAt(i);
-        if (dr[i]-diff>0) {
-        String sq = current.getSequence();
-        current.setSequence(sq.substring(0, hcend-dr[i])+gaps.substring(0, dr[i]-diff)+sq.substring());
-        }
-        }
-       }
-       }*/
-
-    viewport.setStartRes(seq.findIndex(startRes)-1);
 
-    viewport.firePropertyChange("alignment", null, viewport.getAlignment().getSequences());
-
-  }
-
- public void alignmentChanged()
- {
-   AlignViewport av;
-   AlignmentPanel ap;
-
-   for(int i=0; i<alignPanels.size(); i++)
-   {
-     ap = (AlignmentPanel) alignPanels.elementAt(i);
-     av = ap.av;
-
-   if (av.padGaps)
-       av.getAlignment().padGaps();
-
-     if (av.hconsensus != null && av.autoCalculateConsensus)
-     {
-       av.updateConsensus(ap);
-       av.updateConservation(ap);
-       ap.annotationPanel.repaint();
-     }
-
-     resetAllColourSchemes();
-
-     av.alignment.adjustSequenceAnnotations();
-
-     if (ap.overviewPanel != null)
-       ap.overviewPanel.updateOverviewImage();
-
-     ap.repaint();
-   }
- }
+    //This is to maintain viewport position on first residue
+    //of first sequence
+    SequenceI seq = viewport.alignment.getSequenceAt(0);
+    int startRes = seq.findPosition(viewport.startRes);
 
-  void resetAllColourSchemes()
-  {
-    ColourSchemeI cs = viewport.globalColourScheme;
-    if(cs!=null)
-    {
-      if (cs instanceof ClustalxColourScheme)
-      {
-        ( (ClustalxColourScheme) viewport.getGlobalColourScheme()).
-            resetClustalX(viewport.alignment.getSequences(),
-                          viewport.alignment.getWidth());
-      }
+    addHistoryItem(new RemoveGapsCommand("Remove Gaps",
+                                         seqs,
+                                         start, end,
+                                         viewport.alignment));
 
-      cs.setConsensus(viewport.hconsensus);
-      if (cs.conservationApplied())
-      {
-        Alignment al = (Alignment) viewport.alignment;
-        Conservation c = new Conservation("All",
-                                          ResidueProperties.propHash, 3,
-                                          al.getSequences(), 0,
-                                          al.getWidth() - 1);
-        c.calculate();
-        c.verdict(false, viewport.ConsPercGaps);
+    viewport.setStartRes(seq.findIndex(startRes)-1);
 
-        cs.setConservation(c);
-      }
-    }
+    viewport.firePropertyChange("alignment", null,
+                                viewport.getAlignment().getSequences());
 
-    int s, sSize = viewport.alignment.getGroups().size();
-    for(s=0; s<sSize; s++)
-    {
-      SequenceGroup sg = (SequenceGroup)viewport.alignment.getGroups().elementAt(s);
-      if(sg.cs!=null && sg.cs instanceof ClustalxColourScheme)
-      {
-        ((ClustalxColourScheme)sg.cs).resetClustalX(
-            sg.getSequences(true), sg.getWidth());
-      }
-      sg.recalcConservation();
-    }
   }
 
   /**
@@ -1682,9 +1999,6 @@ public class AlignFrame
    */
   public void padGapsMenuitem_actionPerformed(ActionEvent e)
   {
-    addHistoryItem(new HistoryItem("Pad Gaps", viewport.alignment,
-                                   HistoryItem.HIDE));
-
     viewport.padGaps = padGapsMenuitem.isSelected();
 
     viewport.firePropertyChange("alignment",
@@ -1699,13 +2013,70 @@ public class AlignFrame
    */
   public void findMenuItem_actionPerformed(ActionEvent e)
   {
-    JInternalFrame frame = new JInternalFrame();
-    Finder finder = new Finder(viewport, alignPanel, frame);
-    frame.setContentPane(finder);
-    frame.setLayer(JLayeredPane.PALETTE_LAYER);
-    Desktop.addInternalFrame(frame, "Find", 340, 110);
+    new Finder();
+  }
+
+  public void newView_actionPerformed(ActionEvent e)
+  {
+    AlignmentPanel newap =
+        new Jalview2XML().copyAlignPanel(alignPanel, true);
+
+    newap.av.gatherViewsHere = false;
+
+    if (viewport.viewName == null)
+    {
+      viewport.viewName = "Original";
+    }
+
+    newap.av.historyList = viewport.historyList;
+    newap.av.redoList = viewport.redoList;
+
+    int index = Desktop.getViewCount(viewport.getSequenceSetId());
+    String newViewName = "View " +index;
+
+    Vector comps = (Vector) PaintRefresher.components.get(viewport.
+        getSequenceSetId());
+    Vector existingNames = new Vector();
+    for(int i=0; i<comps.size(); i++)
+    {
+      if(comps.elementAt(i) instanceof AlignmentPanel)
+      {
+        AlignmentPanel ap = (AlignmentPanel)comps.elementAt(i);
+        if(!existingNames.contains(ap.av.viewName))
+        {
+          existingNames.addElement(ap.av.viewName);
+      }
+    }
+    }
+
+    while(existingNames.contains(newViewName))
+    {
+      newViewName = "View "+ (++index);
+    }
+
+    newap.av.viewName = newViewName;
+
+    addAlignmentPanel(newap, false);
+
+    if(alignPanels.size()==2)
+    {
+      viewport.gatherViewsHere = true;
+    }
+    tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
+  }
+
+  public void expandViews_actionPerformed(ActionEvent e)
+  {
+        Desktop.instance.explodeViews(this);
   }
 
+  public void gatherViews_actionPerformed(ActionEvent e)
+  {
+    Desktop.instance.gatherViews(this);
+  }
+
+
+
   /**
    * DOCUMENT ME!
    *
@@ -1716,13 +2087,6 @@ public class AlignFrame
     new FontChooser(alignPanel);
   }
 
-  public void smoothFont_actionPerformed(ActionEvent e)
-  {
-    viewport.antiAlias = smoothFont.isSelected();
-    alignPanel.annotationPanel.image = null;
-    alignPanel.repaint();
-  }
-
 
   /**
    * DOCUMENT ME!
@@ -1734,9 +2098,16 @@ public class AlignFrame
     viewport.setShowJVSuffix(seqLimits.isSelected());
 
     alignPanel.idPanel.idCanvas.setPreferredSize(alignPanel.calculateIdWidth());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
+  public void idRightAlign_actionPerformed(ActionEvent e)
+  {
+    viewport.rightAlignIds = idRightAlign.isSelected();
+    alignPanel.paintAlignment(true);
+  }
+
+
 
   /**
    * DOCUMENT ME!
@@ -1746,7 +2117,7 @@ public class AlignFrame
   protected void colourTextMenuItem_actionPerformed(ActionEvent e)
   {
     viewport.setColourText(colourTextMenuItem.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1777,13 +2148,13 @@ public class AlignFrame
   public void hideSelSequences_actionPerformed(ActionEvent e)
   {
     viewport.hideAllSelectedSeqs();
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   public void hideSelColumns_actionPerformed(ActionEvent e)
   {
     viewport.hideSelectedColumns();
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   public void hiddenMarkers_actionPerformed(ActionEvent e)
@@ -1800,7 +2171,7 @@ public class AlignFrame
   protected void scaleAbove_actionPerformed(ActionEvent e)
   {
     viewport.setScaleAboveWrapped(scaleAbove.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1811,7 +2182,7 @@ public class AlignFrame
   protected void scaleLeft_actionPerformed(ActionEvent e)
   {
     viewport.setScaleLeftWrapped(scaleLeft.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1822,7 +2193,7 @@ public class AlignFrame
   protected void scaleRight_actionPerformed(ActionEvent e)
   {
     viewport.setScaleRightWrapped(scaleRight.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1833,7 +2204,7 @@ public class AlignFrame
   public void viewBoxesMenuItem_actionPerformed(ActionEvent e)
   {
     viewport.setShowBoxes(viewBoxesMenuItem.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1844,7 +2215,7 @@ public class AlignFrame
   public void viewTextMenuItem_actionPerformed(ActionEvent e)
   {
     viewport.setShowText(viewTextMenuItem.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -1855,7 +2226,7 @@ public class AlignFrame
   protected void renderGapsMenuItem_actionPerformed(ActionEvent e)
   {
     viewport.setRenderGaps(renderGapsMenuItem.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
   }
 
 
@@ -1878,7 +2249,7 @@ public class AlignFrame
   public void showSeqFeatures_actionPerformed(ActionEvent evt)
   {
     viewport.setShowSequenceFeatures(showSeqFeatures.isSelected());
-    alignPanel.repaint();
+    alignPanel.paintAlignment(true);
     if (alignPanel.getOverviewPanel() != null)
     {
       alignPanel.getOverviewPanel().updateOverviewImage();
@@ -1896,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!
    *
@@ -1928,6 +2344,11 @@ public class AlignFrame
     alignPanel.setOverviewPanel(overview);
   }
 
+  public void textColour_actionPerformed(ActionEvent e)
+  {
+    new TextColourChooser().chooseColour(alignPanel, null);
+  }
+
   /**
    * DOCUMENT ME!
    *
@@ -2115,7 +2536,7 @@ public class AlignFrame
         if (cs instanceof ClustalxColourScheme)
         {
           sg.cs = new ClustalxColourScheme(
-              sg.getSequences(true), sg.getWidth());
+              sg.getSequences(viewport.hiddenRepSequences), sg.getWidth());
         }
         else if (cs instanceof UserColourScheme)
         {
@@ -2140,34 +2561,43 @@ public class AlignFrame
                 viewport.getIgnoreGapsConsensus());
 
          sg.cs.setConsensus(AAFrequency.calculate(
-             sg.getSequences(true), 0,
-             sg.getWidth()));
+             sg.getSequences(viewport.hiddenRepSequences), sg.getStartRes(),
+             sg.getEndRes()+1));
        }
         else
+        {
           sg.cs.setThreshold(0, viewport.getIgnoreGapsConsensus());
+        }
 
 
         if (viewport.getConservationSelected())
         {
           Conservation c = new Conservation("Group",
                                             ResidueProperties.propHash, 3,
-                                            sg.getSequences(true), 0,
-                                            viewport.alignment.getWidth() - 1);
+                                            sg.getSequences(viewport.
+              hiddenRepSequences),
+                                            sg.getStartRes(),
+                                            sg.getEndRes()+1);
           c.calculate();
           c.verdict(false, viewport.ConsPercGaps);
           sg.cs.setConservation(c);
         }
         else
+        {
           sg.cs.setConservation(null);
       }
     }
+    }
 
     if (alignPanel.getOverviewPanel() != null)
     {
       alignPanel.getOverviewPanel().updateOverviewImage();
     }
 
-    alignPanel.repaint();
+
+
+
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -2277,7 +2707,8 @@ public class AlignFrame
 
       while (userColours.hasMoreElements())
       {
-        final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(userColours.
+        final JRadioButtonMenuItem radioItem = new JRadioButtonMenuItem(
+            userColours.
             nextElement().toString());
         radioItem.setName("USER_DEFINED");
         radioItem.addMouseListener(new MouseAdapter()
@@ -2288,16 +2719,19 @@ public class AlignFrame
                 {
                   radioItem.removeActionListener(radioItem.getActionListeners()[0]);
 
-                  int option = JOptionPane.showInternalConfirmDialog(jalview.gui.Desktop.desktop,
+              int option = JOptionPane.showInternalConfirmDialog(jalview.gui.
+                  Desktop.desktop,
                       "Remove from default list?",
                       "Remove user defined colour",
                       JOptionPane.YES_NO_OPTION);
                   if(option == JOptionPane.YES_OPTION)
                   {
-                    jalview.gui.UserDefinedColours.removeColourFromDefaults(radioItem.getText());
+                jalview.gui.UserDefinedColours.removeColourFromDefaults(
+                    radioItem.getText());
                     colourMenu.remove(radioItem);
                   }
                   else
+              {
                     radioItem.addActionListener(new ActionListener()
                     {
                       public void actionPerformed(ActionEvent evt)
@@ -2307,6 +2741,7 @@ public class AlignFrame
                     });
                 }
               }
+          }
             });
         radioItem.addActionListener(new ActionListener()
         {
@@ -2349,11 +2784,12 @@ public class AlignFrame
    */
   public void sortPairwiseMenuItem_actionPerformed(ActionEvent e)
   {
-    addHistoryItem(new HistoryItem("Pairwise Sort", viewport.alignment,
-                                   HistoryItem.SORT));
+    SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
     AlignmentSorter.sortByPID(viewport.getAlignment(),
                               viewport.getAlignment().getSequenceAt(0));
-    alignPanel.repaint();
+    addHistoryItem(new OrderCommand("Pairwise Sort", oldOrder,
+                                    viewport.alignment));
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -2363,10 +2799,10 @@ public class AlignFrame
    */
   public void sortIDMenuItem_actionPerformed(ActionEvent e)
   {
-    addHistoryItem(new HistoryItem("ID Sort", viewport.alignment,
-                                   HistoryItem.SORT));
+    SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
     AlignmentSorter.sortByID(viewport.getAlignment());
-    alignPanel.repaint();
+    addHistoryItem(new OrderCommand("ID Sort", oldOrder, viewport.alignment));
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -2376,11 +2812,11 @@ public class AlignFrame
    */
   public void sortGroupMenuItem_actionPerformed(ActionEvent e)
   {
-    addHistoryItem(new HistoryItem("Group Sort", viewport.alignment,
-                                   HistoryItem.SORT));
-
+    SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
     AlignmentSorter.sortByGroup(viewport.getAlignment());
-    alignPanel.repaint();
+    addHistoryItem(new OrderCommand("Group Sort", oldOrder, viewport.alignment));
+
+    alignPanel.paintAlignment(true);
   }
 
   /**
@@ -2402,7 +2838,7 @@ public class AlignFrame
   public void pairwiseAlignmentMenuItem_actionPerformed(ActionEvent e)
   {
     if ( (viewport.getSelectionGroup() == null) ||
-        (viewport.getSelectionGroup().getSize(false) < 2))
+        (viewport.getSelectionGroup().getSize() < 2))
     {
       JOptionPane.showInternalMessageDialog(this,
                                             "You must select at least 2 sequences.",
@@ -2425,8 +2861,8 @@ public class AlignFrame
   public void PCAMenuItem_actionPerformed(ActionEvent e)
   {
     if ( ( (viewport.getSelectionGroup() != null) &&
-          (viewport.getSelectionGroup().getSize(false) < 4) &&
-          (viewport.getSelectionGroup().getSize(false) > 0)) ||
+          (viewport.getSelectionGroup().getSize() < 4) &&
+          (viewport.getSelectionGroup().getSize() > 0)) ||
         (viewport.getAlignment().getHeight() < 4))
     {
       JOptionPane.showInternalMessageDialog(this,
@@ -2438,7 +2874,7 @@ public class AlignFrame
       return;
     }
 
-     new PCAPanel(viewport);
+     new PCAPanel(alignPanel);
   }
 
 
@@ -2505,8 +2941,10 @@ public class AlignFrame
   {
     TreePanel tp;
 
-    if (viewport.getSelectionGroup() != null) {
-      if (viewport.getSelectionGroup().getSize(false) < 3) {
+    if (viewport.getSelectionGroup() != null)
+    {
+      if (viewport.getSelectionGroup().getSize() < 3)
+      {
         JOptionPane.showMessageDialog(Desktop.desktop,
                                       "You need to have more than two sequences selected to build a tree!",
                                       "Not enough sequences",
@@ -2518,9 +2956,9 @@ public class AlignFrame
       SequenceGroup sg = viewport.getSelectionGroup();
 
       /* Decide if the selection is a column region */
-      while (s < sg.getSize(false))
+      while (s < sg.getSize())
       {
-        if ( ( (SequenceI) sg.getSequences(false).elementAt(s++)).getLength() <
+        if ( ( (SequenceI) sg.getSequences(null).elementAt(s++)).getLength() <
             sg.getEndRes())
         {
           JOptionPane.showMessageDialog(Desktop.desktop,
@@ -2553,14 +2991,23 @@ public class AlignFrame
       }
 
       if(viewport.alignment.getHeight()<2)
+      {
         return;
+      }
 
       tp = new TreePanel(alignPanel, type, pwType);
     }
 
-    addTreeMenuItem(tp, title);
+    title += " from ";
+
+    if(viewport.viewName!=null)
+    {
+      title+= viewport.viewName+" of ";
+    }
+
+    title += this.title;
 
-    Desktop.addInternalFrame(tp, title + " from " + this.title, 600, 500);
+    Desktop.addInternalFrame(tp, title, 600, 500);
   }
 
   /**
@@ -2577,12 +3024,15 @@ public class AlignFrame
     {
       public void actionPerformed(ActionEvent e)
       {
-        addHistoryItem(new HistoryItem("Sort", viewport.alignment,
-                                       HistoryItem.SORT));
+        SequenceI [] oldOrder = viewport.getAlignment().getSequencesArray();
 
         // TODO: JBPNote - have to map order entries to curent SequenceI pointers
         AlignmentSorter.sortBy(viewport.getAlignment(), order);
-        alignPanel.repaint();
+
+        addHistoryItem(new OrderCommand(order.getName(), oldOrder,
+                                        viewport.alignment));
+
+        alignPanel.paintAlignment(true);
       }
     });
   }
@@ -2596,46 +3046,54 @@ public class AlignFrame
    * @param treePanel Displayed tree window.
    * @param title SortBy menu item title.
    */
-  void addTreeMenuItem(final TreePanel treePanel, String title)
+  public void buildTreeMenu()
   {
-    final JMenuItem item = new JMenuItem(title);
-
-    treeCount++;
+    sortByTreeMenu.removeAll();
 
-    if (treeCount == 1)
+    Vector comps = (Vector) PaintRefresher.components.get(viewport.
+        getSequenceSetId());
+    Vector treePanels = new Vector();
+    int i, iSize = comps.size();
+    for(i=0; i<iSize; i++)
     {
-      sort.add(sortByTreeMenu);
+      if(comps.elementAt(i) instanceof TreePanel)
+      {
+        treePanels.add(comps.elementAt(i));
+      }
     }
 
-    sortByTreeMenu.add(item);
-    item.addActionListener(new java.awt.event.ActionListener()
+    iSize = treePanels.size();
+
+    if(iSize<1)
     {
-      public void actionPerformed(ActionEvent e)
-      {
-        addHistoryItem(new HistoryItem("Tree Sort",
-                                       viewport.alignment, HistoryItem.SORT));
-        AlignmentSorter.sortByTree(viewport.getAlignment(),
-                                   treePanel.getTree());
-        alignPanel.repaint();
-      }
-    });
+      sortByTreeMenu.setVisible(false);
+      return;
+    }
 
-    treePanel.addInternalFrameListener(new javax.swing.event.
-                                       InternalFrameAdapter()
+    sortByTreeMenu.setVisible(true);
+
+    for(i=0; i<treePanels.size(); i++)
     {
-      public void internalFrameClosed(
-          javax.swing.event.InternalFrameEvent evt)
+      TreePanel tp = (TreePanel)treePanels.elementAt(i);
+      final JMenuItem item = new JMenuItem(tp.getTitle());
+      final NJTree tree = ((TreePanel)treePanels.elementAt(i)).getTree();
+      item.addActionListener(new java.awt.event.ActionListener()
       {
-        treeCount--;
-        sortByTreeMenu.remove(item);
-
-        if (treeCount == 0)
+        public void actionPerformed(ActionEvent e)
         {
-          sort.remove(sortByTreeMenu);
+          SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
+          AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
+
+          addHistoryItem(new OrderCommand("Tree Sort",
+                                          oldOrder,
+                                          viewport.alignment));
+
+          alignPanel.paintAlignment(true);
         }
-      }
-      ;
-    });
+      });
+
+      sortByTreeMenu.add(item);
+    }
   }
 
   /**
@@ -2649,7 +3107,7 @@ public class AlignFrame
     AlignmentView msa = null;
 
     if ( (viewport.getSelectionGroup() != null) &&
-        (viewport.getSelectionGroup().getSize(false) > 1))
+        (viewport.getSelectionGroup().getSize() > 1))
     {
       // JBPNote UGLY! To prettify, make SequenceGroup and Alignment conform to some common interface!
       /*SequenceGroup seqs = viewport.getSelectionGroup();
@@ -2691,7 +3149,7 @@ public class AlignFrame
    AlignmentView seqs = null;
 
     if ( (viewport.getSelectionGroup() != null) &&
-        (viewport.getSelectionGroup().getSize(false) > 0))
+        (viewport.getSelectionGroup().getSize() > 0))
     {
       seqs = viewport.getAlignmentView(true);
     }
@@ -2703,7 +3161,8 @@ public class AlignFrame
     // TODO: viewport.alignment.isAligned is a global state - the local selection may well be aligned - we preserve 2.0.8 behaviour for moment.
     if (!viewport.alignment.isAligned())
     {
-      seqs.setSequences(new SeqCigar[] { seqs.getSequences()[0] } );
+      seqs.setSequences(new SeqCigar[]
+                        {seqs.getSequences()[0]});
     }
     return seqs;
   }
@@ -2751,15 +3210,20 @@ public class AlignFrame
   {
     return ShowNewickTree(nf,title,600,500,4,5);
   }
-  public TreePanel ShowNewickTree(NewickFile nf, String title, AlignmentView input)
+
+  public TreePanel ShowNewickTree(NewickFile nf, String title,
+                                  AlignmentView input)
   {
     return ShowNewickTree(nf,title, input, 600,500,4,5);
   }
-  public TreePanel ShowNewickTree(NewickFile nf, String title, int w,int h,int x, int y) {
+
+  public TreePanel ShowNewickTree(NewickFile nf, String title, int w, int h,
+                                  int x, int y)
+  {
     return ShowNewickTree(nf, title, null, w, h, x, y);
   }
   /**
-   * Add a treeviewer for the tree extracted from a newick file object to the current alignment view 
+   * Add a treeviewer for the tree extracted from a newick file object to the current alignment view
    *
    * @param nf the tree
    * @param title tree viewer title
@@ -2770,7 +3234,10 @@ public class AlignFrame
    * @param y position
    * @return TreePanel handle
    */
-  public TreePanel ShowNewickTree(NewickFile nf, String title, AlignmentView input, int w,int h,int x, int y) {
+  public TreePanel ShowNewickTree(NewickFile nf, String title,
+                                  AlignmentView input, int w, int h, int x,
+                                  int y)
+  {
     TreePanel tp = null;
 
     try
@@ -2787,11 +3254,12 @@ public class AlignFrame
         tp.setSize(w,h);
 
         if(x>0 && y>0)
+        {
           tp.setLocation(x,y);
+        }
 
 
         Desktop.addInternalFrame(tp, title, w, h);
-        addTreeMenuItem(tp, title);
       }
     }
     catch (Exception ex)
@@ -2802,28 +3270,6 @@ public class AlignFrame
     return tp;
   }
 
-  class PrintThread
-      extends Thread
-  {
-    public void run()
-    {
-      PrinterJob printJob = PrinterJob.getPrinterJob();
-      PageFormat pf = printJob.pageDialog(printJob.defaultPage());
-      printJob.setPrintable(alignPanel, pf);
-
-      if (printJob.printDialog())
-      {
-        try
-        {
-          printJob.print();
-        }
-        catch (Exception PrintException)
-        {
-          PrintException.printStackTrace();
-        }
-      }
-    }
-  }
 
   /**
    * Generates menu items and listener event actions for web service clients
@@ -2853,7 +3299,9 @@ public class AlignFrame
             {
               AlignmentView msa = gatherSequencesForAlignment();
               new jalview.ws.MsaWSClient(sh, title, msa,
-                  false, true, viewport.getAlignment().getDataset(), af);
+                                         false, true,
+                                         viewport.getAlignment().getDataset(),
+                                         af);
 
             }
 
@@ -2870,7 +3318,9 @@ public class AlignFrame
               {
                 AlignmentView msa = gatherSequencesForAlignment();
                 new jalview.ws.MsaWSClient(sh, title, msa,
-                    true, true, viewport.getAlignment().getDataset(), af);
+                                           true, true,
+                                           viewport.getAlignment().getDataset(),
+                                           af);
 
               }
 
@@ -2915,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));
@@ -2923,7 +3373,7 @@ public class AlignFrame
     }
     else
     {
-      this.webService.removeAll();
+      resetWebServiceMenu();
       this.webService.add(this.webServiceNoServices);
     }
     // TODO: add in rediscovery function
@@ -2931,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.
@@ -2952,95 +3427,34 @@ public class AlignFrame
 
 
 
-
 public void showTranslation_actionPerformed(ActionEvent e)
 {
-  SequenceI [] selection = viewport.getSelectionAsNewSequence();
-  String [] seqstring = viewport.getViewAsString(true);
-
-  int s, sSize = selection.length;
-  SequenceI [] newSeq = new SequenceI[sSize];
-
-  int res, resSize;
-  StringBuffer protein;
-  String seq;
-  for(s=0; s<sSize; s++)
-  {
-    protein = new StringBuffer();
-    seq = AlignSeq.extractGaps("-. ", seqstring[s]);
-    resSize = seq.length();
-    resSize -= resSize%3;
-
-    for(res = 0; res < resSize; res+=3)
-    {
-      String codon = seq.substring(res, res+3);
-      codon = codon.replace('U', 'T');
-      String aa = ResidueProperties.codonTranslate(codon);
-      if(aa==null)
-        protein.append(viewport.getGapCharacter());
-      else if(aa.equals("STOP"))
-        protein.append("X");
-      else
-        protein.append( aa );
-    }
-    newSeq[s] = new Sequence(selection[s].getName(),
-                             protein.toString());
-  }
-
-
-  AlignmentI al = new Alignment(newSeq);
-  al.setDataset(null);
-
-
-  ////////////////////////////////
-  // Copy annotations across
-  jalview.datamodel.AlignmentAnnotation[] annotations
-      = viewport.alignment.getAlignmentAnnotation();
-  int a, aSize;
-  if(annotations!=null)
-  {
-    for (int i = 0; i < annotations.length; i++)
-    {
-      if (annotations[i].label.equals("Quality") ||
-          annotations[i].label.equals("Conservation") ||
-          annotations[i].label.equals("Consensus"))
-      {
-        continue;
-      }
-
-      aSize = viewport.alignment.getWidth() / 3;
-      jalview.datamodel.Annotation[] anots =
-          new jalview.datamodel.Annotation[aSize];
-
-      for (a = 0; a < viewport.alignment.getWidth(); a++)
-      {
-        if (annotations[i].annotations[a] == null
-            || annotations[i].annotations[a] == null)
-          continue;
-
-        anots[a / 3] = new Annotation(
-            annotations[i].annotations[a].displayCharacter,
-            annotations[i].annotations[a].description,
-            annotations[i].annotations[a].secondaryStructure,
-            annotations[i].annotations[a].value,
-            annotations[i].annotations[a].colour);
-      }
-
-      jalview.datamodel.AlignmentAnnotation aa
-          = new jalview.datamodel.AlignmentAnnotation(annotations[i].label,
-          annotations[i].description, anots);
-      al.addAnnotation(aa);
-    }
-  }
+  ///////////////////////////////
+  // Collect Data to be translated/transferred
 
+  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());
+  } 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);
-
-
-
-
+  }
 }
 
 /**
@@ -3051,8 +3465,10 @@ public void showTranslation_actionPerformed(ActionEvent e)
 public boolean parseFeaturesFile(String file, String type)
 {
     boolean featuresFile = false;
-    try{
-      featuresFile = new FeaturesFile(file, type).parse(viewport.alignment.getDataset(),
+    try
+    {
+      featuresFile = new FeaturesFile(file,
+          type).parse(viewport.alignment.getDataset(),
                                          alignPanel.seqPanel.seqCanvas.
                                          getFeatureRenderer().featureColours,
                                          false);
@@ -3066,7 +3482,7 @@ public boolean parseFeaturesFile(String file, String type)
     {
       viewport.showSequenceFeatures = true;
       showSeqFeatures.setSelected(true);
-      alignPanel.repaint();
+      alignPanel.paintAlignment(true);
     }
 
     return featuresFile;
@@ -3091,12 +3507,14 @@ public void drop(DropTargetDropEvent evt)
 
     try
     {
-      DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String");
+      DataFlavor uriListFlavor = new DataFlavor(
+          "text/uri-list;class=java.lang.String");
       if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
       {
         //Works on Windows and MacOSX
         evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
-        files = (java.util.List) t.getTransferData(DataFlavor.javaFileListFlavor);
+        files = (java.util.List) t.getTransferData(DataFlavor.
+            javaFileListFlavor);
       }
       else if (t.isDataFlavorSupported(uriListFlavor))
       {
@@ -3149,7 +3567,8 @@ public void drop(DropTargetDropEvent evt)
   // AlignFrame
    public void loadJalviewDataFile(String file)
   {
-    try{
+    try
+    {
       String protocol = "File";
 
       if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
@@ -3158,7 +3577,7 @@ public void drop(DropTargetDropEvent evt)
       }
 
       boolean isAnnotation = new AnnotationFile().readAnnotationFile(viewport.
-          alignment, file);
+          alignment, file, protocol);
 
       if (!isAnnotation)
       {
@@ -3175,19 +3594,22 @@ public void drop(DropTargetDropEvent evt)
                 viewport.getAlignment(),
                 0, false);
             alignPanel.adjustAnnotationHeight();
-            alignPanel.repaint();
+            alignPanel.paintAlignment(true);
           }
           else
+          {
             new FileLoader().LoadFile(viewport, file, protocol, format);
         }
       }
+      }
       else
       {
         // (isAnnotation)
         alignPanel.adjustAnnotationHeight();
       }
 
-    }catch(Exception ex)
+    }
+    catch (Exception ex)
     {
       ex.printStackTrace();
     }
@@ -3199,6 +3621,7 @@ public void drop(DropTargetDropEvent evt)
     {
       alignPanel = (AlignmentPanel) alignPanels.elementAt(index);
       viewport = alignPanel.av;
+      setMenusFromViewport(viewport);
     }
   }
 
@@ -3224,4 +3647,40 @@ public void drop(DropTargetDropEvent evt)
   {
     return viewport;
   }
-}
\ No newline at end of file
+}
+
+class PrintThread
+    extends Thread
+{
+  AlignmentPanel ap;
+  public PrintThread(AlignmentPanel ap)
+  {
+   this.ap = ap;
+  }
+  static PageFormat pf;
+  public void run()
+  {
+    PrinterJob printJob = PrinterJob.getPrinterJob();
+
+    if (pf != null)
+    {
+      printJob.setPrintable(ap, pf);
+    }
+    else
+    {
+      printJob.setPrintable(ap);
+    }
+
+    if (printJob.printDialog())
+    {
+      try
+      {
+        printJob.print();
+      }
+      catch (Exception PrintException)
+      {
+        PrintException.printStackTrace();
+      }
+    }
+  }
+}