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