JAL-2295 additional tests, stronger sanitisation of attribute name
[jalview.git] / src / jalview / ext / rbvi / chimera / ChimeraCommands.java
index a5ee933..9ef89fd 100644 (file)
@@ -49,12 +49,18 @@ import MCview.PDBChain;
 public class ChimeraCommands
 {
 
+  private static final String NAMESPACE_PREFIX = "jv_";
+
   /**
-   * utility to construct the commands to colour chains by the given alignment
-   * for passing to Chimera
-   * 
-   * @returns Object[] { Object[] { <model being coloured>,
+   * Constructs Chimera commands to colour residues as per the Jalview alignment
    * 
+   * @param ssm
+   * @param files
+   * @param sequence
+   * @param sr
+   * @param fr
+   * @param alignment
+   * @return
    */
   public static StructureMappingcommandSet getColourBySequenceCommand(
           StructureSelectionManager ssm, String[] files,
@@ -286,8 +292,9 @@ public class ChimeraCommands
   }
 
   /**
-   * Constructs and returns a set of Chimera commands to set attributes on
-   * residues corresponding to features in Jalview
+   * Constructs and returns Chimera commands to set attributes on residues
+   * corresponding to features in Jalview. Attribute names are the Jalview
+   * feature type, with a "jv_" prefix.
    * 
    * @param ssm
    * @param files
@@ -403,7 +410,7 @@ public class ChimeraCommands
       if (!mappedRanges.isEmpty())
       {
         String value = sf.getDescription();
-        if (value == null)
+        if (value == null || value.length() == 0)
         {
           value = type;
         }
@@ -460,8 +467,7 @@ public class ChimeraCommands
     List<String> commands = new ArrayList<String>();
     for (String featureType : featureMap.keySet())
     {
-      String attributeName = "jv_"
-              + featureType.replace(" ", "_").replace("-", "_");
+      String attributeName = makeAttributeName(featureType);
 
       /*
        * clear down existing attributes for this feature
@@ -487,4 +493,38 @@ public class ChimeraCommands
     return commands;
   }
 
+  /**
+   * Makes a prefixed and valid Chimera attribute name. A jv_ prefix is applied
+   * for a 'Jalview' namespace, and any non-alphanumeric character is converted
+   * to an underscore.
+   * 
+   * @param featureType
+   * @return <pre>
+   * @see https://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/setattr.html
+   * </pre>
+   */
+  protected static String makeAttributeName(String featureType)
+  {
+    StringBuilder sb = new StringBuilder();
+    if (featureType != null)
+    {
+      for (char c : featureType.toCharArray())
+      {
+        sb.append(Character.isLetterOrDigit(c) ? c : '_');
+      }
+    }
+    String attName = NAMESPACE_PREFIX + sb.toString();
+
+    /*
+     * Chimera treats an attribute name ending in 'color' as colour-valued;
+     * Jalview doesn't, so prevent this by appending an underscore
+     */
+    if (attName.toUpperCase().endsWith("COLOR"))
+    {
+      attName += "_";
+    }
+
+    return attName;
+  }
+
 }