JAL-845 applet colour by tree; translate as cDNA; pull up history list
[jalview.git] / src / jalview / gui / SplitFrame.java
1 package jalview.gui;
2
3 import jalview.api.ViewStyleI;
4 import jalview.datamodel.AlignmentI;
5 import jalview.jbgui.GAlignFrame;
6 import jalview.jbgui.GSplitFrame;
7 import jalview.structure.StructureSelectionManager;
8 import jalview.viewmodel.AlignmentViewport;
9
10 import java.awt.Component;
11 import java.awt.Toolkit;
12 import java.awt.event.ActionEvent;
13 import java.awt.event.ActionListener;
14 import java.awt.event.KeyAdapter;
15 import java.awt.event.KeyEvent;
16 import java.awt.event.KeyListener;
17 import java.beans.PropertyVetoException;
18 import java.util.Map.Entry;
19
20 import javax.swing.AbstractAction;
21 import javax.swing.InputMap;
22 import javax.swing.JComponent;
23 import javax.swing.JMenuItem;
24 import javax.swing.KeyStroke;
25 import javax.swing.event.InternalFrameAdapter;
26 import javax.swing.event.InternalFrameEvent;
27
28 /**
29  * An internal frame on the desktop that hosts a horizontally split view of
30  * linked DNA and Protein alignments. Additional views can be created in linked
31  * pairs, expanded to separate split frames, or regathered into a single frame.
32  * <p>
33  * (Some) operations on each alignment are automatically mirrored on the other.
34  * These include mouseover (highlighting), sequence and column selection,
35  * sequence ordering and sorting, and grouping, colouring and sorting by tree.
36  * 
37  * @author gmcarstairs
38  *
39  */
40 public class SplitFrame extends GSplitFrame
41 {
42   private static final long serialVersionUID = 1L;
43
44   public SplitFrame(GAlignFrame top, GAlignFrame bottom)
45   {
46     super(top, bottom);
47     init();
48   }
49
50   /**
51    * Initialise this frame.
52    */
53   protected void init()
54   {
55     setSize(AlignFrame.DEFAULT_WIDTH, Desktop.instance.getHeight() - 20);
56
57     setCharacterWidth();
58
59     addCloseFrameListener();
60     
61     addKeyListener();
62
63     addKeyBindings();
64   }
65
66   /**
67    * Set the character width for protein to 3 times that for dna.
68    */
69   private void setCharacterWidth()
70   {
71     final AlignViewport topViewport = ((AlignFrame) getTopFrame()).viewport;
72     final AlignViewport bottomViewport = ((AlignFrame) getBottomFrame()).viewport;
73     final AlignmentI topAlignment = topViewport.getAlignment();
74     final AlignmentI bottomAlignment = bottomViewport.getAlignment();
75     AlignmentViewport cdna = topAlignment.isNucleotide() ? topViewport
76             : (bottomAlignment.isNucleotide() ? bottomViewport : null);
77     AlignmentViewport protein = !topAlignment.isNucleotide() ? topViewport
78             : (!bottomAlignment.isNucleotide() ? bottomViewport : null);
79     if (protein != null && cdna != null)
80     {
81       ViewStyleI vs = cdna.getViewStyle();
82       vs.setCharWidth(3 * vs.getCharWidth());
83       protein.setViewStyle(vs);
84     }
85   }
86
87   /**
88    * Add a listener to tidy up when the frame is closed.
89    */
90   protected void addCloseFrameListener()
91   {
92     addInternalFrameListener(new InternalFrameAdapter()
93     {
94       @Override
95       public void internalFrameClosed(InternalFrameEvent evt)
96       {
97         if (getTopFrame() instanceof AlignFrame)
98         {
99           ((AlignFrame) getTopFrame())
100                   .closeMenuItem_actionPerformed(true);
101         }
102         if (getBottomFrame() instanceof AlignFrame)
103         {
104           ((AlignFrame) getBottomFrame())
105                   .closeMenuItem_actionPerformed(true);
106         }
107       };
108     });
109   }
110
111   /**
112    * Add a key listener that delegates to whichever split component the mouse is
113    * in (or does nothing if neither).
114    */
115   protected void addKeyListener()
116   {
117     addKeyListener(new KeyAdapter() {
118
119       @Override
120       public void keyPressed(KeyEvent e)
121       {
122         AlignFrame af = (AlignFrame) getFrameAtMouse();
123
124         /*
125          * Intercept and override any keys here if wanted.
126          */
127         if (!overrideKey(e, af))
128         {
129           if (af != null)
130           {
131             for (KeyListener kl : af.getKeyListeners())
132             {
133               kl.keyPressed(e);
134             }
135           }
136         }
137       }
138
139       @Override
140       public void keyReleased(KeyEvent e)
141       {
142         Component c = getFrameAtMouse();
143         if (c != null)
144         {
145           for (KeyListener kl : c.getKeyListeners())
146           {
147             kl.keyReleased(e);
148           }
149         }
150       }
151       
152     });
153   }
154
155   /**
156    * Returns true if the key event is overriden and actioned (or ignored) here,
157    * else returns false, indicating it should be delegated to the AlignFrame's
158    * usual handler.
159    * <p>
160    * We can't handle Cmd-Key combinations here, instead this is done by
161    * overriding key bindings.
162    * 
163    * @see addKeyOverrides
164    * @param e
165    * @param af
166    * @return
167    */
168   protected boolean overrideKey(KeyEvent e, AlignFrame af)
169   {
170     boolean actioned = false;
171     int keyCode = e.getKeyCode();
172     switch (keyCode)
173     {
174     case KeyEvent.VK_DOWN:
175       if (e.isAltDown() || !af.viewport.cursorMode)
176       {
177         /*
178          * Key down (or Alt-key-down in cursor mode) - move selected sequences
179          */
180         ((AlignFrame) getTopFrame()).moveSelectedSequences(false);
181         ((AlignFrame) getBottomFrame()).moveSelectedSequences(false);
182         actioned = true;
183         e.consume();
184       }
185       break;
186     case KeyEvent.VK_UP:
187       if (e.isAltDown() || !af.viewport.cursorMode)
188       {
189         /*
190          * Key up (or Alt-key-up in cursor mode) - move selected sequences
191          */
192         ((AlignFrame) getTopFrame()).moveSelectedSequences(true);
193         ((AlignFrame) getBottomFrame()).moveSelectedSequences(true);
194         actioned = true;
195         e.consume();
196       }
197     default:
198     }
199     return actioned;
200   }
201
202   /**
203    * Set key bindings (recommended for Swing over key accelerators).
204    */
205   private void addKeyBindings()
206   {
207     overrideDelegatedKeyBindings();
208
209     overrideImplementedKeyBindings();
210   }
211
212   /**
213    * Override key bindings with alternative action methods implemented in this
214    * class.
215    */
216   protected void overrideImplementedKeyBindings()
217   {
218     overrideNewView();
219     overrideCloseView();
220     overrideExpandViews();
221     overrideGatherViews();
222   }
223
224   /**
225    * Replace Cmd-W close view action with our version.
226    */
227   protected void overrideCloseView()
228   {
229     AbstractAction action;
230     /*
231      * Ctrl-W / Cmd-W - close view or window
232      */
233     KeyStroke key_cmdW = KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit
234             .getDefaultToolkit().getMenuShortcutKeyMask(), false);
235     action = new AbstractAction()
236     {
237       @Override
238       public void actionPerformed(ActionEvent e)
239       {
240         closeView_actionPerformed();
241       }
242     };
243     overrideKeyBinding(key_cmdW, action);
244   }
245
246   /**
247    * Replace Cmd-T new view action with our version.
248    */
249   protected void overrideNewView()
250   {
251     /*
252      * Ctrl-T / Cmd-T open new view
253      */
254     KeyStroke key_cmdT = KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit
255             .getDefaultToolkit().getMenuShortcutKeyMask(), false);
256     AbstractAction action = new AbstractAction()
257     {
258       @Override
259       public void actionPerformed(ActionEvent e)
260       {
261         newView_actionPerformed();
262       }
263     };
264     overrideKeyBinding(key_cmdT, action);
265   }
266
267   /**
268    * For now, delegates key events to the corresponding key accelerator for the
269    * AlignFrame that the mouse is in. Hopefully can be simplified in future if
270    * AlignFrame is changed to use key bindings rather than accelerators.
271    */
272   protected void overrideDelegatedKeyBindings()
273   {
274     if (getTopFrame() instanceof AlignFrame)
275     {
276       /*
277        * Get all accelerator keys in the top frame (the bottom should be
278        * identical) and override each one.
279        */
280       for (Entry<KeyStroke, JMenuItem> acc : ((AlignFrame) getTopFrame())
281               .getAccelerators().entrySet())
282       {
283         overrideKeyBinding(acc);
284       }
285     }
286   }
287
288   /**
289    * Overrides an AlignFrame key accelerator with our version which delegates to
290    * the action listener in whichever frame has the mouse (and does nothing if
291    * neither has).
292    * 
293    * @param acc
294    */
295   private void overrideKeyBinding(Entry<KeyStroke, JMenuItem> acc)
296   {
297     final KeyStroke ks = acc.getKey();
298     InputMap inputMap = this.getInputMap(JComponent.WHEN_FOCUSED);
299     inputMap.put(ks, ks);
300     this.getActionMap().put(ks, new AbstractAction()
301     {
302       @Override
303       public void actionPerformed(ActionEvent e)
304       {
305         Component c = getFrameAtMouse();
306         if (c != null && c instanceof AlignFrame)
307         {
308           for (ActionListener a : ((AlignFrame) c).getAccelerators()
309                   .get(ks).getActionListeners())
310           {
311             a.actionPerformed(null);
312           }
313         }
314       }
315     });
316   }
317
318   /**
319    * Replace an accelerator key's action with the specified action.
320    * 
321    * @param ks
322    */
323   protected void overrideKeyBinding(KeyStroke ks, AbstractAction action)
324   {
325     this.getActionMap().put(ks, action);
326     overrideMenuItem(ks, action);
327   }
328
329   /**
330    * Create and link new views (with matching names) in both panes.
331    * <p>
332    * Note this is _not_ multiple tabs, each hosting a split pane view, rather it
333    * is a single split pane with each split holding multiple tabs which are
334    * linked in pairs.
335    * <p>
336    * TODO implement instead with a tabbed holder in the SplitView, each tab
337    * holding a single JSplitPane. Would avoid a duplicated tab, at the cost of
338    * some additional coding.
339    */
340   protected void newView_actionPerformed()
341   {
342     AlignFrame topFrame = (AlignFrame) getTopFrame();
343     AlignFrame bottomFrame = (AlignFrame) getBottomFrame();
344
345     AlignmentPanel newTopPanel = topFrame.newView(null, true);
346     AlignmentPanel newBottomPanel = bottomFrame.newView(null, true);
347
348     /*
349      * This currently (for the first new view only) leaves the top pane on tab 0
350      * but the bottom on tab 1. This results from 'setInitialTabVisible' echoing
351      * from the bottom back to the first frame. Next line is a fudge to work
352      * around this. TODO find a better way.
353      */
354     if (topFrame.getTabIndex() != bottomFrame.getTabIndex())
355     {
356       topFrame.setDisplayedView(newTopPanel);
357     }
358
359     newBottomPanel.av.viewName = newTopPanel.av.viewName;
360     newTopPanel.av.setCodingComplement(newBottomPanel.av);
361
362     final StructureSelectionManager ssm = StructureSelectionManager
363             .getStructureSelectionManager(Desktop.instance);
364     ssm.addCommandListener(newTopPanel.av);
365     ssm.addCommandListener(newBottomPanel.av);
366   }
367
368   /**
369    * Close the currently selected view in both panes. If there is only one view,
370    * close this split frame.
371    */
372   protected void closeView_actionPerformed()
373   {
374     int viewCount = ((AlignFrame) getTopFrame()).getAlignPanels().size();
375     if (viewCount < 2)
376     {
377       close();
378       return;
379     }
380
381     AlignmentPanel topPanel = ((AlignFrame) getTopFrame()).alignPanel;
382     AlignmentPanel bottomPanel = ((AlignFrame) getBottomFrame()).alignPanel;
383
384     ((AlignFrame) getTopFrame()).closeView(topPanel);
385     ((AlignFrame) getBottomFrame()).closeView(bottomPanel);
386
387   }
388
389   /**
390    * Close child frames and this split frame.
391    */
392   public void close()
393   {
394     ((AlignFrame) getTopFrame()).closeMenuItem_actionPerformed(true);
395     ((AlignFrame) getBottomFrame()).closeMenuItem_actionPerformed(true);
396     try
397     {
398       this.setClosed(true);
399     } catch (PropertyVetoException e)
400     {
401       // ignore
402     }
403   }
404
405   /**
406    * Replace AlignFrame 'expand views' action with SplitFrame version.
407    */
408   protected void overrideExpandViews()
409   {
410     KeyStroke key_X = KeyStroke.getKeyStroke(KeyEvent.VK_X, 0, false);
411     AbstractAction action = new AbstractAction()
412     {
413       @Override
414       public void actionPerformed(ActionEvent e)
415       {
416         expandViews_actionPerformed();
417       }
418     };
419     overrideMenuItem(key_X, action);
420   }
421
422   /**
423    * Replace AlignFrame 'gather views' action with SplitFrame version.
424    */
425   protected void overrideGatherViews()
426   {
427     KeyStroke key_G = KeyStroke.getKeyStroke(KeyEvent.VK_G, 0, false);
428     AbstractAction action = new AbstractAction()
429     {
430       @Override
431       public void actionPerformed(ActionEvent e)
432       {
433         gatherViews_actionPerformed();
434       }
435     };
436     overrideMenuItem(key_G, action);
437   }
438
439   /**
440    * Override the menu action associated with the keystroke in the child frames,
441    * replacing it with the given action.
442    * 
443    * @param ks
444    * @param action
445    */
446   private void overrideMenuItem(KeyStroke ks, AbstractAction action)
447   {
448     overrideMenuItem(ks, action, getTopFrame());
449     overrideMenuItem(ks, action, getBottomFrame());
450   }
451
452   /**
453    * Override the menu action associated with the keystroke in one child frame,
454    * replacing it with the given action. Mwahahahaha.
455    * 
456    * @param key
457    * @param action
458    * @param comp
459    */
460   private void overrideMenuItem(KeyStroke key, final AbstractAction action,
461           JComponent comp)
462   {
463     if (comp instanceof AlignFrame)
464     {
465       JMenuItem mi = ((AlignFrame) comp).getAccelerators().get(key);
466       if (mi != null)
467       {
468         for (ActionListener al : mi.getActionListeners())
469         {
470           mi.removeActionListener(al);
471         }
472         mi.addActionListener(new ActionListener()
473         {
474           @Override
475           public void actionPerformed(ActionEvent e)
476           {
477             action.actionPerformed(e);
478           }
479         });
480       }
481     }
482   }
483
484   /**
485    * Expand any multiple views (which are always in pairs) into separate split
486    * frames.
487    */
488   protected void expandViews_actionPerformed()
489   {
490     Desktop.instance.explodeViews(this);
491   }
492
493   /**
494    * Gather any other SplitFrame views of this alignment back in as multiple
495    * (pairs of) views in this SplitFrame.
496    */
497   protected void gatherViews_actionPerformed()
498   {
499     Desktop.instance.gatherViews(this);
500   }
501 }