JAL-2361 extract methods to (re-)build colour menu
[jalview.git] / src / jalview / gui / UserDefinedColours.java
index 0df23e0..3b6ebfa 100755 (executable)
@@ -26,15 +26,20 @@ import jalview.datamodel.SequenceGroup;
 import jalview.io.JalviewFileChooser;
 import jalview.io.JalviewFileView;
 import jalview.jbgui.GUserDefinedColours;
+import jalview.schemabinding.version2.Colour;
+import jalview.schemabinding.version2.JalviewUserColours;
 import jalview.schemes.ColourSchemeI;
 import jalview.schemes.ResidueProperties;
 import jalview.schemes.UserColourScheme;
 import jalview.util.ColorUtils;
+import jalview.util.Format;
 import jalview.util.MessageManager;
 
 import java.awt.Color;
 import java.awt.Font;
+import java.awt.Insets;
 import java.awt.event.ActionEvent;
+import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
 import java.io.File;
 import java.io.FileInputStream;
@@ -43,8 +48,10 @@ import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
 import java.util.ArrayList;
-import java.util.Hashtable;
+import java.util.List;
+import java.util.SortedMap;
 import java.util.StringTokenizer;
+import java.util.TreeMap;
 
 import javax.swing.JButton;
 import javax.swing.JInternalFrame;
