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.TreeModel;
27 import jalview.api.analysis.SimilarityParamsI;
28 import jalview.bin.Cache;
29 import jalview.bin.Console;
30 import jalview.commands.CommandI;
31 import jalview.commands.OrderCommand;
32 import jalview.datamodel.Alignment;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.AlignmentView;
35 import jalview.datamodel.BinaryNode;
36 import jalview.datamodel.DBRefEntry;
37 import jalview.datamodel.HiddenColumns;
38 import jalview.datamodel.NodeTransformI;
39 import jalview.datamodel.SequenceFeature;
40 import jalview.datamodel.SequenceI;
41 import jalview.datamodel.SequenceNode;
42 import jalview.gui.ImageExporter.ImageWriterI;
43 import jalview.io.JalviewFileChooser;
44 import jalview.io.JalviewFileView;
45 import jalview.io.NewickFile;
46 import jalview.jbgui.GTreePanel;
47 import jalview.util.ImageMaker.TYPE;
48 import jalview.util.MessageManager;
49 import jalview.viewmodel.AlignmentViewport;
52 import java.awt.Graphics;
53 import java.awt.event.ActionEvent;
54 import java.awt.event.ActionListener;
55 import java.beans.PropertyChangeEvent;
56 import java.beans.PropertyChangeListener;
58 import java.io.FileOutputStream;
59 import java.util.ArrayList;
60 import java.util.List;
62 import javax.swing.ButtonGroup;
63 import javax.swing.JMenuItem;
64 import javax.swing.JRadioButtonMenuItem;
66 import org.jibble.epsgraphics.EpsGraphics2D;
74 public class TreePanel extends GTreePanel
76 String substitutionMatrix;
80 String treeTitle; // if tree loaded
82 SimilarityParamsI similarityParams;
84 TreeCanvas treeCanvas;
88 private AlignViewport av;
91 * Creates a new TreePanel object.
96 * @param substitutionMatrix
98 public TreePanel(AlignmentPanel ap, TreeModel tree, String treeType,
99 String substitutionMatrix)
102 this.treeType = treeType;
103 this.substitutionMatrix = substitutionMatrix;
105 initTreePanel(ap, tree);
107 // We know this tree has distances. JBPNote TODO: prolly should add this as
108 // a userdefined default
109 // showDistances(true);
113 * Creates a new TreePanel object.
120 public TreePanel(AlignmentPanel alignPanel, NewickFile newtree,
121 String theTitle, AlignmentView inputData)
124 this.treeTitle = theTitle;
125 initTreePanel(alignPanel, newtree, inputData);
128 public AlignmentI getAlignment()
130 return getTreeCanvas().getViewport().getAlignment();
133 public AlignmentViewport getViewPort()
135 // @Mungo - Why don't we return our own viewport ???
136 return getTreeCanvas().getViewport();
140 * Initialize a tree panel based on a calculated tree
145 void initTreePanel(AlignmentPanel ap, TreeModel tree)
149 TreeLoader tl = new TreeLoader(null, null);
155 * Initialize a tree panel based on a loaded in tree file.
161 void initTreePanel(AlignmentPanel ap,
162 NewickFile loadedTree, AlignmentView inputData)
166 TreeLoader tl = new TreeLoader(loadedTree, inputData);
170 public void buildTreeCanvas(AlignmentPanel ap) {
173 treeCanvas = new TreeCanvas(this, ap, scrollPane);
174 scrollPane.setViewportView(treeCanvas);
177 PaintRefresher.Register(this, ap.av.getSequenceSetId());
179 buildAssociatedViewMenu();
181 av.addPropertyChangeListener(new java.beans.PropertyChangeListener()
184 public void propertyChange(PropertyChangeEvent evt)
186 if (evt.getPropertyName().equals("alignment"))
190 System.out.println("tree is null");
191 // TODO: deal with case when a change event is received whilst a
192 // tree is still being calculated - should save reference for
193 // processing message later.
196 if (evt.getNewValue() == null)
199 "new alignment sequences vector value is null");
202 tree.updatePlaceHolders((List<SequenceI>) evt.getNewValue());
203 treeCanvas.nameHash.clear(); // reset the mapping between canvas
204 // rectangles and leafnodes
216 public void viewMenu_menuSelected()
218 buildAssociatedViewMenu();
221 void buildAssociatedViewMenu()
223 AlignmentPanel[] aps = PaintRefresher
224 .getAssociatedPanels(av.getSequenceSetId());
225 if (aps.length == 1 && getTreeCanvas().getAssociatedPanel() == aps[0])
227 associateLeavesMenu.setVisible(false);
231 associateLeavesMenu.setVisible(true);
234 .getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
236 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
239 associateLeavesMenu.removeAll();
241 JRadioButtonMenuItem item;
242 ButtonGroup buttonGroup = new ButtonGroup();
243 int i, iSize = aps.length;
244 final TreePanel thisTreePanel = this;
245 for (i = 0; i < iSize; i++)
247 final AlignmentPanel ap = aps[i];
248 item = new JRadioButtonMenuItem(ap.av.getViewName(),
249 ap == treeCanvas.getAssociatedPanel());
250 buttonGroup.add(item);
251 item.addActionListener(new ActionListener()
254 public void actionPerformed(ActionEvent evt)
256 treeCanvas.applyToAllViews = false;
257 treeCanvas.setAssociatedPanel(ap);
258 treeCanvas.setViewport(ap.av);
259 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
263 associateLeavesMenu.add(item);
266 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
267 MessageManager.getString("label.all_views"));
268 buttonGroup.add(itemf);
269 itemf.setSelected(treeCanvas.applyToAllViews);
270 itemf.addActionListener(new ActionListener()
273 public void actionPerformed(ActionEvent evt)
275 treeCanvas.applyToAllViews = itemf.isSelected();
278 associateLeavesMenu.add(itemf);
282 class TreeLoader extends Thread
284 private NewickFile newTree;
286 private AlignmentView odata = null;
288 public TreeLoader(NewickFile newickFile, AlignmentView inputData)
290 this.newTree = newickFile;
291 this.odata = inputData;
295 // Must be outside run(), as Jalview2XML tries to
296 // update distance/bootstrap visibility at the same time
297 showBootstrap(newTree.hasBootstrap());
298 showDistances(newTree.hasDistances());
310 tree = new TreeModel(av.getAlignment().getSequencesArray(), odata,
312 if (tree.getOriginalData() == null)
314 originalSeqData.setVisible(false);
321 public void showTree(TreeModel tree)
323 tree.reCount(tree.getTopNode());
324 tree.findHeight(tree.getTopNode());
325 treeCanvas.setTree(tree);
326 treeCanvas.repaint();
328 av.setCurrentTree(tree);
329 if (av.getSortByTree())
331 sortByTree_actionPerformed();
337 public void showDistances(boolean b)
339 treeCanvas.setShowDistances(b);
340 distanceMenu.setSelected(b);
343 public void showBootstrap(boolean b)
345 treeCanvas.setShowBootstrap(b);
346 bootstrapMenu.setSelected(b);
349 public void showPlaceholders(boolean b)
351 placeholdersMenu.setState(b);
352 treeCanvas.setMarkPlaceholders(b);
358 * @return DOCUMENT ME!
360 public TreeModel getTree()
372 public void textbox_actionPerformed(ActionEvent e)
374 CutAndPasteTransfer cap = new CutAndPasteTransfer();
376 String newTitle = getPanelTitle();
378 NewickFile fout = new NewickFile(tree.getTopNode());
381 cap.setText(fout.print(tree.hasBootstrap(), tree.hasDistances(),
382 tree.hasRootDistance()));
383 Desktop.addInternalFrame(cap, newTitle, 500, 100);
384 } catch (OutOfMemoryError oom)
386 new OOMWarning("generating newick tree file", oom);
399 public void saveAsNewick_actionPerformed(ActionEvent e)
401 // TODO: JAL-3048 save newick file for Jalview-JS
402 JalviewFileChooser chooser = new JalviewFileChooser(
403 Cache.getProperty("LAST_DIRECTORY"));
404 chooser.setFileView(new JalviewFileView());
405 chooser.setDialogTitle(
406 MessageManager.getString("label.save_tree_as_newick"));
407 chooser.setToolTipText(MessageManager.getString("action.save"));
409 int value = chooser.showSaveDialog(null);
411 if (value == JalviewFileChooser.APPROVE_OPTION)
413 String choice = chooser.getSelectedFile().getPath();
414 Cache.setProperty("LAST_DIRECTORY",
415 chooser.getSelectedFile().getParent());
419 jalview.io.NewickFile fout = new jalview.io.NewickFile(
421 String output = fout.print(tree.hasBootstrap(), tree.hasDistances(),
422 tree.hasRootDistance());
423 java.io.PrintWriter out = new java.io.PrintWriter(
424 new java.io.FileWriter(choice));
427 } catch (Exception ex)
429 ex.printStackTrace();
441 public void printMenu_actionPerformed(ActionEvent e)
443 // Putting in a thread avoids Swing painting problems
444 treeCanvas.startPrinting();
448 public void originalSeqData_actionPerformed(ActionEvent e)
450 AlignmentView originalData = tree.getOriginalData();
451 if (originalData == null)
454 "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
457 // decide if av alignment is sufficiently different to original data to
458 // warrant a new window to be created
459 // create new alignmnt window with hidden regions (unhiding hidden regions
460 // yields unaligned seqs)
461 // or create a selection box around columns in alignment view
462 // test Alignment(SeqCigar[])
466 // we try to get the associated view's gap character
467 // but this may fail if the view was closed...
468 gc = av.getGapCharacter();
470 } catch (Exception ex)
474 Object[] alAndColsel = originalData.getAlignmentAndHiddenColumns(gc);
476 if (alAndColsel != null && alAndColsel[0] != null)
478 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
480 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
481 AlignmentI dataset = (av != null && av.getAlignment() != null)
482 ? av.getAlignment().getDataset()
486 al.setDataset(dataset);
492 AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
493 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
495 // >>>This is a fix for the moment, until a better solution is
497 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
499 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
502 Desktop.addInternalFrame(af, MessageManager.formatMessage(
503 "label.original_data_for_params", new Object[]
504 { this.title }), AlignFrame.DEFAULT_WIDTH,
505 AlignFrame.DEFAULT_HEIGHT);
517 public void fitToWindow_actionPerformed(ActionEvent e)
519 treeCanvas.fitToWindow = fitToWindow.isSelected();
524 * sort the associated alignment view by the current tree.
529 public void sortByTree_actionPerformed()// modify for Aptx
532 if (treeCanvas.applyToAllViews)
534 final ArrayList<CommandI> commands = new ArrayList<>();
535 for (AlignmentPanel ap : PaintRefresher
536 .getAssociatedPanels(av.getSequenceSetId()))
538 commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
540 av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
544 public void undoCommand(AlignmentI[] views)
546 for (CommandI tsort : commands)
548 tsort.undoCommand(views);
555 return commands.size();
559 public String getDescription()
561 return "Tree Sort (many views)";
565 public void doCommand(AlignmentI[] views)
568 for (CommandI tsort : commands)
570 tsort.doCommand(views);
574 for (AlignmentPanel ap : PaintRefresher
575 .getAssociatedPanels(av.getSequenceSetId()))
577 // ensure all the alignFrames refresh their GI after adding an undo item
578 ap.alignFrame.updateEditMenuBar();
583 treeCanvas.getAssociatedPanel().alignFrame.addHistoryItem(
584 sortAlignmentIn(treeCanvas.getAssociatedPanel()));
589 public CommandI sortAlignmentIn(AlignmentPanel ap)
591 // TODO: move to alignment view controller
592 AlignmentViewport viewport = ap.av;
593 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
594 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
596 undo = new OrderCommand("Tree Sort", oldOrder, viewport.getAlignment());
598 ap.paintAlignment(true, false);
609 public void font_actionPerformed(ActionEvent e)
611 if (treeCanvas == null)
616 new FontChooser(this);
619 public Font getTreeFont()
621 return treeCanvas.font;
624 public void setTreeFont(Font f)
626 if (treeCanvas != null)
628 treeCanvas.setFont(f);
639 public void distanceMenu_actionPerformed(ActionEvent e)
641 treeCanvas.setShowDistances(distanceMenu.isSelected());
651 public void bootstrapMenu_actionPerformed(ActionEvent e)
653 treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
663 public void placeholdersMenu_actionPerformed(ActionEvent e)
665 treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
669 * Outputs the Tree in image format (currently EPS or PNG). The user is
670 * prompted for the file to save to, and for EPS (unless a preference is
671 * already set) for the choice of Text or Lineart for character rendering.
674 public void writeTreeImage(TYPE imageFormat)
676 int width = treeCanvas.getWidth();
677 int height = treeCanvas.getHeight();
678 ImageWriterI writer = new ImageWriterI()
681 public void exportImage(Graphics g) throws Exception
683 treeCanvas.draw(g, width, height);
686 String tree = MessageManager.getString("label.tree");
687 ImageExporter exporter = new ImageExporter(writer, null, imageFormat,
689 exporter.doExport(null, this, width, height,
690 tree.toLowerCase(Locale.ROOT));
694 * change node labels to the annotation referred to by labelClass TODO:
695 * promote to a datamodel modification that can be undone TODO: make argument
696 * one case of a generic transformation function ie { undoStep = apply(Tree,
697 * TransformFunction)};
701 public void changeNames(final String labelClass)
703 tree.applyToNodes(new NodeTransformI()
707 public void transform(BinaryNode node)
709 if (node instanceof SequenceNode
710 && !((SequenceNode) node).isPlaceholder()
711 && !((SequenceNode) node).isDummy())
713 String newname = null;
714 SequenceI sq = (SequenceI) ((SequenceNode) node).element();
717 // search dbrefs, features and annotation
718 List<DBRefEntry> refs = jalview.util.DBRefUtils
719 .selectRefs(sq.getDBRefs(), new String[]
720 { labelClass.toUpperCase(Locale.ROOT) });
723 for (int i = 0, ni = refs.size(); i < ni; i++)
727 newname = new String(refs.get(i).getAccessionId());
731 newname += "; " + refs.get(i).getAccessionId();
737 List<SequenceFeature> features = sq.getFeatures()
738 .getPositionalFeatures(labelClass);
739 for (SequenceFeature feature : features)
743 newname = feature.getDescription();
747 newname = newname + "; " + feature.getDescription();
754 // String oldname = ((SequenceNode) node).getName();
755 // TODO : save oldname in the undo object for this modification.
756 ((SequenceNode) node).setName(newname);
764 * Formats a localised title for the tree panel, like
766 * Neighbour Joining Using BLOSUM62
768 * For a tree loaded from file, just uses the file name
772 public String getPanelTitle() // to be moved/fixed
774 if (treeTitle != null)
781 * i18n description of Neighbour Joining or Average Distance method
783 String treecalcnm = MessageManager.getString(
784 "label.tree_calc_" + treeType.toLowerCase(Locale.ROOT));
787 * short score model name (long description can be too long)
789 String smn = substitutionMatrix;
792 * put them together as <method> Using <model>
794 final String ttl = MessageManager.formatMessage("label.calc_title",
801 * Builds an EPS image and writes it to the specified file.
805 * true for Text character rendering, false for Lineart
807 protected void writeEpsFile(File outFile, boolean textOption)
811 int width = treeCanvas.getWidth();
812 int height = treeCanvas.getHeight();
814 FileOutputStream out = new FileOutputStream(outFile);
815 EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width,
817 pg.setAccurateTextMode(!textOption);
818 treeCanvas.draw(pg, width, height);
822 } catch (Exception ex)
824 System.err.println("Error writing tree as EPS");
825 ex.printStackTrace();
829 public AlignViewport getViewport()
834 public void setViewport(AlignViewport av)
839 public TreeCanvas getTreeCanvas()