2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3 * Copyright (C) 2014 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.
26 import java.awt.event.*;
27 import java.awt.image.*;
29 import javax.swing.event.HyperlinkEvent;
30 import javax.swing.event.HyperlinkListener;
31 import javax.swing.text.html.HTMLEditorKit;
32 import javax.swing.text.html.StyleSheet;
34 import jalview.jbgui.*;
35 import jalview.util.MessageManager;
36 import jalview.ws.WSClientI;
39 * Base class for web service client thread and gui TODO: create StAX parser to
40 * extract html body content reliably when preparing html formatted job statuses
45 public class WebserviceInfo extends GWebserviceInfo implements
46 HyperlinkListener, IProgressIndicator
50 public static final int STATE_QUEUING = 0;
53 public static final int STATE_RUNNING = 1;
55 /** Job has finished with no errors */
56 public static final int STATE_STOPPED_OK = 2;
58 /** Job has been cancelled with no errors */
59 public static final int STATE_CANCELLED_OK = 3;
61 /** job has stopped because of some error */
62 public static final int STATE_STOPPED_ERROR = 4;
64 /** job has failed because of some unavoidable service interruption */
65 public static final int STATE_STOPPED_SERVERERROR = 5;
67 int currentStatus = STATE_QUEUING;
75 jalview.ws.WSClientI thisService;
77 boolean serviceIsCancellable;
81 JTabbedPane subjobs = null;
83 java.util.Vector jobPanes = null;
85 private boolean serviceCanMergeResults = false;
87 private boolean viewResultsImmediatly = true;
93 * to indicate if results will be shown in a new window as soon as
96 public boolean isViewResultsImmediatly()
98 return viewResultsImmediatly;
105 * to indicate if results will be shown in a new window as soon as
106 * they are available.
108 public void setViewResultsImmediatly(boolean viewResultsImmediatly)
110 this.viewResultsImmediatly = viewResultsImmediatly;
113 private StyleSheet getStyleSheet(HTMLEditorKit editorKit)
116 // Copied blatantly from
117 // http://www.velocityreviews.com/forums/t132265-string-into-htmldocument.html
118 StyleSheet myStyleSheet = new StyleSheet();
120 myStyleSheet.addStyleSheet(editorKit.getStyleSheet());
122 editorKit.setStyleSheet(myStyleSheet);
125 * Set the style sheet rules here by reading them from the constants
129 * for (int ix=0; ix<CSS_RULES.length; ix++) {
131 * myStyleSheet.addRule(CSS_RULES[ix]);
140 public synchronized int addJobPane()
142 JScrollPane jobpane = new JScrollPane();
143 JComponent _progressText;
146 JEditorPane progressText = new JEditorPane("text/html", "");
147 progressText.addHyperlinkListener(this);
148 _progressText = progressText;
149 // progressText.setFont(new java.awt.Font("Verdana", 0, 10));
150 // progressText.setBorder(null);
151 progressText.setEditable(false);
153 * HTMLEditorKit myEditorKit = new HTMLEditorKit();
155 * StyleSheet myStyleSheet = getStyleSheet(myEditorKit);
157 * HTMLDocument tipDocument = (HTMLDocument)
158 * (myEditorKit.createDefaultDocument());
160 * progressText.setDocument(tipDocument);
161 */progressText.setText("<html><h1>WS Job</h1></html>");
165 JTextArea progressText = new JTextArea();
166 _progressText = progressText;
168 progressText.setFont(new java.awt.Font("Verdana", 0, 10));
169 progressText.setBorder(null);
170 progressText.setEditable(false);
171 progressText.setText("WS Job");
172 progressText.setLineWrap(true);
173 progressText.setWrapStyleWord(true);
175 jobpane.setName("JobPane");
176 jobpane.getViewport().add(_progressText, null);
177 jobpane.setBorder(null);
178 if (jobPanes == null)
180 jobPanes = new Vector();
182 int newpane = jobPanes.size();
183 jobPanes.add(jobpane);
187 this.add(jobpane, BorderLayout.CENTER);
193 // revert to a tabbed pane.
194 JScrollPane firstpane;
195 this.remove(firstpane = (JScrollPane) jobPanes.get(0));
196 subjobs = new JTabbedPane();
197 this.add(subjobs, BorderLayout.CENTER);
198 subjobs.add(firstpane);
199 subjobs.setTitleAt(0, firstpane.getName());
201 subjobs.add(jobpane);
203 return newpane; // index for accessor methods below
207 * Creates a new WebserviceInfo object.
210 * short name and job type
212 * reference or other human readable description
214 public WebserviceInfo(String title, String info)
216 init(title, info, 520, 500);
220 * Creates a new WebserviceInfo object.
231 public WebserviceInfo(String title, String info, int width, int height)
233 init(title, info, width, height);
239 * @return DOCUMENT ME!
241 public jalview.ws.WSClientI getthisService()
247 * Update state of GUI based on client capabilities (like whether the job is
248 * cancellable, whether the 'merge results' button is shown.
251 * service client to query for capabilities
253 public void setthisService(jalview.ws.WSClientI newservice)
255 thisService = newservice;
256 serviceIsCancellable = newservice.isCancellable();
257 frame.setClosable(!serviceIsCancellable);
258 serviceCanMergeResults = newservice.canMergeResults();
259 rebuildButtonPanel();
262 private void rebuildButtonPanel()
264 if (buttonPanel != null)
266 buttonPanel.removeAll();
267 if (serviceIsCancellable)
269 buttonPanel.add(cancel);
270 frame.setClosable(false);
274 frame.setClosable(true);
291 void init(String title, String info, int width, int height)
293 frame = new JInternalFrame();
294 frame.setContentPane(this);
295 Desktop.addInternalFrame(frame, title, width, height);
296 frame.setClosable(false);
301 java.net.URL url = getClass().getResource(
302 "/images/Jalview_Logo_small.png");
303 image = java.awt.Toolkit.getDefaultToolkit().createImage(url);
305 MediaTracker mt = new MediaTracker(this);
306 mt.addImage(image, 0);
311 } catch (Exception ex)
315 AnimatedPanel ap = new AnimatedPanel();
316 titlePanel.add(ap, BorderLayout.CENTER);
318 Thread thread = new Thread(ap);
320 final WebserviceInfo thisinfo = this;
321 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
323 public void internalFrameClosed(
324 javax.swing.event.InternalFrameEvent evt)
326 // System.out.println("Shutting down webservice client");
327 WSClientI service = thisinfo.getthisService();
328 if (service != null && service.isCancellable())
342 * integer status from state constants
344 public void setStatus(int status)
346 currentStatus = status;
350 * subjob status indicator
355 public void setStatus(int jobpane, int status)
357 if (jobpane < 0 || jobpane >= jobPanes.size())
359 throw new Error(MessageManager.formatMessage("error.setstatus_called_non_existent_job_pane", new String[]{Integer.valueOf(jobpane).toString()}));
364 setProgressName(jobpane + " - QUEUED", jobpane);
367 setProgressName(jobpane + " - RUNNING", jobpane);
369 case STATE_STOPPED_OK:
370 setProgressName(jobpane + " - FINISHED", jobpane);
372 case STATE_CANCELLED_OK:
373 setProgressName(jobpane + " - CANCELLED", jobpane);
375 case STATE_STOPPED_ERROR:
376 setProgressName(jobpane + " - BROKEN", jobpane);
378 case STATE_STOPPED_SERVERERROR:
379 setProgressName(jobpane + " - ALERT", jobpane);
382 setProgressName(jobpane + " - UNKNOWN STATE", jobpane);
389 * @return DOCUMENT ME!
391 public String getInfoText()
393 return infoText.getText();
402 public void setInfoText(String text)
404 infoText.setText(text);
413 public void appendInfoText(String text)
415 infoText.append(text);
421 * @return DOCUMENT ME!
423 public String getProgressText(int which)
425 if (jobPanes == null)
431 return ((JEditorPane) ((JScrollPane) jobPanes.get(which))
432 .getViewport().getComponent(0)).getText();
436 return ((JTextArea) ((JScrollPane) jobPanes.get(which)).getViewport()
437 .getComponent(0)).getText();
447 public void setProgressText(int which, String text)
449 if (jobPanes == null)
455 ((JEditorPane) ((JScrollPane) jobPanes.get(which)).getViewport()
456 .getComponent(0)).setText(ensureHtmlTagged(text));
460 ((JTextArea) ((JScrollPane) jobPanes.get(which)).getViewport()
461 .getComponent(0)).setText(text);
466 * extract content from <body> content </body>
470 * - set to leave the initial html tag intact
472 * - set to leave the final html tag intact
475 private String getHtmlFragment(String text, boolean leaveFirst,
482 String lowertxt = text.toLowerCase();
483 int htmlpos = leaveFirst ? -1 : lowertxt.indexOf("<body");
485 int htmlend = leaveLast ? -1 : lowertxt.indexOf("</body");
486 int htmlpose = lowertxt.indexOf(">", htmlpos), htmlende = lowertxt
487 .indexOf(">", htmlend);
488 if (htmlend == -1 && htmlpos == -1)
494 return text.substring((htmlpos == -1 ? 0 : htmlpose + 1), htmlend);
496 return text.substring(htmlpos == -1 ? 0 : htmlpose + 1);
500 * very simple routine for adding/ensuring html tags are present in text.
503 * @return properly html tag enclosed text
505 private String ensureHtmlTagged(String text)
511 String lowertxt = text.toLowerCase();
512 int htmlpos = lowertxt.indexOf("<body");
513 int htmlend = lowertxt.indexOf("</body");
514 int doctype = lowertxt.indexOf("<!doctype");
515 int xmltype = lowertxt.indexOf("<?xml");
518 text = text + "</body></html>";
522 if ((doctype > -1 && htmlpos > doctype)
523 || (xmltype > -1 && htmlpos > xmltype))
525 text = "<html><head></head><body>\n" + text.substring(htmlpos - 1);
530 text = "<html><head></head><body>\n" + text;
532 if (text.indexOf("<meta") > -1)
534 System.err.println("HTML COntent: \n" + text
535 + "<< END HTML CONTENT\n");
547 public void appendProgressText(int which, String text)
549 if (jobPanes == null)
555 String txt = getHtmlFragment(
556 ((JEditorPane) ((JScrollPane) jobPanes.get(which))
557 .getViewport().getComponent(0)).getText(), true,
559 ((JEditorPane) ((JScrollPane) jobPanes.get(which)).getViewport()
560 .getComponent(0)).setText(ensureHtmlTagged(txt
561 + getHtmlFragment(text, false, true)));
565 ((JTextArea) ((JScrollPane) jobPanes.get(which)).getViewport()
566 .getComponent(0)).append(text);
571 * setProgressText(0, text)
573 public void setProgressText(String text)
575 setProgressText(0, text);
579 * appendProgressText(0, text)
581 public void appendProgressText(String text)
583 appendProgressText(0, text);
589 public String getProgressText()
591 return getProgressText(0);
595 * get the tab title for a subjob
601 public String getProgressName(int which)
603 if (jobPanes == null)
609 return subjobs.getTitleAt(which);
613 return ((JScrollPane) jobPanes.get(which)).getViewport()
614 .getComponent(0).getName();
619 * set the tab title for a subjob
626 public void setProgressName(String name, int which)
630 subjobs.setTitleAt(which, name);
631 subjobs.revalidate();
634 JScrollPane c = (JScrollPane) jobPanes.get(which);
635 c.getViewport().getComponent(0).setName(name);
640 * Gui action for cancelling the current job, if possible.
645 protected void cancel_actionPerformed(ActionEvent e)
647 if (!serviceIsCancellable)
649 // JBPNote : TODO: We should REALLY just tell the WSClientI to cancel
650 // anyhow - it has to stop threads and clean up
651 // JBPNote : TODO: Instead of a warning, we should have an optional 'Are
653 warnUser(MessageManager.getString("warn.job_cannot_be_cancelled_close_window"),
654 MessageManager.getString("action.cancel_job"));
658 thisService.cancelJob();
660 frame.setClosable(true);
664 * Spawns a thread that pops up a warning dialog box with the given message
670 public void warnUser(final String message, final String title)
672 javax.swing.SwingUtilities.invokeLater(new Runnable()
676 JOptionPane.showInternalMessageDialog(Desktop.desktop, message,
677 title, JOptionPane.WARNING_MESSAGE);
684 * Set up GUI for user to get at results - and possibly automatically display
685 * them if viewResultsImmediatly is set.
687 public void setResultsReady()
689 frame.setClosable(true);
690 buttonPanel.remove(cancel);
691 buttonPanel.add(showResultsNewFrame);
692 if (serviceCanMergeResults)
694 buttonPanel.add(mergeResults);
695 buttonPanel.setLayout(new GridLayout(2, 1, 5, 5));
697 buttonPanel.validate();
699 if (viewResultsImmediatly)
701 showResultsNewFrame.doClick();
706 * called when job has finished but no result objects can be passed back to
709 public void setFinishedNoResults()
711 frame.setClosable(true);
712 buttonPanel.remove(cancel);
713 buttonPanel.validate();
717 class AnimatedPanel extends JPanel implements Runnable
721 BufferedImage offscreen;
725 startTime = System.currentTimeMillis();
727 while (currentStatus < STATE_STOPPED_OK)
733 int units = (int) ((System.currentTimeMillis() - startTime) / 10f);
736 startTime = System.currentTimeMillis();
738 if (currentStatus >= STATE_STOPPED_OK)
744 } catch (Exception ex)
749 cancel.setEnabled(false);
754 if (offscreen == null || offscreen.getWidth(this) != getWidth()
755 || offscreen.getHeight(this) != getHeight())
757 offscreen = new BufferedImage(getWidth(), getHeight(),
758 BufferedImage.TYPE_INT_ARGB);
761 Graphics2D g = (Graphics2D) offscreen.getGraphics();
763 g.setColor(Color.white);
764 g.fillRect(0, 0, getWidth(), getHeight());
766 g.setFont(new Font("Arial", Font.BOLD, 12));
767 g.setColor(Color.black);
769 switch (currentStatus)
773 title.concat(" - ").concat(
774 MessageManager.getString("label.state_queueing")),
781 title.concat(" - ").concat(
782 MessageManager.getString("label.state_running")),
787 case STATE_STOPPED_OK:
789 title.concat(" - ").concat(
790 MessageManager.getString("label.state_completed")),
795 case STATE_CANCELLED_OK:
797 title.concat(" - ").concat(
799 .getString("label.state_job_cancelled")),
804 case STATE_STOPPED_ERROR:
806 title.concat(" - ").concat(
807 MessageManager.getString("label.state_job_error")),
812 case STATE_STOPPED_SERVERERROR:
814 title.concat(" - ").concat(
816 .getString("label.server_error_try_later")),
824 int x = image.getWidth(this) / 2, y = image.getHeight(this) / 2;
825 g.rotate(Math.toRadians(angle), 10 + x, 10 + y);
826 g.drawImage(image, 10, 10, this);
827 g.rotate(-Math.toRadians(angle), 10 + x, 10 + y);
831 public void paintComponent(Graphics g1)
835 g1.drawImage(offscreen, 0, 0, this);
839 boolean renderAsHtml = false;
841 public void setRenderAsHtml(boolean b)
846 public void hyperlinkUpdate(HyperlinkEvent e)
848 Desktop.hyperlinkUpdate(e);
851 // methods for implementing IProgressIndicator
852 // need to refactor to a reusable stub class
853 Hashtable progressBars, progressBarHandlers;
858 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
861 public void setProgressBar(String message, long id)
863 if (progressBars == null)
865 progressBars = new Hashtable();
866 progressBarHandlers = new Hashtable();
869 JPanel progressPanel;
870 Long lId = new Long(id);
871 GridLayout layout = (GridLayout) statusPanel.getLayout();
872 if (progressBars.get(lId) != null)
874 progressPanel = (JPanel) progressBars.get(new Long(id));
875 statusPanel.remove(progressPanel);
876 progressBars.remove(lId);
877 progressPanel = null;
880 statusBar.setText(message);
882 if (progressBarHandlers.contains(lId))
884 progressBarHandlers.remove(lId);
886 layout.setRows(layout.getRows() - 1);
890 progressPanel = new JPanel(new BorderLayout(10, 5));
892 JProgressBar progressBar = new JProgressBar();
893 progressBar.setIndeterminate(true);
895 progressPanel.add(new JLabel(message), BorderLayout.WEST);
896 progressPanel.add(progressBar, BorderLayout.CENTER);
898 layout.setRows(layout.getRows() + 1);
899 statusPanel.add(progressPanel);
901 progressBars.put(lId, progressPanel);
904 // setMenusForViewport();
909 public void registerHandler(final long id,
910 final IProgressIndicatorHandler handler)
912 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
914 throw new Error(MessageManager.getString("error.call_setprogressbar_before_registering_handler"));
916 progressBarHandlers.put(new Long(id), handler);
917 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
918 if (handler.canCancel())
920 JButton cancel = new JButton(
921 MessageManager.getString("action.cancel"));
922 final IProgressIndicator us = this;
923 cancel.addActionListener(new ActionListener()
927 public void actionPerformed(ActionEvent e)
929 handler.cancelActivity(id);
930 us.setProgressBar(MessageManager.formatMessage("label.cancelled_params", new String[]{((JLabel) progressPanel.getComponent(0)).getText()}), id);
933 progressPanel.add(cancel, BorderLayout.EAST);
939 * @return true if any progress bars are still active
942 public boolean operationInProgress()
944 if (progressBars != null && progressBars.size() > 0)