JAL-244 Added light grey marks to indicate regions to resize the margins
[jalview.git] / src / jalview / gui / AnnotationLabels.java
index 15f1fe0..6006026 100755 (executable)
  */
 package jalview.gui;
 
-import jalview.analysis.AlignSeq;
-import jalview.analysis.AlignmentUtils;
-import jalview.datamodel.Alignment;
-import jalview.datamodel.AlignmentAnnotation;
-import jalview.datamodel.Annotation;
-import jalview.datamodel.Sequence;
-import jalview.datamodel.SequenceGroup;
-import jalview.datamodel.SequenceI;
-import jalview.io.FileFormat;
-import jalview.io.FormatAdapter;
-import jalview.util.Comparison;
-import jalview.util.MessageManager;
-import jalview.util.Platform;
-
+import java.awt.Canvas;
 import java.awt.Color;
 import java.awt.Cursor;
 import java.awt.Dimension;
@@ -50,10 +37,10 @@ import java.awt.event.MouseEvent;
 import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
 import java.awt.geom.AffineTransform;
-import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
-import java.util.regex.Pattern;
+import java.util.Iterator;
+import java.util.Locale;
 
 import javax.swing.JCheckBoxMenuItem;
 import javax.swing.JMenuItem;
@@ -62,6 +49,25 @@ import javax.swing.JPopupMenu;
 import javax.swing.SwingUtilities;
 import javax.swing.ToolTipManager;
 
+import jalview.analysis.AlignSeq;
+import jalview.analysis.AlignmentUtils;
+import jalview.bin.Cache;
+import jalview.bin.Jalview;
+import jalview.datamodel.Alignment;
+import jalview.datamodel.AlignmentAnnotation;
+import jalview.datamodel.Annotation;
+import jalview.datamodel.ContactMatrixI;
+import jalview.datamodel.GroupSet;
+import jalview.datamodel.HiddenColumns;
+import jalview.datamodel.Sequence;
+import jalview.datamodel.SequenceGroup;
+import jalview.datamodel.SequenceI;
+import jalview.io.FileFormat;
+import jalview.io.FormatAdapter;
+import jalview.util.Comparison;
+import jalview.util.MessageManager;
+import jalview.util.Platform;
+
 /**
  * The panel that holds the labels for alignment annotations, providing
  * tooltips, context menus, drag to reorder rows, and drag to adjust panel
@@ -70,6 +76,10 @@ import javax.swing.ToolTipManager;
 public class AnnotationLabels extends JPanel
         implements MouseListener, MouseMotionListener, ActionListener
 {
+  private static final String HTML_END_TAG = "</html>";
+
+  private static final String HTML_START_TAG = "<html>";
+
   /**
    * width in pixels within which height adjuster arrows are shown and active
    */
@@ -78,10 +88,7 @@ public class AnnotationLabels extends JPanel
   /**
    * height in pixels for allowing height adjuster to be active
    */
-  private static int HEIGHT_ADJUSTER_HEIGHT = 10;
-
-  private static final Pattern LEFT_ANGLE_BRACKET_PATTERN = Pattern
-          .compile("<");
+  public static int HEIGHT_ADJUSTER_HEIGHT = 10;
 
   private static final Font font = new Font("Arial", Font.PLAIN, 11);
 
@@ -109,6 +116,8 @@ public class AnnotationLabels extends JPanel
   private static final String COPYCONS_SEQ = MessageManager
           .getString("label.copy_consensus_sequence");
 
+  private static final String ADJUST_ANNOTATION_LABELS_WIDTH_PREF = "ADJUST_ANNOTATION_LABELS_WIDTH";
+
   private final boolean debugRedraw = false;
 
   private AlignmentPanel ap;
@@ -127,6 +136,10 @@ public class AnnotationLabels extends JPanel
 
   private boolean resizePanel = false;
 
+  private int annotationIdWidth = -1;
+
+  public static final String RESIZE_MARGINS_MARK_PREF = "RESIZE_MARGINS_MARK";
+
   /**
    * Creates a new AnnotationLabels object
    * 
@@ -207,41 +220,33 @@ public class AnnotationLabels extends JPanel
     AlignmentAnnotation[] aa = ap.av.getAlignment()
             .getAlignmentAnnotation();
 
-    boolean fullRepaint = false;
-    if (evt.getActionCommand().equals(ADDNEW))
+    String action = evt.getActionCommand();
+    if (ADDNEW.equals(action))
     {
+      /*
+       * non-returning dialog
+       */
       AlignmentAnnotation newAnnotation = new AlignmentAnnotation(null,
               null, new Annotation[ap.av.getAlignment().getWidth()]);
-
-      if (!editLabelDescription(newAnnotation))
-      {
-        return;
-      }
-
-      ap.av.getAlignment().addAnnotation(newAnnotation);
-      ap.av.getAlignment().setAnnotationIndex(newAnnotation, 0);
-      fullRepaint = true;
+      editLabelDescription(newAnnotation, true);
     }
-    else if (evt.getActionCommand().equals(EDITNAME))
+    else if (EDITNAME.equals(action))
     {
-      String name = aa[selectedRow].label;
-      editLabelDescription(aa[selectedRow]);
-      if (!name.equalsIgnoreCase(aa[selectedRow].label))
-      {
-        fullRepaint = true;
-      }
+      /*
+       * non-returning dialog
+       */
+      editLabelDescription(aa[selectedRow], false);
     }
-    else if (evt.getActionCommand().equals(HIDE))
+    else if (HIDE.equals(action))
     {
       aa[selectedRow].visible = false;
     }
