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