2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 import javax.imageio.*;
27 import java.awt.event.*;
28 import java.awt.image.*;
31 import org.jibble.epsgraphics.*;
32 import jalview.analysis.*;
33 import jalview.commands.OrderCommand;
34 import jalview.datamodel.*;
36 import jalview.jbgui.*;
44 public class TreePanel extends GTreePanel
50 TreeCanvas treeCanvas;
57 * Creates a new TreePanel object.
72 public TreePanel(AlignmentPanel ap, String type, String pwtype)
75 initTreePanel(ap, type, pwtype, null, null);
77 // We know this tree has distances. JBPNote TODO: prolly should add this as
78 // a userdefined default
79 // showDistances(true);
83 * Creates a new TreePanel object.
96 public TreePanel(AlignmentPanel ap, String type, String pwtype,
100 initTreePanel(ap, type, pwtype, newtree, null);
103 public TreePanel(AlignmentPanel av, String type, String pwtype,
104 NewickFile newtree, AlignmentView inputData)
107 initTreePanel(av, type, pwtype, newtree, inputData);
110 public AlignmentI getAlignment()
112 return treeCanvas.av.getAlignment();
115 public AlignViewport getViewPort()
117 return treeCanvas.av;
120 void initTreePanel(AlignmentPanel ap, String type, String pwtype,
121 NewickFile newTree, AlignmentView inputData)
126 this.pwtype = pwtype;
128 treeCanvas = new TreeCanvas(this, ap, scrollPane);
129 scrollPane.setViewportView(treeCanvas);
131 PaintRefresher.Register(this, ap.av.getSequenceSetId());
133 buildAssociatedViewMenu();
135 av.addPropertyChangeListener(new java.beans.PropertyChangeListener()
137 public void propertyChange(PropertyChangeEvent evt)
139 if (evt.getPropertyName().equals("alignment"))
143 System.out.println("tree is null");
144 // TODO: deal with case when a change event is received whilst a tree is still being calculated - should save reference for processing message later.
147 if (evt.getNewValue() == null)
150 .println("new alignment sequences vector value is null");
153 tree.UpdatePlaceHolders((Vector) evt.getNewValue());
154 treeCanvas.nameHash.clear(); // reset the mapping between canvas
155 // rectangles and leafnodes
161 TreeLoader tl = new TreeLoader(newTree);
162 if (inputData != null)
164 tl.odata = inputData;
170 public void viewMenu_menuSelected()
172 buildAssociatedViewMenu();
175 void buildAssociatedViewMenu()
177 AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av
178 .getSequenceSetId());
179 if (aps.length == 1 && treeCanvas.ap == aps[0])
181 associateLeavesMenu.setVisible(false);
185 associateLeavesMenu.setVisible(true);
187 if ((viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
189 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
192 associateLeavesMenu.removeAll();
194 JRadioButtonMenuItem item;
195 ButtonGroup buttonGroup = new ButtonGroup();
196 int i, iSize = aps.length;
197 final TreePanel thisTreePanel = this;
198 for (i = 0; i < iSize; i++)
200 final AlignmentPanel ap = aps[i];
201 item = new JRadioButtonMenuItem(ap.av.viewName, ap == treeCanvas.ap);
202 buttonGroup.add(item);
203 item.addActionListener(new ActionListener()
205 public void actionPerformed(ActionEvent evt)
207 treeCanvas.applyToAllViews = false;
209 treeCanvas.av = ap.av;
210 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
214 associateLeavesMenu.add(item);
217 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem("All Views");
218 buttonGroup.add(itemf);
219 itemf.setSelected(treeCanvas.applyToAllViews);
220 itemf.addActionListener(new ActionListener()
222 public void actionPerformed(ActionEvent evt)
224 treeCanvas.applyToAllViews = itemf.isSelected();
227 associateLeavesMenu.add(itemf);
231 class TreeLoader extends Thread
235 jalview.datamodel.AlignmentView odata = null;
237 public TreeLoader(NewickFile newtree)
239 this.newtree = newtree;
242 // Must be outside run(), as Jalview2XML tries to
243 // update distance/bootstrap visibility at the same time
244 showBootstrap(newtree.HasBootstrap());
245 showDistances(newtree.HasDistances());
256 tree = new NJTree(av.alignment.getSequencesArray(), newtree);
260 tree = new NJTree(av.alignment.getSequencesArray(), odata,
263 if (!tree.hasOriginalSequenceData())
265 allowOriginalSeqData(false);
272 AlignmentView seqStrings = av.getAlignmentView(av
273 .getSelectionGroup() != null);
274 if (av.getSelectionGroup() == null)
277 end = av.alignment.getWidth();
278 seqs = av.alignment.getSequencesArray();
282 start = av.getSelectionGroup().getStartRes();
283 end = av.getSelectionGroup().getEndRes() + 1;
284 seqs = av.getSelectionGroup().getSequencesInOrder(av.alignment);
287 tree = new NJTree(seqs, seqStrings, type, pwtype, start, end);
291 tree.reCount(tree.getTopNode());
292 tree.findHeight(tree.getTopNode());
293 treeCanvas.setTree(tree);
294 treeCanvas.repaint();
295 av.setCurrentTree(tree);
296 if (av.getSortByTree())
298 sortByTree_actionPerformed(null);
303 public void showDistances(boolean b)
305 treeCanvas.setShowDistances(b);
306 distanceMenu.setSelected(b);
309 public void showBootstrap(boolean b)
311 treeCanvas.setShowBootstrap(b);
312 bootstrapMenu.setSelected(b);
315 public void showPlaceholders(boolean b)
317 placeholdersMenu.setState(b);
318 treeCanvas.setMarkPlaceholders(b);
321 private void allowOriginalSeqData(boolean b)
323 originalSeqData.setVisible(b);
329 * @return DOCUMENT ME!
331 public NJTree getTree()
342 public void textbox_actionPerformed(ActionEvent e)
344 CutAndPasteTransfer cap = new CutAndPasteTransfer();
346 StringBuffer buffer = new StringBuffer();
348 if (type.equals("AV"))
350 buffer.append("Average distance tree using ");
354 buffer.append("Neighbour joining tree using ");
357 if (pwtype.equals("BL"))
359 buffer.append("BLOSUM62");
363 buffer.append("PID");
366 Desktop.addInternalFrame(cap, buffer.toString(), 500, 100);
368 jalview.io.NewickFile fout = new jalview.io.NewickFile(tree
370 cap.setText(fout.print(tree.isHasBootstrap(), tree.isHasDistances(),
371 tree.isHasRootDistance()));
380 public void saveAsNewick_actionPerformed(ActionEvent e)
382 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
383 .getProperty("LAST_DIRECTORY"));
384 chooser.setFileView(new JalviewFileView());
385 chooser.setDialogTitle("Save tree as newick file");
386 chooser.setToolTipText("Save");
388 int value = chooser.showSaveDialog(null);
390 if (value == JalviewFileChooser.APPROVE_OPTION)
392 String choice = chooser.getSelectedFile().getPath();
393 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
394 .getSelectedFile().getParent());
398 jalview.io.NewickFile fout = new jalview.io.NewickFile(tree
400 String output = fout.print(tree.isHasBootstrap(), tree
401 .isHasDistances(), tree.isHasRootDistance());
402 java.io.PrintWriter out = new java.io.PrintWriter(
403 new java.io.FileWriter(choice));
406 } catch (Exception ex)
408 ex.printStackTrace();
419 public void printMenu_actionPerformed(ActionEvent e)
421 // Putting in a thread avoids Swing painting problems
422 treeCanvas.startPrinting();
425 public void originalSeqData_actionPerformed(ActionEvent e)
427 if (!tree.hasOriginalSequenceData())
429 jalview.bin.Cache.log
430 .info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
433 // decide if av alignment is sufficiently different to original data to
434 // warrant a new window to be created
435 // create new alignmnt window with hidden regions (unhiding hidden regions
436 // yields unaligned seqs)
437 // or create a selection box around columns in alignment view
438 // test Alignment(SeqCigar[])
442 // we try to get the associated view's gap character
443 // but this may fail if the view was closed...
444 gc = av.getGapCharacter();
446 } catch (Exception ex)
450 Object[] alAndColsel = tree.seqData.getAlignmentAndColumnSelection(gc);
452 if (alAndColsel != null && alAndColsel[0] != null)
454 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
456 Alignment al = new Alignment((SequenceI[]) alAndColsel[0]);
457 Alignment dataset = (av != null && av.getAlignment() != null) ? av
458 .getAlignment().getDataset() : null;
461 al.setDataset(dataset);
467 AlignFrame af = new AlignFrame(al,
468 (ColumnSelection) alAndColsel[1], AlignFrame.DEFAULT_WIDTH,
469 AlignFrame.DEFAULT_HEIGHT);
471 // >>>This is a fix for the moment, until a better solution is
473 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
475 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
478 Desktop.addInternalFrame(af, "Original Data for " + this.title,
479 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
490 public void fitToWindow_actionPerformed(ActionEvent e)
492 treeCanvas.fitToWindow = fitToWindow.isSelected();
497 * sort the associated alignment view by the current tree.
500 public void sortByTree_actionPerformed(ActionEvent e)
502 AlignmentPanel ap = av.getAlignPanel();
503 SequenceI[] oldOrder = av.getAlignment().getSequencesArray();
504 AlignmentSorter.sortByTree(av.getAlignment(), tree);
507 .addHistoryItem(new OrderCommand("Tree Sort", oldOrder,
510 ap.paintAlignment(true);
520 public void font_actionPerformed(ActionEvent e)
522 if (treeCanvas == null)
527 new FontChooser(this);
530 public Font getTreeFont()
532 return treeCanvas.font;
535 public void setTreeFont(Font font)
537 if (treeCanvas != null)
539 treeCanvas.setFont(font);
549 public void distanceMenu_actionPerformed(ActionEvent e)
551 treeCanvas.setShowDistances(distanceMenu.isSelected());
560 public void bootstrapMenu_actionPerformed(ActionEvent e)
562 treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
571 public void placeholdersMenu_actionPerformed(ActionEvent e)
573 treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
582 public void epsTree_actionPerformed(ActionEvent e)
584 boolean accurateText = true;
586 String renderStyle = jalview.bin.Cache.getDefault("EPS_RENDERING",
589 // If we need to prompt, and if the GUI is visible then
590 // Prompt for EPS rendering style
591 if (renderStyle.equalsIgnoreCase("Prompt each time")
592 && !(System.getProperty("java.awt.headless") != null && System
593 .getProperty("java.awt.headless").equals("true")))
595 EPSOptions eps = new EPSOptions();
596 renderStyle = eps.getValue();
598 if (renderStyle == null || eps.cancelled)
605 if (renderStyle.equalsIgnoreCase("text"))
607 accurateText = false;
610 int width = treeCanvas.getWidth();
611 int height = treeCanvas.getHeight();
615 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
616 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
617 { "eps" }, new String[]
618 { "Encapsulated Postscript" }, "Encapsulated Postscript");
619 chooser.setFileView(new jalview.io.JalviewFileView());
620 chooser.setDialogTitle("Create EPS file from tree");
621 chooser.setToolTipText("Save");
623 int value = chooser.showSaveDialog(this);
625 if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
630 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
631 .getSelectedFile().getParent());
633 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
634 EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width, height);
636 pg.setAccurateTextMode(accurateText);
638 treeCanvas.draw(pg, width, height);
642 } catch (Exception ex)
644 ex.printStackTrace();
654 public void pngTree_actionPerformed(ActionEvent e)
656 int width = treeCanvas.getWidth();
657 int height = treeCanvas.getHeight();
661 jalview.io.JalviewFileChooser chooser = new jalview.io.JalviewFileChooser(
662 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
663 { "png" }, new String[]
664 { "Portable network graphics" }, "Portable network graphics");
666 chooser.setFileView(new jalview.io.JalviewFileView());
667 chooser.setDialogTitle("Create PNG image from tree");
668 chooser.setToolTipText("Save");
670 int value = chooser.showSaveDialog(this);
672 if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
677 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
678 .getSelectedFile().getParent());
680 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
682 BufferedImage bi = new BufferedImage(width, height,
683 BufferedImage.TYPE_INT_RGB);
684 Graphics png = bi.getGraphics();
686 treeCanvas.draw(png, width, height);
688 ImageIO.write(bi, "png", out);
690 } catch (Exception ex)
692 ex.printStackTrace();
696 * change node labels to the annotation referred to by labelClass
697 * TODO: promote to a datamodel modification that can be undone
698 * TODO: make argument one case of a generic transformation function ie { undoStep = apply(Tree, TransformFunction)};
701 public void changeNames(final String labelClass)
703 tree.applyToNodes(new NodeTransformI() {
705 public void transform(BinaryNode node)
707 if (node instanceof SequenceNode && !((SequenceNode) node).isPlaceholder() && !((SequenceNode) node).isDummy())
710 SequenceI sq = (SequenceI) ((SequenceNode) node).element();
713 // search dbrefs, features and annotation
714 DBRefEntry[] refs = jalview.util.DBRefUtils.selectRefs(sq.getDBRef(), new String[] {labelClass.toUpperCase()});
717 for (int i=0; i<refs.length;i++)
719 if (newname == null) {
720 newname = new String(refs[i].getAccessionId());
722 newname = newname +"; "+refs[i].getAccessionId();
728 SequenceFeature sf[] = sq.getSequenceFeatures();
729 for (int i=0;sf!=null && i<sf.length; i++)
731 if (sf[i].getType().equals(labelClass))
735 newname = new String(sf[i].getDescription());
737 newname = newname + "; "+sf[i].getDescription();
745 String oldname = ((SequenceNode) node).getName();
746 // TODO : save in the undo object for this modification.
747 ((SequenceNode) node).setName(newname);