-    else if (evt.getActionCommand().equals(DELETE))
+    else if (DELETE.equals(action))
     {
       ap.av.getAlignment().deleteAnnotation(aa[selectedRow]);
       ap.av.getCalcManager().removeWorkerForAnnotation(aa[selectedRow]);
-      fullRepaint = true;
     }
-    else if (evt.getActionCommand().equals(SHOWALL))
+    else if (SHOWALL.equals(action))
     {
       for (int i = 0; i < aa.length; i++)
       {
@@ -250,15 +255,12 @@ public class AnnotationLabels extends JPanel
           aa[i].visible = true;
         }
       }
-      fullRepaint = true;
     }
-    else if (evt.getActionCommand().equals(OUTPUT_TEXT))
+    else if (OUTPUT_TEXT.equals(action))
     {
-      new AnnotationExporter().exportAnnotations(ap,
-              new AlignmentAnnotation[]
-              { aa[selectedRow] });
+      new AnnotationExporter(ap).exportAnnotation(aa[selectedRow]);
     }
-    else if (evt.getActionCommand().equals(COPYCONS_SEQ))
+    else if (COPYCONS_SEQ.equals(action))
     {
       SequenceI cons = null;
       if (aa[selectedRow].groupRef != null)
@@ -273,46 +275,48 @@ public class AnnotationLabels extends JPanel
       {
         copy_annotseqtoclipboard(cons);
       }
-
     }
-    else if (evt.getActionCommand().equals(TOGGLE_LABELSCALE))
+    else if (TOGGLE_LABELSCALE.equals(action))
     {
       aa[selectedRow].scaleColLabel = !aa[selectedRow].scaleColLabel;
     }
 
-    ap.refresh(fullRepaint);
-
+    ap.refresh(true);
   }
 
   /**
-   * DOCUMENT ME!
+   * Shows a dialog where the annotation name and description may be edited. If
+   * parameter addNew is true, then on confirmation, a new AlignmentAnnotation
+   * is added, else an existing annotation is updated.
    * 
-   * @param e
-   *          DOCUMENT ME!
+   * @param annotation
+   * @param addNew
    */
-  boolean editLabelDescription(AlignmentAnnotation annotation)
+  void editLabelDescription(AlignmentAnnotation annotation, boolean addNew)
   {
-    // TODO i18n
+    String name = MessageManager.getString("label.annotation_name");
+    String description = MessageManager
+            .getString("label.annotation_description");
+    String title = MessageManager
+            .getString("label.edit_annotation_name_description");
     EditNameDialog dialog = new EditNameDialog(annotation.label,
-            annotation.description, "       Annotation Name ",
-            "Annotation Description ", "Edit Annotation Name/Description",
-            ap.alignFrame);
+            annotation.description, name, description);
 
-    if (!dialog.accept)
-    {
-      return false;
-    }
-
-    annotation.label = dialog.getName();
-
-    String text = dialog.getDescription();
-    if (text != null && text.length() == 0)
-    {
-      text = null;
-    }
-    annotation.description = text;
-
-    return true;
+    dialog.showDialog(ap.alignFrame, title, () -> {
+      annotation.label = dialog.getName();
+      String text = dialog.getDescription();
+      if (text != null && text.length() == 0)
+      {
+        text = null;
+      }
+      annotation.description = text;
+      if (addNew)
+      {
+        ap.av.getAlignment().addAnnotation(annotation);
+        ap.av.getAlignment().setAnnotationIndex(annotation, 0);
+      }
+      ap.refresh(true);
+    });
   }
 
   @Override
@@ -377,15 +381,6 @@ public class AnnotationLabels extends JPanel
             AlignmentUtils.showOrHideSequenceAnnotations(
                     ap.av.getAlignment(), Collections.singleton(label),
                     null, false, false);
-            // for (AlignmentAnnotation ann : ap.av.getAlignment()
-            // .getAlignmentAnnotation())
-            // {
-            // if (ann.sequenceRef != null && ann.label != null
-            // && ann.label.equals(label))
-            // {
-            // ann.visible = false;
-            // }
-            // }
             ap.refresh(true);
           }
         });
