JAL-2089 patch broken merge to master for Release 2.10.0b1
[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.UserColourScheme;
33 import jalview.util.Format;
34 import jalview.util.MappingUtils;
35 import jalview.viewmodel.AlignmentViewport;
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<SequenceNode> leaves = tree.findLeaves(tree.getTopNode());
125     boolean has_placeholders = false;
126     longestName = "";
127
128     for (int i = 0; i < leaves.size(); i++)
129     {
130       SequenceNode lf = 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<SequenceNode> leaves = tree.findLeaves(highlightNode);
528
529         for (int i = 0; i < leaves.size(); i++)
530         {
531           SequenceI seq = (SequenceI) leaves.elementAt(i).element();
532           treeSelectionChanged(seq);
533         }
534       }
535
536       PaintRefresher.Refresh(this, av.getSequenceSetId());
537       repaint();
538       av.sendSelection();
539     }
540   }
541
542   @Override
543   public void mouseDragged(MouseEvent ect)
544   {
545   }
546
547   @Override
548   public void mouseMoved(MouseEvent evt)
549   {
550     av.setCurrentTree(tree);
551
552     Object ob = findElement(evt.getX(), evt.getY());
553
554     if (ob instanceof SequenceNode)
555     {
556       highlightNode = (SequenceNode) ob;
557       repaint();
558     }
559     else
560     {
561       if (highlightNode != null)
562       {
563         highlightNode = null;
564         repaint();
565       }
566     }
567   }
568
569   @Override
570   public void mousePressed(MouseEvent e)
571   {
572     av.setCurrentTree(tree);
573
574     int x = e.getX();
575     int y = e.getY();
576
577     Object ob = findElement(x, y);
578
579     if (ob instanceof SequenceI)
580     {
581       treeSelectionChanged((Sequence) ob);
582       PaintRefresher.Refresh(this, av.getSequenceSetId());
583       repaint();
584       av.sendSelection();
585       return;
586     }
587     else if (!(ob instanceof SequenceNode))
588     {
589       // Find threshold
590
591       if (tree.getMaxHeight() != 0)
592       {
593         threshold = (float) (x - offx)
594                 / (float) (getSize().width - labelLength - 2 * offx);
595
596         tree.getGroups().removeAllElements();
597         tree.groupNodes(tree.getTopNode(), threshold);
598         setColor(tree.getTopNode(), Color.black);
599
600         av.setSelectionGroup(null);
601         av.getAlignment().deleteAllGroups();
602         av.clearSequenceColours();
603         final AlignViewportI codingComplement = av.getCodingComplement();
604         if (codingComplement != null)
605         {
606           codingComplement.setSelectionGroup(null);
607           codingComplement.getAlignment().deleteAllGroups();
608           codingComplement.clearSequenceColours();
609         }
610
611         colourGroups();
612
613       }
614     }
615
616     PaintRefresher.Refresh(this, av.getSequenceSetId());
617     repaint();
618
619   }
620
621   void colourGroups()
622   {
623     for (int i = 0; i < tree.getGroups().size(); i++)
624     {
625
626       Color col = new Color((int) (Math.random() * 255),
627               (int) (Math.random() * 255), (int) (Math.random() * 255));
628       setColor(tree.getGroups().elementAt(i), col.brighter());
629
630       Vector<SequenceNode> l = tree.findLeaves(tree.getGroups()
631               .elementAt(i));
632
633       Vector<SequenceI> sequences = new Vector<SequenceI>();
634       for (int j = 0; j < l.size(); j++)
635       {
636         SequenceI s1 = (SequenceI) l.elementAt(j).element();
637         if (!sequences.contains(s1))
638         {
639           sequences.addElement(s1);
640         }
641       }
642
643       ColourSchemeI cs = null;
644
645       SequenceGroup sg = new SequenceGroup(sequences, "", cs, true, true,
646               false, 0, av.getAlignment().getWidth() - 1);
647
648       if (av.getGlobalColourScheme() != null)
649       {
650         if (av.getGlobalColourScheme() instanceof UserColourScheme)
651         {
652           cs = new UserColourScheme(
653                   ((UserColourScheme) av.getGlobalColourScheme())
654                           .getColours());
655
656         }
657         else
658         {
659           cs = ColourSchemeProperty.getColour(sg, ColourSchemeProperty
660                   .getColourName(av.getGlobalColourScheme()));
661         }
662         // cs is null if shading is an annotationColourGradient
663         if (cs != null)
664         {
665           cs.setThreshold(av.getGlobalColourScheme().getThreshold(),
666                   av.isIgnoreGapsConsensus());
667         }
668       }
669       // TODO: cs used to be initialized with a sequence collection and
670       // recalcConservation called automatically
671       // instead we set it manually - recalc called after updateAnnotation
672       sg.cs = cs;
673
674       sg.setName("JTreeGroup:" + sg.hashCode());
675       sg.setIdColour(col);
676       if (av.getGlobalColourScheme() != null
677               && av.getGlobalColourScheme().conservationApplied())
678       {
679         Conservation c = new Conservation("Group", 3,
680                 sg.getSequences(null), sg.getStartRes(), sg.getEndRes());
681
682         c.calculate();
683         c.verdict(false, av.getConsPercGaps());
684         cs.setConservation(c);
685
686         sg.cs = cs;
687
688       }
689
690       av.getAlignment().addGroup(sg);
691
692       // TODO this is duplicated with gui TreeCanvas - refactor
693       av.getAlignment().addGroup(sg);
694       final AlignViewportI codingComplement = av.getCodingComplement();
695       if (codingComplement != null)
696       {
697         SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(sg, av,
698                 codingComplement);
699         if (mappedGroup.getSequences().size() > 0)
700         {
701           codingComplement.getAlignment().addGroup(mappedGroup);
702           for (SequenceI seq : mappedGroup.getSequences())
703           {
704             // TODO why does gui require col.brighter() here??
705             codingComplement.setSequenceColour(seq, col);
706           }
707         }
708       }
709
710     }
711     ap.updateAnnotation();
712     if (av.getCodingComplement() != null)
713     {
714       ((AlignmentViewport) av.getCodingComplement()).firePropertyChange(
715               "alignment", null, ap.av.getAlignment().getSequences());
716     }
717   }
718
719   public void setShowDistances(boolean state)
720   {
721     this.showDistances = state;
722     repaint();
723   }
724
725   public void setShowBootstrap(boolean state)
726   {
727     this.showBootstrap = state;
728     repaint();
729   }
730
731   public void setMarkPlaceholders(boolean state)
732   {
733     this.markPlaceholders = state;
734     repaint();
735   }
736
737 }