8c3e39a2198f64575d6bd7ad55c010159243466c
[jalview.git] / src / jalview / appletgui / TreeCanvas.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.appletgui;
22
23 import jalview.analysis.Conservation;
24 import jalview.analysis.TreeModel;
25 import jalview.api.AlignViewportI;
26 import jalview.datamodel.BinaryNode;
27 import jalview.datamodel.Sequence;
28 import jalview.datamodel.SequenceGroup;
29 import jalview.datamodel.SequenceI;
30 import jalview.datamodel.SequenceNode;
31 import jalview.schemes.ColourSchemeI;
32 import jalview.schemes.ColourSchemeProperty;
33 import jalview.schemes.UserColourScheme;
34 import jalview.util.Format;
35 import jalview.util.MappingUtils;
36 import jalview.viewmodel.AlignmentViewport;
37
38 import java.awt.Color;
39 import java.awt.Dimension;
40 import java.awt.Font;
41 import java.awt.FontMetrics;
42 import java.awt.Graphics;
43 import java.awt.Panel;
44 import java.awt.Point;
45 import java.awt.Rectangle;
46 import java.awt.ScrollPane;
47 import java.awt.event.MouseEvent;
48 import java.awt.event.MouseListener;
49 import java.awt.event.MouseMotionListener;
50 import java.util.Enumeration;
51 import java.util.Hashtable;
52 import java.util.List;
53 import java.util.Vector;
54
55 public class TreeCanvas extends Panel
56         implements MouseListener, MouseMotionListener
57 {
58   TreeModel tree;
59
60   ScrollPane scrollPane;
61
62   AlignViewport av;
63
64   public static final String PLACEHOLDER = " * ";
65
66   Font font;
67
68   boolean fitToWindow = true;
69
70   boolean showDistances = false;
71
72   boolean showBootstrap = false;
73
74   boolean markPlaceholders = false;
75
76   int offx = 20;
77
78   int offy;
79
80   float threshold;
81
82   String longestName;
83
84   int labelLength = -1;
85
86   Hashtable nameHash = new Hashtable();
87
88   Hashtable nodeHash = new Hashtable();
89
90   BinaryNode highlightNode;
91
92   AlignmentPanel ap;
93
94   public TreeCanvas(AlignmentPanel ap, ScrollPane scroller)
95   {
96     this.ap = ap;
97     this.av = ap.av;
98     font = av.getFont();
99     scrollPane = scroller;
100     addMouseListener(this);
101     addMouseMotionListener(this);
102     setLayout(null);
103
104     PaintRefresher.Register(this, av.getSequenceSetId());
105   }
106
107   public void treeSelectionChanged(SequenceI sequence)
108   {
109     SequenceGroup selected = av.getSelectionGroup();
110     if (selected == null)
111     {
112       selected = new SequenceGroup();
113       av.setSelectionGroup(selected);
114     }
115
116     selected.setEndRes(av.getAlignment().getWidth() - 1);
117     selected.addOrRemove(sequence, true);
118   }
119
120   public void setTree(TreeModel tree2)
121   {
122     this.tree = tree2;
123     tree2.findHeight(tree2.getTopNode());
124
125     // Now have to calculate longest name based on the leaves
126     Vector<BinaryNode> leaves = tree2.findLeaves(tree2.getTopNode());
127     boolean has_placeholders = false;
128     longestName = "";
129
130     for (int i = 0; i < leaves.size(); i++)
131     {
132       BinaryNode lf = leaves.elementAt(i);
133
134       if (lf instanceof SequenceNode && ((SequenceNode)lf).isPlaceholder())
135       {
136         has_placeholders = true;
137       }
138
139       if (longestName.length() < ((Sequence) lf.element()).getName()
140               .length())
141       {
142         longestName = TreeCanvas.PLACEHOLDER
143                 + ((Sequence) lf.element()).getName();
144       }
145     }
146
147     setMarkPlaceholders(has_placeholders);
148   }
149
150   public void drawNode(Graphics g, BinaryNode node, float chunk,
151           double scale, int width, int offx, int offy)
152   {
153     if (node == null)
154     {
155       return;
156     }
157
158     if (node.left() == null && node.right() == null)
159     {
160       // Drawing leaf node
161
162       double height = node.height;
163       double dist = node.dist;
164
165       int xstart = (int) ((height - dist) * scale) + offx;
166       int xend = (int) (height * scale) + offx;
167
168       int ypos = (int) (node.ycount * chunk) + offy;
169
170       if (node.element() instanceof SequenceI)
171       {
172         SequenceI seq = (SequenceI) node.element();
173
174         if (av.getSequenceColour(seq) == Color.white)
175         {
176           g.setColor(Color.black);
177         }
178         else
179         {
180           g.setColor(av.getSequenceColour(seq).darker());
181         }
182
183       }
184       else
185       {
186         g.setColor(Color.black);
187       }
188
189       // Draw horizontal line
190       g.drawLine(xstart, ypos, xend, ypos);
191
192       String nodeLabel = "";
193       if (showDistances && node.dist > 0)
194       {
195         nodeLabel = new Format("%-.2f").form(node.dist);
196       }
197       if (showBootstrap)
198       {
199         int btstrap = node.getBootstrap();
200         if (btstrap > -1)
201         {
202           if (showDistances)
203           {
204             nodeLabel = nodeLabel + " : ";
205           }
206           nodeLabel = nodeLabel + String.valueOf(node.getBootstrap());
207         }
208       }
209       if (!nodeLabel.equals(""))
210       {
211         g.drawString(nodeLabel, xstart + 2, ypos - 2);
212       }
213
214       String name = (markPlaceholders && node instanceof SequenceNode && ((SequenceNode) node).isPlaceholder())
215               ? (PLACEHOLDER + node.getName())
216               : node.getName();
217       FontMetrics fm = g.getFontMetrics(font);
218       int charWidth = fm.stringWidth(name) + 3;
219       int charHeight = fm.getHeight();
220
221       Rectangle rect = new Rectangle(xend + 10, ypos - charHeight,
222               charWidth, charHeight);
223
224       nameHash.put(node.element(), rect);
225
226       // Colour selected leaves differently
227       SequenceGroup selected = av.getSelectionGroup();
228       if (selected != null
229               && selected.getSequences(null).contains(node.element()))
230       {
231         g.setColor(Color.gray);
232
233         g.fillRect(xend + 10, ypos - charHeight + 3, charWidth, charHeight);
234         g.setColor(Color.white);
235       }
236       g.drawString(name, xend + 10, ypos);
237       g.setColor(Color.black);
238     }
239     else
240     {
241       drawNode(g, (BinaryNode) node.left(), chunk, scale, width, offx,
242               offy);
243       drawNode(g, (BinaryNode) node.right(), chunk, scale, width, offx,
244               offy);
245
246       double height = node.height;
247       double dist = node.dist;
248
249       int xstart = (int) ((height - dist) * scale) + offx;
250       int xend = (int) (height * scale) + offx;
251       int ypos = (int) (node.ycount * chunk) + offy;
252
253       g.setColor(node.color.darker());
254
255       // Draw horizontal line
256       g.drawLine(xstart, ypos, xend, ypos);
257       if (node == highlightNode)
258       {
259         g.fillRect(xend - 3, ypos - 3, 6, 6);
260       }
261       else
262       {
263         g.fillRect(xend - 2, ypos - 2, 4, 4);
264       }
265
266       int ystart = (int) (node.left() == null ? 0
267               : (((BinaryNode) node.left()).ycount * chunk)) + offy;
268       int yend = (int) (node.right() == null ? 0
269               : (((BinaryNode) node.right()).ycount * chunk)) + offy;
270
271       Rectangle pos = new Rectangle(xend - 2, ypos - 2, 5, 5);
272       nodeHash.put(node, pos);
273
274       g.drawLine((int) (height * scale) + offx, ystart,
275               (int) (height * scale) + offx, yend);
276
277       String nodeLabel = "";
278
279       if (showDistances && (node.dist > 0))
280       {
281         nodeLabel = new Format("%-.2f").form(node.dist);
282       }
283
284       if (showBootstrap)
285       {
286         int btstrap = node.getBootstrap();
287         if (btstrap > -1)
288         {
289           if (showDistances)
290           {
291             nodeLabel = nodeLabel + " : ";
292           }
293           nodeLabel = nodeLabel + String.valueOf(node.getBootstrap());
294         }
295       }
296
297       if (!nodeLabel.equals(""))
298       {
299         g.drawString(nodeLabel, xstart + 2, ypos - 2);
300       }
301
302     }
303   }
304
305   public Object findElement(int x, int y)
306   {
307     Enumeration keys = nameHash.keys();
308
309     while (keys.hasMoreElements())
310     {
311       Object ob = keys.nextElement();
312       Rectangle rect = (Rectangle) nameHash.get(ob);
313
314       if (x >= rect.x && x <= (rect.x + rect.width) && y >= rect.y
315               && y <= (rect.y + rect.height))
316       {
317         return ob;
318       }
319     }
320     keys = nodeHash.keys();
321
322     while (keys.hasMoreElements())
323     {
324       Object ob = keys.nextElement();
325       Rectangle rect = (Rectangle) nodeHash.get(ob);
326
327       if (x >= rect.x && x <= (rect.x + rect.width) && y >= rect.y
328               && y <= (rect.y + rect.height))
329       {
330         return ob;
331       }
332     }
333     return null;
334
335   }
336
337   public void pickNodes(Rectangle pickBox)
338   {
339     int width = getSize().width;
340     int height = getSize().height;
341
342     BinaryNode top = tree.getTopNode();
343
344     double wscale = (float) (width * .8 - offx * 2) / tree.getMaxHeight();
345     if (top.count == 0)
346     {
347       top.count = ((BinaryNode) top.left()).count
348               + ((BinaryNode) top.right()).count;
349     }
350     float chunk = (float) (height - offy) / top.count;
351
352     pickNode(pickBox, top, chunk, wscale, width, offx, offy);
353   }
354
355   public void pickNode(Rectangle pickBox, BinaryNode node, float chunk,
356           double scale, int width, int offx, int offy)
357   {
358     if (node == null)
359     {
360       return;
361     }
362
363     if (node.left() == null && node.right() == null)
364     {
365       double height = node.height;
366       // float dist = node.dist;
367
368       // int xstart = (int) ( (height - dist) * scale) + offx;
369       int xend = (int) (height * scale) + offx;
370
371       int ypos = (int) (node.ycount * chunk) + offy;
372
373       if (pickBox.contains(new Point(xend, ypos)))
374       {
375         if (node.element() instanceof SequenceI)
376         {
377           SequenceI seq = (SequenceI) node.element();
378           SequenceGroup sg = av.getSelectionGroup();
379           if (sg != null)
380           {
381             sg.addOrRemove(seq, true);
382           }
383         }
384       }
385     }
386     else
387     {
388       pickNode(pickBox, (BinaryNode) node.left(), chunk, scale, width,
389               offx, offy);
390       pickNode(pickBox, (BinaryNode) node.right(), chunk, scale, width,
391               offx, offy);
392     }
393   }
394
395   public void setColor(BinaryNode node, Color c)
396   {
397     if (node == null)
398     {
399       return;
400     }
401
402     if (node.left() == null && node.right() == null)
403     {
404       node.color = c;
405
406       if (node.element() instanceof SequenceI)
407       {
408         av.setSequenceColour((SequenceI) node.element(), c);
409       }
410     }
411     else
412     {
413       node.color = c;
414       setColor((BinaryNode) node.left(), c);
415       setColor((BinaryNode) node.right(), c);
416     }
417   }
418
419   @Override
420   public void update(Graphics g)
421   {
422     paint(g);
423   }
424
425   @Override
426   public void paint(Graphics g)
427   {
428     if (tree == null)
429     {
430       return;
431     }
432
433     if (nameHash.size() == 0)
434     {
435       repaint();
436     }
437
438     int width = scrollPane.getSize().width;
439     int height = scrollPane.getSize().height;
440     if (!fitToWindow)
441     {
442       height = g.getFontMetrics(font).getHeight() * nameHash.size();
443     }
444
445     if (getSize().width > width)
446     {
447       setSize(new Dimension(width, height));
448       scrollPane.validate();
449       return;
450     }
451
452     setSize(new Dimension(width, height));
453
454     g.setFont(font);
455     draw(g, width, height);
456     validate();
457   }
458
459   public void draw(Graphics g, int width, int height)
460   {
461     offy = font.getSize() + 10;
462
463     g.setColor(Color.white);
464     g.fillRect(0, 0, width, height);
465
466     labelLength = g.getFontMetrics(font).stringWidth(longestName) + 20; // 20
467     // allows
468     // for
469     // scrollbar
470
471     double wscale = (width - labelLength - offx * 2) / tree.getMaxHeight();
472
473     BinaryNode top = tree.getTopNode();
474
475     if (top.count == 0)
476     {
477       top.count = ((BinaryNode) top.left()).count
478               + ((BinaryNode) top.right()).count;
479     }
480     float chunk = (float) (height - offy) / top.count;
481
482     drawNode(g, tree.getTopNode(), chunk, wscale, width, offx, offy);
483
484     if (threshold != 0)
485     {
486       if (av.getCurrentTree() == tree)
487       {
488         g.setColor(Color.red);
489       }
490       else
491       {
492         g.setColor(Color.gray);
493       }
494
495       int x = (int) (threshold * (getSize().width - labelLength - 2 * offx)
496               + offx);
497
498       g.drawLine(x, 0, x, getSize().height);
499     }
500
501   }
502
503   @Override
504   public void mouseReleased(MouseEvent e)
505   {
506   }
507
508   @Override
509   public void mouseEntered(MouseEvent e)
510   {
511   }
512
513   @Override
514   public void mouseExited(MouseEvent e)
515   {
516   }
517
518   @Override
519   public void mouseClicked(MouseEvent evt)
520   {
521     if (highlightNode != null)
522     {
523       if (evt.getClickCount() > 1)
524       {
525         tree.swapNodes(highlightNode);
526         tree.reCount(tree.getTopNode());
527         tree.findHeight(tree.getTopNode());
528       }
529       else
530       {
531         Vector<BinaryNode> leaves = tree.findLeaves(highlightNode);
532
533         for (int i = 0; i < leaves.size(); i++)
534         {
535           SequenceI seq = (SequenceI) leaves.elementAt(i).element();
536           treeSelectionChanged(seq);
537         }
538       }
539
540       PaintRefresher.Refresh(this, av.getSequenceSetId());
541       repaint();
542       av.sendSelection();
543     }
544   }
545
546   @Override
547   public void mouseDragged(MouseEvent ect)
548   {
549   }
550
551   @Override
552   public void mouseMoved(MouseEvent evt)
553   {
554     av.setCurrentTree(tree);
555
556     Object ob = findElement(evt.getX(), evt.getY());
557
558     if (ob instanceof BinaryNode)
559     {
560       highlightNode = (BinaryNode) ob;
561       repaint();
562     }
563     else
564     {
565       if (highlightNode != null)
566       {
567         highlightNode = null;
568         repaint();
569       }
570     }
571   }
572
573   @Override
574   public void mousePressed(MouseEvent e)
575   {
576     av.setCurrentTree(tree);
577
578     int x = e.getX();
579     int y = e.getY();
580
581     Object ob = findElement(x, y);
582
583     if (ob instanceof SequenceI)
584     {
585       treeSelectionChanged((Sequence) ob);
586       PaintRefresher.Refresh(this, av.getSequenceSetId());
587       repaint();
588       av.sendSelection();
589       return;
590     }
591     else if (!(ob instanceof SequenceNode))
592     {
593       // Find threshold
594
595       if (tree.getMaxHeight() != 0)
596       {
597         threshold = (float) (x - offx)
598                 / (float) (getSize().width - labelLength - 2 * offx);
599
600         List<BinaryNode> groups = tree.groupNodes(threshold);
601         setColor(tree.getTopNode(), Color.black);
602
603         av.setSelectionGroup(null);
604         av.getAlignment().deleteAllGroups();
605         av.clearSequenceColours();
606         final AlignViewportI codingComplement = av.getCodingComplement();
607         if (codingComplement != null)
608         {
609           codingComplement.setSelectionGroup(null);
610           codingComplement.getAlignment().deleteAllGroups();
611           codingComplement.clearSequenceColours();
612         }
613
614         colourGroups(groups);
615
616       }
617     }
618
619     PaintRefresher.Refresh(this, av.getSequenceSetId());
620     repaint();
621
622   }
623
624   void colourGroups(List<BinaryNode> groups)
625   {
626     for (int i = 0; i < groups.size(); i++)
627     {
628
629       Color col = new Color((int) (Math.random() * 255),
630               (int) (Math.random() * 255), (int) (Math.random() * 255));
631       setColor(groups.get(i), col.brighter());
632
633       Vector<BinaryNode> l = tree.findLeaves(groups.get(i));
634
635       Vector<SequenceI> sequences = new Vector<>();
636       for (int j = 0; j < l.size(); j++)
637       {
638         SequenceI s1 = (SequenceI) l.elementAt(j).element();
639         if (!sequences.contains(s1))
640         {
641           sequences.addElement(s1);
642         }
643       }
644
645       ColourSchemeI cs = null;
646
647       SequenceGroup sg = new SequenceGroup(sequences, "", cs, true, true,
648               false, 0, av.getAlignment().getWidth() - 1);
649
650       if (av.getGlobalColourScheme() != null)
651       {
652         if (av.getGlobalColourScheme() instanceof UserColourScheme)
653         {
654           cs = new UserColourScheme(
655                   ((UserColourScheme) av.getGlobalColourScheme())
656                           .getColours());
657
658         }
659         else
660         {
661           cs = ColourSchemeProperty.getColourScheme(av, sg,
662                   ColourSchemeProperty
663                           .getColourName(av.getGlobalColourScheme()));
664         }
665         // cs is null if shading is an annotationColourGradient
666         // if (cs != null)
667         // {
668         // cs.setThreshold(av.getViewportColourScheme().getThreshold(),
669         // av.isIgnoreGapsConsensus());
670         // }
671       }
672       // TODO: cs used to be initialized with a sequence collection and
673       // recalcConservation called automatically
674       // instead we set it manually - recalc called after updateAnnotation
675       sg.setColourScheme(cs);
676       sg.getGroupColourScheme().setThreshold(
677               av.getResidueShading().getThreshold(),
678               av.isIgnoreGapsConsensus());
679
680       sg.setName("JTreeGroup:" + sg.hashCode());
681       sg.setIdColour(col);
682       if (av.getGlobalColourScheme() != null
683               && av.getResidueShading().conservationApplied())
684       {
685         Conservation c = new Conservation("Group", sg.getSequences(null),
686                 sg.getStartRes(), sg.getEndRes());
687
688         c.calculate();
689         c.verdict(false, av.getConsPercGaps());
690
691         sg.setColourScheme(cs);
692         sg.getGroupColourScheme().setConservation(c);
693       }
694
695       av.getAlignment().addGroup(sg);
696
697       // TODO this is duplicated with gui TreeCanvas - refactor
698       av.getAlignment().addGroup(sg);
699       final AlignViewportI codingComplement = av.getCodingComplement();
700       if (codingComplement != null)
701       {
702         SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg, av,
703                 codingComplement);
704         if (mappedGroup.getSequences().size() > 0)
705         {
706           codingComplement.getAlignment().addGroup(mappedGroup);
707           for (SequenceI seq : mappedGroup.getSequences())
708           {
709             // TODO why does gui require col.brighter() here??
710             codingComplement.setSequenceColour(seq, col);
711           }
712         }
713       }
714
715     }
716     ap.updateAnnotation();
717     if (av.getCodingComplement() != null)
718     {
719       ((AlignmentViewport) av.getCodingComplement()).firePropertyChange(
720               "alignment", null, ap.av.getAlignment().getSequences());
721     }
722   }
723
724   public void setShowDistances(boolean state)
725   {
726     this.showDistances = state;
727     repaint();
728   }
729
730   public void setShowBootstrap(boolean state)
731   {
732     this.showBootstrap = state;
733     repaint();
734   }
735
736   public void setMarkPlaceholders(boolean state)
737   {
738     this.markPlaceholders = state;
739     repaint();
740   }
741
742 }