@@ -424,174 +419,305 @@ public class AnnotationLabels extends JPanel
       }
       else if (label.indexOf("Consensus") > -1)
       {
-        pop.addSeparator();
-        // av and sequencegroup need to implement same interface for
-        final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
-                MessageManager.getString("label.ignore_gaps_consensus"),
-                (aa[selectedRow].groupRef != null)
-                        ? aa[selectedRow].groupRef.getIgnoreGapsConsensus()
-                        : ap.av.isIgnoreGapsConsensus());
-        final AlignmentAnnotation aaa = aa[selectedRow];
-        cbmi.addActionListener(new ActionListener()
+        addConsensusMenuOptions(ap, aa[selectedRow], pop);
+
+        final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
+        consclipbrd.addActionListener(this);
+        pop.add(consclipbrd);
+      }
+
+      addColourOrFilterByOptions(ap, aa[selectedRow], pop);
+
+      if (aa[selectedRow].graph == AlignmentAnnotation.CONTACT_MAP)
+      {
+        addContactMatrixOptions(ap, aa[selectedRow], pop);
+        // Set/adjust threshold for grouping ?
+        // colour alignment by this [type]
+        // select/hide columns by this row
+
+      }
+    }
+
+    pop.show(this, evt.getX(), evt.getY());
+  }
+
+  static void addColourOrFilterByOptions(final AlignmentPanel ap,
+          final AlignmentAnnotation alignmentAnnotation,
+          final JPopupMenu pop)
+  {
+    JMenuItem item;
+    item = new JMenuItem(
+            MessageManager.getString("label.colour_by_annotation"));
+    item.addActionListener(new ActionListener()
+    {
+
+      @Override
+      public void actionPerformed(ActionEvent e)
+      {
+        AnnotationColourChooser.displayFor(ap.av, ap, alignmentAnnotation,
+                false);
+      };
+    });
+    pop.add(item);
+    if (alignmentAnnotation.sequenceRef != null)
+    {
+      item = new JMenuItem(
+              MessageManager.getString("label.colour_by_annotation") + " ("
+                      + MessageManager.getString("label.per_seq") + ")");
+      item.addActionListener(new ActionListener()
+      {
+        @Override
+        public void actionPerformed(ActionEvent e)
         {
+          AnnotationColourChooser.displayFor(ap.av, ap, alignmentAnnotation,
+                  true);
+        };
+      });
+      pop.add(item);
+    }
+    item = new JMenuItem(
+            MessageManager.getString("action.select_by_annotation"));
+    item.addActionListener(new ActionListener()
+    {
+
+      @Override
+      public void actionPerformed(ActionEvent e)
+      {
+        AnnotationColumnChooser.displayFor(ap.av, ap, alignmentAnnotation);
+      };
+    });
+    pop.add(item);
+  }
+
+  static void addContactMatrixOptions(final AlignmentPanel ap,
+          final AlignmentAnnotation alignmentAnnotation,
+          final JPopupMenu pop)
+  {
+
+    final ContactMatrixI cm = ap.av.getContactMatrix(alignmentAnnotation);
+    JMenuItem item;
+    if (cm != null)
+    {
+      pop.addSeparator();
+
+      if (cm.hasGroups())
+      {
+        JCheckBoxMenuItem chitem = new JCheckBoxMenuItem(
+                MessageManager.getString("action.show_groups_on_matrix"));
+        chitem.setToolTipText(MessageManager
+                .getString("action.show_groups_on_matrix_tooltip"));
+        boolean showGroups = alignmentAnnotation
+                .isShowGroupsForContactMatrix();
+        final AlignmentAnnotation sel_row = alignmentAnnotation;
+        chitem.setState(showGroups);
+        chitem.addActionListener(new ActionListener()
+        {
+
           @Override
           public void actionPerformed(ActionEvent e)
           {
-            if (aaa.groupRef != null)
-            {
-              // TODO: pass on reference to ap so the view can be updated.
-              aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
-              ap.getAnnotationPanel()
-                      .paint(ap.getAnnotationPanel().getGraphics());
-            }
-            else
-            {
-              ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
-            }
+            sel_row.setShowGroupsForContactMatrix(chitem.getState());
+            // so any annotation colour changes are propagated - though they
+            // probably won't be unless the annotation row colours are removed
+            // too!
             ap.alignmentChanged();
           }
         });
-        pop.add(cbmi);
-        // av and sequencegroup need to implement same interface for
-        if (aaa.groupRef != null)
+        pop.add(chitem);
+      }
+      if (cm.hasTree())
+      {
+        item = new JMenuItem(
+                MessageManager.getString("action.show_tree_for_matrix"));
+        item.setToolTipText(MessageManager
+                .getString("action.show_tree_for_matrix_tooltip"));
+        item.addActionListener(new ActionListener()
         {
-          final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
-                  MessageManager.getString("label.show_group_histogram"),
-                  aa[selectedRow].groupRef.isShowConsensusHistogram());
-          chist.addActionListener(new ActionListener()
-          {
-            @Override
-            public void actionPerformed(ActionEvent e)
-            {
-              // TODO: pass on reference
-              // to ap
-              // so the
-              // view
-              // can be
-              // updated.
-              aaa.groupRef.setShowConsensusHistogram(chist.getState());
-              ap.repaint();
-              // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
-            }
-          });
-          pop.add(chist);
-          final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
-                  MessageManager.getString("label.show_group_logo"),
-                  aa[selectedRow].groupRef.isShowSequenceLogo());
-          cprofl.addActionListener(new ActionListener()
+
+          @Override
+          public void actionPerformed(ActionEvent e)
           {
-            @Override
-            public void actionPerformed(ActionEvent e)
-            {
-              // TODO: pass on reference
-              // to ap
-              // so the
-              // view
-              // can be
-              // updated.
-              aaa.groupRef.setshowSequenceLogo(cprofl.getState());
-              ap.repaint();
-              // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
-            }
-          });
-          pop.add(cprofl);
-          final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
-                  MessageManager.getString("label.normalise_group_logo"),
-                  aa[selectedRow].groupRef.isNormaliseSequenceLogo());
-          cproflnorm.addActionListener(new ActionListener()
+
+            ap.alignFrame.showContactMapTree(alignmentAnnotation, cm);
+
+          }
+        });
+        pop.add(item);
+      }
+      else
+      {
+        item = new JMenuItem(
+                MessageManager.getString("action.cluster_matrix"));
+        item.setToolTipText(
+                MessageManager.getString("action.cluster_matrix_tooltip"));
+        item.addActionListener(new ActionListener()
+        {
+          @Override
+          public void actionPerformed(ActionEvent e)
           {
-            @Override
-            public void actionPerformed(ActionEvent e)
+            new Thread(new Runnable()
             {
+              @Override
+              public void run()
+              {
+                final long progBar;
+                ap.alignFrame.setProgressBar(
+                        MessageManager.formatMessage(
+                                "action.clustering_matrix_for",
+                                cm.getAnnotDescr(), 5f),
+                        progBar = System.currentTimeMillis());
+                cm.setGroupSet(GroupSet.makeGroups(cm, true));
+                cm.randomlyReColourGroups();
+                cm.transferGroupColorsTo(alignmentAnnotation);
+                ap.alignmentChanged();
+                ap.alignFrame.showContactMapTree(alignmentAnnotation, cm);
+                ap.alignFrame.setProgressBar(null, progBar);
+              }
+            }).start();
+          }
+        });
+        pop.add(item);
+      }
+    }
+  }
 
