update author list in license for (JAL-826)
[jalview.git] / src / jalview / appletgui / TreeCanvas.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, 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   public TreeCanvas(AlignmentPanel ap, ScrollPane scroller)
69   {
70     this.ap = ap;
71     this.av = ap.av;
72     font = av.getFont();
73     scrollPane = scroller;
74     addMouseListener(this);
75     addMouseMotionListener(this);
76     setLayout(null);
77
78     PaintRefresher.Register(this, av.getSequenceSetId());
79   }
80
81   public void treeSelectionChanged(SequenceI sequence)
82   {
83     SequenceGroup selected = av.getSelectionGroup();
84     if (selected == null)
85     {
86       selected = new SequenceGroup();
87       av.setSelectionGroup(selected);
88     }
89
90     selected.setEndRes(av.alignment.getWidth() - 1);
91     selected.addOrRemove(sequence, true);
92   }
93
94   public void setTree(NJTree tree)
95   {
96     this.tree = tree;
97     tree.findHeight(tree.getTopNode());
98
99     // Now have to calculate longest name based on the leaves
100     Vector leaves = tree.findLeaves(tree.getTopNode(), new Vector());
101     boolean has_placeholders = false;
102     longestName = "";
103
104     for (int i = 0; i < leaves.size(); i++)
105     {
106       SequenceNode lf = (SequenceNode) leaves.elementAt(i);
107
108       if (lf.isPlaceholder())
109       {
110         has_placeholders = true;
111       }
112
113       if (longestName.length() < ((Sequence) lf.element()).getName()
114               .length())
115       {
116         longestName = TreeCanvas.PLACEHOLDER
117                 + ((Sequence) lf.element()).getName();
118       }
119     }
120
121     setMarkPlaceholders(has_placeholders);
122   }
123
124   public void drawNode(Graphics g, SequenceNode node, float chunk,
125           float scale, int width, int offx, int offy)
126   {
127     if (node == null)
128     {
129       return;
130     }
131
132     if (node.left() == null && node.right() == null)
133     {
134       // Drawing leaf node
135
136       float height = node.height;
137       float dist = node.dist;
138
139       int xstart = (int) ((height - dist) * scale) + offx;
140       int xend = (int) (height * scale) + offx;
141
142       int ypos = (int) (node.ycount * chunk) + offy;
143
144       if (node.element() instanceof SequenceI)
145       {
146         SequenceI seq = (SequenceI) ((SequenceNode) node).element();
147
148         if (av.getSequenceColour(seq) == Color.white)
149         {
150           g.setColor(Color.black);
151         }
152         else
153         {
154           g.setColor(av.getSequenceColour(seq).darker());
155         }
156
157       }
158       else
159       {
160         g.setColor(Color.black);
161       }
162
163       // Draw horizontal line
164       g.drawLine(xstart, ypos, xend, ypos);
165
166       String nodeLabel = "";
167       if (showDistances && node.dist > 0)
168       {
169         nodeLabel = new Format("%-.2f").form(node.dist);
170       }
171       if (showBootstrap)
172       {
173         int btstrap = node.getBootstrap();
174         if (btstrap > -1)
175         {
176           if (showDistances)
177           {
178             nodeLabel = nodeLabel + " : ";
179           }
180           nodeLabel = nodeLabel + String.valueOf(node.getBootstrap());
181         }
182       }
183       if (!nodeLabel.equals(""))
184       {
185         g.drawString(nodeLabel, xstart + 2, ypos - 2);
186       }
187
188       String name = (markPlaceholders && node.isPlaceholder()) ? (PLACEHOLDER + node
189               .getName()) : 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     draw(g, width, height);
428     validate();
429   }
430
431   public void draw(Graphics g, int width, int height)
432   {
433     offy = font.getSize() + 10;
434
435     g.setColor(Color.white);
436     g.fillRect(0, 0, width, height);
437
438     labelLength = g.getFontMetrics(font).stringWidth(longestName) + 20; // 20
439     // allows
440     // for
441     // scrollbar
442
443     float wscale = (float) (width - labelLength - offx * 2)
444             / tree.getMaxHeight();
445
446     SequenceNode top = tree.getTopNode();
447
448     if (top.count == 0)
449     {
450       top.count = ((SequenceNode) top.left()).count
451               + ((SequenceNode) top.right()).count;
452     }
453     float chunk = (float) (height - offy) / top.count;
454
455     drawNode(g, tree.getTopNode(), chunk, wscale, width, offx, offy);
456
457     if (threshold != 0)
458     {
459       if (av.getCurrentTree() == tree)
460       {
461         g.setColor(Color.red);
462       }
463       else
464       {
465         g.setColor(Color.gray);
466       }
467
468       int x = (int) (threshold
469               * (float) (getSize().width - labelLength - 2 * offx) + offx);
470
471       g.drawLine(x, 0, x, getSize().height);
472     }
473
474   }
475
476   public void mouseReleased(MouseEvent e)
477   {
478   }
479
480   public void mouseEntered(MouseEvent e)
481   {
482   }
483
484   public void mouseExited(MouseEvent e)
485   {
486   }
487
488   public void mouseClicked(MouseEvent evt)
489   {
490     if (highlightNode != null)
491     {
492       if (evt.getClickCount() > 1)
493       {
494         tree.swapNodes(highlightNode);
495         tree.reCount(tree.getTopNode());
496         tree.findHeight(tree.getTopNode());
497       }
498       else
499       {
500         Vector leaves = new Vector();
501         tree.findLeaves(highlightNode, leaves);
502
503         for (int i = 0; i < leaves.size(); i++)
504         {
505           SequenceI seq = (SequenceI) ((SequenceNode) leaves.elementAt(i))
506                   .element();
507           treeSelectionChanged(seq);
508         }
509       }
510
511       PaintRefresher.Refresh(this, av.getSequenceSetId());
512       repaint();
513       av.sendSelection();
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       av.sendSelection();
557       return;
558     }
559     else if (!(ob instanceof SequenceNode))
560     {
561       // Find threshold
562
563       if (tree.getMaxHeight() != 0)
564       {
565         threshold = (float) (x - offx)
566                 / (float) (getSize().width - labelLength - 2 * offx);
567
568         tree.getGroups().removeAllElements();
569         tree.groupNodes(tree.getTopNode(), threshold);
570         setColor(tree.getTopNode(), Color.black);
571
572         av.setSelectionGroup(null);
573         av.alignment.deleteAllGroups();
574         av.sequenceColours = null;
575
576         colourGroups();
577
578       }
579     }
580
581     PaintRefresher.Refresh(this, av.getSequenceSetId());
582     repaint();
583
584   }
585
586   void colourGroups()
587   {
588     for (int i = 0; i < tree.getGroups().size(); i++)
589     {
590
591       Color col = new Color((int) (Math.random() * 255),
592               (int) (Math.random() * 255), (int) (Math.random() * 255));
593       setColor((SequenceNode) tree.getGroups().elementAt(i), col.brighter());
594
595       Vector l = tree.findLeaves(
596               (SequenceNode) tree.getGroups().elementAt(i), new Vector());
597
598       Vector sequences = new Vector();
599       for (int j = 0; j < l.size(); j++)
600       {
601         SequenceI s1 = (SequenceI) ((SequenceNode) l.elementAt(j))
602                 .element();
603         if (!sequences.contains(s1))
604         {
605           sequences.addElement(s1);
606         }
607       }
608
609       ColourSchemeI cs = null;
610
611       if (av.getGlobalColourScheme() != null)
612       {
613         if (av.getGlobalColourScheme() instanceof UserColourScheme)
614         {
615           cs = new UserColourScheme(
616                   ((UserColourScheme) av.getGlobalColourScheme())
617                           .getColours());
618
619         }
620         else
621         {
622           cs = ColourSchemeProperty.getColour(sequences, av.alignment
623                   .getWidth(), ColourSchemeProperty.getColourName(av
624                   .getGlobalColourScheme()));
625         }
626         // cs is null if shading is an annotationColourGradient
627         if (cs!=null)
628         {
629           cs.setThreshold(av.getGlobalColourScheme().getThreshold(),
630                   av.getIgnoreGapsConsensus());
631         }
632       }
633
634       SequenceGroup sg = new SequenceGroup(sequences, "", cs, true, true,
635               false, 0, av.alignment.getWidth() - 1);
636
637       sg.setName("JTreeGroup:" + sg.hashCode());
638       sg.setIdColour(col);
639       if (av.getGlobalColourScheme() != null
640               && av.getGlobalColourScheme().conservationApplied())
641       {
642         Conservation c = new Conservation("Group",
643                 ResidueProperties.propHash, 3, sg.getSequences(null),
644                 sg.getStartRes(), sg.getEndRes());
645
646         c.calculate();
647         c.verdict(false, av.ConsPercGaps);
648         cs.setConservation(c);
649
650         sg.cs = cs;
651
652       }
653
654       av.alignment.addGroup(sg);
655
656     }
657     ap.updateAnnotation();
658     
659   }
660
661   public void setShowDistances(boolean state)
662   {
663     this.showDistances = state;
664     repaint();
665   }
666
667   public void setShowBootstrap(boolean state)
668   {
669     this.showBootstrap = state;
670     repaint();
671   }
672
673   public void setMarkPlaceholders(boolean state)
674   {
675     this.markPlaceholders = state;
676     repaint();
677   }
678
679 }