JAL-3416 Remove all JFrame/JInternalFrame icons (set to null)
[jalview.git] / src / jalview / gui / CalculationChooser.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.gui;
22
23 import java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Component;
26 import java.awt.Dimension;
27 import java.awt.FlowLayout;
28 import java.awt.Font;
29 import java.awt.GridLayout;
30 import java.awt.Insets;
31 import java.awt.event.ActionEvent;
32 import java.awt.event.ActionListener;
33 import java.awt.event.FocusEvent;
34 import java.awt.event.FocusListener;
35 import java.awt.event.MouseAdapter;
36 import java.awt.event.MouseEvent;
37 import java.beans.PropertyVetoException;
38 import java.util.ArrayList;
39 import java.util.List;
40
41 import javax.swing.BorderFactory;
42 import javax.swing.ButtonGroup;
43 import javax.swing.DefaultComboBoxModel;
44 import javax.swing.JButton;
45 import javax.swing.JCheckBox;
46 import javax.swing.JComboBox;
47 import javax.swing.JInternalFrame;
48 import javax.swing.JLabel;
49 import javax.swing.JLayeredPane;
50 import javax.swing.JPanel;
51 import javax.swing.JRadioButton;
52 import javax.swing.event.InternalFrameAdapter;
53 import javax.swing.event.InternalFrameEvent;
54
55 import jalview.analysis.TreeBuilder;
56 import jalview.analysis.scoremodels.ScoreModels;
57 import jalview.analysis.scoremodels.SimilarityParams;
58 import jalview.api.analysis.ScoreModelI;
59 import jalview.api.analysis.SimilarityParamsI;
60 import jalview.bin.Cache;
61 import jalview.datamodel.SequenceGroup;
62 import jalview.util.MessageManager;
63
64 /**
65  * A dialog where a user can choose and action Tree or PCA calculation options
66  */
67 public class CalculationChooser extends JPanel
68 {
69   /*
70    * flag for whether gap matches residue in the PID calculation for a Tree
71    * - true gives Jalview 2.10.1 behaviour
72    * - set to false (using Groovy) for a more correct tree
73    * (JAL-374)
74    */
75   private static boolean treeMatchGaps = true;
76
77   private static final Font VERDANA_11PT = new Font("Verdana", 0, 11);
78
79   private static final int MIN_TREE_SELECTION = 3;
80
81   private static final int MIN_PCA_SELECTION = 4;
82
83   AlignFrame af;
84
85   JRadioButton pca;
86
87   JRadioButton neighbourJoining;
88
89   JRadioButton averageDistance;
90
91   JComboBox<String> modelNames;
92
93   JButton calculate;
94
95   private JInternalFrame frame;
96
97   private JCheckBox includeGaps;
98
99   private JCheckBox matchGaps;
100
101   private JCheckBox includeGappedColumns;
102
103   private JCheckBox shorterSequence;
104
105   final ComboBoxTooltipRenderer renderer = new ComboBoxTooltipRenderer();
106
107   List<String> tips = new ArrayList<>();
108
109   /*
110    * the most recently opened PCA results panel
111    */
112   private PCAPanel pcaPanel;
113
114   /**
115    * Constructor
116    * 
117    * @param af
118    */
119   public CalculationChooser(AlignFrame alignFrame)
120   {
121     this.af = alignFrame;
122     init();
123     af.alignPanel.setCalculationDialog(this);
124   }
125
126   /**
127    * Lays out the panel and adds it to the desktop
128    */
129   void init()
130   {
131     setLayout(new BorderLayout());
132     frame = new JInternalFrame();
133     frame.setFrameIcon(null);
134     frame.setContentPane(this);
135     this.setBackground(Color.white);
136     frame.addFocusListener(new FocusListener()
137     {
138
139       @Override
140       public void focusLost(FocusEvent e)
141       {
142       }
143
144       @Override
145       public void focusGained(FocusEvent e)
146       {
147         validateCalcTypes();
148       }
149     });
150     /*
151      * Layout consists of 3 or 4 panels:
152      * - first with choice of PCA or tree method NJ or AV
153      * - second with choice of score model
154      * - third with score model parameter options [suppressed]
155      * - fourth with OK and Cancel
156      */
157     pca = new JRadioButton(
158             MessageManager.getString("label.principal_component_analysis"));
159     pca.setOpaque(false);
160
161     neighbourJoining = new JRadioButton(
162             MessageManager.getString("label.tree_calc_nj"));
163     neighbourJoining.setSelected(true);
164     neighbourJoining.setOpaque(false);
165
166     averageDistance = new JRadioButton(
167             MessageManager.getString("label.tree_calc_av"));
168     averageDistance.setOpaque(false);
169
170     JPanel calcChoicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
171     calcChoicePanel.setOpaque(false);
172
173     // first create the Tree calculation's border panel
174     JPanel treePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
175     treePanel.setOpaque(false);
176
177     JvSwingUtils.createTitledBorder(treePanel,
178             MessageManager.getString("label.tree"), true);
179
180     // then copy the inset dimensions for the border-less PCA panel
181     JPanel pcaBorderless = new JPanel(new FlowLayout(FlowLayout.LEFT));
182     Insets b = treePanel.getBorder().getBorderInsets(treePanel);
183     pcaBorderless.setBorder(
184             BorderFactory.createEmptyBorder(2, b.left, 2, b.right));
185     pcaBorderless.setOpaque(false);
186
187     pcaBorderless.add(pca, FlowLayout.LEFT);
188     calcChoicePanel.add(pcaBorderless, FlowLayout.LEFT);
189
190     treePanel.add(neighbourJoining);
191     treePanel.add(averageDistance);
192
193     calcChoicePanel.add(treePanel);
194
195     ButtonGroup calcTypes = new ButtonGroup();
196     calcTypes.add(pca);
197     calcTypes.add(neighbourJoining);
198     calcTypes.add(averageDistance);
199
200     ActionListener calcChanged = new ActionListener()
201     {
202       @Override
203       public void actionPerformed(ActionEvent e)
204       {
205         validateCalcTypes();
206       }
207     };
208     pca.addActionListener(calcChanged);
209     neighbourJoining.addActionListener(calcChanged);
210     averageDistance.addActionListener(calcChanged);
211
212     /*
213      * score models drop-down - with added tooltips!
214      */
215     modelNames = buildModelOptionsList();
216
217     JPanel scoreModelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
218     scoreModelPanel.setOpaque(false);
219     scoreModelPanel.add(modelNames);
220
221     /*
222      * score model parameters
223      */
224     JPanel paramsPanel = new JPanel(new GridLayout(5, 1));
225     paramsPanel.setOpaque(false);
226     includeGaps = new JCheckBox("Include gaps");
227     matchGaps = new JCheckBox("Match gaps");
228     includeGappedColumns = new JCheckBox("Include gapped columns");
229     shorterSequence = new JCheckBox("Match on shorter sequence");
230     paramsPanel.add(new JLabel("Pairwise sequence scoring options"));
231     paramsPanel.add(includeGaps);
232     paramsPanel.add(matchGaps);
233     paramsPanel.add(includeGappedColumns);
234     paramsPanel.add(shorterSequence);
235
236     /*
237      * OK / Cancel buttons
238      */
239     calculate = new JButton(MessageManager.getString("action.calculate"));
240     calculate.setFont(VERDANA_11PT);
241     calculate.addActionListener(new java.awt.event.ActionListener()
242     {
243       @Override
244       public void actionPerformed(ActionEvent e)
245       {
246         calculate_actionPerformed();
247       }
248     });
249     JButton close = new JButton(MessageManager.getString("action.close"));
250     close.setFont(VERDANA_11PT);
251     close.addActionListener(new java.awt.event.ActionListener()
252     {
253       @Override
254       public void actionPerformed(ActionEvent e)
255       {
256         close_actionPerformed();
257       }
258     });
259     JPanel actionPanel = new JPanel();
260     actionPanel.setOpaque(false);
261     actionPanel.add(calculate);
262     actionPanel.add(close);
263
264     boolean includeParams = false;
265     this.add(calcChoicePanel, BorderLayout.CENTER);
266     calcChoicePanel.add(scoreModelPanel);
267     if (includeParams)
268     {
269       scoreModelPanel.add(paramsPanel);
270     }
271     this.add(actionPanel, BorderLayout.SOUTH);
272
273     int width = 350;
274     int height = includeParams ? 420 : 240;
275
276     setMinimumSize(new Dimension(325, height - 10));
277     String title = MessageManager.getString("label.choose_calculation");
278     if (af.getViewport().getViewName() != null)
279     {
280       title = title + " (" + af.getViewport().getViewName() + ")";
281     }
282
283     Desktop.addInternalFrame(frame, title, width, height, false);
284     calcChoicePanel.doLayout();
285     revalidate();
286     /*
287      * null the AlignmentPanel's reference to the dialog when it is closed
288      */
289     frame.addInternalFrameListener(new InternalFrameAdapter()
290     {
291       @Override
292       public void internalFrameClosed(InternalFrameEvent evt)
293       {
294         af.alignPanel.setCalculationDialog(null);
295       };
296     });
297
298     validateCalcTypes();
299     frame.setLayer(JLayeredPane.PALETTE_LAYER);
300   }
301
302   /**
303    * enable calculations applicable for the current alignment or selection.
304    */
305   protected void validateCalcTypes()
306   {
307     int size = af.getViewport().getAlignment().getHeight();
308     if (af.getViewport().getSelectionGroup() != null)
309     {
310       size = af.getViewport().getSelectionGroup().getSize();
311     }
312
313     /*
314      * disable calc options for which there is insufficient input data
315      * return value of true means enabled and selected
316      */
317     boolean checkPca = checkEnabled(pca, size, MIN_PCA_SELECTION);
318     boolean checkNeighbourJoining = checkEnabled(neighbourJoining, size,
319             MIN_TREE_SELECTION);
320     boolean checkAverageDistance = checkEnabled(averageDistance, size,
321             MIN_TREE_SELECTION);
322
323     if (checkPca || checkNeighbourJoining || checkAverageDistance)
324     {
325       calculate.setToolTipText(null);
326       calculate.setEnabled(true);
327     }
328     else
329     {
330       calculate.setEnabled(false);
331     }
332     updateScoreModels(modelNames, tips);
333   }
334
335   /**
336    * Check the input and disable a calculation's radio button if necessary. A
337    * tooltip is shown for disabled calculations.
338    * 
339    * @param calc
340    *          - radio button for the calculation being validated
341    * @param size
342    *          - size of input to calculation
343    * @param minsize
344    *          - minimum size for calculation
345    * @return true if size >= minsize and calc.isSelected
346    */
347   private boolean checkEnabled(JRadioButton calc, int size, int minsize)
348   {
349     String ttip = MessageManager
350             .formatMessage("label.you_need_at_least_n_sequences", minsize);
351
352     calc.setEnabled(size >= minsize);
353     if (!calc.isEnabled())
354     {
355       calc.setToolTipText(ttip);
356     }
357     else
358     {
359       calc.setToolTipText(null);
360     }
361     if (calc.isSelected())
362     {
363       modelNames.setEnabled(calc.isEnabled());
364       if (calc.isEnabled())
365       {
366         return true;
367       }
368       else
369       {
370         calculate.setToolTipText(ttip);
371       }
372     }
373     return false;
374   }
375
376   /**
377    * A rather elaborate helper method (blame Swing, not me) that builds a
378    * drop-down list of score models (by name) with descriptions as tooltips.
379    * There is also a tooltip shown for the currently selected item when hovering
380    * over it (without opening the list).
381    */
382   protected JComboBox<String> buildModelOptionsList()
383   {
384     final JComboBox<String> scoreModelsCombo = new JComboBox<>();
385     scoreModelsCombo.setRenderer(renderer);
386
387     /*
388      * show tooltip on mouse over the combobox
389      * note the listener has to be on the components that make up
390      * the combobox, doesn't work if just on the combobox
391      */
392     final MouseAdapter mouseListener = new MouseAdapter()
393     {
394       @Override
395       public void mouseEntered(MouseEvent e)
396       {
397         scoreModelsCombo.setToolTipText(
398                 tips.get(scoreModelsCombo.getSelectedIndex()));
399       }
400
401       @Override
402       public void mouseExited(MouseEvent e)
403       {
404         scoreModelsCombo.setToolTipText(null);
405       }
406     };
407     for (Component c : scoreModelsCombo.getComponents())
408     {
409       c.addMouseListener(mouseListener);
410     }
411
412     updateScoreModels(scoreModelsCombo, tips);
413
414     /*
415      * set the list of tooltips on the combobox's renderer
416      */
417     renderer.setTooltips(tips);
418
419     return scoreModelsCombo;
420   }
421
422   private void updateScoreModels(JComboBox<String> comboBox,
423           List<String> toolTips)
424   {
425     Object curSel = comboBox.getSelectedItem();
426     toolTips.clear();
427     DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
428
429     /*
430      * select the score models applicable to the alignment type
431      */
432     boolean nucleotide = af.getViewport().getAlignment().isNucleotide();
433     List<ScoreModelI> models = getApplicableScoreModels(nucleotide,
434             pca.isSelected());
435
436     /*
437      * now we can actually add entries to the combobox,
438      * remembering their descriptions for tooltips
439      */
440     boolean selectedIsPresent = false;
441     for (ScoreModelI sm : models)
442     {
443       if (curSel != null && sm.getName().equals(curSel))
444       {
445         selectedIsPresent = true;
446         curSel = sm.getName();
447       }
448       model.addElement(sm.getName());
449
450       /*
451        * tooltip is description if provided, else text lookup with
452        * fallback on the model name
453        */
454       String tooltip = sm.getDescription();
455       if (tooltip == null)
456       {
457         tooltip = MessageManager.getStringOrReturn("label.score_model_",
458                 sm.getName());
459       }
460       toolTips.add(tooltip);
461     }
462
463     if (selectedIsPresent)
464     {
465       model.setSelectedItem(curSel);
466     }
467     // finally, update the model
468     comboBox.setModel(model);
469   }
470
471   /**
472    * Builds a list of score models which are applicable for the alignment and
473    * calculation type (peptide or generic models for protein, nucleotide or
474    * generic models for nucleotide).
475    * <p>
476    * As a special case, includes BLOSUM62 as an extra option for nucleotide PCA.
477    * This is for backwards compatibility with Jalview prior to 2.8 when BLOSUM62
478    * was the only score matrix supported. This is included if property
479    * BLOSUM62_PCA_FOR_NUCLEOTIDE is set to true in the Jalview properties file.
480    * 
481    * @param nucleotide
482    * @param forPca
483    * @return
484    */
485   protected static List<ScoreModelI> getApplicableScoreModels(
486           boolean nucleotide, boolean forPca)
487   {
488     List<ScoreModelI> filtered = new ArrayList<>();
489
490     ScoreModels scoreModels = ScoreModels.getInstance();
491     for (ScoreModelI sm : scoreModels.getModels())
492     {
493       if (!nucleotide && sm.isProtein() || nucleotide && sm.isDNA())
494       {
495         filtered.add(sm);
496       }
497     }
498
499     /*
500      * special case: add BLOSUM62 as last option for nucleotide PCA, 
501      * for backwards compatibility with Jalview < 2.8 (JAL-2962)
502      */
503     if (nucleotide && forPca
504             && Cache.getDefault("BLOSUM62_PCA_FOR_NUCLEOTIDE", false))
505     {
506       filtered.add(scoreModels.getBlosum62());
507     }
508
509     return filtered;
510   }
511
512   /**
513    * Open and calculate the selected tree or PCA on 'OK'
514    */
515   protected void calculate_actionPerformed()
516   {
517     boolean doPCA = pca.isSelected();
518     String modelName = modelNames.getSelectedItem().toString();
519     SimilarityParamsI params = getSimilarityParameters(doPCA);
520
521     if (doPCA)
522     {
523       openPcaPanel(modelName, params);
524     }
525     else
526     {
527       openTreePanel(modelName, params);
528     }
529
530     // closeFrame();
531   }
532
533   /**
534    * Open a new Tree panel on the desktop
535    * 
536    * @param modelName
537    * @param params
538    */
539   protected void openTreePanel(String modelName, SimilarityParamsI params)
540   {
541     /*
542      * gui validation shouldn't allow insufficient sequences here, but leave
543      * this check in in case this method gets exposed programmatically in future
544      */
545     AlignViewport viewport = af.getViewport();
546     SequenceGroup sg = viewport.getSelectionGroup();
547     if (sg != null && sg.getSize() < MIN_TREE_SELECTION)
548     {
549       JvOptionPane.showMessageDialog(Desktop.desktop,
550               MessageManager.formatMessage(
551                       "label.you_need_at_least_n_sequences",
552                       MIN_TREE_SELECTION),
553               MessageManager.getString("label.not_enough_sequences"),
554               JvOptionPane.WARNING_MESSAGE);
555       return;
556     }
557
558     String treeType = neighbourJoining.isSelected()
559             ? TreeBuilder.NEIGHBOUR_JOINING
560             : TreeBuilder.AVERAGE_DISTANCE;
561     af.newTreePanel(treeType, modelName, params);
562   }
563
564   /**
565    * Open a new PCA panel on the desktop
566    * 
567    * @param modelName
568    * @param params
569    */
570   protected void openPcaPanel(String modelName, SimilarityParamsI params)
571   {
572     AlignViewport viewport = af.getViewport();
573
574     /*
575      * gui validation shouldn't allow insufficient sequences here, but leave
576      * this check in in case this method gets exposed programmatically in future
577      */
578     if (((viewport.getSelectionGroup() != null)
579             && (viewport.getSelectionGroup().getSize() < MIN_PCA_SELECTION)
580             && (viewport.getSelectionGroup().getSize() > 0))
581             || (viewport.getAlignment().getHeight() < MIN_PCA_SELECTION))
582     {
583       JvOptionPane.showInternalMessageDialog(this,
584               MessageManager.formatMessage(
585                       "label.you_need_at_least_n_sequences",
586                       MIN_PCA_SELECTION),
587               MessageManager
588                       .getString("label.sequence_selection_insufficient"),
589               JvOptionPane.WARNING_MESSAGE);
590       return;
591     }
592
593     /*
594      * construct the panel and kick off its calculation thread
595      */
596     pcaPanel = new PCAPanel(af.alignPanel, modelName, params);
597     new Thread(pcaPanel).start();
598
599   }
600
601   /**
602    * 
603    */
604   protected void closeFrame()
605   {
606     try
607     {
608       frame.setClosed(true);
609     } catch (PropertyVetoException ex)
610     {
611     }
612   }
613
614   /**
615    * Returns a data bean holding parameters for similarity (or distance) model
616    * calculation
617    * 
618    * @param doPCA
619    * @return
620    */
621   protected SimilarityParamsI getSimilarityParameters(boolean doPCA)
622   {
623     // commented out: parameter choices read from gui widgets
624     // SimilarityParamsI params = new SimilarityParams(
625     // includeGappedColumns.isSelected(), matchGaps.isSelected(),
626     // includeGaps.isSelected(), shorterSequence.isSelected());
627
628     boolean includeGapGap = true;
629     boolean includeGapResidue = true;
630     boolean matchOnShortestLength = false;
631
632     /*
633      * 'matchGaps' flag is only used in the PID calculation
634      * - set to false for PCA so that PCA using PID reproduces SeqSpace PCA
635      * - set to true for Tree to reproduce Jalview 2.10.1 calculation
636      * - set to false for Tree for a more correct calculation (JAL-374)
637      */
638     boolean matchGap = doPCA ? false : treeMatchGaps;
639
640     return new SimilarityParams(includeGapGap, matchGap, includeGapResidue,
641             matchOnShortestLength);
642   }
643
644   /**
645    * Closes dialog on Close button press
646    */
647   protected void close_actionPerformed()
648   {
649     try
650     {
651       frame.setClosed(true);
652     } catch (Exception ex)
653     {
654     }
655   }
656
657   public PCAPanel getPcaPanel()
658   {
659     return pcaPanel;
660   }
661 }