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