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 java.util.Locale;
25 import jalview.analysis.AlignmentSorter;
26 import jalview.analysis.AverageDistanceTree;
27 import jalview.analysis.NJTree;
28 import jalview.analysis.TreeBuilder;
29 import jalview.analysis.TreeModel;
30 import jalview.analysis.scoremodels.ScoreModels;
31 import jalview.api.analysis.ScoreModelI;
32 import jalview.api.analysis.SimilarityParamsI;
33 import jalview.bin.Cache;
34 import jalview.bin.Console;
35 import jalview.commands.CommandI;
36 import jalview.commands.OrderCommand;
37 import jalview.datamodel.Alignment;
38 import jalview.datamodel.AlignmentI;
39 import jalview.datamodel.AlignmentView;
40 import jalview.datamodel.BinaryNode;
41 import jalview.datamodel.DBRefEntry;
42 import jalview.datamodel.HiddenColumns;
43 import jalview.datamodel.NodeTransformI;
44 import jalview.datamodel.SequenceFeature;
45 import jalview.datamodel.SequenceI;
46 import jalview.datamodel.SequenceNode;
47 import jalview.gui.ImageExporter.ImageWriterI;
48 import jalview.io.JalviewFileChooser;
49 import jalview.io.JalviewFileView;
50 import jalview.io.NewickFile;
51 import jalview.jbgui.GTreePanel;
52 import jalview.util.ImageMaker.TYPE;
53 import jalview.util.MessageManager;
54 import jalview.viewmodel.AlignmentViewport;
57 import java.awt.Graphics;
58 import java.awt.event.ActionEvent;
59 import java.awt.event.ActionListener;
60 import java.beans.PropertyChangeEvent;
61 import java.beans.PropertyChangeListener;
63 import java.io.FileOutputStream;
64 import java.util.ArrayList;
65 import java.util.List;
67 import javax.swing.ButtonGroup;
68 import javax.swing.JMenuItem;
69 import javax.swing.JRadioButtonMenuItem;
70 import javax.swing.event.InternalFrameAdapter;
71 import javax.swing.event.InternalFrameEvent;
73 import org.jibble.epsgraphics.EpsGraphics2D;
81 public class TreePanel extends GTreePanel
85 String scoreModelName; // if tree computed
87 String treeTitle; // if tree loaded
89 SimilarityParamsI similarityParams;
91 private TreeCanvas treeCanvas;
95 private AlignViewport av;
98 * Creates a new TreePanel object.
105 public TreePanel(AlignmentPanel ap, String type, String modelName,
106 SimilarityParamsI options)
109 this.similarityParams = options;
110 initTreePanel(ap, type, modelName, null, null);
112 // We know this tree has distances. JBPNote TODO: prolly should add this as
113 // a userdefined default
114 // showDistances(true);
117 public TreePanel(AlignmentPanel alignPanel, NewickFile newtree,
118 String theTitle, AlignmentView inputData)
121 this.treeTitle = theTitle;
122 initTreePanel(alignPanel, null, null, newtree, inputData);
125 public AlignmentI getAlignment()
127 return getTreeCanvas().getViewport().getAlignment();
130 public AlignmentViewport getViewPort()
132 // @Mungo - Why don't we return our own viewport ???
133 return getTreeCanvas().getViewport();
136 void initTreePanel(AlignmentPanel ap, String type, String modelName,
137 NewickFile newTree, AlignmentView inputData)
141 this.treeType = type;
142 this.scoreModelName = modelName;
144 treeCanvas = new TreeCanvas(this, ap, scrollPane);
145 scrollPane.setViewportView(treeCanvas);
147 PaintRefresher.Register(this, ap.av.getSequenceSetId());
149 buildAssociatedViewMenu();
151 final PropertyChangeListener listener = addAlignmentListener();
154 * remove listener when window is closed, so that this
155 * panel can be garbage collected
157 addInternalFrameListener(new InternalFrameAdapter()
160 public void internalFrameClosed(InternalFrameEvent evt)
164 av.removePropertyChangeListener(listener);
170 TreeLoader tl = new TreeLoader(newTree, inputData);
176 * Ensure any potentially large object references are nulled
178 public void releaseReferences()
181 this.treeCanvas.tree = null;
182 this.treeCanvas.nodeHash = null;
183 this.treeCanvas.nameHash = null;
189 protected PropertyChangeListener addAlignmentListener()
191 final PropertyChangeListener listener = new PropertyChangeListener()
193 @SuppressWarnings("unchecked")
195 public void propertyChange(PropertyChangeEvent evt)
197 switch (evt.getPropertyName()) {
198 case AlignmentViewport.PROPERTY_ALIGNMENT:
201 System.out.println("tree is null");
202 // TODO: deal with case when a change event is received whilst a
203 // tree is still being calculated - should save reference for
204 // processing message later.
207 if (evt.getNewValue() == null)
210 "new alignment sequences vector value is null");
214 tree.updatePlaceHolders((List<SequenceI>) evt.getNewValue());
215 treeCanvas.nameHash.clear(); // reset the mapping between canvas
216 // rectangles and leafnodes
222 av.addPropertyChangeListener(listener);
227 public void viewMenu_menuSelected()
229 buildAssociatedViewMenu();
232 void buildAssociatedViewMenu()
234 AlignmentPanel[] aps = PaintRefresher
235 .getAssociatedPanels(av.getSequenceSetId());
236 if (aps.length == 1 && getTreeCanvas().getAssociatedPanel() == aps[0])
238 associateLeavesMenu.setVisible(false);
242 associateLeavesMenu.setVisible(true);
245 .getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
247 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
250 associateLeavesMenu.removeAll();
252 JRadioButtonMenuItem item;
253 ButtonGroup buttonGroup = new ButtonGroup();
254 int i, iSize = aps.length;
255 final TreePanel thisTreePanel = this;
256 for (i = 0; i < iSize; i++)
258 final AlignmentPanel ap = aps[i];
259 item = new JRadioButtonMenuItem(ap.av.getViewName(),
260 ap == treeCanvas.getAssociatedPanel());
261 buttonGroup.add(item);
262 item.addActionListener(new ActionListener()
265 public void actionPerformed(ActionEvent evt)
267 treeCanvas.applyToAllViews = false;
268 treeCanvas.setAssociatedPanel(ap);
269 treeCanvas.setViewport(ap.av);
270 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
274 associateLeavesMenu.add(item);
277 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
278 MessageManager.getString("label.all_views"));
279 buttonGroup.add(itemf);
280 itemf.setSelected(treeCanvas.applyToAllViews);
281 itemf.addActionListener(new ActionListener()
284 public void actionPerformed(ActionEvent evt)
286 treeCanvas.applyToAllViews = itemf.isSelected();
289 associateLeavesMenu.add(itemf);
293 class TreeLoader extends Thread
295 private NewickFile newtree;
297 private AlignmentView odata = null;
299 public TreeLoader(NewickFile newickFile, AlignmentView inputData)
301 this.newtree = newickFile;
302 this.odata = inputData;
304 if (newickFile != null)
306 // Must be outside run(), as Jalview2XML tries to
307 // update distance/bootstrap visibility at the same time
308 showBootstrap(newickFile.HasBootstrap());
309 showDistances(newickFile.HasDistances());
319 tree = new TreeModel(av.getAlignment().getSequencesArray(), odata,
321 if (tree.getOriginalData() == null)
323 originalSeqData.setVisible(false);
328 ScoreModelI sm = ScoreModels.getInstance().getScoreModel(
329 scoreModelName, treeCanvas.getAssociatedPanel());
330 TreeBuilder njtree = treeType.equals(TreeBuilder.NEIGHBOUR_JOINING)
331 ? new NJTree(av, sm, similarityParams)
332 : new AverageDistanceTree(av, sm, similarityParams);
333 tree = new TreeModel(njtree);
337 tree.reCount(tree.getTopNode());
338 tree.findHeight(tree.getTopNode());
339 treeCanvas.setTree(tree);
340 treeCanvas.repaint();
341 av.setCurrentTree(tree);
342 if (av.getSortByTree())
344 sortByTree_actionPerformed();
349 public void showDistances(boolean b)
351 treeCanvas.setShowDistances(b);
352 distanceMenu.setSelected(b);
355 public void showBootstrap(boolean b)
357 treeCanvas.setShowBootstrap(b);
358 bootstrapMenu.setSelected(b);
361 public void showPlaceholders(boolean b)
363 placeholdersMenu.setState(b);
364 treeCanvas.setMarkPlaceholders(b);
370 * @return DOCUMENT ME!
372 public TreeModel getTree()
384 public void textbox_actionPerformed(ActionEvent e)
386 CutAndPasteTransfer cap = new CutAndPasteTransfer();
388 String newTitle = getPanelTitle();
390 NewickFile fout = new NewickFile(tree.getTopNode());
393 cap.setText(fout.print(tree.hasBootstrap(), tree.hasDistances(),
394 tree.hasRootDistance()));
395 Desktop.addInternalFrame(cap, newTitle, 500, 100);
396 } catch (OutOfMemoryError oom)
398 new OOMWarning("generating newick tree file", oom);
411 public void saveAsNewick_actionPerformed(ActionEvent e)
413 // TODO: JAL-3048 save newick file for Jalview-JS
414 JalviewFileChooser chooser = new JalviewFileChooser(
415 Cache.getProperty("LAST_DIRECTORY"));
416 chooser.setFileView(new JalviewFileView());
417 chooser.setDialogTitle(
418 MessageManager.getString("label.save_tree_as_newick"));
419 chooser.setToolTipText(MessageManager.getString("action.save"));
421 int value = chooser.showSaveDialog(null);
423 if (value == JalviewFileChooser.APPROVE_OPTION)
425 String choice = chooser.getSelectedFile().getPath();
426 Cache.setProperty("LAST_DIRECTORY",
427 chooser.getSelectedFile().getParent());
431 jalview.io.NewickFile fout = new jalview.io.NewickFile(
433 String output = fout.print(tree.hasBootstrap(), tree.hasDistances(),
434 tree.hasRootDistance());
435 java.io.PrintWriter out = new java.io.PrintWriter(
436 new java.io.FileWriter(choice));
439 } catch (Exception ex)
441 ex.printStackTrace();
453 public void printMenu_actionPerformed(ActionEvent e)
455 // Putting in a thread avoids Swing painting problems
456 treeCanvas.startPrinting();
460 public void originalSeqData_actionPerformed(ActionEvent e)
462 AlignmentView originalData = tree.getOriginalData();
463 if (originalData == null)
466 "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
469 // decide if av alignment is sufficiently different to original data to
470 // warrant a new window to be created
471 // create new alignmnt window with hidden regions (unhiding hidden regions
472 // yields unaligned seqs)
473 // or create a selection box around columns in alignment view
474 // test Alignment(SeqCigar[])
478 // we try to get the associated view's gap character
479 // but this may fail if the view was closed...
480 gc = av.getGapCharacter();
482 } catch (Exception ex)
486 Object[] alAndColsel = originalData.getAlignmentAndHiddenColumns(gc);
488 if (alAndColsel != null && alAndColsel[0] != null)
490 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
492 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
493 AlignmentI dataset = (av != null && av.getAlignment() != null)
494 ? av.getAlignment().getDataset()
498 al.setDataset(dataset);
504 AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
505 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
507 // >>>This is a fix for the moment, until a better solution is
509 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
511 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
514 Desktop.addInternalFrame(af, MessageManager.formatMessage(
515 "label.original_data_for_params", new Object[]
516 { this.title }), AlignFrame.DEFAULT_WIDTH,
517 AlignFrame.DEFAULT_HEIGHT);
529 public void fitToWindow_actionPerformed(ActionEvent e)
531 treeCanvas.fitToWindow = fitToWindow.isSelected();
536 * sort the associated alignment view by the current tree.
541 public void sortByTree_actionPerformed()
544 if (treeCanvas.applyToAllViews)
546 final ArrayList<CommandI> commands = new ArrayList<>();
547 for (AlignmentPanel ap : PaintRefresher
548 .getAssociatedPanels(av.getSequenceSetId()))
550 commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
552 av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
556 public void undoCommand(AlignmentI[] views)
558 for (CommandI tsort : commands)
560 tsort.undoCommand(views);
567 return commands.size();
571 public String getDescription()
573 return "Tree Sort (many views)";
577 public void doCommand(AlignmentI[] views)
580 for (CommandI tsort : commands)
582 tsort.doCommand(views);
586 for (AlignmentPanel ap : PaintRefresher
587 .getAssociatedPanels(av.getSequenceSetId()))
589 // ensure all the alignFrames refresh their GI after adding an undo item
590 ap.alignFrame.updateEditMenuBar();
595 treeCanvas.getAssociatedPanel().alignFrame.addHistoryItem(
596 sortAlignmentIn(treeCanvas.getAssociatedPanel()));
601 public CommandI sortAlignmentIn(AlignmentPanel ap)
603 // TODO: move to alignment view controller
604 AlignmentViewport viewport = ap.av;
605 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
606 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
608 undo = new OrderCommand("Tree Sort", oldOrder, viewport.getAlignment());
610 ap.paintAlignment(true, false);
621 public void font_actionPerformed(ActionEvent e)
623 if (treeCanvas == null)
628 new FontChooser(this);
631 public Font getTreeFont()
633 return treeCanvas.font;
636 public void setTreeFont(Font f)
638 if (treeCanvas != null)
640 treeCanvas.setFont(f);
651 public void distanceMenu_actionPerformed(ActionEvent e)
653 treeCanvas.setShowDistances(distanceMenu.isSelected());
663 public void bootstrapMenu_actionPerformed(ActionEvent e)
665 treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
675 public void placeholdersMenu_actionPerformed(ActionEvent e)
677 treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
681 * Outputs the Tree in image format (currently EPS or PNG). The user is
682 * prompted for the file to save to, and for EPS (unless a preference is
683 * already set) for the choice of Text or Lineart for character rendering.
686 public void writeTreeImage(TYPE imageFormat)
688 int width = treeCanvas.getWidth();
689 int height = treeCanvas.getHeight();
690 ImageWriterI writer = new ImageWriterI()
693 public void exportImage(Graphics g) throws Exception
695 treeCanvas.draw(g, width, height);
698 String tree = MessageManager.getString("label.tree");
699 ImageExporter exporter = new ImageExporter(writer, null, imageFormat,
701 exporter.doExport(null, this, width, height,
702 tree.toLowerCase(Locale.ROOT));
706 * change node labels to the annotation referred to by labelClass TODO:
707 * promote to a datamodel modification that can be undone TODO: make argument
708 * one case of a generic transformation function ie { undoStep = apply(Tree,
709 * TransformFunction)};
713 public void changeNames(final String labelClass)
715 tree.applyToNodes(new NodeTransformI()
719 public void transform(BinaryNode node)
721 if (node instanceof SequenceNode
722 && !((SequenceNode) node).isPlaceholder()
723 && !((SequenceNode) node).isDummy())
725 String newname = null;
726 SequenceI sq = (SequenceI) ((SequenceNode) node).element();
729 // search dbrefs, features and annotation
730 List<DBRefEntry> refs = jalview.util.DBRefUtils
731 .selectRefs(sq.getDBRefs(), new String[]
732 { labelClass.toUpperCase(Locale.ROOT) });
735 for (int i = 0, ni = refs.size(); i < ni; i++)
739 newname = new String(refs.get(i).getAccessionId());
743 newname += "; " + refs.get(i).getAccessionId();
749 List<SequenceFeature> features = sq.getFeatures()
750 .getPositionalFeatures(labelClass);
751 for (SequenceFeature feature : features)
755 newname = feature.getDescription();
759 newname = newname + "; " + feature.getDescription();
766 // String oldname = ((SequenceNode) node).getName();
767 // TODO : save oldname in the undo object for this modification.
768 ((SequenceNode) node).setName(newname);
776 * Formats a localised title for the tree panel, like
778 * Neighbour Joining Using BLOSUM62
780 * For a tree loaded from file, just uses the file name
784 public String getPanelTitle()
786 if (treeTitle != null)
792 * i18n description of Neighbour Joining or Average Distance method
794 String treecalcnm = MessageManager.getString(
795 "label.tree_calc_" + treeType.toLowerCase(Locale.ROOT));
798 * short score model name (long description can be too long)
800 String smn = scoreModelName;
803 * put them together as <method> Using <model>
805 final String ttl = MessageManager.formatMessage("label.calc_title",
811 * Builds an EPS image and writes it to the specified file.
815 * true for Text character rendering, false for Lineart
817 protected void writeEpsFile(File outFile, boolean textOption)
821 int width = treeCanvas.getWidth();
822 int height = treeCanvas.getHeight();
824 FileOutputStream out = new FileOutputStream(outFile);
825 EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width,
827 pg.setAccurateTextMode(!textOption);
828 treeCanvas.draw(pg, width, height);
832 } catch (Exception ex)
834 System.err.println("Error writing tree as EPS");
835 ex.printStackTrace();
839 public AlignViewport getViewport()
844 public void setViewport(AlignViewport av)
849 public TreeCanvas getTreeCanvas()