2929a007203a66e16413dc528eea970d64caadd0
[jalview.git] / src / jalview / gui / SplitFrame.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9.0b1)
3  * Copyright (C) 2015 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import jalview.api.SplitContainerI;
24 import jalview.api.ViewStyleI;
25 import jalview.datamodel.AlignmentI;
26 import jalview.jbgui.GAlignFrame;
27 import jalview.jbgui.GSplitFrame;
28 import jalview.structure.StructureSelectionManager;
29 import jalview.util.Platform;
30 import jalview.viewmodel.AlignmentViewport;
31
32 import java.awt.Component;
33 import java.awt.Toolkit;
34 import java.awt.event.ActionEvent;
35 import java.awt.event.ActionListener;
36 import java.awt.event.KeyAdapter;
37 import java.awt.event.KeyEvent;
38 import java.awt.event.KeyListener;
39 import java.beans.PropertyVetoException;
40 import java.util.Map.Entry;
41 import java.util.Set;
42
43 import javax.swing.AbstractAction;
44 import javax.swing.InputMap;
45 import javax.swing.JComponent;
46 import javax.swing.JMenuItem;
47 import javax.swing.KeyStroke;
48 import javax.swing.UIDefaults;
49 import javax.swing.UIManager;
50 import javax.swing.event.InternalFrameAdapter;
51 import javax.swing.event.InternalFrameEvent;
52
53 /**
54  * An internal frame on the desktop that hosts a horizontally split view of
55  * linked DNA and Protein alignments. Additional views can be created in linked
56  * pairs, expanded to separate split frames, or regathered into a single frame.
57  * <p>
58  * (Some) operations on each alignment are automatically mirrored on the other.
59  * These include mouseover (highlighting), sequence and column selection,
60  * sequence ordering and sorting, and grouping, colouring and sorting by tree.
61  * 
62  * @author gmcarstairs
63  *
64  */
65 public class SplitFrame extends GSplitFrame implements SplitContainerI
66 {
67   private static final long serialVersionUID = 1L;
68
69   public SplitFrame(GAlignFrame top, GAlignFrame bottom)
70   {
71     super(top, bottom);
72     init();
73   }
74
75   /**
76    * Initialise this frame.
77    */
78   protected void init()
79   {
80     getTopFrame().setSplitFrame(this);
81     getBottomFrame().setSplitFrame(this);
82     getTopFrame().setVisible(true);
83     getBottomFrame().setVisible(true);
84
85     ((AlignFrame) getTopFrame()).getViewport().setCodingComplement(
86             ((AlignFrame) getBottomFrame()).getViewport());
87
88     /*
89      * estimate width and height of SplitFrame; this.getInsets() doesn't seem to
90      * give the full additional size (a few pixels short)
91      */
92     UIDefaults defaults = UIManager.getDefaults();
93     Set<Object> keySet = defaults.keySet();
94     for (Object key : keySet)
95     {
96       System.out.println(key.toString() + " = "
97               + UIManager.get(key).toString());
98     }
99     int widthFudge = Platform.isAMac() ? 28 : 28; // Windows tbc
100     int heightFudge = Platform.isAMac() ? 50 : 50; // tbc
101     int width = ((AlignFrame) getTopFrame()).getWidth() + widthFudge;
102     int height = ((AlignFrame) getTopFrame()).getHeight()
103             + ((AlignFrame) getBottomFrame()).getHeight() + DIVIDER_SIZE
104             + heightFudge;
105     height = fitHeightToDesktop(height);
106     setSize(width, height);
107
108     adjustLayout();
109
110     addCloseFrameListener();
111
112     addKeyListener();
113
114     addKeyBindings();
115
116     addCommandListeners();
117   }
118
119   /**
120    * Reduce the height if too large to fit in the Desktop. Also adjust the
121    * divider location in proportion.
122    * 
123    * @param height
124    *          in pixels
125    * @return original or reduced height
126    */
127   public int fitHeightToDesktop(int height)
128   {
129     // allow about 65 pixels for Desktop decorators on Windows
130
131     int newHeight = Math.min(height, Desktop.instance.getHeight() - 65);
132     if (newHeight != height)
133     {
134       int oldDividerLocation = getDividerLocation();
135       setDividerLocation(oldDividerLocation * newHeight / height);
136     }
137     return newHeight;
138   }
139
140   /**
141    * Set the top and bottom frames to listen to each others Commands (e.g. Edit,
142    * Order).
143    */
144   protected void addCommandListeners()
145   {
146     // TODO if CommandListener is only ever 1:1 for complementary views,
147     // may change broadcast pattern to direct messaging (more efficient)
148     final StructureSelectionManager ssm = StructureSelectionManager
149             .getStructureSelectionManager(Desktop.instance);
150     ssm.addCommandListener(((AlignFrame) getTopFrame()).getViewport());
151     ssm.addCommandListener(((AlignFrame) getBottomFrame()).getViewport());
152   }
153
154   /**
155    * Do any tweaking and twerking of the layout wanted.
156    */
157   public void adjustLayout()
158   {
159     /*
160      * Ensure sequence ids are the same width so sequences line up
161      */
162     int w1 = ((AlignFrame) getTopFrame()).getViewport().getIdWidth();
163     int w2 = ((AlignFrame) getBottomFrame()).getViewport().getIdWidth();
164     int w3 = Math.max(w1, w2);
165     if (w1 != w3)
166     {
167       ((AlignFrame) getTopFrame()).getViewport().setIdWidth(w3);
168     }
169     if (w2 != w3)
170     {
171       ((AlignFrame) getBottomFrame()).getViewport().setIdWidth(w3);
172     }
173
174     /*
175      * Scale protein to either 1 or 3 times character width of dna
176      */
177     final AlignViewport topViewport = ((AlignFrame) getTopFrame()).viewport;
178     final AlignViewport bottomViewport = ((AlignFrame) getBottomFrame()).viewport;
179     final AlignmentI topAlignment = topViewport.getAlignment();
180     final AlignmentI bottomAlignment = bottomViewport.getAlignment();
181     AlignmentViewport cdna = topAlignment.isNucleotide() ? topViewport
182             : (bottomAlignment.isNucleotide() ? bottomViewport : null);
183     AlignmentViewport protein = !topAlignment.isNucleotide() ? topViewport
184             : (!bottomAlignment.isNucleotide() ? bottomViewport : null);
185     if (protein != null && cdna != null)
186     {
187       ViewStyleI vs = protein.getViewStyle();
188       int scale = vs.isScaleProteinAsCdna() ? 3 : 1;
189       vs.setCharWidth(scale * cdna.getViewStyle().getCharWidth());
190       protein.setViewStyle(vs);
191     }
192   }
193
194   /**
195    * Add a listener to tidy up when the frame is closed.
196    */
197   protected void addCloseFrameListener()
198   {
199     addInternalFrameListener(new InternalFrameAdapter()
200     {
201       @Override
202       public void internalFrameClosed(InternalFrameEvent evt)
203       {
204         close();
205       };
206     });
207   }
208
209   /**
210    * Add a key listener that delegates to whichever split component the mouse is
211    * in (or does nothing if neither).
212    */
213   protected void addKeyListener()
214   {
215     addKeyListener(new KeyAdapter()
216     {
217
218       @Override
219       public void keyPressed(KeyEvent e)
220       {
221         AlignFrame af = (AlignFrame) getFrameAtMouse();
222
223         /*
224          * Intercept and override any keys here if wanted.
225          */
226         if (!overrideKey(e, af))
227         {
228           if (af != null)
229           {
230             for (KeyListener kl : af.getKeyListeners())
231             {
232               kl.keyPressed(e);
233             }
234           }
235         }
236       }
237
238       @Override
239       public void keyReleased(KeyEvent e)
240       {
241         Component c = getFrameAtMouse();
242         if (c != null)
243         {
244           for (KeyListener kl : c.getKeyListeners())
245           {
246             kl.keyReleased(e);
247           }
248         }
249       }
250
251     });
252   }
253
254   /**
255    * Returns true if the key event is overriden and actioned (or ignored) here,
256    * else returns false, indicating it should be delegated to the AlignFrame's
257    * usual handler.
258    * <p>
259    * We can't handle Cmd-Key combinations here, instead this is done by
260    * overriding key bindings.
261    * 
262    * @see addKeyOverrides
263    * @param e
264    * @param af
265    * @return
266    */
267   protected boolean overrideKey(KeyEvent e, AlignFrame af)
268   {
269     boolean actioned = false;
270     int keyCode = e.getKeyCode();
271     switch (keyCode)
272     {
273     case KeyEvent.VK_DOWN:
274       if (e.isAltDown() || !af.viewport.cursorMode)
275       {
276         /*
277          * Key down (or Alt-key-down in cursor mode) - move selected sequences
278          */
279         ((AlignFrame) getTopFrame()).moveSelectedSequences(false);
280         ((AlignFrame) getBottomFrame()).moveSelectedSequences(false);
281         actioned = true;
282         e.consume();
283       }
284       break;
285     case KeyEvent.VK_UP:
286       if (e.isAltDown() || !af.viewport.cursorMode)
287       {
288         /*
289          * Key up (or Alt-key-up in cursor mode) - move selected sequences
290          */
291         ((AlignFrame) getTopFrame()).moveSelectedSequences(true);
292         ((AlignFrame) getBottomFrame()).moveSelectedSequences(true);
293         actioned = true;
294         e.consume();
295       }
296     default:
297     }
298     return actioned;
299   }
300
301   /**
302    * Set key bindings (recommended for Swing over key accelerators).
303    */
304   private void addKeyBindings()
305   {
306     overrideDelegatedKeyBindings();
307
308     overrideImplementedKeyBindings();
309   }
310
311   /**
312    * Override key bindings with alternative action methods implemented in this
313    * class.
314    */
315   protected void overrideImplementedKeyBindings()
316   {
317     overrideFind();
318     overrideNewView();
319     overrideCloseView();
320     overrideExpandViews();
321     overrideGatherViews();
322   }
323
324   /**
325    * Replace Cmd-W close view action with our version.
326    */
327   protected void overrideCloseView()
328   {
329     AbstractAction action;
330     /*
331      * Ctrl-W / Cmd-W - close view or window
332      */
333     KeyStroke key_cmdW = KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit
334             .getDefaultToolkit().getMenuShortcutKeyMask(), false);
335     action = new AbstractAction()
336     {
337       @Override
338       public void actionPerformed(ActionEvent e)
339       {
340         closeView_actionPerformed();
341       }
342     };
343     overrideKeyBinding(key_cmdW, action);
344   }
345
346   /**
347    * Replace Cmd-T new view action with our version.
348    */
349   protected void overrideNewView()
350   {
351     /*
352      * Ctrl-T / Cmd-T open new view
353      */
354     KeyStroke key_cmdT = KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit
355             .getDefaultToolkit().getMenuShortcutKeyMask(), false);
356     AbstractAction action = new AbstractAction()
357     {
358       @Override
359       public void actionPerformed(ActionEvent e)
360       {
361         newView_actionPerformed();
362       }
363     };
364     overrideKeyBinding(key_cmdT, action);
365   }
366
367   /**
368    * For now, delegates key events to the corresponding key accelerator for the
369    * AlignFrame that the mouse is in. Hopefully can be simplified in future if
370    * AlignFrame is changed to use key bindings rather than accelerators.
371    */
372   protected void overrideDelegatedKeyBindings()
373   {
374     if (getTopFrame() instanceof AlignFrame)
375     {
376       /*
377        * Get all accelerator keys in the top frame (the bottom should be
378        * identical) and override each one.
379        */
380       for (Entry<KeyStroke, JMenuItem> acc : ((AlignFrame) getTopFrame())
381               .getAccelerators().entrySet())
382       {
383         overrideKeyBinding(acc);
384       }
385     }
386   }
387
388   /**
389    * Overrides an AlignFrame key accelerator with our version which delegates to
390    * the action listener in whichever frame has the mouse (and does nothing if
391    * neither has).
392    * 
393    * @param acc
394    */
395   private void overrideKeyBinding(Entry<KeyStroke, JMenuItem> acc)
396   {
397     final KeyStroke ks = acc.getKey();
398     InputMap inputMap = this.getInputMap(JComponent.WHEN_FOCUSED);
399     inputMap.put(ks, ks);
400     this.getActionMap().put(ks, new AbstractAction()
401     {
402       @Override
403       public void actionPerformed(ActionEvent e)
404       {
405         Component c = getFrameAtMouse();
406         if (c != null && c instanceof AlignFrame)
407         {
408           for (ActionListener a : ((AlignFrame) c).getAccelerators()
409                   .get(ks).getActionListeners())
410           {
411             a.actionPerformed(null);
412           }
413         }
414       }
415     });
416   }
417
418   /**
419    * Replace an accelerator key's action with the specified action.
420    * 
421    * @param ks
422    */
423   protected void overrideKeyBinding(KeyStroke ks, AbstractAction action)
424   {
425     this.getActionMap().put(ks, action);
426     overrideMenuItem(ks, action);
427   }
428
429   /**
430    * Create and link new views (with matching names) in both panes.
431    * <p>
432    * Note this is _not_ multiple tabs, each hosting a split pane view, rather it
433    * is a single split pane with each split holding multiple tabs which are
434    * linked in pairs.
435    * <p>
436    * TODO implement instead with a tabbed holder in the SplitView, each tab
437    * holding a single JSplitPane. Would avoid a duplicated tab, at the cost of
438    * some additional coding.
439    */
440   protected void newView_actionPerformed()
441   {
442     AlignFrame topFrame = (AlignFrame) getTopFrame();
443     AlignFrame bottomFrame = (AlignFrame) getBottomFrame();
444     final boolean scaleProteinAsCdna = topFrame.viewport
445             .isScaleProteinAsCdna();
446
447     AlignmentPanel newTopPanel = topFrame.newView(null, true);
448     AlignmentPanel newBottomPanel = bottomFrame.newView(null, true);
449
450     /*
451      * This currently (for the first new view only) leaves the top pane on tab 0
452      * but the bottom on tab 1. This results from 'setInitialTabVisible' echoing
453      * from the bottom back to the first frame. Next line is a fudge to work
454      * around this. TODO find a better way.
455      */
456     if (topFrame.getTabIndex() != bottomFrame.getTabIndex())
457     {
458       topFrame.setDisplayedView(newTopPanel);
459     }
460
461     newBottomPanel.av.viewName = newTopPanel.av.viewName;
462     newTopPanel.av.setCodingComplement(newBottomPanel.av);
463
464     /*
465      * These lines can be removed once scaleProteinAsCdna is added to element
466      * Viewport in jalview.xsd, as Jalview2XML.copyAlignPanel will then take
467      * care of it
468      */
469     newTopPanel.av.setScaleProteinAsCdna(scaleProteinAsCdna);
470     newBottomPanel.av.setScaleProteinAsCdna(scaleProteinAsCdna);
471
472     /*
473      * Line up id labels etc
474      */
475     adjustLayout();
476
477     final StructureSelectionManager ssm = StructureSelectionManager
478             .getStructureSelectionManager(Desktop.instance);
479     ssm.addCommandListener(newTopPanel.av);
480     ssm.addCommandListener(newBottomPanel.av);
481   }
482
483   /**
484    * Close the currently selected view in both panes. If there is only one view,
485    * close this split frame.
486    */
487   protected void closeView_actionPerformed()
488   {
489     int viewCount = ((AlignFrame) getTopFrame()).getAlignPanels().size();
490     if (viewCount < 2)
491     {
492       close();
493       return;
494     }
495
496     AlignmentPanel topPanel = ((AlignFrame) getTopFrame()).alignPanel;
497     AlignmentPanel bottomPanel = ((AlignFrame) getBottomFrame()).alignPanel;
498
499     ((AlignFrame) getTopFrame()).closeView(topPanel);
500     ((AlignFrame) getBottomFrame()).closeView(bottomPanel);
501
502   }
503
504   /**
505    * Close child frames and this split frame.
506    */
507   public void close()
508   {
509     ((AlignFrame) getTopFrame()).closeMenuItem_actionPerformed(true);
510     ((AlignFrame) getBottomFrame()).closeMenuItem_actionPerformed(true);
511     try
512     {
513       this.setClosed(true);
514     } catch (PropertyVetoException e)
515     {
516       // ignore
517     }
518   }
519
520   /**
521    * Replace AlignFrame 'expand views' action with SplitFrame version.
522    */
523   protected void overrideExpandViews()
524   {
525     KeyStroke key_X = KeyStroke.getKeyStroke(KeyEvent.VK_X, 0, false);
526     AbstractAction action = new AbstractAction()
527     {
528       @Override
529       public void actionPerformed(ActionEvent e)
530       {
531         expandViews_actionPerformed();
532       }
533     };
534     overrideMenuItem(key_X, action);
535   }
536
537   /**
538    * Replace AlignFrame 'gather views' action with SplitFrame version.
539    */
540   protected void overrideGatherViews()
541   {
542     KeyStroke key_G = KeyStroke.getKeyStroke(KeyEvent.VK_G, 0, false);
543     AbstractAction action = new AbstractAction()
544     {
545       @Override
546       public void actionPerformed(ActionEvent e)
547       {
548         gatherViews_actionPerformed();
549       }
550     };
551     overrideMenuItem(key_G, action);
552   }
553
554   /**
555    * Override the menu action associated with the keystroke in the child frames,
556    * replacing it with the given action.
557    * 
558    * @param ks
559    * @param action
560    */
561   private void overrideMenuItem(KeyStroke ks, AbstractAction action)
562   {
563     overrideMenuItem(ks, action, getTopFrame());
564     overrideMenuItem(ks, action, getBottomFrame());
565   }
566
567   /**
568    * Override the menu action associated with the keystroke in one child frame,
569    * replacing it with the given action. Mwahahahaha.
570    * 
571    * @param key
572    * @param action
573    * @param comp
574    */
575   private void overrideMenuItem(KeyStroke key, final AbstractAction action,
576           JComponent comp)
577   {
578     if (comp instanceof AlignFrame)
579     {
580       JMenuItem mi = ((AlignFrame) comp).getAccelerators().get(key);
581       if (mi != null)
582       {
583         for (ActionListener al : mi.getActionListeners())
584         {
585           mi.removeActionListener(al);
586         }
587         mi.addActionListener(new ActionListener()
588         {
589           @Override
590           public void actionPerformed(ActionEvent e)
591           {
592             action.actionPerformed(e);
593           }
594         });
595       }
596     }
597   }
598
599   /**
600    * Expand any multiple views (which are always in pairs) into separate split
601    * frames.
602    */
603   protected void expandViews_actionPerformed()
604   {
605     Desktop.instance.explodeViews(this);
606   }
607
608   /**
609    * Gather any other SplitFrame views of this alignment back in as multiple
610    * (pairs of) views in this SplitFrame.
611    */
612   protected void gatherViews_actionPerformed()
613   {
614     Desktop.instance.gatherViews(this);
615   }
616
617   /**
618    * Returns the alignment in the complementary frame to the one given.
619    */
620   @Override
621   public AlignmentI getComplement(Object alignFrame)
622   {
623     if (alignFrame == this.getTopFrame())
624     {
625       return ((AlignFrame) getBottomFrame()).viewport.getAlignment();
626     }
627     else if (alignFrame == this.getBottomFrame())
628     {
629       return ((AlignFrame) getTopFrame()).viewport.getAlignment();
630     }
631     return null;
632   }
633
634   /**
635    * Returns the title of the complementary frame to the one given.
636    */
637   @Override
638   public String getComplementTitle(Object alignFrame)
639   {
640     if (alignFrame == this.getTopFrame())
641     {
642       return ((AlignFrame) getBottomFrame()).getTitle();
643     }
644     else if (alignFrame == this.getBottomFrame())
645     {
646       return ((AlignFrame) getTopFrame()).getTitle();
647     }
648     return null;
649   }
650
651   /**
652    * Set the 'other half' to hidden / revealed.
653    */
654   @Override
655   public void setComplementVisible(Object alignFrame, boolean show)
656   {
657     /*
658      * Hiding the AlignPanel suppresses unnecessary repaints
659      */
660     if (alignFrame == getTopFrame())
661     {
662       ((AlignFrame) getBottomFrame()).alignPanel.setVisible(show);
663     }
664     else if (alignFrame == getBottomFrame())
665     {
666       ((AlignFrame) getTopFrame()).alignPanel.setVisible(show);
667     }
668     super.setComplementVisible(alignFrame, show);
669   }
670
671   /**
672    * Replace Cmd-F Find action with our version. This is necessary because the
673    * 'default' Finder searches in the first AlignFrame it finds. We need it to
674    * search in the half of the SplitFrame that has the mouse.
675    */
676   protected void overrideFind()
677   {
678     /*
679      * Ctrl-F / Cmd-F open Finder dialog, 'focused' on the right alignment
680      */
681     KeyStroke key_cmdF = KeyStroke.getKeyStroke(KeyEvent.VK_F, Toolkit
682             .getDefaultToolkit().getMenuShortcutKeyMask(), false);
683     AbstractAction action = new AbstractAction()
684     {
685       @Override
686       public void actionPerformed(ActionEvent e)
687       {
688         Component c = getFrameAtMouse();
689         if (c != null && c instanceof AlignFrame)
690         {
691           AlignFrame af = (AlignFrame) c;
692           new Finder(af.viewport, af.alignPanel);
693         }
694       }
695     };
696     overrideKeyBinding(key_cmdF, action);
697   }
698 }