JAL-3438 spotless for 2.11.2.0
[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 java.awt.BorderLayout;
24 import java.awt.Component;
25 import java.awt.Dimension;
26 import java.awt.event.ActionEvent;
27 import java.awt.event.ActionListener;
28 import java.awt.event.KeyAdapter;
29 import java.awt.event.KeyEvent;
30 import java.awt.event.KeyListener;
31 import java.beans.PropertyVetoException;
32 import java.util.Arrays;
33 import java.util.List;
34 import java.util.Map.Entry;
35
36 import javax.swing.AbstractAction;
37 import javax.swing.InputMap;
38 import javax.swing.JButton;
39 import javax.swing.JComponent;
40 import javax.swing.JDesktopPane;
41 import javax.swing.JInternalFrame;
42 import javax.swing.JLayeredPane;
43 import javax.swing.JMenuItem;
44 import javax.swing.JPanel;
45 import javax.swing.JTabbedPane;
46 import javax.swing.KeyStroke;
47 import javax.swing.event.ChangeEvent;
48 import javax.swing.event.ChangeListener;
49 import javax.swing.event.InternalFrameAdapter;
50 import javax.swing.event.InternalFrameEvent;
51
52 import jalview.api.AlignViewControllerGuiI;
53 import jalview.api.FeatureSettingsControllerI;
54 import jalview.api.SplitContainerI;
55 import jalview.controller.FeatureSettingsControllerGuiI;
56 import jalview.datamodel.AlignmentI;
57 import jalview.jbgui.GAlignFrame;
58 import jalview.jbgui.GSplitFrame;
59 import jalview.structure.StructureSelectionManager;
60 import jalview.util.MessageManager;
61 import jalview.util.Platform;
62 import jalview.viewmodel.AlignmentViewport;
63
64 /**
65  * An internal frame on the desktop that hosts a horizontally split view of
66  * linked DNA and Protein alignments. Additional views can be created in linked
67  * pairs, expanded to separate split frames, or regathered into a single frame.
68  * <p>
69  * (Some) operations on each alignment are automatically mirrored on the other.
70  * These include mouseover (highlighting), sequence and column selection,
71  * sequence ordering and sorting, and grouping, colouring and sorting by tree.
72  * 
73  * @author gmcarstairs
74  *
75  */
76 public class SplitFrame extends GSplitFrame implements SplitContainerI
77 {
78   private static final int WINDOWS_INSETS_WIDTH = 28; // tbc
79
80   private static final int MAC_INSETS_WIDTH = 28;
81
82   private static final int WINDOWS_INSETS_HEIGHT = 50; // tbc
83
84   private static final int MAC_INSETS_HEIGHT = 50;
85
86   private static final int DESKTOP_DECORATORS_HEIGHT = 65;
87
88   private static final long serialVersionUID = 1L;
89
90   /**
91    * geometry for Feature Settings Holder
92    */
93   private static final int FS_MIN_WIDTH = 400;
94
95   private static final int FS_MIN_HEIGHT = 400;
96
97   public SplitFrame(GAlignFrame top, GAlignFrame bottom)
98   {
99     super(top, bottom);
100     init();
101   }
102
103   /**
104    * Initialise this frame.
105    */
106   protected void init()
107   {
108     getTopFrame().setSplitFrame(this);
109     getBottomFrame().setSplitFrame(this);
110     getTopFrame().setVisible(true);
111     getBottomFrame().setVisible(true);
112
113     ((AlignFrame) getTopFrame()).getViewport().setCodingComplement(
114             ((AlignFrame) getBottomFrame()).getViewport());
115
116     /*
117      * estimate width and height of SplitFrame; this.getInsets() doesn't seem to
118      * give the full additional size (a few pixels short)
119      */
120     int widthFudge = Platform.isAMacAndNotJS() ? MAC_INSETS_WIDTH
121             : WINDOWS_INSETS_WIDTH;
122     int heightFudge = Platform.isAMacAndNotJS() ? MAC_INSETS_HEIGHT
123             : WINDOWS_INSETS_HEIGHT;
124     int width = ((AlignFrame) getTopFrame()).getWidth() + widthFudge;
125     int height = ((AlignFrame) getTopFrame()).getHeight()
126             + ((AlignFrame) getBottomFrame()).getHeight() + DIVIDER_SIZE
127             + heightFudge;
128     height = fitHeightToDesktop(height);
129     setSize(width, height);
130
131     adjustLayout();
132
133     addCloseFrameListener();
134
135     addKeyListener();
136
137     addKeyBindings();
138
139     addCommandListeners();
140   }
141
142   /**
143    * Reduce the height if too large to fit in the Desktop. Also adjust the
144    * divider location in proportion.
145    * 
146    * @param height
147    *          in pixels
148    * @return original or reduced height
149    */
150   public int fitHeightToDesktop(int height)
151   {
152     // allow about 65 pixels for Desktop decorators on Windows
153
154     int newHeight = Math.min(height,
155             Desktop.instance.getHeight() - DESKTOP_DECORATORS_HEIGHT);
156     if (newHeight != height)
157     {
158       int oldDividerLocation = getDividerLocation();
159       setDividerLocation(oldDividerLocation * newHeight / height);
160     }
161     return newHeight;
162   }
163
164   /**
165    * Set the top and bottom frames to listen to each others Commands (e.g. Edit,
166    * Order).
167    */
168   protected void addCommandListeners()
169   {
170     // TODO if CommandListener is only ever 1:1 for complementary views,
171     // may change broadcast pattern to direct messaging (more efficient)
172     final StructureSelectionManager ssm = StructureSelectionManager
173             .getStructureSelectionManager(Desktop.instance);
174     ssm.addCommandListener(((AlignFrame) getTopFrame()).getViewport());
175     ssm.addCommandListener(((AlignFrame) getBottomFrame()).getViewport());
176   }
177
178   /**
179    * Do any tweaking and twerking of the layout wanted.
180    */
181   public void adjustLayout()
182   {
183     final AlignViewport topViewport = ((AlignFrame) getTopFrame()).viewport;
184     final AlignViewport bottomViewport = ((AlignFrame) getBottomFrame()).viewport;
185
186     /*
187      * Ensure sequence ids are the same width so sequences line up
188      */
189     int w1 = topViewport.getIdWidth();
190     int w2 = bottomViewport.getIdWidth();
191     int w3 = Math.max(w1, w2);
192     topViewport.setIdWidth(w3);
193     bottomViewport.setIdWidth(w3);
194
195     /*
196      * Scale protein to either 1 or 3 times character width of dna
197      */
198     final AlignmentI topAlignment = topViewport.getAlignment();
199     final AlignmentI bottomAlignment = bottomViewport.getAlignment();
200     AlignmentViewport cdna = topAlignment.isNucleotide() ? topViewport
201             : (bottomAlignment.isNucleotide() ? bottomViewport : null);
202     AlignmentViewport protein = !topAlignment.isNucleotide() ? topViewport
203             : (!bottomAlignment.isNucleotide() ? bottomViewport : null);
204     if (protein != null && cdna != null)
205     {
206       int scale = protein.isScaleProteinAsCdna() ? 3 : 1;
207       protein.setCharWidth(scale * cdna.getViewStyle().getCharWidth());
208     }
209   }
210
211   /**
212    * Adjusts the divider for a sensible split of the real estate (for example,
213    * when many transcripts are shown with a single protein). This should only be
214    * called after the split pane has been laid out (made visible) so it has a
215    * height. The aim is to avoid unnecessary vertical scroll bars, while
216    * ensuring that at least 2 sequences are visible in each panel.
217    * <p>
218    * Once laid out, the user may choose to customise as they wish, so this
219    * method is not called again after the initial layout.
220    */
221   protected void adjustInitialLayout()
222   {
223     AlignFrame topFrame = (AlignFrame) getTopFrame();
224     AlignFrame bottomFrame = (AlignFrame) getBottomFrame();
225
226     /*
227      * recompute layout of top and bottom panels to reflect their
228      * actual (rather than requested) height
229      */
230     topFrame.alignPanel.adjustAnnotationHeight();
231     bottomFrame.alignPanel.adjustAnnotationHeight();
232
233     final AlignViewport topViewport = topFrame.viewport;
234     final AlignViewport bottomViewport = bottomFrame.viewport;
235     final AlignmentI topAlignment = topViewport.getAlignment();
236     final AlignmentI bottomAlignment = bottomViewport.getAlignment();
237     boolean topAnnotations = topViewport.isShowAnnotation();
238     boolean bottomAnnotations = bottomViewport.isShowAnnotation();
239     // TODO need number of visible sequences here, not #sequences - how?
240     int topCount = topAlignment.getHeight();
241     int bottomCount = bottomAlignment.getHeight();
242     int topCharHeight = topViewport.getViewStyle().getCharHeight();
243     int bottomCharHeight = bottomViewport.getViewStyle().getCharHeight();
244
245     /*
246      * calculate the minimum ratio that leaves at least the height 
247      * of two sequences (after rounding) visible in the top panel
248      */
249     int topPanelHeight = topFrame.getHeight();
250     int bottomPanelHeight = bottomFrame.getHeight();
251     int topSequencesHeight = topFrame.alignPanel.getSeqPanel().seqCanvas
252             .getHeight();
253     int topPanelMinHeight = topPanelHeight
254             - Math.max(0, topSequencesHeight - 3 * topCharHeight);
255     double totalHeight = (double) topPanelHeight + bottomPanelHeight;
256     double minRatio = topPanelMinHeight / totalHeight;
257
258     /*
259      * calculate the maximum ratio that leaves at least the height 
260      * of two sequences (after rounding) visible in the bottom panel
261      */
262     int bottomSequencesHeight = bottomFrame.alignPanel
263             .getSeqPanel().seqCanvas.getHeight();
264     int bottomPanelMinHeight = bottomPanelHeight
265             - Math.max(0, bottomSequencesHeight - 3 * bottomCharHeight);
266     double maxRatio = (totalHeight - bottomPanelMinHeight) / totalHeight;
267
268     /*
269      * estimate ratio of (topFrameContent / bottomFrameContent)
270      */
271     int insets = Platform.isAMacAndNotJS() ? MAC_INSETS_HEIGHT
272             : WINDOWS_INSETS_HEIGHT;
273     // allow 3 'rows' for scale, scrollbar, status bar
274     int topHeight = insets + (3 + topCount) * topCharHeight
275             + (topAnnotations ? topViewport.calcPanelHeight() : 0);
276     int bottomHeight = insets + (3 + bottomCount) * bottomCharHeight
277             + (bottomAnnotations ? bottomViewport.calcPanelHeight() : 0);
278     double ratio = ((double) topHeight)
279             / (double) (topHeight + bottomHeight);
280
281     /*
282      * limit ratio to avoid concealing all sequences
283      */
284     ratio = Math.min(ratio, maxRatio);
285     ratio = Math.max(ratio, minRatio);
286     setRelativeDividerLocation(ratio);
287   }
288
289   /**
290    * Add a listener to tidy up when the frame is closed.
291    */
292   protected void addCloseFrameListener()
293   {
294     addInternalFrameListener(new InternalFrameAdapter()
295     {
296       @Override
297       public void internalFrameClosed(InternalFrameEvent evt)
298       {
299         close();
300       };
301     });
302   }
303
304   /**
305    * Add a key listener that delegates to whichever split component the mouse is
306    * in (or does nothing if neither).
307    */
308   protected void addKeyListener()
309   {
310     addKeyListener(new KeyAdapter()
311     {
312
313       @Override
314       public void keyPressed(KeyEvent e)
315       {
316         AlignFrame af = (AlignFrame) getFrameAtMouse();
317
318         /*
319          * Intercept and override any keys here if wanted.
320          */
321         if (!overrideKey(e, af))
322         {
323           if (af != null)
324           {
325             for (KeyListener kl : af.getKeyListeners())
326             {
327               kl.keyPressed(e);
328             }
329           }
330         }
331       }
332
333       @Override
334       public void keyReleased(KeyEvent e)
335       {
336         Component c = getFrameAtMouse();
337         if (c != null)
338         {
339           for (KeyListener kl : c.getKeyListeners())
340           {
341             kl.keyReleased(e);
342           }
343         }
344       }
345
346     });
347   }
348
349   /**
350    * Returns true if the key event is overriden and actioned (or ignored) here,
351    * else returns false, indicating it should be delegated to the AlignFrame's
352    * usual handler.
353    * <p>
354    * We can't handle Cmd-Key combinations here, instead this is done by
355    * overriding key bindings.
356    * 
357    * @see addKeyOverrides
358    * @param e
359    * @param af
360    * @return
361    */
362   protected boolean overrideKey(KeyEvent e, AlignFrame af)
363   {
364     boolean actioned = false;
365     int keyCode = e.getKeyCode();
366     switch (keyCode)
367     {
368     case KeyEvent.VK_DOWN:
369       if (e.isAltDown() || !af.viewport.cursorMode)
370       {
371         /*
372          * Key down (or Alt-key-down in cursor mode) - move selected sequences
373          */
374         ((AlignFrame) getTopFrame()).moveSelectedSequences(false);
375         ((AlignFrame) getBottomFrame()).moveSelectedSequences(false);
376         actioned = true;
377         e.consume();
378       }
379       break;
380     case KeyEvent.VK_UP:
381       if (e.isAltDown() || !af.viewport.cursorMode)
382       {
383         /*
384          * Key up (or Alt-key-up in cursor mode) - move selected sequences
385          */
386         ((AlignFrame) getTopFrame()).moveSelectedSequences(true);
387         ((AlignFrame) getBottomFrame()).moveSelectedSequences(true);
388         actioned = true;
389         e.consume();
390       }
391       break;
392     default:
393     }
394     return actioned;
395   }
396
397   /**
398    * Set key bindings (recommended for Swing over key accelerators).
399    */
400   private void addKeyBindings()
401   {
402     overrideDelegatedKeyBindings();
403
404     overrideImplementedKeyBindings();
405   }
406
407   /**
408    * Override key bindings with alternative action methods implemented in this
409    * class.
410    */
411   protected void overrideImplementedKeyBindings()
412   {
413     overrideFind();
414     overrideNewView();
415     overrideCloseView();
416     overrideExpandViews();
417     overrideGatherViews();
418   }
419
420   /**
421    * Replace Cmd-W close view action with our version.
422    */
423   protected void overrideCloseView()
424   {
425     AbstractAction action;
426     /*
427      * Ctrl-W / Cmd-W - close view or window
428      */
429     KeyStroke key_cmdW = KeyStroke.getKeyStroke(KeyEvent.VK_W,
430             jalview.util.ShortcutKeyMaskExWrapper
431                     .getMenuShortcutKeyMaskEx(),
432             false);
433     action = new AbstractAction()
434     {
435       @Override
436       public void actionPerformed(ActionEvent e)
437       {
438         closeView_actionPerformed();
439       }
440     };
441     overrideKeyBinding(key_cmdW, action);
442   }
443
444   /**
445    * Replace Cmd-T new view action with our version.
446    */
447   protected void overrideNewView()
448   {
449     /*
450      * Ctrl-T / Cmd-T open new view
451      */
452     KeyStroke key_cmdT = KeyStroke.getKeyStroke(KeyEvent.VK_T,
453             jalview.util.ShortcutKeyMaskExWrapper
454                     .getMenuShortcutKeyMaskEx(),
455             false);
456     AbstractAction action = new AbstractAction()
457     {
458       @Override
459       public void actionPerformed(ActionEvent e)
460       {
461         newView_actionPerformed();
462       }
463     };
464     overrideKeyBinding(key_cmdT, action);
465   }
466
467   /**
468    * For now, delegates key events to the corresponding key accelerator for the
469    * AlignFrame that the mouse is in. Hopefully can be simplified in future if
470    * AlignFrame is changed to use key bindings rather than accelerators.
471    */
472   protected void overrideDelegatedKeyBindings()
473   {
474     if (getTopFrame() instanceof AlignFrame)
475     {
476       /*
477        * Get all accelerator keys in the top frame (the bottom should be
478        * identical) and override each one.
479        */
480       for (Entry<KeyStroke, JMenuItem> acc : ((AlignFrame) getTopFrame())
481               .getAccelerators().entrySet())
482       {
483         overrideKeyBinding(acc);
484       }
485     }
486   }
487
488   /**
489    * Overrides an AlignFrame key accelerator with our version which delegates to
490    * the action listener in whichever frame has the mouse (and does nothing if
491    * neither has).
492    * 
493    * @param acc
494    */
495   private void overrideKeyBinding(Entry<KeyStroke, JMenuItem> acc)
496   {
497     final KeyStroke ks = acc.getKey();
498     InputMap inputMap = this.getInputMap(JComponent.WHEN_FOCUSED);
499     inputMap.put(ks, ks);
500     this.getActionMap().put(ks, new AbstractAction()
501     {
502       @Override
503       public void actionPerformed(ActionEvent e)
504       {
505         Component c = getFrameAtMouse();
506         if (c != null && c instanceof AlignFrame)
507         {
508           for (ActionListener a : ((AlignFrame) c).getAccelerators().get(ks)
509                   .getActionListeners())
510           {
511             a.actionPerformed(null);
512           }
513         }
514       }
515     });
516   }
517
518   /**
519    * Replace an accelerator key's action with the specified action.
520    * 
521    * @param ks
522    */
523   protected void overrideKeyBinding(KeyStroke ks, AbstractAction action)
524   {
525     this.getActionMap().put(ks, action);
526     overrideMenuItem(ks, action);
527   }
528
529   /**
530    * Create and link new views (with matching names) in both panes.
531    * <p>
532    * Note this is _not_ multiple tabs, each hosting a split pane view, rather it
533    * is a single split pane with each split holding multiple tabs which are
534    * linked in pairs.
535    * <p>
536    * TODO implement instead with a tabbed holder in the SplitView, each tab
537    * holding a single JSplitPane. Would avoid a duplicated tab, at the cost of
538    * some additional coding.
539    */
540   protected void newView_actionPerformed()
541   {
542     AlignFrame topFrame = (AlignFrame) getTopFrame();
543     AlignFrame bottomFrame = (AlignFrame) getBottomFrame();
544     final boolean scaleProteinAsCdna = topFrame.viewport
545             .isScaleProteinAsCdna();
546
547     AlignmentPanel newTopPanel = topFrame.newView(null, true);
548     AlignmentPanel newBottomPanel = bottomFrame.newView(null, true);
549
550     /*
551      * This currently (for the first new view only) leaves the top pane on tab 0
552      * but the bottom on tab 1. This results from 'setInitialTabVisible' echoing
553      * from the bottom back to the first frame. Next line is a fudge to work
554      * around this. TODO find a better way.
555      */
556     if (topFrame.getTabIndex() != bottomFrame.getTabIndex())
557     {
558       topFrame.setDisplayedView(newTopPanel);
559     }
560
561     newBottomPanel.av.setViewName(newTopPanel.av.getViewName());
562     newTopPanel.av.setCodingComplement(newBottomPanel.av);
563
564     /*
565      * These lines can be removed once scaleProteinAsCdna is added to element
566      * Viewport in jalview.xsd, as Jalview2XML.copyAlignPanel will then take
567      * care of it
568      */
569     newTopPanel.av.setScaleProteinAsCdna(scaleProteinAsCdna);
570     newBottomPanel.av.setScaleProteinAsCdna(scaleProteinAsCdna);
571
572     /*
573      * Line up id labels etc
574      */
575     adjustLayout();
576
577     final StructureSelectionManager ssm = StructureSelectionManager
578             .getStructureSelectionManager(Desktop.instance);
579     ssm.addCommandListener(newTopPanel.av);
580     ssm.addCommandListener(newBottomPanel.av);
581   }
582
583   /**
584    * Close the currently selected view in both panes. If there is only one view,
585    * close this split frame.
586    */
587   protected void closeView_actionPerformed()
588   {
589     int viewCount = ((AlignFrame) getTopFrame()).getAlignPanels().size();
590     if (viewCount < 2)
591     {
592       close();
593       return;
594     }
595
596     AlignmentPanel topPanel = ((AlignFrame) getTopFrame()).alignPanel;
597     AlignmentPanel bottomPanel = ((AlignFrame) getBottomFrame()).alignPanel;
598
599     ((AlignFrame) getTopFrame()).closeView(topPanel);
600     ((AlignFrame) getBottomFrame()).closeView(bottomPanel);
601
602   }
603
604   /**
605    * Close child frames and this split frame.
606    */
607   public void close()
608   {
609     ((AlignFrame) getTopFrame()).closeMenuItem_actionPerformed(true);
610     ((AlignFrame) getBottomFrame()).closeMenuItem_actionPerformed(true);
611     try
612     {
613       this.setClosed(true);
614     } catch (PropertyVetoException e)
615     {
616       // ignore
617     }
618   }
619
620   /**
621    * Replace AlignFrame 'expand views' action with SplitFrame version.
622    */
623   protected void overrideExpandViews()
624   {
625     KeyStroke key_X = KeyStroke.getKeyStroke(KeyEvent.VK_X, 0, false);
626     AbstractAction action = new AbstractAction()
627     {
628       @Override
629       public void actionPerformed(ActionEvent e)
630       {
631         expandViews_actionPerformed();
632       }
633     };
634     overrideMenuItem(key_X, action);
635   }
636
637   /**
638    * Replace AlignFrame 'gather views' action with SplitFrame version.
639    */
640   protected void overrideGatherViews()
641   {
642     KeyStroke key_G = KeyStroke.getKeyStroke(KeyEvent.VK_G, 0, false);
643     AbstractAction action = new AbstractAction()
644     {
645       @Override
646       public void actionPerformed(ActionEvent e)
647       {
648         gatherViews_actionPerformed();
649       }
650     };
651     overrideMenuItem(key_G, action);
652   }
653
654   /**
655    * Override the menu action associated with the keystroke in the child frames,
656    * replacing it with the given action.
657    * 
658    * @param ks
659    * @param action
660    */
661   private void overrideMenuItem(KeyStroke ks, AbstractAction action)
662   {
663     overrideMenuItem(ks, action, getTopFrame());
664     overrideMenuItem(ks, action, getBottomFrame());
665   }
666
667   /**
668    * Override the menu action associated with the keystroke in one child frame,
669    * replacing it with the given action. Mwahahahaha.
670    * 
671    * @param key
672    * @param action
673    * @param comp
674    */
675   private void overrideMenuItem(KeyStroke key, final AbstractAction action,
676           JComponent comp)
677   {
678     if (comp instanceof AlignFrame)
679     {
680       JMenuItem mi = ((AlignFrame) comp).getAccelerators().get(key);
681       if (mi != null)
682       {
683         for (ActionListener al : mi.getActionListeners())
684         {
685           mi.removeActionListener(al);
686         }
687         mi.addActionListener(new ActionListener()
688         {
689           @Override
690           public void actionPerformed(ActionEvent e)
691           {
692             action.actionPerformed(e);
693           }
694         });
695       }
696     }
697   }
698
699   /**
700    * Expand any multiple views (which are always in pairs) into separate split
701    * frames.
702    */
703   protected void expandViews_actionPerformed()
704   {
705     Desktop.instance.explodeViews(this);
706   }
707
708   /**
709    * Gather any other SplitFrame views of this alignment back in as multiple
710    * (pairs of) views in this SplitFrame.
711    */
712   protected void gatherViews_actionPerformed()
713   {
714     Desktop.instance.gatherViews(this);
715   }
716
717   /**
718    * Returns the alignment in the complementary frame to the one given.
719    */
720   @Override
721   public AlignmentI getComplement(Object alignFrame)
722   {
723     if (alignFrame == this.getTopFrame())
724     {
725       return ((AlignFrame) getBottomFrame()).viewport.getAlignment();
726     }
727     else if (alignFrame == this.getBottomFrame())
728     {
729       return ((AlignFrame) getTopFrame()).viewport.getAlignment();
730     }
731     return null;
732   }
733
734   /**
735    * Returns the title of the complementary frame to the one given.
736    */
737   @Override
738   public String getComplementTitle(Object alignFrame)
739   {
740     if (alignFrame == this.getTopFrame())
741     {
742       return ((AlignFrame) getBottomFrame()).getTitle();
743     }
744     else if (alignFrame == this.getBottomFrame())
745     {
746       return ((AlignFrame) getTopFrame()).getTitle();
747     }
748     return null;
749   }
750
751   /**
752    * Set the 'other half' to hidden / revealed.
753    */
754   @Override
755   public void setComplementVisible(Object alignFrame, boolean show)
756   {
757     /*
758      * Hiding the AlignPanel suppresses unnecessary repaints
759      */
760     if (alignFrame == getTopFrame())
761     {
762       ((AlignFrame) getBottomFrame()).alignPanel.setVisible(show);
763     }
764     else if (alignFrame == getBottomFrame())
765     {
766       ((AlignFrame) getTopFrame()).alignPanel.setVisible(show);
767     }
768     super.setComplementVisible(alignFrame, show);
769   }
770
771   /**
772    * return the AlignFrames held by this container
773    * 
774    * @return { Top alignFrame (Usually CDS), Bottom AlignFrame (Usually
775    *         Protein)}
776    */
777   public List<AlignFrame> getAlignFrames()
778   {
779     return Arrays
780             .asList(new AlignFrame[]
781             { (AlignFrame) getTopFrame(), (AlignFrame) getBottomFrame() });
782   }
783
784   @Override
785   public AlignFrame getComplementAlignFrame(
786           AlignViewControllerGuiI alignFrame)
787   {
788     if (getTopFrame() == alignFrame)
789     {
790       return (AlignFrame) getBottomFrame();
791     }
792     if (getBottomFrame() == alignFrame)
793     {
794       return (AlignFrame) getTopFrame();
795     }
796     // we didn't know anything about this frame...
797     return null;
798   }
799
800   /**
801    * Replace Cmd-F Find action with our version. This is necessary because the
802    * 'default' Finder searches in the first AlignFrame it finds. We need it to
803    * search in the half of the SplitFrame that has the mouse.
804    */
805   protected void overrideFind()
806   {
807     /*
808      * Ctrl-F / Cmd-F open Finder dialog, 'focused' on the right alignment
809      */
810     KeyStroke key_cmdF = KeyStroke.getKeyStroke(KeyEvent.VK_F,
811             jalview.util.ShortcutKeyMaskExWrapper
812                     .getMenuShortcutKeyMaskEx(),
813             false);
814     AbstractAction action = new AbstractAction()
815     {
816       @Override
817       public void actionPerformed(ActionEvent e)
818       {
819         Component c = getFrameAtMouse();
820         if (c != null && c instanceof AlignFrame)
821         {
822           AlignFrame af = (AlignFrame) c;
823           boolean dna = af.getViewport().getAlignment().isNucleotide();
824           String scope = MessageManager.getString("label.in") + " "
825                   + (dna ? MessageManager.getString("label.nucleotide")
826                           : MessageManager.getString("label.protein"));
827           new Finder(af.alignPanel, true, scope);
828         }
829       }
830     };
831     overrideKeyBinding(key_cmdF, action);
832   }
833
834   /**
835    * Override to do nothing if triggered from one of the child frames
836    */
837   @Override
838   public void setSelected(boolean selected) throws PropertyVetoException
839   {
840     JDesktopPane desktopPane = getDesktopPane();
841     JInternalFrame fr = desktopPane == null ? null
842             : desktopPane.getSelectedFrame();
843     if (fr == getTopFrame() || fr == getBottomFrame())
844     {
845       /* 
846        * patch for JAL-3288 (deselecting top/bottom frame closes popup menu); 
847        * it may be possible to remove this method in future
848        * if the underlying Java behaviour changes
849        */
850       if (selected)
851       {
852         moveToFront();
853       }
854       return;
855     }
856     super.setSelected(selected);
857   }
858
859   /**
860    * holds the frame for feature settings, so Protein and DNA tabs can be
861    * managed
862    */
863   JInternalFrame featureSettingsUI;
864
865   JTabbedPane featureSettingsPanels;
866
867   @Override
868   public void addFeatureSettingsUI(
869           FeatureSettingsControllerGuiI featureSettings)
870   {
871     boolean showInternalFrame = false;
872     if (featureSettingsUI == null || featureSettingsPanels == null)
873     {
874       showInternalFrame = true;
875       featureSettingsPanels = new JTabbedPane();
876       featureSettingsPanels.addChangeListener(new ChangeListener()
877       {
878
879         @Override
880         public void stateChanged(ChangeEvent e)
881         {
882           if (e.getSource() != featureSettingsPanels
883                   || featureSettingsUI == null
884                   || featureSettingsUI.isClosed()
885                   || !featureSettingsUI.isVisible())
886           {
887             // not our tabbed pane
888             return;
889           }
890           int tab = featureSettingsPanels.getSelectedIndex();
891           if (tab < 0 || featureSettingsPanels
892                   .getSelectedComponent() instanceof FeatureSettingsControllerGuiI)
893           {
894             // no tab selected or already showing a feature settings GUI
895             return;
896           }
897           getAlignFrames().get(tab).showFeatureSettingsUI();
898         }
899       });
900       featureSettingsUI = new JInternalFrame(MessageManager.getString(
901               "label.sequence_feature_settings_for_CDS_and_Protein"));
902       featureSettingsPanels.setOpaque(true);
903
904       JPanel dialog = new JPanel();
905       dialog.setOpaque(true);
906       dialog.setLayout(new BorderLayout());
907       dialog.add(featureSettingsPanels, BorderLayout.CENTER);
908       JPanel buttons = new JPanel();
909       JButton ok = new JButton(MessageManager.getString("action.ok"));
910       ok.addActionListener(new ActionListener()
911       {
912
913         @Override
914         public void actionPerformed(ActionEvent e)
915         {
916           try
917           {
918             featureSettingsUI.setClosed(true);
919           } catch (PropertyVetoException pv)
920           {
921             pv.printStackTrace();
922           }
923         }
924       });
925       JButton cancel = new JButton(
926               MessageManager.getString("action.cancel"));
927       cancel.addActionListener(new ActionListener()
928       {
929
930         @Override
931         public void actionPerformed(ActionEvent e)
932         {
933           try
934           {
935             for (Component fspanel : featureSettingsPanels.getComponents())
936             {
937               if (fspanel instanceof FeatureSettingsControllerGuiI)
938               {
939                 ((FeatureSettingsControllerGuiI) fspanel).revert();
940               }
941             }
942             featureSettingsUI.setClosed(true);
943           } catch (Exception pv)
944           {
945             pv.printStackTrace();
946           }
947         }
948       });
949       buttons.add(ok);
950       buttons.add(cancel);
951       dialog.add(buttons, BorderLayout.SOUTH);
952       featureSettingsUI.setContentPane(dialog);
953       createDummyTabs();
954     }
955     if (featureSettingsPanels
956             .indexOfTabComponent((Component) featureSettings) > -1)
957     {
958       // just show the feature settings !
959       featureSettingsPanels
960               .setSelectedComponent((Component) featureSettings);
961       return;
962     }
963     // otherwise replace the dummy tab with the given feature settings
964     int pos = getAlignFrames().indexOf(featureSettings.getAlignframe());
965     // if pos==-1 then alignFrame isn't managed by this splitframe
966     if (pos == 0)
967     {
968       featureSettingsPanels.removeTabAt(0);
969       featureSettingsPanels.insertTab(tabName[0], null,
970               (Component) featureSettings,
971               MessageManager.formatMessage(
972                       "label.sequence_feature_settings_for", tabName[0]),
973               0);
974     }
975     if (pos == 1)
976     {
977       featureSettingsPanels.removeTabAt(1);
978       featureSettingsPanels.insertTab(tabName[1], null,
979               (Component) featureSettings,
980               MessageManager.formatMessage(
981                       "label.sequence_feature_settings_for", tabName[1]),
982               1);
983     }
984     featureSettingsPanels.setSelectedComponent((Component) featureSettings);
985
986     // TODO: JAL-3535 - construct a feature settings title including names of
987     // currently selected CDS and Protein names
988
989     if (showInternalFrame)
990     {
991       if (Platform.isAMacAndNotJS())
992       {
993         Desktop.addInternalFrame(featureSettingsUI,
994                 MessageManager.getString(
995                         "label.sequence_feature_settings_for_CDS_and_Protein"),
996                 600, 480);
997       }
998       else
999       {
1000         Desktop.addInternalFrame(featureSettingsUI,
1001                 MessageManager.getString(
1002                         "label.sequence_feature_settings_for_CDS_and_Protein"),
1003                 600, 450);
1004       }
1005       featureSettingsUI
1006               .setMinimumSize(new Dimension(FS_MIN_WIDTH, FS_MIN_HEIGHT));
1007
1008       featureSettingsUI.addInternalFrameListener(
1009               new javax.swing.event.InternalFrameAdapter()
1010               {
1011                 @Override
1012                 public void internalFrameClosed(
1013                         javax.swing.event.InternalFrameEvent evt)
1014                 {
1015                   for (int tab = 0; tab < featureSettingsPanels
1016                           .getTabCount();)
1017                   {
1018                     FeatureSettingsControllerGuiI fsettings = (FeatureSettingsControllerGuiI) featureSettingsPanels
1019                             .getTabComponentAt(tab);
1020                     if (fsettings != null)
1021                     {
1022                       featureSettingsPanels.removeTabAt(tab);
1023                       fsettings.featureSettings_isClosed();
1024                     }
1025                     else
1026                     {
1027                       tab++;
1028                     }
1029                   }
1030                   featureSettingsPanels = null;
1031                   featureSettingsUI = null;
1032                 };
1033               });
1034       featureSettingsUI.setLayer(JLayeredPane.PALETTE_LAYER);
1035     }
1036   }
1037
1038   /**
1039    * tab names for feature settings
1040    */
1041   private String[] tabName = new String[] {
1042       MessageManager.getString("label.CDS"),
1043       MessageManager.getString("label.protein") };
1044
1045   /**
1046    * create placeholder tabs which materialise the feature settings for a given
1047    * view. Also reinitialises any tabs containing stale feature settings
1048    */
1049   private void createDummyTabs()
1050   {
1051     for (int tabIndex = 0; tabIndex < 2; tabIndex++)
1052     {
1053       JPanel dummyTab = new JPanel();
1054       featureSettingsPanels.addTab(tabName[tabIndex], dummyTab);
1055     }
1056   }
1057
1058   private void replaceWithDummyTab(FeatureSettingsControllerI toClose)
1059   {
1060     Component dummyTab = null;
1061     for (int tabIndex = 0; tabIndex < 2; tabIndex++)
1062     {
1063       if (featureSettingsPanels.getTabCount() > tabIndex)
1064       {
1065         dummyTab = featureSettingsPanels.getTabComponentAt(tabIndex);
1066         if (dummyTab instanceof FeatureSettingsControllerGuiI
1067                 && !dummyTab.isVisible())
1068         {
1069           featureSettingsPanels.removeTabAt(tabIndex);
1070           // close the feature Settings tab
1071           ((FeatureSettingsControllerGuiI) dummyTab)
1072                   .featureSettings_isClosed();
1073           // create a dummy tab in its place
1074           dummyTab = new JPanel();
1075           featureSettingsPanels.insertTab(tabName[tabIndex], null, dummyTab,
1076                   MessageManager.formatMessage(
1077                           "label.sequence_feature_settings_for",
1078                           tabName[tabIndex]),
1079                   tabIndex);
1080         }
1081       }
1082     }
1083   }
1084
1085   @Override
1086   public void closeFeatureSettings(
1087           FeatureSettingsControllerI featureSettings,
1088           boolean closeContainingFrame)
1089   {
1090     if (featureSettingsUI != null)
1091     {
1092       if (closeContainingFrame)
1093       {
1094         try
1095         {
1096           featureSettingsUI.setClosed(true);
1097         } catch (Exception x)
1098         {
1099         }
1100         featureSettingsUI = null;
1101       }
1102       else
1103       {
1104         replaceWithDummyTab(featureSettings);
1105       }
1106     }
1107   }
1108
1109   @Override
1110   public boolean isFeatureSettingsOpen()
1111   {
1112     return featureSettingsUI != null && !featureSettingsUI.isClosed();
1113   }
1114 }