minimal fixes - probably not valid since forester jar out of sync
[jalview.git] / src / jalview / gui / TreePanel.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.gui;
22
23 import java.util.Locale;
24
25 import jalview.analysis.AlignmentSorter;
26 import jalview.analysis.TreeModel;
27 import jalview.api.analysis.SimilarityParamsI;
28 import jalview.bin.Cache;
29 import jalview.bin.Console;
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.DBRefEntry;
37 import jalview.datamodel.HiddenColumns;
38 import jalview.datamodel.NodeTransformI;
39 import jalview.datamodel.SequenceFeature;
40 import jalview.datamodel.SequenceI;
41 import jalview.datamodel.SequenceNode;
42 import jalview.gui.ImageExporter.ImageWriterI;
43 import jalview.io.JalviewFileChooser;
44 import jalview.io.JalviewFileView;
45 import jalview.io.NewickFile;
46 import jalview.jbgui.GTreePanel;
47 import jalview.util.ImageMaker.TYPE;
48 import jalview.util.MessageManager;
49 import jalview.viewmodel.AlignmentViewport;
50
51 import java.awt.Font;
52 import java.awt.Graphics;
53 import java.awt.event.ActionEvent;
54 import java.awt.event.ActionListener;
55 import java.beans.PropertyChangeEvent;
56 import java.beans.PropertyChangeListener;
57 import java.io.File;
58 import java.io.FileOutputStream;
59 import java.util.ArrayList;
60 import java.util.List;
61
62 import javax.swing.ButtonGroup;
63 import javax.swing.JMenuItem;
64 import javax.swing.JRadioButtonMenuItem;
65
66 import org.jibble.epsgraphics.EpsGraphics2D;
67
68 /**
69  * DOCUMENT ME!
70  * 
71  * @author $author$
72  * @version $Revision$
73  */
74 public class TreePanel extends GTreePanel
75 {
76   String substitutionMatrix;
77
78   String treeType;
79
80   String treeTitle; // if tree loaded
81
82   SimilarityParamsI similarityParams;
83
84   TreeCanvas treeCanvas;
85
86   TreeModel tree;
87
88   private AlignViewport av;
89
90   /**
91    * Creates a new TreePanel object.
92    * 
93    * @param ap
94    * @param tree
95    * @param treeType
96    * @param substitutionMatrix
97    */
98   public TreePanel(AlignmentPanel ap, TreeModel tree, String treeType,
99           String substitutionMatrix)
100   {
101     super();
102     this.treeType = treeType;
103     this.substitutionMatrix = substitutionMatrix;
104     this.tree = tree;
105     initTreePanel(ap, tree);
106
107     // We know this tree has distances. JBPNote TODO: prolly should add this as
108     // a userdefined default
109     // showDistances(true);
110   }
111
112   /**
113    * Creates a new TreePanel object.
114    * 
115    * @param alignPanel
116    * @param newtree
117    * @param theTitle
118    * @param inputData
119    */
120   public TreePanel(AlignmentPanel alignPanel, NewickFile newtree,
121           String theTitle, AlignmentView inputData)
122   {
123     super();
124     this.treeTitle = theTitle;
125     initTreePanel(alignPanel, newtree, inputData);
126   }
127
128   public AlignmentI getAlignment()
129   {
130     return getTreeCanvas().getViewport().getAlignment();
131   }
132
133   public AlignmentViewport getViewPort()
134   {
135     // @Mungo - Why don't we return our own viewport ???
136     return getTreeCanvas().getViewport();
137   }
138
139   /**
140    * Initialize a tree panel based on a calculated tree
141    * 
142    * @param ap
143    * @param tree
144    */
145   void initTreePanel(AlignmentPanel ap, TreeModel tree)
146   {
147     buildTreeCanvas(ap);
148
149     TreeLoader tl = new TreeLoader(null, null);
150     tl.start();
151
152   }
153
154   /**
155    * Initialize a tree panel based on a loaded in tree file.
156    * 
157    * @param ap
158    * @param loadedTree
159    * @param inputData
160    */
161   void initTreePanel(AlignmentPanel ap, 
162           NewickFile loadedTree, AlignmentView inputData)
163   {
164     buildTreeCanvas(ap);
165
166     TreeLoader tl = new TreeLoader(loadedTree, inputData);
167     tl.start();
168   }
169
170 public void buildTreeCanvas(AlignmentPanel ap) { 
171      av = ap.av;
172
173     treeCanvas = new TreeCanvas(this, ap, scrollPane);
174     scrollPane.setViewportView(treeCanvas);
175
176
177     PaintRefresher.Register(this, ap.av.getSequenceSetId());
178
179     buildAssociatedViewMenu();
180
181     av.addPropertyChangeListener(new java.beans.PropertyChangeListener()
182     {
183       @Override
184       public void propertyChange(PropertyChangeEvent evt)
185       {
186         if (evt.getPropertyName().equals("alignment"))
187         {
188           if (tree == null)
189           {
190             System.out.println("tree is null");
191             // TODO: deal with case when a change event is received whilst a
192             // tree is still being calculated - should save reference for
193             // processing message later.
194             return;
195           }
196           if (evt.getNewValue() == null)
197           {
198             System.out.println(
199                     "new alignment sequences vector value is null");
200           }
201
202           tree.updatePlaceHolders((List<SequenceI>) evt.getNewValue());
203           treeCanvas.nameHash.clear(); // reset the mapping between canvas
204           // rectangles and leafnodes
205           repaint();
206         }
207       }
208     });
209
210
211   
212
213   }
214
215   @Override
216   public void viewMenu_menuSelected()
217   {
218     buildAssociatedViewMenu();
219   }
220
221   void buildAssociatedViewMenu()
222   {
223     AlignmentPanel[] aps = PaintRefresher
224             .getAssociatedPanels(av.getSequenceSetId());
225     if (aps.length == 1 && getTreeCanvas().getAssociatedPanel() == aps[0])
226     {
227       associateLeavesMenu.setVisible(false);
228       return;
229     }
230
231     associateLeavesMenu.setVisible(true);
232
233     if ((viewMenu
234             .getItem(viewMenu.getItemCount() - 2) instanceof JMenuItem))
235     {
236       viewMenu.insertSeparator(viewMenu.getItemCount() - 1);
237     }
238
239     associateLeavesMenu.removeAll();
240
241     JRadioButtonMenuItem item;
242     ButtonGroup buttonGroup = new ButtonGroup();
243     int i, iSize = aps.length;
244     final TreePanel thisTreePanel = this;
245     for (i = 0; i < iSize; i++)
246     {
247       final AlignmentPanel ap = aps[i];
248       item = new JRadioButtonMenuItem(ap.av.getViewName(),
249               ap == treeCanvas.getAssociatedPanel());
250       buttonGroup.add(item);
251       item.addActionListener(new ActionListener()
252       {
253         @Override
254         public void actionPerformed(ActionEvent evt)
255         {
256           treeCanvas.applyToAllViews = false;
257           treeCanvas.setAssociatedPanel(ap);
258           treeCanvas.setViewport(ap.av);
259           PaintRefresher.Register(thisTreePanel, ap.av.getSequenceSetId());
260         }
261       });
262
263       associateLeavesMenu.add(item);
264     }
265
266     final JRadioButtonMenuItem itemf = new JRadioButtonMenuItem(
267             MessageManager.getString("label.all_views"));
268     buttonGroup.add(itemf);
269     itemf.setSelected(treeCanvas.applyToAllViews);
270     itemf.addActionListener(new ActionListener()
271     {
272       @Override
273       public void actionPerformed(ActionEvent evt)
274       {
275         treeCanvas.applyToAllViews = itemf.isSelected();
276       }
277     });
278     associateLeavesMenu.add(itemf);
279
280   }
281
282   class TreeLoader extends Thread
283   {
284     private NewickFile newTree;
285
286     private AlignmentView odata = null;
287
288     public TreeLoader(NewickFile newickFile, AlignmentView inputData)
289     {
290       this.newTree = newickFile;
291       this.odata = inputData;
292
293       if (newTree != null)
294       {
295         // Must be outside run(), as Jalview2XML tries to
296         // update distance/bootstrap visibility at the same time
297         showBootstrap(newTree.hasBootstrap());
298         showDistances(newTree.hasDistances());
299
300       }
301
302     }
303
304     @Override
305     public void run()
306     {
307
308       if (newTree != null)
309       {
310         tree = new TreeModel(av.getAlignment().getSequencesArray(), odata,
311                 newTree);
312         if (tree.getOriginalData() == null)
313         {
314           originalSeqData.setVisible(false);
315         }
316       }
317       showTree(tree);
318
319     }
320       
321     public void showTree(TreeModel tree)
322     {
323       tree.reCount(tree.getTopNode());
324       tree.findHeight(tree.getTopNode());
325       treeCanvas.setTree(tree);
326       treeCanvas.repaint();
327
328       av.setCurrentTree(tree);
329       if (av.getSortByTree())
330       {
331         sortByTree_actionPerformed();
332       }
333
334     }
335   }
336
337   public void showDistances(boolean b)
338   {
339     treeCanvas.setShowDistances(b);
340     distanceMenu.setSelected(b);
341   }
342
343   public void showBootstrap(boolean b)
344   {
345     treeCanvas.setShowBootstrap(b);
346     bootstrapMenu.setSelected(b);
347   }
348
349   public void showPlaceholders(boolean b)
350   {
351     placeholdersMenu.setState(b);
352     treeCanvas.setMarkPlaceholders(b);
353   }
354
355   /**
356    * DOCUMENT ME!
357    * 
358    * @return DOCUMENT ME!
359    */
360   public TreeModel getTree()
361   {
362     return tree;
363   }
364
365   /**
366    * DOCUMENT ME!
367    * 
368    * @param e
369    *          DOCUMENT ME!
370    */
371   @Override
372   public void textbox_actionPerformed(ActionEvent e)
373   {
374     CutAndPasteTransfer cap = new CutAndPasteTransfer();
375
376     String newTitle = getPanelTitle();
377
378     NewickFile fout = new NewickFile(tree.getTopNode());
379     try
380     {
381       cap.setText(fout.print(tree.hasBootstrap(), tree.hasDistances(),
382               tree.hasRootDistance()));
383       Desktop.addInternalFrame(cap, newTitle, 500, 100);
384     } catch (OutOfMemoryError oom)
385     {
386       new OOMWarning("generating newick tree file", oom);
387       cap.dispose();
388     }
389
390   }
391
392   /**
393    * DOCUMENT ME!
394    * 
395    * @param e
396    *          DOCUMENT ME!
397    */
398   @Override
399   public void saveAsNewick_actionPerformed(ActionEvent e)
400   {
401     // TODO: JAL-3048 save newick file for Jalview-JS
402     JalviewFileChooser chooser = new JalviewFileChooser(
403             Cache.getProperty("LAST_DIRECTORY"));
404     chooser.setFileView(new JalviewFileView());
405     chooser.setDialogTitle(
406             MessageManager.getString("label.save_tree_as_newick"));
407     chooser.setToolTipText(MessageManager.getString("action.save"));
408
409     int value = chooser.showSaveDialog(null);
410
411     if (value == JalviewFileChooser.APPROVE_OPTION)
412     {
413       String choice = chooser.getSelectedFile().getPath();
414       Cache.setProperty("LAST_DIRECTORY",
415               chooser.getSelectedFile().getParent());
416
417       try
418       {
419         jalview.io.NewickFile fout = new jalview.io.NewickFile(
420                 tree.getTopNode());
421         String output = fout.print(tree.hasBootstrap(), tree.hasDistances(),
422                 tree.hasRootDistance());
423         java.io.PrintWriter out = new java.io.PrintWriter(
424                 new java.io.FileWriter(choice));
425         out.println(output);
426         out.close();
427       } catch (Exception ex)
428       {
429         ex.printStackTrace();
430       }
431     }
432   }
433
434   /**
435    * DOCUMENT ME!
436    * 
437    * @param e
438    *          DOCUMENT ME!
439    */
440   @Override
441   public void printMenu_actionPerformed(ActionEvent e)
442   {
443     // Putting in a thread avoids Swing painting problems
444     treeCanvas.startPrinting();
445   }
446
447   @Override
448   public void originalSeqData_actionPerformed(ActionEvent e)
449   {
450     AlignmentView originalData = tree.getOriginalData();
451     if (originalData == null)
452     {
453       Console.info(
454               "Unexpected call to originalSeqData_actionPerformed - should have hidden this menu action.");
455       return;
456     }
457     // decide if av alignment is sufficiently different to original data to
458     // warrant a new window to be created
459     // create new alignmnt window with hidden regions (unhiding hidden regions
460     // yields unaligned seqs)
461     // or create a selection box around columns in alignment view
462     // test Alignment(SeqCigar[])
463     char gc = '-';
464     try
465     {
466       // we try to get the associated view's gap character
467       // but this may fail if the view was closed...
468       gc = av.getGapCharacter();
469
470     } catch (Exception ex)
471     {
472     }
473
474     Object[] alAndColsel = originalData.getAlignmentAndHiddenColumns(gc);
475
476     if (alAndColsel != null && alAndColsel[0] != null)
477     {
478       // AlignmentOrder origorder = new AlignmentOrder(alAndColsel[0]);
479
480       AlignmentI al = new Alignment((SequenceI[]) alAndColsel[0]);
481       AlignmentI dataset = (av != null && av.getAlignment() != null)
482               ? av.getAlignment().getDataset()
483               : null;
484       if (dataset != null)
485       {
486         al.setDataset(dataset);
487       }
488
489       if (true)
490       {
491         // make a new frame!
492         AlignFrame af = new AlignFrame(al, (HiddenColumns) alAndColsel[1],
493                 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
494
495         // >>>This is a fix for the moment, until a better solution is
496         // found!!<<<
497         // af.getFeatureRenderer().transferSettings(alignFrame.getFeatureRenderer());
498
499         // af.addSortByOrderMenuItem(ServiceName + " Ordering",
500         // msaorder);
501
502         Desktop.addInternalFrame(af, MessageManager.formatMessage(
503                 "label.original_data_for_params", new Object[]
504                 { this.title }), AlignFrame.DEFAULT_WIDTH,
505                 AlignFrame.DEFAULT_HEIGHT);
506       }
507     }
508   }
509
510   /**
511    * DOCUMENT ME!
512    * 
513    * @param e
514    *          DOCUMENT ME!
515    */
516   @Override
517   public void fitToWindow_actionPerformed(ActionEvent e)
518   {
519     treeCanvas.fitToWindow = fitToWindow.isSelected();
520     repaint();
521   }
522
523   /**
524    * sort the associated alignment view by the current tree.
525    * 
526    * @param e
527    */
528   @Override
529   public void sortByTree_actionPerformed()// modify for Aptx
530   {
531
532     if (treeCanvas.applyToAllViews)
533     {
534       final ArrayList<CommandI> commands = new ArrayList<>();
535       for (AlignmentPanel ap : PaintRefresher
536               .getAssociatedPanels(av.getSequenceSetId()))
537       {
538         commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
539       }
540       av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
541       {
542
543         @Override
544         public void undoCommand(AlignmentI[] views)
545         {
546           for (CommandI tsort : commands)
547           {
548             tsort.undoCommand(views);
549           }
550         }
551
552         @Override
553         public int getSize()
554         {
555           return commands.size();
556         }
557
558         @Override
559         public String getDescription()
560         {
561           return "Tree Sort (many views)";
562         }
563
564         @Override
565         public void doCommand(AlignmentI[] views)
566         {
567
568           for (CommandI tsort : commands)
569           {
570             tsort.doCommand(views);
571           }
572         }
573       });
574       for (AlignmentPanel ap : PaintRefresher
575               .getAssociatedPanels(av.getSequenceSetId()))
576       {
577         // ensure all the alignFrames refresh their GI after adding an undo item
578         ap.alignFrame.updateEditMenuBar();
579       }
580     }
581     else
582     {
583       treeCanvas.getAssociatedPanel().alignFrame.addHistoryItem(
584               sortAlignmentIn(treeCanvas.getAssociatedPanel()));
585     }
586
587   }
588
589   public CommandI sortAlignmentIn(AlignmentPanel ap)
590   {
591     // TODO: move to alignment view controller
592     AlignmentViewport viewport = ap.av;
593     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
594     AlignmentSorter.sortByTree(viewport.getAlignment(), tree);
595     CommandI undo;
596     undo = new OrderCommand("Tree Sort", oldOrder, viewport.getAlignment());
597
598     ap.paintAlignment(true, false);
599     return undo;
600   }
601
602   /**
603    * DOCUMENT ME!
604    * 
605    * @param e
606    *          DOCUMENT ME!
607    */
608   @Override
609   public void font_actionPerformed(ActionEvent e)
610   {
611     if (treeCanvas == null)
612     {
613       return;
614     }
615
616     new FontChooser(this);
617   }
618
619   public Font getTreeFont()
620   {
621     return treeCanvas.font;
622   }
623
624   public void setTreeFont(Font f)
625   {
626     if (treeCanvas != null)
627     {
628       treeCanvas.setFont(f);
629     }
630   }
631
632   /**
633    * DOCUMENT ME!
634    * 
635    * @param e
636    *          DOCUMENT ME!
637    */
638   @Override
639   public void distanceMenu_actionPerformed(ActionEvent e)
640   {
641     treeCanvas.setShowDistances(distanceMenu.isSelected());
642   }
643
644   /**
645    * DOCUMENT ME!
646    * 
647    * @param e
648    *          DOCUMENT ME!
649    */
650   @Override
651   public void bootstrapMenu_actionPerformed(ActionEvent e)
652   {
653     treeCanvas.setShowBootstrap(bootstrapMenu.isSelected());
654   }
655
656   /**
657    * DOCUMENT ME!
658    * 
659    * @param e
660    *          DOCUMENT ME!
661    */
662   @Override
663   public void placeholdersMenu_actionPerformed(ActionEvent e)
664   {
665     treeCanvas.setMarkPlaceholders(placeholdersMenu.isSelected());
666   }
667
668   /**
669    * Outputs the Tree in image format (currently EPS or PNG). The user is
670    * prompted for the file to save to, and for EPS (unless a preference is
671    * already set) for the choice of Text or Lineart for character rendering.
672    */
673   @Override
674   public void writeTreeImage(TYPE imageFormat)
675   {
676     int width = treeCanvas.getWidth();
677     int height = treeCanvas.getHeight();
678     ImageWriterI writer = new ImageWriterI()
679     {
680       @Override
681       public void exportImage(Graphics g) throws Exception
682       {
683         treeCanvas.draw(g, width, height);
684       }
685     };
686     String tree = MessageManager.getString("label.tree");
687     ImageExporter exporter = new ImageExporter(writer, null, imageFormat,
688             tree);
689     exporter.doExport(null, this, width, height,
690             tree.toLowerCase(Locale.ROOT));
691   }
692
693   /**
694    * change node labels to the annotation referred to by labelClass TODO:
695    * promote to a datamodel modification that can be undone TODO: make argument
696    * one case of a generic transformation function ie { undoStep = apply(Tree,
697    * TransformFunction)};
698    * 
699    * @param labelClass
700    */
701   public void changeNames(final String labelClass)
702   {
703     tree.applyToNodes(new NodeTransformI()
704     {
705
706       @Override
707       public void transform(BinaryNode node)
708       {
709         if (node instanceof SequenceNode
710                 && !((SequenceNode) node).isPlaceholder()
711                 && !((SequenceNode) node).isDummy())
712         {
713           String newname = null;
714           SequenceI sq = (SequenceI) ((SequenceNode) node).element();
715           if (sq != null)
716           {
717             // search dbrefs, features and annotation
718             List<DBRefEntry> refs = jalview.util.DBRefUtils
719                     .selectRefs(sq.getDBRefs(), new String[]
720                     { labelClass.toUpperCase(Locale.ROOT) });
721             if (refs != null)
722             {
723               for (int i = 0, ni = refs.size(); i < ni; i++)
724               {
725                 if (newname == null)
726                 {
727                   newname = new String(refs.get(i).getAccessionId());
728                 }
729                 else
730                 {
731                   newname += "; " + refs.get(i).getAccessionId();
732                 }
733               }
734             }
735             if (newname == null)
736             {
737               List<SequenceFeature> features = sq.getFeatures()
738                       .getPositionalFeatures(labelClass);
739               for (SequenceFeature feature : features)
740               {
741                 if (newname == null)
742                 {
743                   newname = feature.getDescription();
744                 }
745                 else
746                 {
747                   newname = newname + "; " + feature.getDescription();
748                 }
749               }
750             }
751           }
752           if (newname != null)
753           {
754             // String oldname = ((SequenceNode) node).getName();
755             // TODO : save oldname in the undo object for this modification.
756             ((SequenceNode) node).setName(newname);
757           }
758         }
759       }
760     });
761   }
762
763   /**
764    * Formats a localised title for the tree panel, like
765    * <p>
766    * Neighbour Joining Using BLOSUM62
767    * <p>
768    * For a tree loaded from file, just uses the file name
769    * 
770    * @return
771    */
772   public String getPanelTitle() // to be moved/fixed
773   {
774     if (treeTitle != null)
775     {
776       return treeTitle;
777     }
778     else
779     {
780     /*
781      * i18n description of Neighbour Joining or Average Distance method
782      */
783     String treecalcnm = MessageManager.getString(
784             "label.tree_calc_" + treeType.toLowerCase(Locale.ROOT));
785
786     /*
787      * short score model name (long description can be too long)
788      */
789     String smn = substitutionMatrix;
790
791     /*
792      * put them together as <method> Using <model>
793      */
794     final String ttl = MessageManager.formatMessage("label.calc_title",
795             treecalcnm, smn);
796       return ttl;
797     }
798   }
799
800   /**
801    * Builds an EPS image and writes it to the specified file.
802    * 
803    * @param outFile
804    * @param textOption
805    *          true for Text character rendering, false for Lineart
806    */
807   protected void writeEpsFile(File outFile, boolean textOption)
808   {
809     try
810     {
811       int width = treeCanvas.getWidth();
812       int height = treeCanvas.getHeight();
813
814       FileOutputStream out = new FileOutputStream(outFile);
815       EpsGraphics2D pg = new EpsGraphics2D("Tree", out, 0, 0, width,
816               height);
817       pg.setAccurateTextMode(!textOption);
818       treeCanvas.draw(pg, width, height);
819
820       pg.flush();
821       pg.close();
822     } catch (Exception ex)
823     {
824       System.err.println("Error writing tree as EPS");
825       ex.printStackTrace();
826     }
827   }
828
829   public AlignViewport getViewport()
830   {
831     return av;
832   }
833
834   public void setViewport(AlignViewport av)
835   {
836     this.av = av;
837   }
838
839   public TreeCanvas getTreeCanvas()
840   {
841     return treeCanvas;
842   }
843 }