JAL-4435 Append numbers to group names if there is a naming conflict
authorRenia Correya <rcorreya001@dundee.ac.uk>
Wed, 16 Oct 2024 13:29:33 +0000 (14:29 +0100)
committerRenia Correya <rcorreya001@dundee.ac.uk>
Wed, 16 Oct 2024 13:29:33 +0000 (14:29 +0100)
src/jalview/gui/TreeCanvas.java

index 59b8d4b..33f8c6d 100755 (executable)
@@ -1393,9 +1393,41 @@ public class TreeCanvas extends JPanel implements MouseListener, Runnable,
     SequenceGroup _sg = new SequenceGroup(sequences, null, cs, true, true,
             false, 0, av.getAlignment().getWidth() - 1);
     
+    // Check if the label is not null and not empty
     if(label != null && !label.isEmpty()) {
+      // Retrieve the existing groups from the alignment
+      List<SequenceGroup> existingGroups = av.getAlignment().getGroups();
+      
+      // Reduce the label length
       label = AlignmentUtils.reduceLabelLength(label);
-      _sg.setName("JTreeGroup:" + label);
+      
+      // Create group name based on the label
+      String newGroupName = "JTreeGroup:" + label;
+      
+      // Counter for groups with the same name
+      int noOfGroupsWithSameName = 0;
+      
+      // Iterate through the existing groups to check for naming conflicts
+      for (SequenceGroup sg : existingGroups) {
+        if (sg.getName().equals(newGroupName) || sg.getName().matches(newGroupName + " \\d+")) {
+
+          noOfGroupsWithSameName++;
+          
+          // If a group name matches exactly, update the group's name by appending the count
+          if(sg.getName().equals(newGroupName) ) {
+            String updatedGroupName = sg.getName() + " " + noOfGroupsWithSameName;
+            sg.setName(updatedGroupName);
+          }
+        }
+      }
+      
+      // If count > 0, increment the count and append it to the new group name
+      if(noOfGroupsWithSameName>0) {
+        noOfGroupsWithSameName++;
+        newGroupName = newGroupName + " " + noOfGroupsWithSameName;
+      }
+      
+      _sg.setName(newGroupName);
     }
     else {
       _sg.setName("JTreeGroup:" + _sg.hashCode());