JAL-1365 unified GUI building for AACon and RNAAliFold service clients
[jalview.git] / src / jalview / ws / jws2 / SequenceAnnotationWSClient.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, 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.ws.jws2;
19
20 import jalview.api.AlignCalcWorkerI;
21 import jalview.bin.Cache;
22 import jalview.gui.AlignFrame;
23 import jalview.gui.Desktop;
24 import jalview.gui.JvSwingUtils;
25 import jalview.ws.jws2.dm.AAConSettings;
26 import jalview.ws.jws2.jabaws2.Jws2Instance;
27 import jalview.ws.params.WsParamSetI;
28 import jalview.ws.uimodel.AlignAnalysisUIText;
29
30 import java.awt.event.ActionEvent;
31 import java.awt.event.ActionListener;
32 import java.util.List;
33
34 import javax.swing.JCheckBoxMenuItem;
35 import javax.swing.JMenu;
36 import javax.swing.JMenuItem;
37 import javax.swing.JOptionPane;
38 import javax.swing.event.MenuEvent;
39 import javax.swing.event.MenuListener;
40
41 /**
42  * @author jprocter
43  * 
44  */
45 public class SequenceAnnotationWSClient extends Jws2Client
46 {
47   /**
48    * initialise a client so its attachWSMenuEntry method can be called.
49    */
50   public SequenceAnnotationWSClient()
51   {
52     // TODO Auto-generated constructor stub
53   }
54
55   public SequenceAnnotationWSClient(final Jws2Instance sh,
56           AlignFrame alignFrame, WsParamSetI preset, boolean editParams)
57   {
58     super(alignFrame, preset, null);
59     initSequenceAnnotationWSClient(sh, alignFrame, preset, editParams);
60   }
61
62   // dan think. Do I need to change this method to run RNAalifold through the GUI
63   
64   public void initSequenceAnnotationWSClient(final Jws2Instance sh,
65           AlignFrame alignFrame, WsParamSetI preset, boolean editParams)
66   {
67         // dan changed! dan test. comment out if conditional
68 //    if (alignFrame.getViewport().getAlignment().isNucleotide())
69 //    {
70 //      JOptionPane.showMessageDialog(Desktop.desktop, sh.serviceType
71 //              + " can only be used\nfor amino acid alignments.",
72 //              "Wrong type of sequences!", JOptionPane.WARNING_MESSAGE);
73 //      return;
74 //
75 //    }
76     AlignAnalysisUIText aaui = sh.getAlignAnalysisUI();
77     if (aaui!=null)
78     {
79       Class clientClass = aaui.getClient();
80       
81       // Build an AACon style client - take alignment, return annotation for
82       // columns
83
84       List<AlignCalcWorkerI> clnts = alignFrame.getViewport()
85               .getCalcManager()
86               .getRegisteredWorkersOfClass(clientClass);
87       JabawsAlignCalcWorker worker;
88       if (clnts == null || clnts.size() == 0)
89       {
90         if (!processParams(sh, editParams))
91         {
92           return;
93         }
94         try {
95           worker = (JabawsAlignCalcWorker) (clientClass.getConstructor(
96                   new Class[] { Jws2Instance.class, 
97                           AlignFrame.class, WsParamSetI.class, 
98                           List.class }).newInstance(new Object[] { sh, alignFrame, this.preset, paramset}));
99         } catch (Exception x)
100         {
101           x.printStackTrace();
102           throw new Error("Implementation error",x);
103         }
104         alignFrame
105                 .getViewport()
106                 .getCalcManager()
107                 .registerWorker(
108                         worker);
109         alignFrame.getViewport().getCalcManager().startWorker(worker);
110
111       }
112       else
113       {
114         worker = (JabawsAlignCalcWorker) clnts.get(0);
115         if (editParams)
116         {
117           paramset = worker.getArguments();
118           preset = worker.getPreset();
119         }
120
121         if (!processParams(sh, editParams, true))
122         {
123           return;
124         }
125         // reinstate worker if it was blacklisted (might have happened due to
126         // invalid parameters)
127         alignFrame.getViewport().getCalcManager().workerMayRun(worker);
128         worker.updateParameters(this.preset, paramset);
129       }
130     }
131     if (sh.action.toLowerCase().contains("disorder"))
132     {
133       // build IUPred style client. take sequences, returns annotation per
134       // sequence.
135       if (!processParams(sh, editParams))
136       {
137         return;
138       }
139
140       alignFrame
141               .getViewport()
142               .getCalcManager()
143               .startWorker(
144                       new AADisorderClient(sh, alignFrame, preset, paramset));
145     }
146   }
147
148   public SequenceAnnotationWSClient(AAConSettings fave,
149           AlignFrame alignFrame, boolean b)
150   {
151     super(alignFrame, fave.getPreset(), fave.getJobArgset());
152     initSequenceAnnotationWSClient(fave.getService(), alignFrame,
153             fave.getPreset(), b);
154   }
155
156   /*
157    * (non-Javadoc)
158    * 
159    * @see jalview.ws.jws2.Jws2Client#attachWSMenuEntry(javax.swing.JMenu,
160    * jalview.ws.jws2.jabaws2.Jws2Instance, jalview.gui.AlignFrame)
161    */
162   public void attachWSMenuEntry(JMenu wsmenu, final Jws2Instance service,
163           final AlignFrame alignFrame)
164   {
165     if (registerAAConWSInstance(wsmenu, service, alignFrame)) {
166       // Alignment dependent analysis calculation WS gui
167       return;
168     }
169     boolean hasparams = service.hasParameters();
170     // Assume name ends in WS
171     String calcName = service.serviceType.substring(0,
172             service.serviceType.length() - 2);
173
174     JMenuItem annotservice = new JMenuItem(calcName + " Defaults");
175     annotservice.addActionListener(new ActionListener()
176     {
177
178       @Override
179       public void actionPerformed(ActionEvent e)
180       {
181         new SequenceAnnotationWSClient(service, alignFrame, null, false);
182       }
183     });
184     wsmenu.add(annotservice);
185     if (hasparams)
186     {
187       // only add these menu options if the service has user-modifiable
188       // arguments
189       annotservice = new JMenuItem("Edit settings and run ...");
190       annotservice
191               .setToolTipText("View and change parameters before running calculation");
192
193       annotservice.addActionListener(new ActionListener()
194       {
195         public void actionPerformed(ActionEvent e)
196         {
197           new SequenceAnnotationWSClient(service, alignFrame, null, true);
198         }
199       });
200       wsmenu.add(annotservice);
201       List<WsParamSetI> presets = service.getParamStore().getPresets();
202       if (presets != null && presets.size() > 0)
203       {
204         JMenu presetlist = new JMenu("Run " + calcName + "with preset");
205
206         for (final WsParamSetI preset : presets)
207         {
208           final JMenuItem methodR = new JMenuItem(preset.getName());
209           methodR.setToolTipText("<html><p>"
210                   + JvSwingUtils.wrapTooltip("<strong>"
211                           + (preset.isModifiable() ? "User Preset"
212                                   : "Service Preset") + "</strong><br/>"
213                           + preset.getDescription() + "</p>") + "</html>");
214           methodR.addActionListener(new ActionListener()
215           {
216             public void actionPerformed(ActionEvent e)
217             {
218               new SequenceAnnotationWSClient(service, alignFrame, preset,
219                       false);
220             }
221
222           });
223           presetlist.add(methodR);
224         }
225         wsmenu.add(presetlist);
226       }
227
228     }
229     else
230     {
231       annotservice = new JMenuItem("View documentation");
232       if (service.docUrl != null)
233       {
234         annotservice.addActionListener(new ActionListener()
235         {
236
237           @Override
238           public void actionPerformed(ActionEvent arg0)
239           {
240             Desktop.instance.showUrl(service.docUrl);
241           }
242         });
243         annotservice.setToolTipText("<html>"
244                 + JvSwingUtils.wrapTooltip("View <a href=\""
245                         + service.docUrl + "\">" + service.docUrl + "</a>")
246                 + "</html>");
247         wsmenu.add(annotservice);
248       }
249     }
250   }
251
252   
253   private boolean registerAAConWSInstance(final JMenu wsmenu,
254           final Jws2Instance service, final AlignFrame alignFrame)
255   {
256     final AlignAnalysisUIText aaui = service.getAlignAnalysisUI(); // null ; // AlignAnalysisUIText.aaConGUI.get(service.serviceType.toString());
257     if (aaui==null)
258     {
259       // not an instantaneous calculation GUI type service
260       return false;
261     }
262     // create the instaneous calculation GUI bits and update state if existing GUI elements already present
263     
264     JCheckBoxMenuItem _aaConEnabled = null;
265     for (int i = 0; i < wsmenu.getItemCount(); i++)
266     {
267       JMenuItem item = wsmenu.getItem(i);
268       if (item instanceof JCheckBoxMenuItem
269               && item.getText().equals(aaui.getAAconToggle()))
270       {
271         _aaConEnabled = (JCheckBoxMenuItem) item;
272       }
273     }
274     // is there an aaCon worker already present - if so, set it to use the
275     // given service handle
276     {
277       List<AlignCalcWorkerI> aaconClient = alignFrame.getViewport()
278               .getCalcManager()
279               .getRegisteredWorkersOfClass(aaui.getClient());
280       if (aaconClient != null && aaconClient.size() > 0)
281       {
282         JabawsAlignCalcWorker worker = (JabawsAlignCalcWorker) aaconClient.get(0);
283         if (!worker.service.hosturl.equals(service.hosturl))
284         {
285           // javax.swing.SwingUtilities.invokeLater(new Runnable()
286           {
287             // @Override
288             // public void run()
289             {
290               removeCurrentAAConWorkerFor(aaui, alignFrame);
291               buildCurrentAAConWorkerFor(aaui, alignFrame, service);
292             }
293           }// );
294         }
295       }
296     }
297
298     // is there a service already registered ? there shouldn't be if we are
299     // being called correctly
300     if (_aaConEnabled == null)
301     {
302       final JCheckBoxMenuItem aaConEnabled = new JCheckBoxMenuItem(
303               aaui.getAAconToggle());
304       wsmenu.addMenuListener(new MenuListener()
305       {
306
307         @Override
308         public void menuSelected(MenuEvent arg0)
309         {
310           // TODO: refactor to the implementing class.
311           wsmenu.setEnabled((alignFrame.getViewport().getAlignment()
312                   .isNucleotide() ? aaui.isNa() : aaui.isPr()));
313           List<AlignCalcWorkerI> aaconClient = alignFrame.getViewport()
314                   .getCalcManager()
315                   .getRegisteredWorkersOfClass(aaui.getClient());
316           if (aaconClient != null && aaconClient.size() > 0)
317           {
318             aaConEnabled.setSelected(true);
319           }
320           else
321           {
322             aaConEnabled.setSelected(false);
323           }
324         }
325
326         @Override
327         public void menuDeselected(MenuEvent arg0)
328         {
329           // TODO Auto-generated method stub
330
331         }
332
333         @Override
334         public void menuCanceled(MenuEvent arg0)
335         {
336           // TODO Auto-generated method stub
337
338         }
339       });
340       aaConEnabled.setToolTipText("<html><p>"
341               + JvSwingUtils.wrapTooltip(aaui.getAAconToggleTooltip() + "</p>")
342               + "</html>");
343       aaConEnabled.addActionListener(new ActionListener()
344       {
345         @Override
346         public void actionPerformed(ActionEvent arg0)
347         {
348           List<AlignCalcWorkerI> aaconClient = alignFrame.getViewport()
349                   .getCalcManager()
350                   .getRegisteredWorkersOfClass(aaui.getClient());
351           if (aaconClient != null && aaconClient.size() > 0)
352           {
353             removeCurrentAAConWorkerFor(aaui, alignFrame);
354           }
355           else
356           {
357             buildCurrentAAConWorkerFor(aaui, alignFrame);
358
359           }
360         }
361
362       });
363       wsmenu.add(aaConEnabled);
364       JMenuItem modifyParams = new JMenuItem(aaui.getAAeditSettings());
365       modifyParams.setToolTipText("<html><p>"
366               + JvSwingUtils.wrapTooltip(aaui.getAAeditSettingsTooltip() + "</p>")
367               + "</html>");
368       modifyParams.addActionListener(new ActionListener()
369       {
370
371         @Override
372         public void actionPerformed(ActionEvent arg0)
373         {
374           showAAConAnnotationSettingsFor(aaui, alignFrame);
375         }
376       });
377       wsmenu.add(modifyParams);
378
379     }
380     return true;
381   }
382
383   private static void showAAConAnnotationSettingsFor(final AlignAnalysisUIText aaui, AlignFrame alignFrame)
384   {
385     /*
386      * preferred settings Whether AACon is automatically recalculated Which
387      * AACon server to use What parameters to use
388      */
389     // could actually do a class search for this too
390     AAConSettings fave = (AAConSettings) alignFrame.getViewport()
391             .getCalcIdSettingsFor(aaui.getCalcId());
392     if (fave == null)
393     {
394       fave = createDefaultAAConSettings(aaui);
395     }
396     new SequenceAnnotationWSClient(fave, alignFrame, true);
397
398   }
399
400   private static void buildCurrentAAConWorkerFor(final AlignAnalysisUIText aaui, AlignFrame alignFrame)
401   {
402     buildCurrentAAConWorkerFor(aaui, alignFrame, null);
403   }
404
405   private static void buildCurrentAAConWorkerFor(final AlignAnalysisUIText aaui, AlignFrame alignFrame,
406           Jws2Instance service)
407   {
408     /*
409      * preferred settings Whether AACon is automatically recalculated Which
410      * AACon server to use What parameters to use
411      */
412     AAConSettings fave = (AAConSettings) alignFrame.getViewport()
413             .getCalcIdSettingsFor(aaui.getCalcId());
414     if (fave == null)
415     {
416       fave = createDefaultAAConSettings(aaui, service);
417     }
418     else
419     {
420       if (service != null
421               && !fave.getService().hosturl.equals(service.hosturl))
422       {
423         Cache.log.debug("Changing AACon service to " + service.hosturl
424                 + " from " + fave.getService().hosturl);
425         fave.setService(service);
426       }
427     }
428     new SequenceAnnotationWSClient(fave, alignFrame, false);
429   }
430
431   private static AAConSettings createDefaultAAConSettings(AlignAnalysisUIText aaui)
432   {
433     return createDefaultAAConSettings(aaui, null);
434   }
435
436   private static AAConSettings createDefaultAAConSettings(AlignAnalysisUIText aaui,
437           Jws2Instance service)
438   {
439     if (service != null)
440     {
441       if (!service.serviceType.toString().equals(
442               compbio.ws.client.Services.AAConWS.toString()))
443       {
444         Cache.log
445                 .warn("Ignoring invalid preferred service for AACon calculations (service type was "
446                         + service.serviceType + ")");
447         service = null;
448       }
449       else
450       {
451         // check service is actually in the list of currently avaialable
452         // services
453         if (!Jws2Discoverer.getDiscoverer().getServices().contains(service))
454         {
455           // it isn't ..
456           service = null;
457         }
458       }
459     }
460     if (service == null)
461     {
462       // get the default service for AACon
463       service = Jws2Discoverer.getDiscoverer().getPreferredServiceFor(null,
464               aaui.getServiceType());
465     }
466     if (service == null)
467     {
468       // TODO raise dialog box explaining error, and/or open the JABA
469       // preferences menu.
470       throw new Error("No AACon service found.");
471     }
472     return new AAConSettings(true, service, null, null);
473   }
474
475   private static void removeCurrentAAConWorkerFor(AlignAnalysisUIText aaui, AlignFrame alignFrame)
476   {
477     alignFrame.getViewport().getCalcManager()
478             .removeRegisteredWorkersOfClass(aaui.getClient());
479   }
480 }