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;
46 import com.sun.xml.internal.ws.streaming.TidyXMLStreamReader;
53 * @version $Revision: 1.155 $
55 public class Desktop extends jalview.jbgui.GDesktop implements
56 DropTargetListener, ClipboardOwner, IProgressIndicator, jalview.api.StructureSelectionManagerProvider
59 private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
62 * news reader - null if it was never started.
64 private BlogReader jvnews=null;
68 * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.beans.PropertyChangeListener)
70 public void addJalviewPropertyChangeListener(
71 PropertyChangeListener listener)
73 changeSupport.addJalviewPropertyChangeListener(listener);
79 * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.lang.String,
80 * java.beans.PropertyChangeListener)
82 public void addJalviewPropertyChangeListener(String propertyName,
83 PropertyChangeListener listener)
85 changeSupport.addJalviewPropertyChangeListener(propertyName, listener);
91 * @see jalview.gui.JalviewChangeSupport#removeJalviewPropertyChangeListener(java.lang.String,
92 * java.beans.PropertyChangeListener)
94 public void removeJalviewPropertyChangeListener(String propertyName,
95 PropertyChangeListener listener)
97 changeSupport.removeJalviewPropertyChangeListener(propertyName,
101 /** Singleton Desktop instance */
102 public static Desktop instance;
104 public static MyDesktopPane desktop;
106 static int openFrameCount = 0;
108 static final int xOffset = 30;
110 static final int yOffset = 30;
112 public static jalview.ws.jws1.Discoverer discoverer;
114 public static Object[] jalviewClipboard;
116 public static boolean internalCopy = false;
118 static int fileLoadingCount = 0;
120 class MyDesktopManager implements DesktopManager
123 private DesktopManager delegate;
125 public MyDesktopManager(DesktopManager delegate)
127 this.delegate = delegate;
130 public void activateFrame(JInternalFrame f)
134 delegate.activateFrame(f);
135 } catch (NullPointerException npe)
137 Point p = getMousePosition();
138 instance.showPasteMenu(p.x, p.y);
142 public void beginDraggingFrame(JComponent f)
144 delegate.beginDraggingFrame(f);
147 public void beginResizingFrame(JComponent f, int direction)
149 delegate.beginResizingFrame(f, direction);
152 public void closeFrame(JInternalFrame f)
154 delegate.closeFrame(f);
157 public void deactivateFrame(JInternalFrame f)
159 delegate.deactivateFrame(f);
162 public void deiconifyFrame(JInternalFrame f)
164 delegate.deiconifyFrame(f);
167 public void dragFrame(JComponent f, int newX, int newY)
169 delegate.dragFrame(f, newX, newY);
172 public void endDraggingFrame(JComponent f)
174 delegate.endDraggingFrame(f);
177 public void endResizingFrame(JComponent f)
179 delegate.endResizingFrame(f);
182 public void iconifyFrame(JInternalFrame f)
184 delegate.iconifyFrame(f);
187 public void maximizeFrame(JInternalFrame f)
189 delegate.maximizeFrame(f);
192 public void minimizeFrame(JInternalFrame f)
194 delegate.minimizeFrame(f);
197 public void openFrame(JInternalFrame f)
199 delegate.openFrame(f);
202 public void resizeFrame(JComponent f, int newX, int newY, int newWidth,
205 delegate.resizeFrame(f, newX, newY, newWidth, newHeight);
208 public void setBoundsForFrame(JComponent f, int newX, int newY,
209 int newWidth, int newHeight)
211 delegate.setBoundsForFrame(f, newX, newY, newWidth, newHeight);
214 // All other methods, simply delegate
219 * Creates a new Desktop object.
224 * A note to implementors. It is ESSENTIAL that any activities that might
225 * block are spawned off as threads rather than waited for during this
229 doVamsasClientCheck();
232 setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
233 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
234 boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",
236 boolean showjconsole = jalview.bin.Cache.getDefault(
237 "SHOW_JAVA_CONSOLE", false);
238 desktop = new MyDesktopPane(selmemusage);
239 showMemusage.setSelected(selmemusage);
240 desktop.setBackground(Color.white);
241 getContentPane().setLayout(new BorderLayout());
242 // alternate config - have scrollbars - see notes in JAL-153
243 //JScrollPane sp = new JScrollPane();
244 //sp.getViewport().setView(desktop);
245 //getContentPane().add(sp, BorderLayout.CENTER);
246 getContentPane().add(desktop, BorderLayout.CENTER);
247 desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
249 // This line prevents Windows Look&Feel resizing all new windows to maximum
250 // if previous window was maximised
251 desktop.setDesktopManager(new MyDesktopManager(
252 new DefaultDesktopManager()));
253 Rectangle dims = getLastKnownDimensions("");
260 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
261 setBounds((int) (screenSize.width - 900) / 2,
262 (int) (screenSize.height - 650) / 2, 900, 650);
264 jconsole = new Console(this, showjconsole);
265 // add essential build information
266 jconsole.setHeader("Jalview Desktop "
267 + jalview.bin.Cache.getProperty("VERSION") + "\n"
269 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown") + "\n"
270 + "Java version: " + System.getProperty("java.version") + "\n"
271 + System.getProperty("os.arch") + " "
272 + System.getProperty("os.name") + " "
273 + System.getProperty("os.version"));
275 showConsole(showjconsole);
277 showNews.setVisible(false);
278 final Desktop me = this;
279 // Thread off the news reader, in case there are connection problems.
280 new Thread( new Runnable() {
284 jvnews = new BlogReader(me);
285 showNews.setVisible(true);
289 this.addWindowListener(new WindowAdapter()
291 public void windowClosing(WindowEvent evt)
297 this.addMouseListener(new MouseAdapter()
299 public void mousePressed(MouseEvent evt)
301 if (SwingUtilities.isRightMouseButton(evt))
303 showPasteMenu(evt.getX(), evt.getY());
307 this.addFocusListener(new FocusListener()
311 public void focusLost(FocusEvent e)
313 // TODO Auto-generated method stub
318 public void focusGained(FocusEvent e)
320 Cache.log.debug("Relaying windows after focus gain");
321 // make sure that we sort windows properly after we gain focus
322 instance.relayerWindows();
325 this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
326 // Spawn a thread that shows the splashscreen
327 SwingUtilities.invokeLater(new Runnable()
336 // Thread off a new instance of the file chooser - this reduces the time it
337 // takes to open it later on.
338 new Thread(new Runnable()
342 Cache.log.debug("Filechooser init thread started.");
343 JalviewFileChooser chooser = new JalviewFileChooser(
344 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
345 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
346 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
347 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
348 Cache.log.debug("Filechooser init thread finished.");
351 // Add the service change listener
352 changeSupport.addJalviewPropertyChangeListener("services",
353 new PropertyChangeListener()
357 public void propertyChange(PropertyChangeEvent evt)
359 Cache.log.debug("Firing service changed event for "
360 + evt.getNewValue());
361 JalviewServicesChanged(evt);
367 protected void showNews_actionPerformed(ActionEvent e)
369 showNews(showNews.isSelected());
371 void showNews(boolean visible)
374 jvnews.setVisible(visible);
375 showNews.setSelected(visible);
378 jvnews.refreshNews();
380 // try real hard to get focus when the news is first opened
381 new Thread(new Runnable() {
385 while (jvnews.isVisible() && !jvnews.requestFocusInWindow())
387 try { Thread.sleep(50); } catch (InterruptedException x) {};
397 * recover the last known dimensions for a jalview window
400 * - empty string is desktop, all other windows have unique prefix
401 * @return null or last known dimensions scaled to current geometry (if last
402 * window geom was known)
404 Rectangle getLastKnownDimensions(String windowName)
406 // TODO: lock aspect ratio for scaling desktop Bug #0058199
407 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
408 String x = jalview.bin.Cache.getProperty(windowName + "SCREEN_X");
409 String y = jalview.bin.Cache.getProperty(windowName + "SCREEN_Y");
410 String width = jalview.bin.Cache.getProperty(windowName
412 String height = jalview.bin.Cache.getProperty(windowName
414 if ((x != null) && (y != null) && (width != null) && (height != null))
416 int ix = Integer.parseInt(x), iy = Integer.parseInt(y), iw = Integer
417 .parseInt(width), ih = Integer.parseInt(height);
418 if (jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
420 // attempt #1 - try to cope with change in screen geometry - this
421 // version doesn't preserve original jv aspect ratio.
422 // take ratio of current screen size vs original screen size.
423 double sw = ((1f * screenSize.width) / (1f * Integer
424 .parseInt(jalview.bin.Cache
425 .getProperty("SCREENGEOMETRY_WIDTH"))));
426 double sh = ((1f * screenSize.height) / (1f * Integer
427 .parseInt(jalview.bin.Cache
428 .getProperty("SCREENGEOMETRY_HEIGHT"))));
429 // rescale the bounds depending upon the current screen geometry.
430 ix = (int) (ix * sw);
431 iw = (int) (iw * sw);
432 iy = (int) (iy * sh);
433 ih = (int) (ih * sh);
434 while (ix >= screenSize.width)
436 jalview.bin.Cache.log
437 .debug("Window geometry location recall error: shifting horizontal to within screenbounds.");
438 ix -= screenSize.width;
440 while (iy >= screenSize.height)
442 jalview.bin.Cache.log
443 .debug("Window geometry location recall error: shifting vertical to within screenbounds.");
444 iy -= screenSize.height;
446 jalview.bin.Cache.log.debug("Got last known dimensions for "
447 + windowName + ": x:" + ix + " y:" + iy + " width:" + iw
450 // return dimensions for new instance
451 return new Rectangle(ix, iy, iw, ih);
456 private void doVamsasClientCheck()
458 if (jalview.bin.Cache.vamsasJarsPresent())
460 setupVamsasDisconnectedGui();
461 VamsasMenu.setVisible(true);
462 final Desktop us = this;
463 VamsasMenu.addMenuListener(new MenuListener()
465 // this listener remembers when the menu was first selected, and
466 // doesn't rebuild the session list until it has been cleared and
468 boolean refresh = true;
470 public void menuCanceled(MenuEvent e)
475 public void menuDeselected(MenuEvent e)
480 public void menuSelected(MenuEvent e)
484 us.buildVamsasStMenu();
489 vamsasStart.setVisible(true);
493 void showPasteMenu(int x, int y)
495 JPopupMenu popup = new JPopupMenu();
496 JMenuItem item = new JMenuItem("Paste To New Window");
497 item.addActionListener(new ActionListener()
499 public void actionPerformed(ActionEvent evt)
506 popup.show(this, x, y);
513 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
514 Transferable contents = c.getContents(this);
516 if (contents != null)
518 String file = (String) contents
519 .getTransferData(DataFlavor.stringFlavor);
521 String format = new IdentifyFile().Identify(file,
522 FormatAdapter.PASTE);
524 new FileLoader().LoadFile(file, FormatAdapter.PASTE, format);
527 } catch (Exception ex)
530 .println("Unable to paste alignment from system clipboard:\n"
536 * Adds and opens the given frame to the desktop
547 public static synchronized void addInternalFrame(
548 final JInternalFrame frame, String title, int w, int h)
550 addInternalFrame(frame, title, w, h, true);
567 public static synchronized void addInternalFrame(
568 final JInternalFrame frame, String title, int w, int h,
572 // TODO: allow callers to determine X and Y position of frame (eg. via
574 // TODO: consider fixing method to update entries in the window submenu with
575 // the current window title
577 frame.setTitle(title);
578 if (frame.getWidth() < 1 || frame.getHeight() < 1)
582 // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
583 // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
584 // IF JALVIEW IS RUNNING HEADLESS
585 // ///////////////////////////////////////////////
586 if (System.getProperty("java.awt.headless") != null
587 && System.getProperty("java.awt.headless").equals("true"))
594 frame.setVisible(true);
595 frame.setClosable(true);
596 frame.setResizable(resizable);
597 frame.setMaximizable(resizable);
598 frame.setIconifiable(resizable);
599 frame.setFrameIcon(null);
601 if (frame.getX() < 1 && frame.getY() < 1)
603 frame.setLocation(xOffset * openFrameCount, yOffset
604 * ((openFrameCount - 1) % 10) + yOffset);
607 final JMenuItem menuItem = new JMenuItem(title);
608 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
610 public void internalFrameActivated(
611 javax.swing.event.InternalFrameEvent evt)
613 JInternalFrame itf = desktop.getSelectedFrame();
621 public void internalFrameClosed(
622 javax.swing.event.InternalFrameEvent evt)
624 PaintRefresher.RemoveComponent(frame);
626 windowMenu.remove(menuItem);
627 JInternalFrame itf = desktop.getSelectedFrame();
636 menuItem.addActionListener(new ActionListener()
638 public void actionPerformed(ActionEvent e)
642 frame.setSelected(true);
643 frame.setIcon(false);
644 } catch (java.beans.PropertyVetoException ex)
650 menuItem.addMouseListener(new MouseListener()
654 public void mouseReleased(MouseEvent e)
659 public void mousePressed(MouseEvent e)
664 public void mouseExited(MouseEvent e)
668 frame.setSelected(false);
669 } catch (PropertyVetoException e1)
675 public void mouseEntered(MouseEvent e)
679 frame.setSelected(true);
680 } catch (PropertyVetoException e1)
686 public void mouseClicked(MouseEvent e)
692 windowMenu.add(menuItem);
698 frame.setSelected(true);
699 frame.requestFocus();
700 } catch (java.beans.PropertyVetoException ve)
703 catch (java.lang.ClassCastException cex)
705 Cache.log.warn("Squashed a possible GUI implementation error. If you can recreate this, please look at http://issues.jalview.org/browse/JAL-869",cex);
709 public void lostOwnership(Clipboard clipboard, Transferable contents)
713 Desktop.jalviewClipboard = null;
716 internalCopy = false;
719 public void dragEnter(DropTargetDragEvent evt)
723 public void dragExit(DropTargetEvent evt)
727 public void dragOver(DropTargetDragEvent evt)
731 public void dropActionChanged(DropTargetDragEvent evt)
741 public void drop(DropTargetDropEvent evt)
743 Transferable t = evt.getTransferable();
744 java.util.List files = null;
745 java.util.List protocols = null;
749 DataFlavor uriListFlavor = new DataFlavor(
750 "text/uri-list;class=java.lang.String");
751 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
753 // Works on Windows and MacOSX
754 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
755 files = (java.util.List) t
756 .getTransferData(DataFlavor.javaFileListFlavor);
758 else if (t.isDataFlavorSupported(uriListFlavor))
760 // This is used by Unix drag system
761 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
762 String data = (String) t.getTransferData(uriListFlavor);
763 files = new java.util.ArrayList(1);
764 protocols = new java.util.ArrayList(1);
765 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
766 data, "\r\n"); st.hasMoreTokens();)
768 String s = st.nextToken();
769 if (s.startsWith("#"))
771 // the line is a comment (as per the RFC 2483)
774 java.net.URI uri = new java.net.URI(s);
775 if (uri.getScheme().toLowerCase().startsWith("http"))
777 protocols.add(FormatAdapter.URL);
778 files.add(uri.toString());
782 // otherwise preserve old behaviour: catch all for file objects
783 java.io.File file = new java.io.File(uri);
784 protocols.add(FormatAdapter.FILE);
785 files.add(file.toString());
789 } catch (Exception e)
797 for (int i = 0; i < files.size(); i++)
799 String file = files.get(i).toString();
800 String protocol = (protocols == null) ? FormatAdapter.FILE
801 : (String) protocols.get(i);
802 String format = null;
804 if (file.endsWith(".jar"))
811 format = new IdentifyFile().Identify(file, protocol);
814 new FileLoader().LoadFile(file, protocol, format);
817 } catch (Exception ex)
829 public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
831 JalviewFileChooser chooser = new JalviewFileChooser(
832 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
833 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
834 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
835 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
837 chooser.setFileView(new JalviewFileView());
838 chooser.setDialogTitle("Open local file");
839 chooser.setToolTipText("Open");
841 int value = chooser.showOpenDialog(this);
843 if (value == JalviewFileChooser.APPROVE_OPTION)
845 String choice = chooser.getSelectedFile().getPath();
846 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
847 .getSelectedFile().getParent());
849 String format = null;
850 if (chooser.getSelectedFormat().equals("Jalview"))
856 format = new IdentifyFile().Identify(choice, FormatAdapter.FILE);
859 if (viewport != null)
861 new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE,
866 new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
877 public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
879 // This construct allows us to have a wider textfield
881 JLabel label = new JLabel("Enter URL of Input File");
882 final JComboBox history = new JComboBox();
884 JPanel panel = new JPanel(new GridLayout(2, 1));
887 history.setPreferredSize(new Dimension(400, 20));
888 history.setEditable(true);
889 history.addItem("http://www.");
891 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
895 if (historyItems != null)
897 st = new StringTokenizer(historyItems, "\t");
899 while (st.hasMoreTokens())
901 history.addItem(st.nextElement());
905 int reply = JOptionPane.showInternalConfirmDialog(desktop, panel,
906 "Input Alignment From URL", JOptionPane.OK_CANCEL_OPTION);
908 if (reply != JOptionPane.OK_OPTION)
913 String url = history.getSelectedItem().toString();
915 if (url.toLowerCase().endsWith(".jar"))
917 if (viewport != null)
919 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL,
924 new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
929 String format = new IdentifyFile().Identify(url, FormatAdapter.URL);
931 if (format.equals("URL NOT FOUND"))
933 JOptionPane.showInternalMessageDialog(Desktop.desktop,
934 "Couldn't locate " + url, "URL not found",
935 JOptionPane.WARNING_MESSAGE);
940 if (viewport != null)
942 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
946 new FileLoader().LoadFile(url, FormatAdapter.URL, format);
957 public void inputTextboxMenuItem_actionPerformed(AlignViewport viewport)
959 CutAndPasteTransfer cap = new CutAndPasteTransfer();
960 cap.setForInput(viewport);
961 Desktop.addInternalFrame(cap, "Cut & Paste Alignment File", 600, 500);
969 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
971 .setProperty("SCREENGEOMETRY_WIDTH", screen.width + "");
972 jalview.bin.Cache.setProperty("SCREENGEOMETRY_HEIGHT", screen.height
974 storeLastKnownDimensions("", new Rectangle(getBounds().x,
975 getBounds().y, getWidth(), getHeight()));
977 if (jconsole != null)
979 storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
980 jconsole.stopConsole();
984 storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
991 private void storeLastKnownDimensions(String string, Rectangle jc)
993 jalview.bin.Cache.log.debug("Storing last known dimensions for "
994 + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
995 + " height:" + jc.height);
997 jalview.bin.Cache.setProperty(string + "SCREEN_X", jc.x + "");
998 jalview.bin.Cache.setProperty(string + "SCREEN_Y", jc.y + "");
999 jalview.bin.Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
1000 jalview.bin.Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
1009 public void aboutMenuItem_actionPerformed(ActionEvent e)
1011 StringBuffer message = new StringBuffer("Jalview version "
1012 + jalview.bin.Cache.getProperty("VERSION") + "; last updated: "
1013 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1015 if (!jalview.bin.Cache.getProperty("LATEST_VERSION").equals(
1016 jalview.bin.Cache.getProperty("VERSION")))
1018 message.append("\n\n!! Jalview version "
1019 + jalview.bin.Cache.getProperty("LATEST_VERSION")
1020 + " is available for download from "+jalview.bin.Cache.getDefault("www.jalview.org","http://www.jalview.org")+" !!\n");
1023 // TODO: update this text for each release or centrally store it for lite
1025 message.append("\nAuthors: Jim Procter, Andrew Waterhouse, Michele Clamp, James Cuff, Steve Searle,\n David Martin & Geoff Barton."
1026 + "\nDevelopment managed by The Barton Group, University of Dundee, Scotland, UK.\n"
1027 + "\nFor help, see the FAQ at www.jalview.org and/or join the jalview-discuss@jalview.org mailing list\n"
1028 + "\nIf you use Jalview, please cite:"
1029 + "\nWaterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
1030 + "\nJalview Version 2 - a multiple sequence alignment editor and analysis workbench"
1031 + "\nBioinformatics doi: 10.1093/bioinformatics/btp033");
1032 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1034 message.toString(), "About Jalview", JOptionPane.INFORMATION_MESSAGE);
1043 public void documentationMenuItem_actionPerformed(ActionEvent e)
1047 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
1048 java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
1049 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
1051 javax.help.HelpBroker hb = hs.createHelpBroker();
1052 hb.setCurrentID("home");
1053 hb.setDisplayed(true);
1054 } catch (Exception ex)
1059 public void closeAll_actionPerformed(ActionEvent e)
1061 JInternalFrame[] frames = desktop.getAllFrames();
1062 for (int i = 0; i < frames.length; i++)
1066 frames[i].setClosed(true);
1067 } catch (java.beans.PropertyVetoException ex)
1071 System.out.println("ALL CLOSED");
1072 if (v_client != null)
1074 // TODO clear binding to vamsas document objects on close_all
1079 public void raiseRelated_actionPerformed(ActionEvent e)
1081 reorderAssociatedWindows(false, false);
1084 public void minimizeAssociated_actionPerformed(ActionEvent e)
1086 reorderAssociatedWindows(true, false);
1089 void closeAssociatedWindows()
1091 reorderAssociatedWindows(false, true);
1097 * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1100 protected void garbageCollect_actionPerformed(ActionEvent e)
1102 // We simply collect the garbage
1103 jalview.bin.Cache.log.debug("Collecting garbage...");
1105 jalview.bin.Cache.log.debug("Finished garbage collection.");
1112 * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
1115 protected void showMemusage_actionPerformed(ActionEvent e)
1117 desktop.showMemoryUsage(showMemusage.isSelected());
1124 * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1127 protected void showConsole_actionPerformed(ActionEvent e)
1129 showConsole(showConsole.isSelected());
1132 Console jconsole = null;
1135 * control whether the java console is visible or not
1139 void showConsole(boolean selected)
1141 showConsole.setSelected(selected);
1142 // TODO: decide if we should update properties file
1143 Cache.setProperty("SHOW_JAVA_CONSOLE", Boolean.valueOf(selected)
1145 jconsole.setVisible(selected);
1148 void reorderAssociatedWindows(boolean minimize, boolean close)
1150 JInternalFrame[] frames = desktop.getAllFrames();
1151 if (frames == null || frames.length < 1)
1156 AlignViewport source = null, target = null;
1157 if (frames[0] instanceof AlignFrame)
1159 source = ((AlignFrame) frames[0]).getCurrentView();
1161 else if (frames[0] instanceof TreePanel)
1163 source = ((TreePanel) frames[0]).getViewPort();
1165 else if (frames[0] instanceof PCAPanel)
1167 source = ((PCAPanel) frames[0]).av;
1169 else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1171 source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1176 for (int i = 0; i < frames.length; i++)
1179 if (frames[i] == null)
1183 if (frames[i] instanceof AlignFrame)
1185 target = ((AlignFrame) frames[i]).getCurrentView();
1187 else if (frames[i] instanceof TreePanel)
1189 target = ((TreePanel) frames[i]).getViewPort();
1191 else if (frames[i] instanceof PCAPanel)
1193 target = ((PCAPanel) frames[i]).av;
1195 else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1197 target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1200 if (source == target)
1206 frames[i].setClosed(true);
1210 frames[i].setIcon(minimize);
1213 frames[i].toFront();
1217 } catch (java.beans.PropertyVetoException ex)
1231 protected void preferences_actionPerformed(ActionEvent e)
1242 public void saveState_actionPerformed(ActionEvent e)
1244 JalviewFileChooser chooser = new JalviewFileChooser(
1245 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1246 { "jar" }, new String[]
1247 { "Jalview Project" }, "Jalview Project");
1249 chooser.setFileView(new JalviewFileView());
1250 chooser.setDialogTitle("Save State");
1252 int value = chooser.showSaveDialog(this);
1254 if (value == JalviewFileChooser.APPROVE_OPTION)
1256 final Desktop me = this;
1257 final java.io.File choice = chooser.getSelectedFile();
1258 new Thread(new Runnable()
1263 setProgressBar("Saving jalview project " + choice.getName(),
1265 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1266 // TODO catch and handle errors for savestate
1267 // TODO prevent user from messing with the Desktop whilst we're saving
1270 new Jalview2XML().SaveState(choice);
1271 } catch (OutOfMemoryError oom)
1274 "Whilst saving current state to " + choice.getName(), oom);
1275 } catch (Exception ex)
1278 .error("Problems whilst trying to save to "
1279 + choice.getName(), ex);
1280 JOptionPane.showMessageDialog(me,
1281 "Error whilst saving current state to " + choice.getName(),
1282 "Couldn't save project", JOptionPane.WARNING_MESSAGE);
1284 setProgressBar(null, choice.hashCode());
1296 public void loadState_actionPerformed(ActionEvent e)
1298 JalviewFileChooser chooser = new JalviewFileChooser(
1299 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1300 { "jar" }, new String[]
1301 { "Jalview Project" }, "Jalview Project");
1302 chooser.setFileView(new JalviewFileView());
1303 chooser.setDialogTitle("Restore state");
1305 int value = chooser.showOpenDialog(this);
1307 if (value == JalviewFileChooser.APPROVE_OPTION)
1309 final String choice = chooser.getSelectedFile().getAbsolutePath();
1310 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
1311 .getSelectedFile().getParent());
1312 new Thread(new Runnable()
1316 setProgressBar("loading jalview project " + choice,
1320 new Jalview2XML().LoadJalviewAlign(choice);
1321 } catch (OutOfMemoryError oom)
1323 new OOMWarning("Whilst loading project from " + choice, oom);
1324 } catch (Exception ex)
1326 Cache.log.error("Problems whilst loading project from "
1328 JOptionPane.showMessageDialog(Desktop.desktop,
1329 "Error whilst loading project from " + choice,
1330 "Couldn't load project", JOptionPane.WARNING_MESSAGE);
1332 setProgressBar(null, choice.hashCode());
1338 public void inputSequence_actionPerformed(ActionEvent e)
1340 new SequenceFetcher(this);
1343 JPanel progressPanel;
1344 ArrayList<JPanel> fileLoadingPanels=new ArrayList<JPanel>();
1345 public void startLoading(final String fileName)
1347 if (fileLoadingCount == 0)
1349 fileLoadingPanels.add(addProgressPanel("Loading File: " + fileName + " "));
1354 private JPanel addProgressPanel(String string)
1356 if (progressPanel == null)
1358 progressPanel = new JPanel(new GridLayout(1,1));
1359 totalProgressCount = 0;
1360 instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
1362 JPanel thisprogress=new JPanel(new BorderLayout(10,5));
1363 JProgressBar progressBar = new JProgressBar();
1364 progressBar.setIndeterminate(true);
1366 thisprogress.add(new JLabel(string), BorderLayout.WEST);
1368 thisprogress.add(progressBar, BorderLayout.CENTER);
1369 progressPanel.add(thisprogress);
1370 ((GridLayout)progressPanel.getLayout()).setRows(((GridLayout)progressPanel.getLayout()).getRows()+1);
1371 ++totalProgressCount;
1372 instance.validate();
1373 return thisprogress;
1376 int totalProgressCount = 0;
1378 private void removeProgressPanel(JPanel progbar)
1380 if (progressPanel != null)
1382 progressPanel.remove(progbar);
1383 GridLayout gl = (GridLayout) progressPanel.getLayout();
1384 gl.setRows(gl.getRows()-1);
1385 if (--totalProgressCount < 1)
1387 this.getContentPane().remove(progressPanel);
1388 progressPanel = null;
1394 public void stopLoading()
1397 if (fileLoadingCount < 1)
1399 for (JPanel flp : fileLoadingPanels)
1401 removeProgressPanel(flp);
1403 fileLoadingPanels.clear();
1404 fileLoadingCount = 0;
1409 public static int getViewCount(String alignmentId)
1411 AlignViewport[] aps = getViewports(alignmentId);
1412 return (aps == null) ? 0 : aps.length;
1417 * @param alignmentId
1418 * @return all AlignmentPanels concerning the alignmentId sequence set
1420 public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
1423 if (Desktop.desktop == null)
1425 // no frames created and in headless mode
1426 // TODO: verify that frames are recoverable when in headless mode
1429 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1430 ArrayList aps = new ArrayList();
1431 for (int t = 0; t < frames.length; t++)
1433 if (frames[t] instanceof AlignFrame)
1435 AlignFrame af = (AlignFrame) frames[t];
1436 for (int a = 0; a < af.alignPanels.size(); a++)
1439 .equals(((AlignmentPanel) af.alignPanels.elementAt(a)).av
1440 .getSequenceSetId()))
1442 aps.add(af.alignPanels.elementAt(a));
1447 if (aps.size() == 0)
1451 AlignmentPanel[] vap = new AlignmentPanel[aps.size()];
1452 for (int t = 0; t < vap.length; t++)
1454 vap[t] = (AlignmentPanel) aps.get(t);
1460 * get all the viewports on an alignment.
1462 * @param sequenceSetId
1463 * unique alignment id
1464 * @return all viewports on the alignment bound to sequenceSetId
1466 public static AlignViewport[] getViewports(String sequenceSetId)
1468 Vector viewp = new Vector();
1469 if (desktop != null)
1471 javax.swing.JInternalFrame[] frames = instance.getAllFrames();
1473 for (int t = 0; t < frames.length; t++)
1475 if (frames[t] instanceof AlignFrame)
1477 AlignFrame afr = ((AlignFrame) frames[t]);
1478 if (afr.getViewport().getSequenceSetId().equals(sequenceSetId))
1480 if (afr.alignPanels != null)
1482 for (int a = 0; a < afr.alignPanels.size(); a++)
1484 if (sequenceSetId.equals(((AlignmentPanel) afr.alignPanels
1485 .elementAt(a)).av.getSequenceSetId()))
1487 viewp.addElement(((AlignmentPanel) afr.alignPanels
1494 viewp.addElement(((AlignFrame) frames[t]).getViewport());
1499 if (viewp.size() > 0)
1501 AlignViewport[] vp = new AlignViewport[viewp.size()];
1509 public void explodeViews(AlignFrame af)
1511 int size = af.alignPanels.size();
1517 for (int i = 0; i < size; i++)
1519 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(i);
1520 AlignFrame newaf = new AlignFrame(ap);
1521 if (ap.av.explodedPosition != null
1522 && !ap.av.explodedPosition.equals(af.getBounds()))
1524 newaf.setBounds(ap.av.explodedPosition);
1527 ap.av.gatherViewsHere = false;
1529 addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1530 AlignFrame.DEFAULT_HEIGHT);
1533 af.alignPanels.clear();
1534 af.closeMenuItem_actionPerformed(true);
1538 public void gatherViews(AlignFrame source)
1540 source.viewport.gatherViewsHere = true;
1541 source.viewport.explodedPosition = source.getBounds();
1542 JInternalFrame[] frames = desktop.getAllFrames();
1543 String viewId = source.viewport.sequenceSetID;
1545 for (int t = 0; t < frames.length; t++)
1547 if (frames[t] instanceof AlignFrame && frames[t] != source)
1549 AlignFrame af = (AlignFrame) frames[t];
1550 boolean gatherThis = false;
1551 for (int a = 0; a < af.alignPanels.size(); a++)
1553 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(a);
1554 if (viewId.equals(ap.av.getSequenceSetId()))
1557 ap.av.gatherViewsHere = false;
1558 ap.av.explodedPosition = af.getBounds();
1559 source.addAlignmentPanel(ap, false);
1565 af.alignPanels.clear();
1566 af.closeMenuItem_actionPerformed(true);
1573 jalview.gui.VamsasApplication v_client = null;
1575 public void vamsasImport_actionPerformed(ActionEvent e)
1577 if (v_client == null)
1579 // Load and try to start a session.
1580 JalviewFileChooser chooser = new JalviewFileChooser(
1581 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1583 chooser.setFileView(new JalviewFileView());
1584 chooser.setDialogTitle("Open a saved VAMSAS session");
1585 chooser.setToolTipText("select a vamsas session to be opened as a new vamsas session.");
1587 int value = chooser.showOpenDialog(this);
1589 if (value == JalviewFileChooser.APPROVE_OPTION)
1591 String fle = chooser.getSelectedFile().toString();
1592 if (!vamsasImport(chooser.getSelectedFile()))
1594 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1595 "Couldn't import '" + fle + "' as a new vamsas session.",
1596 "Vamsas Document Import Failed",
1597 JOptionPane.ERROR_MESSAGE);
1603 jalview.bin.Cache.log
1604 .error("Implementation error - load session from a running session is not supported.");
1609 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1612 * @return true if import was a success and a session was started.
1614 public boolean vamsasImport(URL url)
1616 // TODO: create progress bar
1617 if (v_client != null)
1620 jalview.bin.Cache.log
1621 .error("Implementation error - load session from a running session is not supported.");
1627 // copy the URL content to a temporary local file
1628 // TODO: be a bit cleverer here with nio (?!)
1629 File file = File.createTempFile("vdocfromurl", ".vdj");
1630 FileOutputStream fos = new FileOutputStream(file);
1631 BufferedInputStream bis = new BufferedInputStream(url.openStream());
1632 byte[] buffer = new byte[2048];
1634 while ((ln = bis.read(buffer)) > -1)
1636 fos.write(buffer, 0, ln);
1640 v_client = new jalview.gui.VamsasApplication(this, file,
1641 url.toExternalForm());
1642 } catch (Exception ex)
1644 jalview.bin.Cache.log.error(
1645 "Failed to create new vamsas session from contents of URL "
1649 setupVamsasConnectedGui();
1650 v_client.initial_update(); // TODO: thread ?
1651 return v_client.inSession();
1655 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1658 * @return true if import was a success and a session was started.
1660 public boolean vamsasImport(File file)
1662 if (v_client != null)
1665 jalview.bin.Cache.log
1666 .error("Implementation error - load session from a running session is not supported.");
1670 setProgressBar("Importing VAMSAS session from " + file.getName(),
1674 v_client = new jalview.gui.VamsasApplication(this, file, null);
1675 } catch (Exception ex)
1677 setProgressBar("Importing VAMSAS session from " + file.getName(),
1679 jalview.bin.Cache.log.error(
1680 "New vamsas session from existing session file failed:", ex);
1683 setupVamsasConnectedGui();
1684 v_client.initial_update(); // TODO: thread ?
1685 setProgressBar("Importing VAMSAS session from " + file.getName(),
1687 return v_client.inSession();
1690 public boolean joinVamsasSession(String mysesid)
1692 if (v_client != null)
1695 "Trying to join a vamsas session when another is already connected.");
1697 if (mysesid == null)
1699 throw new Error("Invalid vamsas session id.");
1701 v_client = new VamsasApplication(this, mysesid);
1702 setupVamsasConnectedGui();
1703 v_client.initial_update();
1704 return (v_client.inSession());
1707 public void vamsasStart_actionPerformed(ActionEvent e)
1709 if (v_client == null)
1712 // we just start a default session for moment.
1714 * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
1715 * getProperty("LAST_DIRECTORY"));
1717 * chooser.setFileView(new JalviewFileView());
1718 * chooser.setDialogTitle("Load Vamsas file");
1719 * chooser.setToolTipText("Import");
1721 * int value = chooser.showOpenDialog(this);
1723 * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
1724 * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
1726 v_client = new VamsasApplication(this);
1727 setupVamsasConnectedGui();
1728 v_client.initial_update(); // TODO: thread ?
1732 // store current data in session.
1733 v_client.push_update(); // TODO: thread
1737 protected void setupVamsasConnectedGui()
1739 vamsasStart.setText("Session Update");
1740 vamsasSave.setVisible(true);
1741 vamsasStop.setVisible(true);
1742 vamsasImport.setVisible(false); // Document import to existing session is
1743 // not possible for vamsas-client-1.0.
1746 protected void setupVamsasDisconnectedGui()
1748 vamsasSave.setVisible(false);
1749 vamsasStop.setVisible(false);
1750 vamsasImport.setVisible(true);
1751 vamsasStart.setText("New Vamsas Session");
1754 public void vamsasStop_actionPerformed(ActionEvent e)
1756 if (v_client != null)
1758 v_client.end_session();
1760 setupVamsasDisconnectedGui();
1764 protected void buildVamsasStMenu()
1766 if (v_client == null)
1768 String[] sess = null;
1771 sess = VamsasApplication.getSessionList();
1772 } catch (Exception e)
1774 jalview.bin.Cache.log.warn(
1775 "Problem getting current sessions list.", e);
1780 jalview.bin.Cache.log.debug("Got current sessions list: "
1781 + sess.length + " entries.");
1782 VamsasStMenu.removeAll();
1783 for (int i = 0; i < sess.length; i++)
1785 JMenuItem sessit = new JMenuItem();
1786 sessit.setText(sess[i]);
1787 sessit.setToolTipText("Connect to session " + sess[i]);
1788 final Desktop dsktp = this;
1789 final String mysesid = sess[i];
1790 sessit.addActionListener(new ActionListener()
1793 public void actionPerformed(ActionEvent e)
1795 if (dsktp.v_client == null)
1797 Thread rthr = new Thread(new Runnable()
1802 dsktp.v_client = new VamsasApplication(dsktp, mysesid);
1803 dsktp.setupVamsasConnectedGui();
1804 dsktp.v_client.initial_update();
1812 VamsasStMenu.add(sessit);
1814 // don't show an empty menu.
1815 VamsasStMenu.setVisible(sess.length > 0);
1820 jalview.bin.Cache.log.debug("No current vamsas sessions.");
1821 VamsasStMenu.removeAll();
1822 VamsasStMenu.setVisible(false);
1827 // Not interested in the content. Just hide ourselves.
1828 VamsasStMenu.setVisible(false);
1832 public void vamsasSave_actionPerformed(ActionEvent e)
1834 if (v_client != null)
1836 JalviewFileChooser chooser = new JalviewFileChooser(
1837 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1838 { "vdj" }, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
1840 { "Vamsas Document" }, "Vamsas Document");
1842 chooser.setFileView(new JalviewFileView());
1843 chooser.setDialogTitle("Save Vamsas Document Archive");
1845 int value = chooser.showSaveDialog(this);
1847 if (value == JalviewFileChooser.APPROVE_OPTION)
1849 java.io.File choice = chooser.getSelectedFile();
1850 JPanel progpanel = addProgressPanel("Saving VAMSAS Document to "
1851 + choice.getName());
1852 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1853 String warnmsg = null;
1854 String warnttl = null;
1857 v_client.vclient.storeDocument(choice);
1860 warnttl = "Serious Problem saving Vamsas Document";
1861 warnmsg = ex.toString();
1862 jalview.bin.Cache.log.error("Error Whilst saving document to "
1865 } catch (Exception ex)
1867 warnttl = "Problem saving Vamsas Document.";
1868 warnmsg = ex.toString();
1869 jalview.bin.Cache.log.warn("Exception Whilst saving document to "
1873 removeProgressPanel(progpanel);
1874 if (warnmsg != null)
1876 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1878 warnmsg, warnttl, JOptionPane.ERROR_MESSAGE);
1884 JPanel vamUpdate = null;
1887 * hide vamsas user gui bits when a vamsas document event is being handled.
1890 * true to hide gui, false to reveal gui
1892 public void setVamsasUpdate(boolean b)
1894 jalview.bin.Cache.log.debug("Setting gui for Vamsas update "
1895 + (b ? "in progress" : "finished"));
1897 if (vamUpdate != null)
1899 this.removeProgressPanel(vamUpdate);
1903 vamUpdate = this.addProgressPanel("Updating vamsas session");
1905 vamsasStart.setVisible(!b);
1906 vamsasStop.setVisible(!b);
1907 vamsasSave.setVisible(!b);
1910 public JInternalFrame[] getAllFrames()
1912 return desktop.getAllFrames();
1916 * Checks the given url to see if it gives a response indicating that the user
1917 * should be informed of a new questionnaire.
1921 public void checkForQuestionnaire(String url)
1923 UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
1924 // javax.swing.SwingUtilities.invokeLater(jvq);
1925 new Thread(jvq).start();
1929 * Proxy class for JDesktopPane which optionally displays the current memory
1930 * usage and highlights the desktop area with a red bar if free memory runs
1935 public class MyDesktopPane extends JDesktopPane implements Runnable
1938 boolean showMemoryUsage = false;
1942 java.text.NumberFormat df;
1944 float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
1947 public MyDesktopPane(boolean showMemoryUsage)
1949 showMemoryUsage(showMemoryUsage);
1952 public void showMemoryUsage(boolean showMemoryUsage)
1954 this.showMemoryUsage = showMemoryUsage;
1955 if (showMemoryUsage)
1957 Thread worker = new Thread(this);
1962 public boolean isShowMemoryUsage()
1964 return showMemoryUsage;
1969 df = java.text.NumberFormat.getNumberInstance();
1970 df.setMaximumFractionDigits(2);
1971 runtime = Runtime.getRuntime();
1973 while (showMemoryUsage)
1977 maxMemory = runtime.maxMemory() / 1048576f;
1978 allocatedMemory = runtime.totalMemory() / 1048576f;
1979 freeMemory = runtime.freeMemory() / 1048576f;
1980 totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
1982 percentUsage = (totalFreeMemory / maxMemory) * 100;
1984 // if (percentUsage < 20)
1986 // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
1988 // instance.set.setBorder(border1);
1991 // sleep after showing usage
1993 } catch (Exception ex)
1995 ex.printStackTrace();
2000 public void paintComponent(Graphics g)
2002 if (showMemoryUsage && g != null && df != null)
2004 if (percentUsage < 20)
2005 g.setColor(Color.red);
2006 FontMetrics fm = g.getFontMetrics();
2010 "Total Free Memory: " + df.format(totalFreeMemory)
2011 + "MB; Max Memory: " + df.format(maxMemory)
2012 + "MB; " + df.format(percentUsage) + "%", 10,
2013 getHeight() - fm.getHeight());
2021 * fixes stacking order after a modal dialog to ensure windows that should be on top actually are
2023 public void relayerWindows()
2025 if (jvnews!=null && jvnews.isVisible())
2031 protected JMenuItem groovyShell;
2033 public void doGroovyCheck()
2035 if (jalview.bin.Cache.groovyJarsPresent())
2037 groovyShell = new JMenuItem();
2038 groovyShell.setText("Groovy Console...");
2039 groovyShell.addActionListener(new ActionListener()
2041 public void actionPerformed(ActionEvent e)
2043 groovyShell_actionPerformed(e);
2046 toolsMenu.add(groovyShell);
2047 groovyShell.setVisible(true);
2052 * Accessor method to quickly get all the AlignmentFrames loaded.
2054 public static AlignFrame[] getAlignframes()
2056 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2062 Vector avp = new Vector();
2066 for (int i = frames.length - 1; i > -1; i--)
2068 if (frames[i] instanceof AlignFrame)
2070 AlignFrame af = (AlignFrame) frames[i];
2074 } catch (Exception ex)
2076 ex.printStackTrace();
2078 if (avp.size() == 0)
2082 AlignFrame afs[] = new AlignFrame[avp.size()];
2083 for (int i = 0, j = avp.size(); i < j; i++)
2085 afs[i] = (AlignFrame) avp.elementAt(i);
2090 public AppJmol[] getJmols()
2092 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2098 Vector avp = new Vector();
2102 for (int i = frames.length - 1; i > -1; i--)
2104 if (frames[i] instanceof AppJmol)
2106 AppJmol af = (AppJmol) frames[i];
2110 } catch (Exception ex)
2112 ex.printStackTrace();
2114 if (avp.size() == 0)
2118 AppJmol afs[] = new AppJmol[avp.size()];
2119 for (int i = 0, j = avp.size(); i < j; i++)
2121 afs[i] = (AppJmol) avp.elementAt(i);
2128 * Add Groovy Support to Jalview
2130 public void groovyShell_actionPerformed(ActionEvent e)
2132 // use reflection to avoid creating compilation dependency.
2133 if (!jalview.bin.Cache.groovyJarsPresent())
2136 "Implementation Error. Cannot create groovyShell without Groovy on the classpath!");
2140 Class gcClass = Desktop.class.getClassLoader().loadClass(
2141 "groovy.ui.Console");
2142 Constructor gccons = gcClass.getConstructor(null);
2143 java.lang.reflect.Method setvar = gcClass.getMethod("setVariable",
2145 { String.class, Object.class });
2146 java.lang.reflect.Method run = gcClass.getMethod("run", null);
2147 Object gc = gccons.newInstance(null);
2148 setvar.invoke(gc, new Object[]
2149 { "Jalview", this });
2150 run.invoke(gc, null);
2151 } catch (Exception ex)
2153 jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
2155 .showInternalMessageDialog(
2158 "Couldn't create the groovy Shell. Check the error log for the details of what went wrong.",
2159 "Jalview Groovy Support Failed",
2160 JOptionPane.ERROR_MESSAGE);
2165 * Progress bars managed by the IProgressIndicator method.
2167 private Hashtable<Long,JPanel> progressBars;
2168 private Hashtable<Long,IProgressIndicatorHandler> progressBarHandlers;
2173 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2175 public void setProgressBar(String message, long id)
2177 if (progressBars == null)
2179 progressBars = new Hashtable<Long,JPanel>();
2180 progressBarHandlers = new Hashtable<Long,IProgressIndicatorHandler>();
2183 if (progressBars.get(new Long(id)) != null)
2185 JPanel progressPanel = progressBars
2186 .remove(new Long(id));
2187 if (progressBarHandlers.contains(new Long(id)))
2189 progressBarHandlers.remove(new Long(id));
2191 removeProgressPanel(progressPanel);
2195 progressBars.put(new Long(id), addProgressPanel(message));
2202 * @see jalview.gui.IProgressIndicator#registerHandler(long,
2203 * jalview.gui.IProgressIndicatorHandler)
2205 public void registerHandler(final long id,
2206 final IProgressIndicatorHandler handler)
2208 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
2211 "call setProgressBar before registering the progress bar's handler.");
2213 progressBarHandlers.put(new Long(id), handler);
2214 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
2215 if (handler.canCancel())
2217 JButton cancel = new JButton("Cancel");
2218 final IProgressIndicator us = this;
2219 cancel.addActionListener(new ActionListener()
2222 public void actionPerformed(ActionEvent e)
2224 handler.cancelActivity(id);
2227 + ((JLabel) progressPanel.getComponent(0))
2231 progressPanel.add(cancel, BorderLayout.EAST);
2236 * This will return the first AlignFrame viewing AlignViewport av. It will
2237 * break if there are more than one AlignFrames viewing a particular av. This
2240 * @return alignFrame for av
2242 public static AlignFrame getAlignFrameFor(AlignViewport av)
2244 if (desktop != null)
2246 AlignmentPanel[] aps = getAlignmentPanels(av.getSequenceSetId());
2247 for (int panel = 0; aps != null && panel < aps.length; panel++)
2249 if (aps[panel] != null && aps[panel].av == av)
2251 return aps[panel].alignFrame;
2258 public VamsasApplication getVamsasApplication()
2265 * flag set if jalview GUI is being operated programmatically
2267 private boolean inBatchMode = false;
2270 * check if jalview GUI is being operated programmatically
2272 * @return inBatchMode
2274 public boolean isInBatchMode()
2280 * set flag if jalview GUI is being operated programmatically
2282 * @param inBatchMode
2284 public void setInBatchMode(boolean inBatchMode)
2286 this.inBatchMode = inBatchMode;
2289 public void startServiceDiscovery()
2291 startServiceDiscovery(false);
2294 public void startServiceDiscovery(boolean blocking)
2296 boolean alive = true;
2297 Thread t0 = null, t1 = null, t2 = null;
2299 // todo: changesupport handlers need to be transferred
2300 if (discoverer == null)
2302 discoverer = new jalview.ws.jws1.Discoverer();
2303 // register PCS handler for desktop.
2304 discoverer.addPropertyChangeListener(changeSupport);
2306 // JAL-940 - disabled JWS1 service configuration - always start discoverer until we phase out completely
2309 (t0 = new Thread(discoverer)).start();
2314 if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
2316 // EnfinEnvision web service menu entries are rebuild every time the
2317 // menu is shown, so no changeSupport events are needed.
2318 jalview.ws.EnfinEnvision2OneWay.getInstance();
2319 (t1 = new Thread(jalview.ws.EnfinEnvision2OneWay.getInstance()))
2322 } catch (Exception e)
2325 .info("Exception when trying to launch Envision2 workflow discovery.",
2327 Cache.log.info(e.getStackTrace());
2329 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
2331 if (jalview.ws.jws2.Jws2Discoverer.getDiscoverer().isRunning())
2333 jalview.ws.jws2.Jws2Discoverer.getDiscoverer().setAborted(true);
2335 t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer().startDiscoverer(
2341 // TODO: do rest service discovery
2350 } catch (Exception e)
2353 alive = (t1 != null && t1.isAlive())
2354 || (t2 != null && t2.isAlive())
2355 || (t3 != null && t3.isAlive())
2356 || (t0 != null && t0.isAlive());
2362 * called to check if the service discovery process completed successfully.
2366 protected void JalviewServicesChanged(PropertyChangeEvent evt)
2368 if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
2370 final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2371 .getErrorMessages();
2374 if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
2376 if (serviceChangedDialog == null)
2378 // only run if we aren't already displaying one of these.
2379 javax.swing.SwingUtilities
2380 .invokeLater(serviceChangedDialog = new Runnable()
2386 .showInternalMessageDialog(
2389 + "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",
2390 "Preferences Problem",
2391 JOptionPane.WARNING_MESSAGE);
2392 serviceChangedDialog = null;
2401 .error("Errors reported by JABA discovery service. Check web services preferences.\n"
2408 private Runnable serviceChangedDialog = null;
2411 * start a thread to open a URL in the configured browser. Pops up a warning
2412 * dialog to the user if there is an exception when calling out to the browser
2417 public static void showUrl(final String url)
2419 showUrl(url, Desktop.instance);
2422 * Like showUrl but allows progress handler to be specified
2424 * @param progress (null) or object implementing IProgressIndicator
2426 public static void showUrl(final String url, final IProgressIndicator progress)
2428 new Thread(new Runnable()
2434 if (progress!=null) {
2435 progress.setProgressBar("Opening "+url, this.hashCode());
2437 jalview.util.BrowserLauncher.openURL(url);
2438 } catch (Exception ex)
2441 .showInternalMessageDialog(
2443 "Unixers: Couldn't find default web browser."
2444 + "\nAdd the full path to your browser in Preferences.",
2445 "Web browser not found",
2446 JOptionPane.WARNING_MESSAGE);
2448 ex.printStackTrace();
2450 if (progress!=null) {
2451 progress.setProgressBar(null, this.hashCode());
2457 public static WsParamSetManager wsparamManager = null;
2459 public static ParamManager getUserParameterStore()
2461 if (wsparamManager == null)
2463 wsparamManager = new WsParamSetManager();
2465 return wsparamManager;