update author list in license for (JAL-826)
[jalview.git] / src / jalview / gui / FeatureSettings.java
index 0b645f2..bc663e6 100755 (executable)
@@ -1,20 +1,19 @@
 /*
- * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
- * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
+ * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
+ * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, 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
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * This file is part of Jalview.
  * 
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License 
+ * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  * 
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
+ * Jalview is distributed in the hope that it will be useful, but 
+ * WITHOUT ANY WARRANTY; without even the implied warranty 
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
+ * PURPOSE.  See the GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
  */
 package jalview.gui;
 
@@ -23,6 +22,8 @@ import java.util.*;
 
 import java.awt.*;
 import java.awt.event.*;
+import java.awt.geom.AffineTransform;
+import java.awt.image.BufferedImage;
 import java.beans.PropertyChangeEvent;
 import java.beans.PropertyChangeListener;
 
@@ -31,9 +32,12 @@ import javax.swing.event.*;
 import javax.swing.table.*;
 
 import jalview.analysis.AlignmentSorter;
+import jalview.bin.Cache;
 import jalview.commands.OrderCommand;
 import jalview.datamodel.*;
 import jalview.io.*;
+import jalview.schemes.AnnotationColourGradient;
+import jalview.schemes.GraduatedColor;
 
 public class FeatureSettings extends JPanel
 {
@@ -61,7 +65,7 @@ public class FeatureSettings extends JPanel
 
   JSlider transparency = new JSlider();
 
-  JPanel transPanel = new JPanel(new FlowLayout());
+  JPanel transPanel = new JPanel(new GridLayout(1, 2));
 
   public FeatureSettings(AlignFrame af)
   {
@@ -83,8 +87,10 @@ public class FeatureSettings extends JPanel
     table.setFont(new Font("Verdana", Font.PLAIN, 12));
     table.setDefaultRenderer(Color.class, new ColorRenderer());
 
-    table.setDefaultEditor(Color.class, new ColorEditor());
+    table.setDefaultEditor(Color.class, new ColorEditor(this));
 
+    table.setDefaultEditor(GraduatedColor.class, new ColorEditor(this));
+    table.setDefaultRenderer(GraduatedColor.class, new ColorRenderer());
     table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
 
     table.addMouseListener(new MouseAdapter()
@@ -94,7 +100,9 @@ public class FeatureSettings extends JPanel
         selectedRow = table.rowAtPoint(evt.getPoint());
         if (javax.swing.SwingUtilities.isRightMouseButton(evt))
         {
-          popupSort((String)table.getValueAt(selectedRow, 0), evt.getX(), evt.getY());
+          popupSort(selectedRow, (String) table.getValueAt(selectedRow, 0),
+                  table.getValueAt(selectedRow, 1), fr.minmax, evt.getX(),
+                  evt.getY());
         }
       }
     });
@@ -126,7 +134,7 @@ public class FeatureSettings extends JPanel
 
     scrollPane.setViewportView(table);
 
-    dassourceBrowser = new DasSourceBrowser();
+    dassourceBrowser = new DasSourceBrowser(this);
     dasSettingsPane.add(dassourceBrowser, BorderLayout.CENTER);
 
     if (af.getViewport().featuresDisplayed == null
@@ -146,7 +154,7 @@ public class FeatureSettings extends JPanel
         {
           fs.handlingUpdate = true;
           fs.resetTable(null); // new groups may be added with new seuqence
-                                // feature types only
+          // feature types only
           fs.handlingUpdate = false;
         }
       }
@@ -155,44 +163,133 @@ public class FeatureSettings extends JPanel
 
     frame = new JInternalFrame();
     frame.setContentPane(this);
-    Desktop.addInternalFrame(frame, "Sequence Feature Settings", 400, 450);
-    frame
-            .addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
-            {
-              public void internalFrameClosed(
-                      javax.swing.event.InternalFrameEvent evt)
-              {
-                fr.removePropertyChangeListener(change);
-              };
-            });
+    if (new jalview.util.Platform().isAMac())
+    {
+      Desktop.addInternalFrame(frame, "Sequence Feature Settings", 475, 480);
+    }
+    else
+    {
+      Desktop.addInternalFrame(frame, "Sequence Feature Settings", 400, 450);
+    }
+
+    frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
+    {
+      public void internalFrameClosed(
+              javax.swing.event.InternalFrameEvent evt)
+      {
+        fr.removePropertyChangeListener(change);
+        dassourceBrowser.fs = null;
+      };
+    });
     frame.setLayer(JLayeredPane.PALETTE_LAYER);
   }
 
