2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
23 import jalview.util.MessageManager;
24 import jalview.ws.jws2.dm.JabaOption;
25 import jalview.ws.params.ArgumentI;
26 import jalview.ws.params.OptionI;
27 import jalview.ws.params.ParameterI;
28 import jalview.ws.params.ValueConstrainI;
29 import jalview.ws.params.ValueConstrainI.ValueType;
30 import jalview.ws.params.simple.LogarithmicParameter;
31 import jalview.ws.params.simple.StringParameter;
33 import java.awt.BorderLayout;
34 import java.awt.Color;
35 import java.awt.Component;
36 import java.awt.Dimension;
37 import java.awt.FlowLayout;
39 import java.awt.Rectangle;
40 import java.awt.event.ActionEvent;
41 import java.awt.event.ActionListener;
42 import java.awt.event.KeyAdapter;
43 import java.awt.event.KeyEvent;
44 import java.awt.event.MouseEvent;
45 import java.awt.event.MouseListener;
47 import java.util.ArrayList;
48 import java.util.LinkedHashMap;
49 import java.util.List;
52 import javax.swing.JButton;
53 import javax.swing.JCheckBox;
54 import javax.swing.JComboBox;
55 import javax.swing.JComponent;
56 import javax.swing.JLabel;
57 import javax.swing.JMenuItem;
58 import javax.swing.JPanel;
59 import javax.swing.JPopupMenu;
60 import javax.swing.JScrollPane;
61 import javax.swing.JSlider;
62 import javax.swing.JTextArea;
63 import javax.swing.JTextField;
64 import javax.swing.border.TitledBorder;
65 import javax.swing.event.ChangeEvent;
66 import javax.swing.event.ChangeListener;
68 import net.miginfocom.swing.MigLayout;
71 * GUI generator/manager for options and parameters. Originally abstracted from
72 * the WsJobParameters dialog box.
77 public class OptsAndParamsPage
79 public static final int PARAM_WIDTH = 340;
81 public static final int PARAM_HEIGHT = 150;
83 public static final int PARAM_CLOSEDHEIGHT = 80;
85 URL linkImageURL = getClass().getResource("/images/link.gif");
87 Map<String, OptionBox> optSet = new LinkedHashMap<>();
89 Map<String, ParamBox> paramSet = new LinkedHashMap<>();
92 * compact or verbose style parameters
94 boolean compact = false;
96 OptsParametersContainerI poparent;
99 * A class that models a panel rendering a single option (checkbox or choice
102 public class OptionBox extends JPanel
103 implements MouseListener, ActionListener
109 boolean hasLink = false;
111 boolean initEnabled = false;
113 String initVal = null;
117 JComboBox<String> val;
120 * Constructs and adds labels and controls to the panel for one Option
124 public OptionBox(OptionI opt)
127 setLayout(new FlowLayout(FlowLayout.LEFT));
128 enabled = new JCheckBox(opt.getName());
129 enabled.setSelected(opt.isRequired());
132 * If option is required, show a label, if optional a checkbox
133 * (but not for Jabaws pending JWS-126 resolution)
135 if (opt.isRequired() && !(opt instanceof JabaOption))
138 add(new JLabel(opt.getName()));
142 finfo = option.getFurtherDetails();
143 configureCheckbox(opt);
148 * construct the choice box with possible values,
149 * or their display names if provided
151 val = buildComboBox(opt);
152 val.setSelectedItem(opt.getValue());
155 * only show the choicebox if there is more than one option,
156 * or the option is mandatory
158 if (opt.getPossibleValues().size() > 1 || opt.isRequired())
160 val.addActionListener(this);
168 * Configures the checkbox that controls whether or not the option is
173 protected void configureCheckbox(OptionI opt)
175 enabled.setFont(new Font("Verdana", Font.PLAIN, 11));
176 enabled.addActionListener(this);
177 final String desc = opt.getDescription();
181 String description = desc;
182 if (desc == null || desc.trim().isEmpty())
184 description = MessageManager
185 .getString("label.opt_and_params_further_details");
187 description = description + "<br><img src=\"" + linkImageURL
189 String text = JvSwingUtils.wrapTooltip(true, description);
190 enabled.setToolTipText(text);
191 enabled.addMouseListener(this); // for popup menu to show link
195 if (desc != null && desc.trim().length() > 0)
197 enabled.setToolTipText(JvSwingUtils.wrapTooltip(true, desc));
203 public void actionPerformed(ActionEvent e)
205 if (e.getSource() != enabled)
207 enabled.setSelected(true);
212 private void checkIfModified()
214 boolean notmod = (initEnabled == enabled.isSelected());
215 if (enabled.isSelected())
219 notmod &= initVal.equals(val.getSelectedItem());
223 // compare against default service setting
224 notmod &= option.getValue() == null
225 || option.getValue().equals(val.getSelectedItem());
230 notmod &= (initVal != null) ? initVal.equals(val.getSelectedItem())
231 : val.getSelectedItem() != initVal;
233 poparent.argSetModified(this, !notmod);
237 * Answers null if the option is not selected, else a new Option holding the
242 public ArgumentI getSelectedOption()
244 if (!enabled.isSelected())
248 String value = getSelectedValue(option, val.getSelectedIndex());
249 OptionI opt = option.copy();
255 public void mouseClicked(MouseEvent e)
257 if (e.isPopupTrigger()) // for Windows
259 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
264 public void mouseEntered(MouseEvent e)
269 public void mouseExited(MouseEvent e)
274 public void mousePressed(MouseEvent e)
276 if (e.isPopupTrigger()) // Mac
278 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
283 public void mouseReleased(MouseEvent e)
287 public void resetToDefault(boolean setDefaultParams)
289 enabled.setSelected(false);
290 if (option.isRequired()
291 || (setDefaultParams && option.getValue() != null))
293 // Apply default value
294 selectOption(option, option.getValue());
298 public void setInitialValue()
300 initEnabled = enabled.isSelected();
301 if (option.getPossibleValues() != null
302 && option.getPossibleValues().size() > 1)
304 initVal = (String) val.getSelectedItem();
308 initVal = (initEnabled) ? (String) val.getSelectedItem() : null;
313 * toString representation for identification in the debugger only
316 public String toString()
318 return option == null ? super.toString() : option.toString();
324 * A class that models a panel rendering a single parameter
326 public class ParamBox extends JPanel
327 implements ChangeListener, ActionListener, MouseListener
330 * parameter values (or their logs) are multiplied by this
331 * scaling factor to ensure an integer range for the slider
333 private int sliderScaleFactor = 1;
335 boolean isLogarithmicParameter;
337 boolean isChoiceParameter;
339 boolean isIntegerParameter;
341 boolean isStringParameter;
345 JComboBox<String> choicebox;
347 JPanel controlsPanel = new JPanel();
349 boolean descriptionIsVisible = false;
351 JScrollPane descPanel = new JScrollPane();
357 ParameterI parameter;
359 final OptsParametersContainerI pmdialogbox;
361 JPanel settingPanel = new JPanel();
365 JTextArea descriptionText = new JTextArea();
367 ValueConstrainI validator;
369 JTextField valueField;
371 private String descTooltip;
373 public ParamBox(final OptsParametersContainerI paramContainer,
376 pmdialogbox = paramContainer;
377 finfo = parm.getFurtherDetails();
378 validator = parm.getValidValue();
381 isLogarithmicParameter = parm instanceof LogarithmicParameter;
383 if (validator != null)
385 ValueType type = validator.getType();
386 isIntegerParameter = type == ValueType.Integer;
387 isStringParameter = type == ValueType.String;
390 * ensure slider has an integer range corresponding to
391 * the min-max range of the parameter
393 if (validator.getMin() != null && validator.getMax() != null
394 // && !isIntegerParameter
395 && !isStringParameter)
397 double min = validator.getMin().doubleValue();
398 double max = validator.getMax().doubleValue();
399 if (isLogarithmicParameter)
404 sliderScaleFactor = (int) (1000000 / (max - min));
405 // todo scaleMin, scaleMax could also be final fields
409 List<String> possibleValues = parameter.getPossibleValues();
410 isChoiceParameter = possibleValues != null
411 && !possibleValues.isEmpty();
415 addCompactParameter(parm);
419 addExpandableParam(parm);
424 * Adds a 'compact' format parameter, with any help text shown as a tooltip
428 private void addCompactParameter(ParameterI parm)
430 setLayout(new MigLayout("", "[][grow]"));
431 String ttipText = null;
433 controlsPanel.setLayout(new BorderLayout());
435 if (parm.getDescription() != null
436 && parm.getDescription().trim().length() > 0)
438 ttipText = (JvSwingUtils.wrapTooltip(true,
439 parm.getDescription() + (finfo != null ? "<br><img src=\""
440 + linkImageURL + "\"/>"
441 + MessageManager.getString(
442 "label.opt_and_params_further_details")
446 JvSwingUtils.addtoLayout(this, ttipText, new JLabel(parm.getName()),
448 updateControls(parm);
453 * Adds an 'expanded' format parameter, with any help shown in a panel that
454 * may be shown or hidden
458 private void addExpandableParam(ParameterI parm)
460 setPreferredSize(new Dimension(PARAM_WIDTH, PARAM_CLOSEDHEIGHT));
461 setBorder(new TitledBorder(parm.getName()));
463 descriptionText.setFont(new Font("Verdana", Font.PLAIN, 11));
464 descriptionText.setBackground(getBackground());
466 descriptionText.setEditable(false);
467 descPanel.getViewport().setView(descriptionText);
469 descPanel.setVisible(false);
471 JPanel firstrow = new JPanel();
472 firstrow.setLayout(null);
473 controlsPanel.setLayout(new BorderLayout());
474 controlsPanel.setBounds(new Rectangle(39, 10, PARAM_WIDTH - 70,
475 PARAM_CLOSEDHEIGHT - 50));
476 firstrow.add(controlsPanel);
477 firstrow.setBounds(new Rectangle(10, 20, PARAM_WIDTH - 30,
478 PARAM_CLOSEDHEIGHT - 30));
480 if (parm.getDescription() != null
481 && parm.getDescription().trim().length() > 0)
483 addExpandableHelp(firstrow, parm);
486 validator = parm.getValidValue();
488 if (validator != null)
490 isIntegerParameter = validator.getType() == ValueType.Integer;
494 if (parameter.getPossibleValues() != null)
496 isChoiceParameter = true;
499 updateControls(parm);
500 descPanel.setBounds(new Rectangle(10, PARAM_CLOSEDHEIGHT,
501 PARAM_WIDTH - 20, PARAM_HEIGHT - PARAM_CLOSEDHEIGHT - 5));
507 * Adds a button which can be clicked to show or hide help text
512 protected void addExpandableHelp(JPanel container, ParameterI param)
514 JButton showDescBtn = new JButton("+");
515 showDescBtn.setFont(new Font("Verdana", Font.PLAIN, 8));
518 descTooltip = JvSwingUtils.wrapTooltip(true,
519 MessageManager.formatMessage(
520 "label.opt_and_params_show_brief_desc_image_link",
522 { linkImageURL.toExternalForm() }));
523 showDescBtn.addMouseListener(this);
527 descTooltip = JvSwingUtils.wrapTooltip(true, MessageManager
528 .getString("label.opt_and_params_show_brief_desc"));
530 showDescBtn.setToolTipText(descTooltip);
531 showDescBtn.addActionListener(new ActionListener()
534 public void actionPerformed(ActionEvent e)
536 descriptionIsVisible = !descriptionIsVisible;
537 showDescBtn.setText(descriptionIsVisible ? "-" : "+");
538 showDescBtn.setToolTipText(
539 descriptionIsVisible ? null : descTooltip);
540 descPanel.setVisible(descriptionIsVisible);
541 descPanel.getVerticalScrollBar().setValue(0);
542 ParamBox.this.setPreferredSize(new Dimension(PARAM_WIDTH,
543 (descriptionIsVisible) ? PARAM_HEIGHT
544 : PARAM_CLOSEDHEIGHT));
545 ParamBox.this.validate();
546 pmdialogbox.refreshParamLayout();
549 descriptionText.setWrapStyleWord(true);
550 descriptionText.setLineWrap(true);
551 descriptionText.setColumns(32);
552 descriptionText.setText(param.getDescription());
553 showDescBtn.setBounds(new Rectangle(10, 10, 16, 16));
554 container.add(showDescBtn);
558 public void actionPerformed(ActionEvent e)
564 if (!isChoiceParameter)
566 updateSliderFromValueField();
572 * Checks whether the value of this parameter has been changed and notifies
573 * the parent page accordingly
575 private void checkIfModified()
577 Object newValue = updateSliderFromValueField();
578 boolean modified = true;
579 if (newValue.getClass() == lastVal.getClass())
581 modified = !newValue.equals(lastVal);
583 pmdialogbox.argSetModified(this, modified);
587 public int getBaseline(int width, int height)
593 // http://stackoverflow.com/questions/2743177/top-alignment-for-flowlayout
594 // helpful hint of using the Java 1.6 alignBaseLine property of FlowLayout
596 public Component.BaselineResizeBehavior getBaselineResizeBehavior()
598 return Component.BaselineResizeBehavior.CONSTANT_ASCENT;
602 * Answers an argument holding the value entered or selected in the dialog
606 public ArgumentI getParameter()
608 ParameterI prm = parameter.copy();
609 if (isChoiceParameter)
611 String value = getSelectedValue(this.parameter, choicebox.getSelectedIndex());
616 prm.setValue(valueField.getText());
623 // reset the widget's initial value.
628 public void mouseClicked(MouseEvent e)
630 if (e.isPopupTrigger()) // for Windows
632 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
637 public void mouseEntered(MouseEvent e)
642 public void mouseExited(MouseEvent e)
647 public void mousePressed(MouseEvent e)
649 if (e.isPopupTrigger()) // for Mac
651 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
656 public void mouseReleased(MouseEvent e)
661 public void stateChanged(ChangeEvent e)
670 if (!isLogarithmicParameter)
673 * set (int or float formatted) text field value
675 valueField.setText(isIntegerParameter
676 ? String.valueOf(slider.getValue())
678 slider.getValue() / (float) sliderScaleFactor));
682 double value = Math.pow(Math.E,
683 slider.getValue() / (double) sliderScaleFactor);
684 valueField.setText(formatDouble(value));
694 * Answers the value formatted as a string to 3 decimal places - in
695 * scientific notation if the value is less than 0.001
700 String formatDouble(double value)
702 String format = value < 0.001 ? "%3.1E" : "%3.3f";
703 return String.format(format, value);
707 * Formats a number as integer or float (3dp) or scientific notation (1dp)
712 String formatNumber(Number n)
714 return n instanceof Integer ? String.valueOf(n.intValue())
715 : formatDouble(n.doubleValue());
718 void updateControls(ParameterI parm)
721 boolean init = (choicebox == null && valueField == null);
724 if (isChoiceParameter)
726 choicebox = buildComboBox(parm);
727 choicebox.addActionListener(this);
728 controlsPanel.add(choicebox, BorderLayout.CENTER);
732 slider = new JSlider();
733 slider.addChangeListener(this);
734 int cols = parm instanceof StringParameter ? 20 : 0;
735 valueField = new JTextField(cols);
736 valueField.addActionListener(this);
737 valueField.addKeyListener(new KeyAdapter()
740 public void keyReleased(KeyEvent e)
742 int keyCode = e.getKeyCode();
743 if (e.isActionKey() && keyCode != KeyEvent.VK_LEFT
744 && keyCode != KeyEvent.VK_RIGHT)
746 if (valueField.getText().trim().length() > 0)
748 actionPerformed(null);
753 valueField.setPreferredSize(new Dimension(65, 25));
754 controlsPanel.add(slider, BorderLayout.WEST);
755 controlsPanel.add(valueField, BorderLayout.EAST);
759 String value = parm.getValue();
762 if (isChoiceParameter)
764 choicebox.setSelectedItem(value);
768 valueField.setText(value);
771 lastVal = updateSliderFromValueField();
776 * Action depends on the type of the input parameter:
778 * <li>if a text input, returns the trimmed value</li>
779 * <li>if a choice list, returns the selected value</li>
780 * <li>if a value slider and input field, sets the value of the slider from
781 * the value in the text field, limiting it to any defined min-max
784 * Answers the (possibly modified) input value, as a String, Integer, Float
789 Object updateSliderFromValueField()
791 if (validator == null || isStringParameter)
793 if (isChoiceParameter)
795 return getSelectedValue(this.parameter, choicebox.getSelectedIndex());
797 slider.setVisible(false);
798 return valueField.getText().trim();
801 valueField.setText(valueField.getText().trim());
804 * ensure not outside min-max range
805 * TODO: provide some visual indicator if limit reached
809 valueField.setBackground(Color.WHITE);
810 double d = Double.parseDouble(valueField.getText());
811 if (validator.getMin() != null
812 && validator.getMin().doubleValue() > d)
814 valueField.setText(formatNumber(validator.getMin()));
816 if (validator.getMax() != null
817 && validator.getMax().doubleValue() < d)
819 valueField.setText(formatNumber(validator.getMax()));
821 } catch (NumberFormatException e)
823 valueField.setBackground(Color.yellow);
827 if (isIntegerParameter)
832 iVal = Integer.valueOf(valueField.getText());
833 } catch (Exception e)
835 valueField.setBackground(Color.yellow);
836 return Integer.valueOf(0);
839 if (validator.getMin() != null && validator.getMax() != null)
841 slider.getModel().setRangeProperties(iVal, 1,
842 validator.getMin().intValue(),
843 validator.getMax().intValue() + 1, true);
847 slider.setVisible(false);
849 return new Integer(iVal);
852 if (isLogarithmicParameter)
857 double eValue = Double.valueOf(valueField.getText());
858 dVal = Math.log(eValue) * sliderScaleFactor;
859 } catch (Exception e)
861 // shouldn't be possible here
862 valueField.setBackground(Color.yellow);
865 if (validator.getMin() != null && validator.getMax() != null)
867 double scaleMin = Math.log(validator.getMin().doubleValue())
869 double scaleMax = Math.log(validator.getMax().doubleValue())
871 slider.getModel().setRangeProperties((int) (dVal), 1,
872 (int) scaleMin, 1 + (int) scaleMax, true);
876 slider.setVisible(false);
878 return new Double(dVal);
884 fVal = Float.valueOf(valueField.getText());
885 } catch (Exception e)
887 return Float.valueOf(0f); // shouldn't happen
889 if (validator.getMin() != null && validator.getMax() != null)
891 float scaleMin = validator.getMin().floatValue()
893 float scaleMax = validator.getMax().floatValue()
895 slider.getModel().setRangeProperties(
896 (int) (fVal * sliderScaleFactor), 1, (int) scaleMin,
897 1 + (int) scaleMax, true);
901 slider.setVisible(false);
903 return new Float(fVal);
908 * Constructor with the option to show 'compact' format (parameter description
909 * as tooltip) or 'expanded' format (parameter description in a textbox which
910 * may be opened or closed). Use compact for simple description text, expanded
911 * for more wordy or formatted text.
913 * @param paramContainer
915 public OptsAndParamsPage(OptsParametersContainerI paramContainer,
918 poparent = paramContainer;
919 this.compact = compact;
922 public static void showUrlPopUp(JComponent invoker, final String finfo,
926 JPopupMenu mnu = new JPopupMenu();
927 JMenuItem mitem = new JMenuItem(
928 MessageManager.formatMessage("label.view_params", new String[]
930 mitem.addActionListener(new ActionListener()
934 public void actionPerformed(ActionEvent e)
936 Desktop.showUrl(finfo);
941 mnu.show(invoker, x, y);
944 public Map<String, OptionBox> getOptSet()
949 public void setOptSet(Map<String, OptionBox> optSet)
951 this.optSet = optSet;
954 public Map<String, ParamBox> getParamSet()
959 public void setParamSet(Map<String, ParamBox> paramSet)
961 this.paramSet = paramSet;
964 OptionBox addOption(OptionI opt)
966 OptionBox cb = optSet.get(opt.getName());
969 cb = new OptionBox(opt);
970 optSet.put(opt.getName(), cb);
971 // jobOptions.add(cb, FlowLayout.LEFT);
976 ParamBox addParameter(ParameterI arg)
978 ParamBox pb = paramSet.get(arg.getName());
981 pb = new ParamBox(poparent, arg);
982 paramSet.put(arg.getName(), pb);
983 // paramList.add(pb);
986 // take the defaults from the parameter
987 pb.updateControls(arg);
991 void selectOption(OptionI option, String string)
993 OptionBox cb = optSet.get(option.getName());
996 cb = addOption(option);
998 cb.enabled.setSelected(string != null); // initial state for an option.
1001 if (option.getPossibleValues().contains(string))
1003 cb.val.setSelectedItem(string);
1007 throw new Error(String.format("Invalid value '%s' for option '%s'",
1008 string, option.getName()));
1011 if (option.isRequired() && !cb.enabled.isSelected())
1013 // TODO: indicate paramset is not valid.. option needs to be selected!
1015 cb.setInitialValue();
1018 void setParameter(ParameterI arg)
1020 ParamBox pb = paramSet.get(arg.getName());
1027 pb.updateControls(arg);
1033 * Answers a list of arguments representing all the options and arguments
1034 * selected on the dialog, holding their chosen or input values. Optional
1035 * parameters which were not selected are not included.
1039 public List<ArgumentI> getCurrentSettings()
1041 List<ArgumentI> argSet = new ArrayList<>();
1042 for (OptionBox opts : getOptSet().values())
1044 ArgumentI opt = opts.getSelectedOption();
1050 for (ParamBox parambox : getParamSet().values())
1052 ArgumentI parm = parambox.getParameter();
1063 * A helper method that constructs and returns a CombBox for choice of the
1064 * possible option values. If display names are provided, then these are added
1065 * as options, otherwise the actual values are added.
1070 protected JComboBox<String> buildComboBox(OptionI opt)
1072 JComboBox<String> cb = null;
1073 List<String> displayNames = opt.getDisplayNames();
1074 if (displayNames != null)
1076 cb = JvSwingUtils.buildComboWithTooltips(displayNames,
1077 opt.getPossibleValues());
1081 cb = new JComboBox<>();
1082 for (String v : opt.getPossibleValues())
1091 * Answers the value corresponding to the selected item in the choice combo
1092 * box. If display names were not provided, this is simply the selected
1093 * value. If display names were provided, it is the value corresponding to
1094 * the selected item index.
1098 protected static String getSelectedValue(OptionI opt, int sel)
1100 List<String> possibleValues = opt.getPossibleValues();
1101 String value = null;
1102 if (possibleValues != null && possibleValues.size() == 1)
1104 // Hack to make sure the default value for an enabled option with only
1105 // one value is actually returned even if this.val is not displayed
1106 value = possibleValues.get(0);
1110 if (sel >= 0 && sel < possibleValues.size())
1112 value = possibleValues.get(sel);
1116 value = opt.getValue();