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