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;
51 * @version $Revision: 1.155 $
53 public class Desktop extends jalview.jbgui.GDesktop implements
54 DropTargetListener, ClipboardOwner, IProgressIndicator, jalview.api.StructureSelectionManagerProvider
57 private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
60 * news reader - null if it was never started.
62 private BlogReader jvnews=null;
66 * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.beans.PropertyChangeListener)
68 public void addJalviewPropertyChangeListener(
69 PropertyChangeListener listener)
71 changeSupport.addJalviewPropertyChangeListener(listener);
77 * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.lang.String,
78 * java.beans.PropertyChangeListener)
80 public void addJalviewPropertyChangeListener(String propertyName,
81 PropertyChangeListener listener)
83 changeSupport.addJalviewPropertyChangeListener(propertyName, listener);
89 * @see jalview.gui.JalviewChangeSupport#removeJalviewPropertyChangeListener(java.lang.String,
90 * java.beans.PropertyChangeListener)
92 public void removeJalviewPropertyChangeListener(String propertyName,
93 PropertyChangeListener listener)
95 changeSupport.removeJalviewPropertyChangeListener(propertyName,
99 /** Singleton Desktop instance */
100 public static Desktop instance;
102 public static MyDesktopPane desktop;
104 static int openFrameCount = 0;
106 static final int xOffset = 30;
108 static final int yOffset = 30;
110 public static jalview.ws.jws1.Discoverer discoverer;
112 public static Object[] jalviewClipboard;
114 public static boolean internalCopy = false;
116 static int fileLoadingCount = 0;
118 class MyDesktopManager implements DesktopManager
121 private DesktopManager delegate;
123 public MyDesktopManager(DesktopManager delegate)
125 this.delegate = delegate;
128 public void activateFrame(JInternalFrame f)
132 delegate.activateFrame(f);
133 } catch (NullPointerException npe)
135 Point p = getMousePosition();
136 instance.showPasteMenu(p.x, p.y);
140 public void beginDraggingFrame(JComponent f)
142 delegate.beginDraggingFrame(f);
145 public void beginResizingFrame(JComponent f, int direction)
147 delegate.beginResizingFrame(f, direction);
150 public void closeFrame(JInternalFrame f)
152 delegate.closeFrame(f);
155 public void deactivateFrame(JInternalFrame f)
157 delegate.deactivateFrame(f);
160 public void deiconifyFrame(JInternalFrame f)
162 delegate.deiconifyFrame(f);
165 public void dragFrame(JComponent f, int newX, int newY)
167 delegate.dragFrame(f, newX, newY);
170 public void endDraggingFrame(JComponent f)
172 delegate.endDraggingFrame(f);
175 public void endResizingFrame(JComponent f)
177 delegate.endResizingFrame(f);
180 public void iconifyFrame(JInternalFrame f)
182 delegate.iconifyFrame(f);
185 public void maximizeFrame(JInternalFrame f)
187 delegate.maximizeFrame(f);
190 public void minimizeFrame(JInternalFrame f)
192 delegate.minimizeFrame(f);
195 public void openFrame(JInternalFrame f)
197 delegate.openFrame(f);
200 public void resizeFrame(JComponent f, int newX, int newY, int newWidth,
203 delegate.resizeFrame(f, newX, newY, newWidth, newHeight);
206 public void setBoundsForFrame(JComponent f, int newX, int newY,
207 int newWidth, int newHeight)
209 delegate.setBoundsForFrame(f, newX, newY, newWidth, newHeight);
212 // All other methods, simply delegate
217 * Creates a new Desktop object.
222 * A note to implementors. It is ESSENTIAL that any activities that might
223 * block are spawned off as threads rather than waited for during this
227 doVamsasClientCheck();
230 setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
231 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
232 boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",
234 boolean showjconsole = jalview.bin.Cache.getDefault(
235 "SHOW_JAVA_CONSOLE", false);
236 desktop = new MyDesktopPane(selmemusage);
237 showMemusage.setSelected(selmemusage);
238 desktop.setBackground(Color.white);
239 getContentPane().setLayout(new BorderLayout());
240 // alternate config - have scrollbars - see notes in JAL-153
241 //JScrollPane sp = new JScrollPane();
242 //sp.getViewport().setView(desktop);
243 //getContentPane().add(sp, BorderLayout.CENTER);
244 getContentPane().add(desktop, BorderLayout.CENTER);
245 desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
247 // This line prevents Windows Look&Feel resizing all new windows to maximum
248 // if previous window was maximised
249 desktop.setDesktopManager(new MyDesktopManager(
250 new DefaultDesktopManager()));
251 Rectangle dims = getLastKnownDimensions("");
258 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
259 setBounds((int) (screenSize.width - 900) / 2,
260 (int) (screenSize.height - 650) / 2, 900, 650);
262 jconsole = new Console(this, showjconsole);
263 // add essential build information
264 jconsole.setHeader("Jalview Desktop "
265 + jalview.bin.Cache.getProperty("VERSION") + "\n"
267 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown") + "\n"
268 + "Java version: " + System.getProperty("java.version") + "\n"
269 + System.getProperty("os.arch") + " "
270 + System.getProperty("os.name") + " "
271 + System.getProperty("os.version"));
273 showConsole(showjconsole);
275 showNews.setVisible(false);
276 final Desktop me = this;
277 // Thread off the news reader, in case there are connection problems.
278 new Thread( new Runnable() {
282 jvnews = new BlogReader(me);
283 showNews.setVisible(true);
287 this.addWindowListener(new WindowAdapter()
289 public void windowClosing(WindowEvent evt)
295 this.addMouseListener(new MouseAdapter()
297 public void mousePressed(MouseEvent evt)
299 if (SwingUtilities.isRightMouseButton(evt))
301 showPasteMenu(evt.getX(), evt.getY());
306 this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
307 // Spawn a thread that shows the splashscreen
308 SwingUtilities.invokeLater(new Runnable()
317 // Thread off a new instance of the file chooser - this reduces the time it
318 // takes to open it later on.
319 new Thread(new Runnable()
323 Cache.log.debug("Filechooser init thread started.");
324 JalviewFileChooser chooser = new JalviewFileChooser(
325 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
326 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
327 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
328 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
329 Cache.log.debug("Filechooser init thread finished.");
332 // Add the service change listener
333 changeSupport.addJalviewPropertyChangeListener("services",
334 new PropertyChangeListener()
338 public void propertyChange(PropertyChangeEvent evt)
340 Cache.log.debug("Firing service changed event for "
341 + evt.getNewValue());
342 JalviewServicesChanged(evt);
348 protected void showNews_actionPerformed(ActionEvent e)
350 showNews(showNews.isSelected());
352 void showNews(boolean visible)
355 jvnews.setVisible(visible);
356 showNews.setSelected(visible);
359 jvnews.refreshNews();
366 * recover the last known dimensions for a jalview window
369 * - empty string is desktop, all other windows have unique prefix
370 * @return null or last known dimensions scaled to current geometry (if last
371 * window geom was known)
373 Rectangle getLastKnownDimensions(String windowName)
375 // TODO: lock aspect ratio for scaling desktop Bug #0058199
376 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
377 String x = jalview.bin.Cache.getProperty(windowName + "SCREEN_X");
378 String y = jalview.bin.Cache.getProperty(windowName + "SCREEN_Y");
379 String width = jalview.bin.Cache.getProperty(windowName
381 String height = jalview.bin.Cache.getProperty(windowName
383 if ((x != null) && (y != null) && (width != null) && (height != null))
385 int ix = Integer.parseInt(x), iy = Integer.parseInt(y), iw = Integer
386 .parseInt(width), ih = Integer.parseInt(height);
387 if (jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
389 // attempt #1 - try to cope with change in screen geometry - this
390 // version doesn't preserve original jv aspect ratio.
391 // take ratio of current screen size vs original screen size.
392 double sw = ((1f * screenSize.width) / (1f * Integer
393 .parseInt(jalview.bin.Cache
394 .getProperty("SCREENGEOMETRY_WIDTH"))));
395 double sh = ((1f * screenSize.height) / (1f * Integer
396 .parseInt(jalview.bin.Cache
397 .getProperty("SCREENGEOMETRY_HEIGHT"))));
398 // rescale the bounds depending upon the current screen geometry.
399 ix = (int) (ix * sw);
400 iw = (int) (iw * sw);
401 iy = (int) (iy * sh);
402 ih = (int) (ih * sh);
403 while (ix >= screenSize.width)
405 jalview.bin.Cache.log
406 .debug("Window geometry location recall error: shifting horizontal to within screenbounds.");
407 ix -= screenSize.width;
409 while (iy >= screenSize.height)
411 jalview.bin.Cache.log
412 .debug("Window geometry location recall error: shifting vertical to within screenbounds.");
413 iy -= screenSize.height;
415 jalview.bin.Cache.log.debug("Got last known dimensions for "
416 + windowName + ": x:" + ix + " y:" + iy + " width:" + iw
419 // return dimensions for new instance
420 return new Rectangle(ix, iy, iw, ih);
425 private void doVamsasClientCheck()
427 if (jalview.bin.Cache.vamsasJarsPresent())
429 setupVamsasDisconnectedGui();
430 VamsasMenu.setVisible(true);
431 final Desktop us = this;
432 VamsasMenu.addMenuListener(new MenuListener()
434 // this listener remembers when the menu was first selected, and
435 // doesn't rebuild the session list until it has been cleared and
437 boolean refresh = true;
439 public void menuCanceled(MenuEvent e)
444 public void menuDeselected(MenuEvent e)
449 public void menuSelected(MenuEvent e)
453 us.buildVamsasStMenu();
458 vamsasStart.setVisible(true);
462 void showPasteMenu(int x, int y)
464 JPopupMenu popup = new JPopupMenu();
465 JMenuItem item = new JMenuItem("Paste To New Window");
466 item.addActionListener(new ActionListener()
468 public void actionPerformed(ActionEvent evt)
475 popup.show(this, x, y);
482 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
483 Transferable contents = c.getContents(this);
485 if (contents != null)
487 String file = (String) contents
488 .getTransferData(DataFlavor.stringFlavor);
490 String format = new IdentifyFile().Identify(file,
491 FormatAdapter.PASTE);
493 new FileLoader().LoadFile(file, FormatAdapter.PASTE, format);
496 } catch (Exception ex)
499 .println("Unable to paste alignment from system clipboard:\n"
505 * Adds and opens the given frame to the desktop
516 public static synchronized void addInternalFrame(
517 final JInternalFrame frame, String title, int w, int h)
519 addInternalFrame(frame, title, w, h, true);
536 public static synchronized void addInternalFrame(
537 final JInternalFrame frame, String title, int w, int h,
541 // TODO: allow callers to determine X and Y position of frame (eg. via
543 // TODO: consider fixing method to update entries in the window submenu with
544 // the current window title
546 frame.setTitle(title);
547 if (frame.getWidth() < 1 || frame.getHeight() < 1)
551 // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
552 // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
553 // IF JALVIEW IS RUNNING HEADLESS
554 // ///////////////////////////////////////////////
555 if (System.getProperty("java.awt.headless") != null
556 && System.getProperty("java.awt.headless").equals("true"))
563 frame.setVisible(true);
564 frame.setClosable(true);
565 frame.setResizable(resizable);
566 frame.setMaximizable(resizable);
567 frame.setIconifiable(resizable);
568 frame.setFrameIcon(null);
570 if (frame.getX() < 1 && frame.getY() < 1)
572 frame.setLocation(xOffset * openFrameCount, yOffset
573 * ((openFrameCount - 1) % 10) + yOffset);
576 final JMenuItem menuItem = new JMenuItem(title);
577 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
579 public void internalFrameActivated(
580 javax.swing.event.InternalFrameEvent evt)
582 JInternalFrame itf = desktop.getSelectedFrame();
590 public void internalFrameClosed(
591 javax.swing.event.InternalFrameEvent evt)
593 PaintRefresher.RemoveComponent(frame);
595 windowMenu.remove(menuItem);
596 JInternalFrame itf = desktop.getSelectedFrame();
605 menuItem.addActionListener(new ActionListener()
607 public void actionPerformed(ActionEvent e)
611 frame.setSelected(true);
612 frame.setIcon(false);
613 } catch (java.beans.PropertyVetoException ex)
619 menuItem.addMouseListener(new MouseListener()
623 public void mouseReleased(MouseEvent e)
628 public void mousePressed(MouseEvent e)
633 public void mouseExited(MouseEvent e)
637 frame.setSelected(false);
638 } catch (PropertyVetoException e1)
644 public void mouseEntered(MouseEvent e)
648 frame.setSelected(true);
649 } catch (PropertyVetoException e1)
655 public void mouseClicked(MouseEvent e)
661 windowMenu.add(menuItem);
667 frame.setSelected(true);
668 frame.requestFocus();
669 } catch (java.beans.PropertyVetoException ve)
672 catch (java.lang.ClassCastException cex)
674 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);
678 public void lostOwnership(Clipboard clipboard, Transferable contents)
682 Desktop.jalviewClipboard = null;
685 internalCopy = false;
688 public void dragEnter(DropTargetDragEvent evt)
692 public void dragExit(DropTargetEvent evt)
696 public void dragOver(DropTargetDragEvent evt)
700 public void dropActionChanged(DropTargetDragEvent evt)
710 public void drop(DropTargetDropEvent evt)
712 Transferable t = evt.getTransferable();
713 java.util.List files = null;
714 java.util.List protocols = null;
718 DataFlavor uriListFlavor = new DataFlavor(
719 "text/uri-list;class=java.lang.String");
720 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
722 // Works on Windows and MacOSX
723 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
724 files = (java.util.List) t
725 .getTransferData(DataFlavor.javaFileListFlavor);
727 else if (t.isDataFlavorSupported(uriListFlavor))
729 // This is used by Unix drag system
730 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
731 String data = (String) t.getTransferData(uriListFlavor);
732 files = new java.util.ArrayList(1);
733 protocols = new java.util.ArrayList(1);
734 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
735 data, "\r\n"); st.hasMoreTokens();)
737 String s = st.nextToken();
738 if (s.startsWith("#"))
740 // the line is a comment (as per the RFC 2483)
743 java.net.URI uri = new java.net.URI(s);
744 if (uri.getScheme().toLowerCase().startsWith("http"))
746 protocols.add(FormatAdapter.URL);
747 files.add(uri.toString());
751 // otherwise preserve old behaviour: catch all for file objects
752 java.io.File file = new java.io.File(uri);
753 protocols.add(FormatAdapter.FILE);
754 files.add(file.toString());
758 } catch (Exception e)
766 for (int i = 0; i < files.size(); i++)
768 String file = files.get(i).toString();
769 String protocol = (protocols == null) ? FormatAdapter.FILE
770 : (String) protocols.get(i);
771 String format = null;
773 if (file.endsWith(".jar"))
780 format = new IdentifyFile().Identify(file, protocol);
783 new FileLoader().LoadFile(file, protocol, format);
786 } catch (Exception ex)
798 public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
800 JalviewFileChooser chooser = new JalviewFileChooser(
801 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
802 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
803 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
804 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
806 chooser.setFileView(new JalviewFileView());
807 chooser.setDialogTitle("Open local file");
808 chooser.setToolTipText("Open");
810 int value = chooser.showOpenDialog(this);
812 if (value == JalviewFileChooser.APPROVE_OPTION)
814 String choice = chooser.getSelectedFile().getPath();
815 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
816 .getSelectedFile().getParent());
818 String format = null;
819 if (chooser.getSelectedFormat().equals("Jalview"))
825 format = new IdentifyFile().Identify(choice, FormatAdapter.FILE);
828 if (viewport != null)
830 new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE,
835 new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
846 public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
848 // This construct allows us to have a wider textfield
850 JLabel label = new JLabel("Enter URL of Input File");
851 final JComboBox history = new JComboBox();
853 JPanel panel = new JPanel(new GridLayout(2, 1));
856 history.setPreferredSize(new Dimension(400, 20));
857 history.setEditable(true);
858 history.addItem("http://www.");
860 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
864 if (historyItems != null)
866 st = new StringTokenizer(historyItems, "\t");
868 while (st.hasMoreTokens())
870 history.addItem(st.nextElement());
874 int reply = JOptionPane.showInternalConfirmDialog(desktop, panel,
875 "Input Alignment From URL", JOptionPane.OK_CANCEL_OPTION);
877 if (reply != JOptionPane.OK_OPTION)
882 String url = history.getSelectedItem().toString();
884 if (url.toLowerCase().endsWith(".jar"))
886 if (viewport != null)
888 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL,
893 new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
898 String format = new IdentifyFile().Identify(url, FormatAdapter.URL);
900 if (format.equals("URL NOT FOUND"))
902 JOptionPane.showInternalMessageDialog(Desktop.desktop,
903 "Couldn't locate " + url, "URL not found",
904 JOptionPane.WARNING_MESSAGE);
909 if (viewport != null)
911 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
915 new FileLoader().LoadFile(url, FormatAdapter.URL, format);
926 public void inputTextboxMenuItem_actionPerformed(AlignViewport viewport)
928 CutAndPasteTransfer cap = new CutAndPasteTransfer();
929 cap.setForInput(viewport);
930 Desktop.addInternalFrame(cap, "Cut & Paste Alignment File", 600, 500);
938 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
940 .setProperty("SCREENGEOMETRY_WIDTH", screen.width + "");
941 jalview.bin.Cache.setProperty("SCREENGEOMETRY_HEIGHT", screen.height
943 storeLastKnownDimensions("", new Rectangle(getBounds().x,
944 getBounds().y, getWidth(), getHeight()));
946 if (jconsole != null)
948 storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
949 jconsole.stopConsole();
953 storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
960 private void storeLastKnownDimensions(String string, Rectangle jc)
962 jalview.bin.Cache.log.debug("Storing last known dimensions for "
963 + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
964 + " height:" + jc.height);
966 jalview.bin.Cache.setProperty(string + "SCREEN_X", jc.x + "");
967 jalview.bin.Cache.setProperty(string + "SCREEN_Y", jc.y + "");
968 jalview.bin.Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
969 jalview.bin.Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
978 public void aboutMenuItem_actionPerformed(ActionEvent e)
980 StringBuffer message = new StringBuffer("Jalview version "
981 + jalview.bin.Cache.getProperty("VERSION") + "; last updated: "
982 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
984 if (!jalview.bin.Cache.getProperty("LATEST_VERSION").equals(
985 jalview.bin.Cache.getProperty("VERSION")))
987 message.append("\n\n!! Jalview version "
988 + jalview.bin.Cache.getProperty("LATEST_VERSION")
989 + " is available for download from "+jalview.bin.Cache.getDefault("www.jalview.org","http://www.jalview.org")+" !!\n");
992 // TODO: update this text for each release or centrally store it for lite
994 message.append("\nAuthors: Jim Procter, Andrew Waterhouse, Michele Clamp, James Cuff, Steve Searle,\n David Martin & Geoff Barton."
995 + "\nDevelopment managed by The Barton Group, University of Dundee, Scotland, UK.\n"
996 + "\nFor help, see the FAQ at www.jalview.org and/or join the jalview-discuss@jalview.org mailing list\n"
997 + "\nIf you use Jalview, please cite:"
998 + "\nWaterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
999 + "\nJalview Version 2 - a multiple sequence alignment editor and analysis workbench"
1000 + "\nBioinformatics doi: 10.1093/bioinformatics/btp033");
1001 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1003 message.toString(), "About Jalview", JOptionPane.INFORMATION_MESSAGE);
1012 public void documentationMenuItem_actionPerformed(ActionEvent e)
1016 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
1017 java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
1018 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
1020 javax.help.HelpBroker hb = hs.createHelpBroker();
1021 hb.setCurrentID("home");
1022 hb.setDisplayed(true);
1023 } catch (Exception ex)
1028 public void closeAll_actionPerformed(ActionEvent e)
1030 JInternalFrame[] frames = desktop.getAllFrames();
1031 for (int i = 0; i < frames.length; i++)
1035 frames[i].setClosed(true);
1036 } catch (java.beans.PropertyVetoException ex)
1040 System.out.println("ALL CLOSED");
1041 if (v_client != null)
1043 // TODO clear binding to vamsas document objects on close_all
1048 public void raiseRelated_actionPerformed(ActionEvent e)
1050 reorderAssociatedWindows(false, false);
1053 public void minimizeAssociated_actionPerformed(ActionEvent e)
1055 reorderAssociatedWindows(true, false);
1058 void closeAssociatedWindows()
1060 reorderAssociatedWindows(false, true);
1066 * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1069 protected void garbageCollect_actionPerformed(ActionEvent e)
1071 // We simply collect the garbage
1072 jalview.bin.Cache.log.debug("Collecting garbage...");
1074 jalview.bin.Cache.log.debug("Finished garbage collection.");
1081 * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
1084 protected void showMemusage_actionPerformed(ActionEvent e)
1086 desktop.showMemoryUsage(showMemusage.isSelected());
1093 * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1096 protected void showConsole_actionPerformed(ActionEvent e)
1098 showConsole(showConsole.isSelected());
1101 Console jconsole = null;
1104 * control whether the java console is visible or not
1108 void showConsole(boolean selected)
1110 showConsole.setSelected(selected);
1111 // TODO: decide if we should update properties file
1112 Cache.setProperty("SHOW_JAVA_CONSOLE", Boolean.valueOf(selected)
1114 jconsole.setVisible(selected);
1117 void reorderAssociatedWindows(boolean minimize, boolean close)
1119 JInternalFrame[] frames = desktop.getAllFrames();
1120 if (frames == null || frames.length < 1)
1125 AlignViewport source = null, target = null;
1126 if (frames[0] instanceof AlignFrame)
1128 source = ((AlignFrame) frames[0]).getCurrentView();
1130 else if (frames[0] instanceof TreePanel)
1132 source = ((TreePanel) frames[0]).getViewPort();
1134 else if (frames[0] instanceof PCAPanel)
1136 source = ((PCAPanel) frames[0]).av;
1138 else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1140 source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1145 for (int i = 0; i < frames.length; i++)
1148 if (frames[i] == null)
1152 if (frames[i] instanceof AlignFrame)
1154 target = ((AlignFrame) frames[i]).getCurrentView();
1156 else if (frames[i] instanceof TreePanel)
1158 target = ((TreePanel) frames[i]).getViewPort();
1160 else if (frames[i] instanceof PCAPanel)
1162 target = ((PCAPanel) frames[i]).av;
1164 else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1166 target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1169 if (source == target)
1175 frames[i].setClosed(true);
1179 frames[i].setIcon(minimize);
1182 frames[i].toFront();
1186 } catch (java.beans.PropertyVetoException ex)
1200 protected void preferences_actionPerformed(ActionEvent e)
1211 public void saveState_actionPerformed(ActionEvent e)
1213 JalviewFileChooser chooser = new JalviewFileChooser(
1214 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1215 { "jar" }, new String[]
1216 { "Jalview Project" }, "Jalview Project");
1218 chooser.setFileView(new JalviewFileView());
1219 chooser.setDialogTitle("Save State");
1221 int value = chooser.showSaveDialog(this);
1223 if (value == JalviewFileChooser.APPROVE_OPTION)
1225 final Desktop me = this;
1226 final java.io.File choice = chooser.getSelectedFile();
1227 new Thread(new Runnable()
1232 setProgressBar("Saving jalview project " + choice.getName(),
1234 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1235 // TODO catch and handle errors for savestate
1236 // TODO prevent user from messing with the Desktop whilst we're saving
1239 new Jalview2XML().SaveState(choice);
1240 } catch (OutOfMemoryError oom)
1243 "Whilst saving current state to " + choice.getName(), oom);
1244 } catch (Exception ex)
1247 .error("Problems whilst trying to save to "
1248 + choice.getName(), ex);
1249 JOptionPane.showMessageDialog(me,
1250 "Error whilst saving current state to " + choice.getName(),
1251 "Couldn't save project", JOptionPane.WARNING_MESSAGE);
1253 setProgressBar(null, choice.hashCode());
1265 public void loadState_actionPerformed(ActionEvent e)
1267 JalviewFileChooser chooser = new JalviewFileChooser(
1268 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1269 { "jar" }, new String[]
1270 { "Jalview Project" }, "Jalview Project");
1271 chooser.setFileView(new JalviewFileView());
1272 chooser.setDialogTitle("Restore state");
1274 int value = chooser.showOpenDialog(this);
1276 if (value == JalviewFileChooser.APPROVE_OPTION)
1278 final String choice = chooser.getSelectedFile().getAbsolutePath();
1279 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
1280 .getSelectedFile().getParent());
1281 new Thread(new Runnable()
1285 setProgressBar("loading jalview project " + choice,
1289 new Jalview2XML().LoadJalviewAlign(choice);
1290 } catch (OutOfMemoryError oom)
1292 new OOMWarning("Whilst loading project from " + choice, oom);
1293 } catch (Exception ex)
1295 Cache.log.error("Problems whilst loading project from "
1297 JOptionPane.showMessageDialog(Desktop.desktop,
1298 "Error whilst loading project from " + choice,
1299 "Couldn't load project", JOptionPane.WARNING_MESSAGE);
1301 setProgressBar(null, choice.hashCode());
1307 public void inputSequence_actionPerformed(ActionEvent e)
1309 new SequenceFetcher(this);
1312 JPanel progressPanel;
1313 ArrayList<JPanel> fileLoadingPanels=new ArrayList<JPanel>();
1314 public void startLoading(final String fileName)
1316 if (fileLoadingCount == 0)
1318 fileLoadingPanels.add(addProgressPanel("Loading File: " + fileName + " "));
1323 private JPanel addProgressPanel(String string)
1325 if (progressPanel == null)
1327 progressPanel = new JPanel(new GridLayout(1,1));
1328 totalProgressCount = 0;
1329 instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
1331 JPanel thisprogress=new JPanel(new BorderLayout(10,5));
1332 JProgressBar progressBar = new JProgressBar();
1333 progressBar.setIndeterminate(true);
1335 thisprogress.add(new JLabel(string), BorderLayout.WEST);
1337 thisprogress.add(progressBar, BorderLayout.CENTER);
1338 progressPanel.add(thisprogress);
1339 ((GridLayout)progressPanel.getLayout()).setRows(((GridLayout)progressPanel.getLayout()).getRows()+1);
1340 ++totalProgressCount;
1341 instance.validate();
1342 return thisprogress;
1345 int totalProgressCount = 0;
1347 private void removeProgressPanel(JPanel progbar)
1349 if (progressPanel != null)
1351 progressPanel.remove(progbar);
1352 GridLayout gl = (GridLayout) progressPanel.getLayout();
1353 gl.setRows(gl.getRows()-1);
1354 if (--totalProgressCount < 1)
1356 this.getContentPane().remove(progressPanel);
1357 progressPanel = null;
1363 public void stopLoading()
1366 if (fileLoadingCount < 1)
1368 for (JPanel flp : fileLoadingPanels)
1370 removeProgressPanel(flp);
1372 fileLoadingPanels.clear();
1373 fileLoadingCount = 0;
1378 public static int getViewCount(String alignmentId)
1380 AlignViewport[] aps = getViewports(alignmentId);
1381 return (aps == null) ? 0 : aps.length;
1386 * @param alignmentId
1387 * @return all AlignmentPanels concerning the alignmentId sequence set
1389 public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
1392 if (Desktop.desktop == null)
1394 // no frames created and in headless mode
1395 // TODO: verify that frames are recoverable when in headless mode
1398 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1399 ArrayList aps = new ArrayList();
1400 for (int t = 0; t < frames.length; t++)
1402 if (frames[t] instanceof AlignFrame)
1404 AlignFrame af = (AlignFrame) frames[t];
1405 for (int a = 0; a < af.alignPanels.size(); a++)
1408 .equals(((AlignmentPanel) af.alignPanels.elementAt(a)).av
1409 .getSequenceSetId()))
1411 aps.add(af.alignPanels.elementAt(a));
1416 if (aps.size() == 0)
1420 AlignmentPanel[] vap = new AlignmentPanel[aps.size()];
1421 for (int t = 0; t < vap.length; t++)
1423 vap[t] = (AlignmentPanel) aps.get(t);
1429 * get all the viewports on an alignment.
1431 * @param sequenceSetId
1432 * unique alignment id
1433 * @return all viewports on the alignment bound to sequenceSetId
1435 public static AlignViewport[] getViewports(String sequenceSetId)
1437 Vector viewp = new Vector();
1438 if (desktop != null)
1440 javax.swing.JInternalFrame[] frames = instance.getAllFrames();
1442 for (int t = 0; t < frames.length; t++)
1444 if (frames[t] instanceof AlignFrame)
1446 AlignFrame afr = ((AlignFrame) frames[t]);
1447 if (afr.getViewport().getSequenceSetId().equals(sequenceSetId))
1449 if (afr.alignPanels != null)
1451 for (int a = 0; a < afr.alignPanels.size(); a++)
1453 if (sequenceSetId.equals(((AlignmentPanel) afr.alignPanels
1454 .elementAt(a)).av.getSequenceSetId()))
1456 viewp.addElement(((AlignmentPanel) afr.alignPanels
1463 viewp.addElement(((AlignFrame) frames[t]).getViewport());
1468 if (viewp.size() > 0)
1470 AlignViewport[] vp = new AlignViewport[viewp.size()];
1478 public void explodeViews(AlignFrame af)
1480 int size = af.alignPanels.size();
1486 for (int i = 0; i < size; i++)
1488 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(i);
1489 AlignFrame newaf = new AlignFrame(ap);
1490 if (ap.av.explodedPosition != null
1491 && !ap.av.explodedPosition.equals(af.getBounds()))
1493 newaf.setBounds(ap.av.explodedPosition);
1496 ap.av.gatherViewsHere = false;
1498 addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1499 AlignFrame.DEFAULT_HEIGHT);
1502 af.alignPanels.clear();
1503 af.closeMenuItem_actionPerformed(true);
1507 public void gatherViews(AlignFrame source)
1509 source.viewport.gatherViewsHere = true;
1510 source.viewport.explodedPosition = source.getBounds();
1511 JInternalFrame[] frames = desktop.getAllFrames();
1512 String viewId = source.viewport.sequenceSetID;
1514 for (int t = 0; t < frames.length; t++)
1516 if (frames[t] instanceof AlignFrame && frames[t] != source)
1518 AlignFrame af = (AlignFrame) frames[t];
1519 boolean gatherThis = false;
1520 for (int a = 0; a < af.alignPanels.size(); a++)
1522 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(a);
1523 if (viewId.equals(ap.av.getSequenceSetId()))
1526 ap.av.gatherViewsHere = false;
1527 ap.av.explodedPosition = af.getBounds();
1528 source.addAlignmentPanel(ap, false);
1534 af.alignPanels.clear();
1535 af.closeMenuItem_actionPerformed(true);
1542 jalview.gui.VamsasApplication v_client = null;
1544 public void vamsasImport_actionPerformed(ActionEvent e)
1546 if (v_client == null)
1548 // Load and try to start a session.
1549 JalviewFileChooser chooser = new JalviewFileChooser(
1550 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1552 chooser.setFileView(new JalviewFileView());
1553 chooser.setDialogTitle("Open a saved VAMSAS session");
1554 chooser.setToolTipText("select a vamsas session to be opened as a new vamsas session.");
1556 int value = chooser.showOpenDialog(this);
1558 if (value == JalviewFileChooser.APPROVE_OPTION)
1560 String fle = chooser.getSelectedFile().toString();
1561 if (!vamsasImport(chooser.getSelectedFile()))
1563 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1564 "Couldn't import '" + fle + "' as a new vamsas session.",
1565 "Vamsas Document Import Failed",
1566 JOptionPane.ERROR_MESSAGE);
1572 jalview.bin.Cache.log
1573 .error("Implementation error - load session from a running session is not supported.");
1578 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1581 * @return true if import was a success and a session was started.
1583 public boolean vamsasImport(URL url)
1585 // TODO: create progress bar
1586 if (v_client != null)
1589 jalview.bin.Cache.log
1590 .error("Implementation error - load session from a running session is not supported.");
1596 // copy the URL content to a temporary local file
1597 // TODO: be a bit cleverer here with nio (?!)
1598 File file = File.createTempFile("vdocfromurl", ".vdj");
1599 FileOutputStream fos = new FileOutputStream(file);
1600 BufferedInputStream bis = new BufferedInputStream(url.openStream());
1601 byte[] buffer = new byte[2048];
1603 while ((ln = bis.read(buffer)) > -1)
1605 fos.write(buffer, 0, ln);
1609 v_client = new jalview.gui.VamsasApplication(this, file,
1610 url.toExternalForm());
1611 } catch (Exception ex)
1613 jalview.bin.Cache.log.error(
1614 "Failed to create new vamsas session from contents of URL "
1618 setupVamsasConnectedGui();
1619 v_client.initial_update(); // TODO: thread ?
1620 return v_client.inSession();
1624 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1627 * @return true if import was a success and a session was started.
1629 public boolean vamsasImport(File file)
1631 if (v_client != null)
1634 jalview.bin.Cache.log
1635 .error("Implementation error - load session from a running session is not supported.");
1639 setProgressBar("Importing VAMSAS session from " + file.getName(),
1643 v_client = new jalview.gui.VamsasApplication(this, file, null);
1644 } catch (Exception ex)
1646 setProgressBar("Importing VAMSAS session from " + file.getName(),
1648 jalview.bin.Cache.log.error(
1649 "New vamsas session from existing session file failed:", ex);
1652 setupVamsasConnectedGui();
1653 v_client.initial_update(); // TODO: thread ?
1654 setProgressBar("Importing VAMSAS session from " + file.getName(),
1656 return v_client.inSession();
1659 public boolean joinVamsasSession(String mysesid)
1661 if (v_client != null)
1664 "Trying to join a vamsas session when another is already connected.");
1666 if (mysesid == null)
1668 throw new Error("Invalid vamsas session id.");
1670 v_client = new VamsasApplication(this, mysesid);
1671 setupVamsasConnectedGui();
1672 v_client.initial_update();
1673 return (v_client.inSession());
1676 public void vamsasStart_actionPerformed(ActionEvent e)
1678 if (v_client == null)
1681 // we just start a default session for moment.
1683 * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
1684 * getProperty("LAST_DIRECTORY"));
1686 * chooser.setFileView(new JalviewFileView());
1687 * chooser.setDialogTitle("Load Vamsas file");
1688 * chooser.setToolTipText("Import");
1690 * int value = chooser.showOpenDialog(this);
1692 * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
1693 * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
1695 v_client = new VamsasApplication(this);
1696 setupVamsasConnectedGui();
1697 v_client.initial_update(); // TODO: thread ?
1701 // store current data in session.
1702 v_client.push_update(); // TODO: thread
1706 protected void setupVamsasConnectedGui()
1708 vamsasStart.setText("Session Update");
1709 vamsasSave.setVisible(true);
1710 vamsasStop.setVisible(true);
1711 vamsasImport.setVisible(false); // Document import to existing session is
1712 // not possible for vamsas-client-1.0.
1715 protected void setupVamsasDisconnectedGui()
1717 vamsasSave.setVisible(false);
1718 vamsasStop.setVisible(false);
1719 vamsasImport.setVisible(true);
1720 vamsasStart.setText("New Vamsas Session");
1723 public void vamsasStop_actionPerformed(ActionEvent e)
1725 if (v_client != null)
1727 v_client.end_session();
1729 setupVamsasDisconnectedGui();
1733 protected void buildVamsasStMenu()
1735 if (v_client == null)
1737 String[] sess = null;
1740 sess = VamsasApplication.getSessionList();
1741 } catch (Exception e)
1743 jalview.bin.Cache.log.warn(
1744 "Problem getting current sessions list.", e);
1749 jalview.bin.Cache.log.debug("Got current sessions list: "
1750 + sess.length + " entries.");
1751 VamsasStMenu.removeAll();
1752 for (int i = 0; i < sess.length; i++)
1754 JMenuItem sessit = new JMenuItem();
1755 sessit.setText(sess[i]);
1756 sessit.setToolTipText("Connect to session " + sess[i]);
1757 final Desktop dsktp = this;
1758 final String mysesid = sess[i];
1759 sessit.addActionListener(new ActionListener()
1762 public void actionPerformed(ActionEvent e)
1764 if (dsktp.v_client == null)
1766 Thread rthr = new Thread(new Runnable()
1771 dsktp.v_client = new VamsasApplication(dsktp, mysesid);
1772 dsktp.setupVamsasConnectedGui();
1773 dsktp.v_client.initial_update();
1781 VamsasStMenu.add(sessit);
1783 // don't show an empty menu.
1784 VamsasStMenu.setVisible(sess.length > 0);
1789 jalview.bin.Cache.log.debug("No current vamsas sessions.");
1790 VamsasStMenu.removeAll();
1791 VamsasStMenu.setVisible(false);
1796 // Not interested in the content. Just hide ourselves.
1797 VamsasStMenu.setVisible(false);
1801 public void vamsasSave_actionPerformed(ActionEvent e)
1803 if (v_client != null)
1805 JalviewFileChooser chooser = new JalviewFileChooser(
1806 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1807 { "vdj" }, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
1809 { "Vamsas Document" }, "Vamsas Document");
1811 chooser.setFileView(new JalviewFileView());
1812 chooser.setDialogTitle("Save Vamsas Document Archive");
1814 int value = chooser.showSaveDialog(this);
1816 if (value == JalviewFileChooser.APPROVE_OPTION)
1818 java.io.File choice = chooser.getSelectedFile();
1819 JPanel progpanel = addProgressPanel("Saving VAMSAS Document to "
1820 + choice.getName());
1821 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1822 String warnmsg = null;
1823 String warnttl = null;
1826 v_client.vclient.storeDocument(choice);
1829 warnttl = "Serious Problem saving Vamsas Document";
1830 warnmsg = ex.toString();
1831 jalview.bin.Cache.log.error("Error Whilst saving document to "
1834 } catch (Exception ex)
1836 warnttl = "Problem saving Vamsas Document.";
1837 warnmsg = ex.toString();
1838 jalview.bin.Cache.log.warn("Exception Whilst saving document to "
1842 removeProgressPanel(progpanel);
1843 if (warnmsg != null)
1845 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1847 warnmsg, warnttl, JOptionPane.ERROR_MESSAGE);
1853 JPanel vamUpdate = null;
1856 * hide vamsas user gui bits when a vamsas document event is being handled.
1859 * true to hide gui, false to reveal gui
1861 public void setVamsasUpdate(boolean b)
1863 jalview.bin.Cache.log.debug("Setting gui for Vamsas update "
1864 + (b ? "in progress" : "finished"));
1866 if (vamUpdate != null)
1868 this.removeProgressPanel(vamUpdate);
1872 vamUpdate = this.addProgressPanel("Updating vamsas session");
1874 vamsasStart.setVisible(!b);
1875 vamsasStop.setVisible(!b);
1876 vamsasSave.setVisible(!b);
1879 public JInternalFrame[] getAllFrames()
1881 return desktop.getAllFrames();
1885 * Checks the given url to see if it gives a response indicating that the user
1886 * should be informed of a new questionnaire.
1890 public void checkForQuestionnaire(String url)
1892 UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
1893 // javax.swing.SwingUtilities.invokeLater(jvq);
1894 new Thread(jvq).start();
1898 * Proxy class for JDesktopPane which optionally displays the current memory
1899 * usage and highlights the desktop area with a red bar if free memory runs
1904 public class MyDesktopPane extends JDesktopPane implements Runnable
1907 boolean showMemoryUsage = false;
1911 java.text.NumberFormat df;
1913 float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
1916 public MyDesktopPane(boolean showMemoryUsage)
1918 showMemoryUsage(showMemoryUsage);
1921 public void showMemoryUsage(boolean showMemoryUsage)
1923 this.showMemoryUsage = showMemoryUsage;
1924 if (showMemoryUsage)
1926 Thread worker = new Thread(this);
1931 public boolean isShowMemoryUsage()
1933 return showMemoryUsage;
1938 df = java.text.NumberFormat.getNumberInstance();
1939 df.setMaximumFractionDigits(2);
1940 runtime = Runtime.getRuntime();
1942 while (showMemoryUsage)
1946 maxMemory = runtime.maxMemory() / 1048576f;
1947 allocatedMemory = runtime.totalMemory() / 1048576f;
1948 freeMemory = runtime.freeMemory() / 1048576f;
1949 totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
1951 percentUsage = (totalFreeMemory / maxMemory) * 100;
1953 // if (percentUsage < 20)
1955 // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
1957 // instance.set.setBorder(border1);
1960 // sleep after showing usage
1962 } catch (Exception ex)
1964 ex.printStackTrace();
1969 public void paintComponent(Graphics g)
1971 if (showMemoryUsage && g != null && df != null)
1973 if (percentUsage < 20)
1974 g.setColor(Color.red);
1975 FontMetrics fm = g.getFontMetrics();
1979 "Total Free Memory: " + df.format(totalFreeMemory)
1980 + "MB; Max Memory: " + df.format(maxMemory)
1981 + "MB; " + df.format(percentUsage) + "%", 10,
1982 getHeight() - fm.getHeight());
1990 * fixes stacking order after a modal dialog to ensure windows that should be on top actually are
1992 public void relayerWindows()
1994 if (jvnews!=null && jvnews.isVisible())
2000 protected JMenuItem groovyShell;
2002 public void doGroovyCheck()
2004 if (jalview.bin.Cache.groovyJarsPresent())
2006 groovyShell = new JMenuItem();
2007 groovyShell.setText("Groovy Console...");
2008 groovyShell.addActionListener(new ActionListener()
2010 public void actionPerformed(ActionEvent e)
2012 groovyShell_actionPerformed(e);
2015 toolsMenu.add(groovyShell);
2016 groovyShell.setVisible(true);
2021 * Accessor method to quickly get all the AlignmentFrames loaded.
2023 public static AlignFrame[] getAlignframes()
2025 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2031 Vector avp = new Vector();
2035 for (int i = frames.length - 1; i > -1; i--)
2037 if (frames[i] instanceof AlignFrame)
2039 AlignFrame af = (AlignFrame) frames[i];
2043 } catch (Exception ex)
2045 ex.printStackTrace();
2047 if (avp.size() == 0)
2051 AlignFrame afs[] = new AlignFrame[avp.size()];
2052 for (int i = 0, j = avp.size(); i < j; i++)
2054 afs[i] = (AlignFrame) avp.elementAt(i);
2059 public AppJmol[] getJmols()
2061 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2067 Vector avp = new Vector();
2071 for (int i = frames.length - 1; i > -1; i--)
2073 if (frames[i] instanceof AppJmol)
2075 AppJmol af = (AppJmol) frames[i];
2079 } catch (Exception ex)
2081 ex.printStackTrace();
2083 if (avp.size() == 0)
2087 AppJmol afs[] = new AppJmol[avp.size()];
2088 for (int i = 0, j = avp.size(); i < j; i++)
2090 afs[i] = (AppJmol) avp.elementAt(i);
2097 * Add Groovy Support to Jalview
2099 public void groovyShell_actionPerformed(ActionEvent e)
2101 // use reflection to avoid creating compilation dependency.
2102 if (!jalview.bin.Cache.groovyJarsPresent())
2105 "Implementation Error. Cannot create groovyShell without Groovy on the classpath!");
2109 Class gcClass = Desktop.class.getClassLoader().loadClass(
2110 "groovy.ui.Console");
2111 Constructor gccons = gcClass.getConstructor(null);
2112 java.lang.reflect.Method setvar = gcClass.getMethod("setVariable",
2114 { String.class, Object.class });
2115 java.lang.reflect.Method run = gcClass.getMethod("run", null);
2116 Object gc = gccons.newInstance(null);
2117 setvar.invoke(gc, new Object[]
2118 { "Jalview", this });
2119 run.invoke(gc, null);
2120 } catch (Exception ex)
2122 jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
2124 .showInternalMessageDialog(
2127 "Couldn't create the groovy Shell. Check the error log for the details of what went wrong.",
2128 "Jalview Groovy Support Failed",
2129 JOptionPane.ERROR_MESSAGE);
2134 * Progress bars managed by the IProgressIndicator method.
2136 private Hashtable<Long,JPanel> progressBars;
2137 private Hashtable<Long,IProgressIndicatorHandler> progressBarHandlers;
2142 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2144 public void setProgressBar(String message, long id)
2146 if (progressBars == null)
2148 progressBars = new Hashtable<Long,JPanel>();
2149 progressBarHandlers = new Hashtable<Long,IProgressIndicatorHandler>();
2152 if (progressBars.get(new Long(id)) != null)
2154 JPanel progressPanel = progressBars
2155 .remove(new Long(id));
2156 if (progressBarHandlers.contains(new Long(id)))
2158 progressBarHandlers.remove(new Long(id));
2160 removeProgressPanel(progressPanel);
2164 progressBars.put(new Long(id), addProgressPanel(message));
2171 * @see jalview.gui.IProgressIndicator#registerHandler(long,
2172 * jalview.gui.IProgressIndicatorHandler)
2174 public void registerHandler(final long id,
2175 final IProgressIndicatorHandler handler)
2177 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
2180 "call setProgressBar before registering the progress bar's handler.");
2182 progressBarHandlers.put(new Long(id), handler);
2183 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
2184 if (handler.canCancel())
2186 JButton cancel = new JButton("Cancel");
2187 final IProgressIndicator us = this;
2188 cancel.addActionListener(new ActionListener()
2191 public void actionPerformed(ActionEvent e)
2193 handler.cancelActivity(id);
2196 + ((JLabel) progressPanel.getComponent(0))
2200 progressPanel.add(cancel, BorderLayout.EAST);
2205 * This will return the first AlignFrame viewing AlignViewport av. It will
2206 * break if there are more than one AlignFrames viewing a particular av. This
2209 * @return alignFrame for av
2211 public static AlignFrame getAlignFrameFor(AlignViewport av)
2213 if (desktop != null)
2215 AlignmentPanel[] aps = getAlignmentPanels(av.getSequenceSetId());
2216 for (int panel = 0; aps != null && panel < aps.length; panel++)
2218 if (aps[panel] != null && aps[panel].av == av)
2220 return aps[panel].alignFrame;
2227 public VamsasApplication getVamsasApplication()
2234 * flag set if jalview GUI is being operated programmatically
2236 private boolean inBatchMode = false;
2239 * check if jalview GUI is being operated programmatically
2241 * @return inBatchMode
2243 public boolean isInBatchMode()
2249 * set flag if jalview GUI is being operated programmatically
2251 * @param inBatchMode
2253 public void setInBatchMode(boolean inBatchMode)
2255 this.inBatchMode = inBatchMode;
2258 public void startServiceDiscovery()
2260 startServiceDiscovery(false);
2263 public void startServiceDiscovery(boolean blocking)
2265 boolean alive = true;
2266 Thread t0 = null, t1 = null, t2 = null;
2268 // todo: changesupport handlers need to be transferred
2269 if (discoverer == null)
2271 discoverer = new jalview.ws.jws1.Discoverer();
2272 // register PCS handler for desktop.
2273 discoverer.addPropertyChangeListener(changeSupport);
2275 // JAL-940 - disabled JWS1 service configuration - always start discoverer until we phase out completely
2278 (t0 = new Thread(discoverer)).start();
2283 if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
2285 // EnfinEnvision web service menu entries are rebuild every time the
2286 // menu is shown, so no changeSupport events are needed.
2287 jalview.ws.EnfinEnvision2OneWay.getInstance();
2288 (t1 = new Thread(jalview.ws.EnfinEnvision2OneWay.getInstance()))
2291 } catch (Exception e)
2294 .info("Exception when trying to launch Envision2 workflow discovery.",
2296 Cache.log.info(e.getStackTrace());
2298 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
2300 if (jalview.ws.jws2.Jws2Discoverer.getDiscoverer().isRunning())
2302 jalview.ws.jws2.Jws2Discoverer.getDiscoverer().setAborted(true);
2304 t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer().startDiscoverer(
2310 // TODO: do rest service discovery
2319 } catch (Exception e)
2322 alive = (t1 != null && t1.isAlive())
2323 || (t2 != null && t2.isAlive())
2324 || (t3 != null && t3.isAlive())
2325 || (t0 != null && t0.isAlive());
2331 * called to check if the service discovery process completed successfully.
2335 protected void JalviewServicesChanged(PropertyChangeEvent evt)
2337 if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
2339 final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2340 .getErrorMessages();
2343 if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
2345 if (serviceChangedDialog == null)
2347 // only run if we aren't already displaying one of these.
2348 javax.swing.SwingUtilities
2349 .invokeLater(serviceChangedDialog = new Runnable()
2355 .showInternalMessageDialog(
2358 + "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",
2359 "Preferences Problem",
2360 JOptionPane.WARNING_MESSAGE);
2361 serviceChangedDialog = null;
2370 .error("Errors reported by JABA discovery service. Check web services preferences.\n"
2377 private Runnable serviceChangedDialog = null;
2380 * start a thread to open a URL in the configured browser. Pops up a warning
2381 * dialog to the user if there is an exception when calling out to the browser
2386 public static void showUrl(final String url)
2388 showUrl(url, Desktop.instance);
2391 * Like showUrl but allows progress handler to be specified
2393 * @param progress (null) or object implementing IProgressIndicator
2395 public static void showUrl(final String url, final IProgressIndicator progress)
2397 new Thread(new Runnable()
2403 if (progress!=null) {
2404 progress.setProgressBar("Opening "+url, this.hashCode());
2406 jalview.util.BrowserLauncher.openURL(url);
2407 } catch (Exception ex)
2410 .showInternalMessageDialog(
2412 "Unixers: Couldn't find default web browser."
2413 + "\nAdd the full path to your browser in Preferences.",
2414 "Web browser not found",
2415 JOptionPane.WARNING_MESSAGE);
2417 ex.printStackTrace();
2419 if (progress!=null) {
2420 progress.setProgressBar(null, this.hashCode());
2426 public static WsParamSetManager wsparamManager = null;
2428 public static ParamManager getUserParameterStore()
2430 if (wsparamManager == null)
2432 wsparamManager = new WsParamSetManager();
2434 return wsparamManager;