2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import jalview.analysis.AlignmentSorter;
24 import jalview.analysis.AverageDistanceTree;
25 import jalview.analysis.NJTree;
26 import jalview.analysis.TreeBuilder;
27 import jalview.analysis.TreeModel;
28 import jalview.analysis.scoremodels.ScoreModels;
29 import jalview.api.analysis.ScoreModelI;
30 import jalview.api.analysis.SimilarityParamsI;
31 import jalview.bin.Cache;
32 import jalview.commands.CommandI;
33 import jalview.commands.OrderCommand;
34 import jalview.datamodel.Alignment;
35 import jalview.datamodel.AlignmentI;
36 import jalview.datamodel.AlignmentView;
37 import jalview.datamodel.BinaryNode;
38 import jalview.datamodel.DBRefEntry;
39 import jalview.datamodel.HiddenColumns;
40 import jalview.datamodel.NodeTransformI;
41 import jalview.datamodel.SequenceFeature;
42 import jalview.datamodel.SequenceI;
43 import jalview.datamodel.SequenceNode;
44 import jalview.io.JalviewFileChooser;
45 import jalview.io.JalviewFileView;
46 import jalview.io.NewickFile;
47 import jalview.jbgui.GTreePanel;
48 import jalview.util.ImageMaker;
49 import jalview.util.MessageManager;
50 import jalview.viewmodel.AlignmentViewport;
53 import java.awt.Graphics;
54 import java.awt.event.ActionEvent;
55 import java.awt.event.ActionListener;
56 import java.awt.image.BufferedImage;
57 import java.beans.PropertyChangeEvent;
58 import java.io.FileOutputStream;
59 import java.util.ArrayList;
60 import java.util.List;
62 import javax.imageio.ImageIO;
63 import javax.swing.ButtonGroup;
64 import javax.swing.JMenuItem;
65 import javax.swing.JRadioButtonMenuItem;
67 import org.jibble.epsgraphics.EpsGraphics2D;
75 public class TreePanel extends GTreePanel
79 String scoreModelName; // if tree computed
81 String treeTitle; // if tree loaded
83 SimilarityParamsI similarityParams;
85 TreeCanvas treeCanvas;
92 * Creates a new TreePanel object.
99 public TreePanel(AlignmentPanel ap, String type, String modelName,
100 SimilarityParamsI options)
103 this.similarityParams = options;
104 initTreePanel(ap, type, modelName, null, null);
106 // We know this tree has distances. JBPNote TODO: prolly should add this as
107 // a userdefined default
108 // showDistances(true);
111 public TreePanel(AlignmentPanel alignPanel, NewickFile newtree,
112 String theTitle, AlignmentView inputData)
115 this.treeTitle = theTitle;
116 initTreePanel(alignPanel, null, null, newtree, inputData);
119 public AlignmentI getAlignment()
121 return treeCanvas.av.getAlignment();
124 public AlignmentViewport getViewPort()
126 return treeCanvas.av;
129 void initTreePanel(AlignmentPanel ap, String type, String modelName,
130 NewickFile newTree, AlignmentView inputData)
134 this.treeType = type;
135 this.scoreModelName = modelName;
137 treeCanvas = new TreeCanvas(this, ap, scrollPane);
138 scrollPane.setViewportView(treeCanvas);
140 PaintRefresher.Register(this, ap.av.getSequenceSetId());
142 buildAssociatedViewMenu();
144 av.addPropertyChangeListener(new java.beans.PropertyChangeListener()
147 public void propertyChange(PropertyChangeEvent evt)
149 if (evt.getPropertyName().equals("alignment"))
153 System.out.println("tree is null");
154 // TODO: deal with case when a change event is received whilst a
155 // tree is still being calculated - should save reference for
156 // processing message later.
159 if (evt.getNewValue() == null)
162 .println("new alignment sequences vector value is null");
165 tree.updatePlaceHolders((List<SequenceI>) evt.getNewValue());
166 treeCanvas.nameHash.clear(); // reset the mapping between canvas
167 // rectangles and leafnodes
173 TreeLoader tl = new TreeLoader(newTree, inputData);
179 public void viewMenu_menuSelected()
181 buildAssociatedViewMenu();
184 void buildAssociatedViewMenu()
186 AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av
187 .getSequenceSetId());
188 if (aps.length == 1 && treeCanvas.ap == aps[0])
190 associateLeavesMenu.setVisible(false);
194 associateLeavesMenu.setVisible(true);
196 if ((viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
198 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
201 associateLeavesMenu.removeAll();
203 JRadioButtonMenuItem item;
204 ButtonGroup buttonGroup = new ButtonGroup();
205 int i, iSize = aps.length;
206 final TreePanel thisTreePanel = this;
207 for (i = 0; i < iSize; i++)
209 final AlignmentPanel ap = aps[i];
210 item = new JRadioButtonMenuItem(ap.av.viewName, ap == treeCanvas.ap);
211 buttonGroup.add(item);
212 item.addActionListener(new ActionListener()
215 public void actionPerformed(ActionEvent evt)
217 treeCanvas.applyToAllViews = false;
219 treeCanvas.av = ap.av;
220 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
224 associateLeavesMenu.add(item);
227 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
228 MessageManager.getString("label.all_views"));
229 buttonGroup.add(itemf);
230 itemf.setSelected(treeCanvas.applyToAllViews);
231 itemf.addActionListener(new ActionListener()
234 public void actionPerformed(ActionEvent evt)
236 treeCanvas.applyToAllViews = itemf.isSelected();
239 associateLeavesMenu.add(itemf);
243 class TreeLoader extends Thread
245 private NewickFile newtree;
247 private AlignmentView odata = null;
249 public TreeLoader(NewickFile newickFile, AlignmentView inputData)
251 this.newtree = newickFile;
252 this.odata = inputData;
254 if (newickFile != null)
256 // Must be outside run(), as Jalview2XML tries to
257 // update distance/bootstrap visibility at the same time
258 showBootstrap(newickFile.HasBootstrap());
259 showDistances(newickFile.HasDistances());
269 tree = new TreeModel(av.getAlignment().getSequencesArray(), odata,
271 if (tree.getOriginalData() == null)
273 originalSeqData.setVisible(false);
278 ScoreModelI sm = ScoreModels.getInstance().getScoreModel(
279 scoreModelName, treeCanvas.ap);
280 TreeBuilder njtree = treeType.equals(TreeBuilder.NEIGHBOUR_JOINING) ? new NJTree(
281 av, sm, similarityParams) : new AverageDistanceTree(av, sm,
283 tree = new TreeModel(njtree);
287 tree.reCount(tree.getTopNode());
288 tree.findHeight(tree.getTopNode());
289 treeCanvas.setTree(tree);
290 treeCanvas.repaint();
291 av.setCurrentTree(tree);
292 if (av.getSortByTree())
294 sortByTree_actionPerformed();
299 public void showDistances(boolean b)
301 treeCanvas.setShowDistances(b);
302 distanceMenu.setSelected(b);
305 public void showBootstrap(boolean b)
307 treeCanvas.setShowBootstrap(b);
308 bootstrapMenu.setSelected(b);
311 public void showPlaceholders(boolean b)
313 placeholdersMenu.setState(b);
314 treeCanvas.setMarkPlaceholders(b);
320 * @return DOCUMENT ME!
322 public TreeModel getTree()
334 public void textbox_actionPerformed(ActionEvent e)
336 CutAndPasteTransfer cap = new CutAndPasteTransfer();
338 String newTitle = getPanelTitle();
340 NewickFile fout = new NewickFile(tree.getTopNode());
343 cap.setText(fout.print(tree.hasBootstrap(), tree.hasDistances(),
344 tree.hasRootDistance()));
345 Desktop.addInternalFrame(cap, newTitle, 500, 100);
346 } catch (OutOfMemoryError oom)
348 new OOMWarning("generating newick tree file", oom);
361 public void saveAsNewick_actionPerformed(ActionEvent e)
363 JalviewFileChooser chooser = new JalviewFileChooser(
364 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
365 chooser.setFileView(new JalviewFileView());
366 chooser.setDialogTitle(MessageManager
367 .getString("label.save_tree_as_newick"));
368 chooser.setToolTipText(MessageManager.getString("action.save"));
370 int value = chooser.showSaveDialog(null);
372 if (value == JalviewFileChooser.APPROVE_OPTION)
374 String choice = chooser.getSelectedFile().getPath();
375 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
376 .getSelectedFile().getParent());
380 jalview.io.NewickFile fout = new jalview.io.NewickFile(
382 String output = fout.print(tree.hasBootstrap(),
383 tree.hasDistances(), tree.hasRootDistance());
384 java.io.PrintWriter out = new java.io.PrintWriter(
385 new java.io.FileWriter(choice));
388 } catch (Exception ex)
390 ex.printStackTrace();
402 public void printMenu_actionPerformed(ActionEvent e)
404 // Putting in a thread avoids Swing painting problems
405 treeCanvas.startPrinting();
409 public void originalSeqData_actionPerformed(ActionEvent e)
411 AlignmentView originalData = tree.getOriginalData();
412 if (originalData == null)
414 jalview.bin.Cache.log
415 .info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
418 // decide if av alignment is sufficiently different to original data to
419 // warrant a new window to be created
420 // create new alignmnt window with hidden regions (unhiding hidden regions
421 // yields unaligned seqs)
422 // or create a selection box around columns in alignment view
423 // test Alignment(SeqCigar[])
427 // we try to get the associated view's gap character
428 // but this may fail if the view was closed...
429 gc = av.getGapCharacter();
431 } catch (Exception ex)
435 Object[] alAndColsel = originalData.getAlignmentAndHiddenColumns(gc);
437 if (alAndColsel != null && alAndColsel[0] != null)
439 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
441 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
442 AlignmentI dataset = (av != null && av.getAlignment() != null) ? av
443 .getAlignment().getDataset() : null;
446 al.setDataset(dataset);
452 AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
453 AlignFrame.DEFAULT_WIDTH,
454 AlignFrame.DEFAULT_HEIGHT);
456 // >>>This is a fix for the moment, until a better solution is
458 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
460 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
463 Desktop.addInternalFrame(af, MessageManager.formatMessage(
464 "label.original_data_for_params",
465 new Object[] { this.title }), AlignFrame.DEFAULT_WIDTH,
466 AlignFrame.DEFAULT_HEIGHT);
478 public void fitToWindow_actionPerformed(ActionEvent e)
480 treeCanvas.fitToWindow = fitToWindow.isSelected();
485 * sort the associated alignment view by the current tree.
490 public void sortByTree_actionPerformed()
493 if (treeCanvas.applyToAllViews)
495 final ArrayList<CommandI> commands = new ArrayList<CommandI>();
496 for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
497 .getSequenceSetId()))
499 commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
501 av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
505 public void undoCommand(AlignmentI[] views)
507 for (CommandI tsort : commands)
509 tsort.undoCommand(views);
516 return commands.size();
520 public String getDescription()
522 return "Tree Sort (many views)";
526 public void doCommand(AlignmentI[] views)
529 for (CommandI tsort : commands)
531 tsort.doCommand(views);
535 for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
536 .getSequenceSetId()))
538 // ensure all the alignFrames refresh their GI after adding an undo item
539 ap.alignFrame.updateEditMenuBar();
544 treeCanvas.ap.alignFrame
545 .addHistoryItem(sortAlignmentIn(treeCanvas.ap));
550 public CommandI sortAlignmentIn(AlignmentPanel ap)
552 AlignmentViewport viewport = ap.av;
553 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
554 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
556 undo = new OrderCommand("Tree Sort", oldOrder, viewport.getAlignment());
558 ap.paintAlignment(true);
569 public void font_actionPerformed(ActionEvent e)
571 if (treeCanvas == null)
576 new FontChooser(this);
579 public Font getTreeFont()
581 return treeCanvas.font;
584 public void setTreeFont(Font f)
586 if (treeCanvas != null)
588 treeCanvas.setFont(f);
599 public void distanceMenu_actionPerformed(ActionEvent e)
601 treeCanvas.setShowDistances(distanceMenu.isSelected());
611 public void bootstrapMenu_actionPerformed(ActionEvent e)
613 treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
623 public void placeholdersMenu_actionPerformed(ActionEvent e)
625 treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
635 public void epsTree_actionPerformed(ActionEvent e)
637 boolean accurateText = true;
639 String renderStyle = jalview.bin.Cache.getDefault("EPS_RENDERING",
642 // If we need to prompt, and if the GUI is visible then
643 // Prompt for EPS rendering style
644 if (renderStyle.equalsIgnoreCase("Prompt each time")
645 && !(System.getProperty("java.awt.headless") != null && System
646 .getProperty("java.awt.headless").equals("true")))
648 EPSOptions eps = new EPSOptions();
649 renderStyle = eps.getValue();
651 if (renderStyle == null || eps.cancelled)
658 if (renderStyle.equalsIgnoreCase("text"))
660 accurateText = false;
663 int width = treeCanvas.getWidth();
664 int height = treeCanvas.getHeight();
668 JalviewFileChooser chooser = new JalviewFileChooser(
669 ImageMaker.EPS_EXTENSION, ImageMaker.EPS_EXTENSION);
670 chooser.setFileView(new JalviewFileView());
671 chooser.setDialogTitle(MessageManager
672 .getString("label.create_eps_from_tree"));
673 chooser.setToolTipText(MessageManager.getString("action.save"));
675 int value = chooser.showSaveDialog(this);
677 if (value != JalviewFileChooser.APPROVE_OPTION)
682 Cache.setProperty("LAST_DIRECTORY", chooser.getSelectedFile()
685 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
686 EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width, height);
688 pg.setAccurateTextMode(accurateText);
690 treeCanvas.draw(pg, width, height);
694 } catch (Exception ex)
696 ex.printStackTrace();
707 public void pngTree_actionPerformed(ActionEvent e)
709 int width = treeCanvas.getWidth();
710 int height = treeCanvas.getHeight();
714 JalviewFileChooser chooser = new JalviewFileChooser(
715 ImageMaker.PNG_EXTENSION, ImageMaker.PNG_DESCRIPTION);
717 chooser.setFileView(new jalview.io.JalviewFileView());
718 chooser.setDialogTitle(MessageManager
719 .getString("label.create_png_from_tree"));
720 chooser.setToolTipText(MessageManager.getString("action.save"));
722 int value = chooser.showSaveDialog(this);
724 if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
729 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
730 .getSelectedFile().getParent());
732 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
734 BufferedImage bi = new BufferedImage(width, height,
735 BufferedImage.TYPE_INT_RGB);
736 Graphics png = bi.getGraphics();
738 treeCanvas.draw(png, width, height);
740 ImageIO.write(bi, "png", out);
742 } catch (Exception ex)
744 ex.printStackTrace();
749 * change node labels to the annotation referred to by labelClass TODO:
750 * promote to a datamodel modification that can be undone TODO: make argument
751 * one case of a generic transformation function ie { undoStep = apply(Tree,
752 * TransformFunction)};
756 public void changeNames(final String labelClass)
758 tree.applyToNodes(new NodeTransformI()
762 public void transform(BinaryNode node)
764 if (node instanceof SequenceNode
765 && !((SequenceNode) node).isPlaceholder()
766 && !((SequenceNode) node).isDummy())
768 String newname = null;
769 SequenceI sq = (SequenceI) ((SequenceNode) node).element();
772 // search dbrefs, features and annotation
773 DBRefEntry[] refs = jalview.util.DBRefUtils.selectRefs(
775 new String[] { labelClass.toUpperCase() });
778 for (int i = 0; i < refs.length; i++)
782 newname = new String(refs[i].getAccessionId());
786 newname = newname + "; " + refs[i].getAccessionId();
792 List<SequenceFeature> features = sq.getFeatures()
793 .getPositionalFeatures(labelClass);
794 for (SequenceFeature feature : features)
798 newname = feature.getDescription();
802 newname = newname + "; " + feature.getDescription();
809 // String oldname = ((SequenceNode) node).getName();
810 // TODO : save oldname in the undo object for this modification.
811 ((SequenceNode) node).setName(newname);
819 * Formats a localised title for the tree panel, like
821 * Neighbour Joining Using BLOSUM62
823 * For a tree loaded from file, just uses the file name
826 public String getPanelTitle()
828 if (treeTitle != null)
834 * i18n description of Neighbour Joining or Average Distance method
836 String treecalcnm = MessageManager.getString("label.tree_calc_"
837 + treeType.toLowerCase());
840 * short score model name (long description can be too long)
842 String smn = scoreModelName;
845 * put them together as <method> Using <model>
847 final String ttl = MessageManager.formatMessage("label.treecalc_title",