9164cc00131931cdb23a61c3d082a717105aab75
[jalview.git] / src / jalview / gui / WsJobParameters.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
4  * 
5  * This file is part of Jalview.
6  * 
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.gui;
19
20 import java.awt.BorderLayout;
21 import java.awt.Color;
22 import java.awt.Component;
23 import java.awt.Dimension;
24 import java.awt.FlowLayout;
25 import java.awt.Font;
26 import java.awt.GridLayout;
27 import java.awt.Rectangle;
28 import java.awt.event.ActionEvent;
29 import java.awt.event.ActionListener;
30 import java.awt.event.ComponentEvent;
31 import java.awt.event.ComponentListener;
32 import java.awt.event.ContainerEvent;
33 import java.awt.event.ContainerListener;
34 import java.awt.event.ItemEvent;
35 import java.awt.event.ItemListener;
36 import java.awt.event.KeyEvent;
37 import java.awt.event.KeyListener;
38 import java.awt.event.MouseEvent;
39 import java.awt.event.MouseListener;
40 import java.awt.event.WindowEvent;
41 import java.awt.event.WindowListener;
42 import java.awt.event.WindowStateListener;
43 import java.net.URL;
44 import java.util.ArrayList;
45 import java.util.EventObject;
46 import java.util.HashSet;
47 import java.util.Hashtable;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Vector;
52
53 import javax.swing.InputVerifier;
54 import javax.swing.JButton;
55 import javax.swing.JCheckBox;
56 import javax.swing.JComboBox;
57 import javax.swing.JComponent;
58 import javax.swing.JDialog;
59 import javax.swing.JFrame;
60 import javax.swing.JLabel;
61 import javax.swing.JList;
62 import javax.swing.JMenuItem;
63 import javax.swing.JOptionPane;
64 import javax.swing.JPanel;
65 import javax.swing.JPopupMenu;
66 import javax.swing.JScrollPane;
67 import javax.swing.JSlider;
68 import javax.swing.JSplitPane;
69 import javax.swing.JTabbedPane;
70 import javax.swing.JTable;
71 import javax.swing.JTextArea;
72 import javax.swing.JTextField;
73 import javax.swing.ListSelectionModel;
74 import javax.swing.SwingConstants;
75 import javax.swing.SwingUtilities;
76 import javax.swing.border.TitledBorder;
77 import javax.swing.event.CellEditorListener;
78 import javax.swing.event.ChangeEvent;
79 import javax.swing.event.ChangeListener;
80 import javax.swing.event.DocumentEvent;
81 import javax.swing.event.DocumentListener;
82 import javax.swing.table.*;
83
84 import compbio.metadata.Argument;
85 import compbio.metadata.Option;
86 import compbio.metadata.Parameter;
87 import compbio.metadata.Preset;
88 import compbio.metadata.PresetManager;
89 import compbio.metadata.RunnerConfig;
90 import compbio.metadata.ValueConstrain;
91 import compbio.metadata.WrongParameterException;
92 import compbio.metadata.ValueConstrain.Type;
93
94 import jalview.util.jarInputStreamProvider;
95 import jalview.ws.jws2.JabaParamStore;
96 import jalview.ws.jws2.JabaPreset;
97 import jalview.ws.jws2.Jws2Discoverer;
98 import jalview.ws.jws2.ParameterUtils;
99 import jalview.ws.jws2.Jws2Discoverer.Jws2Instance;
100 import jalview.ws.jws2.dm.JabaOption;
101 import jalview.ws.jws2.dm.JabaParameter;
102 import jalview.ws.params.ArgumentI;
103 import jalview.ws.params.OptionI;
104 import jalview.ws.params.ParamDatastoreI;
105 import jalview.ws.params.ParameterI;
106 import jalview.ws.params.ValueConstrainI;
107 import jalview.ws.params.WsParamSetI;
108
109 /**
110  * job parameter editing/browsing dialog box. User can browse existing settings
111  * (user + presets + Defaults), and any changes to parameters creates a modified
112  * user parameter set. LOGIC: If the parameter set is modified, and its name is
113  * a valid, non-existant user parameter set, then a save button is shown. If the
114  * parameter set is modified and its name is a valid, extant user parameter set,
115  * then an update button is shown. If user parameter set's name is edited, and
116  * old name exists as a writable user parameter set, then rename button is
117  * shown. If current parameter set is associated with a user defined parameter
118  * set, then : if set is modifed, a 'revert' button is shown. if set is not
119  * modified, a 'delete' button is shown.
120  * 
121  * @author JimP
122  * 
123  */
124 public class WsJobParameters extends JPanel implements ItemListener,
125         ActionListener, DocumentListener
126 {
127   URL linkImageURL = getClass().getResource("/images/link.gif");
128
129   private static final String SVC_DEF = "Defaults"; // this is the null
130                                                     // parameter set as shown to
131                                                     // user
132
133   private static final int PARAM_WIDTH = 340, PARAM_HEIGHT = 150,
134           PARAM_CLOSEDHEIGHT = 80;
135
136   private static final int OPTSET_HEIGHT = 30;
137
138   JPanel SetNamePanel = new JPanel();
139
140   JPanel setDetails = new JPanel();
141
142   JSplitPane settingsPanel = new JSplitPane();
143
144   JSplitPane jobPanel = new JSplitPane();
145
146   boolean split = true;
147
148   JTabbedPane tabpanels = new JTabbedPane();
149
150   JPanel jobOptions = new JPanel();
151
152   JScrollPane jobOptionsPane = new JScrollPane();
153
154   JPanel jobParameters = new JPanel();
155
156   JButton createpref = new JButton();
157
158   JButton deletepref = new JButton();
159
160   JButton revertpref = new JButton();
161
162   JButton updatepref = new JButton();
163
164   JButton startjob = new JButton();
165
166   JButton canceljob = new JButton();
167
168   JComboBox setName = new JComboBox();
169
170   JTextArea setDescr = new JTextArea();
171
172   JScrollPane paramPane = new JScrollPane();
173
174   JPanel paramList = new JPanel();
175
176   RunnerConfig serviceOptions;
177
178   ParamDatastoreI paramStore;
179
180   WsJobParameters(Jws2Instance service)
181   {
182     this(service, null);
183   }
184
185   public WsJobParameters(Jws2Instance service, WsParamSetI preset)
186   {
187     this(null, service, preset, null);
188   }
189
190   /**
191    * 
192    * @param desktop
193    *          - if null, create new JFrame outside of desktop
194    * @param service
195    * @param preset
196    */
197   public WsJobParameters(JFrame parent, Jws2Instance service,
198           WsParamSetI preset, List<Argument> jobArgset)
199   {
200     this(parent, null, service, preset, jobArgset);
201   }
202
203   /**
204    * 
205    * @param parent
206    * @param paramStorei
207    * @param service
208    * @param preset
209    * @param jobArgset
210    */
211   public WsJobParameters(JFrame parent, ParamDatastoreI paramStorei,
212           Jws2Instance service, WsParamSetI preset, List<Argument> jobArgset)
213   {
214     super();
215     jbInit();
216     this.paramStore = paramStorei;
217     if (paramStore == null)
218     {
219       paramStore = service.getParamStore();
220     }
221     this.service = service;
222     // argSetModified(false);
223     // populate parameter table
224     initForService(service, preset, jobArgset);
225     // display in new JFrame attached to parent.
226     validate();
227   }
228
229   int response = -1;
230
231   JDialog frame = null;
232
233   /**
234    * shows a modal dialog containing the parameters.
235    * 
236    * @return
237    */
238   public boolean showRunDialog()
239   {
240
241     frame = new JDialog(Desktop.instance, true);
242
243     frame.setTitle("Edit parameters for " + service.getActionText());
244     Rectangle deskr = Desktop.instance.getBounds();
245     frame.setBounds(new Rectangle((int) (deskr.getCenterX() - 240),
246             (int) (deskr.getCenterY() - 250), 480, 500));
247     frame.setContentPane(this);
248     // should recover defaults from user prefs.
249     // settingsPanel.setDividerLocation(0.4);
250     // jobPanel.setDividerLocation(0.5);
251     frame.validate();
252     if (split)
253     {
254       javax.swing.SwingUtilities.invokeLater(new Runnable()
255       {
256         public void run()
257         {
258           settingsPanel.setDividerLocation(0.5);
259           jobPanel.setDividerLocation(setDescr.getLineCount() > 3 ? 0.35
260                   : 0.16);
261         }
262       });
263     }
264     else
265     {
266       tabpanels.setSelectedComponent(jobOptionsPane);
267     }
268     frame.setVisible(true);
269
270     if (response > 0)
271     {
272       return true;
273     }
274     return false;
275   }
276
277   private void jbInit()
278   {
279     updatepref = JvSwingUtils.makeButton("Update",
280             "Update this existing user parameter set.",
281             new ActionListener()
282             {
283
284               public void actionPerformed(ActionEvent e)
285               {
286                 update_actionPerformed(e);
287               }
288             });
289     deletepref = JvSwingUtils.makeButton("Delete",
290             "Delete the currently selected user parameter set.",
291             new ActionListener()
292             {
293
294               public void actionPerformed(ActionEvent e)
295               {
296                 delete_actionPerformed(e);
297               }
298             });
299     createpref = JvSwingUtils.makeButton("Create",
300             "Create a new parameter set with the current settings.",
301             new ActionListener()
302             {
303
304               public void actionPerformed(ActionEvent e)
305               {
306                 create_actionPerformed(e);
307               }
308             });
309     revertpref = JvSwingUtils.makeButton("Revert",
310             "Undo all changes to the current parameter set",
311             new ActionListener()
312             {
313
314               public void actionPerformed(ActionEvent e)
315               {
316                 revert_actionPerformed(e);
317               }
318             });
319     startjob = JvSwingUtils.makeButton("Start Job",
320             "Start Job with current settings.", new ActionListener()
321             {
322               public void actionPerformed(ActionEvent e)
323               {
324                 startjob_actionPerformed(e);
325               }
326             });
327     canceljob = JvSwingUtils.makeButton("Cancel Job",
328             "Close this dialog and cancel job.", new ActionListener()
329             {
330               public void actionPerformed(ActionEvent e)
331               {
332                 canceljob_actionPerformed(e);
333               }
334             });
335
336     setDetails.setBorder(new TitledBorder("Details"));
337     setDetails.setLayout(new BorderLayout());
338     setDescr.setColumns(40);
339     setDescr.setWrapStyleWord(true);
340     setDescr.setLineWrap(true);
341     setDescr.setBackground(getBackground());
342     setDescr.setEditable(true);
343     setDescr.getDocument().addDocumentListener(this);
344     setDescr.setToolTipText("Click to edit the notes for this parameter set.");
345     JScrollPane setDescrView = new JScrollPane();
346     // setDescrView.setPreferredSize(new Dimension(350, 200));
347     setDescrView.getViewport().setView(setDescr);
348     setName.setEditable(true);
349     setName.addItemListener(this);
350     setName.getEditor().addActionListener(this);
351     JPanel setNameInfo = new JPanel(new FlowLayout(FlowLayout.LEFT));
352     SetNamePanel.setLayout(new GridLayout(2, 1));
353     SetNamePanel.setMinimumSize(new Dimension(300, 40));
354     JLabel setNameLabel = new JLabel("Current parameter set name :");
355     setNameLabel.setFont(new java.awt.Font("Verdana", Font.PLAIN, 10));
356     // setNameLabel.setHorizontalAlignment(FlowLayout.LEFT);
357     setNameInfo.add(setNameLabel);
358     setNameInfo.add(setName);
359     // initial button visibility
360     updatepref.setVisible(false);
361     deletepref.setVisible(false);
362     revertpref.setVisible(false);
363     createpref.setVisible(false);
364     JPanel setsavebuts = new JPanel();
365     setsavebuts.setLayout(new FlowLayout(FlowLayout.LEFT)); // GridLayout(1,2));
366     ((FlowLayout) setsavebuts.getLayout()).setHgap(10);
367     ((FlowLayout) setsavebuts.getLayout()).setVgap(0);
368     setsavebuts.add(deletepref);
369     setsavebuts.add(revertpref);
370     setsavebuts.add(createpref);
371     setsavebuts.add(updatepref);
372     setsavebuts.setSize(new Dimension(150, 20));
373     JPanel buttonArea = new JPanel(new GridLayout(1, 1));
374     buttonArea.add(setsavebuts);
375     SetNamePanel.add(setNameInfo);
376     SetNamePanel.add(buttonArea);
377     setDetails.add(setDescrView, BorderLayout.CENTER);
378     // setDetails.setPreferredSize(new Dimension(360, 100));
379     jobParameters.setBorder(new TitledBorder("Parameters"));
380     jobParameters.setLayout(new BorderLayout());
381     paramPane.setPreferredSize(new Dimension(360, 300));
382     paramPane.getVerticalScrollBar().setUnitIncrement(20);
383     // paramPanel.setPreferredSize(new Dimension(360, 300));
384     // TODO: relayout buttons nicely
385     paramPane.getViewport().setView(paramList);
386     jobParameters.add(paramPane, BorderLayout.CENTER);
387     JPanel jobOptionsPanel = new JPanel();
388     jobOptionsPanel.setLayout(new BorderLayout());
389     jobOptionsPanel.setBorder(new TitledBorder("Options"));
390     jobOptionsPane.getViewport().setView(jobOptions);
391     jobOptionsPanel.add(jobOptionsPane, BorderLayout.CENTER);
392
393     setLayout(new BorderLayout());
394     jobPanel.setLeftComponent(setDetails);
395     if (split)
396     {
397       settingsPanel.setLeftComponent(jobOptionsPanel);
398       settingsPanel.setRightComponent(jobParameters);
399       settingsPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
400       jobPanel.setRightComponent(settingsPanel);
401     }
402     else
403     {
404       jobPanel.setRightComponent(tabpanels);
405       jobOptionsPane.setName("Options");
406       tabpanels.add(jobOptionsPane);
407       paramPane.setName("Parameters");
408       tabpanels.add(paramPane);
409     }
410     jobPanel.setOrientation(JSplitPane.VERTICAL_SPLIT);
411     add(SetNamePanel, BorderLayout.NORTH);
412     add(jobPanel, BorderLayout.CENTER);
413     JPanel dialogpanel = new JPanel();
414     dialogpanel.add(startjob);
415     dialogpanel.add(canceljob);
416     add(dialogpanel, BorderLayout.SOUTH);
417   }
418
419   protected void revert_actionPerformed(ActionEvent e)
420   {
421     reInitDialog(lastParmSet);
422
423   }
424
425   protected void update_actionPerformed(ActionEvent e)
426   {
427     if (isUserPreset)
428     {
429       String curname = ((String) setName.getSelectedItem()).trim();
430       _updatePreset(lastParmSet, curname);
431       lastParmSet = curname;
432       isUserPreset = true;
433       initArgSetModified();
434       syncSetNamesWithStore();
435     }
436   }
437
438   private void _deleteUserPreset(String lastParmSet2)
439   {
440     paramStore.deletePreset(lastParmSet2);
441   }
442
443   protected void delete_actionPerformed(ActionEvent e)
444   {
445     if (isUserPreset)
446     {
447       // delete current preset's saved entry
448       _deleteUserPreset(lastParmSet);
449     }
450     reInitDialog(null); // service default
451   }
452
453   protected void create_actionPerformed(ActionEvent e)
454   {
455     String curname = ((String) setName.getSelectedItem()).trim();
456     if (curname.length() > 0)
457     {
458       _storeCurrentPreset(curname);
459       lastParmSet = curname;
460       isUserPreset = true;
461       initArgSetModified();
462     }
463     else
464     {
465       // TODO: show warning
466       System.err.println("Invalid name. Not saved.");
467     }
468   }
469
470   protected void canceljob_actionPerformed(ActionEvent e)
471   {
472     response = 0;
473     if (frame != null)
474     {
475       frame.setVisible(false);
476     }
477   }
478
479   protected void startjob_actionPerformed(ActionEvent e)
480   {
481     response = 1;
482     if (frame != null)
483     {
484       frame.setVisible(false);
485     }
486   }
487
488   Jws2Instance service;
489
490   /**
491    * list of service presets in the gui
492    */
493   Hashtable servicePresets = null;
494
495   /**
496    * set if dialog is being set - so handlers will avoid spurious events
497    */
498   boolean settingDialog = false;
499
500   void initForService(Jws2Instance service, WsParamSetI jabap,
501           List<Argument> jabajobArgset)
502   {
503     WsParamSetI p = null;
504     List<ArgumentI> jobArgset = null;
505     settingDialog = true;
506     { // instantiate the abstract proxy for Jaba objects
507       jobArgset = jabajobArgset == null ? null : JabaParamStore
508               .getJwsArgsfromJaba(jabajobArgset);
509       p = jabap; // (jabap != null) ? paramStore.getPreset(jabap.getName()) :
510                  // null;
511     }
512     // TODO: Recover window geometry prefs for this service
513     // jobPanel.setDividerLocation(proportionalLocation)
514     // settingsPanel.setDividerLocation(proportionalLocation)
515     Hashtable exnames = new Hashtable();
516     for (int i = 0, iSize = setName.getItemCount(); i < iSize; i++)
517     {
518       exnames.put((String) setName.getItemAt(i), setName.getItemAt(i));
519     }
520     servicePresets = new Hashtable();
521     // Add the default entry - if not present already.
522     if (!exnames.contains(SVC_DEF))
523     {
524       setName.addItem(SVC_DEF);
525       exnames.put(SVC_DEF, SVC_DEF);
526       servicePresets.put(SVC_DEF, SVC_DEF);
527     }
528     String curname = (p == null ? "" : p.getName());
529     for (WsParamSetI pr : paramStore.getPresets())
530     {
531       if (!pr.isModifiable())
532       {
533         servicePresets.put(pr.getName(), "preset");
534       }
535       else
536       {
537       }
538       if (!exnames.contains(pr.getName()))
539       {
540         setName.addItem(pr.getName());
541       }
542     }
543     // TODO: if initial jobArgset matches a given user setting or preset then
544     // should recover setting accordingly
545     // updateTable(p, jobArgset);
546     if (p != null)
547     {
548       reInitDialog(p.getName());
549       initArgSetModified();
550     }
551     else
552     {
553       if (jobArgset != null && jobArgset.size() > 0)
554       {
555         curSetName = "Supplied Settings";
556         updateTable(p, jobArgset);
557       }
558       else
559       {
560         curSetName = null;
561         reInitDialog(null);
562       }
563     }
564     settingDialog = false;
565
566   }
567
568   @SuppressWarnings("unchecked")
569   private void updateTable(WsParamSetI p, List<ArgumentI> jobArgset)
570   {
571     // populate table from default parameter set.
572     List<ArgumentI> args = paramStore.getServiceParameters();
573
574     // split to params and required arguments
575     {
576       for (ArgumentI myarg : args)
577       {
578         // Ideally, Argument would implement isRequired !
579         if (myarg instanceof ParameterI)
580         {
581           ParameterI parm = (ParameterI) myarg;
582           addParameter(parm);
583         }
584         else
585         {
586           if (myarg instanceof OptionI)
587           {
588             OptionI opt = (OptionI) myarg;
589             addOption(opt).resetToDefault();
590           }
591           else
592           {
593             System.err.println("Ignoring unknown service argument type "
594                     + myarg.getClass().getName());
595           }
596         }
597       }
598       args = null; // no more args to process.
599     }
600     if (p != null)
601     {
602       isUserPreset = false;
603       // initialise setname
604       setName.setSelectedItem(lastSetName = p.getName());
605       setDescr.setText(lastDescrText = p.getDescription());
606       // TODO - URL link
607       try
608       {
609         args = p.getArguments();
610       } catch (Exception e)
611       {
612         e.printStackTrace();
613       }
614       // TODO: check if args should be unselected prior to resetting using the
615       // preset
616     }
617     else
618     {
619       if (lastParmSet == null)
620       {
621         isUserPreset = false;
622         // first call - so create a dummy name
623
624         setName.setSelectedItem(lastSetName = SVC_DEF);
625       }
626     }
627
628     if (jobArgset != null)
629     {
630       argSetModified(jobArgset, true);
631       args = jobArgset;
632     }
633     // get setargs from current object
634     if (args != null)
635     {
636       for (ArgumentI arg : args)
637       {
638         if (arg instanceof ParameterI)
639         {
640           setParameter((ParameterI) arg);
641         }
642         else
643         {
644           if (arg instanceof OptionI)
645           {
646             // System.out.println("Setting option "
647             // + System.identityHashCode(arg) + ":" + arg.getName()
648             // + " with " + arg.getDefaultValue());
649             selectOption((OptionI) arg, arg.getDefaultValue());
650           }
651         }
652
653       }
654     }
655
656     jobOptions.setPreferredSize(new Dimension(PARAM_WIDTH, optSet.size()
657             * OPTSET_HEIGHT));
658     jobOptions.setLayout(new GridLayout(optSet.size(), 1));
659     refreshParamLayout();
660     paramPane.validate();
661     revalidate();
662   }
663
664   private boolean isModified()
665   {
666     return modifiedElements.size() > 0;
667   }
668
669   private Hashtable modifiedElements = new Hashtable();
670
671   /**
672    * reset gui and modification state settings
673    */
674   private void initArgSetModified()
675   {
676     curSetName = null;
677     modifiedElements.clear();
678     updateButtonDisplay();
679   }
680
681   private void updateButtonDisplay()
682   {
683     boolean _update = false, _create = false, _delete = false, _revert = false;
684     if (modifiedElements.size() > 0)
685     {
686       // set modified
687       _revert = true;
688       _update = isUserPreset; // can only update user presets
689       if (!isUserPreset || modifiedElements.containsKey(setName))
690       {
691         // name modified - can create new preset
692         _create = true;
693       }
694     }
695     else
696     {
697       // set unmodified
698     }
699     // can still delete a user preset
700     _delete = isUserPreset;
701
702     createpref.setVisible(_create);
703     updatepref.setVisible(_update);
704     deletepref.setVisible(_delete);
705     revertpref.setVisible(_revert);
706     validate();
707   }
708
709   private void argSetModified(Object modifiedElement, boolean b)
710   {
711     if (settingDialog)
712     {
713       return;
714     }
715     if (!b)
716     {
717       modifiedElements.remove(modifiedElement);
718     }
719     else
720     {
721       if (b && modifiedElement == setName
722               && modifiedElements.contains(modifiedElement))
723       {
724         // HACK! prevents iteration on makeSetNameValid
725         b = false;
726       }
727       modifiedElements.put(modifiedElement, modifiedElement);
728     }
729     // set mod status based on presence of elements in table
730     if (b && modifiedElements.size() > 0)
731     {
732       makeSetNameValid(!isUserPreset);
733       SetNamePanel.revalidate();
734     }
735     updateButtonDisplay();
736   }
737
738   private boolean isServicePreset(String selectedItem)
739   {
740     return selectedItem.equals(SVC_DEF)
741             || servicePresets.containsKey(selectedItem);
742   }
743
744   /**
745    * check if the current set name is a valid set name for saving, if not, then
746    * fix it.
747    */
748   private void makeSetNameValid(boolean newuserset)
749   {
750     boolean stn = settingDialog;
751     boolean renamed = false;
752     settingDialog = true;
753     String nm = (curSetName != null ? curSetName : (String) setName
754             .getSelectedItem());
755     // check if the name is reserved - if it is, rename it.
756     if (isServicePreset(nm))
757     {
758       nm = "User " + nm;
759       renamed = true;
760     }
761     String tnm = nm;
762     if (newuserset)
763     {
764       int i = 0;
765       while (paramStore.getPreset(tnm) != null)
766       {
767         tnm = nm + " (" + (++i) + ")";
768         renamed = true;
769       }
770       if (i > 0)
771       {
772         nm = tnm;
773       }
774     }
775
776     boolean makeupdate = false;
777     // sync the gui with the preset database
778     for (int i = 0, iS = setName.getItemCount(); i < iS; i++)
779     {
780       String snm = (String) setName.getItemAt(i);
781       if (snm.equals(nm))
782       {
783         makeupdate = true;
784         // setName.setSelectedIndex(i);
785       }
786     }
787     if (!makeupdate)
788     {
789       setName.addItem(curSetName = nm);
790       setName.setSelectedItem(curSetName);
791     }
792     if (renamed)
793     {
794       settingDialog = false; // we need this name change to be registered.
795       argSetModified(setName, renamed);
796     }
797     settingDialog = stn;
798   }
799
800   private void addParameter(ParameterI arg)
801   {
802     ParamBox pb = paramSet.get(arg.getName());
803     if (pb == null)
804     {
805       pb = new ParamBox(this, arg);
806       paramSet.put(arg.getName(), pb);
807       paramList.add(pb);
808     }
809     pb.init();
810     // take the defaults from the parameter
811     pb.updateControls(arg);
812   }
813
814   private void setParameter(ParameterI arg)
815   {
816     ParamBox pb = paramSet.get(arg.getName());
817     if (pb == null)
818     {
819       addParameter(arg);
820     }
821     else
822     {
823       pb.updateControls(arg);
824     }
825
826   }
827
828   private void selectOption(OptionI option, String string)
829   {
830     OptionBox cb = optSet.get(option.getName());
831     if (cb == null)
832     {
833       cb = addOption(option);
834     }
835     cb.enabled.setSelected(string != null); // initial state for an option.
836     if (string != null)
837     {
838       if (option.getPossibleValues().contains(string))
839       {
840         cb.val.setSelectedItem(string);
841       }
842       else
843       {
844         throw new Error("Invalid value " + string + " for option " + option);
845       }
846
847     }
848     if (option.isRequired() && !cb.enabled.isSelected())
849     {
850       // TODO: indicate paramset is not valid.. option needs to be selected!
851     }
852     cb.setInitialValue();
853   }
854
855   Map<String, ParamBox> paramSet = new Hashtable<String, ParamBox>();
856
857   public class ParamBox extends JPanel implements ChangeListener,
858           ActionListener, MouseListener
859   {
860     JButton showDesc = new JButton();
861
862     JTextArea string = new JTextArea();
863
864     JScrollPane descPanel = new JScrollPane();
865
866     JSlider slider = null;
867
868     JTextField valueField = null;
869
870     ValueConstrainI validator = null;
871
872     JPanel settingPanel = new JPanel();
873
874     JPanel controlPanel = new JPanel();
875
876     boolean integ = false;
877
878     boolean choice = false;
879
880     boolean descisvisible = false;
881
882     final WsJobParameters pmdialogbox;
883
884     final URL finfo;
885
886     public ParamBox(final WsJobParameters pmlayout, ParameterI parm)
887     {
888       pmdialogbox = pmlayout;
889       setPreferredSize(new Dimension(PARAM_WIDTH, PARAM_CLOSEDHEIGHT));
890       setBorder(new TitledBorder(parm.getName()));
891       setLayout(null);
892       showDesc.setFont(new Font("Verdana", Font.PLAIN, 6));
893       showDesc.setText("+");
894       string.setFont(new Font("Verdana", Font.PLAIN, 11));
895       string.setBackground(getBackground());
896       // string.setSize(new Dimension(PARAM_WIDTH, 80));
897       string.setEditable(false);
898       descPanel.getViewport().setView(string);
899       // descPanel.setLocation(2,17);
900       descPanel.setVisible(false);
901       // string.setMinimumSize(new Dimension(140,80));
902       // string.setMaximumSize(new Dimension(280,80));
903       final ParamBox me = this;
904       finfo = parm.getFurtherDetails();
905       if (finfo != null)
906       {
907         showDesc.setToolTipText("<html>"
908                 + JvSwingUtils
909                         .wrapTooltip("Click to show brief description<br><img src=\""
910                                 + linkImageURL
911                                 + "\"/> Right click for further information.")
912                 + "</html>");
913         showDesc.addMouseListener(this);
914       }
915       else
916       {
917         showDesc.setToolTipText("<html>"
918                 + JvSwingUtils
919                         .wrapTooltip("Click to show brief description.")
920                 + "</html>");
921       }
922       showDesc.addActionListener(new ActionListener()
923       {
924
925         public void actionPerformed(ActionEvent e)
926         {
927           descisvisible = !descisvisible;
928           descPanel.setVisible(descisvisible);
929           me.setPreferredSize(new Dimension(PARAM_WIDTH,
930                   (descisvisible) ? PARAM_HEIGHT : PARAM_CLOSEDHEIGHT));
931           me.validate();
932           pmlayout.refreshParamLayout();
933         }
934       });
935       string.setWrapStyleWord(true);
936       string.setLineWrap(true);
937       string.setColumns(32);
938       string.setText(parm.getDescription());
939       JPanel firstrow = new JPanel();
940       firstrow.setLayout(null);
941       controlPanel.setLayout(new BorderLayout());
942       controlPanel.setBounds(new Rectangle(39, 10, PARAM_WIDTH - 70,
943               PARAM_CLOSEDHEIGHT - 50));
944       showDesc.setBounds(new Rectangle(10, 10, 16, 16));
945       firstrow.add(showDesc);
946       firstrow.add(controlPanel);
947       firstrow.setBounds(new Rectangle(10, 20, PARAM_WIDTH - 30,
948               PARAM_CLOSEDHEIGHT - 30));
949       add(firstrow);
950       validator = parm.getValidValue();
951       parameter = parm;
952       if (validator != null)
953       {
954         integ = validator.getType() == Type.Integer;
955       }
956       else
957       {
958         if (parameter.getPossibleValues() != null)
959         {
960           choice = true;
961         }
962       }
963       updateControls(parm);
964       descPanel.setBounds(new Rectangle(10, PARAM_CLOSEDHEIGHT,
965               PARAM_WIDTH - 20, PARAM_HEIGHT - PARAM_CLOSEDHEIGHT - 5));
966       add(descPanel);
967       validate();
968     }
969
970     public void init()
971     {
972       // reset the widget's initial value.
973       lastVal = null;
974     }
975
976     boolean adjusting = false;
977
978     ParameterI parameter;
979
980     JComboBox choicebox;
981
982     public int getBoxHeight()
983     {
984       return (descisvisible ? PARAM_HEIGHT : PARAM_CLOSEDHEIGHT);
985     }
986
987     public void updateControls(ParameterI parm)
988     {
989       adjusting = true;
990       boolean init = (choicebox == null && valueField == null);
991       float fVal = 0f;
992       int iVal = 0;
993       if (init)
994       {
995         if (choice)
996         {
997           choicebox = new JComboBox();
998           choicebox.addActionListener(this);
999           controlPanel.add(choicebox, BorderLayout.CENTER);
1000         }
1001         else
1002         {
1003           slider = new JSlider();
1004           slider.addChangeListener(this);
1005           valueField = new JTextField();
1006           valueField.addActionListener(this);
1007           valueField.setPreferredSize(new Dimension(60, 25));
1008           controlPanel.add(slider, BorderLayout.WEST);
1009           controlPanel.add(valueField, BorderLayout.EAST);
1010
1011         }
1012       }
1013
1014       if (parm != null)
1015       {
1016         if (choice)
1017         {
1018           if (init)
1019           {
1020             List vals = parm.getPossibleValues();
1021             for (Object val : vals)
1022             {
1023               choicebox.addItem(val);
1024             }
1025           }
1026
1027           if (parm.getDefaultValue() != null)
1028           {
1029             choicebox.setSelectedItem(parm.getDefaultValue());
1030           }
1031         }
1032         else
1033         {
1034           valueField.setText(parm.getDefaultValue());
1035         }
1036       }
1037       lastVal = updateSliderFromValueField();
1038       adjusting = false;
1039     }
1040
1041     Object lastVal;
1042
1043     public ParameterI getParameter()
1044     {
1045       ParameterI prm = parameter.copy();
1046       if (choice)
1047       {
1048         prm.setDefaultValue((String) choicebox.getSelectedItem());
1049       }
1050       else
1051       {
1052         prm.setDefaultValue(valueField.getText());
1053       }
1054       return prm;
1055     }
1056
1057     public Object updateSliderFromValueField()
1058     {
1059       int iVal;
1060       float fVal;
1061       if (validator != null)
1062       {
1063         if (integ)
1064         {
1065           iVal = 0;
1066           try
1067           {
1068             valueField.setText(valueField.getText().trim());
1069             iVal = Integer.valueOf(valueField.getText());
1070             if (validator.getMin() != null
1071                     && validator.getMin().intValue() > iVal)
1072             {
1073               iVal = validator.getMin().intValue();
1074               // TODO: provide visual indication that hard limit was reached for
1075               // this parameter
1076             }
1077             if (validator.getMax() != null
1078                     && validator.getMax().intValue() < iVal)
1079             {
1080               iVal = validator.getMax().intValue();
1081               // TODO: provide visual indication that hard limit was reached for
1082               // this parameter
1083             }
1084           } catch (Exception e)
1085           {
1086           }
1087           ;
1088           if (validator.getMin() != null && validator.getMax() != null)
1089           {
1090             slider.getModel().setRangeProperties(iVal, 1,
1091                     validator.getMin().intValue(),
1092                     validator.getMax().intValue(), true);
1093           }
1094           else
1095           {
1096             slider.setVisible(false);
1097           }
1098           return new int[]
1099           { iVal };
1100         }
1101         else
1102         {
1103           fVal = 0f;
1104           try
1105           {
1106             fVal = Float.valueOf(valueField.getText());
1107             if (validator.getMin() != null
1108                     && validator.getMin().floatValue() > fVal)
1109             {
1110               fVal = validator.getMin().floatValue();
1111               // TODO: provide visual indication that hard limit was reached for
1112               // this parameter
1113             }
1114             if (validator.getMax() != null
1115                     && validator.getMax().floatValue() < fVal)
1116             {
1117               fVal = validator.getMax().floatValue();
1118               // TODO: provide visual indication that hard limit was reached for
1119               // this parameter
1120             }
1121           } catch (Exception e)
1122           {
1123           }
1124           ;
1125           if (validator.getMin() != null && validator.getMax() != null)
1126           {
1127             slider.getModel().setRangeProperties((int) fVal * 1000, 1,
1128                     (int) validator.getMin().floatValue() * 1000,
1129                     (int) validator.getMax().floatValue() * 1000, true);
1130           }
1131           else
1132           {
1133             slider.setVisible(false);
1134           }
1135           return new float[]
1136           { fVal };
1137         }
1138       }
1139       else
1140       {
1141         if (!choice)
1142         {
1143           slider.setVisible(false);
1144           return new String[]
1145           { valueField.getText().trim() };
1146         }
1147         else
1148         {
1149           return new String[]
1150           { (String) choicebox.getSelectedItem() };
1151         }
1152       }
1153
1154     }
1155
1156     public void stateChanged(ChangeEvent e)
1157     {
1158       if (!adjusting)
1159       {
1160         valueField.setText(""
1161                 + ((integ) ? ("" + (int) slider.getValue())
1162                         : ("" + (float) (slider.getValue() / 1000f))));
1163         checkIfModified();
1164       }
1165
1166     }
1167
1168     public void actionPerformed(ActionEvent e)
1169     {
1170       if (adjusting)
1171       {
1172         return;
1173       }
1174       if (!choice)
1175       {
1176         updateSliderFromValueField();
1177       }
1178       checkIfModified();
1179     }
1180
1181     private void checkIfModified()
1182     {
1183       Object cstate = updateSliderFromValueField();
1184       boolean notmod = false;
1185       if (cstate.getClass() == lastVal.getClass())
1186       {
1187         if (cstate instanceof int[])
1188         {
1189           notmod = (((int[]) cstate)[0] == ((int[]) lastVal)[0]);
1190         }
1191         else if (cstate instanceof float[])
1192         {
1193           notmod = (((float[]) cstate)[0] == ((float[]) lastVal)[0]);
1194         }
1195         else if (cstate instanceof String[])
1196         {
1197           notmod = (((String[]) cstate)[0].equals(((String[]) lastVal)[0]));
1198         }
1199       }
1200       pmdialogbox.argSetModified(this, !notmod);
1201     }
1202
1203     public void mouseClicked(MouseEvent e)
1204     {
1205       if (javax.swing.SwingUtilities.isRightMouseButton(e))
1206       {
1207         showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
1208       }
1209     }
1210
1211     public void mousePressed(MouseEvent e)
1212     {
1213       // TODO Auto-generated method stub
1214
1215     }
1216
1217     public void mouseReleased(MouseEvent e)
1218     {
1219       // TODO Auto-generated method stub
1220
1221     }
1222
1223     public void mouseEntered(MouseEvent e)
1224     {
1225       // TODO Auto-generated method stub
1226
1227     }
1228
1229     public void mouseExited(MouseEvent e)
1230     {
1231       // TODO Auto-generated method stub
1232
1233     }
1234
1235   }
1236
1237   Map<String, OptionBox> optSet = new Hashtable<String, OptionBox>();
1238
1239   public class OptionBox extends JPanel implements MouseListener,
1240           ActionListener
1241   {
1242     JComboBox val = new JComboBox();
1243
1244     JCheckBox enabled = new JCheckBox();
1245
1246     JLabel optlabel = new JLabel();
1247
1248     final URL finfo;
1249
1250     boolean hasLink = false;
1251
1252     OptionI option;
1253
1254     public OptionBox(OptionI opt)
1255     {
1256       option = opt;
1257       setLayout(new BorderLayout());
1258       enabled.setSelected(opt.isRequired()); // TODO: lock required options
1259       enabled.setFont(new Font("Verdana", Font.PLAIN, 11));
1260       enabled.setText("");
1261       enabled.setText(opt.getName());
1262       enabled.addActionListener(this);
1263       finfo = option.getFurtherDetails();
1264       if (finfo != null)
1265       {
1266         hasLink = true;
1267         // optlabel.setToolTipText("<html><p>"+opt.getDescription()+"</p><img src=\""+linkImageURL+"\"/></html>");
1268         enabled.setToolTipText("<html>"
1269                 + JvSwingUtils.wrapTooltip(opt.getDescription()
1270                         + "<br><img src=\"" + linkImageURL + "\"/>")
1271                 + "</html>");
1272         // optlabel.addMouseListener(this);
1273         enabled.addMouseListener(this);
1274       }
1275       else
1276       {
1277         // optlabel.setToolTipText(opt.getDescription());
1278         enabled.setToolTipText("<html>"
1279                 + JvSwingUtils.wrapTooltip(opt.getDescription())
1280                 + "</html>");
1281       }
1282       add(enabled, BorderLayout.NORTH);
1283       if (opt.getPossibleValues().size() > 1)
1284       {
1285         setLayout(new GridLayout(1, 2));
1286         for (Object str : opt.getPossibleValues())
1287         {
1288           val.addItem((String) str);
1289         }
1290         val.setSelectedItem((String) opt.getDefaultValue());
1291         val.addActionListener(this);
1292         add(val, BorderLayout.SOUTH);
1293       }
1294       // TODO: add actionListeners for popup (to open further info),
1295       // and to update list of parameters if an option is enabled
1296       // that takes a value.
1297       setInitialValue();
1298     }
1299
1300     public void resetToDefault()
1301     {
1302       enabled.setSelected(false);
1303       if (option.isRequired())
1304       {
1305         // Apply default value
1306         selectOption(option, option.getDefaultValue());
1307       }
1308     }
1309
1310     boolean initEnabled = false;
1311
1312     String initVal = null;
1313
1314     public void setInitialValue()
1315     {
1316       initEnabled = enabled.isSelected();
1317       if (option.getPossibleValues() != null
1318               && option.getPossibleValues().size() > 1)
1319       {
1320         initVal = (String) val.getSelectedItem();
1321       }
1322       else
1323       {
1324         initVal = (initEnabled) ? option.getDefaultValue() : null;
1325       }
1326     }
1327
1328     public OptionI getOptionIfEnabled()
1329     {
1330       if (!enabled.isSelected())
1331       {
1332         return null;
1333       }
1334       OptionI opt = option.copy();
1335
1336       if (val.getSelectedItem() != null)
1337       {
1338         opt.setDefaultValue((String) val.getSelectedItem());
1339       }
1340       return opt;
1341     }
1342
1343     public void actionPerformed(ActionEvent e)
1344     {
1345       if (e.getSource() != enabled)
1346       {
1347         enabled.setSelected(true);
1348       }
1349       checkIfModified();
1350     }
1351
1352     private void checkIfModified()
1353     {
1354       boolean notmod = (initEnabled == enabled.isSelected());
1355       if (enabled.isSelected())
1356       {
1357         if (initVal != null)
1358         {
1359           notmod &= initVal.equals(val.getSelectedItem());
1360         }
1361         else
1362         {
1363           // compare against default service setting
1364           notmod &= option.getDefaultValue() == null
1365                   || option.getDefaultValue().equals(val.getSelectedItem());
1366         }
1367       }
1368       else
1369       {
1370         notmod &= initVal == null;
1371       }
1372       argSetModified(this, !notmod);
1373     }
1374
1375     public void mouseClicked(MouseEvent e)
1376     {
1377       if (javax.swing.SwingUtilities.isRightMouseButton(e))
1378       {
1379         showUrlPopUp(this, finfo.toString(), e.getX(), e.getY());
1380       }
1381     }
1382
1383     public void mousePressed(MouseEvent e)
1384     {
1385       // TODO Auto-generated method stub
1386
1387     }
1388
1389     public void mouseReleased(MouseEvent e)
1390     {
1391       // TODO Auto-generated method stub
1392
1393     }
1394
1395     public void mouseEntered(MouseEvent e)
1396     {
1397       // TODO Auto-generated method stub
1398
1399     }
1400
1401     public void mouseExited(MouseEvent e)
1402     {
1403       // TODO Auto-generated method stub
1404
1405     }
1406
1407   }
1408
1409   private OptionBox addOption(OptionI opt)
1410   {
1411     OptionBox cb = optSet.get(opt.getName());
1412     if (cb == null)
1413     {
1414       cb = new OptionBox(opt);
1415       optSet.put(opt.getName(), cb);
1416       jobOptions.add(cb);
1417     }
1418     return cb;
1419   }
1420
1421   public static void showUrlPopUp(JComponent invoker, final String finfo,
1422           int x, int y)
1423   {
1424
1425     JPopupMenu mnu = new JPopupMenu();
1426     JMenuItem mitem = new JMenuItem("View " + finfo);
1427     mitem.addActionListener(new ActionListener()
1428     {
1429
1430       @Override
1431       public void actionPerformed(ActionEvent e)
1432       {
1433         Desktop.showUrl(finfo);
1434
1435       }
1436     });
1437     mnu.add(mitem);
1438     mnu.show(invoker, x, y);
1439   }
1440
1441   protected void refreshParamLayout()
1442   {
1443     FlowLayout fl = new FlowLayout();
1444     paramList.setLayout(fl);
1445     int s = 2 * fl.getVgap();
1446     for (ParamBox pbox : paramSet.values())
1447     {
1448       s += fl.getVgap() + pbox.getBoxHeight(); // getBoxHeight();
1449     }
1450     paramList.setPreferredSize(new Dimension(PARAM_WIDTH, s));
1451     validate();
1452   }
1453
1454   /**
1455    * testing method - grab a service and parameter set and show the window
1456    * 
1457    * @param args
1458    */
1459   public static void main(String[] args)
1460   {
1461     jalview.ws.jws2.Jws2Discoverer disc = jalview.ws.jws2.Jws2Discoverer
1462             .getDiscoverer();
1463     int p = 0;
1464     if (args.length > 3)
1465     {
1466       Vector<String> services = new Vector<String>();
1467       services.addElement(args[p++]);
1468       Jws2Discoverer.setServiceUrls(services);
1469     }
1470     try
1471     {
1472       disc.run();
1473     } catch (Exception e)
1474     {
1475       System.err.println("Aborting. Problem discovering services.");
1476       e.printStackTrace();
1477       return;
1478     }
1479     Jws2Discoverer.Jws2Instance lastserv = null;
1480     for (Jws2Discoverer.Jws2Instance service : disc.getServices())
1481     {
1482       lastserv = service;
1483       if (p >= args.length || service.serviceType.equalsIgnoreCase(args[p]))
1484       {
1485         if (lastserv != null)
1486         {
1487           List<Preset> prl = null;
1488           Preset pr = null;
1489           if (++p < args.length)
1490           {
1491             PresetManager prman = lastserv.getPresets();
1492             if (prman != null)
1493             {
1494               pr = prman.getPresetByName(args[p]);
1495               if (pr == null)
1496               {
1497                 // just grab the last preset.
1498                 prl = prman.getPresets();
1499               }
1500             }
1501           }
1502           else
1503           {
1504             PresetManager prman = lastserv.getPresets();
1505             if (prman != null)
1506             {
1507               prl = prman.getPresets();
1508             }
1509           }
1510           Iterator<Preset> en = (prl == null) ? null : prl.iterator();
1511           while (en != null && en.hasNext())
1512           {
1513             if (en != null)
1514             {
1515               if (!en.hasNext())
1516               {
1517                 en = prl.iterator();
1518               }
1519               pr = en.next();
1520             }
1521             {
1522               System.out.println("Testing opts dupes for "
1523                       + lastserv.getUri() + " : "
1524                       + lastserv.getActionText() + ":" + pr.getName());
1525               List<Option> rg = lastserv.getRunnerConfig().getOptions();
1526               for (Option o : rg)
1527               {
1528                 try
1529                 {
1530                   Option cpy = jalview.ws.jws2.ParameterUtils.copyOption(o);
1531                 } catch (Exception e)
1532                 {
1533                   System.err.println("Failed to copy " + o.getName());
1534                   e.printStackTrace();
1535                 } catch (Error e)
1536                 {
1537                   System.err.println("Failed to copy " + o.getName());
1538                   e.printStackTrace();
1539                 }
1540               }
1541             }
1542             {
1543               System.out.println("Testing param dupes:");
1544               List<Parameter> rg = lastserv.getRunnerConfig()
1545                       .getParameters();
1546               for (Parameter o : rg)
1547               {
1548                 try
1549                 {
1550                   Parameter cpy = jalview.ws.jws2.ParameterUtils
1551                           .copyParameter(o);
1552                 } catch (Exception e)
1553                 {
1554                   System.err.println("Failed to copy " + o.getName());
1555                   e.printStackTrace();
1556                 } catch (Error e)
1557                 {
1558                   System.err.println("Failed to copy " + o.getName());
1559                   e.printStackTrace();
1560                 }
1561               }
1562             }
1563             {
1564               System.out.println("Testing param write:");
1565               List<String> writeparam = null, readparam = null;
1566               try
1567               {
1568                 writeparam = jalview.ws.jws2.ParameterUtils
1569                         .writeParameterSet(
1570                                 pr.getArguments(lastserv.getRunnerConfig()),
1571                                 " ");
1572                 System.out.println("Testing param read :");
1573                 List<Option> pset = jalview.ws.jws2.ParameterUtils
1574                         .processParameters(writeparam,
1575                                 lastserv.getRunnerConfig(), " ");
1576                 readparam = jalview.ws.jws2.ParameterUtils
1577                         .writeParameterSet(pset, " ");
1578                 Iterator<String> o = pr.getOptions().iterator(), s = writeparam
1579                         .iterator(), t = readparam.iterator();
1580                 boolean failed = false;
1581                 while (s.hasNext() && t.hasNext())
1582                 {
1583                   String on = o.next(), sn = s.next(), st = t.next();
1584                   if (!sn.equals(st))
1585                   {
1586                     System.out.println("Original was " + on
1587                             + " Phase 1 wrote " + sn + "\tPhase 2 wrote "
1588                             + st);
1589                     failed = true;
1590                   }
1591                 }
1592                 if (failed)
1593                 {
1594                   System.out.println("Original parameters:\n"
1595                           + pr.getOptions());
1596                   System.out.println("Wrote parameters in first set:\n"
1597                           + writeparam);
1598                   System.out.println("Wrote parameters in second set:\n"
1599                           + readparam);
1600
1601                 }
1602               } catch (Exception e)
1603               {
1604                 e.printStackTrace();
1605               }
1606             }
1607             WsJobParameters pgui = new WsJobParameters(lastserv,
1608                     new JabaPreset(lastserv, pr));
1609             JFrame jf = new JFrame("Parameters for "
1610                     + lastserv.getActionText());
1611             JPanel cont = new JPanel();
1612             // jf.setPreferredSize(new Dimension(600, 800));
1613             cont.add(pgui);
1614             jf.add(cont);
1615             final Thread thr = Thread.currentThread();
1616             jf.addWindowListener(new WindowListener()
1617             {
1618
1619               public void windowActivated(WindowEvent e)
1620               {
1621                 // TODO Auto-generated method stub
1622
1623               }
1624
1625               public void windowClosed(WindowEvent e)
1626               {
1627               }
1628
1629               public void windowClosing(WindowEvent e)
1630               {
1631                 thr.interrupt();
1632
1633               }
1634
1635               public void windowDeactivated(WindowEvent e)
1636               {
1637                 // TODO Auto-generated method stub
1638
1639               }
1640
1641               public void windowDeiconified(WindowEvent e)
1642               {
1643                 // TODO Auto-generated method stub
1644
1645               }
1646
1647               public void windowIconified(WindowEvent e)
1648               {
1649                 // TODO Auto-generated method stub
1650
1651               }
1652
1653               public void windowOpened(WindowEvent e)
1654               {
1655                 // TODO Auto-generated method stub
1656
1657               }
1658
1659             });
1660             jf.setVisible(true);
1661             boolean inter = false;
1662             while (!inter)
1663             {
1664               try
1665               {
1666                 Thread.sleep(10000);
1667               } catch (Exception e)
1668               {
1669                 inter = true;
1670               }
1671               ;
1672             }
1673             jf.dispose();
1674           }
1675         }
1676       }
1677     }
1678   }
1679
1680   public List<ArgumentI> getJobParams()
1681   {
1682     List<ArgumentI> argSet = new ArrayList<ArgumentI>();
1683     // recover options and parameters from GUI
1684     for (OptionBox opts : optSet.values())
1685     {
1686       OptionI opt = opts.getOptionIfEnabled();
1687       if (opt != null)
1688       {
1689         argSet.add(opt);
1690       }
1691     }
1692     for (ParamBox parambox : paramSet.values())
1693     {
1694       ParameterI parm = parambox.getParameter();
1695       if (parm != null)
1696       {
1697         argSet.add(parm);
1698       }
1699     }
1700
1701     return argSet;
1702   }
1703
1704   String lastParmSet = null;
1705
1706   /*
1707    * Hashtable<String, Object[]> editedParams = new Hashtable<String,
1708    * Object[]>();
1709    * 
1710    * store the given parameters in the user parameter set database.
1711    * 
1712    * @param storeSetName - lastParmSet
1713    * 
1714    * @param descr - setDescr.getText()
1715    * 
1716    * @param jobParams - getJobParams()
1717    * 
1718    * private void _storeUserPreset(String storeSetName, String descr,
1719    * List<ArgumentI> jobParams) { // this is a simple hash store. Object[] pset;
1720    * editedParams.put(storeSetName, pset = new Object[3]); pset[0] =
1721    * storeSetName; pset[1] = descr; pset[2] = jobParams; // writeParam("Saving "
1722    * + storeSetName + ": ", jobParams); }
1723    * 
1724    * private void writeParam(String nm, List<ArgumentI> params) { for (ArgumentI
1725    * p : params) { System.out.println(nm + ":" + System.identityHashCode(p) +
1726    * " Name: " + p.getName() + " Value: " + p.getDefaultValue()); } }
1727    * 
1728    * private Object[] _getUserPreset(String setName) { Object[] pset =
1729    * editedParams.get(setName); // if (pset != null) // writeParam("Retrieving "
1730    * + setName + ": ", (List<Argument>) pset[2]); return pset; }
1731    * 
1732    * * remove the given user preset from the preset stash
1733    * 
1734    * @param setName
1735    * 
1736    * private void _deleteUserPreset(String setName) {
1737    * editedParams.remove(setName); }
1738    */
1739
1740   private void syncSetNamesWithStore()
1741   {
1742     int n = 0;
1743     // remove any set names in the drop down menu that aren't either a reserved
1744     // setting, or a user defined or service preset.
1745     Vector items = new Vector();
1746     while (n < setName.getItemCount())
1747     {
1748       String item = (String) setName.getItemAt(n);
1749       if (!item.equals(SVC_DEF) && !paramStore.presetExists(item))
1750       {
1751         setName.removeItemAt(n);
1752       }
1753       else
1754       {
1755         items.addElement(item);
1756         n++;
1757       }
1758     }
1759     if (!items.contains(SVC_DEF))
1760     {
1761       setName.addItem(SVC_DEF);
1762     }
1763     for (WsParamSetI upn : paramStore.getPresets())
1764     {
1765       if (!items.contains(upn.getName()))
1766       {
1767         setName.addItem(upn.getName());
1768       }
1769     }
1770   }
1771
1772   /**
1773    * true if lastParmSet is a user preset
1774    */
1775   boolean isUserPreset = false;
1776
1777   private void reInitDialog(String nextPreset)
1778   {
1779     settingDialog = true;
1780     // updateTable(null,null); // first reset to defaults
1781     WsParamSetI pset = null;
1782     if (nextPreset != null && nextPreset.length() > 0)
1783     {
1784       pset = paramStore.getPreset(nextPreset);
1785     }
1786     if (pset != null)
1787     {
1788       if (pset.isModifiable())
1789       {
1790         isUserPreset = true;
1791         setDescr.setText(pset.getDescription());
1792         updateTable(null, pset.getArguments());
1793         lastParmSet = nextPreset;
1794       }
1795       else
1796       {
1797         isUserPreset = false;
1798         setDescr.setText("");
1799         // must be a default preset from service
1800         updateTable(pset, null);
1801         lastParmSet = nextPreset;
1802       }
1803     }
1804     else
1805     {
1806       isUserPreset = false;
1807       // Service defaults
1808       setDescr.setText("");
1809       updateTable(null, null);
1810       lastParmSet = SVC_DEF;
1811     }
1812
1813     initArgSetModified();
1814     syncSetNamesWithStore();
1815     setName.setSelectedItem(lastParmSet);
1816     validate();
1817     settingDialog = false;
1818
1819   }
1820
1821   String curSetName = null;
1822
1823   public void itemStateChanged(ItemEvent e)
1824   {
1825     if (e.getSource() == setName && e.getStateChange() == e.SELECTED)
1826     {
1827       final String setname = (String) setName.getSelectedItem();
1828       System.out.println("Item state changed for " + setname
1829               + " (handling ? " + !settingDialog + ")");
1830       if (settingDialog)
1831       {
1832         // ignore event
1833         return;
1834       }
1835       if (setname == null)
1836       {
1837         return;
1838       }
1839       javax.swing.SwingUtilities.invokeLater(new Runnable()
1840       {
1841         public void run()
1842         {
1843           doPreferenceComboStateChange(setname);
1844         }
1845       });
1846     }
1847   }
1848
1849   private void doPreferenceComboStateChange(String setname)
1850   {
1851     // user has selected a different item from combo-box
1852     if (isModified())
1853     {
1854       String lsetname = (curSetName != null) ? curSetName : lastParmSet;
1855       if (lsetname.equals(setname))
1856       {
1857         // setname was just edited - so ignore this event.
1858         return;
1859       }
1860       settingDialog = true;
1861       System.out.println("Prompting to save " + lsetname);
1862       if (javax.swing.JOptionPane
1863               .showConfirmDialog(
1864                       this,
1865                       "Parameter set '"
1866                               + lsetname
1867                               + "' is modifed, and your changes will be lost.\nReally change preset ?",
1868                       "Warning: Unsaved Changes",
1869                       javax.swing.JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION)
1870       {
1871         // revert the combobox to the current item
1872         settingDialog = true;
1873         setName.setSelectedItem(lsetname);
1874         settingDialog = false;
1875         // and leave.
1876         return;
1877         // System.out.println("Saving for " + lsetname);
1878         // _storeCurrentPreset(lsetname);
1879
1880       }
1881     }
1882     settingDialog = true;
1883     reInitDialog(setname);
1884     settingDialog = false;
1885
1886   }
1887
1888   private void _renameExistingPreset(String oldName, String curSetName2)
1889   {
1890     paramStore.updatePreset(oldName, curSetName2, setDescr.getText(),
1891             getJobParams());
1892   }
1893
1894   /**
1895    * store current settings as given name. You should then reset gui.
1896    * 
1897    * @param curSetName2
1898    */
1899   private void _storeCurrentPreset(String curSetName2)
1900   {
1901     paramStore.storePreset(curSetName2, setDescr.getText(), getJobParams());
1902   }
1903
1904   private void _updatePreset(String lastParmSet2, String curname)
1905   {
1906     paramStore.updatePreset(lastParmSet2, curname, setDescr.getText(),
1907             getJobParams());
1908
1909   }
1910
1911   /**
1912    * last saved name for this user preset
1913    */
1914   String lastSetName = null;
1915
1916   /**
1917    * last saved value of the description text for this user preset
1918    */
1919   String lastDescrText = null;
1920
1921   public void actionPerformed(ActionEvent e)
1922   {
1923     if (e.getSource() instanceof Component)
1924     {
1925       Component src = (Component) e.getSource();
1926       if (src.getParent() == setName)
1927       {
1928         // rename any existing records we know about for this set.
1929         String newname = (String) e.getActionCommand().trim();
1930         String msg = null;
1931         if (isServicePreset(newname))
1932         {
1933           final String oldname = curSetName != null ? curSetName
1934                   : lastParmSet;
1935           final Component ourframe = this;
1936           settingDialog = true;
1937           setName.getEditor().setItem(oldname);
1938           settingDialog = false;
1939           javax.swing.SwingUtilities.invokeLater(new Runnable()
1940           {
1941             public void run()
1942             {
1943               JOptionPane.showMessageDialog(ourframe,
1944                       "Invalid name - preset already exists.",
1945                       "Invalid name", JOptionPane.WARNING_MESSAGE);
1946             }
1947           });
1948
1949           return;
1950         }
1951         curSetName = newname;
1952         System.err.println("New name for user setting " + curSetName
1953                 + " (was " + setName.getSelectedItem() + ")");
1954         if (curSetName.equals(setName.getSelectedItem()))
1955         {
1956           curSetName = null;
1957         }
1958         if (curSetName != null)
1959         {
1960           argSetModified(setName, true);
1961           return;
1962         }
1963
1964       }
1965     }
1966   }
1967
1968   private void checkDescrModified()
1969   {
1970     if (!settingDialog)
1971     {
1972
1973       argSetModified(
1974               setDescr,
1975               (lastDescrText == null ? setDescr.getText().trim().length() > 0
1976                       : !setDescr.getText().equals(lastDescrText)));
1977
1978     }
1979   }
1980
1981   public void insertUpdate(DocumentEvent e)
1982   {
1983     checkDescrModified();
1984   }
1985
1986   public void removeUpdate(DocumentEvent e)
1987   {
1988     checkDescrModified();
1989   }
1990
1991   public void changedUpdate(DocumentEvent e)
1992   {
1993     checkDescrModified();
1994   }
1995
1996   /**
1997    * 
1998    * @return null or the service preset selected by the user
1999    */
2000   public WsParamSetI getPreset()
2001   {
2002     if (isUserPreset || isModified()
2003             || (lastParmSet != null && lastParmSet.equals(SVC_DEF)))
2004     {
2005       return null;
2006     }
2007     else
2008     {
2009       return paramStore.getPreset(lastParmSet);
2010     }
2011   }
2012 }