-  protected void popupSort(final String type, int x, int y)
+  protected void popupSort(final int selectedRow, final String type,
+          final Object typeCol, final Hashtable minmax, int x, int y)
   {
-    JPopupMenu men = new JPopupMenu();
-    men.setName("Sort by "+type);
-    JMenuItem scr = new JMenuItem("Score");
+    JPopupMenu men = new JPopupMenu("Settings for " + type);
+    JMenuItem scr = new JMenuItem("Sort by Score");
     men.add(scr);
-    final FeatureSettings me=this;
-    scr.addActionListener(new ActionListener() {
+    final FeatureSettings me = this;
+    scr.addActionListener(new ActionListener()
+    {
 
       public void actionPerformed(ActionEvent e)
       {
-        me.sortByScore(new String[] {type});
+        me.sortByScore(new String[]
+        { type });
       }
-      
+
     });
-    JMenuItem dens = new JMenuItem("Density");
-    dens.addActionListener(new ActionListener() {
+    JMenuItem dens = new JMenuItem("Sort by Density");
+    dens.addActionListener(new ActionListener()
+    {
 
       public void actionPerformed(ActionEvent e)
       {
-        me.sortByDens(new String[] { type });
+        me.sortByDens(new String[]
+        { type });
       }
-      
+
     });
     men.add(dens);
+    if (minmax != null)
+    {
+      final Object typeMinMax = minmax.get(type);
+      /*
+       * final JCheckBoxMenuItem chb = new JCheckBoxMenuItem("Vary Height"); //
+       * this is broken at the moment and isn't that useful anyway!
+       * chb.setSelected(minmax.get(type) != null); chb.addActionListener(new
+       * ActionListener() {
+       * 
+       * public void actionPerformed(ActionEvent e) {
+       * chb.setState(chb.getState()); if (chb.getState()) { minmax.put(type,
+       * null); } else { minmax.put(type, typeMinMax); } }
+       * 
+       * });
+       * 
+       * men.add(chb);
+       */
+      if (typeMinMax != null && ((float[][]) typeMinMax)[0] != null)
+      {
+        // if (table.getValueAt(row, column));
+        // graduated colourschemes for those where minmax exists for the
+        // positional features
+        final JCheckBoxMenuItem mxcol = new JCheckBoxMenuItem(
+                "Graduated Colour");
+        mxcol.setSelected(!(typeCol instanceof Color));
+        men.add(mxcol);
+        mxcol.addActionListener(new ActionListener()
+        {
+          JColorChooser colorChooser;
+
+          public void actionPerformed(ActionEvent e)
+          {
+            if (e.getSource() == mxcol)
+            {
+              if (typeCol instanceof Color)
+              {
+                FeatureColourChooser fc = new FeatureColourChooser(me.fr,
+                        type);
+                fc.addActionListener(this);
+              }
+              else
+              {
+                // bring up simple color chooser
+                colorChooser = new JColorChooser();
+                JDialog dialog = JColorChooser.createDialog(me,
+                        "Select new Colour", true, // modal
+                        colorChooser, this, // OK button handler
+                        null); // no CANCEL button handler
+                colorChooser.setColor(((GraduatedColor) typeCol)
+                        .getMaxColor());
+                dialog.setVisible(true);
+              }
+            }
+            else
+            {
+              if (e.getSource() instanceof FeatureColourChooser)
+              {
+                FeatureColourChooser fc = (FeatureColourChooser) e
+                        .getSource();
+                table.setValueAt(fc.getLastColour(), selectedRow, 1);
+                table.validate();
+              }
+              else
+              {
+                // probably the color chooser!
+                table.setValueAt(colorChooser.getColor(), selectedRow, 1);
+                table.validate();
+                me.updateFeatureRenderer(
+                        ((FeatureTableModel) table.getModel()).getData(),
+                        false);
+              }
+            }
+          }
+
+        });
+      }
+    }
     men.show(table, x, y);
   }
 
@@ -309,8 +406,8 @@ public class FeatureSettings extends JPanel
     {
       public void itemStateChanged(ItemEvent evt)
       {
-        fr.featureGroups.put(check.getText(), new Boolean(check
-                .isSelected()));
+        fr.featureGroups.put(check.getText(),
+                new Boolean(check.isSelected()));
         af.alignPanel.seqPanel.seqCanvas.repaint();
         if (af.alignPanel.overviewPanel != null)
         {
@@ -409,8 +506,8 @@ public class FeatureSettings extends JPanel
     {
       if (!handlingUpdate)
         fr.findAllFeatures(groupChanged != null); // prod to update
-                                                  // colourschemes. but don't
-                                                  // affect display
+      // colourschemes. but don't
+      // affect display
       // First add the checks in the previous render order,
       // in case the window has been closed and reopened
       for (int ro = fr.renderOrder.length - 1; ro > -1; ro--)
@@ -423,9 +520,9 @@ public class FeatureSettings extends JPanel
         }
 
         data[dataIndex][0] = type;
-        data[dataIndex][1] = fr.getColour(type);
-        data[dataIndex][2] = new Boolean(af.getViewport().featuresDisplayed
-                .containsKey(type));
+        data[dataIndex][1] = fr.getFeatureStyle(type);
+        data[dataIndex][2] = new Boolean(
+                af.getViewport().featuresDisplayed.containsKey(type));
         dataIndex++;
         visibleChecks.removeElement(type);
       }
@@ -439,7 +536,7 @@ public class FeatureSettings extends JPanel
       type = visibleChecks.elementAt(i).toString();
       data[dataIndex][0] = type;
 
-      data[dataIndex][1] = fr.getColour(type);
+      data[dataIndex][1] = fr.getFeatureStyle(type);
       if (data[dataIndex][1] == null)
       {
         // "Colour has been updated in another view!!"
@@ -454,7 +551,10 @@ public class FeatureSettings extends JPanel
     if (originalData == null)
     {
       originalData = new Object[data.length][3];
-      System.arraycopy(data, 0, originalData, 0, data.length);
+      for (int i = 0; i < data.length; i++)
+      {
+        System.arraycopy(data[i], 0, originalData[i], 0, 3);
+      }
     }
 
     table.setModel(new FeatureTableModel(data));
@@ -496,10 +596,10 @@ public class FeatureSettings extends JPanel
 
   void load()
   {
-    JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
-            .getProperty("LAST_DIRECTORY"), new String[]
-    { "fc" }, new String[]
-    { "Sequence Feature Colours" }, "Sequence Feature Colours");
+    JalviewFileChooser chooser = new JalviewFileChooser(
+            jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
+            { "fc" }, new String[]
+            { "Sequence Feature Colours" }, "Sequence Feature Colours");
     chooser.setFileView(new jalview.io.JalviewFileView());
     chooser.setDialogTitle("Load Feature Colours");
     chooser.setToolTipText("Load");
@@ -515,14 +615,65 @@ public class FeatureSettings extends JPanel
         InputStreamReader in = new InputStreamReader(new FileInputStream(
                 file), "UTF-8");
 
-        jalview.binding.JalviewUserColours jucs = new jalview.binding.JalviewUserColours();
-        jucs = (jalview.binding.JalviewUserColours) jucs.unmarshal(in);
+        jalview.schemabinding.version2.JalviewUserColours jucs = new jalview.schemabinding.version2.JalviewUserColours();
+        jucs = (jalview.schemabinding.version2.JalviewUserColours) jucs
+                .unmarshal(in);
 
         for (int i = jucs.getColourCount() - 1; i >= 0; i--)
         {
           String name;
-          fr.setColour(name = jucs.getColour(i).getName(), new Color(
-                  Integer.parseInt(jucs.getColour(i).getRGB(), 16)));
+          jalview.schemabinding.version2.Colour newcol = jucs.getColour(i);
+          if (newcol.hasMax())
+          {
+            Color mincol = null, maxcol = null;
+            try
+            {
+              mincol = new Color(Integer.parseInt(newcol.getMinRGB(), 16));
+              maxcol = new Color(Integer.parseInt(newcol.getRGB(), 16));
+
+            } catch (Exception e)
+            {
+              Cache.log.warn("Couldn't parse out graduated feature color.",
+                      e);
+            }
+            GraduatedColor gcol = new GraduatedColor(mincol, maxcol,
+                    newcol.getMin(), newcol.getMax());
+            if (newcol.hasAutoScale())
+            {
+              gcol.setAutoScaled(newcol.getAutoScale());
+            }
+            if (newcol.hasColourByLabel())
+            {
+              gcol.setColourByLabel(newcol.getColourByLabel());
+            }
+            if (newcol.hasThreshold())
+            {
+              gcol.setThresh(newcol.getThreshold());
+              gcol.setThreshType(AnnotationColourGradient.NO_THRESHOLD); // default
+            }
+            if (newcol.getThreshType().length() > 0)
+            {
+              String ttyp = newcol.getThreshType();
+              if (ttyp.equalsIgnoreCase("NONE"))
+              {
+                gcol.setThreshType(AnnotationColourGradient.NO_THRESHOLD);
+              }
+              if (ttyp.equalsIgnoreCase("ABOVE"))
+              {
+                gcol.setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
+              }
+              if (ttyp.equalsIgnoreCase("BELOW"))
+              {
+                gcol.setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
+              }
+            }
+            fr.setColour(name = newcol.getName(), gcol);
+          }
+          else
+          {
+            fr.setColour(name = jucs.getColour(i).getName(), new Color(
+                    Integer.parseInt(jucs.getColour(i).getRGB(), 16)));
+          }
           fr.setOrder(name, (i == 0) ? 0 : i / jucs.getColourCount());
         }
         if (table != null)
@@ -543,10 +694,10 @@ public class FeatureSettings extends JPanel
 
   void save()
   {
-    JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
-            .getProperty("LAST_DIRECTORY"), new String[]
-    { "fc" }, new String[]
-    { "Sequence Feature Colours" }, "Sequence Feature Colours");
+    JalviewFileChooser chooser = new JalviewFileChooser(
+            jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
+            { "fc" }, new String[]
+            { "Sequence Feature Colours" }, "Sequence Feature Colours");
     chooser.setFileView(new jalview.io.JalviewFileView());
     chooser.setDialogTitle("Save Feature Colour Scheme");
     chooser.setToolTipText("Save");
@@ -556,7 +707,7 @@ public class FeatureSettings extends JPanel
     if (value == JalviewFileChooser.APPROVE_OPTION)
     {
       String choice = chooser.getSelectedFile().getPath();
-      jalview.binding.JalviewUserColours ucs = new jalview.binding.JalviewUserColours();
+      jalview.schemabinding.version2.JalviewUserColours ucs = new jalview.schemabinding.version2.JalviewUserColours();
       ucs.setSchemeName("Sequence Features");
       try
       {
@@ -575,12 +726,38 @@ public class FeatureSettings extends JPanel
         }
         jalview.util.QuickSort.sort(sortOrder, sortTypes);
         sortOrder = null;
+        Object fcol;
+        GraduatedColor gcol;
         for (i = 0; i < sortTypes.length; i++)
         {
-          jalview.binding.Colour col = new jalview.binding.Colour();
+          jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
           col.setName(sortTypes[i]);
           col.setRGB(jalview.util.Format.getHexString(fr.getColour(col
                   .getName())));
+          fcol = fr.getFeatureStyle(sortTypes[i]);
+          if (fcol instanceof GraduatedColor)
+          {
+            gcol = (GraduatedColor) fcol;
+            col.setMin(gcol.getMin());
+            col.setMax(gcol.getMax());
+            col.setMinRGB(jalview.util.Format.getHexString(gcol
+                    .getMinColor()));
+            col.setAutoScale(gcol.isAutoScale());
+            col.setThreshold(gcol.getThresh());
+            col.setColourByLabel(gcol.isColourByLabel());
+            switch (gcol.getThreshType())
+            {
+            case AnnotationColourGradient.NO_THRESHOLD:
+              col.setThreshType("NONE");
+              break;
+            case AnnotationColourGradient.ABOVE_THRESHOLD:
+              col.setThreshType("ABOVE");
+              break;
+            case AnnotationColourGradient.BELOW_THRESHOLD:
+              col.setThreshType("BELOW");
+              break;
+            }
+          }
           ucs.addColour(col);
         }
         ucs.marshal(out);
@@ -617,8 +794,8 @@ public class FeatureSettings extends JPanel
       if (awidth[0] > 0)
       {
         width[i] = awidth[1] / awidth[0];// *awidth[0]*awidth[2]; - better
-                                          // weight - but have to make per
-                                          // sequence, too (awidth[2])
+        // weight - but have to make per
+        // sequence, too (awidth[2])
         // if (width[i]==1) // hack to distinguish single width sequences.
         num++;
       }
@@ -714,10 +891,12 @@ public class FeatureSettings extends JPanel
   JButton cancelDAS = new JButton();
 
   JButton optimizeOrder = new JButton();
+
   JButton sortByScore = new JButton();
+
   JButton sortByDens = new JButton();
 
-  JPanel transbuttons = new JPanel(new BorderLayout());
+  JPanel transbuttons = new JPanel(new GridLayout(4, 1));
 
   private void jbInit() throws Exception
   {
@@ -725,7 +904,7 @@ public class FeatureSettings extends JPanel
     settingsPane.setLayout(borderLayout2);
     dasSettingsPane.setLayout(borderLayout3);
     bigPanel.setLayout(borderLayout4);
-    invert.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
+    invert.setFont(JvSwingUtils.getLabelFont());
     invert.setText("Invert Selection");
     invert.addActionListener(new ActionListener()
     {
@@ -734,7 +913,7 @@ public class FeatureSettings extends JPanel
         invertSelection();
       }
     });
-    optimizeOrder.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
+    optimizeOrder.setFont(JvSwingUtils.getLabelFont());
     optimizeOrder.setText("Optimise Order");
     optimizeOrder.addActionListener(new ActionListener()
     {
@@ -743,7 +922,7 @@ public class FeatureSettings extends JPanel
         orderByAvWidth();
       }
     });
-    sortByScore.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
+    sortByScore.setFont(JvSwingUtils.getLabelFont());
     sortByScore.setText("Seq sort by Score");
     sortByScore.addActionListener(new ActionListener()
     {
@@ -752,7 +931,7 @@ public class FeatureSettings extends JPanel
         sortByScore(null);
       }
     });
-    sortByDens.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
+    sortByDens.setFont(JvSwingUtils.getLabelFont());
     sortByDens.setText("Seq Sort by density");
     sortByDens.addActionListener(new ActionListener()
     {
@@ -760,7 +939,8 @@ public class FeatureSettings extends JPanel
       {
         sortByDens(null);
       }
-    });    cancel.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
+    });
+    cancel.setFont(JvSwingUtils.getLabelFont());
     cancel.setText("Cancel");
     cancel.addActionListener(new ActionListener()
     {
@@ -770,7 +950,7 @@ public class FeatureSettings extends JPanel
         close();
       }
     });
-    ok.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
+    ok.setFont(JvSwingUtils.getLabelFont());
     ok.setText("OK");
     ok.addActionListener(new ActionListener()
     {
@@ -779,7 +959,7 @@ public class FeatureSettings extends JPanel
         close();
       }
     });
-    loadColours.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
+    loadColours.setFont(JvSwingUtils.getLabelFont());
     loadColours.setText("Load Colours");
     loadColours.addActionListener(new ActionListener()
     {
@@ -788,7 +968,7 @@ public class FeatureSettings extends JPanel
         load();
       }
     });
-    saveColours.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
+    saveColours.setFont(JvSwingUtils.getLabelFont());
     saveColours.setText("Save Colours");
     saveColours.addActionListener(new ActionListener()
     {
@@ -838,16 +1018,16 @@ public class FeatureSettings extends JPanel
     tabbedPane.addTab("Feature Settings", settingsPane);
     tabbedPane.addTab("DAS Settings", dasSettingsPane);
     bigPanel.add(transPanel, java.awt.BorderLayout.SOUTH);
+    transbuttons.add(optimizeOrder);
+    transbuttons.add(invert);
+    transbuttons.add(sortByScore);
+    transbuttons.add(sortByDens);
     transPanel.add(transparency);
-    transbuttons.add(invert, java.awt.BorderLayout.NORTH);
-    transbuttons.add(optimizeOrder, java.awt.BorderLayout.SOUTH);
     transPanel.add(transbuttons);
     buttonPanel.add(ok);
     buttonPanel.add(cancel);
     buttonPanel.add(loadColours);
     buttonPanel.add(saveColours);
-    buttonPanel.add(sortByScore);
-    buttonPanel.add(sortByDens);
     bigPanel.add(scrollPane, java.awt.BorderLayout.CENTER);
     dasSettingsPane.add(dasButtonPanel, java.awt.BorderLayout.SOUTH);
     dasButtonPanel.add(fetchDAS);
@@ -861,48 +1041,63 @@ public class FeatureSettings extends JPanel
   {
     sortBy(typ, "Sort by Density", AlignmentSorter.FEATURE_DENSITY);
   }
-  protected void sortBy(String[] typ, String methodText, final String method) {
-    if (typ==null)
+
+  protected void sortBy(String[] typ, String methodText, final String method)
+  {
+    if (typ == null)
     {
       typ = getDisplayedFeatureTypes();
     }
-    String gps[]=null;
+    String gps[] = null;
     gps = getDisplayedFeatureGroups();
-    if (typ!=null)
+    if (typ != null)
     {
-      for (int i=0;i<typ.length; i++)
+      ArrayList types = new ArrayList();
+      for (int i = 0; i < typ.length; i++)
       {
-        System.err.println("Sorting on Types:"+typ[i]);
+        if (typ[i] != null)
+        {
+          types.add(typ[i]);
+        }
+        typ = new String[types.size()];
+        types.toArray(typ);
       }
     }
-    if (gps!=null)
+    if (gps != null)
     {
-      
-      for (int i=0;i<gps.length; i++)
+      ArrayList grps = new ArrayList();
+
+      for (int i = 0; i < gps.length; i++)
       {
-        System.err.println("Sorting on groups:"+gps[i]);
+        if (gps[i] != null)
+        {
+          grps.add(gps[i]);
+        }
       }
+      gps = new String[grps.size()];
+      grps.toArray(gps);
     }
     AlignmentPanel alignPanel = af.alignPanel;
     AlignmentI al = alignPanel.av.getAlignment();
 
-    int start,stop;
+    int start, stop;
     SequenceGroup sg = alignPanel.av.getSelectionGroup();
-    if (sg!=null)
+    if (sg != null)
     {
       start = sg.getStartRes();
       stop = sg.getEndRes();
-    } else {
+    }
+    else
+    {
       start = 0;
       stop = al.getWidth();
     }
     SequenceI[] oldOrder = al.getSequencesArray();
-    AlignmentSorter.sortByFeature(typ, gps, start, stop,
-            al, method);
-    af.addHistoryItem(new OrderCommand(methodText, oldOrder,
-            alignPanel.av.getAlignment()));
+    AlignmentSorter.sortByFeature(typ, gps, start, stop, al, method);
+    af.addHistoryItem(new OrderCommand(methodText, oldOrder, alignPanel.av
+            .getAlignment()));
     alignPanel.paintAlignment(true);
-    
+
   }
 
   protected void sortByScore(String[] typ)
@@ -912,15 +1107,16 @@ public class FeatureSettings extends JPanel
 
   private String[] getDisplayedFeatureTypes()
   {
-    String[] typ=null;
-    if (fr!=null)
+    String[] typ = null;
+    if (fr != null)
     {
-      synchronized (fr.renderOrder) {
+      synchronized (fr.renderOrder)
+      {
         typ = new String[fr.renderOrder.length];
         System.arraycopy(fr.renderOrder, 0, typ, 0, typ.length);
-        for (int i=0;i<typ.length;i++)
+        for (int i = 0; i < typ.length; i++)
         {
-          if (af.viewport.featuresDisplayed.get(typ[i])==null)
+          if (af.viewport.featuresDisplayed.get(typ[i]) == null)
           {
             typ[i] = null;
           }
@@ -932,27 +1128,27 @@ public class FeatureSettings extends JPanel
 
   private String[] getDisplayedFeatureGroups()
   {
-    String[] gps=null;
-    if (fr!=null)
+    String[] gps = null;
+    if (fr != null)
     {
-      
-      if (fr.featureGroups!=null)
+
+      if (fr.featureGroups != null)
       {
         Enumeration en = fr.featureGroups.keys();
         gps = new String[fr.featureColours.size()];
-        int g=0;
-        boolean valid=false;
+        int g = 0;
+        boolean valid = false;
         while (en.hasMoreElements())
         {
           String gp = (String) en.nextElement();
-          Boolean on = (Boolean )fr.featureGroups.get(gp);
-          if (on!=null && on.booleanValue())
+          Boolean on = (Boolean) fr.featureGroups.get(gp);
+          if (on != null && on.booleanValue())
           {
             valid = true;
             gps[g++] = gp;
           }
         }
-        while (g<gps.length)
+        while (g < gps.length)
         {
           gps[g++] = null;
         }
@@ -969,6 +1165,7 @@ public class FeatureSettings extends JPanel
   {
     fetchDAS.setEnabled(false);
     cancelDAS.setEnabled(true);
+    dassourceBrowser.setGuiEnabled(false);
     Vector selectedSources = dassourceBrowser.getSelectedSources();
     doDasFeatureFetch(selectedSources, true, true);
   }
@@ -1019,30 +1216,41 @@ public class FeatureSettings extends JPanel
   {
     dassourceBrowser.initDasSources();
   }
+
   /**
-   * examine the current list of das sources and return any matching the given nicknames in sources 
-   * @param sources Vector of Strings to resolve to DAS source nicknames.
+   * examine the current list of das sources and return any matching the given
+   * nicknames in sources
+   * 
+   * @param sources
+   *          Vector of Strings to resolve to DAS source nicknames.
    * @return sources that are present in source list.
    */
   public Vector resolveSourceNicknames(Vector sources)
   {
     return dassourceBrowser.resolveSourceNicknames(sources);
   }
+
   /**
-   * get currently selected das sources. ensure you have called initDasSources before calling this.
+   * get currently selected das sources. ensure you have called initDasSources
+   * before calling this.
+   * 
    * @return vector of selected das source nicknames
    */
   public Vector getSelectedSources()
   {
     return dassourceBrowser.getSelectedSources();
   }
+
   /**
    * properly initialise DAS fetcher and then initiate a new thread to fetch
    * features from the named sources (rather than any turned on by default)
    * 
    * @param sources
+   * @param block
+   *          if true then runs in same thread, otherwise passes to the Swing
+   *          executor
    */
-  public void fetchDasFeatures(Vector sources)
+  public void fetchDasFeatures(Vector sources, boolean block)
   {
     initDasSources();
     Vector resolved = resolveSourceNicknames(sources);
@@ -1053,17 +1261,25 @@ public class FeatureSettings extends JPanel
     if (resolved.size() > 0)
     {
       final Vector dassources = resolved;
-      SwingUtilities.invokeLater(new Runnable()
+      fetchDAS.setEnabled(false);
+      // cancelDAS.setEnabled(true); doDasFetch does this.
+      Runnable fetcher = new Runnable()
       {
 
         public void run()
         {
-          fetchDAS.setEnabled(false);
-          cancelDAS.setEnabled(true);
           doDasFeatureFetch(dassources, true, false);
 
         }
-      });
+      };
+      if (block)
+      {
+        fetcher.run();
+      }
+      else
+      {
+        SwingUtilities.invokeLater(fetcher);
+      }
     }
   }
 
@@ -1077,6 +1293,8 @@ public class FeatureSettings extends JPanel
   {
     fetchDAS.setEnabled(true);
     cancelDAS.setEnabled(false);
+    dassourceBrowser.setGuiEnabled(true);
+
   }
 
   public void cancelDAS_actionPerformed(ActionEvent e)
@@ -1085,8 +1303,7 @@ public class FeatureSettings extends JPanel
     {
       dasFeatureFetcher.cancel();
     }
-    fetchDAS.setEnabled(true);
-    cancelDAS.setEnabled(false);
+    complete();
   }
 
   public void noDasSourceActive()
@@ -1174,17 +1391,44 @@ public class FeatureSettings extends JPanel
 
     javax.swing.border.Border selectedBorder = null;
 
+    final String baseTT = "Click to edit, right/apple click for menu.";
+
     public ColorRenderer()
     {
       setOpaque(true); // MUST do this for background to show up.
+      setHorizontalTextPosition(SwingConstants.CENTER);
+      setVerticalTextPosition(SwingConstants.CENTER);
     }
 
     public Component getTableCellRendererComponent(JTable table,
             Object color, boolean isSelected, boolean hasFocus, int row,
             int column)
     {
-      Color newColor = (Color) color;
-      setBackground(newColor);
+      // JLabel comp = new JLabel();
+      // comp.
+      setOpaque(true);
+      // comp.
+      // setBounds(getBounds());
+      Color newColor;
+      setToolTipText(baseTT);
+      setBackground(table.getBackground());
+      if (color instanceof GraduatedColor)
+      {
+        Rectangle cr = table.getCellRect(row, column, false);
+        FeatureSettings.renderGraduatedColor(this, (GraduatedColor) color,
+                (int) cr.getWidth(), (int) cr.getHeight());
+
+      }
+      else
+      {
+        this.setText("");
+        this.setIcon(null);
+        newColor = (Color) color;
+        // comp.
+        setBackground(newColor);
+        // comp.setToolTipText("RGB value: " + newColor.getRed() + ", "
+        // + newColor.getGreen() + ", " + newColor.getBlue());
+      }
       if (isSelected)
       {
         if (selectedBorder == null)
@@ -1192,6 +1436,7 @@ public class FeatureSettings extends JPanel
           selectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
                   table.getSelectionBackground());
         }
+        // comp.
         setBorder(selectedBorder);
       }
       else
@@ -1201,19 +1446,182 @@ public class FeatureSettings extends JPanel
           unselectedBorder = BorderFactory.createMatteBorder(2, 5, 2, 5,
                   table.getBackground());
         }
+        // comp.
         setBorder(unselectedBorder);
       }
 
-      setToolTipText("RGB value: " + newColor.getRed() + ", "
-              + newColor.getGreen() + ", " + newColor.getBlue());
       return this;
     }
   }
+
+  /**
+   * update comp using rendering settings from gcol
+   * 
+   * @param comp
+   * @param gcol
+   */
+  public static void renderGraduatedColor(JLabel comp, GraduatedColor gcol)
+  {
+    int w = comp.getWidth(), h = comp.getHeight();
+    if (w < 20)
+    {
+      w = (int) comp.getPreferredSize().getWidth();
+      h = (int) comp.getPreferredSize().getHeight();
+      if (w < 20)
+      {
+        w = 80;
+        h = 12;
+      }
+    }
+    renderGraduatedColor(comp, gcol, w, h);
+  }
+
+  public static void renderGraduatedColor(JLabel comp, GraduatedColor gcol,
+          int w, int h)
+  {
+    boolean thr = false;
+    String tt = "";
+    String tx = "";
+    if (gcol.getThreshType() == AnnotationColourGradient.ABOVE_THRESHOLD)
+    {
+      thr = true;
+      tx += ">";
+      tt += "Thresholded (Above " + gcol.getThresh() + ") ";
+    }
+    if (gcol.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
+    {
+      thr = true;
+      tx += "<";
+      tt += "Thresholded (Below " + gcol.getThresh() + ") ";
+    }
+    if (gcol.isColourByLabel())
+    {
+      tt = "Coloured by label text. " + tt;
+      if (thr)
+      {
+        tx += " ";
+      }
+      tx += "Label";
+      comp.setIcon(null);
+    }
+    else
+    {
+      Color newColor = gcol.getMaxColor();
+      comp.setBackground(newColor);
+      // System.err.println("Width is " + w / 2);
+      Icon ficon = new FeatureIcon(gcol, comp.getBackground(), w, h, thr);
+      comp.setIcon(ficon);
+      // tt+="RGB value: Max (" + newColor.getRed() + ", "
+      // + newColor.getGreen() + ", " + newColor.getBlue()
+      // + ")\nMin (" + minCol.getRed() + ", " + minCol.getGreen()
+      // + ", " + minCol.getBlue() + ")");
+    }
+    comp.setHorizontalAlignment(SwingConstants.CENTER);
+    comp.setText(tx);
+    if (tt.length() > 0)
+    {
+      if (comp.getToolTipText() == null)
+      {
+        comp.setToolTipText(tt);
+      }
+      else
+      {
+        comp.setToolTipText(tt + " " + comp.getToolTipText());
+      }
+    }
+  }
+}
+
+class FeatureIcon implements Icon
+{
+  GraduatedColor gcol;
+
+  Color backg;
+
+  boolean midspace = false;
+
+  int width = 50, height = 20;
+
+  int s1, e1; // start and end of midpoint band for thresholded symbol
+
+  Color mpcolour = Color.white;
+
+  FeatureIcon(GraduatedColor gfc, Color bg, int w, int h, boolean mspace)
+  {
+    gcol = gfc;
+    backg = bg;
+    width = w;
+    height = h;
+    midspace = mspace;
+    if (midspace)
+    {
+      s1 = width / 3;
+      e1 = s1 * 2;
+    }
+    else
+    {
+      s1 = width / 2;
+      e1 = s1;
+    }
+  }
+
+  public int getIconWidth()
+  {
+    return width;
+  }
+
+  public int getIconHeight()
+  {
+    return height;
+  }
+
+  public void paintIcon(Component c, Graphics g, int x, int y)
+  {
+
+    if (gcol.isColourByLabel())
+    {
+      g.setColor(backg);
+      g.fillRect(0, 0, width, height);
+      // need an icon here.
+      g.setColor(gcol.getMaxColor());
+
+      g.setFont(new Font("Verdana", Font.PLAIN, 9));
+
+      // g.setFont(g.getFont().deriveFont(
+      // AffineTransform.getScaleInstance(
+      // width/g.getFontMetrics().stringWidth("Label"),
+      // height/g.getFontMetrics().getHeight())));
+
+      g.drawString("Label", 0, 0);
+
+    }
+    else
+    {
+      Color minCol = gcol.getMinColor();
+      g.setColor(minCol);
+      g.fillRect(0, 0, s1, height);
+      if (midspace)
+      {
+        g.setColor(Color.white);
+        g.fillRect(s1, 0, e1 - s1, height);
+      }
+      g.setColor(gcol.getMaxColor());
+      g.fillRect(0, e1, width - e1, height);
+    }
+  }
 }
 
 class ColorEditor extends AbstractCellEditor implements TableCellEditor,
         ActionListener
 {
+  FeatureSettings me;
+
+  GraduatedColor currentGColor;
+
+  FeatureColourChooser chooser;
+
+  String type;
+
   Color currentColor;
 
   JButton button;
@@ -1224,8 +1632,11 @@ class ColorEditor extends AbstractCellEditor implements TableCellEditor,
 
   protected static final String EDIT = "edit";
 
-  public ColorEditor()
+  int selectedRow = 0;
+
+  public ColorEditor(FeatureSettings me)
   {
+    this.me = me;
     // Set up the editor (from the table's point of view),
     // which is a button.
     // This button brings up the color chooser dialog,
@@ -1251,23 +1662,50 @@ class ColorEditor extends AbstractCellEditor implements TableCellEditor,
     {
       // The user has clicked the cell, so
       // bring up the dialog.
-      button.setBackground(currentColor);
-      colorChooser.setColor(currentColor);
-      dialog.setVisible(true);
-
+      if (currentColor != null)
+      {
+        // bring up simple color chooser
+        button.setBackground(currentColor);
+        colorChooser.setColor(currentColor);
+        dialog.setVisible(true);
+      }
+      else
+      {
+        // bring up graduated chooser.
+        chooser = new FeatureColourChooser(me.fr, type);
+        chooser.setRequestFocusEnabled(true);
+        chooser.requestFocus();
+        chooser.addActionListener(this);
+      }
       // Make the renderer reappear.
       fireEditingStopped();
 
     }
     else
     { // User pressed dialog's "OK" button.
-      currentColor = colorChooser.getColor();
+      if (currentColor != null)
+      {
+        currentColor = colorChooser.getColor();
+      }
+      else
+      {
+        // class cast exceptions may be raised if the chooser created on a
+        // non-graduated color
+        currentGColor = (GraduatedColor) chooser.getLastColour();
+      }
+      me.table.setValueAt(getCellEditorValue(), selectedRow, 1);
+      fireEditingStopped();
+      me.table.validate();
     }
   }
 
   // Implement the one CellEditor method that AbstractCellEditor doesn't.
   public Object getCellEditorValue()
   {
+    if (currentColor == null)
+    {
+      return currentGColor;
+    }
     return currentColor;
   }
 
@@ -1275,7 +1713,29 @@ class ColorEditor extends AbstractCellEditor implements TableCellEditor,
   public Component getTableCellEditorComponent(JTable table, Object value,
           boolean isSelected, int row, int column)
   {
-    currentColor = (Color) value;
+    currentGColor = null;
+    currentColor = null;
+    this.selectedRow = row;
+    type = me.table.getValueAt(row, 0).toString();
+    button.setOpaque(true);
+    button.setBackground(me.getBackground());
+    if (value instanceof GraduatedColor)
+    {
+      currentGColor = (GraduatedColor) value;
+      JLabel btn = new JLabel();
+      btn.setSize(button.getSize());
+      FeatureSettings.renderGraduatedColor(btn, currentGColor);
+      button.setBackground(btn.getBackground());
+      button.setIcon(btn.getIcon());
+      button.setText(btn.getText());
+    }
+    else
+    {
+      button.setText("");
+      button.setIcon(null);
+      currentColor = (Color) value;
+      button.setBackground(currentColor);
+    }
     return button;
   }
 }