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()
582 Object newValue = updateSliderFromValueField();
583 boolean modified = true;
584 if (newValue.getClass() == lastVal.getClass())
586 modified = !newValue.equals(lastVal);
588 pmdialogbox.argSetModified(this, modified);
597 public int getBaseline(int width, int height)
603 // http://stackoverflow.com/questions/2743177/top-alignment-for-flowlayout
604 // helpful hint of using the Java 1.6 alignBaseLine property of FlowLayout
606 public Component.BaselineResizeBehavior getBaselineResizeBehavior()
608 return Component.BaselineResizeBehavior.CONSTANT_ASCENT;
612 * Answers an argument holding the value entered or selected in the dialog
616 public ArgumentI getParameter()
618 ParameterI prm = parameter.copy();
619 if (isChoiceParameter)
621 String value = getSelectedValue(this.parameter, choicebox.getSelectedIndex());
626 prm.setValue(valueField.getText());
633 // reset the widget's initial value.
638 public void mouseClicked(MouseEvent e)
640 if (e.isPopupTrigger()) // for Windows
642 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
647 public void mouseEntered(MouseEvent e)
652 public void mouseExited(MouseEvent e)
657 public void mousePressed(MouseEvent e)
659 if (e.isPopupTrigger()) // for Mac
661 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
666 public void mouseReleased(MouseEvent e)
671 public void stateChanged(ChangeEvent e)
680 if (!isLogarithmicParameter)
683 * set (int or float formatted) text field value
685 valueField.setText(isIntegerParameter
686 ? String.valueOf(slider.getValue())
688 slider.getValue() / (float) sliderScaleFactor));
692 double value = Math.pow(Math.E,
693 slider.getValue() / (double) sliderScaleFactor);
694 valueField.setText(formatDouble(value));
704 * Answers the value formatted as a string to 3 decimal places - in
705 * scientific notation if the value is less than 0.001
710 String formatDouble(double value)
712 String format = value < 0.001 ? "%3.1E" : "%3.3f";
713 return String.format(format, value);
717 * Formats a number as integer or float (3dp) or scientific notation (1dp)
722 String formatNumber(Number n)
724 return n instanceof Integer ? String.valueOf(n.intValue())
725 : formatDouble(n.doubleValue());
728 void updateControls(ParameterI parm)
731 boolean init = (choicebox == null && valueField == null);
734 if (isChoiceParameter)
736 choicebox = buildComboBox(parm);
737 controlsPanel.add(choicebox, BorderLayout.CENTER);
741 slider = new JSlider();
742 slider.addChangeListener(this);
743 int cols = parm instanceof StringParameter ? 20 : 0;
744 valueField = new JTextField(cols);
745 valueField.addActionListener(this);
746 valueField.addKeyListener(new KeyAdapter()
749 public void keyReleased(KeyEvent e)
751 int keyCode = e.getKeyCode();
752 if (e.isActionKey() && keyCode != KeyEvent.VK_LEFT
753 && keyCode != KeyEvent.VK_RIGHT)
755 if (valueField.getText().trim().length() > 0)
757 actionPerformed(null);
762 valueField.setPreferredSize(new Dimension(65, 25));
763 controlsPanel.add(slider, BorderLayout.WEST);
764 controlsPanel.add(valueField, BorderLayout.EAST);
768 if (!isChoiceParameter && parm != null)
770 valueField.setText(parm.getValue());
772 lastVal = updateSliderFromValueField();
777 * Action depends on the type of the input parameter:
779 * <li>if a text input, returns the trimmed value</li>
780 * <li>if a choice list, returns the selected value</li>
781 * <li>if a value slider and input field, sets the value of the slider from
782 * the value in the text field, limiting it to any defined min-max
785 * Answers the (possibly modified) input value, as a String, Integer, Float
790 Object updateSliderFromValueField()
792 if (validator == null || isStringParameter)
794 if (isChoiceParameter)
796 return getSelectedValue(this.parameter, choicebox.getSelectedIndex());
798 slider.setVisible(false);
799 return valueField.getText().trim();
802 valueField.setText(valueField.getText().trim());
805 * ensure not outside min-max range
806 * TODO: provide some visual indicator if limit reached
810 valueField.setBackground(Color.WHITE);
811 double d = Double.parseDouble(valueField.getText());
812 if (validator.getMin() != null
813 && validator.getMin().doubleValue() > d)
815 valueField.setText(formatNumber(validator.getMin()));
817 if (validator.getMax() != null
818 && validator.getMax().doubleValue() < d)
820 valueField.setText(formatNumber(validator.getMax()));
822 } catch (NumberFormatException e)
824 valueField.setBackground(Color.yellow);
828 if (isIntegerParameter)
833 iVal = Integer.valueOf(valueField.getText());
834 } catch (Exception e)
836 valueField.setBackground(Color.yellow);
837 return Integer.valueOf(0);
840 if (validator.getMin() != null && validator.getMax() != null)
842 slider.getModel().setRangeProperties(iVal, 1,
843 validator.getMin().intValue(),
844 validator.getMax().intValue() + 1, true);
848 slider.setVisible(false);
850 return new Integer(iVal);
853 if (isLogarithmicParameter)
858 double eValue = Double.valueOf(valueField.getText());
859 dVal = Math.log(eValue) * sliderScaleFactor;
860 } catch (Exception e)
862 // shouldn't be possible here
863 valueField.setBackground(Color.yellow);
866 if (validator.getMin() != null && validator.getMax() != null)
868 double scaleMin = Math.log(validator.getMin().doubleValue())
870 double scaleMax = Math.log(validator.getMax().doubleValue())
872 slider.getModel().setRangeProperties((int) (dVal), 1,
873 (int) scaleMin, 1 + (int) scaleMax, true);
877 slider.setVisible(false);
879 return new Double(dVal);
885 fVal = Float.valueOf(valueField.getText());
886 } catch (Exception e)
888 return Float.valueOf(0f); // shouldn't happen
890 if (validator.getMin() != null && validator.getMax() != null)
892 float scaleMin = validator.getMin().floatValue()
894 float scaleMax = validator.getMax().floatValue()
896 slider.getModel().setRangeProperties(
897 (int) (fVal * sliderScaleFactor), 1, (int) scaleMin,
898 1 + (int) scaleMax, true);
902 slider.setVisible(false);
904 return new Float(fVal);
909 * Constructor with the option to show 'compact' format (parameter description
910 * as tooltip) or 'expanded' format (parameter description in a textbox which
911 * may be opened or closed). Use compact for simple description text, expanded
912 * for more wordy or formatted text.
914 * @param paramContainer
916 public OptsAndParamsPage(OptsParametersContainerI paramContainer,
919 poparent = paramContainer;
920 this.compact = compact;
923 public static void showUrlPopUp(JComponent invoker, final String finfo,
927 JPopupMenu mnu = new JPopupMenu();
928 JMenuItem mitem = new JMenuItem(
929 MessageManager.formatMessage("label.view_params", new String[]
931 mitem.addActionListener(new ActionListener()
935 public void actionPerformed(ActionEvent e)
937 Desktop.showUrl(finfo);
942 mnu.show(invoker, x, y);
945 public Map<String, OptionBox> getOptSet()
950 public void setOptSet(Map<String, OptionBox> optSet)
952 this.optSet = optSet;
955 public Map<String, ParamBox> getParamSet()
960 public void setParamSet(Map<String, ParamBox> paramSet)
962 this.paramSet = paramSet;
965 OptionBox addOption(OptionI opt)
967 OptionBox cb = optSet.get(opt.getName());
970 cb = new OptionBox(opt);
971 optSet.put(opt.getName(), cb);
972 // jobOptions.add(cb, FlowLayout.LEFT);
977 ParamBox addParameter(ParameterI arg)
979 ParamBox pb = paramSet.get(arg.getName());
982 pb = new ParamBox(poparent, arg);
983 paramSet.put(arg.getName(), pb);
984 // paramList.add(pb);
987 // take the defaults from the parameter
988 pb.updateControls(arg);
992 void selectOption(OptionI option, String string)
994 OptionBox cb = optSet.get(option.getName());
997 cb = addOption(option);
999 cb.enabled.setSelected(string != null); // initial state for an option.
1002 if (option.getPossibleValues().contains(string))
1004 cb.val.setSelectedItem(string);
1008 throw new Error(String.format("Invalid value '%s' for option '%s'",
1009 string, option.getName()));
1012 if (option.isRequired() && !cb.enabled.isSelected())
1014 // TODO: indicate paramset is not valid.. option needs to be selected!
1016 cb.setInitialValue();
1019 void setParameter(ParameterI arg)
1021 ParamBox pb = paramSet.get(arg.getName());
1028 pb.updateControls(arg);
1034 * Answers a list of arguments representing all the options and arguments
1035 * selected on the dialog, holding their chosen or input values. Optional
1036 * parameters which were not selected are not included.
1040 public List<ArgumentI> getCurrentSettings()
1042 List<ArgumentI> argSet = new ArrayList<>();
1043 for (OptionBox opts : getOptSet().values())
1045 ArgumentI opt = opts.getSelectedOption();
1051 for (ParamBox parambox : getParamSet().values())
1053 ArgumentI parm = parambox.getParameter();
1064 * A helper method that constructs and returns a CombBox for choice of the
1065 * possible option values. If display names are provided, then these are added
1066 * as options, otherwise the actual values are added.
1071 protected JComboBox<String> buildComboBox(OptionI opt)
1073 JComboBox<String> cb = null;
1074 List<String> displayNames = opt.getDisplayNames();
1075 if (displayNames != null)
1077 cb = JvSwingUtils.buildComboWithTooltips(displayNames,
1078 opt.getPossibleValues());
1082 cb = new JComboBox<>();
1083 for (String v : opt.getPossibleValues())
1092 * Answers the value corresponding to the selected item in the choice combo
1093 * box. If display names were not provided, this is simply the selected
1094 * value. If display names were provided, it is the value corresponding to
1095 * the selected item index.
1099 protected static String getSelectedValue(OptionI opt, int sel)
1101 List<String> possibleValues = opt.getPossibleValues();
1102 String value = null;
1103 if (possibleValues != null && possibleValues.size() == 1)
1105 // Hack to make sure the default value for an enabled option with only
1106 // one value is actually returned even if this.val is not displayed
1107 value = possibleValues.get(0);
1111 if (sel >= 0 && sel < possibleValues.size())
1113 value = possibleValues.get(sel);
1117 value = opt.getValue();