-              // TODO: pass on reference
-              // to ap
-              // so the
-              // view
-              // can be
-              // updated.
-              aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
-              // automatically enable logo display if we're clicked
-              aaa.groupRef.setshowSequenceLogo(true);
-              ap.repaint();
-              // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
-            }
-          });
-          pop.add(cproflnorm);
+  /**
+   * A helper method that adds menu options for calculation and visualisation of
+   * group and/or alignment consensus annotation to a popup menu. This is
+   * designed to be reusable for either unwrapped mode (popup menu is shown on
+   * component AnnotationLabels), or wrapped mode (popup menu is shown on
+   * IdPanel when the mouse is over an annotation label).
+   * 
+   * @param ap
+   * @param ann
+   * @param pop
+   */
+  static void addConsensusMenuOptions(AlignmentPanel ap,
+          AlignmentAnnotation ann, JPopupMenu pop)
+  {
+    pop.addSeparator();
+
+    final JCheckBoxMenuItem cbmi = new JCheckBoxMenuItem(
+            MessageManager.getString("label.ignore_gaps_consensus"),
+            (ann.groupRef != null) ? ann.groupRef.getIgnoreGapsConsensus()
+                    : ap.av.isIgnoreGapsConsensus());
+    final AlignmentAnnotation aaa = ann;
+    cbmi.addActionListener(new ActionListener()
+    {
+      @Override
+      public void actionPerformed(ActionEvent e)
+      {
+        if (aaa.groupRef != null)
+        {
+          aaa.groupRef.setIgnoreGapsConsensus(cbmi.getState());
+          ap.getAnnotationPanel()
+                  .paint(ap.getAnnotationPanel().getGraphics());
         }
         else
         {
-          final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
-                  MessageManager.getString("label.show_histogram"),
-                  av.isShowConsensusHistogram());
-          chist.addActionListener(new ActionListener()
-          {
-            @Override
-            public void actionPerformed(ActionEvent e)
-            {
-              // TODO: pass on reference
-              // to ap
-              // so the
-              // view
-              // can be
-              // updated.
-              av.setShowConsensusHistogram(chist.getState());
-              ap.alignFrame.setMenusForViewport();
-              ap.repaint();
-              // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
-            }
-          });
-          pop.add(chist);
-          final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
-                  MessageManager.getString("label.show_logo"),
-                  av.isShowSequenceLogo());
-          cprof.addActionListener(new ActionListener()
-          {
-            @Override
-            public void actionPerformed(ActionEvent e)
-            {
-              // TODO: pass on reference
-              // to ap
-              // so the
-              // view
-              // can be
-              // updated.
-              av.setShowSequenceLogo(cprof.getState());
-              ap.alignFrame.setMenusForViewport();
-              ap.repaint();
-              // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
-            }
-          });
-          pop.add(cprof);
-          final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
-                  MessageManager.getString("label.normalise_logo"),
-                  av.isNormaliseSequenceLogo());
-          cprofnorm.addActionListener(new ActionListener()
-          {
-            @Override
-            public void actionPerformed(ActionEvent e)
-            {
-              // TODO: pass on reference
-              // to ap
-              // so the
-              // view
-              // can be
-              // updated.
-              av.setShowSequenceLogo(true);
-              av.setNormaliseSequenceLogo(cprofnorm.getState());
-              ap.alignFrame.setMenusForViewport();
-              ap.repaint();
-              // ap.annotationPanel.paint(ap.annotationPanel.getGraphics());
-            }
-          });
-          pop.add(cprofnorm);
+          ap.av.setIgnoreGapsConsensus(cbmi.getState(), ap);
         }
-        final JMenuItem consclipbrd = new JMenuItem(COPYCONS_SEQ);
-        consclipbrd.addActionListener(this);
-        pop.add(consclipbrd);
+        ap.alignmentChanged();
       }
