JAL-1705 refactor show products, set initial split frame 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     int topCount = topAlignment.getHeight();
210     int bottomCount = bottomAlignment.getHeight();
211     int topCharHeight = topViewport.getViewStyle().getCharHeight();
212     int bottomCharHeight = bottomViewport.getViewStyle().getCharHeight();
213
214     /*
215      * estimate ratio of (topFrameContent / bottomFrameContent)
216      */
217     int insets = Platform.isAMac() ? MAC_INSETS_HEIGHT
218             : WINDOWS_INSETS_HEIGHT;
219     // allow 3 'rows' for scale, scrollbar, status bar
220     int topHeight = insets + (3 + topCount) * topCharHeight
221             + (topAnnotations ? topViewport.calcPanelHeight() : 0);
222     int bottomHeight = insets + (3 + bottomCount) * bottomCharHeight
223             + (bottomAnnotations ? bottomViewport.calcPanelHeight() : 0);
224     double ratio = ((double) topHeight) / (topHeight + bottomHeight);
225
226     setRelativeDividerLocation(ratio);
227   }
228
229   /**
230    * Add a listener to tidy up when the frame is closed.
231    */
232   protected void addCloseFrameListener()
233   {
234     addInternalFrameListener(new InternalFrameAdapter()
235     {
236       @Override
237       public void internalFrameClosed(InternalFrameEvent evt)
238       {
239         close();
240       };
241     });
242   }
243
244   /**
245    * Add a key listener that delegates to whichever split component the mouse is
246    * in (or does nothing if neither).
247    */
248   protected void addKeyListener()
249   {
250     addKeyListener(new KeyAdapter()
251     {
252
253       @Override
254       public void keyPressed(KeyEvent e)
255       {
256         AlignFrame af = (AlignFrame) getFrameAtMouse();
257
258         /*
259          * Intercept and override any keys here if wanted.
260          */
261         if (!overrideKey(e, af))
262         {
263           if (af != null)
264           {
265             for (KeyListener kl : af.getKeyListeners())
266             {
267               kl.keyPressed(e);
268             }
269           }
270         }
271       }
272
273       @Override
274       public void keyReleased(KeyEvent e)
275       {
276         Component c = getFrameAtMouse();
277         if (c != null)
278         {
279           for (KeyListener kl : c.getKeyListeners())
280           {
281             kl.keyReleased(e);
282           }
283         }
284       }
285
286     });
287   }
288
289   /**
290    * Returns true if the key event is overriden and actioned (or ignored) here,
291    * else returns false, indicating it should be delegated to the AlignFrame's
292    * usual handler.
293    * <p>
294    * We can't handle Cmd-Key combinations here, instead this is done by
295    * overriding key bindings.
296    * 
297    * @see addKeyOverrides
298    * @param e
299    * @param af
300    * @return
301    */
302   protected boolean overrideKey(KeyEvent e, AlignFrame af)
303   {
304     boolean actioned = false;
305     int keyCode = e.getKeyCode();
306     switch (keyCode)
307     {
308     case KeyEvent.VK_DOWN:
309       if (e.isAltDown() || !af.viewport.cursorMode)
310       {
311         /*
312          * Key down (or Alt-key-down in cursor mode) - move selected sequences
313          */
314         ((AlignFrame) getTopFrame()).moveSelectedSequences(false);
315         ((AlignFrame) getBottomFrame()).moveSelectedSequences(false);
316         actioned = true;
317         e.consume();
318       }
319       break;
320     case KeyEvent.VK_UP:
321       if (e.isAltDown() || !af.viewport.cursorMode)
322       {
323         /*
324          * Key up (or Alt-key-up in cursor mode) - move selected sequences
325          */
326         ((AlignFrame) getTopFrame()).moveSelectedSequences(true);
327         ((AlignFrame) getBottomFrame()).moveSelectedSequences(true);
328         actioned = true;
329         e.consume();
330       }
331     default:
332     }
333     return actioned;
334   }
335
336   /**
337    * Set key bindings (recommended for Swing over key accelerators).
338    */
339   private void addKeyBindings()
340   {
341     overrideDelegatedKeyBindings();
342
343     overrideImplementedKeyBindings();
344   }
345
346   /**
347    * Override key bindings with alternative action methods implemented in this
348    * class.
349    */
350   protected void overrideImplementedKeyBindings()
351   {
352     overrideFind();
353     overrideNewView();
354     overrideCloseView();
355     overrideExpandViews();
356     overrideGatherViews();
357   }
358
359   /**
360    * Replace Cmd-W close view action with our version.
361    */
362   protected void overrideCloseView()
363   {
364     AbstractAction action;
365     /*
366      * Ctrl-W / Cmd-W - close view or window
367      */
368     KeyStroke key_cmdW = KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit
369             .getDefaultToolkit().getMenuShortcutKeyMask(), false);
370     action = new AbstractAction()
371     {
372       @Override
373       public void actionPerformed(ActionEvent e)
374       {
375         closeView_actionPerformed();
376       }
377     };
378     overrideKeyBinding(key_cmdW, action);
379   }
380
381   /**
382    * Replace Cmd-T new view action with our version.
383    */
384   protected void overrideNewView()
385   {
386     /*
387      * Ctrl-T / Cmd-T open new view
388      */
389     KeyStroke key_cmdT = KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit
390             .getDefaultToolkit().getMenuShortcutKeyMask(), false);
391     AbstractAction action = new AbstractAction()
392     {
393       @Override
394       public void actionPerformed(ActionEvent e)
395       {
396         newView_actionPerformed();
397       }
398     };
399     overrideKeyBinding(key_cmdT, action);
400   }
401
402   /**
403    * For now, delegates key events to the corresponding key accelerator for the
404    * AlignFrame that the mouse is in. Hopefully can be simplified in future if
405    * AlignFrame is changed to use key bindings rather than accelerators.
406    */
407   protected void overrideDelegatedKeyBindings()
408   {
409     if (getTopFrame() instanceof AlignFrame)
410     {
411       /*
412        * Get all accelerator keys in the top frame (the bottom should be
413        * identical) and override each one.
414        */
415       for (Entry<KeyStroke, JMenuItem> acc : ((AlignFrame) getTopFrame())
416               .getAccelerators().entrySet())
417       {
418         overrideKeyBinding(acc);
419       }
420     }
421   }
422
423   /**
424    * Overrides an AlignFrame key accelerator with our version which delegates to
425    * the action listener in whichever frame has the mouse (and does nothing if
426    * neither has).
427    * 
428    * @param acc
429    */
430   private void overrideKeyBinding(Entry<KeyStroke, JMenuItem> acc)
431   {
432     final KeyStroke ks = acc.getKey();
433     InputMap inputMap = this.getInputMap(JComponent.WHEN_FOCUSED);
434     inputMap.put(ks, ks);
435     this.getActionMap().put(ks, new AbstractAction()
436     {
437       @Override
438       public void actionPerformed(ActionEvent e)
439       {
440         Component c = getFrameAtMouse();
441         if (c != null && c instanceof AlignFrame)
442         {
443           for (ActionListener a : ((AlignFrame) c).getAccelerators()
444                   .get(ks).getActionListeners())
445           {
446             a.actionPerformed(null);
447           }
448         }
449       }
450     });
451   }
452
453   /**
454    * Replace an accelerator key's action with the specified action.
455    * 
456    * @param ks
457    */
458   protected void overrideKeyBinding(KeyStroke ks, AbstractAction action)
459   {
460     this.getActionMap().put(ks, action);
461     overrideMenuItem(ks, action);
462   }
463
464   /**
465    * Create and link new views (with matching names) in both panes.
466    * <p>
467    * Note this is _not_ multiple tabs, each hosting a split pane view, rather it
468    * is a single split pane with each split holding multiple tabs which are
469    * linked in pairs.
470    * <p>
471    * TODO implement instead with a tabbed holder in the SplitView, each tab
472    * holding a single JSplitPane. Would avoid a duplicated tab, at the cost of
473    * some additional coding.
474    */
475   protected void newView_actionPerformed()
476   {
477     AlignFrame topFrame = (AlignFrame) getTopFrame();
478     AlignFrame bottomFrame = (AlignFrame) getBottomFrame();
479     final boolean scaleProteinAsCdna = topFrame.viewport
480             .isScaleProteinAsCdna();
481
482     AlignmentPanel newTopPanel = topFrame.newView(null, true);
483     AlignmentPanel newBottomPanel = bottomFrame.newView(null, true);
484
485     /*
486      * This currently (for the first new view only) leaves the top pane on tab 0
487      * but the bottom on tab 1. This results from 'setInitialTabVisible' echoing
488      * from the bottom back to the first frame. Next line is a fudge to work
489      * around this. TODO find a better way.
490      */
491     if (topFrame.getTabIndex() != bottomFrame.getTabIndex())
492     {
493       topFrame.setDisplayedView(newTopPanel);
494     }
495
496     newBottomPanel.av.viewName = newTopPanel.av.viewName;
497     newTopPanel.av.setCodingComplement(newBottomPanel.av);
498
499     /*
500      * These lines can be removed once scaleProteinAsCdna is added to element
501      * Viewport in jalview.xsd, as Jalview2XML.copyAlignPanel will then take
502      * care of it
503      */
504     newTopPanel.av.setScaleProteinAsCdna(scaleProteinAsCdna);
505     newBottomPanel.av.setScaleProteinAsCdna(scaleProteinAsCdna);
506
507     /*
508      * Line up id labels etc
509      */
510     adjustLayout();
511
512     final StructureSelectionManager ssm = StructureSelectionManager
513             .getStructureSelectionManager(Desktop.instance);
514     ssm.addCommandListener(newTopPanel.av);
515     ssm.addCommandListener(newBottomPanel.av);
516   }
517
518   /**
519    * Close the currently selected view in both panes. If there is only one view,
520    * close this split frame.
521    */
522   protected void closeView_actionPerformed()
523   {
524     int viewCount = ((AlignFrame) getTopFrame()).getAlignPanels().size();
525     if (viewCount < 2)
526     {
527       close();
528       return;
529     }
530
531     AlignmentPanel topPanel = ((AlignFrame) getTopFrame()).alignPanel;
532     AlignmentPanel bottomPanel = ((AlignFrame) getBottomFrame()).alignPanel;
533
534     ((AlignFrame) getTopFrame()).closeView(topPanel);
535     ((AlignFrame) getBottomFrame()).closeView(bottomPanel);
536
537   }
538
539   /**
540    * Close child frames and this split frame.
541    */
542   public void close()
543   {
544     ((AlignFrame) getTopFrame()).closeMenuItem_actionPerformed(true);
545     ((AlignFrame) getBottomFrame()).closeMenuItem_actionPerformed(true);
546     try
547     {
548       this.setClosed(true);
549     } catch (PropertyVetoException e)
550     {
551       // ignore
552     }
553   }
554
555   /**
556    * Replace AlignFrame 'expand views' action with SplitFrame version.
557    */
558   protected void overrideExpandViews()
559   {
560     KeyStroke key_X = KeyStroke.getKeyStroke(KeyEvent.VK_X, 0, false);
561     AbstractAction action = new AbstractAction()
562     {
563       @Override
564       public void actionPerformed(ActionEvent e)
565       {
566         expandViews_actionPerformed();
567       }
568     };
569     overrideMenuItem(key_X, action);
570   }
571
572   /**
573    * Replace AlignFrame 'gather views' action with SplitFrame version.
574    */
575   protected void overrideGatherViews()
576   {
577     KeyStroke key_G = KeyStroke.getKeyStroke(KeyEvent.VK_G, 0, false);
578     AbstractAction action = new AbstractAction()
579     {
580       @Override
581       public void actionPerformed(ActionEvent e)
582       {
583         gatherViews_actionPerformed();
584       }
585     };
586     overrideMenuItem(key_G, action);
587   }
588
589   /**
590    * Override the menu action associated with the keystroke in the child frames,
591    * replacing it with the given action.
592    * 
593    * @param ks
594    * @param action
595    */
596   private void overrideMenuItem(KeyStroke ks, AbstractAction action)
597   {
598     overrideMenuItem(ks, action, getTopFrame());
599     overrideMenuItem(ks, action, getBottomFrame());
600   }
601
602   /**
603    * Override the menu action associated with the keystroke in one child frame,
604    * replacing it with the given action. Mwahahahaha.
605    * 
606    * @param key
607    * @param action
608    * @param comp
609    */
610   private void overrideMenuItem(KeyStroke key, final AbstractAction action,
611           JComponent comp)
612   {
613     if (comp instanceof AlignFrame)
614     {
615       JMenuItem mi = ((AlignFrame) comp).getAccelerators().get(key);
616       if (mi != null)
617       {
618         for (ActionListener al : mi.getActionListeners())
619         {
620           mi.removeActionListener(al);
621         }
622         mi.addActionListener(new ActionListener()
623         {
624           @Override
625           public void actionPerformed(ActionEvent e)
626           {
627             action.actionPerformed(e);
628           }
629         });
630       }
631     }
632   }
633
634   /**
635    * Expand any multiple views (which are always in pairs) into separate split
636    * frames.
637    */
638   protected void expandViews_actionPerformed()
639   {
640     Desktop.instance.explodeViews(this);
641   }
642
643   /**
644    * Gather any other SplitFrame views of this alignment back in as multiple
645    * (pairs of) views in this SplitFrame.
646    */
647   protected void gatherViews_actionPerformed()
648   {
649     Desktop.instance.gatherViews(this);
650   }
651
652   /**
653    * Returns the alignment in the complementary frame to the one given.
654    */
655   @Override
656   public AlignmentI getComplement(Object alignFrame)
657   {
658     if (alignFrame == this.getTopFrame())
659     {
660       return ((AlignFrame) getBottomFrame()).viewport.getAlignment();
661     }
662     else if (alignFrame == this.getBottomFrame())
663     {
664       return ((AlignFrame) getTopFrame()).viewport.getAlignment();
665     }
666     return null;
667   }
668
669   /**
670    * Returns the title of the complementary frame to the one given.
671    */
672   @Override
673   public String getComplementTitle(Object alignFrame)
674   {
675     if (alignFrame == this.getTopFrame())
676     {
677       return ((AlignFrame) getBottomFrame()).getTitle();
678     }
679     else if (alignFrame == this.getBottomFrame())
680     {
681       return ((AlignFrame) getTopFrame()).getTitle();
682     }
683     return null;
684   }
685
686   /**
687    * Set the 'other half' to hidden / revealed.
688    */
689   @Override
690   public void setComplementVisible(Object alignFrame, boolean show)
691   {
692     /*
693      * Hiding the AlignPanel suppresses unnecessary repaints
694      */
695     if (alignFrame == getTopFrame())
696     {
697       ((AlignFrame) getBottomFrame()).alignPanel.setVisible(show);
698     }
699     else if (alignFrame == getBottomFrame())
700     {
701       ((AlignFrame) getTopFrame()).alignPanel.setVisible(show);
702     }
703     super.setComplementVisible(alignFrame, show);
704   }
705
706   /**
707    * Replace Cmd-F Find action with our version. This is necessary because the
708    * 'default' Finder searches in the first AlignFrame it finds. We need it to
709    * search in the half of the SplitFrame that has the mouse.
710    */
711   protected void overrideFind()
712   {
713     /*
714      * Ctrl-F / Cmd-F open Finder dialog, 'focused' on the right alignment
715      */
716     KeyStroke key_cmdF = KeyStroke.getKeyStroke(KeyEvent.VK_F, Toolkit
717             .getDefaultToolkit().getMenuShortcutKeyMask(), false);
718     AbstractAction action = new AbstractAction()
719     {
720       @Override
721       public void actionPerformed(ActionEvent e)
722       {
723         Component c = getFrameAtMouse();
724         if (c != null && c instanceof AlignFrame)
725         {
726           AlignFrame af = (AlignFrame) c;
727           new Finder(af.viewport, af.alignPanel);
728         }
729       }
730     };
731     overrideKeyBinding(key_cmdF, action);
732   }
733 }