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