JAL-2872 hide sort button in Aptx unless it's actually possible
[jalview.git] / src / jalview / ext / archaeopteryx / JalviewBinding.java
1 package jalview.ext.archaeopteryx;
2
3 import jalview.analysis.AlignmentSorter;
4 import jalview.analysis.Conservation;
5 import jalview.api.AlignViewportI;
6 import jalview.commands.CommandI;
7 import jalview.commands.OrderCommand;
8 import jalview.datamodel.ColumnSelection;
9 import jalview.datamodel.HiddenColumns;
10 import jalview.datamodel.SequenceGroup;
11 import jalview.datamodel.SequenceI;
12 import jalview.ext.treeviewer.ExternalTreeViewerBindingI;
13 import jalview.gui.AlignViewport;
14 import jalview.gui.AlignmentPanel;
15 import jalview.gui.Desktop;
16 import jalview.gui.JvOptionPane;
17 import jalview.gui.PaintRefresher;
18 import jalview.schemes.ColourSchemeI;
19 import jalview.schemes.ColourSchemeProperty;
20 import jalview.schemes.UserColourScheme;
21 import jalview.structure.SelectionSource;
22 import jalview.structure.StructureSelectionManager;
23 import jalview.util.MappingUtils;
24 import jalview.util.MessageManager;
25 import jalview.viewmodel.AlignmentViewport;
26
27 import java.awt.Color;
28 import java.awt.event.ActionEvent;
29 import java.awt.event.InputEvent;
30 import java.awt.event.MouseEvent;
31 import java.util.ArrayList;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36
37 import javax.swing.JTabbedPane;
38 import javax.swing.SwingUtilities;
39 import javax.swing.event.ChangeEvent;
40 import javax.swing.event.ChangeListener;
41 import javax.swing.event.InternalFrameAdapter;
42 import javax.swing.event.InternalFrameEvent;
43
44 import org.forester.archaeopteryx.MainFrame;
45 import org.forester.phylogeny.Phylogeny;
46 import org.forester.phylogeny.PhylogenyMethods;
47 import org.forester.phylogeny.PhylogenyNode;
48 import org.forester.phylogeny.data.BranchColor;
49
50 /**
51  * Class for binding the Archaeopteryx tree viewer to the Jalview alignment that
52  * it originates from, meaning that selecting sequences in the tree viewer also
53  * selects them in the alignment view and vice versa.
54  * 
55  * @author kjvanderheide
56  *
57  */
58 public final class JalviewBinding
59         implements ExternalTreeViewerBindingI<PhylogenyNode>
60 {
61   private final MainFrame aptxFrame;
62
63   private org.forester.archaeopteryx.TreePanel treeView;
64
65   private AlignmentViewport parentAvport;
66
67   private final JTabbedPane treeTabs;
68
69   private final StructureSelectionManager ssm;
70
71   private AlignmentPanel[] associatedPanels;
72
73   private Map<SequenceI, PhylogenyNode> sequencesBoundToNodes;
74
75   private Map<PhylogenyNode, SequenceI> nodesBoundToSequences;
76
77   private float rootX;
78
79   private float furthestNodeX;
80
81   private int nrTreeGroups = 0;
82
83   private boolean applyToAllViews = false;
84
85   /**
86    * 
87    * @param archaeopteryx
88    * 
89    * @param jalviewAlignmentViewport
90    *          alignment viewport from which the tree was calculated.
91    * 
92    * @param alignMappedToNodes
93    *          map with sequences used to calculate the tree and matching tree
94    *          nodes as key, value pair respectively.
95    * 
96    * @param nodesMappedToAlign
97    *          map with tree nodes and matching sequences used to calculate the
98    *          tree as key, value pair respectively.
99    */
100   public JalviewBinding(final MainFrame archaeopteryx,
101           final AlignmentViewport jalviewAlignmentViewport,
102           final Map<SequenceI, PhylogenyNode> alignMappedToNodes,
103           final Map<PhylogenyNode, SequenceI> nodesMappedToAlign)
104   {
105
106     if (archaeopteryx.getMainPanel().getTabbedPane().getTabCount() > 1)
107     {
108       JvOptionPane.showMessageDialog(Desktop.desktop,
109               MessageManager.getString("label.tabs_detected_archaeopteryx"),
110               MessageManager.getString("label.problem_reading_tree_file"),
111               JvOptionPane.WARNING_MESSAGE);
112
113     }
114
115     // deal with/prohibit null values here as that will cause problems
116     aptxFrame = archaeopteryx;
117     parentAvport = jalviewAlignmentViewport;
118     sequencesBoundToNodes = alignMappedToNodes;
119     nodesBoundToSequences = nodesMappedToAlign;
120
121     treeView = archaeopteryx.getMainPanel().getCurrentTreePanel();
122     treeTabs = archaeopteryx.getMainPanel().getTabbedPane();
123     ssm = parentAvport.getStructureSelectionManager();
124     
125     ssm.addSelectionListener(this);
126     treeView.addMouseListener(this);
127
128     PaintRefresher.Register(treeView, parentAvport.getSequenceSetId());
129     associatedPanels = PaintRefresher
130             .getAssociatedPanels(parentAvport.getSequenceSetId());
131
132     aptxFrame.addInternalFrameListener(new InternalFrameAdapter()
133     {
134
135       @Override
136       public void internalFrameClosed(InternalFrameEvent e)
137       {
138         AptxInit.getAllAptxFrames().remove(aptxFrame);
139         ssm.removeSelectionListener(JalviewBinding.this);
140       }
141
142     });
143
144     treeTabs.addChangeListener(new ChangeListener()
145     {
146
147       @Override
148       public void stateChanged(ChangeEvent e)
149       {
150
151         SwingUtilities.invokeLater(new Runnable()
152         {
153
154           @Override
155           /**
156            * Resend the selection to the tree view when tabs get switched, this
157            * has to be buried in invokeLater as Forester first resets the tree
158            * view on switching tabs, without invokeLater this would get called
159            * before Forester resets which would nullify the selection.
160            */
161           public void run()
162           {
163             treeView = archaeopteryx.getMainPanel().getCurrentTreePanel();
164             parentAvport.sendSelection();
165             // PaintRefresher.Refresh(treeView,
166             // parentAvport.getSequenceSetId());
167
168           }
169         });
170
171       }
172
173     });
174
175   }
176
177   @Override
178   public void actionPerformed(ActionEvent e)
179   {
180     // aptxFrame.actionPerformed(e);
181
182   }
183
184   @Override
185   public void mouseClicked(MouseEvent e)
186   {
187     SwingUtilities.invokeLater(new Runnable() {
188
189       @Override
190       /**
191        * invokeLater so that this always runs after Forester's mouseClicked
192        */
193       public void run()
194       {
195         final PhylogenyNode node = treeView.findNode(e.getX(), e.getY());
196         if (node != null)
197         {
198           if ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0) // clear previous
199           // selection if shift
200           // IS NOT pressed
201           {
202             parentAvport.setSelectionGroup(null);
203
204           }
205           showNodeSelectionOnAlign(node);
206         }
207         else
208         {
209
210           partitionTree(e.getX());
211       }
212         PaintRefresher.Refresh(treeView, parentAvport.getSequenceSetId());
213         treeView.repaint();
214
215
216
217       }
218     });
219
220
221   }
222
223   @Override
224   public void mousePressed(final MouseEvent e)
225   {
226
227   }
228   @Override
229   public void mouseReleased(MouseEvent e)
230   {
231   }
232
233   @Override
234   public void mouseEntered(MouseEvent e)
235   {
236   }
237
238   @Override
239   public void mouseExited(MouseEvent e)
240   {
241   }
242
243
244   @Override
245   public void selection(final SequenceGroup seqsel,
246           final ColumnSelection colsel, final HiddenColumns hidden,
247           final SelectionSource source)
248   {
249     if (source == parentAvport) // check if source is alignment from where the
250     // tree originates
251     {
252       treeView.setFoundNodes0(
253               new HashSet<Long>(seqsel.getSequences().size()));
254
255
256       for (SequenceI selectedSequence : seqsel.getSequences())
257       {
258         PhylogenyNode matchingNode = sequencesBoundToNodes.get(selectedSequence);
259         if (matchingNode != null)
260         {
261           treeView.getFoundNodes0().add(matchingNode.getId());
262
263
264           if (!matchingNode.getBranchData().isHasBranchColor())
265           {
266             // Color foundNodesColour = treeView.getTreeColorSet()
267             // .getFoundColor0();
268             // matchingNode.getBranchData()
269             // .setBranchColor(new BranchColor(foundNodesColour));
270
271           }
272
273         }
274
275       }
276
277       treeView.repaint();
278     }
279
280
281   }
282
283   /**
284    * Partially refactored from TreeCanvas
285    */
286   public void partitionTree(final int x)
287   {
288     Phylogeny tree = treeView.getPhylogeny();
289
290     if (!tree.isEmpty())
291     {
292       // should be calculated on each partition as the tree can theoretically
293       // change in the meantime
294       PhylogenyNode furthestNode = PhylogenyMethods
295               .calculateNodeWithMaxDistanceToRoot(tree);
296       furthestNodeX = furthestNode.getXcoord();
297       rootX = tree.getRoot().getXcoord();
298
299       // don't bother if 0 distance tree or clicked x lies outside of tree
300       if (furthestNodeX != rootX && !(x > furthestNodeX))
301       {
302         float threshold = (x - rootX) / (furthestNodeX - rootX);
303         List<PhylogenyNode> foundNodes = getNodesAboveThreshold(threshold,
304                 tree.getRoot());
305
306       }
307     }
308
309
310   }
311
312   public List<PhylogenyNode> getNodesAboveThreshold(double threshold,
313           PhylogenyNode node)
314   {
315
316     List<PhylogenyNode> nodesAboveThreshold = new ArrayList<>();
317
318     parentAvport.setSelectionGroup(null);
319     parentAvport.getAlignment().deleteAllGroups();
320     parentAvport.clearSequenceColours();
321     if (parentAvport.getCodingComplement() != null)
322     {
323       parentAvport.getCodingComplement().setSelectionGroup(null);
324       parentAvport.getCodingComplement().getAlignment().deleteAllGroups();
325       parentAvport.getCodingComplement().clearSequenceColours();
326     }
327
328
329     colourNodesAboveThreshold(nodesAboveThreshold, threshold,
330             node);
331     return nodesAboveThreshold;
332
333   }
334
335   /**
336    * Partially refactored from TreeCanvas colourGroups (can be made nicer).
337    * 
338    * @param nodeList
339    * @param threshold
340    * @param treeLength
341    * @param node
342    * @return
343    */
344   private List<PhylogenyNode> colourNodesAboveThreshold(
345           List<PhylogenyNode> nodeList, double threshold,
346           PhylogenyNode node)
347   {
348
349     for (PhylogenyNode childNode : node.getDescendants())
350     {
351       childNode.getBranchData()
352               .setBranchColor(new BranchColor(Color.black));
353       float nodeCutoff = (childNode.getXcoord() - rootX)
354               / (furthestNodeX - rootX);
355
356       if (nodeCutoff > threshold)
357       {
358         nodeList.add(childNode);
359
360         Color randomColour = new Color((int) (Math.random() * 255),
361                 (int) (Math.random() * 255), (int) (Math.random() * 255));
362         childNode.getBranchData()
363                 .setBranchColor(new BranchColor(randomColour));
364
365         List<SequenceI> groupSeqs = new ArrayList<>();
366         SequenceI seq = nodesBoundToSequences.get(childNode);
367         if (seq != null)
368         {
369           groupSeqs.add(seq);
370           parentAvport.setSequenceColour(seq, randomColour);
371         }
372
373         List<PhylogenyNode> descendantNodes = PhylogenyMethods
374                 .getAllDescendants(childNode);
375         // .forEach instead?
376         for (PhylogenyNode descNode : descendantNodes)
377         {
378           seq = nodesBoundToSequences.get(descNode);
379           if (seq != null)
380           {
381             groupSeqs.add(seq);
382             parentAvport.setSequenceColour(seq, randomColour);
383           }
384
385           descNode.getBranchData()
386                   .setBranchColor(new BranchColor(randomColour));
387         }
388
389         if (groupSeqs != null)
390         {
391           nrTreeGroups++;
392           groupThresholdSequences(groupSeqs, randomColour);
393         }}
394
395       else
396       {
397         colourNodesAboveThreshold(nodeList, threshold, childNode);
398       }
399     }
400
401
402         for (AlignmentPanel associatedPanel : associatedPanels) {
403
404         associatedPanel.updateAnnotation();
405
406         final AlignViewportI codingComplement = associatedPanel.getAlignViewport()
407                 .getCodingComplement();
408         if (codingComplement != null)
409         {
410           // GROSS
411           ((AlignViewport) codingComplement).getAlignPanel()
412                   .updateAnnotation();
413         }
414       }
415
416
417     return nodeList;
418   }
419
420   public void groupThresholdSequences(List<SequenceI> groupedSeqs,
421           Color groupColour)
422   {
423     SequenceGroup treeGroup = new SequenceGroup(groupedSeqs, null, null,
424             true, true, false, 0,
425             parentAvport.getAlignment().getWidth() - 1);
426
427     ColourSchemeI cs = null;
428     if (parentAvport.getGlobalColourScheme() != null)
429     {
430       if (parentAvport.getGlobalColourScheme() instanceof UserColourScheme)
431       {
432         cs = new UserColourScheme(
433                 ((UserColourScheme) parentAvport.getGlobalColourScheme())
434                         .getColours());
435       }
436       else
437       {
438         cs = ColourSchemeProperty.getColourScheme(treeGroup,
439                 ColourSchemeProperty.getColourName(
440                         parentAvport.getGlobalColourScheme()));
441       }
442
443     }
444     treeGroup.setColourScheme(cs);
445     treeGroup.getGroupColourScheme().setThreshold(
446             parentAvport.getResidueShading().getThreshold(),
447             parentAvport.isIgnoreGapsConsensus());
448
449     treeGroup.setName("Tree Group " + nrTreeGroups);
450     treeGroup.setIdColour(groupColour);
451
452     for (AlignmentPanel associatedPanel : associatedPanels)
453     {
454       AlignViewportI altViewport = associatedPanel
455               .getAlignViewport();
456
457       if (altViewport.getGlobalColourScheme() != null
458               && altViewport.getResidueShading()
459                       .conservationApplied())
460       {
461         Conservation conserv = new Conservation(treeGroup.getName(),
462                 treeGroup.getSequences(null), treeGroup.getStartRes(),
463                 treeGroup.getEndRes());
464         conserv.calculate();
465         conserv.verdict(false, altViewport.getConsPercGaps());
466         treeGroup.getGroupColourScheme().setConservation(conserv);
467       }
468
469       altViewport.getAlignment().addGroup(treeGroup);
470       // TODO can we push all of the below into AlignViewportI?
471       final AlignViewportI codingComplement = altViewport
472               .getCodingComplement();
473       if (codingComplement != null)
474       {
475         SequenceGroup mappedGroup = MappingUtils.mapSequenceGroup(treeGroup,
476                 parentAvport, codingComplement);
477         if (mappedGroup.getSequences().size() > 0)
478         {
479           codingComplement.getAlignment().addGroup(mappedGroup);
480           for (SequenceI seq : mappedGroup.getSequences())
481           {
482             codingComplement.setSequenceColour(seq, groupColour.brighter());
483           }
484         }
485       }
486
487     }
488
489   }
490
491   /**
492    * may or may not need an extra repaint on the alignment view (check what kira
493    * does)
494    */
495   @Override
496   public void showNodeSelectionOnAlign(final PhylogenyNode node)
497   {
498
499       if (node.isInternal())
500       {
501         showMatchingChildSequences(node);
502       }
503
504       else
505       {
506         showMatchingSequence(node);
507       }
508
509
510     }
511
512
513
514
515
516   @Override
517   public void showMatchingSequence(final PhylogenyNode nodeToMatch)
518   {
519     SequenceI matchingSequence = nodesBoundToSequences.get(nodeToMatch);
520     if (matchingSequence != null)
521     {
522       long nodeId = nodeToMatch.getId();
523       addOrRemoveInSet(treeView.getFoundNodes0(), nodeId);
524       treeSelectionChanged(matchingSequence);
525       parentAvport.sendSelection();
526
527     }
528   }
529
530   @Override
531   public void showMatchingChildSequences(final PhylogenyNode parentNode)
532   {
533     // redundancy here, Forester already iterates through tree to get all
534     // descendants
535     List<PhylogenyNode> childNodes = PhylogenyMethods
536             .getAllDescendants(parentNode);
537
538
539     for (PhylogenyNode childNode : childNodes)
540     {
541       // childNode.getBranchData().setBranchColor(new BranchColor(Color.BLUE));
542
543       SequenceI matchingSequence = nodesBoundToSequences.get(childNode);
544       if (matchingSequence != null)
545       {
546         long nodeId = childNode.getId();
547         addOrRemoveInSet(treeView.getFoundNodes0(), nodeId);
548
549         treeSelectionChanged(matchingSequence);
550
551       }
552
553     }
554     parentAvport.sendSelection();
555
556
557   }
558
559   /**
560    * Refactored from TreeCanvas.
561    * 
562    * @param sequence
563    *          of the node selected in the tree viewer.
564    */
565   @Override
566   public void treeSelectionChanged(final SequenceI sequence)
567   {
568     if (!parentAvport.isClosed()) // alignment view could be closed
569     {
570       SequenceGroup selected = parentAvport.getSelectionGroup();
571
572       if (selected == null)
573       {
574         selected = new SequenceGroup();
575         parentAvport.setSelectionGroup(selected);
576       }
577
578       selected.setEndRes(parentAvport.getAlignment().getWidth() - 1);
579         selected.addOrRemove(sequence, true);
580     }
581
582   }
583
584   @Override
585   public void sortByTree_actionPerformed()
586   {
587     //
588     // if (treeCanvas.applyToAllViews)
589     // {
590     // final ArrayList<CommandI> commands = new ArrayList<>();
591     // for (AlignmentPanel ap : PaintRefresher
592     // .getAssociatedPanels(parentAvport.getSequenceSetId()))
593     // {
594     // commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
595     // }
596     // parentAvport.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
597     // {
598     //
599     // @Override
600     // public void undoCommand(AlignmentI[] views)
601     // {
602     // for (CommandI tsort : commands)
603     // {
604     // tsort.undoCommand(views);
605     // }
606     // }
607     //
608     // @Override
609     // public int getSize()
610     // {
611     // return commands.size();
612     // }
613     //
614     // @Override
615     // public String getDescription()
616     // {
617     // return "Tree Sort (many views)";
618     // }
619     //
620     // @Override
621     // public void doCommand(AlignmentI[] views)
622     // {
623     //
624     // for (CommandI tsort : commands)
625     // {
626     // tsort.doCommand(views);
627     // }
628     // }
629     // });
630     // for (AlignmentPanel ap : PaintRefresher
631     // .getAssociatedPanels(av.getSequenceSetId()))
632     // {
633     // // ensure all the alignFrames refresh their GI after adding an undo item
634     // ap.alignFrame.updateEditMenuBar();
635     // }
636     // }
637     // else
638     // {
639     // treeCanvas.ap.alignFrame
640     // .addHistoryItem(sortAlignmentIn(treeCanvas.ap));
641     // }
642
643   }
644
645   public CommandI sortAlignmentIn(AlignmentPanel ap)
646   {
647     // TODO: move to alignment view controller
648
649     AlignmentViewport viewport = ap.av;
650     SequenceI[] oldOrder = viewport.getAlignment().getSequencesArray();
651     try
652     {
653     AlignmentSorter.sortByTree(viewport.getAlignment(),
654             nodesBoundToSequences,
655               treeView.getPhylogeny());
656       CommandI undo;
657       undo = new OrderCommand("Tree Sort", oldOrder,
658               viewport.getAlignment());
659
660       ap.paintAlignment(true, false);
661       return undo;
662
663     } catch (Exception e)
664     {
665       System.err.println(e.getMessage());
666     }
667     return null;
668
669   }
670   
671
672
673   /**
674    * TO BE MOVED
675    * 
676    * @param set
677    * @param objectToCheck
678    */
679   public static <E> void addOrRemoveInSet(Set<E> set, E objectToCheck)
680   {
681     if (set.contains(objectToCheck))
682     {
683       set.remove(objectToCheck);
684     }
685     else
686     {
687       set.add(objectToCheck);
688     }
689
690   }
691
692   public AlignmentViewport getParentAvport()
693   {
694     return parentAvport;
695   }
696
697   public void setParentAvport(final AlignmentViewport parentAvport)
698   {
699     this.parentAvport = parentAvport;
700   }
701
702   public AlignmentPanel[] getAssociatedPanels()
703   {
704     return associatedPanels;
705   }
706
707   public void setAssociatedPanels(AlignmentPanel[] associatedPanels)
708   {
709     this.associatedPanels = associatedPanels;
710   }
711
712 }
713
714
715