+    });
+    pop.add(cbmi);
+
+    if (aaa.groupRef != null)
+    {
+      /*
+       * group consensus options
+       */
+      final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
+              MessageManager.getString("label.show_group_histogram"),
+              ann.groupRef.isShowConsensusHistogram());
+      chist.addActionListener(new ActionListener()
+      {
+        @Override
+        public void actionPerformed(ActionEvent e)
+        {
+          aaa.groupRef.setShowConsensusHistogram(chist.getState());
+          ap.repaint();
+        }
+      });
+      pop.add(chist);
+      final JCheckBoxMenuItem cprofl = new JCheckBoxMenuItem(
+              MessageManager.getString("label.show_group_logo"),
+              ann.groupRef.isShowSequenceLogo());
+      cprofl.addActionListener(new ActionListener()
+      {
+        @Override
+        public void actionPerformed(ActionEvent e)
+        {
+          aaa.groupRef.setshowSequenceLogo(cprofl.getState());
+          ap.repaint();
+        }
+      });
+      pop.add(cprofl);
+      final JCheckBoxMenuItem cproflnorm = new JCheckBoxMenuItem(
+              MessageManager.getString("label.normalise_group_logo"),
+              ann.groupRef.isNormaliseSequenceLogo());
+      cproflnorm.addActionListener(new ActionListener()
+      {
+        @Override
+        public void actionPerformed(ActionEvent e)
+        {
+          aaa.groupRef.setNormaliseSequenceLogo(cproflnorm.getState());
+          // automatically enable logo display if we're clicked
+          aaa.groupRef.setshowSequenceLogo(true);
+          ap.repaint();
+        }
+      });
+      pop.add(cproflnorm);
+    }
+    else
+    {
+      /*
+       * alignment consensus options
+       */
+      final JCheckBoxMenuItem chist = new JCheckBoxMenuItem(
+              MessageManager.getString("label.show_histogram"),
+              ap.av.isShowConsensusHistogram());
+      chist.addActionListener(new ActionListener()
+      {
+        @Override
+        public void actionPerformed(ActionEvent e)
+        {
+          ap.av.setShowConsensusHistogram(chist.getState());
+          ap.alignFrame.setMenusForViewport();
+          ap.repaint();
+        }
+      });
+      pop.add(chist);
+      final JCheckBoxMenuItem cprof = new JCheckBoxMenuItem(
+              MessageManager.getString("label.show_logo"),
+              ap.av.isShowSequenceLogo());
+      cprof.addActionListener(new ActionListener()
+      {
+        @Override
+        public void actionPerformed(ActionEvent e)
+        {
+          ap.av.setShowSequenceLogo(cprof.getState());
+          ap.alignFrame.setMenusForViewport();
+          ap.repaint();
+        }
+      });
+      pop.add(cprof);
+      final JCheckBoxMenuItem cprofnorm = new JCheckBoxMenuItem(
+              MessageManager.getString("label.normalise_logo"),
+              ap.av.isNormaliseSequenceLogo());
+      cprofnorm.addActionListener(new ActionListener()
+      {
+        @Override
+        public void actionPerformed(ActionEvent e)
+        {
+          ap.av.setShowSequenceLogo(true);
+          ap.av.setNormaliseSequenceLogo(cprofnorm.getState());
+          ap.alignFrame.setMenusForViewport();
+          ap.repaint();
+        }
+      });
+      pop.add(cprofnorm);
     }
