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
104 JCheckBox enabled = new JCheckBox();
108 boolean hasLink = false;
110 boolean initEnabled = false;
112 String initVal = null;
116 JLabel optlabel = new JLabel();
118 JComboBox<String> val = new JComboBox<>();
120 public OptionBox(OptionI opt)
123 setLayout(new FlowLayout(FlowLayout.LEFT));
124 enabled.setSelected(opt.isRequired()); // TODO: lock required options
125 enabled.setFont(new Font("Verdana", Font.PLAIN, 11));
127 enabled.setText(opt.getName());
128 enabled.addActionListener(this);
129 finfo = option.getFurtherDetails();
130 String desc = opt.getDescription();
135 enabled.setToolTipText(JvSwingUtils.wrapTooltip(true,
136 ((desc == null || desc.trim().length() == 0)
137 ? MessageManager.getString(
138 "label.opt_and_params_further_details")
139 : desc) + "<br><img src=\"" + linkImageURL
141 enabled.addMouseListener(this);
145 if (desc != null && desc.trim().length() > 0)
147 enabled.setToolTipText(
148 JvSwingUtils.wrapTooltip(true, opt.getDescription()));
152 for (String str : opt.getPossibleValues())
156 val.setSelectedItem(opt.getValue());
157 if (opt.getPossibleValues().size() > 1 || opt.isRequired())
159 val.addActionListener(this);
162 // TODO: add actionListeners for popup (to open further info),
163 // and to update list of parameters if an option is enabled
164 // that takes a value. JBPNote: is this TODO still valid ?
169 public void actionPerformed(ActionEvent e)
171 if (e.getSource() != enabled)
173 enabled.setSelected(true);
178 private void checkIfModified()
180 boolean notmod = (initEnabled == enabled.isSelected());
181 if (enabled.isSelected())
185 notmod &= initVal.equals(val.getSelectedItem());
189 // compare against default service setting
190 notmod &= option.getValue() == null
191 || option.getValue().equals(val.getSelectedItem());
196 notmod &= (initVal != null) ? initVal.equals(val.getSelectedItem())
197 : val.getSelectedItem() != initVal;
199 poparent.argSetModified(this, !notmod);
202 public OptionI getOptionIfEnabled()
204 if (!enabled.isSelected())
208 OptionI opt = option.copy();
209 if (opt.getPossibleValues() != null
210 && opt.getPossibleValues().size() == 1)
212 // Hack to make sure the default value for an enabled option with only
213 // one value is actually returned
214 opt.setValue(opt.getPossibleValues().get(0));
216 if (val.getSelectedItem() != null)
218 opt.setValue((String) val.getSelectedItem());
222 if (option.getValue() != null)
224 opt.setValue(option.getValue());
231 public void mouseClicked(MouseEvent e)
233 if (e.isPopupTrigger()) // for Windows
235 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
240 public void mouseEntered(MouseEvent e)
245 public void mouseExited(MouseEvent e)
250 public void mousePressed(MouseEvent e)
252 if (e.isPopupTrigger()) // Mac
254 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
259 public void mouseReleased(MouseEvent e)
263 public void resetToDefault(boolean setDefaultParams)
265 enabled.setSelected(false);
266 if (option.isRequired()
267 || (setDefaultParams && option.getValue() != null))
269 // Apply default value
270 selectOption(option, option.getValue());
274 public void setInitialValue()
276 initEnabled = enabled.isSelected();
277 if (option.getPossibleValues() != null
278 && option.getPossibleValues().size() > 1)
280 initVal = (String) val.getSelectedItem();
284 initVal = (initEnabled) ? (String) val.getSelectedItem() : null;
289 * toString representation for identification in the debugger only
292 public String toString()
294 return option == null ? super.toString() : option.toString();
300 * A class that models a panel rendering a single parameter
302 public class ParamBox extends JPanel
303 implements ChangeListener, ActionListener, MouseListener
306 * parameter values (or their logs) are multiplied by this
307 * scaling factor to ensure an integer range for the slider
309 private int sliderScaleFactor = 1;
311 boolean isLogarithmicParameter;
313 boolean isChoiceParameter;
315 boolean isIntegerParameter;
317 boolean isStringParameter;
321 JComboBox<String> choicebox;
323 JPanel controlsPanel = new JPanel();
325 boolean descriptionIsVisible = false;
327 JScrollPane descPanel = new JScrollPane();
333 ParameterI parameter;
335 final OptsParametersContainerI pmdialogbox;
337 JPanel settingPanel = new JPanel();
341 JTextArea descriptionText = new JTextArea();
343 ValueConstrainI validator;
345 JTextField valueField;
347 private String descTooltip;
349 public ParamBox(final OptsParametersContainerI paramContainer,
352 pmdialogbox = paramContainer;
353 finfo = parm.getFurtherDetails();
354 validator = parm.getValidValue();
357 isLogarithmicParameter = parm instanceof LogarithmicParameter;
359 if (validator != null)
361 ValueType type = validator.getType();
362 isIntegerParameter = type == ValueType.Integer;
363 isStringParameter = type == ValueType.String;
366 * ensure slider has an integer range corresponding to
367 * the min-max range of the parameter
369 if (validator.getMin() != null && !isIntegerParameter
370 && !isStringParameter)
372 double min = validator.getMin().doubleValue();
373 double max = validator.getMax().doubleValue();
374 if (isLogarithmicParameter)
379 sliderScaleFactor = (int) (1000000 / (max - min));
380 // todo scaleMin, scaleMax could also be final fields
385 isChoiceParameter = parameter.getPossibleValues() != null;
390 addCompactParameter(parm);
394 addExpandableParam(parm);
399 * Adds a 'compact' format parameter, with any help text shown as a tooltip
403 private void addCompactParameter(ParameterI parm)
405 setLayout(new MigLayout("", "[][grow]"));
406 String ttipText = null;
408 controlsPanel.setLayout(new BorderLayout());
410 if (parm.getDescription() != null
411 && parm.getDescription().trim().length() > 0)
413 ttipText = (JvSwingUtils.wrapTooltip(true,
414 parm.getDescription() + (finfo != null ? "<br><img src=\""
415 + linkImageURL + "\"/>"
416 + MessageManager.getString(
417 "label.opt_and_params_further_details")
421 JvSwingUtils.addtoLayout(this, ttipText, new JLabel(parm.getName()),
423 updateControls(parm);
428 * Adds an 'expanded' format parameter, with any help shown in a panel that
429 * may be shown or hidden
433 private void addExpandableParam(ParameterI parm)
435 setPreferredSize(new Dimension(PARAM_WIDTH, PARAM_CLOSEDHEIGHT));
436 setBorder(new TitledBorder(parm.getName()));
438 descriptionText.setFont(new Font("Verdana", Font.PLAIN, 11));
439 descriptionText.setBackground(getBackground());
441 descriptionText.setEditable(false);
442 descPanel.getViewport().setView(descriptionText);
444 descPanel.setVisible(false);
446 JPanel firstrow = new JPanel();
447 firstrow.setLayout(null);
448 controlsPanel.setLayout(new BorderLayout());
449 controlsPanel.setBounds(new Rectangle(39, 10, PARAM_WIDTH - 70,
450 PARAM_CLOSEDHEIGHT - 50));
451 firstrow.add(controlsPanel);
452 firstrow.setBounds(new Rectangle(10, 20, PARAM_WIDTH - 30,
453 PARAM_CLOSEDHEIGHT - 30));
455 if (parm.getDescription() != null
456 && parm.getDescription().trim().length() > 0)
458 addExpandableHelp(firstrow, parm);
461 validator = parm.getValidValue();
463 if (validator != null)
465 isIntegerParameter = validator.getType() == ValueType.Integer;
469 if (parameter.getPossibleValues() != null)
471 isChoiceParameter = true;
474 updateControls(parm);
475 descPanel.setBounds(new Rectangle(10, PARAM_CLOSEDHEIGHT,
476 PARAM_WIDTH - 20, PARAM_HEIGHT - PARAM_CLOSEDHEIGHT - 5));
482 * Adds a button which can be clicked to show or hide help text
487 protected void addExpandableHelp(JPanel container, ParameterI param)
489 JButton showDescBtn = new JButton("+");
490 showDescBtn.setFont(new Font("Verdana", Font.PLAIN, 8));
493 descTooltip = JvSwingUtils.wrapTooltip(true,
494 MessageManager.formatMessage(
495 "label.opt_and_params_show_brief_desc_image_link",
497 { linkImageURL.toExternalForm() }));
498 showDescBtn.addMouseListener(this);
502 descTooltip = JvSwingUtils.wrapTooltip(true, MessageManager
503 .getString("label.opt_and_params_show_brief_desc"));
505 showDescBtn.setToolTipText(descTooltip);
506 showDescBtn.addActionListener(new ActionListener()
509 public void actionPerformed(ActionEvent e)
511 descriptionIsVisible = !descriptionIsVisible;
512 showDescBtn.setText(descriptionIsVisible ? "-" : "+");
513 showDescBtn.setToolTipText(
514 descriptionIsVisible ? null : descTooltip);
515 descPanel.setVisible(descriptionIsVisible);
516 descPanel.getVerticalScrollBar().setValue(0);
517 ParamBox.this.setPreferredSize(new Dimension(PARAM_WIDTH,
518 (descriptionIsVisible) ? PARAM_HEIGHT
519 : PARAM_CLOSEDHEIGHT));
520 ParamBox.this.validate();
521 pmdialogbox.refreshParamLayout();
524 descriptionText.setWrapStyleWord(true);
525 descriptionText.setLineWrap(true);
526 descriptionText.setColumns(32);
527 descriptionText.setText(param.getDescription());
528 showDescBtn.setBounds(new Rectangle(10, 10, 16, 16));
529 container.add(showDescBtn);
533 public void actionPerformed(ActionEvent e)
539 if (!isChoiceParameter)
541 updateSliderFromValueField();
547 * Checks whether the value of this parameter has been changed and notifies
548 * the parent page accordingly
550 private void checkIfModified()
552 Object newValue = updateSliderFromValueField();
553 boolean modified = true;
554 if (newValue.getClass() == lastVal.getClass())
556 modified = !newValue.equals(lastVal);
558 pmdialogbox.argSetModified(this, modified);
562 public int getBaseline(int width, int height)
568 // http://stackoverflow.com/questions/2743177/top-alignment-for-flowlayout
569 // helpful hint of using the Java 1.6 alignBaseLine property of FlowLayout
571 public Component.BaselineResizeBehavior getBaselineResizeBehavior()
573 return Component.BaselineResizeBehavior.CONSTANT_ASCENT;
576 public ParameterI getParameter()
578 ParameterI prm = parameter.copy();
579 if (isChoiceParameter)
581 prm.setValue((String) choicebox.getSelectedItem());
585 prm.setValue(valueField.getText());
592 // reset the widget's initial value.
597 public void mouseClicked(MouseEvent e)
599 if (e.isPopupTrigger()) // for Windows
601 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
606 public void mouseEntered(MouseEvent e)
611 public void mouseExited(MouseEvent e)
616 public void mousePressed(MouseEvent e)
618 if (e.isPopupTrigger()) // for Mac
620 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
625 public void mouseReleased(MouseEvent e)
630 public void stateChanged(ChangeEvent e)
634 if (!isLogarithmicParameter)
637 * set (int or float formatted) text field value
639 valueField.setText(isIntegerParameter
640 ? String.valueOf(slider.getValue())
642 slider.getValue() / (float) sliderScaleFactor));
646 double value = Math.pow(Math.E,
647 slider.getValue() / (double) sliderScaleFactor);
648 valueField.setText(formatDouble(value));
655 * Answers the value formatted as a string to 3 decimal places - in
656 * scientific notation if the value is less than 0.001
661 String formatDouble(double value)
663 String format = value < 0.001 ? "%3.1E" : "%3.3f";
664 return String.format(format, value);
668 * Formats a number as integer or float (3dp) or scientific notation (1dp)
673 String formatNumber(Number n)
675 return n instanceof Integer ? String.valueOf(n.intValue())
676 : formatDouble(n.doubleValue());
679 void updateControls(ParameterI parm)
682 boolean init = (choicebox == null && valueField == null);
685 if (isChoiceParameter)
687 choicebox = new JComboBox<>();
688 choicebox.addActionListener(this);
689 controlsPanel.add(choicebox, BorderLayout.CENTER);
693 slider = new JSlider();
694 slider.addChangeListener(this);
695 int cols = parm instanceof StringParameter ? 20 : 0;
696 valueField = new JTextField(cols);
697 valueField.addActionListener(this);
698 valueField.addKeyListener(new KeyAdapter()
701 public void keyReleased(KeyEvent e)
703 int keyCode = e.getKeyCode();
704 if (e.isActionKey() && keyCode != KeyEvent.VK_LEFT
705 && keyCode != KeyEvent.VK_RIGHT)
707 if (valueField.getText().trim().length() > 0)
709 actionPerformed(null);
714 valueField.setPreferredSize(new Dimension(65, 25));
715 controlsPanel.add(slider, BorderLayout.WEST);
716 controlsPanel.add(valueField, BorderLayout.EAST);
722 if (isChoiceParameter)
726 for (String val : parm.getPossibleValues())
728 choicebox.addItem(val);
731 if (parm.getValue() != null)
733 choicebox.setSelectedItem(parm.getValue());
738 valueField.setText(parm.getValue());
741 lastVal = updateSliderFromValueField();
746 * Action depends on the type of the input parameter:
748 * <li>if a text input, returns the trimmed value</li>
749 * <li>if a choice list, returns the selected value</li>
750 * <li>if a value slider and input field, sets the value of the slider from
751 * the value in the text field, limiting it to any defined min-max
754 * Answers the (possibly modified) input value, as a String, Integer, Float
759 Object updateSliderFromValueField()
761 if (validator == null || isStringParameter)
763 if (isChoiceParameter)
765 return choicebox.getSelectedItem();
767 slider.setVisible(false);
768 return valueField.getText().trim();
771 valueField.setText(valueField.getText().trim());
774 * ensure not outside min-max range
775 * TODO: provide some visual indicator if limit reached
779 valueField.setBackground(Color.WHITE);
780 double d = Double.parseDouble(valueField.getText());
781 if (validator.getMin() != null
782 && validator.getMin().doubleValue() > d)
784 valueField.setText(formatNumber(validator.getMin()));
786 if (validator.getMax() != null
787 && validator.getMax().doubleValue() < d)
789 valueField.setText(formatNumber(validator.getMax()));
791 } catch (NumberFormatException e)
793 valueField.setBackground(Color.yellow);
797 if (isIntegerParameter)
802 iVal = Integer.valueOf(valueField.getText());
803 } catch (Exception e)
805 valueField.setBackground(Color.yellow);
806 return Integer.valueOf(0);
809 if (validator.getMin() != null && validator.getMax() != null)
811 slider.getModel().setRangeProperties(iVal, 1,
812 validator.getMin().intValue(),
813 validator.getMax().intValue() + 1, true);
817 slider.setVisible(false);
819 return new Integer(iVal);
822 if (isLogarithmicParameter)
827 double eValue = Double.valueOf(valueField.getText());
828 dVal = Math.log(eValue) * sliderScaleFactor;
829 } catch (Exception e)
831 // shouldn't be possible here
832 valueField.setBackground(Color.yellow);
835 if (validator.getMin() != null && validator.getMax() != null)
837 double scaleMin = Math.log(validator.getMin().doubleValue())
839 double scaleMax = Math.log(validator.getMax().doubleValue())
841 slider.getModel().setRangeProperties((int) (dVal), 1,
842 (int) scaleMin, 1 + (int) scaleMax, true);
846 slider.setVisible(false);
848 return new Double(dVal);
854 fVal = Float.valueOf(valueField.getText());
855 } catch (Exception e)
857 return Float.valueOf(0f); // shouldn't happen
859 if (validator.getMin() != null && validator.getMax() != null)
861 float scaleMin = validator.getMin().floatValue()
863 float scaleMax = validator.getMax().floatValue()
865 slider.getModel().setRangeProperties(
866 (int) (fVal * sliderScaleFactor), 1, (int) scaleMin,
867 1 + (int) scaleMax, true);
871 slider.setVisible(false);
873 return new Float(fVal);
878 * Constructor with the option to show 'compact' format (parameter description
879 * as tooltip) or 'expanded' format (parameter description in a textbox which
880 * may be opened or closed). Use compact for simple description text, expanded
881 * for more wordy or formatted text.
883 * @param paramContainer
885 public OptsAndParamsPage(OptsParametersContainerI paramContainer,
888 poparent = paramContainer;
889 this.compact = compact;
892 public static void showUrlPopUp(JComponent invoker, final String finfo,
896 JPopupMenu mnu = new JPopupMenu();
897 JMenuItem mitem = new JMenuItem(
898 MessageManager.formatMessage("label.view_params", new String[]
900 mitem.addActionListener(new ActionListener()
904 public void actionPerformed(ActionEvent e)
906 Desktop.showUrl(finfo);
911 mnu.show(invoker, x, y);
914 public Map<String, OptionBox> getOptSet()
919 public void setOptSet(Map<String, OptionBox> optSet)
921 this.optSet = optSet;
924 public Map<String, ParamBox> getParamSet()
929 public void setParamSet(Map<String, ParamBox> paramSet)
931 this.paramSet = paramSet;
934 OptionBox addOption(OptionI opt)
936 OptionBox cb = optSet.get(opt.getName());
939 cb = new OptionBox(opt);
940 optSet.put(opt.getName(), cb);
941 // jobOptions.add(cb, FlowLayout.LEFT);
946 ParamBox addParameter(ParameterI arg)
948 ParamBox pb = paramSet.get(arg.getName());
951 pb = new ParamBox(poparent, arg);
952 paramSet.put(arg.getName(), pb);
953 // paramList.add(pb);
956 // take the defaults from the parameter
957 pb.updateControls(arg);
961 void selectOption(OptionI option, String string)
963 OptionBox cb = optSet.get(option.getName());
966 cb = addOption(option);
968 cb.enabled.setSelected(string != null); // initial state for an option.
971 if (option.getPossibleValues().contains(string))
973 cb.val.setSelectedItem(string);
977 throw new Error(String.format("Invalid value '%s' for option '%s'",
978 string, option.getName()));
981 if (option.isRequired() && !cb.enabled.isSelected())
983 // TODO: indicate paramset is not valid.. option needs to be selected!
985 cb.setInitialValue();
988 void setParameter(ParameterI arg)
990 ParamBox pb = paramSet.get(arg.getName());
997 pb.updateControls(arg);
1003 * recover options and parameters from GUI
1007 public List<ArgumentI> getCurrentSettings()
1009 List<ArgumentI> argSet = new ArrayList<>();
1010 for (OptionBox opts : getOptSet().values())
1012 OptionI opt = opts.getOptionIfEnabled();
1018 for (ParamBox parambox : getParamSet().values())
1020 ParameterI parm = parambox.getParameter();