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