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