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