-    pop.show(this, evt.getX(), evt.getY());
   }
 
   /**
@@ -704,73 +830,123 @@ public class AnnotationLabels extends JPanel
     if (selectedRow > -1 && ap.av.getAlignment()
             .getAlignmentAnnotation().length > selectedRow)
     {
-      AlignmentAnnotation aa = ap.av.getAlignment()
-              .getAlignmentAnnotation()[selectedRow];
+      AlignmentAnnotation[] anns = ap.av.getAlignment()
+              .getAlignmentAnnotation();
+      AlignmentAnnotation aa = anns[selectedRow];
+
+      String desc = getTooltip(aa);
+      this.setToolTipText(desc);
+      String msg = getStatusMessage(aa, anns);
+      ap.alignFrame.setStatus(msg);
+    }
+  }
+
+  /**
+   * Constructs suitable text to show in the status bar when over an annotation
+   * label, containing the associated sequence name (if any), and the annotation
+   * labels (or all labels for a graph group annotation)
+   * 
+   * @param aa
+   * @param anns
+   * @return
+   */
+  static String getStatusMessage(AlignmentAnnotation aa,
+          AlignmentAnnotation[] anns)
+  {
+    if (aa == null)
+    {
+      return null;
+    }
 
-      StringBuffer desc = new StringBuffer();
-      if (aa.description != null
-              && !aa.description.equals("New description"))
+    StringBuilder msg = new StringBuilder(32);
+    if (aa.sequenceRef != null)
+    {
+      msg.append(aa.sequenceRef.getName()).append(" : ");
+    }
+
+    if (aa.graphGroup == -1)
+    {
+      msg.append(aa.label);
+    }
+    else if (anns != null)
+    {
+      boolean first = true;
+      for (int i = anns.length - 1; i >= 0; i--)
       {
-        // TODO: we could refactor and merge this code with the code in
-        // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
-        // tooltips
-        desc.append(aa.getDescription(true).trim());
-        // check to see if the description is an html fragment.
-        if (desc.length() < 6 || (desc.substring(0, 6).toLowerCase()
-                .indexOf("<html>") < 0))
+        if (anns[i].graphGroup == aa.graphGroup)
         {
-          // clean the description ready for embedding in html
-          desc = new StringBuffer(LEFT_ANGLE_BRACKET_PATTERN.matcher(desc)
-                  .replaceAll("&lt;"));
-          desc.insert(0, "<html>");
-        }
-        else
-        {
-          // remove terminating html if any
-          int i = desc.substring(desc.length() - 7).toLowerCase()
-                  .lastIndexOf("</html>");
-          if (i > -1)
+          if (!first)
           {
-            desc.setLength(desc.length() - 7 + i);
+            msg.append(", ");
           }
+          msg.append(anns[i].label);
+          first = false;
         }
-        if (aa.hasScore())
-        {
-          desc.append("<br/>");
-        }
-        // if (aa.hasProperties())
-        // {
-        // desc.append("<table>");
-        // for (String prop : aa.getProperties())
-        // {
-        // desc.append("<tr><td>" + prop + "</td><td>"
-        // + aa.getProperty(prop) + "</td><tr>");
-        // }
-        // desc.append("</table>");
-        // }
       }
-      else
+    }
+
+    return msg.toString();
+  }
+
+  /**
+   * Answers a tooltip, formatted as html, containing the annotation description
+   * (prefixed by associated sequence id if applicable), and the annotation
+   * (non-positional) score if it has one. Answers null if neither description
+   * nor score is found.
+   * 
+   * @param aa
+   * @return
+   */
+  static String getTooltip(AlignmentAnnotation aa)
+  {
+    if (aa == null)
+    {
+      return null;
+    }
+    StringBuilder tooltip = new StringBuilder();
+    if (aa.description != null && !aa.description.equals("New description"))
+    {
+      // TODO: we could refactor and merge this code with the code in
+      // jalview.gui.SeqPanel.mouseMoved(..) that formats sequence feature
+      // tooltips
+      String desc = aa.getDescription(true).trim();
+      if (!desc.toLowerCase(Locale.ROOT).startsWith(HTML_START_TAG))
       {
-        // begin the tooltip's html fragment
-        desc.append("<html>");
-        if (aa.hasScore())
-        {
-          // TODO: limit precision of score to avoid noise from imprecise
-          // doubles
-          // (64.7 becomes 64.7+/some tiny value).
-          desc.append(" Score: " + aa.score);
-        }
+        tooltip.append(HTML_START_TAG);
+        desc = desc.replace("<", "&lt;");
       }
-      if (desc.length() > 6)
+      else if (desc.toLowerCase(Locale.ROOT).endsWith(HTML_END_TAG))
       {
-        desc.append("</html>");
-        this.setToolTipText(desc.toString());
+        desc = desc.substring(0, desc.length() - HTML_END_TAG.length());
       }
-      else
+      tooltip.append(desc);
+    }
+    else
+    {
+      // begin the tooltip's html fragment
+      tooltip.append(HTML_START_TAG);
+    }
+    if (aa.hasScore())
+    {
+      if (tooltip.length() > HTML_START_TAG.length())
       {
-        this.setToolTipText(null);
+        tooltip.append("<br/>");
       }
+      // TODO: limit precision of score to avoid noise from imprecise
+      // doubles
+      // (64.7 becomes 64.7+/some tiny value).
+      tooltip.append(" Score: ").append(String.valueOf(aa.score));
     }
+
+    if (tooltip.length() > HTML_START_TAG.length())
+    {
+      return tooltip.append(HTML_END_TAG).toString();
+    }
+
+    /*
+     * nothing in the tooltip (except "<html>")
+     */
+    return null;
   }
 
   /**
@@ -782,12 +958,13 @@ public class AnnotationLabels extends JPanel
   protected void showOrHideAdjuster(MouseEvent evt)
   {
     boolean was = resizePanel;
-    resizePanel = evt.getY() < HEIGHT_ADJUSTER_HEIGHT && evt.getX() < HEIGHT_ADJUSTER_WIDTH;
+    resizePanel = evt.getY() < HEIGHT_ADJUSTER_HEIGHT
+            && evt.getX() < HEIGHT_ADJUSTER_WIDTH;
 
     if (resizePanel != was)
     {
-      setCursor(Cursor.getPredefinedCursor(
-              resizePanel ? Cursor.S_RESIZE_CURSOR
+      setCursor(Cursor
+              .getPredefinedCursor(resizePanel ? Cursor.S_RESIZE_CURSOR
                       : Cursor.DEFAULT_CURSOR));
       repaint();
     }
@@ -934,8 +1111,9 @@ public class AnnotationLabels extends JPanel
     Alignment ds = new Alignment(dseqs);
     if (av.hasHiddenColumns())
     {
-      omitHidden = av.getAlignment().getHiddenColumns()
-              .getVisibleSequenceStrings(0, sq.getLength(), seqs);
+      Iterator<int[]> it = av.getAlignment().getHiddenColumns()
+              .getVisContigsIterator(0, sq.getLength(), false);
+      omitHidden = new String[] { sq.getSequenceStringFromIterator(it) };
     }
 
     int[] alignmentStartEnd = new int[] { 0, ds.getWidth() - 1 };
@@ -951,12 +1129,12 @@ public class AnnotationLabels extends JPanel
     Toolkit.getDefaultToolkit().getSystemClipboard()
             .setContents(new StringSelection(output), Desktop.instance);
 
-    ArrayList<int[]> hiddenColumns = null;
+    HiddenColumns hiddenColumns = null;
 
     if (av.hasHiddenColumns())
     {
-      hiddenColumns = av.getAlignment().getHiddenColumns()
-              .getHiddenColumnsCopy();
+      hiddenColumns = new HiddenColumns(
+              av.getAlignment().getHiddenColumns());
     }
 
     Desktop.jalviewClipboard = new Object[] { seqs, ds, // what is the dataset
@@ -980,7 +1158,7 @@ public class AnnotationLabels extends JPanel
     int width = getWidth();
     if (width == 0)
     {
-      width = ap.calculateIdWidth().width + 4;
+      width = ap.calculateIdWidth().width;
     }
 
     Graphics2D g2 = (Graphics2D) g;
@@ -991,7 +1169,6 @@ public class AnnotationLabels extends JPanel
     }
 
     drawComponent(g2, true, width);
-
   }
 
   /**
@@ -1021,31 +1198,146 @@ public class AnnotationLabels extends JPanel
    * @param width
    *          Width for scaling labels
    */
