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.analysis.scoremodels.SimilarityParams;
27 import jalview.api.analysis.ScoreModelI;
28 import jalview.api.analysis.ViewBasedAnalysisI;
29 import jalview.bin.Cache;
30 import jalview.commands.CommandI;
31 import jalview.commands.OrderCommand;
32 import jalview.datamodel.Alignment;
33 import jalview.datamodel.AlignmentI;
34 import jalview.datamodel.AlignmentView;
35 import jalview.datamodel.BinaryNode;
36 import jalview.datamodel.ColumnSelection;
37 import jalview.datamodel.DBRefEntry;
38 import jalview.datamodel.NodeTransformI;
39 import jalview.datamodel.SequenceFeature;
40 import jalview.datamodel.SequenceI;
41 import jalview.datamodel.SequenceNode;
42 import jalview.io.JalviewFileChooser;
43 import jalview.io.JalviewFileView;
44 import jalview.io.NewickFile;
45 import jalview.jbgui.GTreePanel;
46 import jalview.util.ImageMaker;
47 import jalview.util.MessageManager;
48 import jalview.viewmodel.AlignmentViewport;
51 import java.awt.Graphics;
52 import java.awt.event.ActionEvent;
53 import java.awt.event.ActionListener;
54 import java.awt.image.BufferedImage;
55 import java.beans.PropertyChangeEvent;
56 import java.io.FileOutputStream;
57 import java.util.ArrayList;
58 import java.util.List;
60 import javax.imageio.ImageIO;
61 import javax.swing.ButtonGroup;
62 import javax.swing.JMenuItem;
63 import javax.swing.JRadioButtonMenuItem;
65 import org.jibble.epsgraphics.EpsGraphics2D;
73 public class TreePanel extends GTreePanel
79 TreeCanvas treeCanvas;
86 * Creates a new TreePanel object.
101 public TreePanel(AlignmentPanel ap, String type, String pwtype)
104 initTreePanel(ap, type, pwtype, null, null);
106 // We know this tree has distances. JBPNote TODO: prolly should add this as
107 // a userdefined default
108 // showDistances(true);
111 public TreePanel(AlignmentPanel av, String type, String pwtype,
112 NewickFile newtree, AlignmentView inputData)
115 initTreePanel(av, type, pwtype, newtree, inputData);
118 public AlignmentI getAlignment()
120 return treeCanvas.av.getAlignment();
123 public AlignmentViewport getViewPort()
125 return treeCanvas.av;
128 void initTreePanel(AlignmentPanel ap, String type, String pwtype,
129 NewickFile newTree, AlignmentView inputData)
134 this.pwtype = pwtype;
136 treeCanvas = new TreeCanvas(this, ap, scrollPane);
137 scrollPane.setViewportView(treeCanvas);
139 PaintRefresher.Register(this, ap.av.getSequenceSetId());
141 buildAssociatedViewMenu();
143 av.addPropertyChangeListener(new java.beans.PropertyChangeListener()
146 public void propertyChange(PropertyChangeEvent evt)
148 if (evt.getPropertyName().equals("alignment"))
152 System.out.println("tree is null");
153 // TODO: deal with case when a change event is received whilst a
154 // tree is still being calculated - should save reference for
155 // processing message later.
158 if (evt.getNewValue() == null)
161 .println("new alignment sequences vector value is null");
164 tree.updatePlaceHolders((List<SequenceI>) evt.getNewValue());
165 treeCanvas.nameHash.clear(); // reset the mapping between canvas
166 // rectangles and leafnodes
172 TreeLoader tl = new TreeLoader(newTree);
173 if (inputData != null)
175 tl.odata = inputData;
182 public void viewMenu_menuSelected()
184 buildAssociatedViewMenu();
187 void buildAssociatedViewMenu()
189 AlignmentPanel[] aps = PaintRefresher.getAssociatedPanels(av
190 .getSequenceSetId());
191 if (aps.length == 1 && treeCanvas.ap == aps[0])
193 associateLeavesMenu.setVisible(false);
197 associateLeavesMenu.setVisible(true);
199 if ((viewMenu.getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
201 viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
204 associateLeavesMenu.removeAll();
206 JRadioButtonMenuItem item;
207 ButtonGroup buttonGroup = new ButtonGroup();
208 int i, iSize = aps.length;
209 final TreePanel thisTreePanel = this;
210 for (i = 0; i < iSize; i++)
212 final AlignmentPanel ap = aps[i];
213 item = new JRadioButtonMenuItem(ap.av.viewName, ap == treeCanvas.ap);
214 buttonGroup.add(item);
215 item.addActionListener(new ActionListener()
218 public void actionPerformed(ActionEvent evt)
220 treeCanvas.applyToAllViews = false;
222 treeCanvas.av = ap.av;
223 PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
227 associateLeavesMenu.add(item);
230 final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
231 MessageManager.getString("label.all_views"));
232 buttonGroup.add(itemf);
233 itemf.setSelected(treeCanvas.applyToAllViews);
234 itemf.addActionListener(new ActionListener()
237 public void actionPerformed(ActionEvent evt)
239 treeCanvas.applyToAllViews = itemf.isSelected();
242 associateLeavesMenu.add(itemf);
246 class TreeLoader extends Thread
250 jalview.datamodel.AlignmentView odata = null;
252 public TreeLoader(NewickFile newtree)
254 this.newtree = newtree;
257 // Must be outside run(), as Jalview2XML tries to
258 // update distance/bootstrap visibility at the same time
259 showBootstrap(newtree.HasBootstrap());
260 showDistances(newtree.HasDistances());
272 tree = new NJTree(av.getAlignment().getSequencesArray(), newtree);
276 tree = new NJTree(av.getAlignment().getSequencesArray(), odata,
279 if (!tree.hasOriginalSequenceData())
281 allowOriginalSeqData(false);
288 boolean selview = av.getSelectionGroup() != null
289 && av.getSelectionGroup().getSize() > 1;
290 AlignmentView seqStrings = av.getAlignmentView(selview);
294 end = av.getAlignment().getWidth();
295 seqs = av.getAlignment().getSequencesArray();
299 start = av.getSelectionGroup().getStartRes();
300 end = av.getSelectionGroup().getEndRes() + 1;
301 seqs = av.getSelectionGroup().getSequencesInOrder(
304 ScoreModelI sm = configureScoreModel(pwtype);
305 tree = new NJTree(av, type, sm, SimilarityParams.Jalview);
309 tree.reCount(tree.getTopNode());
310 tree.findHeight(tree.getTopNode());
311 treeCanvas.setTree(tree);
312 treeCanvas.repaint();
313 av.setCurrentTree(tree);
314 if (av.getSortByTree())
316 sortByTree_actionPerformed();
321 public void showDistances(boolean b)
323 treeCanvas.setShowDistances(b);
324 distanceMenu.setSelected(b);
327 public void showBootstrap(boolean b)
329 treeCanvas.setShowBootstrap(b);
330 bootstrapMenu.setSelected(b);
333 public void showPlaceholders(boolean b)
335 placeholdersMenu.setState(b);
336 treeCanvas.setMarkPlaceholders(b);
339 private void allowOriginalSeqData(boolean b)
341 originalSeqData.setVisible(b);
347 * @return DOCUMENT ME!
349 public NJTree getTree()
361 public void textbox_actionPerformed(ActionEvent e)
363 CutAndPasteTransfer cap = new CutAndPasteTransfer();
365 String newTitle = getPanelTitle(type, pwtype);
367 NewickFile fout = new NewickFile(tree.getTopNode());
370 cap.setText(fout.print(tree.hasBootstrap(), tree.hasDistances(),
371 tree.hasRootDistance()));
372 Desktop.addInternalFrame(cap, newTitle, 500, 100);
373 } catch (OutOfMemoryError oom)
375 new OOMWarning("generating newick tree file", oom);
388 public void saveAsNewick_actionPerformed(ActionEvent e)
390 JalviewFileChooser chooser = new JalviewFileChooser(
391 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
392 chooser.setFileView(new JalviewFileView());
393 chooser.setDialogTitle(MessageManager
394 .getString("label.save_tree_as_newick"));
395 chooser.setToolTipText(MessageManager.getString("action.save"));
397 int value = chooser.showSaveDialog(null);
399 if (value == JalviewFileChooser.APPROVE_OPTION)
401 String choice = chooser.getSelectedFile().getPath();
402 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
403 .getSelectedFile().getParent());
407 jalview.io.NewickFile fout = new jalview.io.NewickFile(
409 String output = fout.print(tree.hasBootstrap(),
410 tree.hasDistances(), tree.hasRootDistance());
411 java.io.PrintWriter out = new java.io.PrintWriter(
412 new java.io.FileWriter(choice));
415 } catch (Exception ex)
417 ex.printStackTrace();
429 public void printMenu_actionPerformed(ActionEvent e)
431 // Putting in a thread avoids Swing painting problems
432 treeCanvas.startPrinting();
436 public void originalSeqData_actionPerformed(ActionEvent e)
438 if (!tree.hasOriginalSequenceData())
440 jalview.bin.Cache.log
441 .info("Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
444 // decide if av alignment is sufficiently different to original data to
445 // warrant a new window to be created
446 // create new alignmnt window with hidden regions (unhiding hidden regions
447 // yields unaligned seqs)
448 // or create a selection box around columns in alignment view
449 // test Alignment(SeqCigar[])
453 // we try to get the associated view's gap character
454 // but this may fail if the view was closed...
455 gc = av.getGapCharacter();
457 } catch (Exception ex)
461 Object[] alAndColsel = tree.seqData.getAlignmentAndColumnSelection(gc);
463 if (alAndColsel != null && alAndColsel[0] != null)
465 // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
467 AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
468 AlignmentI dataset = (av != null && av.getAlignment() != null) ? av
469 .getAlignment().getDataset() : null;
472 al.setDataset(dataset);
478 AlignFrame af = new AlignFrame(al,
479 (ColumnSelection) alAndColsel[1], AlignFrame.DEFAULT_WIDTH,
480 AlignFrame.DEFAULT_HEIGHT);
482 // >>>This is a fix for the moment, until a better solution is
484 // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
486 // af.addSortByOrderMenuItem(ServiceName + " Ordering",
489 Desktop.addInternalFrame(af, MessageManager.formatMessage(
490 "label.original_data_for_params",
491 new Object[] { this.title }), AlignFrame.DEFAULT_WIDTH,
492 AlignFrame.DEFAULT_HEIGHT);
504 public void fitToWindow_actionPerformed(ActionEvent e)
506 treeCanvas.fitToWindow = fitToWindow.isSelected();
511 * sort the associated alignment view by the current tree.
516 public void sortByTree_actionPerformed()
519 if (treeCanvas.applyToAllViews)
521 final ArrayList<CommandI> commands = new ArrayList<CommandI>();
522 for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
523 .getSequenceSetId()))
525 commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
527 av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
531 public void undoCommand(AlignmentI[] views)
533 for (CommandI tsort : commands)
535 tsort.undoCommand(views);
542 return commands.size();
546 public String getDescription()
548 return "Tree Sort (many views)";
552 public void doCommand(AlignmentI[] views)
555 for (CommandI tsort : commands)
557 tsort.doCommand(views);
561 for (AlignmentPanel ap : PaintRefresher.getAssociatedPanels(av
562 .getSequenceSetId()))
564 // ensure all the alignFrames refresh their GI after adding an undo item
565 ap.alignFrame.updateEditMenuBar();
570 treeCanvas.ap.alignFrame
571 .addHistoryItem(sortAlignmentIn(treeCanvas.ap));
576 public CommandI sortAlignmentIn(AlignmentPanel ap)
578 AlignmentViewport av = ap.av;
579 SequenceI[] oldOrder = av.getAlignment().getSequencesArray();
580 AlignmentSorter.sortByTree(av.getAlignment(), tree);
582 undo = new OrderCommand("Tree Sort", oldOrder, av.getAlignment());
584 ap.paintAlignment(true);
595 public void font_actionPerformed(ActionEvent e)
597 if (treeCanvas == null)
602 new FontChooser(this);
605 public Font getTreeFont()
607 return treeCanvas.font;
610 public void setTreeFont(Font font)
612 if (treeCanvas != null)
614 treeCanvas.setFont(font);
625 public void distanceMenu_actionPerformed(ActionEvent e)
627 treeCanvas.setShowDistances(distanceMenu.isSelected());
637 public void bootstrapMenu_actionPerformed(ActionEvent e)
639 treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
649 public void placeholdersMenu_actionPerformed(ActionEvent e)
651 treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
661 public void epsTree_actionPerformed(ActionEvent e)
663 boolean accurateText = true;
665 String renderStyle = jalview.bin.Cache.getDefault("EPS_RENDERING",
668 // If we need to prompt, and if the GUI is visible then
669 // Prompt for EPS rendering style
670 if (renderStyle.equalsIgnoreCase("Prompt each time")
671 && !(System.getProperty("java.awt.headless") != null && System
672 .getProperty("java.awt.headless").equals("true")))
674 EPSOptions eps = new EPSOptions();
675 renderStyle = eps.getValue();
677 if (renderStyle == null || eps.cancelled)
684 if (renderStyle.equalsIgnoreCase("text"))
686 accurateText = false;
689 int width = treeCanvas.getWidth();
690 int height = treeCanvas.getHeight();
694 JalviewFileChooser chooser = new JalviewFileChooser(
695 ImageMaker.EPS_EXTENSION, ImageMaker.EPS_EXTENSION);
696 chooser.setFileView(new JalviewFileView());
697 chooser.setDialogTitle(MessageManager
698 .getString("label.create_eps_from_tree"));
699 chooser.setToolTipText(MessageManager.getString("action.save"));
701 int value = chooser.showSaveDialog(this);
703 if (value != JalviewFileChooser.APPROVE_OPTION)
708 Cache.setProperty("LAST_DIRECTORY", chooser.getSelectedFile()
711 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
712 EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width, height);
714 pg.setAccurateTextMode(accurateText);
716 treeCanvas.draw(pg, width, height);
720 } catch (Exception ex)
722 ex.printStackTrace();
733 public void pngTree_actionPerformed(ActionEvent e)
735 int width = treeCanvas.getWidth();
736 int height = treeCanvas.getHeight();
740 JalviewFileChooser chooser = new JalviewFileChooser(
741 ImageMaker.PNG_EXTENSION, ImageMaker.PNG_DESCRIPTION);
743 chooser.setFileView(new jalview.io.JalviewFileView());
744 chooser.setDialogTitle(MessageManager
745 .getString("label.create_png_from_tree"));
746 chooser.setToolTipText(MessageManager.getString("action.save"));
748 int value = chooser.showSaveDialog(this);
750 if (value != jalview.io.JalviewFileChooser.APPROVE_OPTION)
755 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
756 .getSelectedFile().getParent());
758 FileOutputStream out = new FileOutputStream(chooser.getSelectedFile());
760 BufferedImage bi = new BufferedImage(width, height,
761 BufferedImage.TYPE_INT_RGB);
762 Graphics png = bi.getGraphics();
764 treeCanvas.draw(png, width, height);
766 ImageIO.write(bi, "png", out);
768 } catch (Exception ex)
770 ex.printStackTrace();
775 * change node labels to the annotation referred to by labelClass TODO:
776 * promote to a datamodel modification that can be undone TODO: make argument
777 * one case of a generic transformation function ie { undoStep = apply(Tree,
778 * TransformFunction)};
782 public void changeNames(final String labelClass)
784 tree.applyToNodes(new NodeTransformI()
788 public void transform(BinaryNode node)
790 if (node instanceof SequenceNode
791 && !((SequenceNode) node).isPlaceholder()
792 && !((SequenceNode) node).isDummy())
794 String newname = null;
795 SequenceI sq = (SequenceI) ((SequenceNode) node).element();
798 // search dbrefs, features and annotation
799 DBRefEntry[] refs = jalview.util.DBRefUtils.selectRefs(
801 new String[] { labelClass.toUpperCase() });
804 for (int i = 0; i < refs.length; i++)
808 newname = new String(refs[i].getAccessionId());
812 newname = newname + "; " + refs[i].getAccessionId();
818 SequenceFeature sf[] = sq.getSequenceFeatures();
819 for (int i = 0; sf != null && i < sf.length; i++)
821 if (sf[i].getType().equals(labelClass))
825 newname = new String(sf[i].getDescription());
829 newname = newname + "; " + sf[i].getDescription();
837 String oldname = ((SequenceNode) node).getName();
838 // TODO : save in the undo object for this modification.
839 ((SequenceNode) node).setName(newname);
847 * Formats a localised title for the tree panel, like
849 * Neighbour Joining Using BLOSUM62
851 * For a tree loaded from file, just uses the file name
854 * NJ or AV or FromFile
855 * @param modelOrFileName
858 public static String getPanelTitle(String treeType, String modelOrFileName)
860 if (NJTree.FROM_FILE.equals(treeType))
862 return modelOrFileName;
866 * i18n description of Neighbour Joining or Average Distance method
868 String treecalcnm = MessageManager.getString("label.tree_calc_"
869 + treeType.toLowerCase());
872 * i18n description (if any) of score model used
874 String smn = MessageManager.getStringOrReturn("label.score_model_",
878 * put them together as <method> Using <model>
880 final String ttl = MessageManager.formatMessage("label.treecalc_title",
886 * Gets the score model for the given name. If the score model is one that
887 * requires to get state data from the current view, allow it to do so
892 protected ScoreModelI configureScoreModel(String modelName)
894 ScoreModelI sm = ScoreModels.getInstance().forName(modelName);
895 if (sm instanceof ViewBasedAnalysisI)
899 sm = sm.getClass().newInstance();
900 ((ViewBasedAnalysisI) sm).configureFromAlignmentView(treeCanvas.ap);
901 } catch (Exception q)
903 Cache.log.error("Couldn't create a scoremodel instance for "