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.analysis.scoremodels.ScoreModels;
26 import jalview.api.analysis.ScoreModelI;
27 import jalview.api.analysis.ViewBasedAnalysisI;
28 import jalview.bin.Cache;
29 import jalview.commands.CommandI;
30 import jalview.commands.OrderCommand;
31 import jalview.datamodel.Alignment;
32 import jalview.datamodel.AlignmentI;
33 import jalview.datamodel.AlignmentView;
34 import jalview.datamodel.BinaryNode;
35 import jalview.datamodel.ColumnSelection;
36 import jalview.datamodel.DBRefEntry;
37 import jalview.datamodel.NodeTransformI;
38 import jalview.datamodel.SequenceFeature;
39 import jalview.datamodel.SequenceI;
40 import jalview.datamodel.SequenceNode;
41 import jalview.io.JalviewFileChooser;
42 import jalview.io.JalviewFileView;
43 import jalview.io.NewickFile;
44 import jalview.jbgui.GTreePanel;
45 import jalview.util.ImageMaker;
46 import jalview.util.MessageManager;
47 import jalview.viewmodel.AlignmentViewport;
50 import java.awt.Graphics;
51 import java.awt.event.ActionEvent;
52 import java.awt.event.ActionListener;
53 import java.awt.image.BufferedImage;
54 import java.beans.PropertyChangeEvent;
55 import java.io.FileOutputStream;
56 import java.util.ArrayList;
57 import java.util.List;
59 import javax.imageio.ImageIO;
60 import javax.swing.ButtonGroup;
61 import javax.swing.JMenuItem;
62 import javax.swing.JRadioButtonMenuItem;
64 import org.jibble.epsgraphics.EpsGraphics2D;
72 public class TreePanel extends GTreePanel
78 TreeCanvas treeCanvas;
85 * Creates a new TreePanel object.
100 public TreePanel(AlignmentPanel ap, String type, String pwtype)
103 initTreePanel(ap, type, pwtype, null, null);
105 // We know this tree has distances. JBPNote TODO: prolly should add this as
106 // a userdefined default
107 // showDistances(true);
111 * Creates a new TreePanel object.
124 public TreePanel(AlignmentPanel ap, String type, String pwtype,
128 initTreePanel(ap, type, pwtype, newtree, null);
131 public TreePanel(AlignmentPanel av, String type, String pwtype,
132 NewickFile newtree, AlignmentView inputData)
135 initTreePanel(av, type, pwtype, newtree, inputData);
138 public AlignmentI getAlignment()
140 return treeCanvas.av.getAlignment();
143 public AlignmentViewport getViewPort()
145 return treeCanvas.av;
148 void initTreePanel(AlignmentPanel ap, String type, String pwtype,
149 NewickFile newTree, AlignmentView inputData)
154 this.pwtype = pwtype;
156 treeCanvas = new TreeCanvas(this, ap, scrollPane);
157 scrollPane.setViewportView(treeCanvas);
159 PaintRefresher.Register(this, ap.av.getSequenceSetId());
161 buildAssociatedViewMenu();
163 av.addPropertyChangeListener(new java.beans.PropertyChangeListener()
166 public void propertyChange(PropertyChangeEvent evt)
168 if (evt.getPropertyName().equals("alignment"))
172 System.out.println("tree is null");
173 // TODO: deal with case when a change event is received whilst a
174 // tree is still being calculated - should save reference for
175 // processing message later.
178 if (evt.getNewValue() == null)
181 .println("new alignment sequences vector value is null");
184 tree.UpdatePlaceHolders((List<SequenceI>) evt.getNewValue());
185 treeCanvas.nameHash.clear(); // reset the mapping between canvas
186 // rectangles and leafnodes
192 TreeLoader tl = new TreeLoader(newTree);
193 if (inputData != null)
195 tl.odata = inputData;
202 public void viewMenu_menuSelected()
204 buildAssociatedViewMenu();
207 void buildAssociatedViewMenu()
209 AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av
210 .getSequenceSetId());
211 if (aps.length == 1 && treeCanvas.ap == aps[0])
213 associateLeavesMenu.setVisible(false);
217 associateLeavesMenu.setVisible(true);
219 if ((viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
221 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
224 associateLeavesMenu.removeAll();
226 JRadioButtonMenuItem item;
227 ButtonGroup buttonGroup = new ButtonGroup();
228 int i, iSize = aps.length;
229 final TreePanel thisTreePanel = this;
230 for (i = 0; i < iSize; i++)
232 final AlignmentPanel ap = aps[i];
233 item = new JRadioButtonMenuItem(ap.av.viewName, ap == treeCanvas.ap);
234 buttonGroup.add(item);
235 item.addActionListener(new ActionListener()
238 public void actionPerformed(ActionEvent evt)
240 treeCanvas.applyToAllViews = false;
242 treeCanvas.av = ap.av;
243 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
247 associateLeavesMenu.add(item);
250 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
251 MessageManager.getString("label.all_views"));
252 buttonGroup.add(itemf);
253 itemf.setSelected(treeCanvas.applyToAllViews);
254 itemf.addActionListener(new ActionListener()
257 public void actionPerformed(ActionEvent evt)
259 treeCanvas.applyToAllViews = itemf.isSelected();
262 associateLeavesMenu.add(itemf);
266 class TreeLoader extends Thread
270 jalview.datamodel.AlignmentView odata = null;
272 public TreeLoader(NewickFile newtree)
274 this.newtree = newtree;
277 // Must be outside run(), as Jalview2XML tries to
278 // update distance/bootstrap visibility at the same time
279 showBootstrap(newtree.HasBootstrap());
280 showDistances(newtree.HasDistances());
292 tree = new NJTree(av.getAlignment().getSequencesArray(), newtree);
296 tree = new NJTree(av.getAlignment().getSequencesArray(), odata,
299 if (!tree.hasOriginalSequenceData())
301 allowOriginalSeqData(false);
308 boolean selview = av.getSelectionGroup() != null
309 && av.getSelectionGroup().getSize() > 1;
310 AlignmentView seqStrings = av.getAlignmentView(selview);
314 end = av.getAlignment().getWidth();
315 seqs = av.getAlignment().getSequencesArray();
319 start = av.getSelectionGroup().getStartRes();
320 end = av.getSelectionGroup().getEndRes() + 1;
321 seqs = av.getSelectionGroup().getSequencesInOrder(
324 ScoreModelI sm = ScoreModels.getInstance().forName(pwtype);
325 if (sm instanceof ViewBasedAnalysisI)
329 sm = sm.getClass().newInstance();
330 ((ViewBasedAnalysisI) sm)
331 .configureFromAlignmentView(treeCanvas.ap);
332 } catch (Exception q)
334 Cache.log.error("Couldn't create a scoremodel instance for "
337 tree = new NJTree(seqs, seqStrings, type, pwtype, sm, start, end);
341 tree = new NJTree(seqs, seqStrings, type, pwtype, null, start,
347 tree.reCount(tree.getTopNode());
348 tree.findHeight(tree.getTopNode());
349 treeCanvas.setTree(tree);
350 treeCanvas.repaint();
351 av.setCurrentTree(tree);
352 if (av.getSortByTree())
354 sortByTree_actionPerformed();
359 public void showDistances(boolean b)
361 treeCanvas.setShowDistances(b);
362 distanceMenu.setSelected(b);
365 public void showBootstrap(boolean b)
367 treeCanvas.setShowBootstrap(b);
368 bootstrapMenu.setSelected(b);
371 public void showPlaceholders(boolean b)
373 placeholdersMenu.setState(b);
374 treeCanvas.setMarkPlaceholders(b);
377 private void allowOriginalSeqData(boolean b)
379 originalSeqData.setVisible(b);
385 * @return DOCUMENT ME!
387 public NJTree getTree()
399 public void textbox_actionPerformed(ActionEvent e)
401 CutAndPasteTransfer cap = new CutAndPasteTransfer();
403 StringBuffer buffer = new StringBuffer();
405 if (type.equals(NJTree.AVERAGE_DISTANCE))
407 buffer.append("Average distance tree using ");
411 buffer.append("Neighbour joining tree using ");
414 ScoreModelI sm = ScoreModels.getInstance().forName(pwtype);
415 buffer.append(sm.getName());
417 NewickFile fout = new NewickFile(tree.getTopNode());
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);
438 public void saveAsNewick_actionPerformed(ActionEvent e)
440 JalviewFileChooser chooser = new JalviewFileChooser(
441 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
442 chooser.setFileView(new JalviewFileView());
443 chooser.setDialogTitle(MessageManager
444 .getString("label.save_tree_as_newick"));
445 chooser.setToolTipText(MessageManager.getString("action.save"));
447 int value = chooser.showSaveDialog(null);
449 if (value == JalviewFileChooser.APPROVE_OPTION)
451 String choice = chooser.getSelectedFile().getPath();
452 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
453 .getSelectedFile().getParent());
457 jalview.io.NewickFile fout = new jalview.io.NewickFile(
459 String output = fout.print(tree.isHasBootstrap(),
460 tree.isHasDistances(), tree.isHasRootDistance());
461 java.io.PrintWriter out = new java.io.PrintWriter(
462 new java.io.FileWriter(choice));
465 } catch (Exception ex)
467 ex.printStackTrace();
479 public void printMenu_actionPerformed(ActionEvent e)
481 // Putting in a thread avoids Swing painting problems
482 treeCanvas.startPrinting();
486 public void originalSeqData_actionPerformed(ActionEvent e)
488 if (!tree.hasOriginalSequenceData())
490 jalview.bin.Cache.log
491 .info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
494 // decide if av alignment is sufficiently different to original data to
495 // warrant a new window to be created
496 // create new alignmnt window with hidden regions (unhiding hidden regions
497 // yields unaligned seqs)
498 // or create a selection box around columns in alignment view
499 // test Alignment(SeqCigar[])
503 // we try to get the associated view's gap character
504 // but this may fail if the view was closed...
505 gc = av.getGapCharacter();
507 } catch (Exception ex)
511 Object[] alAndColsel = tree.seqData.getAlignmentAndColumnSelection(gc);
513 if (alAndColsel != null && alAndColsel[0] != null)
515 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
517 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
518 AlignmentI dataset = (av != null && av.getAlignment() != null) ? av
519 .getAlignment().getDataset() : null;
522 al.setDataset(dataset);
528 AlignFrame af = new AlignFrame(al,
529 (ColumnSelection) alAndColsel[1], AlignFrame.DEFAULT_WIDTH,
530 AlignFrame.DEFAULT_HEIGHT);
532 // >>>This is a fix for the moment, until a better solution is
534 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
536 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
539 Desktop.addInternalFrame(af, MessageManager.formatMessage(
540 "label.original_data_for_params",
541 new Object[] { this.title }), AlignFrame.DEFAULT_WIDTH,
542 AlignFrame.DEFAULT_HEIGHT);
554 public void fitToWindow_actionPerformed(ActionEvent e)
556 treeCanvas.fitToWindow = fitToWindow.isSelected();
561 * sort the associated alignment view by the current tree.
566 public void sortByTree_actionPerformed()
569 if (treeCanvas.applyToAllViews)
571 final ArrayList<CommandI> commands = new ArrayList<CommandI>();
572 for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
573 .getSequenceSetId()))
575 commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
577 av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
581 public void undoCommand(AlignmentI[] views)
583 for (CommandI tsort : commands)
585 tsort.undoCommand(views);
592 return commands.size();
596 public String getDescription()
598 return "Tree Sort (many views)";
602 public void doCommand(AlignmentI[] views)
605 for (CommandI tsort : commands)
607 tsort.doCommand(views);
611 for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
612 .getSequenceSetId()))
614 // ensure all the alignFrames refresh their GI after adding an undo item
615 ap.alignFrame.updateEditMenuBar();
620 treeCanvas.ap.alignFrame
621 .addHistoryItem(sortAlignmentIn(treeCanvas.ap));
626 public CommandI sortAlignmentIn(AlignmentPanel ap)
628 AlignmentViewport av = ap.av;
629 SequenceI[] oldOrder = av.getAlignment().getSequencesArray();
630 AlignmentSorter.sortByTree(av.getAlignment(), tree);
632 undo = new OrderCommand("Tree Sort", oldOrder, av.getAlignment());
634 ap.paintAlignment(true);
645 public void font_actionPerformed(ActionEvent e)
647 if (treeCanvas == null)
652 new FontChooser(this);
655 public Font getTreeFont()
657 return treeCanvas.font;
660 public void setTreeFont(Font font)
662 if (treeCanvas != null)
664 treeCanvas.setFont(font);
675 public void distanceMenu_actionPerformed(ActionEvent e)
677 treeCanvas.setShowDistances(distanceMenu.isSelected());
687 public void bootstrapMenu_actionPerformed(ActionEvent e)
689 treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
699 public void placeholdersMenu_actionPerformed(ActionEvent e)
701 treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
711 public void epsTree_actionPerformed(ActionEvent e)
713 boolean accurateText = true;
715 String renderStyle = jalview.bin.Cache.getDefault("EPS_RENDERING",
718 // If we need to prompt, and if the GUI is visible then
719 // Prompt for EPS rendering style
720 if (renderStyle.equalsIgnoreCase("Prompt each time")
721 && !(System.getProperty("java.awt.headless") != null && System
722 .getProperty("java.awt.headless").equals("true")))
724 EPSOptions eps = new EPSOptions();
725 renderStyle = eps.getValue();
727 if (renderStyle == null || eps.cancelled)
734 if (renderStyle.equalsIgnoreCase("text"))
736 accurateText = false;
739 int width = treeCanvas.getWidth();
740 int height = treeCanvas.getHeight();
744 JalviewFileChooser chooser = new JalviewFileChooser(
745 ImageMaker.EPS_EXTENSION, ImageMaker.EPS_EXTENSION);
746 chooser.setFileView(new JalviewFileView());
747 chooser.setDialogTitle(MessageManager
748 .getString("label.create_eps_from_tree"));
749 chooser.setToolTipText(MessageManager.getString("action.save"));
751 int value = chooser.showSaveDialog(this);
753 if (value != JalviewFileChooser.APPROVE_OPTION)
758 Cache.setProperty("LAST_DIRECTORY", chooser.getSelectedFile()
761 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
762 EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width, height);
764 pg.setAccurateTextMode(accurateText);
766 treeCanvas.draw(pg, width, height);
770 } catch (Exception ex)
772 ex.printStackTrace();
783 public void pngTree_actionPerformed(ActionEvent e)
785 int width = treeCanvas.getWidth();
786 int height = treeCanvas.getHeight();
790 JalviewFileChooser chooser = new JalviewFileChooser(
791 ImageMaker.PNG_EXTENSION, ImageMaker.PNG_DESCRIPTION);
793 chooser.setFileView(new jalview.io.JalviewFileView());
794 chooser.setDialogTitle(MessageManager
795 .getString("label.create_png_from_tree"));
796 chooser.setToolTipText(MessageManager.getString("action.save"));
798 int value = chooser.showSaveDialog(this);
800 if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
805 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
806 .getSelectedFile().getParent());
808 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
810 BufferedImage bi = new BufferedImage(width, height,
811 BufferedImage.TYPE_INT_RGB);
812 Graphics png = bi.getGraphics();
814 treeCanvas.draw(png, width, height);
816 ImageIO.write(bi, "png", out);
818 } catch (Exception ex)
820 ex.printStackTrace();
825 * change node labels to the annotation referred to by labelClass TODO:
826 * promote to a datamodel modification that can be undone TODO: make argument
827 * one case of a generic transformation function ie { undoStep = apply(Tree,
828 * TransformFunction)};
832 public void changeNames(final String labelClass)
834 tree.applyToNodes(new NodeTransformI()
838 public void transform(BinaryNode node)
840 if (node instanceof SequenceNode
841 && !((SequenceNode) node).isPlaceholder()
842 && !((SequenceNode) node).isDummy())
844 String newname = null;
845 SequenceI sq = (SequenceI) ((SequenceNode) node).element();
848 // search dbrefs, features and annotation
849 DBRefEntry[] refs = jalview.util.DBRefUtils.selectRefs(
851 new String[] { labelClass.toUpperCase() });
854 for (int i = 0; i < refs.length; i++)
858 newname = new String(refs[i].getAccessionId());
862 newname = newname + "; " + refs[i].getAccessionId();
868 SequenceFeature sf[] = sq.getSequenceFeatures();
869 for (int i = 0; sf != null && i < sf.length; i++)
871 if (sf[i].getType().equals(labelClass))
875 newname = new String(sf[i].getDescription());
879 newname = newname + "; " + sf[i].getDescription();
887 String oldname = ((SequenceNode) node).getName();
888 // TODO : save in the undo object for this modification.
889 ((SequenceNode) node).setName(newname);