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