7a0668de3133d86694e912b29cd80ae0a091a994
[jalview.git] / src / jalview / ext / archaeopteryx / JalviewBinding.java
1 package jalview.ext.archaeopteryx;
2
3 import jalview.datamodel.ColumnSelection;
4 import jalview.datamodel.HiddenColumns;
5 import jalview.datamodel.SequenceGroup;
6 import jalview.datamodel.SequenceI;
7 import jalview.ext.treeviewer.ExternalTreeViewerBindingI;
8 import jalview.gui.PaintRefresher;
9 import jalview.structure.SelectionSource;
10 import jalview.structure.StructureSelectionManager;
11 import jalview.viewmodel.AlignmentViewport;
12
13 import java.awt.event.ActionEvent;
14 import java.awt.event.InputEvent;
15 import java.awt.event.MouseEvent;
16 import java.util.HashSet;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Set;
20
21 import javax.swing.JTabbedPane;
22 import javax.swing.SwingUtilities;
23 import javax.swing.event.ChangeEvent;
24 import javax.swing.event.ChangeListener;
25
26 import org.forester.archaeopteryx.MainFrame;
27 import org.forester.phylogeny.Phylogeny;
28 import org.forester.phylogeny.PhylogenyMethods;
29 import org.forester.phylogeny.PhylogenyNode;
30
31 /**
32  * Class for binding the Archaeopteryx tree viewer to the Jalview alignment that
33  * it originates from, meaning that selecting sequences in the tree viewer also
34  * selects them in the alignment view and vice versa.
35  * 
36  * @author kjvanderheide
37  *
38  */
39 public final class JalviewBinding
40         implements ExternalTreeViewerBindingI<PhylogenyNode>
41 {
42   private final MainFrame aptxFrame;
43
44   private org.forester.archaeopteryx.TreePanel currentTreeView;
45
46   private final AlignmentViewport parentAvport;
47
48   private JTabbedPane treeTabs;
49
50   private final StructureSelectionManager ssm;
51
52   private Map<SequenceI, PhylogenyNode> sequencesBoundToNodes;
53
54   private Map<PhylogenyNode, SequenceI> nodesBoundToSequences;
55
56   /**
57    * 
58    * @param archaeopteryx
59    * 
60    * @param jalviewAlignmentViewport
61    *          alignment viewport from which the tree was calculated.
62    * 
63    * @param alignMappedToNodes
64    *          map with sequences used to calculate the tree and matching tree
65    *          nodes as key, value pair respectively.
66    * 
67    * @param nodesMappedToAlign
68    *          map with tree nodes and matching sequences used to calculate the
69    *          tree as key, value pair respectively.
70    */
71   public JalviewBinding(final MainFrame archaeopteryx,
72           final AlignmentViewport jalviewAlignmentViewport,
73           final Map<SequenceI, PhylogenyNode> alignMappedToNodes,
74           final Map<PhylogenyNode, SequenceI> nodesMappedToAlign)
75   {
76     // deal with/prohibit null values here as that will cause problems
77     aptxFrame = archaeopteryx;
78     parentAvport = jalviewAlignmentViewport;
79     sequencesBoundToNodes = alignMappedToNodes;
80     nodesBoundToSequences = nodesMappedToAlign;
81
82     treeTabs = aptxFrame.getMainPanel().getTabbedPane();
83     ssm = parentAvport.getStructureSelectionManager();
84
85     // archaeopteryx.getMainPanel().getControlPanel().setColorBranches(true);
86     
87     ssm.addSelectionListener(this);
88
89     int tabCount = treeTabs.getTabCount();
90
91     for (int i = 0; i < tabCount; i++)
92     {
93       // roundabout way to select each tree because getComponentAt(i) requires
94       // casting to TreePanel which doesn't work
95       treeTabs.setSelectedIndex(i);
96       currentTreeView = aptxFrame.getMainPanel().getCurrentTreePanel();
97       currentTreeView.addMouseListener(this);
98       PaintRefresher.Register(currentTreeView,
99               parentAvport.getSequenceSetId());
100     }
101
102
103     treeTabs.addChangeListener(new ChangeListener()
104     {
105
106       @Override
107       public void stateChanged(ChangeEvent e)
108       {
109
110         SwingUtilities.invokeLater(new Runnable()
111         {
112
113           @Override
114           /**
115            * Resend the selection to the tree view when tabs get switched, this
116            * has to be buried in invokeLater as Forester first resets the tree
117            * view on switching tabs, without invokeLater this would get called
118            * before Forester resets which would nullify the selection.
119            */
120           public void run()
121           {
122             currentTreeView = aptxFrame.getMainPanel()
123                     .getCurrentTreePanel();
124             parentAvport.sendSelection();
125
126           }
127         });
128
129       }
130       
131     });
132
133   }
134
135   @Override
136   public void actionPerformed(ActionEvent e)
137   {
138   }
139
140   @Override
141   public void mouseClicked(MouseEvent e)
142   {
143     SwingUtilities.invokeLater(new Runnable() {
144
145       @Override
146       /**
147        * invokeLater so that this always runs after Forester's mouseClicked
148        */
149       public void run()
150       {
151
152         final PhylogenyNode node = currentTreeView.findNode(e.getX(),
153                 e.getY());
154         if (node != null)
155         {
156           if ((e.getModifiers() & InputEvent.SHIFT_MASK) == 0) // clear previous
157           // selection if shift
158           // IS NOT pressed
159           {
160
161             parentAvport.setSelectionGroup(null);
162
163           }
164           showNodeSelectionOnAlign(node);
165         }
166         else
167         {
168           partitionTree(e);
169         
170         
171       }
172       
173       }
174     });
175
176
177   }
178
179   @Override
180   public void mousePressed(final MouseEvent e)
181   {
182
183   }
184   @Override
185   public void mouseReleased(MouseEvent e)
186   {
187   }
188
189   @Override
190   public void mouseEntered(MouseEvent e)
191   {
192   }
193
194   @Override
195   public void mouseExited(MouseEvent e)
196   {
197   }
198
199
200   @Override
201   public void selection(final SequenceGroup seqsel,
202           final ColumnSelection colsel, final HiddenColumns hidden,
203           final SelectionSource source)
204   {
205     if (source == parentAvport) // check if source is alignment from where the
206     // tree originates
207     {
208       currentTreeView.setFoundNodes0(
209               new HashSet<Long>(seqsel.getSequences().size()));
210
211       for (SequenceI selectedSequence : seqsel.getSequences())
212       {
213         PhylogenyNode matchingNode = sequencesBoundToNodes.get(selectedSequence);
214         if (matchingNode != null)
215         {
216           currentTreeView.getFoundNodes0().add(matchingNode.getId());
217         }
218
219       }
220       aptxFrame.repaint();
221
222     }
223
224
225   }
226
227   /**
228    * Partially refactored from TreeCanvas
229    */
230   public void partitionTree(final MouseEvent e)
231   {
232     int x = e.getX();
233     int lineLength = currentTreeView.getHeight();
234
235     Phylogeny tree = currentTreeView.getPhylogeny();
236     double treeHeight = tree.calculateHeight(true);
237
238
239
240     if (treeHeight != 0)
241     {
242       int viewWidth = currentTreeView.getWidth();
243
244       // treeView.validate();
245
246       // System.out.println("selection");
247       // System.out.println(x);
248       // System.out.println("-------------");
249       // System.out.println("width");
250       // System.out.println(viewWidth);
251
252     }
253
254
255   }
256   
257
258
259   @Override
260   public void showNodeSelectionOnAlign(final PhylogenyNode node)
261   {
262
263       if (node.isInternal())
264       {
265         showMatchingChildSequences(node);
266       }
267
268       else
269       {
270         showMatchingSequence(node);
271       }
272
273     }
274
275
276
277
278
279   @Override
280   public void showMatchingSequence(final PhylogenyNode nodeToMatch)
281   {
282     SequenceI matchingSequence = nodesBoundToSequences.get(nodeToMatch);
283     if (matchingSequence != null)
284     {
285       long nodeId = nodeToMatch.getId();
286       addOrRemoveInSet(currentTreeView.getFoundNodes0(), nodeId);
287       treeSelectionChanged(matchingSequence);
288       parentAvport.sendSelection();
289
290     }
291   }
292
293   @Override
294   public void showMatchingChildSequences(final PhylogenyNode parentNode)
295   {
296     List<PhylogenyNode> childNodes = PhylogenyMethods
297             .getAllDescendants(parentNode);
298
299
300     for (PhylogenyNode childNode : childNodes)
301     {
302       // childNode.getBranchData().setBranchColor(new BranchColor(Color.BLUE));
303
304       SequenceI matchingSequence = nodesBoundToSequences.get(childNode);
305       if (matchingSequence != null)
306       {
307         long nodeId = childNode.getId();
308         addOrRemoveInSet(currentTreeView.getFoundNodes0(), nodeId);
309
310         treeSelectionChanged(matchingSequence);
311
312       }
313
314     }
315     parentAvport.sendSelection();
316
317
318   }
319
320   /**
321    * Refactored from TreeCanvas.
322    * 
323    * @param sequence
324    *          of the node selected in the tree viewer.
325    */
326   @Override
327   public void treeSelectionChanged(final SequenceI sequence)
328   {
329     if (!parentAvport.isClosed()) // alignment view could be closed
330     {
331       SequenceGroup selected = parentAvport.getSelectionGroup();
332
333       if (selected == null)
334       {
335         selected = new SequenceGroup();
336         parentAvport.setSelectionGroup(selected);
337       }
338
339       selected.setEndRes(parentAvport.getAlignment().getWidth() - 1);
340         selected.addOrRemove(sequence, true);
341     }
342
343   }
344   public void sortByTree_actionPerformed() {
345     // parentAvport.mirrorCommand(command, undo, ssm, source);
346
347     // alignFrame
348     // .addHistoryItem(sortAlignmentIn(treeCanvas.ap));
349     
350   }
351   
352
353   /**
354    * sort the associated alignment view by the current tree.
355    * 
356    * @param e
357    */
358   // @Override
359   // public void sortByTree_actionPerformed()// modify for Aptx
360   // {
361   //
362   // // if (treeCanvas.applyToAllViews)
363   //
364   // final ArrayList<CommandI> commands = new ArrayList<>();
365   // for (AlignmentPanel ap : PaintRefresher
366   // .getAssociatedPanels(parentAvport.getSequenceSetId()))
367   // {
368   // commands.add(sortAlignmentIn(ap.av.getAlignPanel()));
369   // }
370   // av.getAlignPanel().alignFrame.addHistoryItem(new CommandI()
371   // {
372   //
373   // @Override
374   // public void undoCommand(AlignmentI[] views)
375   // {
376   // for (CommandI tsort : commands)
377   // {
378   // tsort.undoCommand(views);
379   // }
380   // }
381   //
382   // @Override
383   // public int getSize()
384   // {
385   // return commands.size();
386   // }
387   //
388   // @Override
389   // public String getDescription()
390   // {
391   // return "Tree Sort (many views)";
392   // }
393   //
394   // @Override
395   // public void doCommand(AlignmentI[] views)
396   // {
397   //
398   // for (CommandI tsort : commands)
399   // {
400   // tsort.doCommand(views);
401   // }
402   // }
403   // });
404   // for (AlignmentPanel ap : PaintRefresher
405   // .getAssociatedPanels(av.getSequenceSetId()))
406   // {
407   // // ensure all the alignFrames refresh their GI after adding an undo item
408   // ap.alignFrame.updateEditMenuBar();
409   // }
410   // }
411   // else
412   // {
413   // treeCanvas.ap.alignFrame
414   // .addHistoryItem(sortAlignmentIn(treeCanvas.ap));
415   // }
416
417
418
419   /**
420    * TO BE MOVED
421    * 
422    * @param set
423    * @param objectToCheck
424    */
425   public static <E> void addOrRemoveInSet(Set<E> set, E objectToCheck)
426   {
427     if (set.contains(objectToCheck))
428     {
429       set.remove(objectToCheck);
430     }
431     else
432     {
433       set.add(objectToCheck);
434     }
435
436   }
437
438   public AlignmentViewport getParentAvport()
439   {
440     return parentAvport;
441   }
442
443   public org.forester.archaeopteryx.TreePanel getTreeView()
444   {
445     return currentTreeView;
446   }
447
448 }
449
450
451
452