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.commands.CommandI;
34 import jalview.commands.OrderCommand;
35 import jalview.datamodel.Alignment;
36 import jalview.datamodel.AlignmentI;
37 import jalview.datamodel.AlignmentView;
38 import jalview.datamodel.BinaryNode;
39 import jalview.datamodel.DBRefEntry;
40 import jalview.datamodel.HiddenColumns;
41 import jalview.datamodel.NodeTransformI;
42 import jalview.datamodel.SequenceFeature;
43 import jalview.datamodel.SequenceI;
44 import jalview.datamodel.SequenceNode;
45 import jalview.gui.ImageExporter.ImageWriterI;
46 import jalview.io.JalviewFileChooser;
47 import jalview.io.JalviewFileView;
48 import jalview.io.NewickFile;
49 import jalview.jbgui.GTreePanel;
50 import jalview.util.ImageMaker.TYPE;
51 import jalview.util.MessageManager;
52 import jalview.viewmodel.AlignmentViewport;
55 import java.awt.Graphics;
56 import java.awt.event.ActionEvent;
57 import java.awt.event.ActionListener;
58 import java.beans.PropertyChangeEvent;
59 import java.beans.PropertyChangeListener;
61 import java.io.FileOutputStream;
62 import java.util.ArrayList;
63 import java.util.List;
65 import javax.swing.ButtonGroup;
66 import javax.swing.JMenuItem;
67 import javax.swing.JRadioButtonMenuItem;
68 import javax.swing.event.InternalFrameAdapter;
69 import javax.swing.event.InternalFrameEvent;
71 import org.jibble.epsgraphics.EpsGraphics2D;
79 public class TreePanel extends GTreePanel
83 String scoreModelName; // if tree computed
85 String treeTitle; // if tree loaded
87 SimilarityParamsI similarityParams;
89 private TreeCanvas treeCanvas;
93 private AlignViewport av;
96 * Creates a new TreePanel object.
103 public TreePanel(AlignmentPanel ap, String type, String modelName,
104 SimilarityParamsI options)
107 this.similarityParams = options;
108 initTreePanel(ap, type, modelName, null, null);
110 // We know this tree has distances. JBPNote TODO: prolly should add this as
111 // a userdefined default
112 // showDistances(true);
115 public TreePanel(AlignmentPanel alignPanel, NewickFile newtree,
116 String theTitle, AlignmentView inputData)
119 this.treeTitle = theTitle;
120 initTreePanel(alignPanel, null, null, newtree, inputData);
123 public AlignmentI getAlignment()
125 return getTreeCanvas().getViewport().getAlignment();
128 public AlignmentViewport getViewPort()
130 // @Mungo - Why don't we return our own viewport ???
131 return getTreeCanvas().getViewport();
134 void initTreePanel(AlignmentPanel ap, String type, String modelName,
135 NewickFile newTree, AlignmentView inputData)
139 this.treeType = type;
140 this.scoreModelName = modelName;
142 treeCanvas = new TreeCanvas(this, ap, scrollPane);
143 scrollPane.setViewportView(treeCanvas);
145 PaintRefresher.Register(this, ap.av.getSequenceSetId());
147 buildAssociatedViewMenu();
149 final PropertyChangeListener listener = addAlignmentListener();
152 * remove listener when window is closed, so that this
153 * panel can be garbage collected
155 addInternalFrameListener(new InternalFrameAdapter()
158 public void internalFrameClosed(InternalFrameEvent evt)
162 av.removePropertyChangeListener(listener);
168 TreeLoader tl = new TreeLoader(newTree, inputData);
174 * Ensure any potentially large object references are nulled
176 public void releaseReferences()
179 this.treeCanvas.tree = null;
180 this.treeCanvas.nodeHash = null;
181 this.treeCanvas.nameHash = null;
187 protected PropertyChangeListener addAlignmentListener()
189 final PropertyChangeListener listener = new PropertyChangeListener()
191 @SuppressWarnings("unchecked")
193 public void propertyChange(PropertyChangeEvent evt)
195 switch (evt.getPropertyName()) {
196 case AlignmentViewport.PROPERTY_ALIGNMENT:
199 System.out.println("tree is null");
200 // TODO: deal with case when a change event is received whilst a
201 // tree is still being calculated - should save reference for
202 // processing message later.
205 if (evt.getNewValue() == null)
208 "new alignment sequences vector value is null");
212 tree.updatePlaceHolders((List<SequenceI>) evt.getNewValue());
213 treeCanvas.nameHash.clear(); // reset the mapping between canvas
214 // rectangles and leafnodes
220 av.addPropertyChangeListener(listener);
225 public void viewMenu_menuSelected()
227 buildAssociatedViewMenu();
230 void buildAssociatedViewMenu()
232 AlignmentPanel[] aps = PaintRefresher
233 .getAssociatedPanels(av.getSequenceSetId());
234 if (aps.length == 1 && getTreeCanvas().getAssociatedPanel() == aps[0])
236 associateLeavesMenu.setVisible(false);
240 associateLeavesMenu.setVisible(true);
243 .getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
245 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
248 associateLeavesMenu.removeAll();
250 JRadioButtonMenuItem item;
251 ButtonGroup buttonGroup = new ButtonGroup();
252 int i, iSize = aps.length;
253 final TreePanel thisTreePanel = this;
254 for (i = 0; i < iSize; i++)
256 final AlignmentPanel ap = aps[i];
257 item = new JRadioButtonMenuItem(ap.av.getViewName(),
258 ap == treeCanvas.getAssociatedPanel());
259 buttonGroup.add(item);
260 item.addActionListener(new ActionListener()
263 public void actionPerformed(ActionEvent evt)
265 treeCanvas.applyToAllViews = false;
266 treeCanvas.setAssociatedPanel(ap);
267 treeCanvas.setViewport(ap.av);
268 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
272 associateLeavesMenu.add(item);
275 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
276 MessageManager.getString("label.all_views"));
277 buttonGroup.add(itemf);
278 itemf.setSelected(treeCanvas.applyToAllViews);
279 itemf.addActionListener(new ActionListener()
282 public void actionPerformed(ActionEvent evt)
284 treeCanvas.applyToAllViews = itemf.isSelected();
287 associateLeavesMenu.add(itemf);
291 class TreeLoader extends Thread
293 private NewickFile newtree;
295 private AlignmentView odata = null;
297 public TreeLoader(NewickFile newickFile, AlignmentView inputData)
299 this.newtree = newickFile;
300 this.odata = inputData;
302 if (newickFile != null)
304 // Must be outside run(), as Jalview2XML tries to
305 // update distance/bootstrap visibility at the same time
306 showBootstrap(newickFile.HasBootstrap());
307 showDistances(newickFile.HasDistances());
317 tree = new TreeModel(av.getAlignment().getSequencesArray(), odata,
319 if (tree.getOriginalData() == null)
321 originalSeqData.setVisible(false);
326 ScoreModelI sm = ScoreModels.getInstance()
327 .getScoreModel(scoreModelName,
328 treeCanvas.getAssociatedPanel());
329 TreeBuilder njtree = treeType.equals(TreeBuilder.NEIGHBOUR_JOINING)
330 ? new NJTree(av, sm, similarityParams)
331 : new AverageDistanceTree(av, sm, similarityParams);
332 tree = new TreeModel(njtree);
336 tree.reCount(tree.getTopNode());
337 tree.findHeight(tree.getTopNode());
338 treeCanvas.setTree(tree);
339 treeCanvas.repaint();
340 av.setCurrentTree(tree);
341 if (av.getSortByTree())
343 sortByTree_actionPerformed();
348 public void showDistances(boolean b)
350 treeCanvas.setShowDistances(b);
351 distanceMenu.setSelected(b);
354 public void showBootstrap(boolean b)
356 treeCanvas.setShowBootstrap(b);
357 bootstrapMenu.setSelected(b);
360 public void showPlaceholders(boolean b)
362 placeholdersMenu.setState(b);
363 treeCanvas.setMarkPlaceholders(b);
369 * @return DOCUMENT ME!
371 public TreeModel getTree()
383 public void textbox_actionPerformed(ActionEvent e)
385 CutAndPasteTransfer cap = new CutAndPasteTransfer();
387 String newTitle = getPanelTitle();
389 NewickFile fout = new NewickFile(tree.getTopNode());
392 cap.setText(fout.print(tree.hasBootstrap(), tree.hasDistances(),
393 tree.hasRootDistance()));
394 Desktop.addInternalFrame(cap, newTitle, 500, 100);
395 } catch (OutOfMemoryError oom)
397 new OOMWarning("generating newick tree file", oom);
410 public void saveAsNewick_actionPerformed(ActionEvent e)
412 // TODO: JAL-3048 save newick file for Jalview-JS
413 JalviewFileChooser chooser = new JalviewFileChooser(
414 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
415 chooser.setFileView(new JalviewFileView());
416 chooser.setDialogTitle(
417 MessageManager.getString("label.save_tree_as_newick"));
418 chooser.setToolTipText(MessageManager.getString("action.save"));
420 int value = chooser.showSaveDialog(null);
422 if (value == JalviewFileChooser.APPROVE_OPTION)
424 String choice = chooser.getSelectedFile().getPath();
425 jalview.bin.Cache.setProperty("LAST_DIRECTORY",
426 chooser.getSelectedFile().getParent());
430 jalview.io.NewickFile fout = new jalview.io.NewickFile(
432 String output = fout.print(tree.hasBootstrap(), tree.hasDistances(),
433 tree.hasRootDistance());
434 java.io.PrintWriter out = new java.io.PrintWriter(
435 new java.io.FileWriter(choice));
438 } catch (Exception ex)
440 ex.printStackTrace();
452 public void printMenu_actionPerformed(ActionEvent e)
454 // Putting in a thread avoids Swing painting problems
455 treeCanvas.startPrinting();
459 public void originalSeqData_actionPerformed(ActionEvent e)
461 AlignmentView originalData = tree.getOriginalData();
462 if (originalData == null)
464 jalview.bin.Cache.log.info(
465 "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
468 // decide if av alignment is sufficiently different to original data to
469 // warrant a new window to be created
470 // create new alignmnt window with hidden regions (unhiding hidden regions
471 // yields unaligned seqs)
472 // or create a selection box around columns in alignment view
473 // test Alignment(SeqCigar[])
477 // we try to get the associated view's gap character
478 // but this may fail if the view was closed...
479 gc = av.getGapCharacter();
481 } catch (Exception ex)
485 Object[] alAndColsel = originalData.getAlignmentAndHiddenColumns(gc);
487 if (alAndColsel != null && alAndColsel[0] != null)
489 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
491 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
492 AlignmentI dataset = (av != null && av.getAlignment() != null)
493 ? av.getAlignment().getDataset()
497 al.setDataset(dataset);
503 AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
504 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
506 // >>>This is a fix for the moment, until a better solution is
508 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
510 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
513 Desktop.addInternalFrame(af, MessageManager.formatMessage(
514 "label.original_data_for_params", new Object[]
515 { this.title }), AlignFrame.DEFAULT_WIDTH,
516 AlignFrame.DEFAULT_HEIGHT);
528 public void fitToWindow_actionPerformed(ActionEvent e)
530 treeCanvas.fitToWindow = fitToWindow.isSelected();
535 * sort the associated alignment view by the current tree.
540 public void sortByTree_actionPerformed()
543 if (treeCanvas.applyToAllViews)
545 final ArrayList<CommandI> commands = new ArrayList<>();
546 for (AlignmentPanel ap : PaintRefresher
547 .getAssociatedPanels(av.getSequenceSetId()))
549 commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
551 av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
555 public void undoCommand(AlignmentI[] views)
557 for (CommandI tsort : commands)
559 tsort.undoCommand(views);
566 return commands.size();
570 public String getDescription()
572 return "Tree Sort (many views)";
576 public void doCommand(AlignmentI[] views)
579 for (CommandI tsort : commands)
581 tsort.doCommand(views);
585 for (AlignmentPanel ap : PaintRefresher
586 .getAssociatedPanels(av.getSequenceSetId()))
588 // ensure all the alignFrames refresh their GI after adding an undo item
589 ap.alignFrame.updateEditMenuBar();
594 treeCanvas.getAssociatedPanel().alignFrame
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, tree.toLowerCase(Locale.ROOT));
705 * change node labels to the annotation referred to by labelClass TODO:
706 * promote to a datamodel modification that can be undone TODO: make argument
707 * one case of a generic transformation function ie { undoStep = apply(Tree,
708 * TransformFunction)};
712 public void changeNames(final String labelClass)
714 tree.applyToNodes(new NodeTransformI()
718 public void transform(BinaryNode node)
720 if (node instanceof SequenceNode
721 && !((SequenceNode) node).isPlaceholder()
722 && !((SequenceNode) node).isDummy())
724 String newname = null;
725 SequenceI sq = (SequenceI) ((SequenceNode) node).element();
728 // search dbrefs, features and annotation
729 List<DBRefEntry> refs = jalview.util.DBRefUtils
730 .selectRefs(sq.getDBRefs(), new String[]
731 { labelClass.toUpperCase(Locale.ROOT) });
734 for (int i = 0, ni = refs.size(); i < ni; i++)
738 newname = new String(refs.get(i).getAccessionId());
742 newname += "; " + refs.get(i).getAccessionId();
748 List<SequenceFeature> features = sq.getFeatures()
749 .getPositionalFeatures(labelClass);
750 for (SequenceFeature feature : features)
754 newname = feature.getDescription();
758 newname = newname + "; " + feature.getDescription();
765 // String oldname = ((SequenceNode) node).getName();
766 // TODO : save oldname in the undo object for this modification.
767 ((SequenceNode) node).setName(newname);
775 * Formats a localised title for the tree panel, like
777 * Neighbour Joining Using BLOSUM62
779 * For a tree loaded from file, just uses the file name
783 public String getPanelTitle()
785 if (treeTitle != null)
791 * i18n description of Neighbour Joining or Average Distance method
793 String treecalcnm = MessageManager
794 .getString("label.tree_calc_" + treeType.toLowerCase(Locale.ROOT));
797 * short score model name (long description can be too long)
799 String smn = scoreModelName;
802 * put them together as <method> Using <model>
804 final String ttl = MessageManager.formatMessage("label.calc_title",
810 * Builds an EPS image and writes it to the specified file.
814 * true for Text character rendering, false for Lineart
816 protected void writeEpsFile(File outFile, boolean textOption)
820 int width = treeCanvas.getWidth();
821 int height = treeCanvas.getHeight();
823 FileOutputStream out = new FileOutputStream(
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()