@@ -61,35 +68,41 @@ import javax.swing.event.ChangeListener;
 public class UserDefinedColours extends GUserDefinedColours implements
         ChangeListener
 {
+  private static final Font VERDANA_BOLD_10 = new Font("Verdana", Font.BOLD, 10);
+
+  private static final String USER_DEFINED_COLOURS = "USER_DEFINED_COLOURS";
+
+  private static final String LAST_DIRECTORY = "LAST_DIRECTORY";
+
   private static final int MY_FRAME_HEIGHT = 420;
 
   private static final int MY_FRAME_WIDTH = 810;
 
   private static final int MY_FRAME_WIDTH_CASE_SENSITIVE = 970;
 
+  static SortedMap<String, UserColourScheme> userColourSchemes;
+
   AlignmentPanel ap;
 
   SequenceGroup seqGroup;
 
-  ArrayList<JButton> selectedButtons;
+  List<JButton> selectedButtons;
 
   ColourSchemeI oldColourScheme;
 
   JInternalFrame frame;
 
-  JalviewStructureDisplayI jmol;
+  JalviewStructureDisplayI structureViewer;
 
-  ArrayList<JButton> upperCaseButtons;
+  List<JButton> upperCaseButtons;
 
-  ArrayList<JButton> lowerCaseButtons;
+  List<JButton> lowerCaseButtons;
 
   /**
    * Creates a new UserDefinedColours object.
    * 
    * @param ap
-   *          DOCUMENT ME!
    * @param sg
-   *          DOCUMENT ME!
    */
   public UserDefinedColours(AlignmentPanel ap, SequenceGroup sg)
   {
@@ -131,11 +144,11 @@ public class UserDefinedColours extends GUserDefinedColours implements
     showFrame();
   }
 
-  public UserDefinedColours(JalviewStructureDisplayI jmol,
+  public UserDefinedColours(JalviewStructureDisplayI viewer,
           ColourSchemeI oldcs)
   {
     super();
-    this.jmol = jmol;
+    this.structureViewer = viewer;
 
     colorChooser.getSelectionModel().addChangeListener(this);
 
@@ -384,28 +397,35 @@ public class UserDefinedColours extends GUserDefinedColours implements
   }
 
   /**
-   * DOCUMENT ME!
+   * A helper method to update or make a colour button, whose background colour
+   * is the associated colour, and text colour a darker shade of the same. If
+   * the button is already in the list, then its text and margins are updated,
+   * if not then it is created and added. This method supports toggling between
+   * case-sensitive and case-insensitive button panels. The case-sensitive
+   * version has abbreviated button text in order to fit in more buttons.
    * 
    * @param label
-   *          DOCUMENT ME!
-   * @param aa
-   *          DOCUMENT ME!
+   * @param residue
+   * @param the
+   *          list of buttons
+   * @param buttonIndex
+   *          the button's position in the list
    */
-  JButton makeButton(String label, String aa,
-          ArrayList<JButton> caseSensitiveButtons, int buttonIndex)
+  JButton makeButton(String label, String residue,
+          List<JButton> buttons, int buttonIndex)
   {
     final JButton button;
     Color col;
 
-    if (buttonIndex < caseSensitiveButtons.size())
+    if (buttonIndex < buttons.size())
     {
-      button = caseSensitiveButtons.get(buttonIndex);
+      button = buttons.get(buttonIndex);
       col = button.getBackground();
     }
     else
     {
       button = new JButton();
-      button.addMouseListener(new java.awt.event.MouseAdapter()
+      button.addMouseListener(new MouseAdapter()
       {
         @Override
         public void mouseClicked(MouseEvent e)
@@ -414,14 +434,14 @@ public class UserDefinedColours extends GUserDefinedColours implements
         }
       });
 
-      caseSensitiveButtons.add(button);
+      buttons.add(button);
 
       col = Color.white;
       if (oldColourScheme != null)
       {
         try
         {
-          col = oldColourScheme.findColour(aa.charAt(0), -1, null);
+          col = oldColourScheme.findColour(residue.charAt(0), -1, null);
         } catch (Exception ex)
         {
         }
@@ -430,30 +450,29 @@ public class UserDefinedColours extends GUserDefinedColours implements
 
     if (caseSensitive.isSelected())
     {
-      button.setMargin(new java.awt.Insets(2, 2, 2, 2));
+      button.setMargin(new Insets(2, 2, 2, 2));
     }
     else
     {
-      button.setMargin(new java.awt.Insets(2, 14, 2, 14));
+      button.setMargin(new Insets(2, 14, 2, 14));
     }
 
     button.setOpaque(true); // required for the next line to have effect
     button.setBackground(col);
     button.setText(label);
     button.setForeground(ColorUtils.darkerThan(col));
-    button.setFont(new java.awt.Font("Verdana", Font.BOLD, 10));
+    button.setFont(VERDANA_BOLD_10);
 
     return button;
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * On 'OK', check that at least one colour has been assigned to a residue (and
+   * if not issue a warning), and apply the chosen colour scheme and close the
+   * panel.
    */
   @Override
-  protected void okButton_actionPerformed(ActionEvent e)
+  protected void okButton_actionPerformed()
   {
     if (isNoSelectionMade())
     {
@@ -464,7 +483,7 @@ public class UserDefinedColours extends GUserDefinedColours implements
     }
     else
     {
-      applyButton_actionPerformed(null);
+      applyButton_actionPerformed();
 
       try
       {
@@ -493,13 +512,11 @@ public class UserDefinedColours extends GUserDefinedColours implements
   }
 
   /**
-   * DOCUMENT ME!
-   * 
-   * @param e
-   *          DOCUMENT ME!
+   * Applies the current colour scheme to the alignment, sequence group or
+   * structure view.
    */
   @Override
-  protected void applyButton_actionPerformed(ActionEvent e)
+  protected void applyButton_actionPerformed()
   {
     if (isNoSelectionMade())
     {
@@ -521,9 +538,9 @@ public class UserDefinedColours extends GUserDefinedColours implements
     {
       ap.alignFrame.changeColour(ucs);
     }
-    else if (jmol != null)
+    else if (structureViewer != null)
     {
-      jmol.setJalviewColourScheme(ucs);
+      structureViewer.setJalviewColourScheme(ucs);
     }
   }
 
@@ -598,8 +615,7 @@ public class UserDefinedColours extends GUserDefinedColours implements
     lowerCaseButtons = new ArrayList<JButton>();
 
     JalviewFileChooser chooser = new JalviewFileChooser(
-            Cache.getProperty("LAST_DIRECTORY"), "jc",
-            "Jalview User Colours");
+            Cache.getProperty(LAST_DIRECTORY), "jc", "Jalview User Colours");
     chooser.setFileView(new JalviewFileView());
     chooser.setDialogTitle(MessageManager
             .getString("label.load_colour_scheme"));
@@ -607,50 +623,42 @@ public class UserDefinedColours extends GUserDefinedColours implements
 
     int value = chooser.showOpenDialog(this);
 
-    if (value == JalviewFileChooser.APPROVE_OPTION)
+    if (value != JalviewFileChooser.APPROVE_OPTION)
     {
-      File choice = chooser.getSelectedFile();
-      jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
-      String defaultColours = jalview.bin.Cache.getDefault(
-              "USER_DEFINED_COLOURS", choice.getPath());
-      if (defaultColours.indexOf(choice.getPath()) == -1)
-      {
-        defaultColours = defaultColours.concat("|")
-                .concat(choice.getPath());
-      }
-
-      jalview.bin.Cache.setProperty("USER_DEFINED_COLOURS", defaultColours);
-
-      UserColourScheme ucs = loadColours(choice.getAbsolutePath());
-      Color[] colors = ucs.getColours();
-      schemeName.setText(ucs.getName());
-
-      if (ucs.getLowerCaseColours() != null)
-      {
-        caseSensitive.setSelected(true);
-        lcaseColour.setEnabled(true);
-        resetButtonPanel(true);
-        for (int i = 0; i < lowerCaseButtons.size(); i++)
-        {
-          JButton button = lowerCaseButtons.get(i);
-          button.setBackground(ucs.getLowerCaseColours()[i]);
-        }
+      return;
+    }
+    File choice = chooser.getSelectedFile();
+    Cache.setProperty(LAST_DIRECTORY, choice.getParent());
 
-      }
-      else
-      {
-        caseSensitive.setSelected(false);
-        lcaseColour.setEnabled(false);
-        resetButtonPanel(false);
-      }
+    UserColourScheme ucs = loadColours(choice.getAbsolutePath());
+    Color[] colors = ucs.getColours();
+    schemeName.setText(ucs.getName());
 
-      for (int i = 0; i < upperCaseButtons.size(); i++)
+    if (ucs.getLowerCaseColours() != null)
+    {
+      caseSensitive.setSelected(true);
+      lcaseColour.setEnabled(true);
+      resetButtonPanel(true);
+      for (int i = 0; i < lowerCaseButtons.size(); i++)
       {
-        JButton button = upperCaseButtons.get(i);
-        button.setBackground(colors[i]);
+        JButton button = lowerCaseButtons.get(i);
+        button.setBackground(ucs.getLowerCaseColours()[i]);
       }
+    }
+    else
+    {
+      caseSensitive.setSelected(false);
+      lcaseColour.setEnabled(false);
+      resetButtonPanel(false);
+    }
 
+    for (int i = 0; i < upperCaseButtons.size(); i++)
+    {
+      JButton button = upperCaseButtons.get(i);
+      button.setBackground(colors[i]);
     }
+
+    addNewColourScheme(choice.getPath());
   }
 
   /**
@@ -662,7 +670,7 @@ public class UserDefinedColours extends GUserDefinedColours implements
   {
     UserColourScheme ret = null;
 
-    String colours = jalview.bin.Cache.getProperty("USER_DEFINED_COLOURS");
+    String colours = Cache.getProperty(USER_DEFINED_COLOURS);
     if (colours != null)
     {
       if (colours.indexOf("|") > -1)
@@ -833,7 +841,7 @@ public class UserDefinedColours extends GUserDefinedColours implements
       userColourSchemes.remove(schemeName.getText());
     }
     JalviewFileChooser chooser = new JalviewFileChooser(
-            Cache.getProperty("LAST_DIRECTORY"), "jc",
+            Cache.getProperty(LAST_DIRECTORY), "jc",
             "Jalview User Colours");
 
     chooser.setFileView(new JalviewFileView());
@@ -846,47 +854,82 @@ public class UserDefinedColours extends GUserDefinedColours implements
     if (value == JalviewFileChooser.APPROVE_OPTION)
     {
       String choice = chooser.getSelectedFile().getPath();
-      String defaultColours = jalview.bin.Cache.getDefault(
-              "USER_DEFINED_COLOURS", choice);
-      if (defaultColours.indexOf(choice) == -1)
+      addNewColourScheme(choice);
+      saveToFile(choice);
+    }
+  }
+
+  /**
+   * Adds the current colour scheme to the Jalview properties file so it is
+   * loaded on next startup, and updates the Colour menu in the parent
+   * AlignFrame (if there is one). Note this action does not including applying
+   * the colour scheme.
+   * 
+   * @param filePath
+   */
+  protected void addNewColourScheme(String filePath)
+  {
+    /*
+     * update the delimited list of user defined colour files in
+     * Jalview property USER_DEFINED_COLOURS
+     */
+    String defaultColours = Cache
+            .getDefault(USER_DEFINED_COLOURS, filePath);
+    if (defaultColours.indexOf(filePath) == -1)
+    {
+      if (defaultColours.length() > 0)
       {
-        if (defaultColours.length() > 0)
-        {
-          defaultColours = defaultColours.concat("|");
-        }
-        defaultColours = defaultColours.concat(choice);
+        defaultColours = defaultColours.concat("|");
       }
+      defaultColours = defaultColours.concat(filePath);
+    }
+    Cache.setProperty(USER_DEFINED_COLOURS, defaultColours);
 
-      userColourSchemes.put(schemeName.getText(), getSchemeFromButtons());
-
-      ap.alignFrame.updateUserColourMenu();
-
-      jalview.bin.Cache.setProperty("USER_DEFINED_COLOURS", defaultColours);
-
-      jalview.schemabinding.version2.JalviewUserColours ucs = new jalview.schemabinding.version2.JalviewUserColours();
+    /*
+     * add to the cache in this object
+     */
+    userColourSchemes.put(schemeName.getText(), getSchemeFromButtons());
 
-      ucs.setSchemeName(schemeName.getText());
-      try
-      {
-        PrintWriter out = new PrintWriter(new OutputStreamWriter(
-                new FileOutputStream(choice), "UTF-8"));
+    /*
+     * update the Colour menu items
+     */
+    if (ap != null)
+    {
+      ap.alignFrame.buildColourMenu();// updateUserColourMenu();
+    }
+  }
 
-        for (int i = 0; i < buttonPanel.getComponentCount(); i++)
-        {
-          JButton button = (JButton) buttonPanel.getComponent(i);
-          jalview.schemabinding.version2.Colour col = new jalview.schemabinding.version2.Colour();
-          col.setName(button.getText());
-          col.setRGB(jalview.util.Format.getHexString(button
-                  .getBackground()));
-          ucs.addColour(col);
-        }
+  /**
+   * Saves the colour scheme to file in XML format
+   * 
+   * @param filePath
+   */
+  protected void saveToFile(String filePath)
+  {
+    /*
+     * build a Java model of colour scheme as XML, and 
+     * marshal to file
+     */
+    JalviewUserColours ucs = new JalviewUserColours();
+    ucs.setSchemeName(schemeName.getText());
+    try
+    {
+      PrintWriter out = new PrintWriter(new OutputStreamWriter(
+              new FileOutputStream(filePath), "UTF-8"));
 
-        ucs.marshal(out);
-        out.close();
-      } catch (Exception ex)
+      for (int i = 0; i < buttonPanel.getComponentCount(); i++)
       {
-        ex.printStackTrace();
+        JButton button = (JButton) buttonPanel.getComponent(i);
+        Colour col = new Colour();
+        col.setName(button.getText());
+        col.setRGB(Format.getHexString(button.getBackground()));
+        ucs.addColour(col);
       }
+      ucs.marshal(out);
+      out.close();
+    } catch (Exception ex)
+    {
+      ex.printStackTrace();
     }
   }
 
@@ -912,9 +955,9 @@ public class UserDefinedColours extends GUserDefinedColours implements
       ap.paintAlignment(true);
     }
 
-    if (jmol != null)
+    if (structureViewer != null)
     {
-      jmol.setJalviewColourScheme(oldColourScheme);
+      structureViewer.setJalviewColourScheme(oldColourScheme);
     }
 
     try
@@ -925,16 +968,14 @@ public class UserDefinedColours extends GUserDefinedColours implements
     }
   }
 
-  static Hashtable userColourSchemes;
-
-  public static Hashtable getUserColourSchemes()
+  public static SortedMap<String, UserColourScheme> getUserColourSchemes()
   {
     return userColourSchemes;
   }
 
   public static void initUserColourSchemes(String files)
   {
-    userColourSchemes = new Hashtable();
+    userColourSchemes = new TreeMap<String, UserColourScheme>();
 
     if (files == null || files.length() == 0)
     {
@@ -969,13 +1010,11 @@ public class UserDefinedColours extends GUserDefinedColours implements
     {
       if (coloursFound.toString().length() > 1)
       {
-        jalview.bin.Cache.setProperty("USER_DEFINED_COLOURS",
-                coloursFound.toString());
+        Cache.setProperty(USER_DEFINED_COLOURS, coloursFound.toString());
       }
       else
       {
-        jalview.bin.Cache.applicationProperties
-                .remove("USER_DEFINED_COLOURS");
+        Cache.applicationProperties.remove(USER_DEFINED_COLOURS);
       }
     }
   }
@@ -986,11 +1025,11 @@ public class UserDefinedColours extends GUserDefinedColours implements
     // In case colours can't be loaded, we'll remove them
     // from the default list here.
 
-    userColourSchemes = new Hashtable();
+    userColourSchemes = new TreeMap<String, UserColourScheme>();
 
     StringBuffer coloursFound = new StringBuffer();
     StringTokenizer st = new StringTokenizer(
-            jalview.bin.Cache.getProperty("USER_DEFINED_COLOURS"), "|");
+            Cache.getProperty(USER_DEFINED_COLOURS), "|");
 
     while (st.hasMoreElements())
     {
@@ -1015,13 +1054,11 @@ public class UserDefinedColours extends GUserDefinedColours implements
 
     if (coloursFound.toString().length() > 1)
     {
-      jalview.bin.Cache.setProperty("USER_DEFINED_COLOURS",
-              coloursFound.toString());
+      Cache.setProperty(USER_DEFINED_COLOURS, coloursFound.toString());
     }
     else
     {
-      jalview.bin.Cache.applicationProperties
-              .remove("USER_DEFINED_COLOURS");
+      Cache.applicationProperties.remove(USER_DEFINED_COLOURS);
     }
 
   }