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.NJTree;
25 import jalview.api.analysis.ScoreModelI;
26 import jalview.api.analysis.ViewBasedAnalysisI;
27 import jalview.bin.Cache;
28 import jalview.commands.CommandI;
29 import jalview.commands.OrderCommand;
30 import jalview.datamodel.Alignment;
31 import jalview.datamodel.AlignmentI;
32 import jalview.datamodel.AlignmentView;
33 import jalview.datamodel.BinaryNode;
34 import jalview.datamodel.ColumnSelection;
35 import jalview.datamodel.DBRefEntry;
36 import jalview.datamodel.NodeTransformI;
37 import jalview.datamodel.SequenceFeature;
38 import jalview.datamodel.SequenceI;
39 import jalview.datamodel.SequenceNode;
40 import jalview.io.JalviewFileChooser;
41 import jalview.io.JalviewFileView;
42 import jalview.io.NewickFile;
43 import jalview.jbgui.GTreePanel;
44 import jalview.schemes.ResidueProperties;
45 import jalview.util.MessageManager;
46 import jalview.viewmodel.AlignmentViewport;
49 import java.awt.Graphics;
50 import java.awt.event.ActionEvent;
51 import java.awt.event.ActionListener;
52 import java.awt.image.BufferedImage;
53 import java.beans.PropertyChangeEvent;
54 import java.io.FileOutputStream;
55 import java.util.ArrayList;
56 import java.util.List;
58 import javax.imageio.ImageIO;
59 import javax.swing.ButtonGroup;
60 import javax.swing.JMenuItem;
61 import javax.swing.JRadioButtonMenuItem;
63 import org.jibble.epsgraphics.EpsGraphics2D;
71 public class TreePanel extends GTreePanel
77 TreeCanvas treeCanvas;
84 * Creates a new TreePanel object.
99 public TreePanel(AlignmentPanel ap, String type, String pwtype)
102 initTreePanel(ap, type, pwtype, null, null);
104 // We know this tree has distances. JBPNote TODO: prolly should add this as
105 // a userdefined default
106 // showDistances(true);
110 * Creates a new TreePanel object.
123 public TreePanel(AlignmentPanel ap, String type, String pwtype,
127 initTreePanel(ap, type, pwtype, newtree, null);
130 public TreePanel(AlignmentPanel av, String type, String pwtype,
131 NewickFile newtree, AlignmentView inputData)
134 initTreePanel(av, type, pwtype, newtree, inputData);
137 public AlignmentI getAlignment()
139 return treeCanvas.av.getAlignment();
142 public AlignmentViewport getViewPort()
144 return treeCanvas.av;
147 void initTreePanel(AlignmentPanel ap, String type, String pwtype,
148 NewickFile newTree, AlignmentView inputData)
153 this.pwtype = pwtype;
155 treeCanvas = new TreeCanvas(this, ap, scrollPane);
156 scrollPane.setViewportView(treeCanvas);
158 PaintRefresher.Register(this, ap.av.getSequenceSetId());
160 buildAssociatedViewMenu();
162 av.addPropertyChangeListener(new java.beans.PropertyChangeListener()
165 public void propertyChange(PropertyChangeEvent evt)
167 if (evt.getPropertyName().equals("alignment"))
171 System.out.println("tree is null");
172 // TODO: deal with case when a change event is received whilst a
173 // tree is still being calculated - should save reference for
174 // processing message later.
177 if (evt.getNewValue() == null)
180 .println("new alignment sequences vector value is null");
183 tree.UpdatePlaceHolders((List<SequenceI>) evt.getNewValue());
184 treeCanvas.nameHash.clear(); // reset the mapping between canvas
185 // rectangles and leafnodes
191 TreeLoader tl = new TreeLoader(newTree);
192 if (inputData != null)
194 tl.odata = inputData;
201 public void viewMenu_menuSelected()
203 buildAssociatedViewMenu();
206 void buildAssociatedViewMenu()
208 AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av
209 .getSequenceSetId());
210 if (aps.length == 1 && treeCanvas.ap == aps[0])
212 associateLeavesMenu.setVisible(false);
216 associateLeavesMenu.setVisible(true);
218 if ((viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
220 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
223 associateLeavesMenu.removeAll();
225 JRadioButtonMenuItem item;
226 ButtonGroup buttonGroup = new ButtonGroup();
227 int i, iSize = aps.length;
228 final TreePanel thisTreePanel = this;
229 for (i = 0; i < iSize; i++)
231 final AlignmentPanel ap = aps[i];
232 item = new JRadioButtonMenuItem(ap.av.viewName, ap == treeCanvas.ap);
233 buttonGroup.add(item);
234 item.addActionListener(new ActionListener()
237 public void actionPerformed(ActionEvent evt)
239 treeCanvas.applyToAllViews = false;
241 treeCanvas.av = ap.av;
242 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
246 associateLeavesMenu.add(item);
249 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
250 MessageManager.getString("label.all_views"));
251 buttonGroup.add(itemf);
252 itemf.setSelected(treeCanvas.applyToAllViews);
253 itemf.addActionListener(new ActionListener()
256 public void actionPerformed(ActionEvent evt)
258 treeCanvas.applyToAllViews = itemf.isSelected();
261 associateLeavesMenu.add(itemf);
265 class TreeLoader extends Thread
269 jalview.datamodel.AlignmentView odata = null;
271 public TreeLoader(NewickFile newtree)
273 this.newtree = newtree;
276 // Must be outside run(), as Jalview2XML tries to
277 // update distance/bootstrap visibility at the same time
278 showBootstrap(newtree.HasBootstrap());
279 showDistances(newtree.HasDistances());
291 tree = new NJTree(av.getAlignment().getSequencesArray(), newtree);
295 tree = new NJTree(av.getAlignment().getSequencesArray(), odata,
298 if (!tree.hasOriginalSequenceData())
300 allowOriginalSeqData(false);
307 boolean selview = av.getSelectionGroup() != null
308 && av.getSelectionGroup().getSize() > 1;
309 AlignmentView seqStrings = av.getAlignmentView(selview);
313 end = av.getAlignment().getWidth();
314 seqs = av.getAlignment().getSequencesArray();
318 start = av.getSelectionGroup().getStartRes();
319 end = av.getSelectionGroup().getEndRes() + 1;
320 seqs = av.getSelectionGroup().getSequencesInOrder(
323 ScoreModelI sm = ResidueProperties.getScoreModel(pwtype);
324 if (sm instanceof ViewBasedAnalysisI)
328 sm = sm.getClass().newInstance();
329 ((ViewBasedAnalysisI) sm)
330 .configureFromAlignmentView(treeCanvas.ap);
331 } catch (Exception q)
333 Cache.log.error("Couldn't create a scoremodel instance for "
336 tree = new NJTree(seqs, seqStrings, type, pwtype, sm, start, end);
340 tree = new NJTree(seqs, seqStrings, type, pwtype, null, start,
346 tree.reCount(tree.getTopNode());
347 tree.findHeight(tree.getTopNode());
348 treeCanvas.setTree(tree);
349 treeCanvas.repaint();
350 av.setCurrentTree(tree);
351 if (av.getSortByTree())
353 sortByTree_actionPerformed();
358 public void showDistances(boolean b)
360 treeCanvas.setShowDistances(b);
361 distanceMenu.setSelected(b);
364 public void showBootstrap(boolean b)
366 treeCanvas.setShowBootstrap(b);
367 bootstrapMenu.setSelected(b);
370 public void showPlaceholders(boolean b)
372 placeholdersMenu.setState(b);
373 treeCanvas.setMarkPlaceholders(b);
376 private void allowOriginalSeqData(boolean b)
378 originalSeqData.setVisible(b);
384 * @return DOCUMENT ME!
386 public NJTree getTree()
398 public void textbox_actionPerformed(ActionEvent e)
400 CutAndPasteTransfer cap = new CutAndPasteTransfer();
402 StringBuffer buffer = new StringBuffer();
404 if (type.equals("AV"))
406 buffer.append("Average distance tree using ");
410 buffer.append("Neighbour joining tree using ");
413 if (pwtype.equals("BL"))
415 buffer.append("BLOSUM62");
419 buffer.append("PID");
422 jalview.io.NewickFile fout = new jalview.io.NewickFile(
426 cap.setText(fout.print(tree.isHasBootstrap(), tree.isHasDistances(),
427 tree.isHasRootDistance()));
428 Desktop.addInternalFrame(cap, buffer.toString(), 500, 100);
429 } catch (OutOfMemoryError oom)
431 new OOMWarning("generating newick tree file", oom);
444 public void saveAsNewick_actionPerformed(ActionEvent e)
446 JalviewFileChooser chooser = new JalviewFileChooser(
447 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
448 chooser.setFileView(new JalviewFileView());
449 chooser.setDialogTitle(MessageManager
450 .getString("label.save_tree_as_newick"));
451 chooser.setToolTipText(MessageManager.getString("action.save"));
453 int value = chooser.showSaveDialog(null);
455 if (value == JalviewFileChooser.APPROVE_OPTION)
457 String choice = chooser.getSelectedFile().getPath();
458 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
459 .getSelectedFile().getParent());
463 jalview.io.NewickFile fout = new jalview.io.NewickFile(
465 String output = fout.print(tree.isHasBootstrap(),
466 tree.isHasDistances(), tree.isHasRootDistance());
467 java.io.PrintWriter out = new java.io.PrintWriter(
468 new java.io.FileWriter(choice));
471 } catch (Exception ex)
473 ex.printStackTrace();
485 public void printMenu_actionPerformed(ActionEvent e)
487 // Putting in a thread avoids Swing painting problems
488 treeCanvas.startPrinting();
492 public void originalSeqData_actionPerformed(ActionEvent e)
494 if (!tree.hasOriginalSequenceData())
496 jalview.bin.Cache.log
497 .info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
500 // decide if av alignment is sufficiently different to original data to
501 // warrant a new window to be created
502 // create new alignmnt window with hidden regions (unhiding hidden regions
503 // yields unaligned seqs)
504 // or create a selection box around columns in alignment view
505 // test Alignment(SeqCigar[])
509 // we try to get the associated view's gap character
510 // but this may fail if the view was closed...
511 gc = av.getGapCharacter();
513 } catch (Exception ex)
517 Object[] alAndColsel = tree.seqData.getAlignmentAndColumnSelection(gc);
519 if (alAndColsel != null && alAndColsel[0] != null)
521 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
523 Alignment al = new Alignment((SequenceI[]) alAndColsel[0]);
524 Alignment dataset = (av != null && av.getAlignment() != null) ? av
525 .getAlignment().getDataset() : null;
528 al.setDataset(dataset);
534 AlignFrame af = new AlignFrame(al,
535 (ColumnSelection) alAndColsel[1], AlignFrame.DEFAULT_WIDTH,
536 AlignFrame.DEFAULT_HEIGHT);
538 // >>>This is a fix for the moment, until a better solution is
540 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
542 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
545 Desktop.addInternalFrame(af, MessageManager.formatMessage(
546 "label.original_data_for_params",
547 new Object[] { this.title }), AlignFrame.DEFAULT_WIDTH,
548 AlignFrame.DEFAULT_HEIGHT);
560 public void fitToWindow_actionPerformed(ActionEvent e)
562 treeCanvas.fitToWindow = fitToWindow.isSelected();
567 * sort the associated alignment view by the current tree.
572 public void sortByTree_actionPerformed()
575 if (treeCanvas.applyToAllViews)
577 final ArrayList<CommandI> commands = new ArrayList<CommandI>();
578 for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
579 .getSequenceSetId()))
581 commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
583 av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
587 public void undoCommand(AlignmentI[] views)
589 for (CommandI tsort : commands)
591 tsort.undoCommand(views);
598 return commands.size();
602 public String getDescription()
604 return "Tree Sort (many views)";
608 public void doCommand(AlignmentI[] views)
611 for (CommandI tsort : commands)
613 tsort.doCommand(views);
617 for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
618 .getSequenceSetId()))
620 // ensure all the alignFrames refresh their GI after adding an undo item
621 ap.alignFrame.updateEditMenuBar();
626 treeCanvas.ap.alignFrame
627 .addHistoryItem(sortAlignmentIn(treeCanvas.ap));
632 public CommandI sortAlignmentIn(AlignmentPanel ap)
634 AlignmentViewport av = ap.av;
635 SequenceI[] oldOrder = av.getAlignment().getSequencesArray();
636 AlignmentSorter.sortByTree(av.getAlignment(), tree);
638 undo = new OrderCommand("Tree Sort", oldOrder, av.getAlignment());
640 ap.paintAlignment(true);
651 public void font_actionPerformed(ActionEvent e)
653 if (treeCanvas == null)
658 new FontChooser(this);
661 public Font getTreeFont()
663 return treeCanvas.font;
666 public void setTreeFont(Font font)
668 if (treeCanvas != null)
670 treeCanvas.setFont(font);
681 public void distanceMenu_actionPerformed(ActionEvent e)
683 treeCanvas.setShowDistances(distanceMenu.isSelected());
693 public void bootstrapMenu_actionPerformed(ActionEvent e)
695 treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
705 public void placeholdersMenu_actionPerformed(ActionEvent e)
707 treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
717 public void epsTree_actionPerformed(ActionEvent e)
719 boolean accurateText = true;
721 String renderStyle = jalview.bin.Cache.getDefault("EPS_RENDERING",
724 // If we need to prompt, and if the GUI is visible then
725 // Prompt for EPS rendering style
726 if (renderStyle.equalsIgnoreCase("Prompt each time")
727 && !(System.getProperty("java.awt.headless") != null && System
728 .getProperty("java.awt.headless").equals("true")))
730 EPSOptions eps = new EPSOptions();
731 renderStyle = eps.getValue();
733 if (renderStyle == null || eps.cancelled)
740 if (renderStyle.equalsIgnoreCase("text"))
742 accurateText = false;
745 int width = treeCanvas.getWidth();
746 int height = treeCanvas.getHeight();
750 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
751 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
752 { "eps" }, new String[] { "Encapsulated Postscript" },
753 "Encapsulated Postscript");
754 chooser.setFileView(new jalview.io.JalviewFileView());
755 chooser.setDialogTitle(MessageManager
756 .getString("label.create_eps_from_tree"));
757 chooser.setToolTipText(MessageManager.getString("action.save"));
759 int value = chooser.showSaveDialog(this);
761 if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
766 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
767 .getSelectedFile().getParent());
769 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
770 EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width, height);
772 pg.setAccurateTextMode(accurateText);
774 treeCanvas.draw(pg, width, height);
778 } catch (Exception ex)
780 ex.printStackTrace();
791 public void pngTree_actionPerformed(ActionEvent e)
793 int width = treeCanvas.getWidth();
794 int height = treeCanvas.getHeight();
798 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
799 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
800 { "png" }, new String[] { "Portable network graphics" },
801 "Portable network graphics");
803 chooser.setFileView(new jalview.io.JalviewFileView());
804 chooser.setDialogTitle(MessageManager
805 .getString("label.create_png_from_tree"));
806 chooser.setToolTipText(MessageManager.getString("action.save"));
808 int value = chooser.showSaveDialog(this);
810 if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
815 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
816 .getSelectedFile().getParent());
818 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
820 BufferedImage bi = new BufferedImage(width, height,
821 BufferedImage.TYPE_INT_RGB);
822 Graphics png = bi.getGraphics();
824 treeCanvas.draw(png, width, height);
826 ImageIO.write(bi, "png", out);
828 } catch (Exception ex)
830 ex.printStackTrace();
835 * change node labels to the annotation referred to by labelClass TODO:
836 * promote to a datamodel modification that can be undone TODO: make argument
837 * one case of a generic transformation function ie { undoStep = apply(Tree,
838 * TransformFunction)};
842 public void changeNames(final String labelClass)
844 tree.applyToNodes(new NodeTransformI()
848 public void transform(BinaryNode node)
850 if (node instanceof SequenceNode
851 && !((SequenceNode) node).isPlaceholder()
852 && !((SequenceNode) node).isDummy())
854 String newname = null;
855 SequenceI sq = (SequenceI) ((SequenceNode) node).element();
858 // search dbrefs, features and annotation
859 DBRefEntry[] refs = jalview.util.DBRefUtils.selectRefs(
861 new String[] { labelClass.toUpperCase() });
864 for (int i = 0; i < refs.length; i++)
868 newname = new String(refs[i].getAccessionId());
872 newname = newname + "; " + refs[i].getAccessionId();
878 SequenceFeature sf[] = sq.getSequenceFeatures();
879 for (int i = 0; sf != null && i < sf.length; i++)
881 if (sf[i].getType().equals(labelClass))
885 newname = new String(sf[i].getDescription());
889 newname = newname + "; " + sf[i].getDescription();
897 String oldname = ((SequenceNode) node).getName();
898 // TODO : save in the undo object for this modification.
899 ((SequenceNode) node).setName(newname);