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.beans.PropertyChangeListener;
59 import java.io.FileOutputStream;
60 import java.util.ArrayList;
61 import java.util.List;
63 import javax.imageio.ImageIO;
64 import javax.swing.ButtonGroup;
65 import javax.swing.JMenuItem;
66 import javax.swing.JRadioButtonMenuItem;
67 import javax.swing.event.InternalFrameAdapter;
68 import javax.swing.event.InternalFrameEvent;
70 import org.jibble.epsgraphics.EpsGraphics2D;
78 public class TreePanel extends GTreePanel
82 String scoreModelName; // if tree computed
84 String treeTitle; // if tree loaded
86 SimilarityParamsI similarityParams;
88 TreeCanvas treeCanvas;
95 * Creates a new TreePanel object.
102 public TreePanel(AlignmentPanel ap, String type, String modelName,
103 SimilarityParamsI options)
106 this.similarityParams = options;
107 initTreePanel(ap, type, modelName, null, null);
109 // We know this tree has distances. JBPNote TODO: prolly should add this as
110 // a userdefined default
111 // showDistances(true);
114 public TreePanel(AlignmentPanel alignPanel, NewickFile newtree,
115 String theTitle, AlignmentView inputData)
118 this.treeTitle = theTitle;
119 initTreePanel(alignPanel, null, null, newtree, inputData);
122 public AlignmentI getAlignment()
124 return treeCanvas.av.getAlignment();
127 public AlignmentViewport getViewPort()
129 return treeCanvas.av;
132 void initTreePanel(AlignmentPanel ap, String type, String modelName,
133 NewickFile newTree, AlignmentView inputData)
137 this.treeType = type;
138 this.scoreModelName = modelName;
140 treeCanvas = new TreeCanvas(this, ap, scrollPane);
141 scrollPane.setViewportView(treeCanvas);
143 PaintRefresher.Register(this, ap.av.getSequenceSetId());
145 buildAssociatedViewMenu();
147 final PropertyChangeListener listener = addAlignmentListener();
150 * remove listener when window is closed, so that this
151 * panel can be garbage collected
153 addInternalFrameListener(new InternalFrameAdapter()
156 public void internalFrameClosed(InternalFrameEvent evt)
160 av.removePropertyChangeListener(listener);
165 TreeLoader tl = new TreeLoader(newTree, inputData);
173 protected PropertyChangeListener addAlignmentListener()
175 final PropertyChangeListener listener = new PropertyChangeListener()
178 public void propertyChange(PropertyChangeEvent evt)
180 if (evt.getPropertyName().equals("alignment"))
184 System.out.println("tree is null");
185 // TODO: deal with case when a change event is received whilst a
186 // tree is still being calculated - should save reference for
187 // processing message later.
190 if (evt.getNewValue() == null)
193 "new alignment sequences vector value is null");
196 tree.updatePlaceHolders((List<SequenceI>) evt.getNewValue());
197 treeCanvas.nameHash.clear(); // reset the mapping between canvas
198 // rectangles and leafnodes
203 av.addPropertyChangeListener(listener);
208 public void viewMenu_menuSelected()
210 buildAssociatedViewMenu();
213 void buildAssociatedViewMenu()
215 AlignmentPanel[] aps = PaintRefresher
216 .getAssociatedPanels(av.getSequenceSetId());
217 if (aps.length == 1 && treeCanvas.ap == aps[0])
219 associateLeavesMenu.setVisible(false);
223 associateLeavesMenu.setVisible(true);
226 .getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
228 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
231 associateLeavesMenu.removeAll();
233 JRadioButtonMenuItem item;
234 ButtonGroup buttonGroup = new ButtonGroup();
235 int i, iSize = aps.length;
236 final TreePanel thisTreePanel = this;
237 for (i = 0; i < iSize; i++)
239 final AlignmentPanel ap = aps[i];
240 item = new JRadioButtonMenuItem(ap.av.viewName, ap == treeCanvas.ap);
241 buttonGroup.add(item);
242 item.addActionListener(new ActionListener()
245 public void actionPerformed(ActionEvent evt)
247 treeCanvas.applyToAllViews = false;
249 treeCanvas.av = ap.av;
250 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
254 associateLeavesMenu.add(item);
257 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
258 MessageManager.getString("label.all_views"));
259 buttonGroup.add(itemf);
260 itemf.setSelected(treeCanvas.applyToAllViews);
261 itemf.addActionListener(new ActionListener()
264 public void actionPerformed(ActionEvent evt)
266 treeCanvas.applyToAllViews = itemf.isSelected();
269 associateLeavesMenu.add(itemf);
273 class TreeLoader extends Thread
275 private NewickFile newtree;
277 private AlignmentView odata = null;
279 public TreeLoader(NewickFile newickFile, AlignmentView inputData)
281 this.newtree = newickFile;
282 this.odata = inputData;
284 if (newickFile != null)
286 // Must be outside run(), as Jalview2XML tries to
287 // update distance/bootstrap visibility at the same time
288 showBootstrap(newickFile.HasBootstrap());
289 showDistances(newickFile.HasDistances());
299 tree = new TreeModel(av.getAlignment().getSequencesArray(), odata,
301 if (tree.getOriginalData() == null)
303 originalSeqData.setVisible(false);
308 ScoreModelI sm = ScoreModels.getInstance()
309 .getScoreModel(scoreModelName, treeCanvas.ap);
310 TreeBuilder njtree = treeType.equals(TreeBuilder.NEIGHBOUR_JOINING)
311 ? new NJTree(av, sm, similarityParams)
312 : new AverageDistanceTree(av, sm, similarityParams);
313 tree = new TreeModel(njtree);
317 tree.reCount(tree.getTopNode());
318 tree.findHeight(tree.getTopNode());
319 treeCanvas.setTree(tree);
320 treeCanvas.repaint();
321 av.setCurrentTree(tree);
322 if (av.getSortByTree())
324 sortByTree_actionPerformed();
329 public void showDistances(boolean b)
331 treeCanvas.setShowDistances(b);
332 distanceMenu.setSelected(b);
335 public void showBootstrap(boolean b)
337 treeCanvas.setShowBootstrap(b);
338 bootstrapMenu.setSelected(b);
341 public void showPlaceholders(boolean b)
343 placeholdersMenu.setState(b);
344 treeCanvas.setMarkPlaceholders(b);
350 * @return DOCUMENT ME!
352 public TreeModel getTree()
364 public void textbox_actionPerformed(ActionEvent e)
366 CutAndPasteTransfer cap = new CutAndPasteTransfer();
368 String newTitle = getPanelTitle();
370 NewickFile fout = new NewickFile(tree.getTopNode());
373 cap.setText(fout.print(tree.hasBootstrap(), tree.hasDistances(),
374 tree.hasRootDistance()));
375 Desktop.addInternalFrame(cap, newTitle, 500, 100);
376 } catch (OutOfMemoryError oom)
378 new OOMWarning("generating newick tree file", oom);
391 public void saveAsNewick_actionPerformed(ActionEvent e)
393 JalviewFileChooser chooser = new JalviewFileChooser(
394 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
395 chooser.setFileView(new JalviewFileView());
396 chooser.setDialogTitle(
397 MessageManager.getString("label.save_tree_as_newick"));
398 chooser.setToolTipText(MessageManager.getString("action.save"));
400 int value = chooser.showSaveDialog(null);
402 if (value == JalviewFileChooser.APPROVE_OPTION)
404 String choice = chooser.getSelectedFile().getPath();
405 jalview.bin.Cache.setProperty("LAST_DIRECTORY",
406 chooser.getSelectedFile().getParent());
410 jalview.io.NewickFile fout = new jalview.io.NewickFile(
412 String output = fout.print(tree.hasBootstrap(), tree.hasDistances(),
413 tree.hasRootDistance());
414 java.io.PrintWriter out = new java.io.PrintWriter(
415 new java.io.FileWriter(choice));
418 } catch (Exception ex)
420 ex.printStackTrace();
432 public void printMenu_actionPerformed(ActionEvent e)
434 // Putting in a thread avoids Swing painting problems
435 treeCanvas.startPrinting();
439 public void originalSeqData_actionPerformed(ActionEvent e)
441 AlignmentView originalData = tree.getOriginalData();
442 if (originalData == null)
444 jalview.bin.Cache.log.info(
445 "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
448 // decide if av alignment is sufficiently different to original data to
449 // warrant a new window to be created
450 // create new alignmnt window with hidden regions (unhiding hidden regions
451 // yields unaligned seqs)
452 // or create a selection box around columns in alignment view
453 // test Alignment(SeqCigar[])
457 // we try to get the associated view's gap character
458 // but this may fail if the view was closed...
459 gc = av.getGapCharacter();
461 } catch (Exception ex)
465 Object[] alAndColsel = originalData.getAlignmentAndHiddenColumns(gc);
467 if (alAndColsel != null && alAndColsel[0] != null)
469 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
471 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
472 AlignmentI dataset = (av != null && av.getAlignment() != null)
473 ? av.getAlignment().getDataset()
477 al.setDataset(dataset);
483 AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
484 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
486 // >>>This is a fix for the moment, until a better solution is
488 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
490 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
493 Desktop.addInternalFrame(af, MessageManager.formatMessage(
494 "label.original_data_for_params", new Object[]
495 { this.title }), AlignFrame.DEFAULT_WIDTH,
496 AlignFrame.DEFAULT_HEIGHT);
508 public void fitToWindow_actionPerformed(ActionEvent e)
510 treeCanvas.fitToWindow = fitToWindow.isSelected();
515 * sort the associated alignment view by the current tree.
520 public void sortByTree_actionPerformed()
523 if (treeCanvas.applyToAllViews)
525 final ArrayList<CommandI> commands = new ArrayList<>();
526 for (AlignmentPanel ap : PaintRefresher
527 .getAssociatedPanels(av.getSequenceSetId()))
529 commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
531 av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
535 public void undoCommand(AlignmentI[] views)
537 for (CommandI tsort : commands)
539 tsort.undoCommand(views);
546 return commands.size();
550 public String getDescription()
552 return "Tree Sort (many views)";
556 public void doCommand(AlignmentI[] views)
559 for (CommandI tsort : commands)
561 tsort.doCommand(views);
565 for (AlignmentPanel ap : PaintRefresher
566 .getAssociatedPanels(av.getSequenceSetId()))
568 // ensure all the alignFrames refresh their GI after adding an undo item
569 ap.alignFrame.updateEditMenuBar();
574 treeCanvas.ap.alignFrame
575 .addHistoryItem(sortAlignmentIn(treeCanvas.ap));
580 public CommandI sortAlignmentIn(AlignmentPanel ap)
582 // TODO: move to alignment view controller
583 AlignmentViewport viewport = ap.av;
584 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
585 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
587 undo = new OrderCommand("Tree Sort", oldOrder, viewport.getAlignment());
589 ap.paintAlignment(true, false);
600 public void font_actionPerformed(ActionEvent e)
602 if (treeCanvas == null)
607 new FontChooser(this);
610 public Font getTreeFont()
612 return treeCanvas.font;
615 public void setTreeFont(Font f)
617 if (treeCanvas != null)
619 treeCanvas.setFont(f);
630 public void distanceMenu_actionPerformed(ActionEvent e)
632 treeCanvas.setShowDistances(distanceMenu.isSelected());
642 public void bootstrapMenu_actionPerformed(ActionEvent e)
644 treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
654 public void placeholdersMenu_actionPerformed(ActionEvent e)
656 treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
666 public void epsTree_actionPerformed(ActionEvent e)
668 boolean accurateText = true;
670 String renderStyle = jalview.bin.Cache.getDefault("EPS_RENDERING",
673 // If we need to prompt, and if the GUI is visible then
674 // Prompt for EPS rendering style
675 if (renderStyle.equalsIgnoreCase("Prompt each time")
676 && !(System.getProperty("java.awt.headless") != null && System
677 .getProperty("java.awt.headless").equals("true")))
679 EPSOptions eps = new EPSOptions();
680 renderStyle = eps.getValue();
682 if (renderStyle == null || eps.cancelled)
689 if (renderStyle.equalsIgnoreCase("text"))
691 accurateText = false;
694 int width = treeCanvas.getWidth();
695 int height = treeCanvas.getHeight();
699 JalviewFileChooser chooser = new JalviewFileChooser(
700 ImageMaker.EPS_EXTENSION, ImageMaker.EPS_EXTENSION);
701 chooser.setFileView(new JalviewFileView());
702 chooser.setDialogTitle(
703 MessageManager.getString("label.create_eps_from_tree"));
704 chooser.setToolTipText(MessageManager.getString("action.save"));
706 int value = chooser.showSaveDialog(this);
708 if (value != JalviewFileChooser.APPROVE_OPTION)
713 Cache.setProperty("LAST_DIRECTORY",
714 chooser.getSelectedFile().getParent());
716 FileOutputStream out = new FileOutputStream(
717 chooser.getSelectedFile());
718 EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width,
721 pg.setAccurateTextMode(accurateText);
723 treeCanvas.draw(pg, width, height);
727 } catch (Exception ex)
729 ex.printStackTrace();
740 public void pngTree_actionPerformed(ActionEvent e)
742 int width = treeCanvas.getWidth();
743 int height = treeCanvas.getHeight();
747 JalviewFileChooser chooser = new JalviewFileChooser(
748 ImageMaker.PNG_EXTENSION, ImageMaker.PNG_DESCRIPTION);
750 chooser.setFileView(new jalview.io.JalviewFileView());
751 chooser.setDialogTitle(
752 MessageManager.getString("label.create_png_from_tree"));
753 chooser.setToolTipText(MessageManager.getString("action.save"));
755 int value = chooser.showSaveDialog(this);
757 if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
762 jalview.bin.Cache.setProperty("LAST_DIRECTORY",
763 chooser.getSelectedFile().getParent());
765 FileOutputStream out = new FileOutputStream(
766 chooser.getSelectedFile());
768 BufferedImage bi = new BufferedImage(width, height,
769 BufferedImage.TYPE_INT_RGB);
770 Graphics png = bi.getGraphics();
772 treeCanvas.draw(png, width, height);
774 ImageIO.write(bi, "png", out);
776 } catch (Exception ex)
778 ex.printStackTrace();
783 * change node labels to the annotation referred to by labelClass TODO:
784 * promote to a datamodel modification that can be undone TODO: make argument
785 * one case of a generic transformation function ie { undoStep = apply(Tree,
786 * TransformFunction)};
790 public void changeNames(final String labelClass)
792 tree.applyToNodes(new NodeTransformI()
796 public void transform(BinaryNode node)
798 if (node instanceof SequenceNode
799 && !((SequenceNode) node).isPlaceholder()
800 && !((SequenceNode) node).isDummy())
802 String newname = null;
803 SequenceI sq = (SequenceI) ((SequenceNode) node).element();
806 // search dbrefs, features and annotation
807 DBRefEntry[] refs = jalview.util.DBRefUtils
808 .selectRefs(sq.getDBRefs(), new String[]
809 { labelClass.toUpperCase() });
812 for (int i = 0; i < refs.length; i++)
816 newname = new String(refs[i].getAccessionId());
820 newname = newname + "; " + refs[i].getAccessionId();
826 List<SequenceFeature> features = sq.getFeatures()
827 .getPositionalFeatures(labelClass);
828 for (SequenceFeature feature : features)
832 newname = feature.getDescription();
836 newname = newname + "; " + feature.getDescription();
843 // String oldname = ((SequenceNode) node).getName();
844 // TODO : save oldname in the undo object for this modification.
845 ((SequenceNode) node).setName(newname);
853 * Formats a localised title for the tree panel, like
855 * Neighbour Joining Using BLOSUM62
857 * For a tree loaded from file, just uses the file name
861 public String getPanelTitle()
863 if (treeTitle != null)
869 * i18n description of Neighbour Joining or Average Distance method
871 String treecalcnm = MessageManager
872 .getString("label.tree_calc_" + treeType.toLowerCase());
875 * short score model name (long description can be too long)
877 String smn = scoreModelName;
880 * put them together as <method> Using <model>
882 final String ttl = MessageManager.formatMessage("label.treecalc_title",