-  public void drawComponent(Graphics g, boolean clip, int width)
+  public void drawComponent(Graphics g, boolean clip, int givenWidth)
   {
-    if (av.getFont().getSize() < 10)
+    int width = givenWidth;
+    IdwidthAdjuster iwa = null;
+    if (ap != null)
     {
-      g.setFont(font);
+      iwa = ap.idwidthAdjuster;
+      if ((Cache.getDefault(ADJUST_ANNOTATION_LABELS_WIDTH_PREF, true)
+              || Jalview.isHeadlessMode()))
+      {
+        Graphics2D g2d = (Graphics2D) g;
+        Graphics dummy = g2d.create();
+        int newAnnotationIdWidth = drawLabels(dummy, clip, width, false,
+                null);
+        dummy.dispose();
+        Dimension d = ap.calculateDefaultAlignmentIdWidth();
+        int alignmentIdWidth = d.width;
+        if (iwa != null && !iwa.manuallyAdjusted())
+        {
+          // If no manual adjustment to ID column with has been made then adjust
+          // width match widest of alignment or annotation id widths
+          boolean allowShrink = Cache.getDefault("ALLOW_SHRINK_ID_WIDTH",
+                  false);
+          width = Math.max(alignmentIdWidth, newAnnotationIdWidth);
+          if (clip && width < givenWidth && !allowShrink)
+          {
+            width = givenWidth;
+          }
+        }
+        else if (newAnnotationIdWidth != annotationIdWidth
+                && newAnnotationIdWidth > givenWidth
+                && newAnnotationIdWidth > alignmentIdWidth)
+        {
+          // otherwise if the annotation id width has become larger than the
+          // current id width, increase
+          width = newAnnotationIdWidth;
+          annotationIdWidth = newAnnotationIdWidth;
+        }
+        // set the width if it's changed
+        if (width != ap.av.getIdWidth())
+        {
+          iwa.setWidth(width);
+        }
+      }
     }
     else
     {
-      g.setFont(av.getFont());
+      int newAnnotationIdWidth = drawLabels(g, clip, width, false, null);
+      width = Math.max(newAnnotationIdWidth, givenWidth);
+    }
+    drawLabels(g, clip, width, true, null);
+  }
+
+  /**
+   * Render the full set of annotation Labels for the alignment at the given
+   * cursor. If actuallyDraw is false or g is null then no actual drawing will
+   * occur, but the widest label width will be returned. If g is null then
+   * fmetrics must be supplied.
+   * 
+   * Returns the width of the annotation labels.
+   * 
+   * @param g
+   *          Graphics2D instance (needed for font scaling)
+   * @param clip
+   *          - true indicates that only current visible area needs to be
+   *          rendered
+   * @param width
+   *          Width for scaling labels
+   * @param fmetrics
+   *          FontMetrics if Graphics object g is null
+   */
+  public int drawLabels(Graphics g0, boolean clip, int width,
+          boolean actuallyDraw, FontMetrics fmetrics)
+  {
+    if (clip)
+    {
+      clip = Cache.getDefault("MOVE_SEQUENCE_ID_WITH_VISIBLE_ANNOTATIONS",
+              true);
+    }
+    Graphics g = null;
+    // create a dummy Graphics object if not drawing and one is supplied
+    if (g0 != null)
+    {
+      if (!actuallyDraw)
+      {
+        Graphics2D g2d = (Graphics2D) g0;
+        g = g2d.create();
+      }
+      else
+      {
+        g = g0;
+      }
+    }
+    int actualWidth = 0;
+    if (g != null)
+    {
+      if (av.getFont().getSize() < 10)
+      {
+        g.setFont(font);
+      }
+      else
+      {
+        g.setFont(av.getFont());
+      }
     }
 
-    FontMetrics fm = g.getFontMetrics(g.getFont());
-    g.setColor(Color.white);
-    g.fillRect(0, 0, getWidth(), getHeight());
+    FontMetrics fm = fmetrics == null ? g.getFontMetrics(g.getFont())
+            : fmetrics;
+    if (actuallyDraw)
+    {
+      g.setColor(Color.white);
+      g.fillRect(0, 0, getWidth(), getHeight());
 
-    g.translate(0, getScrollOffset());
-    g.setColor(Color.black);
+      if (!Cache.getDefault(RESIZE_MARGINS_MARK_PREF, false)
+              && !av.getWrapAlignment())
+      {
+        g.setColor(Color.LIGHT_GRAY);
+        g.drawLine(0, HEIGHT_ADJUSTER_HEIGHT / 4, HEIGHT_ADJUSTER_WIDTH / 4,
+                HEIGHT_ADJUSTER_HEIGHT / 4);
+        g.drawLine(0, 3 * HEIGHT_ADJUSTER_HEIGHT / 4,
+                HEIGHT_ADJUSTER_WIDTH / 4, 3 * HEIGHT_ADJUSTER_HEIGHT / 4);
 
+      }
+    }
+
+    if (actuallyDraw)
+    {
+      g.translate(0, getScrollOffset());
+      g.setColor(Color.black);
+    }
+    SequenceI lastSeqRef = null;
+    String lastLabel = null;
     AlignmentAnnotation[] aa = av.getAlignment().getAlignmentAnnotation();
-    int fontHeight = g.getFont().getSize();
+    int fontHeight = g != null ? g.getFont().getSize()
+            : fm.getFont().getSize();
     int y = 0;
     int x = 0;
     int graphExtras = 0;
     int offset = 0;
-    Font baseFont = g.getFont();
+    Font baseFont = g != null ? g.getFont() : fm.getFont();
     FontMetrics baseMetrics = fm;
     int ofontH = fontHeight;
     int sOffset = 0;
@@ -1063,6 +1355,7 @@ public class AnnotationLabels extends JPanel
     {
       hasHiddenRows = false;
       int olY = 0;
+      int nexAA = 0;
       for (int i = 0; i < aa.length; i++)
       {
         visible = true;
@@ -1072,6 +1365,10 @@ public class AnnotationLabels extends JPanel
           continue;
         }
         olY = y;
+        // look ahead to next annotation
+        for (nexAA = i + 1; nexAA < aa.length
+                && !aa[nexAA].visible; nexAA++)
+          ;
         y += aa[i].height;
         if (clip)
         {
@@ -1104,8 +1401,10 @@ public class AnnotationLabels extends JPanel
             continue;
           }
         }
-        g.setColor(Color.black);
-
+        if (actuallyDraw && g != null)
+        {
+          g.setColor(Color.black);
+        }
         offset = -aa[i].height / 2;
 
         if (aa[i].hasText)
@@ -1117,8 +1416,42 @@ public class AnnotationLabels extends JPanel
         {
           offset += fm.getDescent();
         }
+        String label = aa[i].label;
+        boolean vertBar = false;
+        if ((lastLabel != null && lastLabel.equals(label)))
+        {
+          label = aa[i].description;
+        }
+        else
+        {
+          if (nexAA < aa.length && label.equals(aa[nexAA].label)) // &&
+                                                                  // aa[nexY].sequenceRef==aa[i].sequenceRef)
+          {
+            lastLabel = label;
+            // next label is the same as this label
+            label = aa[i].description;
+          }
+          else
+          {
+            lastLabel = label;
+          }
+        }
+        if (aa[i].sequenceRef != null)
+        {
+          if (aa[i].sequenceRef != lastSeqRef)
+          {
+            label = aa[i].sequenceRef.getName() + " " + label;
+            // TODO record relationship between sequence and this annotation and
+            // display it here
+          }
+          else
+          {
+            vertBar = true;
+          }
+        }
 
-        x = width - fm.stringWidth(aa[i].label) - 3;
+        int labelWidth = fm.stringWidth(label) + 3;
+        x = width - labelWidth;
 
         if (aa[i].graphGroup > -1)
         {
@@ -1151,10 +1484,15 @@ public class AnnotationLabels extends JPanel
               s = ((float) fontHeight) / (float) ofontH;
               Font f = baseFont
                       .deriveFont(AffineTransform.getScaleInstance(s, s));
-              g.setFont(f);
-              fm = g.getFontMetrics();
-              graphExtras = (aa[i].height - (groupSize * (fontHeight + 8)))
-                      / 2;
+              Canvas c = new Canvas();
+              fm = c.getFontMetrics(f);
+              if (actuallyDraw && g != null)
+              {
+                g.setFont(f);
+                // fm = g.getFontMetrics();
+                graphExtras = (aa[i].height
+                        - (groupSize * (fontHeight + 8))) / 2;
+              }
             }
           }
           if (visible)
