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);
147 val = new JComboBox<>();
148 for (String str : opt.getPossibleValues())
152 val.setSelectedItem(opt.getValue());
153 if (opt.getPossibleValues().size() > 1 || opt.isRequired())
155 val.addActionListener(this);
163 * Configures the checkbox that controls whether or not the option is
168 protected void configureCheckbox(OptionI opt)
170 enabled.setFont(new Font("Verdana", Font.PLAIN, 11));
171 enabled.addActionListener(this);
172 final String desc = opt.getDescription();
176 String description = desc;
177 if (desc == null || desc.trim().isEmpty())
179 description = MessageManager
180 .getString("label.opt_and_params_further_details");
182 description = description + "<br><img src=\"" + linkImageURL
184 String text = JvSwingUtils.wrapTooltip(true, description);
185 enabled.setToolTipText(text);
186 enabled.addMouseListener(this); // for popup menu to show link
190 if (desc != null && desc.trim().length() > 0)
192 enabled.setToolTipText(JvSwingUtils.wrapTooltip(true, desc));
198 public void actionPerformed(ActionEvent e)
200 if (e.getSource() != enabled)
202 enabled.setSelected(true);
207 private void checkIfModified()
209 boolean notmod = (initEnabled == enabled.isSelected());
210 if (enabled.isSelected())
214 notmod &= initVal.equals(val.getSelectedItem());
218 // compare against default service setting
219 notmod &= option.getValue() == null
220 || option.getValue().equals(val.getSelectedItem());
225 notmod &= (initVal != null) ? initVal.equals(val.getSelectedItem())
226 : val.getSelectedItem() != initVal;
228 poparent.argSetModified(this, !notmod);
231 public OptionI getOptionIfEnabled()
233 if (!enabled.isSelected())
237 OptionI opt = option.copy();
238 if (opt.getPossibleValues() != null
239 && opt.getPossibleValues().size() == 1)
241 // Hack to make sure the default value for an enabled option with only
242 // one value is actually returned
243 opt.setValue(opt.getPossibleValues().get(0));
245 if (val.getSelectedItem() != null)
247 opt.setValue((String) val.getSelectedItem());
251 if (option.getValue() != null)
253 opt.setValue(option.getValue());
260 public void mouseClicked(MouseEvent e)
262 if (e.isPopupTrigger()) // for Windows
264 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
269 public void mouseEntered(MouseEvent e)
274 public void mouseExited(MouseEvent e)
279 public void mousePressed(MouseEvent e)
281 if (e.isPopupTrigger()) // Mac
283 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
288 public void mouseReleased(MouseEvent e)
292 public void resetToDefault(boolean setDefaultParams)
294 enabled.setSelected(false);
295 if (option.isRequired()
296 || (setDefaultParams && option.getValue() != null))
298 // Apply default value
299 selectOption(option, option.getValue());
303 public void setInitialValue()
305 initEnabled = enabled.isSelected();
306 if (option.getPossibleValues() != null
307 && option.getPossibleValues().size() > 1)
309 initVal = (String) val.getSelectedItem();
313 initVal = (initEnabled) ? (String) val.getSelectedItem() : null;
318 * toString representation for identification in the debugger only
321 public String toString()
323 return option == null ? super.toString() : option.toString();
329 * A class that models a panel rendering a single parameter
331 public class ParamBox extends JPanel
332 implements ChangeListener, ActionListener, MouseListener
335 * parameter values (or their logs) are multiplied by this
336 * scaling factor to ensure an integer range for the slider
338 private int sliderScaleFactor = 1;
340 boolean isLogarithmicParameter;
342 boolean isChoiceParameter;
344 boolean isIntegerParameter;
346 boolean isStringParameter;
350 JComboBox<String> choicebox;
352 JPanel controlsPanel = new JPanel();
354 boolean descriptionIsVisible = false;
356 JScrollPane descPanel = new JScrollPane();
362 ParameterI parameter;
364 final OptsParametersContainerI pmdialogbox;
366 JPanel settingPanel = new JPanel();
370 JTextArea descriptionText = new JTextArea();
372 ValueConstrainI validator;
374 JTextField valueField;
376 private String descTooltip;
378 public ParamBox(final OptsParametersContainerI paramContainer,
381 pmdialogbox = paramContainer;
382 finfo = parm.getFurtherDetails();
383 validator = parm.getValidValue();
386 isLogarithmicParameter = parm instanceof LogarithmicParameter;
388 if (validator != null)
390 ValueType type = validator.getType();
391 isIntegerParameter = type == ValueType.Integer;
392 isStringParameter = type == ValueType.String;
395 * ensure slider has an integer range corresponding to
396 * the min-max range of the parameter
398 if (validator.getMin() != null && validator.getMax() != null
399 // && !isIntegerParameter
400 && !isStringParameter)
402 double min = validator.getMin().doubleValue();
403 double max = validator.getMax().doubleValue();
404 if (isLogarithmicParameter)
409 sliderScaleFactor = (int) (1000000 / (max - min));
410 // todo scaleMin, scaleMax could also be final fields
414 List<String> possibleValues = parameter.getPossibleValues();
415 isChoiceParameter = possibleValues != null
416 && !possibleValues.isEmpty();
420 addCompactParameter(parm);
424 addExpandableParam(parm);
429 * Adds a 'compact' format parameter, with any help text shown as a tooltip
433 private void addCompactParameter(ParameterI parm)
435 setLayout(new MigLayout("", "[][grow]"));
436 String ttipText = null;
438 controlsPanel.setLayout(new BorderLayout());
440 if (parm.getDescription() != null
441 && parm.getDescription().trim().length() > 0)
443 ttipText = (JvSwingUtils.wrapTooltip(true,
444 parm.getDescription() + (finfo != null ? "<br><img src=\""
445 + linkImageURL + "\"/>"
446 + MessageManager.getString(
447 "label.opt_and_params_further_details")
451 JvSwingUtils.addtoLayout(this, ttipText, new JLabel(parm.getName()),
453 updateControls(parm);
458 * Adds an 'expanded' format parameter, with any help shown in a panel that
459 * may be shown or hidden
463 private void addExpandableParam(ParameterI parm)
465 setPreferredSize(new Dimension(PARAM_WIDTH, PARAM_CLOSEDHEIGHT));
466 setBorder(new TitledBorder(parm.getName()));
468 descriptionText.setFont(new Font("Verdana", Font.PLAIN, 11));
469 descriptionText.setBackground(getBackground());
471 descriptionText.setEditable(false);
472 descPanel.getViewport().setView(descriptionText);
474 descPanel.setVisible(false);
476 JPanel firstrow = new JPanel();
477 firstrow.setLayout(null);
478 controlsPanel.setLayout(new BorderLayout());
479 controlsPanel.setBounds(new Rectangle(39, 10, PARAM_WIDTH - 70,
480 PARAM_CLOSEDHEIGHT - 50));
481 firstrow.add(controlsPanel);
482 firstrow.setBounds(new Rectangle(10, 20, PARAM_WIDTH - 30,
483 PARAM_CLOSEDHEIGHT - 30));
485 if (parm.getDescription() != null
486 && parm.getDescription().trim().length() > 0)
488 addExpandableHelp(firstrow, parm);
491 validator = parm.getValidValue();
493 if (validator != null)
495 isIntegerParameter = validator.getType() == ValueType.Integer;
499 if (parameter.getPossibleValues() != null)
501 isChoiceParameter = true;
504 updateControls(parm);
505 descPanel.setBounds(new Rectangle(10, PARAM_CLOSEDHEIGHT,
506 PARAM_WIDTH - 20, PARAM_HEIGHT - PARAM_CLOSEDHEIGHT - 5));
512 * Adds a button which can be clicked to show or hide help text
517 protected void addExpandableHelp(JPanel container, ParameterI param)
519 JButton showDescBtn = new JButton("+");
520 showDescBtn.setFont(new Font("Verdana", Font.PLAIN, 8));
523 descTooltip = JvSwingUtils.wrapTooltip(true,
524 MessageManager.formatMessage(
525 "label.opt_and_params_show_brief_desc_image_link",
527 { linkImageURL.toExternalForm() }));
528 showDescBtn.addMouseListener(this);
532 descTooltip = JvSwingUtils.wrapTooltip(true, MessageManager
533 .getString("label.opt_and_params_show_brief_desc"));
535 showDescBtn.setToolTipText(descTooltip);
536 showDescBtn.addActionListener(new ActionListener()
539 public void actionPerformed(ActionEvent e)
541 descriptionIsVisible = !descriptionIsVisible;
542 showDescBtn.setText(descriptionIsVisible ? "-" : "+");
543 showDescBtn.setToolTipText(
544 descriptionIsVisible ? null : descTooltip);
545 descPanel.setVisible(descriptionIsVisible);
546 descPanel.getVerticalScrollBar().setValue(0);
547 ParamBox.this.setPreferredSize(new Dimension(PARAM_WIDTH,
548 (descriptionIsVisible) ? PARAM_HEIGHT
549 : PARAM_CLOSEDHEIGHT));
550 ParamBox.this.validate();
551 pmdialogbox.refreshParamLayout();
554 descriptionText.setWrapStyleWord(true);
555 descriptionText.setLineWrap(true);
556 descriptionText.setColumns(32);
557 descriptionText.setText(param.getDescription());
558 showDescBtn.setBounds(new Rectangle(10, 10, 16, 16));
559 container.add(showDescBtn);
563 public void actionPerformed(ActionEvent e)
569 if (!isChoiceParameter)
571 updateSliderFromValueField();
577 * Checks whether the value of this parameter has been changed and notifies
578 * the parent page accordingly
580 private void checkIfModified()
587 Object newValue = updateSliderFromValueField();
588 boolean modified = true;
589 if (newValue.getClass() == lastVal.getClass())
591 modified = !newValue.equals(lastVal);
593 pmdialogbox.argSetModified(this, modified);
602 public int getBaseline(int width, int height)
608 // http://stackoverflow.com/questions/2743177/top-alignment-for-flowlayout
609 // helpful hint of using the Java 1.6 alignBaseLine property of FlowLayout
611 public Component.BaselineResizeBehavior getBaselineResizeBehavior()
613 return Component.BaselineResizeBehavior.CONSTANT_ASCENT;
616 public ParameterI getParameter()
618 ParameterI prm = parameter.copy();
619 if (isChoiceParameter)
621 prm.setValue((String) choicebox.getSelectedItem());
625 prm.setValue(valueField.getText());
632 // reset the widget's initial value.
637 public void mouseClicked(MouseEvent e)
639 if (e.isPopupTrigger()) // for Windows
641 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
646 public void mouseEntered(MouseEvent e)
651 public void mouseExited(MouseEvent e)
656 public void mousePressed(MouseEvent e)
658 if (e.isPopupTrigger()) // for Mac
660 showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
665 public void mouseReleased(MouseEvent e)
670 public void stateChanged(ChangeEvent e)
679 if (!isLogarithmicParameter)
682 * set (int or float formatted) text field value
684 valueField.setText(isIntegerParameter
685 ? String.valueOf(slider.getValue())
687 slider.getValue() / (float) sliderScaleFactor));
691 double value = Math.pow(Math.E,
692 slider.getValue() / (double) sliderScaleFactor);
693 valueField.setText(formatDouble(value));
703 * Answers the value formatted as a string to 3 decimal places - in
704 * scientific notation if the value is less than 0.001
709 String formatDouble(double value)
711 String format = value < 0.001 ? "%3.1E" : "%3.3f";
712 return String.format(format, value);
716 * Formats a number as integer or float (3dp) or scientific notation (1dp)
721 String formatNumber(Number n)
723 return n instanceof Integer ? String.valueOf(n.intValue())
724 : formatDouble(n.doubleValue());
727 void updateControls(ParameterI parm)
730 boolean init = (choicebox == null && valueField == null);
733 if (isChoiceParameter)
735 choicebox = new JComboBox<>();
736 choicebox.addActionListener(this);
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);
770 if (isChoiceParameter)
774 for (String val : parm.getPossibleValues())
776 choicebox.addItem(val);
779 if (parm.getValue() != null)
781 choicebox.setSelectedItem(parm.getValue());
786 valueField.setText(parm.getValue());
789 lastVal = updateSliderFromValueField();
794 * Action depends on the type of the input parameter:
796 * <li>if a text input, returns the trimmed value</li>
797 * <li>if a choice list, returns the selected value</li>
798 * <li>if a value slider and input field, sets the value of the slider from
799 * the value in the text field, limiting it to any defined min-max
802 * Answers the (possibly modified) input value, as a String, Integer, Float
807 Object updateSliderFromValueField()
809 if (validator == null || isStringParameter)
811 if (isChoiceParameter)
813 return choicebox.getSelectedItem();
815 slider.setVisible(false);
816 return valueField.getText().trim();
819 valueField.setText(valueField.getText().trim());
822 * ensure not outside min-max range
823 * TODO: provide some visual indicator if limit reached
827 valueField.setBackground(Color.WHITE);
828 double d = Double.parseDouble(valueField.getText());
829 if (validator.getMin() != null
830 && validator.getMin().doubleValue() > d)
832 valueField.setText(formatNumber(validator.getMin()));
834 if (validator.getMax() != null
835 && validator.getMax().doubleValue() < d)
837 valueField.setText(formatNumber(validator.getMax()));
839 } catch (NumberFormatException e)
841 valueField.setBackground(Color.yellow);
845 if (isIntegerParameter)
850 iVal = Integer.valueOf(valueField.getText());
851 } catch (Exception e)
853 valueField.setBackground(Color.yellow);
854 return Integer.valueOf(0);
857 if (validator.getMin() != null && validator.getMax() != null)
859 slider.getModel().setRangeProperties(iVal, 1,
860 validator.getMin().intValue(),
861 validator.getMax().intValue() + 1, true);
865 slider.setVisible(false);
867 return new Integer(iVal);
870 if (isLogarithmicParameter)
875 double eValue = Double.valueOf(valueField.getText());
876 dVal = Math.log(eValue) * sliderScaleFactor;
877 } catch (Exception e)
879 // shouldn't be possible here
880 valueField.setBackground(Color.yellow);
883 if (validator.getMin() != null && validator.getMax() != null)
885 double scaleMin = Math.log(validator.getMin().doubleValue())
887 double scaleMax = Math.log(validator.getMax().doubleValue())
889 slider.getModel().setRangeProperties((int) (dVal), 1,
890 (int) scaleMin, 1 + (int) scaleMax, true);
894 slider.setVisible(false);
896 return new Double(dVal);
902 fVal = Float.valueOf(valueField.getText());
903 } catch (Exception e)
905 return Float.valueOf(0f); // shouldn't happen
907 if (validator.getMin() != null && validator.getMax() != null)
909 float scaleMin = validator.getMin().floatValue()
911 float scaleMax = validator.getMax().floatValue()
913 slider.getModel().setRangeProperties(
914 (int) (fVal * sliderScaleFactor), 1, (int) scaleMin,
915 1 + (int) scaleMax, true);
919 slider.setVisible(false);
921 return new Float(fVal);
926 * Constructor with the option to show 'compact' format (parameter description
927 * as tooltip) or 'expanded' format (parameter description in a textbox which
928 * may be opened or closed). Use compact for simple description text, expanded
929 * for more wordy or formatted text.
931 * @param paramContainer
933 public OptsAndParamsPage(OptsParametersContainerI paramContainer,
936 poparent = paramContainer;
937 this.compact = compact;
940 public static void showUrlPopUp(JComponent invoker, final String finfo,
944 JPopupMenu mnu = new JPopupMenu();
945 JMenuItem mitem = new JMenuItem(
946 MessageManager.formatMessage("label.view_params", new String[]
948 mitem.addActionListener(new ActionListener()
952 public void actionPerformed(ActionEvent e)
954 Desktop.showUrl(finfo);
959 mnu.show(invoker, x, y);
962 public Map<String, OptionBox> getOptSet()
967 public void setOptSet(Map<String, OptionBox> optSet)
969 this.optSet = optSet;
972 public Map<String, ParamBox> getParamSet()
977 public void setParamSet(Map<String, ParamBox> paramSet)
979 this.paramSet = paramSet;
982 OptionBox addOption(OptionI opt)
984 OptionBox cb = optSet.get(opt.getName());
987 cb = new OptionBox(opt);
988 optSet.put(opt.getName(), cb);
989 // jobOptions.add(cb, FlowLayout.LEFT);
994 ParamBox addParameter(ParameterI arg)
996 ParamBox pb = paramSet.get(arg.getName());
999 pb = new ParamBox(poparent, arg);
1000 paramSet.put(arg.getName(), pb);
1001 // paramList.add(pb);
1004 // take the defaults from the parameter
1005 pb.updateControls(arg);
1009 void selectOption(OptionI option, String string)
1011 OptionBox cb = optSet.get(option.getName());
1014 cb = addOption(option);
1016 cb.enabled.setSelected(string != null); // initial state for an option.
1019 if (option.getPossibleValues().contains(string))
1021 cb.val.setSelectedItem(string);
1025 throw new Error(String.format("Invalid value '%s' for option '%s'",
1026 string, option.getName()));
1029 if (option.isRequired() && !cb.enabled.isSelected())
1031 // TODO: indicate paramset is not valid.. option needs to be selected!
1033 cb.setInitialValue();
1036 void setParameter(ParameterI arg)
1038 ParamBox pb = paramSet.get(arg.getName());
1045 pb.updateControls(arg);
1051 * recover options and parameters from GUI
1055 public List<ArgumentI> getCurrentSettings()
1057 List<ArgumentI> argSet = new ArrayList<>();
1058 for (OptionBox opts : getOptSet().values())
1060 OptionI opt = opts.getOptionIfEnabled();
1066 for (ParamBox parambox : getParamSet().values())
1068 ParameterI parm = parambox.getParameter();