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.params.ArgumentI;
25 import jalview.ws.params.OptionI;
26 import jalview.ws.params.ParameterI;
27 import jalview.ws.params.ValueConstrainI;
28 import jalview.ws.params.ValueConstrainI.ValueType;
29 import jalview.ws.params.simple.LogarithmicParameter;
30 import jalview.ws.params.simple.StringParameter;
32 import java.awt.BorderLayout;
33 import java.awt.Color;
34 import java.awt.Component;
35 import java.awt.Dimension;
36 import java.awt.FlowLayout;
38 import java.awt.Rectangle;
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.MouseEvent;
44 import java.awt.event.MouseListener;
46 import java.util.ArrayList;
47 import java.util.LinkedHashMap;
48 import java.util.List;
51 import javax.swing.JButton;
52 import javax.swing.JCheckBox;
53 import javax.swing.JComboBox;
54 import javax.swing.JComponent;
55 import javax.swing.JLabel;
56 import javax.swing.JMenuItem;
57 import javax.swing.JPanel;
58 import javax.swing.JPopupMenu;
59 import javax.swing.JScrollPane;
60 import javax.swing.JSlider;
61 import javax.swing.JTextArea;
62 import javax.swing.JTextField;
63 import javax.swing.border.TitledBorder;
64 import javax.swing.event.ChangeEvent;
65 import javax.swing.event.ChangeListener;
67 import net.miginfocom.swing.MigLayout;
70 * GUI generator/manager for options and parameters. Originally abstracted from
71 * the WsJobParameters dialog box.
76 public class OptsAndParamsPage
78 public static final int PARAM_WIDTH = 340;
80 public static final int PARAM_HEIGHT = 150;
82 public static final int PARAM_CLOSEDHEIGHT = 80;
84 URL linkImageURL = getClass().getResource("/images/link.gif");
86 Map<String, OptionBox> optSet = new LinkedHashMap<>();
88 Map<String, ParamBox> paramSet = new LinkedHashMap<>();
91 * compact or verbose style parameters
93 boolean compact = false;
95 OptsParametersContainerI poparent;
98 * A class that models a panel rendering a single option (checkbox or choice
101 public class OptionBox extends JPanel
102 implements MouseListener, ActionListener
108 boolean hasLink = false;
110 boolean initEnabled = false;
112 String initVal = null;
116 JComboBox<String> val;
118 public OptionBox(OptionI opt)
121 setLayout(new FlowLayout(FlowLayout.LEFT));
122 enabled = new JCheckBox();
123 enabled.setSelected(opt.isRequired()); // TODO: lock required options
124 enabled.setFont(new Font("Verdana", Font.PLAIN, 11));
126 enabled.setText(opt.getName());
127 enabled.addActionListener(this);
128 finfo = option.getFurtherDetails();
129 String desc = opt.getDescription();
134 enabled.setToolTipText(JvSwingUtils.wrapTooltip(true,
135 ((desc == null || desc.trim().length() == 0)
136 ? MessageManager.getString(
137 "label.opt_and_params_further_details")
138 : desc) + "<br><img src=\"" + linkImageURL
140 enabled.addMouseListener(this);
144 if (desc != null && desc.trim().length() > 0)
146 enabled.setToolTipText(
147 JvSwingUtils.wrapTooltip(true, opt.getDescription()));
152 // todo combo or radio buttons?
153 val = new JComboBox<>();
154 for (String str : opt.getPossibleValues())
158 val.setSelectedItem(opt.getValue());
159 if (opt.getPossibleValues().size() > 1 || opt.isRequired())
161 val.addActionListener(this);
164 // TODO: add actionListeners for popup (to open further info),
165 // and to update list of parameters if an option is enabled
166 // that takes a value. JBPNote: is this TODO still valid ?
171 public void actionPerformed(ActionEvent e)
173 if (e.getSource() != enabled)
175 enabled.setSelected(true);
180 private void checkIfModified()
182 boolean notmod = (initEnabled == enabled.isSelected());
183 if (enabled.isSelected())
187 notmod &= initVal.equals(val.getSelectedItem());
191 // compare against default service setting
192 notmod &= option.getValue() == null
193 || option.getValue().equals(val.getSelectedItem());
198 notmod &= (initVal != null) ? initVal.equals(val.getSelectedItem())
199 : val.getSelectedItem() != initVal;
201 poparent.argSetModified(this, !notmod);
204 public OptionI getOptionIfEnabled()
206 if (!enabled.isSelected())
210 OptionI opt = option.copy();
211 if (opt.getPossibleValues() != null
212 && opt.getPossibleValues().size() == 1)
214 // Hack to make sure the default value for an enabled option with only
215 // one value is actually returned
216 opt.setValue(opt.getPossibleValues().get(0));
218 if (val.getSelectedItem() != null)
220 opt.setValue((String) val.getSelectedItem());
224 if (option.getValue() != null)
226 opt.setValue(option.getValue());
233 public void mouseClicked(MouseEvent e)
235 if (e.isPopupTrigger()) // for Windows
237 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
242 public void mouseEntered(MouseEvent e)
247 public void mouseExited(MouseEvent e)
252 public void mousePressed(MouseEvent e)
254 if (e.isPopupTrigger()) // Mac
256 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
261 public void mouseReleased(MouseEvent e)
265 public void resetToDefault(boolean setDefaultParams)
267 enabled.setSelected(false);
268 if (option.isRequired()
269 || (setDefaultParams && option.getValue() != null))
271 // Apply default value
272 selectOption(option, option.getValue());
276 public void setInitialValue()
278 initEnabled = enabled.isSelected();
279 if (option.getPossibleValues() != null
280 && option.getPossibleValues().size() > 1)
282 initVal = (String) val.getSelectedItem();
286 initVal = (initEnabled) ? (String) val.getSelectedItem() : null;
291 * toString representation for identification in the debugger only
294 public String toString()
296 return option == null ? super.toString() : option.toString();
302 * A class that models a panel rendering a single parameter
304 public class ParamBox extends JPanel
305 implements ChangeListener, ActionListener, MouseListener
308 * parameter values (or their logs) are multiplied by this
309 * scaling factor to ensure an integer range for the slider
311 private int sliderScaleFactor = 1;
313 boolean isLogarithmicParameter;
315 boolean isChoiceParameter;
317 boolean isIntegerParameter;
319 boolean isStringParameter;
323 JComboBox<String> choicebox;
325 JPanel controlsPanel = new JPanel();
327 boolean descriptionIsVisible = false;
329 JScrollPane descPanel = new JScrollPane();
335 ParameterI parameter;
337 final OptsParametersContainerI pmdialogbox;
339 JPanel settingPanel = new JPanel();
343 JTextArea descriptionText = new JTextArea();
345 ValueConstrainI validator;
347 JTextField valueField;
349 private String descTooltip;
351 public ParamBox(final OptsParametersContainerI paramContainer,
354 pmdialogbox = paramContainer;
355 finfo = parm.getFurtherDetails();
356 validator = parm.getValidValue();
359 isLogarithmicParameter = parm instanceof LogarithmicParameter;
361 if (validator != null)
363 ValueType type = validator.getType();
364 isIntegerParameter = type == ValueType.Integer;
365 isStringParameter = type == ValueType.String;
368 * ensure slider has an integer range corresponding to
369 * the min-max range of the parameter
371 if (validator.getMin() != null && validator.getMax() != null
372 // && !isIntegerParameter
373 && !isStringParameter)
375 double min = validator.getMin().doubleValue();
376 double max = validator.getMax().doubleValue();
377 if (isLogarithmicParameter)
382 sliderScaleFactor = (int) (1000000 / (max - min));
383 // todo scaleMin, scaleMax could also be final fields
387 List<String> possibleValues = parameter.getPossibleValues();
388 isChoiceParameter = possibleValues != null
389 && !possibleValues.isEmpty();
393 addCompactParameter(parm);
397 addExpandableParam(parm);
402 * Adds a 'compact' format parameter, with any help text shown as a tooltip
406 private void addCompactParameter(ParameterI parm)
408 setLayout(new MigLayout("", "[][grow]"));
409 String ttipText = null;
411 controlsPanel.setLayout(new BorderLayout());
413 if (parm.getDescription() != null
414 && parm.getDescription().trim().length() > 0)
416 ttipText = (JvSwingUtils.wrapTooltip(true,
417 parm.getDescription() + (finfo != null ? "<br><img src=\""
418 + linkImageURL + "\"/>"
419 + MessageManager.getString(
420 "label.opt_and_params_further_details")
424 JvSwingUtils.addtoLayout(this, ttipText, new JLabel(parm.getName()),
426 updateControls(parm);
431 * Adds an 'expanded' format parameter, with any help shown in a panel that
432 * may be shown or hidden
436 private void addExpandableParam(ParameterI parm)
438 setPreferredSize(new Dimension(PARAM_WIDTH, PARAM_CLOSEDHEIGHT));
439 setBorder(new TitledBorder(parm.getName()));
441 descriptionText.setFont(new Font("Verdana", Font.PLAIN, 11));
442 descriptionText.setBackground(getBackground());
444 descriptionText.setEditable(false);
445 descPanel.getViewport().setView(descriptionText);
447 descPanel.setVisible(false);
449 JPanel firstrow = new JPanel();
450 firstrow.setLayout(null);
451 controlsPanel.setLayout(new BorderLayout());
452 controlsPanel.setBounds(new Rectangle(39, 10, PARAM_WIDTH - 70,
453 PARAM_CLOSEDHEIGHT - 50));
454 firstrow.add(controlsPanel);
455 firstrow.setBounds(new Rectangle(10, 20, PARAM_WIDTH - 30,
456 PARAM_CLOSEDHEIGHT - 30));
458 if (parm.getDescription() != null
459 && parm.getDescription().trim().length() > 0)
461 addExpandableHelp(firstrow, parm);
464 validator = parm.getValidValue();
466 if (validator != null)
468 isIntegerParameter = validator.getType() == ValueType.Integer;
472 if (parameter.getPossibleValues() != null)
474 isChoiceParameter = true;
477 updateControls(parm);
478 descPanel.setBounds(new Rectangle(10, PARAM_CLOSEDHEIGHT,
479 PARAM_WIDTH - 20, PARAM_HEIGHT - PARAM_CLOSEDHEIGHT - 5));
485 * Adds a button which can be clicked to show or hide help text
490 protected void addExpandableHelp(JPanel container, ParameterI param)
492 JButton showDescBtn = new JButton("+");
493 showDescBtn.setFont(new Font("Verdana", Font.PLAIN, 8));
496 descTooltip = JvSwingUtils.wrapTooltip(true,
497 MessageManager.formatMessage(
498 "label.opt_and_params_show_brief_desc_image_link",
500 { linkImageURL.toExternalForm() }));
501 showDescBtn.addMouseListener(this);
505 descTooltip = JvSwingUtils.wrapTooltip(true, MessageManager
506 .getString("label.opt_and_params_show_brief_desc"));
508 showDescBtn.setToolTipText(descTooltip);
509 showDescBtn.addActionListener(new ActionListener()
512 public void actionPerformed(ActionEvent e)
514 descriptionIsVisible = !descriptionIsVisible;
515 showDescBtn.setText(descriptionIsVisible ? "-" : "+");
516 showDescBtn.setToolTipText(
517 descriptionIsVisible ? null : descTooltip);
518 descPanel.setVisible(descriptionIsVisible);
519 descPanel.getVerticalScrollBar().setValue(0);
520 ParamBox.this.setPreferredSize(new Dimension(PARAM_WIDTH,
521 (descriptionIsVisible) ? PARAM_HEIGHT
522 : PARAM_CLOSEDHEIGHT));
523 ParamBox.this.validate();
524 pmdialogbox.refreshParamLayout();
527 descriptionText.setWrapStyleWord(true);
528 descriptionText.setLineWrap(true);
529 descriptionText.setColumns(32);
530 descriptionText.setText(param.getDescription());
531 showDescBtn.setBounds(new Rectangle(10, 10, 16, 16));
532 container.add(showDescBtn);
536 public void actionPerformed(ActionEvent e)
542 if (!isChoiceParameter)
544 updateSliderFromValueField();
550 * Checks whether the value of this parameter has been changed and notifies
551 * the parent page accordingly
553 private void checkIfModified()
555 Object newValue = updateSliderFromValueField();
556 boolean modified = true;
557 if (newValue.getClass() == lastVal.getClass())
559 modified = !newValue.equals(lastVal);
561 pmdialogbox.argSetModified(this, modified);
565 public int getBaseline(int width, int height)
571 // http://stackoverflow.com/questions/2743177/top-alignment-for-flowlayout
572 // helpful hint of using the Java 1.6 alignBaseLine property of FlowLayout
574 public Component.BaselineResizeBehavior getBaselineResizeBehavior()
576 return Component.BaselineResizeBehavior.CONSTANT_ASCENT;
579 public ParameterI getParameter()
581 ParameterI prm = parameter.copy();
582 if (isChoiceParameter)
584 prm.setValue((String) choicebox.getSelectedItem());
588 prm.setValue(valueField.getText());
595 // reset the widget's initial value.
600 public void mouseClicked(MouseEvent e)
602 if (e.isPopupTrigger()) // for Windows
604 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
609 public void mouseEntered(MouseEvent e)
614 public void mouseExited(MouseEvent e)
619 public void mousePressed(MouseEvent e)
621 if (e.isPopupTrigger()) // for Mac
623 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
628 public void mouseReleased(MouseEvent e)
633 public void stateChanged(ChangeEvent e)
637 if (!isLogarithmicParameter)
640 * set (int or float formatted) text field value
642 valueField.setText(isIntegerParameter
643 ? String.valueOf(slider.getValue())
645 slider.getValue() / (float) sliderScaleFactor));
649 double value = Math.pow(Math.E,
650 slider.getValue() / (double) sliderScaleFactor);
651 valueField.setText(formatDouble(value));
658 * Answers the value formatted as a string to 3 decimal places - in
659 * scientific notation if the value is less than 0.001
664 String formatDouble(double value)
666 String format = value < 0.001 ? "%3.1E" : "%3.3f";
667 return String.format(format, value);
671 * Formats a number as integer or float (3dp) or scientific notation (1dp)
676 String formatNumber(Number n)
678 return n instanceof Integer ? String.valueOf(n.intValue())
679 : formatDouble(n.doubleValue());
682 void updateControls(ParameterI parm)
685 boolean init = (choicebox == null && valueField == null);
688 if (isChoiceParameter)
690 choicebox = new JComboBox<>();
691 choicebox.addActionListener(this);
692 controlsPanel.add(choicebox, BorderLayout.CENTER);
696 slider = new JSlider();
697 slider.addChangeListener(this);
698 int cols = parm instanceof StringParameter ? 20 : 0;
699 valueField = new JTextField(cols);
700 valueField.addActionListener(this);
701 valueField.addKeyListener(new KeyAdapter()
704 public void keyReleased(KeyEvent e)
706 int keyCode = e.getKeyCode();
707 if (e.isActionKey() && keyCode != KeyEvent.VK_LEFT
708 && keyCode != KeyEvent.VK_RIGHT)
710 if (valueField.getText().trim().length() > 0)
712 actionPerformed(null);
717 valueField.setPreferredSize(new Dimension(65, 25));
718 controlsPanel.add(slider, BorderLayout.WEST);
719 controlsPanel.add(valueField, BorderLayout.EAST);
725 if (isChoiceParameter)
729 for (String val : parm.getPossibleValues())
731 choicebox.addItem(val);
734 if (parm.getValue() != null)
736 choicebox.setSelectedItem(parm.getValue());
741 valueField.setText(parm.getValue());
744 lastVal = updateSliderFromValueField();
749 * Action depends on the type of the input parameter:
751 * <li>if a text input, returns the trimmed value</li>
752 * <li>if a choice list, returns the selected value</li>
753 * <li>if a value slider and input field, sets the value of the slider from
754 * the value in the text field, limiting it to any defined min-max
757 * Answers the (possibly modified) input value, as a String, Integer, Float
762 Object updateSliderFromValueField()
764 if (validator == null || isStringParameter)
766 if (isChoiceParameter)
768 return choicebox.getSelectedItem();
770 slider.setVisible(false);
771 return valueField.getText().trim();
774 valueField.setText(valueField.getText().trim());
777 * ensure not outside min-max range
778 * TODO: provide some visual indicator if limit reached
782 valueField.setBackground(Color.WHITE);
783 double d = Double.parseDouble(valueField.getText());
784 if (validator.getMin() != null
785 && validator.getMin().doubleValue() > d)
787 valueField.setText(formatNumber(validator.getMin()));
789 if (validator.getMax() != null
790 && validator.getMax().doubleValue() < d)
792 valueField.setText(formatNumber(validator.getMax()));
794 } catch (NumberFormatException e)
796 valueField.setBackground(Color.yellow);
800 if (isIntegerParameter)
805 iVal = Integer.valueOf(valueField.getText());
806 } catch (Exception e)
808 valueField.setBackground(Color.yellow);
809 return Integer.valueOf(0);
812 if (validator.getMin() != null && validator.getMax() != null)
814 slider.getModel().setRangeProperties(iVal, 1,
815 validator.getMin().intValue(),
816 validator.getMax().intValue() + 1, true);
820 slider.setVisible(false);
822 return new Integer(iVal);
825 if (isLogarithmicParameter)
830 double eValue = Double.valueOf(valueField.getText());
831 dVal = Math.log(eValue) * sliderScaleFactor;
832 } catch (Exception e)
834 // shouldn't be possible here
835 valueField.setBackground(Color.yellow);
838 if (validator.getMin() != null && validator.getMax() != null)
840 double scaleMin = Math.log(validator.getMin().doubleValue())
842 double scaleMax = Math.log(validator.getMax().doubleValue())
844 slider.getModel().setRangeProperties((int) (dVal), 1,
845 (int) scaleMin, 1 + (int) scaleMax, true);
849 slider.setVisible(false);
851 return new Double(dVal);
857 fVal = Float.valueOf(valueField.getText());
858 } catch (Exception e)
860 return Float.valueOf(0f); // shouldn't happen
862 if (validator.getMin() != null && validator.getMax() != null)
864 float scaleMin = validator.getMin().floatValue()
866 float scaleMax = validator.getMax().floatValue()
868 slider.getModel().setRangeProperties(
869 (int) (fVal * sliderScaleFactor), 1, (int) scaleMin,
870 1 + (int) scaleMax, true);
874 slider.setVisible(false);
876 return new Float(fVal);
881 * Constructor with the option to show 'compact' format (parameter description
882 * as tooltip) or 'expanded' format (parameter description in a textbox which
883 * may be opened or closed). Use compact for simple description text, expanded
884 * for more wordy or formatted text.
886 * @param paramContainer
888 public OptsAndParamsPage(OptsParametersContainerI paramContainer,
891 poparent = paramContainer;
892 this.compact = compact;
895 public static void showUrlPopUp(JComponent invoker, final String finfo,
899 JPopupMenu mnu = new JPopupMenu();
900 JMenuItem mitem = new JMenuItem(
901 MessageManager.formatMessage("label.view_params", new String[]
903 mitem.addActionListener(new ActionListener()
907 public void actionPerformed(ActionEvent e)
909 Desktop.showUrl(finfo);
914 mnu.show(invoker, x, y);
917 public Map<String, OptionBox> getOptSet()
922 public void setOptSet(Map<String, OptionBox> optSet)
924 this.optSet = optSet;
927 public Map<String, ParamBox> getParamSet()
932 public void setParamSet(Map<String, ParamBox> paramSet)
934 this.paramSet = paramSet;
937 OptionBox addOption(OptionI opt)
939 OptionBox cb = optSet.get(opt.getName());
942 cb = new OptionBox(opt);
943 optSet.put(opt.getName(), cb);
944 // jobOptions.add(cb, FlowLayout.LEFT);
949 ParamBox addParameter(ParameterI arg)
951 ParamBox pb = paramSet.get(arg.getName());
954 pb = new ParamBox(poparent, arg);
955 paramSet.put(arg.getName(), pb);
956 // paramList.add(pb);
959 // take the defaults from the parameter
960 pb.updateControls(arg);
964 void selectOption(OptionI option, String string)
966 OptionBox cb = optSet.get(option.getName());
969 cb = addOption(option);
971 cb.enabled.setSelected(string != null); // initial state for an option.
974 if (option.getPossibleValues().contains(string))
976 cb.val.setSelectedItem(string);
980 throw new Error(String.format("Invalid value '%s' for option '%s'",
981 string, option.getName()));
984 if (option.isRequired() && !cb.enabled.isSelected())
986 // TODO: indicate paramset is not valid.. option needs to be selected!
988 cb.setInitialValue();
991 void setParameter(ParameterI arg)
993 ParamBox pb = paramSet.get(arg.getName());
1000 pb.updateControls(arg);
1006 * recover options and parameters from GUI
1010 public List<ArgumentI> getCurrentSettings()
1012 List<ArgumentI> argSet = new ArrayList<>();
1013 for (OptionBox opts : getOptSet().values())
1015 OptionI opt = opts.getOptionIfEnabled();
1021 for (ParamBox parambox : getParamSet().values())
1023 ParameterI parm = parambox.getParameter();