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()
164 public void propertyChange(PropertyChangeEvent evt)
166 if (evt.getPropertyName().equals("alignment"))
170 System.out.println("tree is null");
171 // TODO: deal with case when a change event is received whilst a
172 // tree is still being calculated - should save reference for
173 // processing message later.
176 if (evt.getNewValue() == null)
179 .println("new alignment sequences vector value is null");
182 tree.UpdatePlaceHolders((List<SequenceI>) evt.getNewValue());
183 treeCanvas.nameHash.clear(); // reset the mapping between canvas
184 // rectangles and leafnodes
190 TreeLoader tl = new TreeLoader(newTree);
191 if (inputData != null)
193 tl.odata = inputData;
199 public void viewMenu_menuSelected()
201 buildAssociatedViewMenu();
204 void buildAssociatedViewMenu()
206 AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av
207 .getSequenceSetId());
208 if (aps.length == 1 && treeCanvas.ap == aps[0])
210 associateLeavesMenu.setVisible(false);
214 associateLeavesMenu.setVisible(true);
216 if ((viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
218 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
221 associateLeavesMenu.removeAll();
223 JRadioButtonMenuItem item;
224 ButtonGroup buttonGroup = new ButtonGroup();
225 int i, iSize = aps.length;
226 final TreePanel thisTreePanel = this;
227 for (i = 0; i < iSize; i++)
229 final AlignmentPanel ap = aps[i];
230 item = new JRadioButtonMenuItem(ap.av.viewName, ap == treeCanvas.ap);
231 buttonGroup.add(item);
232 item.addActionListener(new ActionListener()
234 public void actionPerformed(ActionEvent evt)
236 treeCanvas.applyToAllViews = false;
238 treeCanvas.av = ap.av;
239 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
243 associateLeavesMenu.add(item);
246 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
248 buttonGroup.add(itemf);
249 itemf.setSelected(treeCanvas.applyToAllViews);
250 itemf.addActionListener(new ActionListener()
252 public void actionPerformed(ActionEvent evt)
254 treeCanvas.applyToAllViews = itemf.isSelected();
257 associateLeavesMenu.add(itemf);
261 class TreeLoader extends Thread
265 jalview.datamodel.AlignmentView odata = null;
267 public TreeLoader(NewickFile newtree)
269 this.newtree = newtree;
272 // Must be outside run(), as Jalview2XML tries to
273 // update distance/bootstrap visibility at the same time
274 showBootstrap(newtree.HasBootstrap());
275 showDistances(newtree.HasDistances());
286 tree = new NJTree(av.getAlignment().getSequencesArray(), newtree);
290 tree = new NJTree(av.getAlignment().getSequencesArray(), odata,
293 if (!tree.hasOriginalSequenceData())
295 allowOriginalSeqData(false);
302 boolean selview = av.getSelectionGroup() != null
303 && av.getSelectionGroup().getSize() > 1;
304 AlignmentView seqStrings = av.getAlignmentView(selview);
308 end = av.getAlignment().getWidth();
309 seqs = av.getAlignment().getSequencesArray();
313 start = av.getSelectionGroup().getStartRes();
314 end = av.getSelectionGroup().getEndRes() + 1;
315 seqs = av.getSelectionGroup().getSequencesInOrder(
318 ScoreModelI sm = ResidueProperties.getScoreModel(pwtype);
319 if (sm instanceof ViewBasedAnalysisI)
323 sm = sm.getClass().newInstance();
324 ((ViewBasedAnalysisI) sm)
325 .configureFromAlignmentView(treeCanvas.ap);
326 } catch (Exception q)
328 Cache.log.error("Couldn't create a scoremodel instance for "
331 tree = new NJTree(seqs, seqStrings, type, pwtype, sm, start, end);
335 tree = new NJTree(seqs, seqStrings, type, pwtype, null, start,
341 tree.reCount(tree.getTopNode());
342 tree.findHeight(tree.getTopNode());
343 treeCanvas.setTree(tree);
344 treeCanvas.repaint();
345 av.setCurrentTree(tree);
346 if (av.getSortByTree())
348 sortByTree_actionPerformed();
353 public void showDistances(boolean b)
355 treeCanvas.setShowDistances(b);
356 distanceMenu.setSelected(b);
359 public void showBootstrap(boolean b)
361 treeCanvas.setShowBootstrap(b);
362 bootstrapMenu.setSelected(b);
365 public void showPlaceholders(boolean b)
367 placeholdersMenu.setState(b);
368 treeCanvas.setMarkPlaceholders(b);
371 private void allowOriginalSeqData(boolean b)
373 originalSeqData.setVisible(b);
379 * @return DOCUMENT ME!
381 public NJTree getTree()
392 public void textbox_actionPerformed(ActionEvent e)
394 CutAndPasteTransfer cap = new CutAndPasteTransfer();
396 StringBuffer buffer = new StringBuffer();
398 if (type.equals("AV"))
400 buffer.append("Average distance tree using ");
404 buffer.append("Neighbour joining tree using ");
407 if (pwtype.equals("BL"))
409 buffer.append("BLOSUM62");
413 buffer.append("PID");
416 jalview.io.NewickFile fout = new jalview.io.NewickFile(
420 cap.setText(fout.print(tree.isHasBootstrap(), tree.isHasDistances(),
421 tree.isHasRootDistance()));
422 Desktop.addInternalFrame(cap, buffer.toString(), 500, 100);
423 } catch (OutOfMemoryError oom)
425 new OOMWarning("generating newick tree file", oom);
437 public void saveAsNewick_actionPerformed(ActionEvent e)
439 JalviewFileChooser chooser = new JalviewFileChooser(
440 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
441 chooser.setFileView(new JalviewFileView());
442 chooser.setDialogTitle(MessageManager.getString("label.save_tree_as_newick"));
443 chooser.setToolTipText(MessageManager.getString("action.save"));
445 int value = chooser.showSaveDialog(null);
447 if (value == JalviewFileChooser.APPROVE_OPTION)
449 String choice = chooser.getSelectedFile().getPath();
450 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
451 .getSelectedFile().getParent());
455 jalview.io.NewickFile fout = new jalview.io.NewickFile(
457 String output = fout.print(tree.isHasBootstrap(),
458 tree.isHasDistances(), tree.isHasRootDistance());
459 java.io.PrintWriter out = new java.io.PrintWriter(
460 new java.io.FileWriter(choice));
463 } catch (Exception ex)
465 ex.printStackTrace();
476 public void printMenu_actionPerformed(ActionEvent e)
478 // Putting in a thread avoids Swing painting problems
479 treeCanvas.startPrinting();
482 public void originalSeqData_actionPerformed(ActionEvent e)
484 if (!tree.hasOriginalSequenceData())
486 jalview.bin.Cache.log
487 .info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
490 // decide if av alignment is sufficiently different to original data to
491 // warrant a new window to be created
492 // create new alignmnt window with hidden regions (unhiding hidden regions
493 // yields unaligned seqs)
494 // or create a selection box around columns in alignment view
495 // test Alignment(SeqCigar[])
499 // we try to get the associated view's gap character
500 // but this may fail if the view was closed...
501 gc = av.getGapCharacter();
503 } catch (Exception ex)
507 Object[] alAndColsel = tree.seqData.getAlignmentAndColumnSelection(gc);
509 if (alAndColsel != null && alAndColsel[0] != null)
511 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
513 Alignment al = new Alignment((SequenceI[]) alAndColsel[0]);
514 Alignment dataset = (av != null && av.getAlignment() != null) ? av
515 .getAlignment().getDataset() : null;
518 al.setDataset(dataset);
524 AlignFrame af = new AlignFrame(al,
525 (ColumnSelection) alAndColsel[1], AlignFrame.DEFAULT_WIDTH,
526 AlignFrame.DEFAULT_HEIGHT);
528 // >>>This is a fix for the moment, until a better solution is
530 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
532 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
535 Desktop.addInternalFrame(af, MessageManager.formatMessage(
536 "label.original_data_for_params", new Object[]
537 { this.title }), AlignFrame.DEFAULT_WIDTH,
538 AlignFrame.DEFAULT_HEIGHT);
549 public void fitToWindow_actionPerformed(ActionEvent e)
551 treeCanvas.fitToWindow = fitToWindow.isSelected();
556 * sort the associated alignment view by the current tree.
561 public void sortByTree_actionPerformed()
564 if (treeCanvas.applyToAllViews)
566 final ArrayList<CommandI> commands = new ArrayList<CommandI>();
567 for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
568 .getSequenceSetId()))
570 commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
572 av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
576 public void undoCommand(AlignmentI[] views)
578 for (CommandI tsort : commands)
580 tsort.undoCommand(views);
587 return commands.size();
591 public String getDescription()
593 return "Tree Sort (many views)";
597 public void doCommand(AlignmentI[] views)
600 for (CommandI tsort : commands)
602 tsort.doCommand(views);
606 for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
607 .getSequenceSetId()))
609 // ensure all the alignFrames refresh their GI after adding an undo item
610 ap.alignFrame.updateEditMenuBar();
615 treeCanvas.ap.alignFrame
616 .addHistoryItem(sortAlignmentIn(treeCanvas.ap));
621 public CommandI sortAlignmentIn(AlignmentPanel ap)
623 AlignmentViewport av = ap.av;
624 SequenceI[] oldOrder = av.getAlignment().getSequencesArray();
625 AlignmentSorter.sortByTree(av.getAlignment(), tree);
627 undo = new OrderCommand("Tree Sort", oldOrder, av.getAlignment());
629 ap.paintAlignment(true);
639 public void font_actionPerformed(ActionEvent e)
641 if (treeCanvas == null)
646 new FontChooser(this);
649 public Font getTreeFont()
651 return treeCanvas.font;
654 public void setTreeFont(Font font)
656 if (treeCanvas != null)
658 treeCanvas.setFont(font);
668 public void distanceMenu_actionPerformed(ActionEvent e)
670 treeCanvas.setShowDistances(distanceMenu.isSelected());
679 public void bootstrapMenu_actionPerformed(ActionEvent e)
681 treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
690 public void placeholdersMenu_actionPerformed(ActionEvent e)
692 treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
701 public void epsTree_actionPerformed(ActionEvent e)
703 boolean accurateText = true;
705 String renderStyle = jalview.bin.Cache.getDefault("EPS_RENDERING",
708 // If we need to prompt, and if the GUI is visible then
709 // Prompt for EPS rendering style
710 if (renderStyle.equalsIgnoreCase("Prompt each time")
711 && !(System.getProperty("java.awt.headless") != null && System
712 .getProperty("java.awt.headless").equals("true")))
714 EPSOptions eps = new EPSOptions();
715 renderStyle = eps.getValue();
717 if (renderStyle == null || eps.cancelled)
724 if (renderStyle.equalsIgnoreCase("text"))
726 accurateText = false;
729 int width = treeCanvas.getWidth();
730 int height = treeCanvas.getHeight();
734 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
735 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
736 { "eps" }, new String[]
737 { "Encapsulated Postscript" }, "Encapsulated Postscript");
738 chooser.setFileView(new jalview.io.JalviewFileView());
739 chooser.setDialogTitle(MessageManager.getString("label.create_eps_from_tree"));
740 chooser.setToolTipText(MessageManager.getString("action.save"));
742 int value = chooser.showSaveDialog(this);
744 if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
749 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
750 .getSelectedFile().getParent());
752 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
753 EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width, height);
755 pg.setAccurateTextMode(accurateText);
757 treeCanvas.draw(pg, width, height);
761 } catch (Exception ex)
763 ex.printStackTrace();
773 public void pngTree_actionPerformed(ActionEvent e)
775 int width = treeCanvas.getWidth();
776 int height = treeCanvas.getHeight();
780 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
781 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
782 { "png" }, new String[]
783 { "Portable network graphics" }, "Portable network graphics");
785 chooser.setFileView(new jalview.io.JalviewFileView());
786 chooser.setDialogTitle(MessageManager.getString("label.create_png_from_tree"));
787 chooser.setToolTipText(MessageManager.getString("action.save"));
789 int value = chooser.showSaveDialog(this);
791 if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
796 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
797 .getSelectedFile().getParent());
799 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
801 BufferedImage bi = new BufferedImage(width, height,
802 BufferedImage.TYPE_INT_RGB);
803 Graphics png = bi.getGraphics();
805 treeCanvas.draw(png, width, height);
807 ImageIO.write(bi, "png", out);
809 } catch (Exception ex)
811 ex.printStackTrace();
816 * change node labels to the annotation referred to by labelClass TODO:
817 * promote to a datamodel modification that can be undone TODO: make argument
818 * one case of a generic transformation function ie { undoStep = apply(Tree,
819 * TransformFunction)};
823 public void changeNames(final String labelClass)
825 tree.applyToNodes(new NodeTransformI()
828 public void transform(BinaryNode node)
830 if (node instanceof SequenceNode
831 && !((SequenceNode) node).isPlaceholder()
832 && !((SequenceNode) node).isDummy())
834 String newname = null;
835 SequenceI sq = (SequenceI) ((SequenceNode) node).element();
838 // search dbrefs, features and annotation
839 DBRefEntry[] refs = jalview.util.DBRefUtils.selectRefs(
840 sq.getDBRef(), new String[]
841 { labelClass.toUpperCase() });
844 for (int i = 0; i < refs.length; i++)
848 newname = new String(refs[i].getAccessionId());
852 newname = newname + "; " + refs[i].getAccessionId();
858 SequenceFeature sf[] = sq.getSequenceFeatures();
859 for (int i = 0; sf != null && i < sf.length; i++)
861 if (sf[i].getType().equals(labelClass))
865 newname = new String(sf[i].getDescription());
869 newname = newname + "; " + sf[i].getDescription();
877 String oldname = ((SequenceNode) node).getName();
878 // TODO : save in the undo object for this modification.
879 ((SequenceNode) node).setName(newname);