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.
24 import java.awt.Graphics;
25 import java.awt.event.ActionEvent;
26 import java.awt.event.ActionListener;
27 import java.awt.event.KeyAdapter;
28 import java.awt.event.KeyEvent;
29 import java.beans.PropertyChangeEvent;
30 import java.beans.PropertyChangeListener;
32 import java.io.FileOutputStream;
33 import java.util.ArrayList;
34 import java.util.List;
35 import java.util.Locale;
37 import javax.swing.ButtonGroup;
38 import javax.swing.JMenuItem;
39 import javax.swing.JRadioButtonMenuItem;
40 import javax.swing.event.InternalFrameAdapter;
41 import javax.swing.event.InternalFrameEvent;
43 import org.jibble.epsgraphics.EpsGraphics2D;
45 import jalview.analysis.AlignmentSorter;
46 import jalview.analysis.AverageDistanceTree;
47 import jalview.analysis.NJTree;
48 import jalview.analysis.TreeBuilder;
49 import jalview.analysis.TreeModel;
50 import jalview.analysis.scoremodels.ScoreModels;
51 import jalview.api.analysis.ScoreModelI;
52 import jalview.api.analysis.SimilarityParamsI;
53 import jalview.bin.Cache;
54 import jalview.bin.Console;
55 import jalview.commands.CommandI;
56 import jalview.commands.OrderCommand;
57 import jalview.datamodel.Alignment;
58 import jalview.datamodel.AlignmentAnnotation;
59 import jalview.datamodel.AlignmentI;
60 import jalview.datamodel.AlignmentView;
61 import jalview.datamodel.BinaryNode;
62 import jalview.datamodel.DBRefEntry;
63 import jalview.datamodel.HiddenColumns;
64 import jalview.datamodel.NodeTransformI;
65 import jalview.datamodel.SequenceFeature;
66 import jalview.datamodel.SequenceI;
67 import jalview.datamodel.SequenceNode;
68 import jalview.gui.ImageExporter.ImageWriterI;
69 import jalview.io.JalviewFileChooser;
70 import jalview.io.JalviewFileView;
71 import jalview.io.NewickFile;
72 import jalview.io.exceptions.ImageOutputException;
73 import jalview.jbgui.GTreePanel;
74 import jalview.util.ImageMaker.TYPE;
75 import jalview.util.MessageManager;
76 import jalview.viewmodel.AlignmentViewport;
84 public class TreePanel extends GTreePanel
88 String scoreModelName; // if tree computed
90 String treeTitle; // if tree loaded
92 SimilarityParamsI similarityParams;
94 private TreeCanvas treeCanvas;
98 private AlignViewport av;
101 * Creates a new TreePanel object.
108 public TreePanel(AlignmentPanel ap, String type, String modelName,
109 SimilarityParamsI options)
112 this.setFrameIcon(null);
113 this.similarityParams = options;
114 initTreePanel(ap, type, modelName, null, null);
116 // We know this tree has distances. JBPNote TODO: prolly should add this as
117 // a userdefined default
118 // showDistances(true);
121 public TreePanel(AlignmentPanel alignPanel, NewickFile newtree,
122 String theTitle, AlignmentView inputData)
125 this.setFrameIcon(null);
126 this.treeTitle = theTitle;
127 initTreePanel(alignPanel, null, null, newtree, inputData);
131 * columnwise tree associated with positions in aa
138 public TreePanel(AlignmentPanel alignPanel, NewickFile fin,
139 AlignmentAnnotation aa, String title)
143 assocAnnotation = aa;
144 this.setFrameIcon(null);
145 this.treeTitle = title;
146 initTreePanel(alignPanel, null, null, fin, null);
149 boolean columnWise = false;
151 AlignmentAnnotation assocAnnotation = null;
153 public boolean isColumnWise()
158 public AlignmentAnnotation getAssocAnnotation()
160 return assocAnnotation;
163 public AlignmentI getAlignment()
165 return getTreeCanvas().getViewport().getAlignment();
168 public AlignmentViewport getViewPort()
170 // @Mungo - Why don't we return our own viewport ???
171 return getTreeCanvas().getViewport();
174 void initTreePanel(AlignmentPanel ap, String type, String modelName,
175 NewickFile newTree, AlignmentView inputData)
179 this.treeType = type;
180 this.scoreModelName = modelName;
182 treeCanvas = new TreeCanvas(this, ap, scrollPane);
183 scrollPane.setViewportView(treeCanvas);
187 bootstrapMenu.setVisible(false);
188 placeholdersMenu.setState(false);
189 placeholdersMenu.setVisible(false);
190 fitToWindow.setState(false);
191 sortAssocViews.setVisible(false);
194 addKeyListener(new KeyAdapter()
197 public void keyPressed(KeyEvent e)
199 switch (e.getKeyCode())
202 treeCanvas.clearSelectedLeaves();
210 PaintRefresher.Register(this, ap.av.getSequenceSetId());
212 buildAssociatedViewMenu();
214 final PropertyChangeListener listener = addAlignmentListener();
217 * remove listener when window is closed, so that this
218 * panel can be garbage collected
220 addInternalFrameListener(new InternalFrameAdapter()
223 public void internalFrameClosed(InternalFrameEvent evt)
227 av.removePropertyChangeListener(listener);
233 TreeLoader tl = new TreeLoader(newTree, inputData);
239 * Ensure any potentially large object references are nulled
241 public void releaseReferences()
244 this.treeCanvas.tree = null;
245 this.treeCanvas.nodeHash = null;
246 this.treeCanvas.nameHash = null;
252 protected PropertyChangeListener addAlignmentListener()
254 final PropertyChangeListener listener = new PropertyChangeListener()
257 public void propertyChange(PropertyChangeEvent evt)
259 if (evt.getPropertyName().equals("alignment"))
263 jalview.bin.Console.outPrintln("tree is null");
264 // TODO: deal with case when a change event is received whilst a
265 // tree is still being calculated - should save reference for
266 // processing message later.
269 if (evt.getNewValue() == null)
271 jalview.bin.Console.outPrintln(
272 "new alignment sequences vector value is null");
275 tree.updatePlaceHolders((List<SequenceI>) evt.getNewValue());
276 treeCanvas.nameHash.clear(); // reset the mapping between canvas
277 // rectangles and leafnodes
282 av.addPropertyChangeListener(listener);
287 public void viewMenu_menuSelected()
289 buildAssociatedViewMenu();
292 void buildAssociatedViewMenu()
294 AlignmentPanel[] aps = PaintRefresher
295 .getAssociatedPanels(av.getSequenceSetId());
296 if (aps.length == 1 && getTreeCanvas().getAssociatedPanel() == aps[0])
298 associateLeavesMenu.setVisible(false);
302 associateLeavesMenu.setVisible(true);
305 .getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
307 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
310 associateLeavesMenu.removeAll();
312 JRadioButtonMenuItem item;
313 ButtonGroup buttonGroup = new ButtonGroup();
314 int i, iSize = aps.length;
315 final TreePanel thisTreePanel = this;
316 for (i = 0; i < iSize; i++)
318 final AlignmentPanel ap = aps[i];
319 item = new JRadioButtonMenuItem(ap.av.getViewName(),
320 ap == treeCanvas.getAssociatedPanel());
321 buttonGroup.add(item);
322 item.addActionListener(new ActionListener()
325 public void actionPerformed(ActionEvent evt)
327 treeCanvas.applyToAllViews = false;
328 treeCanvas.setAssociatedPanel(ap);
329 treeCanvas.setViewport(ap.av);
330 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
334 associateLeavesMenu.add(item);
337 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
338 MessageManager.getString("label.all_views"));
339 buttonGroup.add(itemf);
340 itemf.setSelected(treeCanvas.applyToAllViews);
341 itemf.addActionListener(new ActionListener()
344 public void actionPerformed(ActionEvent evt)
346 treeCanvas.applyToAllViews = itemf.isSelected();
349 associateLeavesMenu.add(itemf);
353 class TreeLoader extends Thread
355 private NewickFile newtree;
357 private AlignmentView odata = null;
359 public TreeLoader(NewickFile newickFile, AlignmentView inputData)
361 this.newtree = newickFile;
362 this.odata = inputData;
364 if (newickFile != null)
366 // Must be outside run(), as Jalview2XML tries to
367 // update distance/bootstrap visibility at the same time
368 showBootstrap(newickFile.HasBootstrap());
369 showDistances(newickFile.HasDistances());
379 tree = new TreeModel(av.getAlignment().getSequencesArray(), odata,
381 if (tree.getOriginalData() == null)
383 originalSeqData.setVisible(false);
388 ScoreModelI sm = ScoreModels.getInstance().getScoreModel(
389 scoreModelName, treeCanvas.getAssociatedPanel());
390 TreeBuilder njtree = treeType.equals(TreeBuilder.NEIGHBOUR_JOINING)
391 ? new NJTree(av, sm, similarityParams)
392 : new AverageDistanceTree(av, sm, similarityParams);
393 tree = new TreeModel(njtree);
394 // don't display distances for columnwise trees
396 showDistances(!columnWise);
397 tree.reCount(tree.getTopNode());
398 tree.findHeight(tree.getTopNode());
399 treeCanvas.setTree(tree);
400 treeCanvas.repaint();
401 av.setCurrentTree(tree);
402 if (av.getSortByTree())
404 sortByTree_actionPerformed();
409 public void showDistances(boolean b)
411 treeCanvas.setShowDistances(b);
412 distanceMenu.setSelected(b);
415 public void showBootstrap(boolean b)
417 treeCanvas.setShowBootstrap(b);
418 bootstrapMenu.setSelected(b);
421 public void showPlaceholders(boolean b)
423 placeholdersMenu.setState(b);
424 treeCanvas.setMarkPlaceholders(b);
430 * @return DOCUMENT ME!
432 public TreeModel getTree()
444 public void textbox_actionPerformed(ActionEvent e)
446 CutAndPasteTransfer cap = new CutAndPasteTransfer();
448 String newTitle = getPanelTitle();
450 NewickFile fout = new NewickFile(tree.getTopNode());
453 cap.setText(fout.print(tree.hasBootstrap(), tree.hasDistances(),
454 tree.hasRootDistance()));
455 Desktop.addInternalFrame(cap, newTitle, 500, 100);
456 } catch (OutOfMemoryError oom)
458 new OOMWarning("generating newick tree file", oom);
471 public void saveAsNewick_actionPerformed(ActionEvent e)
473 // TODO: JAL-3048 save newick file for Jalview-JS
474 JalviewFileChooser chooser = new JalviewFileChooser(
475 Cache.getProperty("LAST_DIRECTORY"));
476 chooser.setFileView(new JalviewFileView());
477 chooser.setDialogTitle(
478 MessageManager.getString("label.save_tree_as_newick"));
479 chooser.setToolTipText(MessageManager.getString("action.save"));
481 int value = chooser.showSaveDialog(null);
483 if (value == JalviewFileChooser.APPROVE_OPTION)
485 String choice = chooser.getSelectedFile().getPath();
486 Cache.setProperty("LAST_DIRECTORY",
487 chooser.getSelectedFile().getParent());
491 jalview.io.NewickFile fout = new jalview.io.NewickFile(
493 String output = fout.print(tree.hasBootstrap(), tree.hasDistances(),
494 tree.hasRootDistance());
495 java.io.PrintWriter out = new java.io.PrintWriter(
496 new java.io.FileWriter(choice));
499 } catch (Exception ex)
501 ex.printStackTrace();
513 public void printMenu_actionPerformed(ActionEvent e)
515 // Putting in a thread avoids Swing painting problems
516 treeCanvas.startPrinting();
520 public void originalSeqData_actionPerformed(ActionEvent e)
522 AlignmentView originalData = tree.getOriginalData();
523 if (originalData == null)
526 "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
529 // decide if av alignment is sufficiently different to original data to
530 // warrant a new window to be created
531 // create new alignmnt window with hidden regions (unhiding hidden regions
532 // yields unaligned seqs)
533 // or create a selection box around columns in alignment view
534 // test Alignment(SeqCigar[])
538 // we try to get the associated view's gap character
539 // but this may fail if the view was closed...
540 gc = av.getGapCharacter();
542 } catch (Exception ex)
546 Object[] alAndColsel = originalData.getAlignmentAndHiddenColumns(gc);
548 if (alAndColsel != null && alAndColsel[0] != null)
550 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
552 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
553 AlignmentI dataset = (av != null && av.getAlignment() != null)
554 ? av.getAlignment().getDataset()
558 al.setDataset(dataset);
564 AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
565 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
567 // >>>This is a fix for the moment, until a better solution is
569 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
571 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
574 Desktop.addInternalFrame(af, MessageManager.formatMessage(
575 "label.original_data_for_params", new Object[]
576 { this.title }), AlignFrame.DEFAULT_WIDTH,
577 AlignFrame.DEFAULT_HEIGHT);
589 public void fitToWindow_actionPerformed(ActionEvent e)
591 treeCanvas.fitToWindow = fitToWindow.isSelected();
596 * sort the associated alignment view by the current tree.
601 public void sortByTree_actionPerformed()
604 if (treeCanvas.applyToAllViews)
606 final ArrayList<CommandI> commands = new ArrayList<>();
607 for (AlignmentPanel ap : PaintRefresher
608 .getAssociatedPanels(av.getSequenceSetId()))
610 commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
612 av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
616 public void undoCommand(AlignmentI[] views)
618 for (CommandI tsort : commands)
620 tsort.undoCommand(views);
627 return commands.size();
631 public String getDescription()
633 return "Tree Sort (many views)";
637 public void doCommand(AlignmentI[] views)
640 for (CommandI tsort : commands)
642 tsort.doCommand(views);
646 for (AlignmentPanel ap : PaintRefresher
647 .getAssociatedPanels(av.getSequenceSetId()))
649 // ensure all the alignFrames refresh their GI after adding an undo item
650 ap.alignFrame.updateEditMenuBar();
655 treeCanvas.getAssociatedPanel().alignFrame.addHistoryItem(
656 sortAlignmentIn(treeCanvas.getAssociatedPanel()));
661 public CommandI sortAlignmentIn(AlignmentPanel ap)
663 // TODO: move to alignment view controller
664 AlignmentViewport viewport = ap.av;
665 SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
666 AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
668 undo = new OrderCommand("Tree Sort", oldOrder, viewport.getAlignment());
670 ap.paintAlignment(true, false);
681 public void font_actionPerformed(ActionEvent e)
683 if (treeCanvas == null)
688 new FontChooser(this);
691 public Font getTreeFont()
693 return treeCanvas.font;
696 public void setTreeFont(Font f)
698 if (treeCanvas != null)
700 treeCanvas.setFont(f);
711 public void distanceMenu_actionPerformed(ActionEvent e)
713 treeCanvas.setShowDistances(distanceMenu.isSelected());
723 public void bootstrapMenu_actionPerformed(ActionEvent e)
725 treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
735 public void placeholdersMenu_actionPerformed(ActionEvent e)
737 treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
741 * Outputs the Tree in image format (currently EPS or PNG). The user is
742 * prompted for the file to save to, and for EPS (unless a preference is
743 * already set) for the choice of Text or Lineart for character rendering.
746 public void writeTreeImage(TYPE imageFormat)
748 int width = treeCanvas.getWidth();
749 int height = treeCanvas.getHeight();
750 ImageWriterI writer = new ImageWriterI()
753 public void exportImage(Graphics g) throws Exception
755 treeCanvas.draw(g, width, height);
758 String tree = MessageManager.getString("label.tree");
759 ImageExporter exporter = new ImageExporter(writer, null, imageFormat,
763 exporter.doExport(null, this, width, height,
764 tree.toLowerCase(Locale.ROOT));
765 } catch (ImageOutputException ioex)
768 "Unexpected error whilst writing " + imageFormat.toString(),
774 * change node labels to the annotation referred to by labelClass TODO:
775 * promote to a datamodel modification that can be undone TODO: make argument
776 * one case of a generic transformation function ie { undoStep = apply(Tree,
777 * TransformFunction)};
781 public void changeNames(final String labelClass)
783 tree.applyToNodes(new NodeTransformI()
787 public void transform(BinaryNode node)
789 if (node instanceof SequenceNode
790 && !((SequenceNode) node).isPlaceholder()
791 && !((SequenceNode) node).isDummy())
793 String newname = null;
794 SequenceI sq = (SequenceI) ((BinaryNode) node).element();
797 // search dbrefs, features and annotation
798 List<DBRefEntry> refs = jalview.util.DBRefUtils
799 .selectRefs(sq.getDBRefs(), new String[]
800 { labelClass.toUpperCase(Locale.ROOT) });
803 for (int i = 0, ni = refs.size(); i < ni; i++)
807 newname = new String(refs.get(i).getAccessionId());
811 newname += "; " + refs.get(i).getAccessionId();
817 List<SequenceFeature> features = sq.getFeatures()
818 .getPositionalFeatures(labelClass);
819 for (SequenceFeature feature : features)
823 newname = feature.getDescription();
827 newname = newname + "; " + feature.getDescription();
834 // String oldname = ((SequenceNode) node).getName();
835 // TODO : save oldname in the undo object for this modification.
836 ((BinaryNode) node).setName(newname);
844 * Formats a localised title for the tree panel, like
846 * Neighbour Joining Using BLOSUM62
848 * For a tree loaded from file, just uses the file name
852 public String getPanelTitle()
854 if (treeTitle != null)
860 * i18n description of Neighbour Joining or Average Distance method
862 String treecalcnm = MessageManager.getString(
863 "label.tree_calc_" + treeType.toLowerCase(Locale.ROOT));
866 * short score model name (long description can be too long)
868 String smn = scoreModelName;
871 * put them together as <method> Using <model>
873 final String ttl = MessageManager.formatMessage("label.calc_title",
879 * Builds an EPS image and writes it to the specified file.
883 * true for Text character rendering, false for Lineart
885 protected void writeEpsFile(File outFile, boolean textOption)
889 int width = treeCanvas.getWidth();
890 int height = treeCanvas.getHeight();
892 FileOutputStream out = new FileOutputStream(outFile);
893 EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width,
895 pg.setAccurateTextMode(!textOption);
896 treeCanvas.draw(pg, width, height);
900 } catch (Exception ex)
902 jalview.bin.Console.errPrintln("Error writing tree as EPS");
903 ex.printStackTrace();
907 public AlignViewport getViewport()
912 public void setViewport(AlignViewport av)
917 public TreeCanvas getTreeCanvas()