Merge commit 'alpha/update_2_12_for_2_11_2_series_merge^2' into HEAD
[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.isAMacAndNotJS() ? MAC_INSETS_WIDTH
122             : WINDOWS_INSETS_WIDTH;
123     int heightFudge = Platform.isAMacAndNotJS() ? 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.getInstance().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.getInstance());
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.isAMacAndNotJS() ? 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             Platform.SHORTCUT_KEY_MASK, 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             Platform.SHORTCUT_KEY_MASK, 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.getInstance());
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.getInstance().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.getInstance().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             Platform.SHORTCUT_KEY_MASK, 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           boolean dna = af.getViewport().getAlignment().isNucleotide();
819           String scope = MessageManager.getString("label.in") + " "
820                   + (dna ? MessageManager.getString("label.nucleotide")
821                           : MessageManager.getString("label.protein"));
822           new Finder(af.alignPanel, true, scope);
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.isAMacAndNotJS())
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 }