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
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 of the License, or (at your option) any later version.
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.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
20 import jalview.bin.Cache;
22 import jalview.ws.params.ParamManager;
25 import java.awt.datatransfer.*;
26 import java.awt.dnd.*;
27 import java.awt.event.*;
28 import java.beans.PropertyChangeEvent;
29 import java.beans.PropertyChangeListener;
30 import java.beans.PropertyVetoException;
31 import java.io.BufferedInputStream;
32 import java.io.BufferedOutputStream;
34 import java.io.FileOutputStream;
35 import java.io.InputStream;
36 import java.lang.reflect.Constructor;
38 import java.net.URLConnection;
39 import java.nio.channels.ReadableByteChannel;
43 import javax.swing.event.MenuEvent;
44 import javax.swing.event.MenuListener;
53 public class Desktop extends jalview.jbgui.GDesktop implements
54 DropTargetListener, ClipboardOwner, IProgressIndicator
57 private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
61 * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.beans.PropertyChangeListener)
63 public void addJalviewPropertyChangeListener(
64 PropertyChangeListener listener)
66 changeSupport.addJalviewPropertyChangeListener(listener);
72 * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.lang.String,
73 * java.beans.PropertyChangeListener)
75 public void addJalviewPropertyChangeListener(String propertyName,
76 PropertyChangeListener listener)
78 changeSupport.addJalviewPropertyChangeListener(propertyName, listener);
84 * @see jalview.gui.JalviewChangeSupport#removeJalviewPropertyChangeListener(java.lang.String,
85 * java.beans.PropertyChangeListener)
87 public void removeJalviewPropertyChangeListener(String propertyName,
88 PropertyChangeListener listener)
90 changeSupport.removeJalviewPropertyChangeListener(propertyName,
94 /** Singleton Desktop instance */
95 public static Desktop instance;
97 public static MyDesktopPane desktop;
99 static int openFrameCount = 0;
101 static final int xOffset = 30;
103 static final int yOffset = 30;
105 public static jalview.ws.jws1.Discoverer discoverer;
107 public static Object[] jalviewClipboard;
109 public static boolean internalCopy = false;
111 static int fileLoadingCount = 0;
113 class MyDesktopManager implements DesktopManager
116 private DesktopManager delegate;
118 public MyDesktopManager(DesktopManager delegate)
120 this.delegate = delegate;
123 public void activateFrame(JInternalFrame f)
127 delegate.activateFrame(f);
128 } catch (NullPointerException npe)
130 Point p = getMousePosition();
131 instance.showPasteMenu(p.x, p.y);
135 public void beginDraggingFrame(JComponent f)
137 delegate.beginDraggingFrame(f);
140 public void beginResizingFrame(JComponent f, int direction)
142 delegate.beginResizingFrame(f, direction);
145 public void closeFrame(JInternalFrame f)
147 delegate.closeFrame(f);
150 public void deactivateFrame(JInternalFrame f)
152 delegate.deactivateFrame(f);
155 public void deiconifyFrame(JInternalFrame f)
157 delegate.deiconifyFrame(f);
160 public void dragFrame(JComponent f, int newX, int newY)
162 delegate.dragFrame(f, newX, newY);
165 public void endDraggingFrame(JComponent f)
167 delegate.endDraggingFrame(f);
170 public void endResizingFrame(JComponent f)
172 delegate.endResizingFrame(f);
175 public void iconifyFrame(JInternalFrame f)
177 delegate.iconifyFrame(f);
180 public void maximizeFrame(JInternalFrame f)
182 delegate.maximizeFrame(f);
185 public void minimizeFrame(JInternalFrame f)
187 delegate.minimizeFrame(f);
190 public void openFrame(JInternalFrame f)
192 delegate.openFrame(f);
195 public void resizeFrame(JComponent f, int newX, int newY, int newWidth,
198 delegate.resizeFrame(f, newX, newY, newWidth, newHeight);
201 public void setBoundsForFrame(JComponent f, int newX, int newY,
202 int newWidth, int newHeight)
204 delegate.setBoundsForFrame(f, newX, newY, newWidth, newHeight);
207 // All other methods, simply delegate
212 * Creates a new Desktop object.
217 * A note to implementors. It is ESSENTIAL that any activities that might
218 * block are spawned off as threads rather than waited for during this
222 doVamsasClientCheck();
225 setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
226 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
227 boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",
229 boolean showjconsole = jalview.bin.Cache.getDefault(
230 "SHOW_JAVA_CONSOLE", false);
231 desktop = new MyDesktopPane(selmemusage);
232 showMemusage.setSelected(selmemusage);
233 desktop.setBackground(Color.white);
234 getContentPane().setLayout(new BorderLayout());
235 getContentPane().add(desktop, BorderLayout.CENTER);
236 desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
238 // This line prevents Windows Look&Feel resizing all new windows to maximum
239 // if previous window was maximised
240 desktop.setDesktopManager(new MyDesktopManager(
241 new DefaultDesktopManager()));
242 Rectangle dims = getLastKnownDimensions("");
249 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
250 setBounds((int) (screenSize.width - 900) / 2,
251 (int) (screenSize.height - 650) / 2, 900, 650);
253 jconsole = new Console(this, showjconsole);
254 // add essential build information
255 jconsole.setHeader("Jalview Desktop "
256 + jalview.bin.Cache.getProperty("VERSION") + "\n"
258 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown") + "\n"
259 + "Java version: " + System.getProperty("java.version") + "\n"
260 + System.getProperty("os.arch") + " "
261 + System.getProperty("os.name") + " "
262 + System.getProperty("os.version"));
264 showConsole(showjconsole);
266 this.addWindowListener(new WindowAdapter()
268 public void windowClosing(WindowEvent evt)
274 this.addMouseListener(new MouseAdapter()
276 public void mousePressed(MouseEvent evt)
278 if (SwingUtilities.isRightMouseButton(evt))
280 showPasteMenu(evt.getX(), evt.getY());
285 this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
286 // Spawn a thread that shows the splashscreen
287 SwingUtilities.invokeLater(new Runnable()
296 // Thread off a new instance of the file chooser - this reduces the time it
297 // takes to open it later on.
298 new Thread(new Runnable()
302 Cache.log.debug("Filechooser init thread started.");
303 JalviewFileChooser chooser = new JalviewFileChooser(
304 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
305 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
306 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
307 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
308 Cache.log.debug("Filechooser init thread finished.");
311 // Add the service change listener
312 changeSupport.addJalviewPropertyChangeListener("services",
313 new PropertyChangeListener()
317 public void propertyChange(PropertyChangeEvent evt)
319 Cache.log.debug("Firing service changed event for "
320 + evt.getNewValue());
321 JalviewServicesChanged(evt);
328 * recover the last known dimensions for a jalview window
331 * - empty string is desktop, all other windows have unique prefix
332 * @return null or last known dimensions scaled to current geometry (if last
333 * window geom was known)
335 Rectangle getLastKnownDimensions(String windowName)
337 // TODO: lock aspect ratio for scaling desktop Bug #0058199
338 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
339 String x = jalview.bin.Cache.getProperty(windowName + "SCREEN_X");
340 String y = jalview.bin.Cache.getProperty(windowName + "SCREEN_Y");
341 String width = jalview.bin.Cache.getProperty(windowName
343 String height = jalview.bin.Cache.getProperty(windowName
345 if ((x != null) && (y != null) && (width != null) && (height != null))
347 int ix = Integer.parseInt(x), iy = Integer.parseInt(y), iw = Integer
348 .parseInt(width), ih = Integer.parseInt(height);
349 if (jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
351 // attempt #1 - try to cope with change in screen geometry - this
352 // version doesn't preserve original jv aspect ratio.
353 // take ratio of current screen size vs original screen size.
354 double sw = ((1f * screenSize.width) / (1f * Integer
355 .parseInt(jalview.bin.Cache
356 .getProperty("SCREENGEOMETRY_WIDTH"))));
357 double sh = ((1f * screenSize.height) / (1f * Integer
358 .parseInt(jalview.bin.Cache
359 .getProperty("SCREENGEOMETRY_HEIGHT"))));
360 // rescale the bounds depending upon the current screen geometry.
361 ix = (int) (ix * sw);
362 iw = (int) (iw * sw);
363 iy = (int) (iy * sh);
364 ih = (int) (ih * sh);
365 while (ix >= screenSize.width)
367 jalview.bin.Cache.log
368 .debug("Window geometry location recall error: shifting horizontal to within screenbounds.");
369 ix -= screenSize.width;
371 while (iy >= screenSize.height)
373 jalview.bin.Cache.log
374 .debug("Window geometry location recall error: shifting vertical to within screenbounds.");
375 iy -= screenSize.height;
377 jalview.bin.Cache.log.debug("Got last known dimensions for "
378 + windowName + ": x:" + ix + " y:" + iy + " width:" + iw
381 // return dimensions for new instance
382 return new Rectangle(ix, iy, iw, ih);
387 private void doVamsasClientCheck()
389 if (jalview.bin.Cache.vamsasJarsPresent())
391 setupVamsasDisconnectedGui();
392 VamsasMenu.setVisible(true);
393 final Desktop us = this;
394 VamsasMenu.addMenuListener(new MenuListener()
396 // this listener remembers when the menu was first selected, and
397 // doesn't rebuild the session list until it has been cleared and
399 boolean refresh = true;
401 public void menuCanceled(MenuEvent e)
406 public void menuDeselected(MenuEvent e)
411 public void menuSelected(MenuEvent e)
415 us.buildVamsasStMenu();
420 vamsasStart.setVisible(true);
424 void showPasteMenu(int x, int y)
426 JPopupMenu popup = new JPopupMenu();
427 JMenuItem item = new JMenuItem("Paste To New Window");
428 item.addActionListener(new ActionListener()
430 public void actionPerformed(ActionEvent evt)
437 popup.show(this, x, y);
444 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
445 Transferable contents = c.getContents(this);
447 if (contents != null)
449 String file = (String) contents
450 .getTransferData(DataFlavor.stringFlavor);
452 String format = new IdentifyFile().Identify(file,
453 FormatAdapter.PASTE);
455 new FileLoader().LoadFile(file, FormatAdapter.PASTE, format);
458 } catch (Exception ex)
461 .println("Unable to paste alignment from system clipboard:\n"
467 * Adds and opens the given frame to the desktop
478 public static synchronized void addInternalFrame(
479 final JInternalFrame frame, String title, int w, int h)
481 addInternalFrame(frame, title, w, h, true);
498 public static synchronized void addInternalFrame(
499 final JInternalFrame frame, String title, int w, int h,
503 // TODO: allow callers to determine X and Y position of frame (eg. via
505 // TODO: consider fixing method to update entries in the window submenu with
506 // the current window title
508 frame.setTitle(title);
509 if (frame.getWidth() < 1 || frame.getHeight() < 1)
513 // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
514 // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
515 // IF JALVIEW IS RUNNING HEADLESS
516 // ///////////////////////////////////////////////
517 if (System.getProperty("java.awt.headless") != null
518 && System.getProperty("java.awt.headless").equals("true"))
525 frame.setVisible(true);
526 frame.setClosable(true);
527 frame.setResizable(resizable);
528 frame.setMaximizable(resizable);
529 frame.setIconifiable(resizable);
530 frame.setFrameIcon(null);
532 if (frame.getX() < 1 && frame.getY() < 1)
534 frame.setLocation(xOffset * openFrameCount, yOffset
535 * ((openFrameCount - 1) % 10) + yOffset);
538 final JMenuItem menuItem = new JMenuItem(title);
539 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
541 public void internalFrameActivated(
542 javax.swing.event.InternalFrameEvent evt)
544 JInternalFrame itf = desktop.getSelectedFrame();
552 public void internalFrameClosed(
553 javax.swing.event.InternalFrameEvent evt)
555 PaintRefresher.RemoveComponent(frame);
557 windowMenu.remove(menuItem);
558 JInternalFrame itf = desktop.getSelectedFrame();
567 menuItem.addActionListener(new ActionListener()
569 public void actionPerformed(ActionEvent e)
573 frame.setSelected(true);
574 frame.setIcon(false);
575 } catch (java.beans.PropertyVetoException ex)
581 menuItem.addMouseListener(new MouseListener()
585 public void mouseReleased(MouseEvent e)
590 public void mousePressed(MouseEvent e)
595 public void mouseExited(MouseEvent e)
599 frame.setSelected(false);
600 } catch (PropertyVetoException e1)
606 public void mouseEntered(MouseEvent e)
610 frame.setSelected(true);
611 } catch (PropertyVetoException e1)
617 public void mouseClicked(MouseEvent e)
623 windowMenu.add(menuItem);
629 frame.setSelected(true);
630 frame.requestFocus();
631 } catch (java.beans.PropertyVetoException ve)
636 public void lostOwnership(Clipboard clipboard, Transferable contents)
640 Desktop.jalviewClipboard = null;
643 internalCopy = false;
646 public void dragEnter(DropTargetDragEvent evt)
650 public void dragExit(DropTargetEvent evt)
654 public void dragOver(DropTargetDragEvent evt)
658 public void dropActionChanged(DropTargetDragEvent evt)
668 public void drop(DropTargetDropEvent evt)
670 Transferable t = evt.getTransferable();
671 java.util.List files = null;
672 java.util.List protocols = null;
676 DataFlavor uriListFlavor = new DataFlavor(
677 "text/uri-list;class=java.lang.String");
678 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
680 // Works on Windows and MacOSX
681 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
682 files = (java.util.List) t
683 .getTransferData(DataFlavor.javaFileListFlavor);
685 else if (t.isDataFlavorSupported(uriListFlavor))
687 // This is used by Unix drag system
688 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
689 String data = (String) t.getTransferData(uriListFlavor);
690 files = new java.util.ArrayList(1);
691 protocols = new java.util.ArrayList(1);
692 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
693 data, "\r\n"); st.hasMoreTokens();)
695 String s = st.nextToken();
696 if (s.startsWith("#"))
698 // the line is a comment (as per the RFC 2483)
701 java.net.URI uri = new java.net.URI(s);
702 if (uri.getScheme().toLowerCase().startsWith("http"))
704 protocols.add(FormatAdapter.URL);
705 files.add(uri.toString());
709 // otherwise preserve old behaviour: catch all for file objects
710 java.io.File file = new java.io.File(uri);
711 protocols.add(FormatAdapter.FILE);
712 files.add(file.toString());
716 } catch (Exception e)
724 for (int i = 0; i < files.size(); i++)
726 String file = files.get(i).toString();
727 String protocol = (protocols == null) ? FormatAdapter.FILE
728 : (String) protocols.get(i);
729 String format = null;
731 if (file.endsWith(".jar"))
738 format = new IdentifyFile().Identify(file, protocol);
741 new FileLoader().LoadFile(file, protocol, format);
744 } catch (Exception ex)
756 public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
758 JalviewFileChooser chooser = new JalviewFileChooser(
759 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
760 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
761 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
762 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
764 chooser.setFileView(new JalviewFileView());
765 chooser.setDialogTitle("Open local file");
766 chooser.setToolTipText("Open");
768 int value = chooser.showOpenDialog(this);
770 if (value == JalviewFileChooser.APPROVE_OPTION)
772 String choice = chooser.getSelectedFile().getPath();
773 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
774 .getSelectedFile().getParent());
776 String format = null;
777 if (chooser.getSelectedFormat().equals("Jalview"))
783 format = new IdentifyFile().Identify(choice, FormatAdapter.FILE);
786 if (viewport != null)
788 new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE,
793 new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
804 public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
806 // This construct allows us to have a wider textfield
808 JLabel label = new JLabel("Enter URL of Input File");
809 final JComboBox history = new JComboBox();
811 JPanel panel = new JPanel(new GridLayout(2, 1));
814 history.setPreferredSize(new Dimension(400, 20));
815 history.setEditable(true);
816 history.addItem("http://www.");
818 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
822 if (historyItems != null)
824 st = new StringTokenizer(historyItems, "\t");
826 while (st.hasMoreTokens())
828 history.addItem(st.nextElement());
832 int reply = JOptionPane.showInternalConfirmDialog(desktop, panel,
833 "Input Alignment From URL", JOptionPane.OK_CANCEL_OPTION);
835 if (reply != JOptionPane.OK_OPTION)
840 String url = history.getSelectedItem().toString();
842 if (url.toLowerCase().endsWith(".jar"))
844 if (viewport != null)
846 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL,
851 new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
856 String format = new IdentifyFile().Identify(url, FormatAdapter.URL);
858 if (format.equals("URL NOT FOUND"))
860 JOptionPane.showInternalMessageDialog(Desktop.desktop,
861 "Couldn't locate " + url, "URL not found",
862 JOptionPane.WARNING_MESSAGE);
867 if (viewport != null)
869 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
873 new FileLoader().LoadFile(url, FormatAdapter.URL, format);
884 public void inputTextboxMenuItem_actionPerformed(AlignViewport viewport)
886 CutAndPasteTransfer cap = new CutAndPasteTransfer();
887 cap.setForInput(viewport);
888 Desktop.addInternalFrame(cap, "Cut & Paste Alignment File", 600, 500);
896 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
898 .setProperty("SCREENGEOMETRY_WIDTH", screen.width + "");
899 jalview.bin.Cache.setProperty("SCREENGEOMETRY_HEIGHT", screen.height
901 storeLastKnownDimensions("", new Rectangle(getBounds().x,
902 getBounds().y, getWidth(), getHeight()));
904 if (jconsole != null)
906 storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
907 jconsole.stopConsole();
912 private void storeLastKnownDimensions(String string, Rectangle jc)
914 jalview.bin.Cache.log.debug("Storing last known dimensions for "
915 + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
916 + " height:" + jc.height);
918 jalview.bin.Cache.setProperty(string + "SCREEN_X", jc.x + "");
919 jalview.bin.Cache.setProperty(string + "SCREEN_Y", jc.y + "");
920 jalview.bin.Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
921 jalview.bin.Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
930 public void aboutMenuItem_actionPerformed(ActionEvent e)
932 StringBuffer message = new StringBuffer("Jalview version "
933 + jalview.bin.Cache.getProperty("VERSION") + "; last updated: "
934 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
936 if (!jalview.bin.Cache.getProperty("LATEST_VERSION").equals(
937 jalview.bin.Cache.getProperty("VERSION")))
939 message.append("\n\n!! Jalview version "
940 + jalview.bin.Cache.getProperty("LATEST_VERSION")
941 + " is available for download from http://www.jalview.org !!\n");
944 // TODO: update this text for each release or centrally store it for lite
946 message.append("\nAuthors: Jim Procter, Andrew Waterhouse, Michele Clamp, James Cuff, Steve Searle,\n David Martin & Geoff Barton."
947 + "\nDevelopment managed by The Barton Group, University of Dundee, Scotland, UK.\n"
948 + "\nFor help, see the FAQ at www.jalview.org and/or join the jalview-discuss@jalview.org mailing list\n"
949 + "\nIf you use Jalview, please cite:"
950 + "\nWaterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
951 + "\nJalview Version 2 - a multiple sequence alignment editor and analysis workbench"
952 + "\nBioinformatics doi: 10.1093/bioinformatics/btp033");
953 JOptionPane.showInternalMessageDialog(Desktop.desktop,
955 message.toString(), "About Jalview", JOptionPane.INFORMATION_MESSAGE);
964 public void documentationMenuItem_actionPerformed(ActionEvent e)
968 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
969 java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
970 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
972 javax.help.HelpBroker hb = hs.createHelpBroker();
973 hb.setCurrentID("home");
974 hb.setDisplayed(true);
975 } catch (Exception ex)
980 public void closeAll_actionPerformed(ActionEvent e)
982 JInternalFrame[] frames = desktop.getAllFrames();
983 for (int i = 0; i < frames.length; i++)
987 frames[i].setClosed(true);
988 } catch (java.beans.PropertyVetoException ex)
992 System.out.println("ALL CLOSED");
993 if (v_client != null)
995 // TODO clear binding to vamsas document objects on close_all
1000 public void raiseRelated_actionPerformed(ActionEvent e)
1002 reorderAssociatedWindows(false, false);
1005 public void minimizeAssociated_actionPerformed(ActionEvent e)
1007 reorderAssociatedWindows(true, false);
1010 void closeAssociatedWindows()
1012 reorderAssociatedWindows(false, true);
1018 * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1021 protected void garbageCollect_actionPerformed(ActionEvent e)
1023 // We simply collect the garbage
1024 jalview.bin.Cache.log.debug("Collecting garbage...");
1026 jalview.bin.Cache.log.debug("Finished garbage collection.");
1033 * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
1036 protected void showMemusage_actionPerformed(ActionEvent e)
1038 desktop.showMemoryUsage(showMemusage.isSelected());
1045 * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1048 protected void showConsole_actionPerformed(ActionEvent e)
1050 showConsole(showConsole.isSelected());
1053 Console jconsole = null;
1056 * control whether the java console is visible or not
1060 void showConsole(boolean selected)
1062 showConsole.setSelected(selected);
1063 // TODO: decide if we should update properties file
1064 Cache.setProperty("SHOW_JAVA_CONSOLE", Boolean.valueOf(selected)
1066 jconsole.setVisible(selected);
1069 void reorderAssociatedWindows(boolean minimize, boolean close)
1071 JInternalFrame[] frames = desktop.getAllFrames();
1072 if (frames == null || frames.length < 1)
1077 AlignViewport source = null, target = null;
1078 if (frames[0] instanceof AlignFrame)
1080 source = ((AlignFrame) frames[0]).getCurrentView();
1082 else if (frames[0] instanceof TreePanel)
1084 source = ((TreePanel) frames[0]).getViewPort();
1086 else if (frames[0] instanceof PCAPanel)
1088 source = ((PCAPanel) frames[0]).av;
1090 else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1092 source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1097 for (int i = 0; i < frames.length; i++)
1100 if (frames[i] == null)
1104 if (frames[i] instanceof AlignFrame)
1106 target = ((AlignFrame) frames[i]).getCurrentView();
1108 else if (frames[i] instanceof TreePanel)
1110 target = ((TreePanel) frames[i]).getViewPort();
1112 else if (frames[i] instanceof PCAPanel)
1114 target = ((PCAPanel) frames[i]).av;
1116 else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1118 target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1121 if (source == target)
1127 frames[i].setClosed(true);
1131 frames[i].setIcon(minimize);
1134 frames[i].toFront();
1138 } catch (java.beans.PropertyVetoException ex)
1152 protected void preferences_actionPerformed(ActionEvent e)
1163 public void saveState_actionPerformed(ActionEvent e)
1165 JalviewFileChooser chooser = new JalviewFileChooser(
1166 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1167 { "jar" }, new String[]
1168 { "Jalview Project" }, "Jalview Project");
1170 chooser.setFileView(new JalviewFileView());
1171 chooser.setDialogTitle("Save State");
1173 int value = chooser.showSaveDialog(this);
1175 if (value == JalviewFileChooser.APPROVE_OPTION)
1177 java.io.File choice = chooser.getSelectedFile();
1178 setProgressBar("Saving jalview project " + choice.getName(),
1180 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1181 // TODO catch and handle errors for savestate
1184 new Jalview2XML().SaveState(choice);
1185 } catch (OutOfMemoryError oom)
1188 "Whilst saving current state to " + choice.getName(), oom);
1189 } catch (Exception ex)
1192 .error("Problems whilst trying to save to "
1193 + choice.getName(), ex);
1194 JOptionPane.showMessageDialog(this,
1195 "Error whilst saving current state to " + choice.getName(),
1196 "Couldn't save project", JOptionPane.WARNING_MESSAGE);
1198 setProgressBar(null, choice.hashCode());
1209 public void loadState_actionPerformed(ActionEvent e)
1211 JalviewFileChooser chooser = new JalviewFileChooser(
1212 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1213 { "jar" }, new String[]
1214 { "Jalview Project" }, "Jalview Project");
1215 chooser.setFileView(new JalviewFileView());
1216 chooser.setDialogTitle("Restore state");
1218 int value = chooser.showOpenDialog(this);
1220 if (value == JalviewFileChooser.APPROVE_OPTION)
1222 final String choice = chooser.getSelectedFile().getAbsolutePath();
1223 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
1224 .getSelectedFile().getParent());
1225 new Thread(new Runnable()
1229 setProgressBar("loading jalview project " + choice,
1233 new Jalview2XML().LoadJalviewAlign(choice);
1234 } catch (OutOfMemoryError oom)
1236 new OOMWarning("Whilst loading project from " + choice, oom);
1237 } catch (Exception ex)
1239 Cache.log.error("Problems whilst loading project from "
1241 JOptionPane.showMessageDialog(Desktop.desktop,
1242 "Error whilst loading project from " + choice,
1243 "Couldn't load project", JOptionPane.WARNING_MESSAGE);
1245 setProgressBar(null, choice.hashCode());
1251 public void inputSequence_actionPerformed(ActionEvent e)
1253 new SequenceFetcher(this);
1256 JPanel progressPanel;
1258 public void startLoading(final String fileName)
1260 if (fileLoadingCount == 0)
1262 addProgressPanel("Loading File: " + fileName + " ");
1268 private JProgressBar addProgressPanel(String string)
1270 if (progressPanel == null)
1272 progressPanel = new JPanel(new BorderLayout());
1273 totalProgressCount = 0;
1275 JProgressBar progressBar = new JProgressBar();
1276 progressBar.setIndeterminate(true);
1278 progressPanel.add(new JLabel(string), BorderLayout.WEST);
1280 progressPanel.add(progressBar, BorderLayout.CENTER);
1282 instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
1283 totalProgressCount++;
1288 int totalProgressCount = 0;
1290 private void removeProgressPanel(JProgressBar progbar)
1292 if (progressPanel != null)
1294 progressPanel.remove(progbar);
1295 if (--totalProgressCount < 1)
1297 this.getContentPane().remove(progressPanel);
1298 progressPanel = null;
1304 public void stopLoading()
1307 if (fileLoadingCount < 1)
1309 if (progressPanel != null)
1311 this.getContentPane().remove(progressPanel);
1312 progressPanel = null;
1314 fileLoadingCount = 0;
1319 public static int getViewCount(String alignmentId)
1321 AlignViewport[] aps = getViewports(alignmentId);
1322 return (aps == null) ? 0 : aps.length;
1327 * @param alignmentId
1328 * @return all AlignmentPanels concerning the alignmentId sequence set
1330 public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
1333 if (Desktop.desktop == null)
1335 // no frames created and in headless mode
1336 // TODO: verify that frames are recoverable when in headless mode
1339 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1340 ArrayList aps = new ArrayList();
1341 for (int t = 0; t < frames.length; t++)
1343 if (frames[t] instanceof AlignFrame)
1345 AlignFrame af = (AlignFrame) frames[t];
1346 for (int a = 0; a < af.alignPanels.size(); a++)
1349 .equals(((AlignmentPanel) af.alignPanels.elementAt(a)).av
1350 .getSequenceSetId()))
1352 aps.add(af.alignPanels.elementAt(a));
1357 if (aps.size() == 0)
1361 AlignmentPanel[] vap = new AlignmentPanel[aps.size()];
1362 for (int t = 0; t < vap.length; t++)
1364 vap[t] = (AlignmentPanel) aps.get(t);
1370 * get all the viewports on an alignment.
1372 * @param sequenceSetId
1373 * unique alignment id
1374 * @return all viewports on the alignment bound to sequenceSetId
1376 public static AlignViewport[] getViewports(String sequenceSetId)
1378 Vector viewp = new Vector();
1379 if (desktop != null)
1381 javax.swing.JInternalFrame[] frames = instance.getAllFrames();
1383 for (int t = 0; t < frames.length; t++)
1385 if (frames[t] instanceof AlignFrame)
1387 AlignFrame afr = ((AlignFrame) frames[t]);
1388 if (afr.getViewport().getSequenceSetId().equals(sequenceSetId))
1390 if (afr.alignPanels != null)
1392 for (int a = 0; a < afr.alignPanels.size(); a++)
1394 if (sequenceSetId.equals(((AlignmentPanel) afr.alignPanels
1395 .elementAt(a)).av.getSequenceSetId()))
1397 viewp.addElement(((AlignmentPanel) afr.alignPanels
1404 viewp.addElement(((AlignFrame) frames[t]).getViewport());
1409 if (viewp.size() > 0)
1411 AlignViewport[] vp = new AlignViewport[viewp.size()];
1419 public void explodeViews(AlignFrame af)
1421 int size = af.alignPanels.size();
1427 for (int i = 0; i < size; i++)
1429 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(i);
1430 AlignFrame newaf = new AlignFrame(ap);
1431 if (ap.av.explodedPosition != null
1432 && !ap.av.explodedPosition.equals(af.getBounds()))
1434 newaf.setBounds(ap.av.explodedPosition);
1437 ap.av.gatherViewsHere = false;
1439 addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1440 AlignFrame.DEFAULT_HEIGHT);
1443 af.alignPanels.clear();
1444 af.closeMenuItem_actionPerformed(true);
1448 public void gatherViews(AlignFrame source)
1450 source.viewport.gatherViewsHere = true;
1451 source.viewport.explodedPosition = source.getBounds();
1452 JInternalFrame[] frames = desktop.getAllFrames();
1453 String viewId = source.viewport.sequenceSetID;
1455 for (int t = 0; t < frames.length; t++)
1457 if (frames[t] instanceof AlignFrame && frames[t] != source)
1459 AlignFrame af = (AlignFrame) frames[t];
1460 boolean gatherThis = false;
1461 for (int a = 0; a < af.alignPanels.size(); a++)
1463 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(a);
1464 if (viewId.equals(ap.av.getSequenceSetId()))
1467 ap.av.gatherViewsHere = false;
1468 ap.av.explodedPosition = af.getBounds();
1469 source.addAlignmentPanel(ap, false);
1475 af.alignPanels.clear();
1476 af.closeMenuItem_actionPerformed(true);
1483 jalview.gui.VamsasApplication v_client = null;
1485 public void vamsasImport_actionPerformed(ActionEvent e)
1487 if (v_client == null)
1489 // Load and try to start a session.
1490 JalviewFileChooser chooser = new JalviewFileChooser(
1491 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1493 chooser.setFileView(new JalviewFileView());
1494 chooser.setDialogTitle("Open a saved VAMSAS session");
1495 chooser.setToolTipText("select a vamsas session to be opened as a new vamsas session.");
1497 int value = chooser.showOpenDialog(this);
1499 if (value == JalviewFileChooser.APPROVE_OPTION)
1501 String fle = chooser.getSelectedFile().toString();
1502 if (!vamsasImport(chooser.getSelectedFile()))
1504 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1505 "Couldn't import '" + fle + "' as a new vamsas session.",
1506 "Vamsas Document Import Failed",
1507 JOptionPane.ERROR_MESSAGE);
1513 jalview.bin.Cache.log
1514 .error("Implementation error - load session from a running session is not supported.");
1519 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1522 * @return true if import was a success and a session was started.
1524 public boolean vamsasImport(URL url)
1526 // TODO: create progress bar
1527 if (v_client != null)
1530 jalview.bin.Cache.log
1531 .error("Implementation error - load session from a running session is not supported.");
1537 // copy the URL content to a temporary local file
1538 // TODO: be a bit cleverer here with nio (?!)
1539 File file = File.createTempFile("vdocfromurl", ".vdj");
1540 FileOutputStream fos = new FileOutputStream(file);
1541 BufferedInputStream bis = new BufferedInputStream(url.openStream());
1542 byte[] buffer = new byte[2048];
1544 while ((ln = bis.read(buffer)) > -1)
1546 fos.write(buffer, 0, ln);
1550 v_client = new jalview.gui.VamsasApplication(this, file,
1551 url.toExternalForm());
1552 } catch (Exception ex)
1554 jalview.bin.Cache.log.error(
1555 "Failed to create new vamsas session from contents of URL "
1559 setupVamsasConnectedGui();
1560 v_client.initial_update(); // TODO: thread ?
1561 return v_client.inSession();
1565 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1568 * @return true if import was a success and a session was started.
1570 public boolean vamsasImport(File file)
1572 if (v_client != null)
1575 jalview.bin.Cache.log
1576 .error("Implementation error - load session from a running session is not supported.");
1580 setProgressBar("Importing VAMSAS session from " + file.getName(),
1584 v_client = new jalview.gui.VamsasApplication(this, file, null);
1585 } catch (Exception ex)
1587 setProgressBar("Importing VAMSAS session from " + file.getName(),
1589 jalview.bin.Cache.log.error(
1590 "New vamsas session from existing session file failed:", ex);
1593 setupVamsasConnectedGui();
1594 v_client.initial_update(); // TODO: thread ?
1595 setProgressBar("Importing VAMSAS session from " + file.getName(),
1597 return v_client.inSession();
1600 public boolean joinVamsasSession(String mysesid)
1602 if (v_client != null)
1605 "Trying to join a vamsas session when another is already connected.");
1607 if (mysesid == null)
1609 throw new Error("Invalid vamsas session id.");
1611 v_client = new VamsasApplication(this, mysesid);
1612 setupVamsasConnectedGui();
1613 v_client.initial_update();
1614 return (v_client.inSession());
1617 public void vamsasStart_actionPerformed(ActionEvent e)
1619 if (v_client == null)
1622 // we just start a default session for moment.
1624 * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
1625 * getProperty("LAST_DIRECTORY"));
1627 * chooser.setFileView(new JalviewFileView());
1628 * chooser.setDialogTitle("Load Vamsas file");
1629 * chooser.setToolTipText("Import");
1631 * int value = chooser.showOpenDialog(this);
1633 * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
1634 * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
1636 v_client = new VamsasApplication(this);
1637 setupVamsasConnectedGui();
1638 v_client.initial_update(); // TODO: thread ?
1642 // store current data in session.
1643 v_client.push_update(); // TODO: thread
1647 protected void setupVamsasConnectedGui()
1649 vamsasStart.setText("Session Update");
1650 vamsasSave.setVisible(true);
1651 vamsasStop.setVisible(true);
1652 vamsasImport.setVisible(false); // Document import to existing session is
1653 // not possible for vamsas-client-1.0.
1656 protected void setupVamsasDisconnectedGui()
1658 vamsasSave.setVisible(false);
1659 vamsasStop.setVisible(false);
1660 vamsasImport.setVisible(true);
1661 vamsasStart.setText("New Vamsas Session");
1664 public void vamsasStop_actionPerformed(ActionEvent e)
1666 if (v_client != null)
1668 v_client.end_session();
1670 setupVamsasDisconnectedGui();
1674 protected void buildVamsasStMenu()
1676 if (v_client == null)
1678 String[] sess = null;
1681 sess = VamsasApplication.getSessionList();
1682 } catch (Exception e)
1684 jalview.bin.Cache.log.warn(
1685 "Problem getting current sessions list.", e);
1690 jalview.bin.Cache.log.debug("Got current sessions list: "
1691 + sess.length + " entries.");
1692 VamsasStMenu.removeAll();
1693 for (int i = 0; i < sess.length; i++)
1695 JMenuItem sessit = new JMenuItem();
1696 sessit.setText(sess[i]);
1697 sessit.setToolTipText("Connect to session " + sess[i]);
1698 final Desktop dsktp = this;
1699 final String mysesid = sess[i];
1700 sessit.addActionListener(new ActionListener()
1703 public void actionPerformed(ActionEvent e)
1705 if (dsktp.v_client == null)
1707 Thread rthr = new Thread(new Runnable()
1712 dsktp.v_client = new VamsasApplication(dsktp, mysesid);
1713 dsktp.setupVamsasConnectedGui();
1714 dsktp.v_client.initial_update();
1722 VamsasStMenu.add(sessit);
1724 // don't show an empty menu.
1725 VamsasStMenu.setVisible(sess.length > 0);
1730 jalview.bin.Cache.log.debug("No current vamsas sessions.");
1731 VamsasStMenu.removeAll();
1732 VamsasStMenu.setVisible(false);
1737 // Not interested in the content. Just hide ourselves.
1738 VamsasStMenu.setVisible(false);
1742 public void vamsasSave_actionPerformed(ActionEvent e)
1744 if (v_client != null)
1746 JalviewFileChooser chooser = new JalviewFileChooser(
1747 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1748 { "vdj" }, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
1750 { "Vamsas Document" }, "Vamsas Document");
1752 chooser.setFileView(new JalviewFileView());
1753 chooser.setDialogTitle("Save Vamsas Document Archive");
1755 int value = chooser.showSaveDialog(this);
1757 if (value == JalviewFileChooser.APPROVE_OPTION)
1759 java.io.File choice = chooser.getSelectedFile();
1760 JProgressBar progpanel = addProgressPanel("Saving VAMSAS Document to "
1761 + choice.getName());
1762 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1763 String warnmsg = null;
1764 String warnttl = null;
1767 v_client.vclient.storeDocument(choice);
1770 warnttl = "Serious Problem saving Vamsas Document";
1771 warnmsg = ex.toString();
1772 jalview.bin.Cache.log.error("Error Whilst saving document to "
1775 } catch (Exception ex)
1777 warnttl = "Problem saving Vamsas Document.";
1778 warnmsg = ex.toString();
1779 jalview.bin.Cache.log.warn("Exception Whilst saving document to "
1783 removeProgressPanel(progpanel);
1784 if (warnmsg != null)
1786 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1788 warnmsg, warnttl, JOptionPane.ERROR_MESSAGE);
1794 JProgressBar vamUpdate = null;
1797 * hide vamsas user gui bits when a vamsas document event is being handled.
1800 * true to hide gui, false to reveal gui
1802 public void setVamsasUpdate(boolean b)
1804 jalview.bin.Cache.log.debug("Setting gui for Vamsas update "
1805 + (b ? "in progress" : "finished"));
1807 if (vamUpdate != null)
1809 this.removeProgressPanel(vamUpdate);
1813 vamUpdate = this.addProgressPanel("Updating vamsas session");
1815 vamsasStart.setVisible(!b);
1816 vamsasStop.setVisible(!b);
1817 vamsasSave.setVisible(!b);
1820 public JInternalFrame[] getAllFrames()
1822 return desktop.getAllFrames();
1826 * Checks the given url to see if it gives a response indicating that the user
1827 * should be informed of a new questionnaire.
1831 public void checkForQuestionnaire(String url)
1833 UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
1834 // javax.swing.SwingUtilities.invokeLater(jvq);
1835 new Thread(jvq).start();
1839 * Proxy class for JDesktopPane which optionally displays the current memory
1840 * usage and highlights the desktop area with a red bar if free memory runs
1845 public class MyDesktopPane extends JDesktopPane implements Runnable
1848 boolean showMemoryUsage = false;
1852 java.text.NumberFormat df;
1854 float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
1857 public MyDesktopPane(boolean showMemoryUsage)
1859 showMemoryUsage(showMemoryUsage);
1862 public void showMemoryUsage(boolean showMemoryUsage)
1864 this.showMemoryUsage = showMemoryUsage;
1865 if (showMemoryUsage)
1867 Thread worker = new Thread(this);
1872 public boolean isShowMemoryUsage()
1874 return showMemoryUsage;
1879 df = java.text.NumberFormat.getNumberInstance();
1880 df.setMaximumFractionDigits(2);
1881 runtime = Runtime.getRuntime();
1883 while (showMemoryUsage)
1887 maxMemory = runtime.maxMemory() / 1048576f;
1888 allocatedMemory = runtime.totalMemory() / 1048576f;
1889 freeMemory = runtime.freeMemory() / 1048576f;
1890 totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
1892 percentUsage = (totalFreeMemory / maxMemory) * 100;
1894 // if (percentUsage < 20)
1896 // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
1898 // instance.set.setBorder(border1);
1901 // sleep after showing usage
1903 } catch (Exception ex)
1905 ex.printStackTrace();
1910 public void paintComponent(Graphics g)
1912 if (showMemoryUsage && g != null && df != null)
1914 if (percentUsage < 20)
1915 g.setColor(Color.red);
1916 FontMetrics fm = g.getFontMetrics();
1920 "Total Free Memory: " + df.format(totalFreeMemory)
1921 + "MB; Max Memory: " + df.format(maxMemory)
1922 + "MB; " + df.format(percentUsage) + "%", 10,
1923 getHeight() - fm.getHeight());
1930 protected JMenuItem groovyShell;
1932 public void doGroovyCheck()
1934 if (jalview.bin.Cache.groovyJarsPresent())
1936 groovyShell = new JMenuItem();
1937 groovyShell.setText("Groovy Console...");
1938 groovyShell.addActionListener(new ActionListener()
1940 public void actionPerformed(ActionEvent e)
1942 groovyShell_actionPerformed(e);
1945 toolsMenu.add(groovyShell);
1946 groovyShell.setVisible(true);
1951 * Accessor method to quickly get all the AlignmentFrames loaded.
1953 public static AlignFrame[] getAlignframes()
1955 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1961 Vector avp = new Vector();
1965 for (int i = frames.length - 1; i > -1; i--)
1967 if (frames[i] instanceof AlignFrame)
1969 AlignFrame af = (AlignFrame) frames[i];
1973 } catch (Exception ex)
1975 ex.printStackTrace();
1977 if (avp.size() == 0)
1981 AlignFrame afs[] = new AlignFrame[avp.size()];
1982 for (int i = 0, j = avp.size(); i < j; i++)
1984 afs[i] = (AlignFrame) avp.elementAt(i);
1989 public AppJmol[] getJmols()
1991 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1997 Vector avp = new Vector();
2001 for (int i = frames.length - 1; i > -1; i--)
2003 if (frames[i] instanceof AppJmol)
2005 AppJmol af = (AppJmol) frames[i];
2009 } catch (Exception ex)
2011 ex.printStackTrace();
2013 if (avp.size() == 0)
2017 AppJmol afs[] = new AppJmol[avp.size()];
2018 for (int i = 0, j = avp.size(); i < j; i++)
2020 afs[i] = (AppJmol) avp.elementAt(i);
2027 * Add Groovy Support to Jalview
2029 public void groovyShell_actionPerformed(ActionEvent e)
2031 // use reflection to avoid creating compilation dependency.
2032 if (!jalview.bin.Cache.groovyJarsPresent())
2035 "Implementation Error. Cannot create groovyShell without Groovy on the classpath!");
2039 Class gcClass = Desktop.class.getClassLoader().loadClass(
2040 "groovy.ui.Console");
2041 Constructor gccons = gcClass.getConstructor(null);
2042 java.lang.reflect.Method setvar = gcClass.getMethod("setVariable",
2044 { String.class, Object.class });
2045 java.lang.reflect.Method run = gcClass.getMethod("run", null);
2046 Object gc = gccons.newInstance(null);
2047 setvar.invoke(gc, new Object[]
2048 { "Jalview", this });
2049 run.invoke(gc, null);
2050 } catch (Exception ex)
2052 jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
2054 .showInternalMessageDialog(
2057 "Couldn't create the groovy Shell. Check the error log for the details of what went wrong.",
2058 "Jalview Groovy Support Failed",
2059 JOptionPane.ERROR_MESSAGE);
2064 * Progress bars managed by the IProgressIndicator method.
2066 private Hashtable progressBars, progressBarHandlers;
2071 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2073 public void setProgressBar(String message, long id)
2075 if (progressBars == null)
2077 progressBars = new Hashtable();
2078 progressBarHandlers = new Hashtable();
2081 if (progressBars.get(new Long(id)) != null)
2083 JProgressBar progressPanel = (JProgressBar) progressBars
2084 .remove(new Long(id));
2085 if (progressBarHandlers.contains(new Long(id)))
2087 progressBarHandlers.remove(new Long(id));
2089 removeProgressPanel(progressPanel);
2093 progressBars.put(new Long(id), addProgressPanel(message));
2100 * @see jalview.gui.IProgressIndicator#registerHandler(long,
2101 * jalview.gui.IProgressIndicatorHandler)
2103 public void registerHandler(final long id,
2104 final IProgressIndicatorHandler handler)
2106 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
2109 "call setProgressBar before registering the progress bar's handler.");
2111 progressBarHandlers.put(new Long(id), handler);
2112 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
2113 if (handler.canCancel())
2115 JButton cancel = new JButton("Cancel");
2116 final IProgressIndicator us = this;
2117 cancel.addActionListener(new ActionListener()
2120 public void actionPerformed(ActionEvent e)
2122 handler.cancelActivity(id);
2125 + ((JLabel) progressPanel.getComponent(0))
2129 progressPanel.add(cancel, BorderLayout.EAST);
2134 * This will return the first AlignFrame viewing AlignViewport av. It will
2135 * break if there are more than one AlignFrames viewing a particular av. This
2138 * @return alignFrame for av
2140 public static AlignFrame getAlignFrameFor(AlignViewport av)
2142 if (desktop != null)
2144 AlignmentPanel[] aps = getAlignmentPanels(av.getSequenceSetId());
2145 for (int panel = 0; aps != null && panel < aps.length; panel++)
2147 if (aps[panel] != null && aps[panel].av == av)
2149 return aps[panel].alignFrame;
2156 public VamsasApplication getVamsasApplication()
2163 * flag set if jalview GUI is being operated programmatically
2165 private boolean inBatchMode = false;
2168 * check if jalview GUI is being operated programmatically
2170 * @return inBatchMode
2172 public boolean isInBatchMode()
2178 * set flag if jalview GUI is being operated programmatically
2180 * @param inBatchMode
2182 public void setInBatchMode(boolean inBatchMode)
2184 this.inBatchMode = inBatchMode;
2187 public void startServiceDiscovery()
2189 startServiceDiscovery(false);
2192 public void startServiceDiscovery(boolean blocking)
2194 boolean alive = true;
2195 Thread t0 = null, t1 = null, t2 = null;
2197 // todo: changesupport handlers need to be transferred
2198 if (discoverer == null)
2200 discoverer = new jalview.ws.jws1.Discoverer();
2201 // register PCS handler for desktop.
2202 discoverer.addPropertyChangeListener(changeSupport);
2204 if (Cache.getDefault("SHOW_JWS1_SERVICES", true))
2206 (t0 = new Thread(discoverer)).start();
2211 if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
2213 // EnfinEnvision web service menu entries are rebuild every time the
2214 // menu is shown, so no changeSupport events are needed.
2215 jalview.ws.EnfinEnvision2OneWay.getInstance();
2216 (t1 = new Thread(jalview.ws.EnfinEnvision2OneWay.getInstance()))
2219 } catch (Exception e)
2222 .info("Exception when trying to launch Envision2 workflow discovery.",
2224 Cache.log.info(e.getStackTrace());
2226 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
2228 if (jalview.ws.jws2.Jws2Discoverer.getDiscoverer().isRunning())
2230 jalview.ws.jws2.Jws2Discoverer.getDiscoverer().setAborted(true);
2232 t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer().startDiscoverer(
2238 // TODO: do rest service discovery
2247 } catch (Exception e)
2250 alive = (t1 != null && t1.isAlive())
2251 || (t2 != null && t2.isAlive())
2252 || (t3 != null && t3.isAlive())
2253 || (t0 != null && t0.isAlive());
2259 * called to check if the service discovery process completed successfully.
2263 protected void JalviewServicesChanged(PropertyChangeEvent evt)
2265 if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
2267 final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2268 .getErrorMessages();
2271 if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
2273 if (serviceChangedDialog == null)
2275 // only run if we aren't already displaying one of these.
2276 javax.swing.SwingUtilities
2277 .invokeLater(serviceChangedDialog = new Runnable()
2283 .showInternalMessageDialog(
2286 + "It may be that you have invalid JABA URLs\nin your web service preferences.\n\nGo to the Web services tab of the\nTools->Preferences dialog box to change them.\n",
2287 "Preferences Problem",
2288 JOptionPane.WARNING_MESSAGE);
2289 serviceChangedDialog = null;
2298 .error("Errors reported by JABA discovery service. Check web services preferences.\n"
2305 private Runnable serviceChangedDialog = null;
2308 * start a thread to open a URL in the configured browser. Pops up a warning
2309 * dialog to the user if there is an exception when calling out to the browser
2314 public static void showUrl(final String url)
2316 showUrl(url, Desktop.instance);
2319 * Like showUrl but allows progress handler to be specified
2321 * @param progress (null) or object implementing IProgressIndicator
2323 public static void showUrl(final String url, final IProgressIndicator progress)
2325 new Thread(new Runnable()
2331 if (progress!=null) {
2332 progress.setProgressBar("Opening "+url, this.hashCode());
2334 jalview.util.BrowserLauncher.openURL(url);
2335 } catch (Exception ex)
2338 .showInternalMessageDialog(
2340 "Unixers: Couldn't find default web browser."
2341 + "\nAdd the full path to your browser in Preferences.",
2342 "Web browser not found",
2343 JOptionPane.WARNING_MESSAGE);
2345 ex.printStackTrace();
2347 if (progress!=null) {
2348 progress.setProgressBar(null, this.hashCode());
2354 public static WsParamSetManager wsparamManager = null;
2356 public static ParamManager getUserParameterStore()
2358 if (wsparamManager == null)
2360 wsparamManager = new WsParamSetManager();
2362 return wsparamManager;