merge from 2_4_Release branch
[jalview.git] / src / jalview / appletgui / TreeCanvas.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3  * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.appletgui;
20
21 import java.util.*;
22
23 import java.awt.*;
24 import java.awt.event.*;
25
26 import jalview.analysis.*;
27 import jalview.datamodel.*;
28 import jalview.schemes.*;
29 import jalview.util.*;
30
31 public class TreeCanvas extends Panel implements MouseListener,
32         MouseMotionListener
33 {
34   NJTree tree;
35
36   ScrollPane scrollPane;
37
38   AlignViewport av;
39
40   public static final String PLACEHOLDER = " * ";
41
42   Font font;
43
44   boolean fitToWindow = true;
45
46   boolean showDistances = false;
47
48   boolean showBootstrap = false;
49
50   boolean markPlaceholders = false;
51
52   int offx = 20;
53
54   int offy;
55
56   float threshold;
57
58   String longestName;
59
60   int labelLength = -1;
61
62   Hashtable nameHash = new Hashtable();
63
64   Hashtable nodeHash = new Hashtable();
65
66   SequenceNode highlightNode;
67
68   public TreeCanvas(AlignViewport av, ScrollPane scroller)
69   {
70     this.av = av;
71     font = av.getFont();
72     scrollPane = scroller;
73     addMouseListener(this);
74     addMouseMotionListener(this);
75     setLayout(null);
76
77     PaintRefresher.Register(this, av.getSequenceSetId());
78   }
79
80   public void treeSelectionChanged(SequenceI sequence)
81   {
82     SequenceGroup selected = av.getSelectionGroup();
83     if (selected == null)
84     {
85       selected = new SequenceGroup();
86       av.setSelectionGroup(selected);
87     }
88
89     selected.setEndRes(av.alignment.getWidth() - 1);
90     selected.addOrRemove(sequence, true);
91   }
92
93   public void setTree(NJTree tree)
94   {
95     this.tree = tree;
96     tree.findHeight(tree.getTopNode());
97
98     // Now have to calculate longest name based on the leaves
99     Vector leaves = tree.findLeaves(tree.getTopNode(), new Vector());
100     boolean has_placeholders = false;
101     longestName = "";
102
103     for (int i = 0; i < leaves.size(); i++)
104     {
105       SequenceNode lf = (SequenceNode) leaves.elementAt(i);
106
107       if (lf.isPlaceholder())
108       {
109         has_placeholders = true;
110       }
111
112       if (longestName.length() < ((Sequence) lf.element()).getName()
113               .length())
114       {
115         longestName = TreeCanvas.PLACEHOLDER
116                 + ((Sequence) lf.element()).getName();
117       }
118     }
119
120     setMarkPlaceholders(has_placeholders);
121   }
122
123   public void drawNode(Graphics g, SequenceNode node, float chunk,
124           float scale, int width, int offx, int offy)
125   {
126     if (node == null)
127     {
128       return;
129     }
130
131     if (node.left() == null && node.right() == null)
132     {
133       // Drawing leaf node
134
135       float height = node.height;
136       float dist = node.dist;
137
138       int xstart = (int) ((height - dist) * scale) + offx;
139       int xend = (int) (height * scale) + offx;
140
141       int ypos = (int) (node.ycount * chunk) + offy;
142
143       if (node.element() instanceof SequenceI)
144       {
145         SequenceI seq = (SequenceI) ((SequenceNode) node).element();
146
147         if (av.getSequenceColour(seq) == Color.white)
148         {
149           g.setColor(Color.black);
150         }
151         else
152         {
153           g.setColor(av.getSequenceColour(seq).darker());
154         }
155
156       }
157       else
158       {
159         g.setColor(Color.black);
160       }
161
162       // Draw horizontal line
163       g.drawLine(xstart, ypos, xend, ypos);
164
165       String nodeLabel = "";
166       if (showDistances && node.dist > 0)
167       {
168         nodeLabel = new Format("%-.2f").form(node.dist);
169       }
170       if (showBootstrap)
171       {
172         int btstrap = node.getBootstrap();
173         if (btstrap > -1)
174         {
175           if (showDistances)
176           {
177             nodeLabel = nodeLabel + " : ";
178           }
179           nodeLabel = nodeLabel + String.valueOf(node.getBootstrap());
180         }
181       }
182       if (!nodeLabel.equals(""))
183       {
184         g.drawString(nodeLabel, xstart + 2, ypos - 2);
185       }
186
187       String name = (markPlaceholders && node.isPlaceholder()) ? (PLACEHOLDER + node
188               .getName())
189               : node.getName();
190       FontMetrics fm = g.getFontMetrics(font);
191       int charWidth = fm.stringWidth(name) + 3;
192       int charHeight = fm.getHeight();
193
194       Rectangle rect = new Rectangle(xend + 10, ypos - charHeight,
195               charWidth, charHeight);
196
197       nameHash.put((SequenceI) node.element(), rect);
198
199       // Colour selected leaves differently
200       SequenceGroup selected = av.getSelectionGroup();
201       if (selected != null
202               && selected.getSequences(null).contains(
203                       (SequenceI) 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(((SequenceNode) 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   public void update(Graphics g)
394   {
395     paint(g);
396   }
397
398   public void paint(Graphics g)
399   {
400     if (tree == null)
401     {
402       return;
403     }
404
405     if (nameHash.size() == 0)
406     {
407       repaint();
408     }
409
410     int width = scrollPane.getSize().width;
411     int height = scrollPane.getSize().height;
412     if (!fitToWindow)
413     {
414       height = g.getFontMetrics(font).getHeight() * nameHash.size();
415     }
416
417     if (getSize().width > width)
418     {
419       setSize(new Dimension(width, height));
420       scrollPane.validate();
421       return;
422     }
423
424     setSize(new Dimension(width, height));
425
426     g.setFont(font);
427
428     draw(g, width, height);
429
430   }
431
432   public void draw(Graphics g, int width, int height)
433   {
434     offy = font.getSize() + 10;
435
436     g.setColor(Color.white);
437     g.fillRect(0, 0, width, height);
438
439     labelLength = g.getFontMetrics(font).stringWidth(longestName) + 20; // 20
440                                                                         // allows
441                                                                         // for
442                                                                         // scrollbar
443
444     float wscale = (float) (width - labelLength - offx * 2)
445             / 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
470               * (float) (getSize().width - labelLength - 2 * offx) + offx);
471
472       g.drawLine(x, 0, x, getSize().height);
473     }
474
475   }
476
477   public void mouseReleased(MouseEvent e)
478   {
479   }
480
481   public void mouseEntered(MouseEvent e)
482   {
483   }
484
485   public void mouseExited(MouseEvent e)
486   {
487   }
488
489   public void mouseClicked(MouseEvent evt)
490   {
491     if (highlightNode != null)
492     {
493       if (evt.getClickCount() > 1)
494       {
495         tree.swapNodes(highlightNode);
496         tree.reCount(tree.getTopNode());
497         tree.findHeight(tree.getTopNode());
498       }
499       else
500       {
501         Vector leaves = new Vector();
502         tree.findLeaves(highlightNode, leaves);
503
504         for (int i = 0; i < leaves.size(); i++)
505         {
506           SequenceI seq = (SequenceI) ((SequenceNode) leaves.elementAt(i))
507                   .element();
508           treeSelectionChanged(seq);
509         }
510       }
511
512       PaintRefresher.Refresh(this, av.getSequenceSetId());
513       repaint();
514     }
515   }
516
517   public void mouseDragged(MouseEvent ect)
518   {
519   }
520
521   public void mouseMoved(MouseEvent evt)
522   {
523     av.setCurrentTree(tree);
524
525     Object ob = findElement(evt.getX(), evt.getY());
526
527     if (ob instanceof SequenceNode)
528     {
529       highlightNode = (SequenceNode) ob;
530       repaint();
531     }
532     else
533     {
534       if (highlightNode != null)
535       {
536         highlightNode = null;
537         repaint();
538       }
539     }
540   }
541
542   public void mousePressed(MouseEvent e)
543   {
544     av.setCurrentTree(tree);
545
546     int x = e.getX();
547     int y = e.getY();
548
549     Object ob = findElement(x, y);
550
551     if (ob instanceof SequenceI)
552     {
553       treeSelectionChanged((Sequence) ob);
554       PaintRefresher.Refresh(this, av.getSequenceSetId());
555       repaint();
556       return;
557     }
558     else if (!(ob instanceof SequenceNode))
559     {
560       // Find threshold
561
562       if (tree.getMaxHeight() != 0)
563       {
564         threshold = (float) (x - offx)
565                 / (float) (getSize().width - labelLength - 2 * offx);
566
567         tree.getGroups().removeAllElements();
568         tree.groupNodes(tree.getTopNode(), threshold);
569         setColor(tree.getTopNode(), Color.black);
570
571         av.setSelectionGroup(null);
572         av.alignment.deleteAllGroups();
573         av.sequenceColours = null;
574
575         colourGroups();
576
577       }
578     }
579
580     PaintRefresher.Refresh(this, av.getSequenceSetId());
581     repaint();
582
583   }
584
585   void colourGroups()
586   {
587     for (int i = 0; i < tree.getGroups().size(); i++)
588     {
589
590       Color col = new Color((int) (Math.random() * 255), (int) (Math
591               .random() * 255), (int) (Math.random() * 255));
592       setColor((SequenceNode) tree.getGroups().elementAt(i), col.brighter());
593
594       Vector l = tree.findLeaves((SequenceNode) tree.getGroups().elementAt(
595               i), new Vector());
596
597       Vector sequences = new Vector();
598       for (int j = 0; j < l.size(); j++)
599       {
600         SequenceI s1 = (SequenceI) ((SequenceNode) l.elementAt(j))
601                 .element();
602         if (!sequences.contains(s1))
603         {
604           sequences.addElement(s1);
605         }
606       }
607
608       ColourSchemeI cs = null;
609
610       if (av.getGlobalColourScheme() != null)
611       {
612         if (av.getGlobalColourScheme() instanceof UserColourScheme)
613         {
614           cs = new UserColourScheme(((UserColourScheme) av
615                   .getGlobalColourScheme()).getColours());
616
617         }
618         else
619         {
620           cs = ColourSchemeProperty.getColour(sequences, av.alignment
621                   .getWidth(), ColourSchemeProperty.getColourName(av
622                   .getGlobalColourScheme()));
623         }
624
625         cs.setThreshold(av.getGlobalColourScheme().getThreshold(), av
626                 .getIgnoreGapsConsensus());
627       }
628
629       SequenceGroup sg = new SequenceGroup(sequences, "", cs, true, true,
630               false, 0, av.alignment.getWidth() - 1);
631
632       sg.setName("JTreeGroup:" + sg.hashCode());
633       sg.setIdColour(col);
634       if (av.getGlobalColourScheme() != null
635               && av.getGlobalColourScheme().conservationApplied())
636       {
637         Conservation c = new Conservation("Group",
638                 ResidueProperties.propHash, 3, sg.getSequences(null), sg
639                         .getStartRes(), sg.getEndRes());
640
641         c.calculate();
642         c.verdict(false, av.ConsPercGaps);
643         cs.setConservation(c);
644
645         sg.cs = cs;
646
647       }
648
649       av.alignment.addGroup(sg);
650
651     }
652
653   }
654
655   public void setShowDistances(boolean state)
656   {
657     this.showDistances = state;
658     repaint();
659   }
660
661   public void setShowBootstrap(boolean state)
662   {
663     this.showBootstrap = state;
664     repaint();
665   }
666
667   public void setMarkPlaceholders(boolean state)
668   {
669     this.markPlaceholders = state;
670     repaint();
671   }
672
673 }