Merge branch 'develop' of https://source.jalview.org/git/jalview into develop
[jalview.git] / src / jalview / gui / TreePanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.NJTree;
25 import jalview.api.analysis.ScoreModelI;
26 import jalview.api.analysis.ViewBasedAnalysisI;
27 import jalview.bin.Cache;
28 import jalview.commands.CommandI;
29 import jalview.commands.OrderCommand;
30 import jalview.datamodel.Alignment;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.AlignmentView;
33 import jalview.datamodel.BinaryNode;
34 import jalview.datamodel.ColumnSelection;
35 import jalview.datamodel.DBRefEntry;
36 import jalview.datamodel.NodeTransformI;
37 import jalview.datamodel.SequenceFeature;
38 import jalview.datamodel.SequenceI;
39 import jalview.datamodel.SequenceNode;
40 import jalview.io.JalviewFileChooser;
41 import jalview.io.JalviewFileView;
42 import jalview.io.NewickFile;
43 import jalview.jbgui.GTreePanel;
44 import jalview.schemes.ResidueProperties;
45 import jalview.util.MessageManager;
46 import jalview.viewmodel.AlignmentViewport;
47
48 import java.awt.Font;
49 import java.awt.Graphics;
50 import java.awt.event.ActionEvent;
51 import java.awt.event.ActionListener;
52 import java.awt.image.BufferedImage;
53 import java.beans.PropertyChangeEvent;
54 import java.io.FileOutputStream;
55 import java.util.ArrayList;
56 import java.util.List;
57
58 import javax.imageio.ImageIO;
59 import javax.swing.ButtonGroup;
60 import javax.swing.JMenuItem;
61 import javax.swing.JRadioButtonMenuItem;
62
63 import org.jibble.epsgraphics.EpsGraphics2D;
64
65 /**
66  * DOCUMENT ME!
67  * 
68  * @author $author$
69  * @version $Revision$
70  */
71 public class TreePanel extends GTreePanel
72 {
73   String type;
74
75   String pwtype;
76
77   TreeCanvas treeCanvas;
78
79   NJTree tree;
80
81   AlignViewport av;
82
83   /**
84    * Creates a new TreePanel object.
85    * 
86    * @param av
87    *          DOCUMENT ME!
88    * @param seqVector
89    *          DOCUMENT ME!
90    * @param type
91    *          DOCUMENT ME!
92    * @param pwtype
93    *          DOCUMENT ME!
94    * @param s
95    *          DOCUMENT ME!
96    * @param e
97    *          DOCUMENT ME!
98    */
99   public TreePanel(AlignmentPanel ap, String type, String pwtype)
100   {
101     super();
102     initTreePanel(ap, type, pwtype, null, null);
103
104     // We know this tree has distances. JBPNote TODO: prolly should add this as
105     // a userdefined default
106     // showDistances(true);
107   }
108
109   /**
110    * Creates a new TreePanel object.
111    * 
112    * @param av
113    *          DOCUMENT ME!
114    * @param seqVector
115    *          DOCUMENT ME!
116    * @param newtree
117    *          DOCUMENT ME!
118    * @param type
119    *          DOCUMENT ME!
120    * @param pwtype
121    *          DOCUMENT ME!
122    */
123   public TreePanel(AlignmentPanel ap, String type, String pwtype,
124           NewickFile newtree)
125   {
126     super();
127     initTreePanel(ap, type, pwtype, newtree, null);
128   }
129
130   public TreePanel(AlignmentPanel av, String type, String pwtype,
131           NewickFile newtree, AlignmentView inputData)
132   {
133     super();
134     initTreePanel(av, type, pwtype, newtree, inputData);
135   }
136
137   public AlignmentI getAlignment()
138   {
139     return treeCanvas.av.getAlignment();
140   }
141
142   public AlignmentViewport getViewPort()
143   {
144     return treeCanvas.av;
145   }
146
147   void initTreePanel(AlignmentPanel ap, String type, String pwtype,
148           NewickFile newTree, AlignmentView inputData)
149   {
150
151     av = ap.av;
152     this.type = type;
153     this.pwtype = pwtype;
154
155     treeCanvas = new TreeCanvas(this, ap, scrollPane);
156     scrollPane.setViewportView(treeCanvas);
157
158     PaintRefresher.Register(this, ap.av.getSequenceSetId());
159
160     buildAssociatedViewMenu();
161
162     av.addPropertyChangeListener(new java.beans.PropertyChangeListener()
163     {
164       @Override
165       public void propertyChange(PropertyChangeEvent evt)
166       {
167         if (evt.getPropertyName().equals("alignment"))
168         {
169           if (tree == null)
170           {
171             System.out.println("tree is null");
172             // TODO: deal with case when a change event is received whilst a
173             // tree is still being calculated - should save reference for
174             // processing message later.
175             return;
176           }
177           if (evt.getNewValue() == null)
178           {
179             System.out
180                     .println("new alignment sequences vector value is null");
181           }
182
183           tree.UpdatePlaceHolders((List<SequenceI>) evt.getNewValue());
184           treeCanvas.nameHash.clear(); // reset the mapping between canvas
185           // rectangles and leafnodes
186           repaint();
187         }
188       }
189     });
190
191     TreeLoader tl = new TreeLoader(newTree);
192     if (inputData != null)
193     {
194       tl.odata = inputData;
195     }
196     tl.start();
197
198   }
199
200   @Override
201   public void viewMenu_menuSelected()
202   {
203     buildAssociatedViewMenu();
204   }
205
206   void buildAssociatedViewMenu()
207   {
208     AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av
209             .getSequenceSetId());
210     if (aps.length == 1 && treeCanvas.ap == aps[0])
211     {
212       associateLeavesMenu.setVisible(false);
213       return;
214     }
215
216     associateLeavesMenu.setVisible(true);
217
218     if ((viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
219     {
220       viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
221     }
222
223     associateLeavesMenu.removeAll();
224
225     JRadioButtonMenuItem item;
226     ButtonGroup buttonGroup = new ButtonGroup();
227     int i, iSize = aps.length;
228     final TreePanel thisTreePanel = this;
229     for (i = 0; i < iSize; i++)
230     {
231       final AlignmentPanel ap = aps[i];
232       item = new JRadioButtonMenuItem(ap.av.viewName, ap == treeCanvas.ap);
233       buttonGroup.add(item);
234       item.addActionListener(new ActionListener()
235       {
236         @Override
237         public void actionPerformed(ActionEvent evt)
238         {
239           treeCanvas.applyToAllViews = false;
240           treeCanvas.ap = ap;
241           treeCanvas.av = ap.av;
242           PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
243         }
244       });
245
246       associateLeavesMenu.add(item);
247     }
248
249     final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
250             MessageManager.getString("label.all_views"));
251     buttonGroup.add(itemf);
252     itemf.setSelected(treeCanvas.applyToAllViews);
253     itemf.addActionListener(new ActionListener()
254     {
255       @Override
256       public void actionPerformed(ActionEvent evt)
257       {
258         treeCanvas.applyToAllViews = itemf.isSelected();
259       }
260     });
261     associateLeavesMenu.add(itemf);
262
263   }
264
265   class TreeLoader extends Thread
266   {
267     NewickFile newtree;
268
269     jalview.datamodel.AlignmentView odata = null;
270
271     public TreeLoader(NewickFile newtree)
272     {
273       this.newtree = newtree;
274       if (newtree != null)
275       {
276         // Must be outside run(), as Jalview2XML tries to
277         // update distance/bootstrap visibility at the same time
278         showBootstrap(newtree.HasBootstrap());
279         showDistances(newtree.HasDistances());
280       }
281     }
282
283     @Override
284     public void run()
285     {
286
287       if (newtree != null)
288       {
289         if (odata == null)
290         {
291           tree = new NJTree(av.getAlignment().getSequencesArray(), newtree);
292         }
293         else
294         {
295           tree = new NJTree(av.getAlignment().getSequencesArray(), odata,
296                   newtree);
297         }
298         if (!tree.hasOriginalSequenceData())
299         {
300           allowOriginalSeqData(false);
301         }
302       }
303       else
304       {
305         int start, end;
306         SequenceI[] seqs;
307         boolean selview = av.getSelectionGroup() != null
308                 && av.getSelectionGroup().getSize() > 1;
309         AlignmentView seqStrings = av.getAlignmentView(selview);
310         if (!selview)
311         {
312           start = 0;
313           end = av.getAlignment().getWidth();
314           seqs = av.getAlignment().getSequencesArray();
315         }
316         else
317         {
318           start = av.getSelectionGroup().getStartRes();
319           end = av.getSelectionGroup().getEndRes() + 1;
320           seqs = av.getSelectionGroup().getSequencesInOrder(
321                   av.getAlignment());
322         }
323         ScoreModelI sm = ResidueProperties.getScoreModel(pwtype);
324         if (sm instanceof ViewBasedAnalysisI)
325         {
326           try
327           {
328             sm = sm.getClass().newInstance();
329             ((ViewBasedAnalysisI) sm)
330                     .configureFromAlignmentView(treeCanvas.ap);
331           } catch (Exception q)
332           {
333             Cache.log.error("Couldn't create a scoremodel instance for "
334                     + sm.getName());
335           }
336           tree = new NJTree(seqs, seqStrings, type, pwtype, sm, start, end);
337         }
338         else
339         {
340           tree = new NJTree(seqs, seqStrings, type, pwtype, null, start,
341                   end);
342         }
343         showDistances(true);
344       }
345
346       tree.reCount(tree.getTopNode());
347       tree.findHeight(tree.getTopNode());
348       treeCanvas.setTree(tree);
349       treeCanvas.repaint();
350       av.setCurrentTree(tree);
351       if (av.getSortByTree())
352       {
353         sortByTree_actionPerformed();
354       }
355     }
356   }
357
358   public void showDistances(boolean b)
359   {
360     treeCanvas.setShowDistances(b);
361     distanceMenu.setSelected(b);
362   }
363
364   public void showBootstrap(boolean b)
365   {
366     treeCanvas.setShowBootstrap(b);
367     bootstrapMenu.setSelected(b);
368   }
369
370   public void showPlaceholders(boolean b)
371   {
372     placeholdersMenu.setState(b);
373     treeCanvas.setMarkPlaceholders(b);
374   }
375
376   private void allowOriginalSeqData(boolean b)
377   {
378     originalSeqData.setVisible(b);
379   }
380
381   /**
382    * DOCUMENT ME!
383    * 
384    * @return DOCUMENT ME!
385    */
386   public NJTree getTree()
387   {
388     return tree;
389   }
390
391   /**
392    * DOCUMENT ME!
393    * 
394    * @param e
395    *          DOCUMENT ME!
396    */
397   @Override
398   public void textbox_actionPerformed(ActionEvent e)
399   {
400     CutAndPasteTransfer cap = new CutAndPasteTransfer();
401
402     StringBuffer buffer = new StringBuffer();
403
404     if (type.equals("AV"))
405     {
406       buffer.append("Average distance tree using ");
407     }
408     else
409     {
410       buffer.append("Neighbour joining tree using ");
411     }
412
413     if (pwtype.equals("BL"))
414     {
415       buffer.append("BLOSUM62");
416     }
417     else
418     {
419       buffer.append("PID");
420     }
421
422     jalview.io.NewickFile fout = new jalview.io.NewickFile(
423             tree.getTopNode());
424     try
425     {
426       cap.setText(fout.print(tree.isHasBootstrap(), tree.isHasDistances(),
427               tree.isHasRootDistance()));
428       Desktop.addInternalFrame(cap, buffer.toString(), 500, 100);
429     } catch (OutOfMemoryError oom)
430     {
431       new OOMWarning("generating newick tree file", oom);
432       cap.dispose();
433     }
434
435   }
436
437   /**
438    * DOCUMENT ME!
439    * 
440    * @param e
441    *          DOCUMENT ME!
442    */
443   @Override
444   public void saveAsNewick_actionPerformed(ActionEvent e)
445   {
446     JalviewFileChooser chooser = new JalviewFileChooser(
447             jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
448     chooser.setFileView(new JalviewFileView());
449     chooser.setDialogTitle(MessageManager
450             .getString("label.save_tree_as_newick"));
451     chooser.setToolTipText(MessageManager.getString("action.save"));
452
453     int value = chooser.showSaveDialog(null);
454
455     if (value == JalviewFileChooser.APPROVE_OPTION)
456     {
457       String choice = chooser.getSelectedFile().getPath();
458       jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
459               .getSelectedFile().getParent());
460
461       try
462       {
463         jalview.io.NewickFile fout = new jalview.io.NewickFile(
464                 tree.getTopNode());
465         String output = fout.print(tree.isHasBootstrap(),
466                 tree.isHasDistances(), tree.isHasRootDistance());
467         java.io.PrintWriter out = new java.io.PrintWriter(
468                 new java.io.FileWriter(choice));
469         out.println(output);
470         out.close();
471       } catch (Exception ex)
472       {
473         ex.printStackTrace();
474       }
475     }
476   }
477
478   /**
479    * DOCUMENT ME!
480    * 
481    * @param e
482    *          DOCUMENT ME!
483    */
484   @Override
485   public void printMenu_actionPerformed(ActionEvent e)
486   {
487     // Putting in a thread avoids Swing painting problems
488     treeCanvas.startPrinting();
489   }
490
491   @Override
492   public void originalSeqData_actionPerformed(ActionEvent e)
493   {
494     if (!tree.hasOriginalSequenceData())
495     {
496       jalview.bin.Cache.log
497               .info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
498       return;
499     }
500     // decide if av alignment is sufficiently different to original data to
501     // warrant a new window to be created
502     // create new alignmnt window with hidden regions (unhiding hidden regions
503     // yields unaligned seqs)
504     // or create a selection box around columns in alignment view
505     // test Alignment(SeqCigar[])
506     char gc = '-';
507     try
508     {
509       // we try to get the associated view's gap character
510       // but this may fail if the view was closed...
511       gc = av.getGapCharacter();
512
513     } catch (Exception ex)
514     {
515     }
516     ;
517     Object[] alAndColsel = tree.seqData.getAlignmentAndColumnSelection(gc);
518
519     if (alAndColsel != null && alAndColsel[0] != null)
520     {
521       // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
522
523       Alignment al = new Alignment((SequenceI[]) alAndColsel[0]);
524       Alignment dataset = (av != null && av.getAlignment() != null) ? av
525               .getAlignment().getDataset() : null;
526       if (dataset != null)
527       {
528         al.setDataset(dataset);
529       }
530
531       if (true)
532       {
533         // make a new frame!
534         AlignFrame af = new AlignFrame(al,
535                 (ColumnSelection) alAndColsel[1], AlignFrame.DEFAULT_WIDTH,
536                 AlignFrame.DEFAULT_HEIGHT);
537
538         // >>>This is a fix for the moment, until a better solution is
539         // found!!<<<
540         // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
541
542         // af.addSortByOrderMenuItem(ServiceName + " Ordering",
543         // msaorder);
544
545         Desktop.addInternalFrame(af, MessageManager.formatMessage(
546                 "label.original_data_for_params",
547                 new Object[] { this.title }), AlignFrame.DEFAULT_WIDTH,
548                 AlignFrame.DEFAULT_HEIGHT);
549       }
550     }
551   }
552
553   /**
554    * DOCUMENT ME!
555    * 
556    * @param e
557    *          DOCUMENT ME!
558    */
559   @Override
560   public void fitToWindow_actionPerformed(ActionEvent e)
561   {
562     treeCanvas.fitToWindow = fitToWindow.isSelected();
563     repaint();
564   }
565
566   /**
567    * sort the associated alignment view by the current tree.
568    * 
569    * @param e
570    */
571   @Override
572   public void sortByTree_actionPerformed()
573   {
574
575     if (treeCanvas.applyToAllViews)
576     {
577       final ArrayList<CommandI> commands = new ArrayList<CommandI>();
578       for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
579               .getSequenceSetId()))
580       {
581         commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
582       }
583       av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
584       {
585
586         @Override
587         public void undoCommand(AlignmentI[] views)
588         {
589           for (CommandI tsort : commands)
590           {
591             tsort.undoCommand(views);
592           }
593         }
594
595         @Override
596         public int getSize()
597         {
598           return commands.size();
599         }
600
601         @Override
602         public String getDescription()
603         {
604           return "Tree Sort (many views)";
605         }
606
607         @Override
608         public void doCommand(AlignmentI[] views)
609         {
610
611           for (CommandI tsort : commands)
612           {
613             tsort.doCommand(views);
614           }
615         }
616       });
617       for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
618               .getSequenceSetId()))
619       {
620         // ensure all the alignFrames refresh their GI after adding an undo item
621         ap.alignFrame.updateEditMenuBar();
622       }
623     }
624     else
625     {
626       treeCanvas.ap.alignFrame
627               .addHistoryItem(sortAlignmentIn(treeCanvas.ap));
628     }
629
630   }
631
632   public CommandI sortAlignmentIn(AlignmentPanel ap)
633   {
634     AlignmentViewport av = ap.av;
635     SequenceI[] oldOrder = av.getAlignment().getSequencesArray();
636     AlignmentSorter.sortByTree(av.getAlignment(), tree);
637     CommandI undo;
638     undo = new OrderCommand("Tree Sort", oldOrder, av.getAlignment());
639
640     ap.paintAlignment(true);
641     return undo;
642   }
643
644   /**
645    * DOCUMENT ME!
646    * 
647    * @param e
648    *          DOCUMENT ME!
649    */
650   @Override
651   public void font_actionPerformed(ActionEvent e)
652   {
653     if (treeCanvas == null)
654     {
655       return;
656     }
657
658     new FontChooser(this);
659   }
660
661   public Font getTreeFont()
662   {
663     return treeCanvas.font;
664   }
665
666   public void setTreeFont(Font font)
667   {
668     if (treeCanvas != null)
669     {
670       treeCanvas.setFont(font);
671     }
672   }
673
674   /**
675    * DOCUMENT ME!
676    * 
677    * @param e
678    *          DOCUMENT ME!
679    */
680   @Override
681   public void distanceMenu_actionPerformed(ActionEvent e)
682   {
683     treeCanvas.setShowDistances(distanceMenu.isSelected());
684   }
685
686   /**
687    * DOCUMENT ME!
688    * 
689    * @param e
690    *          DOCUMENT ME!
691    */
692   @Override
693   public void bootstrapMenu_actionPerformed(ActionEvent e)
694   {
695     treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
696   }
697
698   /**
699    * DOCUMENT ME!
700    * 
701    * @param e
702    *          DOCUMENT ME!
703    */
704   @Override
705   public void placeholdersMenu_actionPerformed(ActionEvent e)
706   {
707     treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
708   }
709
710   /**
711    * DOCUMENT ME!
712    * 
713    * @param e
714    *          DOCUMENT ME!
715    */
716   @Override
717   public void epsTree_actionPerformed(ActionEvent e)
718   {
719     boolean accurateText = true;
720
721     String renderStyle = jalview.bin.Cache.getDefault("EPS_RENDERING",
722             "Prompt each time");
723
724     // If we need to prompt, and if the GUI is visible then
725     // Prompt for EPS rendering style
726     if (renderStyle.equalsIgnoreCase("Prompt each time")
727             && !(System.getProperty("java.awt.headless") != null && System
728                     .getProperty("java.awt.headless").equals("true")))
729     {
730       EPSOptions eps = new EPSOptions();
731       renderStyle = eps.getValue();
732
733       if (renderStyle == null || eps.cancelled)
734       {
735         return;
736       }
737
738     }
739
740     if (renderStyle.equalsIgnoreCase("text"))
741     {
742       accurateText = false;
743     }
744
745     int width = treeCanvas.getWidth();
746     int height = treeCanvas.getHeight();
747
748     try
749     {
750       jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
751               jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
752               { "eps" }, new String[] { "Encapsulated Postscript" },
753               "Encapsulated Postscript");
754       chooser.setFileView(new jalview.io.JalviewFileView());
755       chooser.setDialogTitle(MessageManager
756               .getString("label.create_eps_from_tree"));
757       chooser.setToolTipText(MessageManager.getString("action.save"));
758
759       int value = chooser.showSaveDialog(this);
760
761       if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
762       {
763         return;
764       }
765
766       jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
767               .getSelectedFile().getParent());
768
769       FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
770       EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width, height);
771
772       pg.setAccurateTextMode(accurateText);
773
774       treeCanvas.draw(pg, width, height);
775
776       pg.flush();
777       pg.close();
778     } catch (Exception ex)
779     {
780       ex.printStackTrace();
781     }
782   }
783
784   /**
785    * DOCUMENT ME!
786    * 
787    * @param e
788    *          DOCUMENT ME!
789    */
790   @Override
791   public void pngTree_actionPerformed(ActionEvent e)
792   {
793     int width = treeCanvas.getWidth();
794     int height = treeCanvas.getHeight();
795
796     try
797     {
798       jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
799               jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
800               { "png" }, new String[] { "Portable network graphics" },
801               "Portable network graphics");
802
803       chooser.setFileView(new jalview.io.JalviewFileView());
804       chooser.setDialogTitle(MessageManager
805               .getString("label.create_png_from_tree"));
806       chooser.setToolTipText(MessageManager.getString("action.save"));
807
808       int value = chooser.showSaveDialog(this);
809
810       if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
811       {
812         return;
813       }
814
815       jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
816               .getSelectedFile().getParent());
817
818       FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
819
820       BufferedImage bi = new BufferedImage(width, height,
821               BufferedImage.TYPE_INT_RGB);
822       Graphics png = bi.getGraphics();
823
824       treeCanvas.draw(png, width, height);
825
826       ImageIO.write(bi, "png", out);
827       out.close();
828     } catch (Exception ex)
829     {
830       ex.printStackTrace();
831     }
832   }
833
834   /**
835    * change node labels to the annotation referred to by labelClass TODO:
836    * promote to a datamodel modification that can be undone TODO: make argument
837    * one case of a generic transformation function ie { undoStep = apply(Tree,
838    * TransformFunction)};
839    * 
840    * @param labelClass
841    */
842   public void changeNames(final String labelClass)
843   {
844     tree.applyToNodes(new NodeTransformI()
845     {
846
847       @Override
848       public void transform(BinaryNode node)
849       {
850         if (node instanceof SequenceNode
851                 && !((SequenceNode) node).isPlaceholder()
852                 && !((SequenceNode) node).isDummy())
853         {
854           String newname = null;
855           SequenceI sq = (SequenceI) ((SequenceNode) node).element();
856           if (sq != null)
857           {
858             // search dbrefs, features and annotation
859             DBRefEntry[] refs = jalview.util.DBRefUtils.selectRefs(
860                     sq.getDBRefs(),
861                     new String[] { labelClass.toUpperCase() });
862             if (refs != null)
863             {
864               for (int i = 0; i < refs.length; i++)
865               {
866                 if (newname == null)
867                 {
868                   newname = new String(refs[i].getAccessionId());
869                 }
870                 else
871                 {
872                   newname = newname + "; " + refs[i].getAccessionId();
873                 }
874               }
875             }
876             if (newname == null)
877             {
878               SequenceFeature sf[] = sq.getSequenceFeatures();
879               for (int i = 0; sf != null && i < sf.length; i++)
880               {
881                 if (sf[i].getType().equals(labelClass))
882                 {
883                   if (newname == null)
884                   {
885                     newname = new String(sf[i].getDescription());
886                   }
887                   else
888                   {
889                     newname = newname + "; " + sf[i].getDescription();
890                   }
891                 }
892               }
893             }
894           }
895           if (newname != null)
896           {
897             String oldname = ((SequenceNode) node).getName();
898             // TODO : save in the undo object for this modification.
899             ((SequenceNode) node).setName(newname);
900           }
901         }
902       }
903     });
904   }
905 }