@@ -1163,47 +1501,81 @@ public class AnnotationLabels extends JPanel
             {
               if (aa[gg].graphGroup == aa[i].graphGroup)
               {
-                x = width - fm.stringWidth(aa[gg].label) - 3;
-                g.drawString(aa[gg].label, x, y - graphExtras);
-
-                if (aa[gg]._linecolour != null)
+                labelWidth = fm.stringWidth(aa[gg].label) + 3;
+                x = width - labelWidth;
+                if (actuallyDraw && g != null)
                 {
+                  g.drawString(aa[gg].label, x, y - graphExtras);
 
-                  g.setColor(aa[gg]._linecolour);
-                  g.drawLine(x, y - graphExtras + 3,
-                          x + fm.stringWidth(aa[gg].label),
-                          y - graphExtras + 3);
-                }
+                  if (aa[gg]._linecolour != null)
+                  {
+
+                    g.setColor(aa[gg]._linecolour);
+                    g.drawLine(x, y - graphExtras + 3,
+                            x + fm.stringWidth(aa[gg].label),
+                            y - graphExtras + 3);
+                  }
 
-                g.setColor(Color.black);
+                  g.setColor(Color.black);
+                }
                 graphExtras += fontHeight + 8;
               }
             }
           }
-          g.setFont(baseFont);
+          if (actuallyDraw && g != null)
+          {
+            g.setFont(baseFont);
+          }
           fm = baseMetrics;
           fontHeight = ofontH;
         }
         else
         {
-          g.drawString(aa[i].label, x, y + offset);
+          if (actuallyDraw && g != null)
+          {
+            if (vertBar)
+            {
+              g.drawLine(width - 3, y + offset - fontHeight, width - 3,
+                      (int) (y - 1.5 * aa[i].height - offset - fontHeight));
+              // g.drawLine(20, y + offset, x - 20, y + offset);
+
+            }
+            g.drawString(label, x, y + offset);
+          }
+        }
+        lastSeqRef = aa[i].sequenceRef;
+
+        if (labelWidth > actualWidth)
+        {
+          actualWidth = labelWidth;
         }
       }
     }
 
     if (!resizePanel && dragEvent != null && aa != null)
     {
-      g.setColor(Color.lightGray);
-      g.drawString(aa[selectedRow].label, dragEvent.getX(),
-              dragEvent.getY() - getScrollOffset());
+      if (actuallyDraw && g != null)
+      {
+        g.setColor(Color.lightGray);
+        g.drawString(
+                (aa[selectedRow].sequenceRef == null ? ""
+                        : aa[selectedRow].sequenceRef.getName())
+                        + aa[selectedRow].label,
+                dragEvent.getX(), dragEvent.getY() - getScrollOffset());
+      }
     }
 
     if (!av.getWrapAlignment() && ((aa == null) || (aa.length < 1)))
     {
-      g.drawString(MessageManager.getString("label.right_click"), 2, 8);
-      g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
-              18);
+      if (actuallyDraw && g != null)
+      {
+        g.drawString(MessageManager.getString("label.right_click"), 2, 8);
+        g.drawString(MessageManager.getString("label.to_add_annotation"), 2,
+                18);
+      }
     }
+
+    return actualWidth;
   }
 
   public int getScrollOffset()