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