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();
361 // try real hard to get focus when the news is first opened
362 new Thread(new Runnable() {
366 while (jvnews.isVisible() && !jvnews.requestFocusInWindow())
368 try { Thread.sleep(50); } catch (InterruptedException x) {};
378 * recover the last known dimensions for a jalview window
381 * - empty string is desktop, all other windows have unique prefix
382 * @return null or last known dimensions scaled to current geometry (if last
383 * window geom was known)
385 Rectangle getLastKnownDimensions(String windowName)
387 // TODO: lock aspect ratio for scaling desktop Bug #0058199
388 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
389 String x = jalview.bin.Cache.getProperty(windowName + "SCREEN_X");
390 String y = jalview.bin.Cache.getProperty(windowName + "SCREEN_Y");
391 String width = jalview.bin.Cache.getProperty(windowName
393 String height = jalview.bin.Cache.getProperty(windowName
395 if ((x != null) && (y != null) && (width != null) && (height != null))
397 int ix = Integer.parseInt(x), iy = Integer.parseInt(y), iw = Integer
398 .parseInt(width), ih = Integer.parseInt(height);
399 if (jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
401 // attempt #1 - try to cope with change in screen geometry - this
402 // version doesn't preserve original jv aspect ratio.
403 // take ratio of current screen size vs original screen size.
404 double sw = ((1f * screenSize.width) / (1f * Integer
405 .parseInt(jalview.bin.Cache
406 .getProperty("SCREENGEOMETRY_WIDTH"))));
407 double sh = ((1f * screenSize.height) / (1f * Integer
408 .parseInt(jalview.bin.Cache
409 .getProperty("SCREENGEOMETRY_HEIGHT"))));
410 // rescale the bounds depending upon the current screen geometry.
411 ix = (int) (ix * sw);
412 iw = (int) (iw * sw);
413 iy = (int) (iy * sh);
414 ih = (int) (ih * sh);
415 while (ix >= screenSize.width)
417 jalview.bin.Cache.log
418 .debug("Window geometry location recall error: shifting horizontal to within screenbounds.");
419 ix -= screenSize.width;
421 while (iy >= screenSize.height)
423 jalview.bin.Cache.log
424 .debug("Window geometry location recall error: shifting vertical to within screenbounds.");
425 iy -= screenSize.height;
427 jalview.bin.Cache.log.debug("Got last known dimensions for "
428 + windowName + ": x:" + ix + " y:" + iy + " width:" + iw
431 // return dimensions for new instance
432 return new Rectangle(ix, iy, iw, ih);
437 private void doVamsasClientCheck()
439 if (jalview.bin.Cache.vamsasJarsPresent())
441 setupVamsasDisconnectedGui();
442 VamsasMenu.setVisible(true);
443 final Desktop us = this;
444 VamsasMenu.addMenuListener(new MenuListener()
446 // this listener remembers when the menu was first selected, and
447 // doesn't rebuild the session list until it has been cleared and
449 boolean refresh = true;
451 public void menuCanceled(MenuEvent e)
456 public void menuDeselected(MenuEvent e)
461 public void menuSelected(MenuEvent e)
465 us.buildVamsasStMenu();
470 vamsasStart.setVisible(true);
474 void showPasteMenu(int x, int y)
476 JPopupMenu popup = new JPopupMenu();
477 JMenuItem item = new JMenuItem("Paste To New Window");
478 item.addActionListener(new ActionListener()
480 public void actionPerformed(ActionEvent evt)
487 popup.show(this, x, y);
494 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
495 Transferable contents = c.getContents(this);
497 if (contents != null)
499 String file = (String) contents
500 .getTransferData(DataFlavor.stringFlavor);
502 String format = new IdentifyFile().Identify(file,
503 FormatAdapter.PASTE);
505 new FileLoader().LoadFile(file, FormatAdapter.PASTE, format);
508 } catch (Exception ex)
511 .println("Unable to paste alignment from system clipboard:\n"
517 * Adds and opens the given frame to the desktop
528 public static synchronized void addInternalFrame(
529 final JInternalFrame frame, String title, int w, int h)
531 addInternalFrame(frame, title, w, h, true);
548 public static synchronized void addInternalFrame(
549 final JInternalFrame frame, String title, int w, int h,
553 // TODO: allow callers to determine X and Y position of frame (eg. via
555 // TODO: consider fixing method to update entries in the window submenu with
556 // the current window title
558 frame.setTitle(title);
559 if (frame.getWidth() < 1 || frame.getHeight() < 1)
563 // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
564 // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
565 // IF JALVIEW IS RUNNING HEADLESS
566 // ///////////////////////////////////////////////
567 if (System.getProperty("java.awt.headless") != null
568 && System.getProperty("java.awt.headless").equals("true"))
575 frame.setVisible(true);
576 frame.setClosable(true);
577 frame.setResizable(resizable);
578 frame.setMaximizable(resizable);
579 frame.setIconifiable(resizable);
580 frame.setFrameIcon(null);
582 if (frame.getX() < 1 && frame.getY() < 1)
584 frame.setLocation(xOffset * openFrameCount, yOffset
585 * ((openFrameCount - 1) % 10) + yOffset);
588 final JMenuItem menuItem = new JMenuItem(title);
589 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
591 public void internalFrameActivated(
592 javax.swing.event.InternalFrameEvent evt)
594 JInternalFrame itf = desktop.getSelectedFrame();
602 public void internalFrameClosed(
603 javax.swing.event.InternalFrameEvent evt)
605 PaintRefresher.RemoveComponent(frame);
607 windowMenu.remove(menuItem);
608 JInternalFrame itf = desktop.getSelectedFrame();
617 menuItem.addActionListener(new ActionListener()
619 public void actionPerformed(ActionEvent e)
623 frame.setSelected(true);
624 frame.setIcon(false);
625 } catch (java.beans.PropertyVetoException ex)
631 menuItem.addMouseListener(new MouseListener()
635 public void mouseReleased(MouseEvent e)
640 public void mousePressed(MouseEvent e)
645 public void mouseExited(MouseEvent e)
649 frame.setSelected(false);
650 } catch (PropertyVetoException e1)
656 public void mouseEntered(MouseEvent e)
660 frame.setSelected(true);
661 } catch (PropertyVetoException e1)
667 public void mouseClicked(MouseEvent e)
673 windowMenu.add(menuItem);
679 frame.setSelected(true);
680 frame.requestFocus();
681 } catch (java.beans.PropertyVetoException ve)
684 catch (java.lang.ClassCastException cex)
686 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);
690 public void lostOwnership(Clipboard clipboard, Transferable contents)
694 Desktop.jalviewClipboard = null;
697 internalCopy = false;
700 public void dragEnter(DropTargetDragEvent evt)
704 public void dragExit(DropTargetEvent evt)
708 public void dragOver(DropTargetDragEvent evt)
712 public void dropActionChanged(DropTargetDragEvent evt)
722 public void drop(DropTargetDropEvent evt)
724 Transferable t = evt.getTransferable();
725 java.util.List files = null;
726 java.util.List protocols = null;
730 DataFlavor uriListFlavor = new DataFlavor(
731 "text/uri-list;class=java.lang.String");
732 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
734 // Works on Windows and MacOSX
735 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
736 files = (java.util.List) t
737 .getTransferData(DataFlavor.javaFileListFlavor);
739 else if (t.isDataFlavorSupported(uriListFlavor))
741 // This is used by Unix drag system
742 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
743 String data = (String) t.getTransferData(uriListFlavor);
744 files = new java.util.ArrayList(1);
745 protocols = new java.util.ArrayList(1);
746 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
747 data, "\r\n"); st.hasMoreTokens();)
749 String s = st.nextToken();
750 if (s.startsWith("#"))
752 // the line is a comment (as per the RFC 2483)
755 java.net.URI uri = new java.net.URI(s);
756 if (uri.getScheme().toLowerCase().startsWith("http"))
758 protocols.add(FormatAdapter.URL);
759 files.add(uri.toString());
763 // otherwise preserve old behaviour: catch all for file objects
764 java.io.File file = new java.io.File(uri);
765 protocols.add(FormatAdapter.FILE);
766 files.add(file.toString());
770 } catch (Exception e)
778 for (int i = 0; i < files.size(); i++)
780 String file = files.get(i).toString();
781 String protocol = (protocols == null) ? FormatAdapter.FILE
782 : (String) protocols.get(i);
783 String format = null;
785 if (file.endsWith(".jar"))
792 format = new IdentifyFile().Identify(file, protocol);
795 new FileLoader().LoadFile(file, protocol, format);
798 } catch (Exception ex)
810 public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
812 JalviewFileChooser chooser = new JalviewFileChooser(
813 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
814 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
815 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
816 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
818 chooser.setFileView(new JalviewFileView());
819 chooser.setDialogTitle("Open local file");
820 chooser.setToolTipText("Open");
822 int value = chooser.showOpenDialog(this);
824 if (value == JalviewFileChooser.APPROVE_OPTION)
826 String choice = chooser.getSelectedFile().getPath();
827 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
828 .getSelectedFile().getParent());
830 String format = null;
831 if (chooser.getSelectedFormat().equals("Jalview"))
837 format = new IdentifyFile().Identify(choice, FormatAdapter.FILE);
840 if (viewport != null)
842 new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE,
847 new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
858 public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
860 // This construct allows us to have a wider textfield
862 JLabel label = new JLabel("Enter URL of Input File");
863 final JComboBox history = new JComboBox();
865 JPanel panel = new JPanel(new GridLayout(2, 1));
868 history.setPreferredSize(new Dimension(400, 20));
869 history.setEditable(true);
870 history.addItem("http://www.");
872 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
876 if (historyItems != null)
878 st = new StringTokenizer(historyItems, "\t");
880 while (st.hasMoreTokens())
882 history.addItem(st.nextElement());
886 int reply = JOptionPane.showInternalConfirmDialog(desktop, panel,
887 "Input Alignment From URL", JOptionPane.OK_CANCEL_OPTION);
889 if (reply != JOptionPane.OK_OPTION)
894 String url = history.getSelectedItem().toString();
896 if (url.toLowerCase().endsWith(".jar"))
898 if (viewport != null)
900 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL,
905 new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
910 String format = new IdentifyFile().Identify(url, FormatAdapter.URL);
912 if (format.equals("URL NOT FOUND"))
914 JOptionPane.showInternalMessageDialog(Desktop.desktop,
915 "Couldn't locate " + url, "URL not found",
916 JOptionPane.WARNING_MESSAGE);
921 if (viewport != null)
923 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
927 new FileLoader().LoadFile(url, FormatAdapter.URL, format);
938 public void inputTextboxMenuItem_actionPerformed(AlignViewport viewport)
940 CutAndPasteTransfer cap = new CutAndPasteTransfer();
941 cap.setForInput(viewport);
942 Desktop.addInternalFrame(cap, "Cut & Paste Alignment File", 600, 500);
950 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
952 .setProperty("SCREENGEOMETRY_WIDTH", screen.width + "");
953 jalview.bin.Cache.setProperty("SCREENGEOMETRY_HEIGHT", screen.height
955 storeLastKnownDimensions("", new Rectangle(getBounds().x,
956 getBounds().y, getWidth(), getHeight()));
958 if (jconsole != null)
960 storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
961 jconsole.stopConsole();
965 storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
972 private void storeLastKnownDimensions(String string, Rectangle jc)
974 jalview.bin.Cache.log.debug("Storing last known dimensions for "
975 + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
976 + " height:" + jc.height);
978 jalview.bin.Cache.setProperty(string + "SCREEN_X", jc.x + "");
979 jalview.bin.Cache.setProperty(string + "SCREEN_Y", jc.y + "");
980 jalview.bin.Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
981 jalview.bin.Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
990 public void aboutMenuItem_actionPerformed(ActionEvent e)
992 StringBuffer message = new StringBuffer("Jalview version "
993 + jalview.bin.Cache.getProperty("VERSION") + "; last updated: "
994 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
996 if (!jalview.bin.Cache.getProperty("LATEST_VERSION").equals(
997 jalview.bin.Cache.getProperty("VERSION")))
999 message.append("\n\n!! Jalview version "
1000 + jalview.bin.Cache.getProperty("LATEST_VERSION")
1001 + " is available for download from "+jalview.bin.Cache.getDefault("www.jalview.org","http://www.jalview.org")+" !!\n");
1004 // TODO: update this text for each release or centrally store it for lite
1006 message.append("\nAuthors: Jim Procter, Andrew Waterhouse, Michele Clamp, James Cuff, Steve Searle,\n David Martin & Geoff Barton."
1007 + "\nDevelopment managed by The Barton Group, University of Dundee, Scotland, UK.\n"
1008 + "\nFor help, see the FAQ at www.jalview.org and/or join the jalview-discuss@jalview.org mailing list\n"
1009 + "\nIf you use Jalview, please cite:"
1010 + "\nWaterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
1011 + "\nJalview Version 2 - a multiple sequence alignment editor and analysis workbench"
1012 + "\nBioinformatics doi: 10.1093/bioinformatics/btp033");
1013 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1015 message.toString(), "About Jalview", JOptionPane.INFORMATION_MESSAGE);
1024 public void documentationMenuItem_actionPerformed(ActionEvent e)
1028 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
1029 java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
1030 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
1032 javax.help.HelpBroker hb = hs.createHelpBroker();
1033 hb.setCurrentID("home");
1034 hb.setDisplayed(true);
1035 } catch (Exception ex)
1040 public void closeAll_actionPerformed(ActionEvent e)
1042 JInternalFrame[] frames = desktop.getAllFrames();
1043 for (int i = 0; i < frames.length; i++)
1047 frames[i].setClosed(true);
1048 } catch (java.beans.PropertyVetoException ex)
1052 System.out.println("ALL CLOSED");
1053 if (v_client != null)
1055 // TODO clear binding to vamsas document objects on close_all
1060 public void raiseRelated_actionPerformed(ActionEvent e)
1062 reorderAssociatedWindows(false, false);
1065 public void minimizeAssociated_actionPerformed(ActionEvent e)
1067 reorderAssociatedWindows(true, false);
1070 void closeAssociatedWindows()
1072 reorderAssociatedWindows(false, true);
1078 * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1081 protected void garbageCollect_actionPerformed(ActionEvent e)
1083 // We simply collect the garbage
1084 jalview.bin.Cache.log.debug("Collecting garbage...");
1086 jalview.bin.Cache.log.debug("Finished garbage collection.");
1093 * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
1096 protected void showMemusage_actionPerformed(ActionEvent e)
1098 desktop.showMemoryUsage(showMemusage.isSelected());
1105 * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1108 protected void showConsole_actionPerformed(ActionEvent e)
1110 showConsole(showConsole.isSelected());
1113 Console jconsole = null;
1116 * control whether the java console is visible or not
1120 void showConsole(boolean selected)
1122 showConsole.setSelected(selected);
1123 // TODO: decide if we should update properties file
1124 Cache.setProperty("SHOW_JAVA_CONSOLE", Boolean.valueOf(selected)
1126 jconsole.setVisible(selected);
1129 void reorderAssociatedWindows(boolean minimize, boolean close)
1131 JInternalFrame[] frames = desktop.getAllFrames();
1132 if (frames == null || frames.length < 1)
1137 AlignViewport source = null, target = null;
1138 if (frames[0] instanceof AlignFrame)
1140 source = ((AlignFrame) frames[0]).getCurrentView();
1142 else if (frames[0] instanceof TreePanel)
1144 source = ((TreePanel) frames[0]).getViewPort();
1146 else if (frames[0] instanceof PCAPanel)
1148 source = ((PCAPanel) frames[0]).av;
1150 else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1152 source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1157 for (int i = 0; i < frames.length; i++)
1160 if (frames[i] == null)
1164 if (frames[i] instanceof AlignFrame)
1166 target = ((AlignFrame) frames[i]).getCurrentView();
1168 else if (frames[i] instanceof TreePanel)
1170 target = ((TreePanel) frames[i]).getViewPort();
1172 else if (frames[i] instanceof PCAPanel)
1174 target = ((PCAPanel) frames[i]).av;
1176 else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1178 target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1181 if (source == target)
1187 frames[i].setClosed(true);
1191 frames[i].setIcon(minimize);
1194 frames[i].toFront();
1198 } catch (java.beans.PropertyVetoException ex)
1212 protected void preferences_actionPerformed(ActionEvent e)
1223 public void saveState_actionPerformed(ActionEvent e)
1225 JalviewFileChooser chooser = new JalviewFileChooser(
1226 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1227 { "jar" }, new String[]
1228 { "Jalview Project" }, "Jalview Project");
1230 chooser.setFileView(new JalviewFileView());
1231 chooser.setDialogTitle("Save State");
1233 int value = chooser.showSaveDialog(this);
1235 if (value == JalviewFileChooser.APPROVE_OPTION)
1237 final Desktop me = this;
1238 final java.io.File choice = chooser.getSelectedFile();
1239 new Thread(new Runnable()
1244 setProgressBar("Saving jalview project " + choice.getName(),
1246 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1247 // TODO catch and handle errors for savestate
1248 // TODO prevent user from messing with the Desktop whilst we're saving
1251 new Jalview2XML().SaveState(choice);
1252 } catch (OutOfMemoryError oom)
1255 "Whilst saving current state to " + choice.getName(), oom);
1256 } catch (Exception ex)
1259 .error("Problems whilst trying to save to "
1260 + choice.getName(), ex);
1261 JOptionPane.showMessageDialog(me,
1262 "Error whilst saving current state to " + choice.getName(),
1263 "Couldn't save project", JOptionPane.WARNING_MESSAGE);
1265 setProgressBar(null, choice.hashCode());
1277 public void loadState_actionPerformed(ActionEvent e)
1279 JalviewFileChooser chooser = new JalviewFileChooser(
1280 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1281 { "jar" }, new String[]
1282 { "Jalview Project" }, "Jalview Project");
1283 chooser.setFileView(new JalviewFileView());
1284 chooser.setDialogTitle("Restore state");
1286 int value = chooser.showOpenDialog(this);
1288 if (value == JalviewFileChooser.APPROVE_OPTION)
1290 final String choice = chooser.getSelectedFile().getAbsolutePath();
1291 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
1292 .getSelectedFile().getParent());
1293 new Thread(new Runnable()
1297 setProgressBar("loading jalview project " + choice,
1301 new Jalview2XML().LoadJalviewAlign(choice);
1302 } catch (OutOfMemoryError oom)
1304 new OOMWarning("Whilst loading project from " + choice, oom);
1305 } catch (Exception ex)
1307 Cache.log.error("Problems whilst loading project from "
1309 JOptionPane.showMessageDialog(Desktop.desktop,
1310 "Error whilst loading project from " + choice,
1311 "Couldn't load project", JOptionPane.WARNING_MESSAGE);
1313 setProgressBar(null, choice.hashCode());
1319 public void inputSequence_actionPerformed(ActionEvent e)
1321 new SequenceFetcher(this);
1324 JPanel progressPanel;
1325 ArrayList<JPanel> fileLoadingPanels=new ArrayList<JPanel>();
1326 public void startLoading(final String fileName)
1328 if (fileLoadingCount == 0)
1330 fileLoadingPanels.add(addProgressPanel("Loading File: " + fileName + " "));
1335 private JPanel addProgressPanel(String string)
1337 if (progressPanel == null)
1339 progressPanel = new JPanel(new GridLayout(1,1));
1340 totalProgressCount = 0;
1341 instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
1343 JPanel thisprogress=new JPanel(new BorderLayout(10,5));
1344 JProgressBar progressBar = new JProgressBar();
1345 progressBar.setIndeterminate(true);
1347 thisprogress.add(new JLabel(string), BorderLayout.WEST);
1349 thisprogress.add(progressBar, BorderLayout.CENTER);
1350 progressPanel.add(thisprogress);
1351 ((GridLayout)progressPanel.getLayout()).setRows(((GridLayout)progressPanel.getLayout()).getRows()+1);
1352 ++totalProgressCount;
1353 instance.validate();
1354 return thisprogress;
1357 int totalProgressCount = 0;
1359 private void removeProgressPanel(JPanel progbar)
1361 if (progressPanel != null)
1363 progressPanel.remove(progbar);
1364 GridLayout gl = (GridLayout) progressPanel.getLayout();
1365 gl.setRows(gl.getRows()-1);
1366 if (--totalProgressCount < 1)
1368 this.getContentPane().remove(progressPanel);
1369 progressPanel = null;
1375 public void stopLoading()
1378 if (fileLoadingCount < 1)
1380 for (JPanel flp : fileLoadingPanels)
1382 removeProgressPanel(flp);
1384 fileLoadingPanels.clear();
1385 fileLoadingCount = 0;
1390 public static int getViewCount(String alignmentId)
1392 AlignViewport[] aps = getViewports(alignmentId);
1393 return (aps == null) ? 0 : aps.length;
1398 * @param alignmentId
1399 * @return all AlignmentPanels concerning the alignmentId sequence set
1401 public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
1404 if (Desktop.desktop == null)
1406 // no frames created and in headless mode
1407 // TODO: verify that frames are recoverable when in headless mode
1410 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1411 ArrayList aps = new ArrayList();
1412 for (int t = 0; t < frames.length; t++)
1414 if (frames[t] instanceof AlignFrame)
1416 AlignFrame af = (AlignFrame) frames[t];
1417 for (int a = 0; a < af.alignPanels.size(); a++)
1420 .equals(((AlignmentPanel) af.alignPanels.elementAt(a)).av
1421 .getSequenceSetId()))
1423 aps.add(af.alignPanels.elementAt(a));
1428 if (aps.size() == 0)
1432 AlignmentPanel[] vap = new AlignmentPanel[aps.size()];
1433 for (int t = 0; t < vap.length; t++)
1435 vap[t] = (AlignmentPanel) aps.get(t);
1441 * get all the viewports on an alignment.
1443 * @param sequenceSetId
1444 * unique alignment id
1445 * @return all viewports on the alignment bound to sequenceSetId
1447 public static AlignViewport[] getViewports(String sequenceSetId)
1449 Vector viewp = new Vector();
1450 if (desktop != null)
1452 javax.swing.JInternalFrame[] frames = instance.getAllFrames();
1454 for (int t = 0; t < frames.length; t++)
1456 if (frames[t] instanceof AlignFrame)
1458 AlignFrame afr = ((AlignFrame) frames[t]);
1459 if (afr.getViewport().getSequenceSetId().equals(sequenceSetId))
1461 if (afr.alignPanels != null)
1463 for (int a = 0; a < afr.alignPanels.size(); a++)
1465 if (sequenceSetId.equals(((AlignmentPanel) afr.alignPanels
1466 .elementAt(a)).av.getSequenceSetId()))
1468 viewp.addElement(((AlignmentPanel) afr.alignPanels
1475 viewp.addElement(((AlignFrame) frames[t]).getViewport());
1480 if (viewp.size() > 0)
1482 AlignViewport[] vp = new AlignViewport[viewp.size()];
1490 public void explodeViews(AlignFrame af)
1492 int size = af.alignPanels.size();
1498 for (int i = 0; i < size; i++)
1500 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(i);
1501 AlignFrame newaf = new AlignFrame(ap);
1502 if (ap.av.explodedPosition != null
1503 && !ap.av.explodedPosition.equals(af.getBounds()))
1505 newaf.setBounds(ap.av.explodedPosition);
1508 ap.av.gatherViewsHere = false;
1510 addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1511 AlignFrame.DEFAULT_HEIGHT);
1514 af.alignPanels.clear();
1515 af.closeMenuItem_actionPerformed(true);
1519 public void gatherViews(AlignFrame source)
1521 source.viewport.gatherViewsHere = true;
1522 source.viewport.explodedPosition = source.getBounds();
1523 JInternalFrame[] frames = desktop.getAllFrames();
1524 String viewId = source.viewport.sequenceSetID;
1526 for (int t = 0; t < frames.length; t++)
1528 if (frames[t] instanceof AlignFrame && frames[t] != source)
1530 AlignFrame af = (AlignFrame) frames[t];
1531 boolean gatherThis = false;
1532 for (int a = 0; a < af.alignPanels.size(); a++)
1534 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(a);
1535 if (viewId.equals(ap.av.getSequenceSetId()))
1538 ap.av.gatherViewsHere = false;
1539 ap.av.explodedPosition = af.getBounds();
1540 source.addAlignmentPanel(ap, false);
1546 af.alignPanels.clear();
1547 af.closeMenuItem_actionPerformed(true);
1554 jalview.gui.VamsasApplication v_client = null;
1556 public void vamsasImport_actionPerformed(ActionEvent e)
1558 if (v_client == null)
1560 // Load and try to start a session.
1561 JalviewFileChooser chooser = new JalviewFileChooser(
1562 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1564 chooser.setFileView(new JalviewFileView());
1565 chooser.setDialogTitle("Open a saved VAMSAS session");
1566 chooser.setToolTipText("select a vamsas session to be opened as a new vamsas session.");
1568 int value = chooser.showOpenDialog(this);
1570 if (value == JalviewFileChooser.APPROVE_OPTION)
1572 String fle = chooser.getSelectedFile().toString();
1573 if (!vamsasImport(chooser.getSelectedFile()))
1575 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1576 "Couldn't import '" + fle + "' as a new vamsas session.",
1577 "Vamsas Document Import Failed",
1578 JOptionPane.ERROR_MESSAGE);
1584 jalview.bin.Cache.log
1585 .error("Implementation error - load session from a running session is not supported.");
1590 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1593 * @return true if import was a success and a session was started.
1595 public boolean vamsasImport(URL url)
1597 // TODO: create progress bar
1598 if (v_client != null)
1601 jalview.bin.Cache.log
1602 .error("Implementation error - load session from a running session is not supported.");
1608 // copy the URL content to a temporary local file
1609 // TODO: be a bit cleverer here with nio (?!)
1610 File file = File.createTempFile("vdocfromurl", ".vdj");
1611 FileOutputStream fos = new FileOutputStream(file);
1612 BufferedInputStream bis = new BufferedInputStream(url.openStream());
1613 byte[] buffer = new byte[2048];
1615 while ((ln = bis.read(buffer)) > -1)
1617 fos.write(buffer, 0, ln);
1621 v_client = new jalview.gui.VamsasApplication(this, file,
1622 url.toExternalForm());
1623 } catch (Exception ex)
1625 jalview.bin.Cache.log.error(
1626 "Failed to create new vamsas session from contents of URL "
1630 setupVamsasConnectedGui();
1631 v_client.initial_update(); // TODO: thread ?
1632 return v_client.inSession();
1636 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1639 * @return true if import was a success and a session was started.
1641 public boolean vamsasImport(File file)
1643 if (v_client != null)
1646 jalview.bin.Cache.log
1647 .error("Implementation error - load session from a running session is not supported.");
1651 setProgressBar("Importing VAMSAS session from " + file.getName(),
1655 v_client = new jalview.gui.VamsasApplication(this, file, null);
1656 } catch (Exception ex)
1658 setProgressBar("Importing VAMSAS session from " + file.getName(),
1660 jalview.bin.Cache.log.error(
1661 "New vamsas session from existing session file failed:", ex);
1664 setupVamsasConnectedGui();
1665 v_client.initial_update(); // TODO: thread ?
1666 setProgressBar("Importing VAMSAS session from " + file.getName(),
1668 return v_client.inSession();
1671 public boolean joinVamsasSession(String mysesid)
1673 if (v_client != null)
1676 "Trying to join a vamsas session when another is already connected.");
1678 if (mysesid == null)
1680 throw new Error("Invalid vamsas session id.");
1682 v_client = new VamsasApplication(this, mysesid);
1683 setupVamsasConnectedGui();
1684 v_client.initial_update();
1685 return (v_client.inSession());
1688 public void vamsasStart_actionPerformed(ActionEvent e)
1690 if (v_client == null)
1693 // we just start a default session for moment.
1695 * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
1696 * getProperty("LAST_DIRECTORY"));
1698 * chooser.setFileView(new JalviewFileView());
1699 * chooser.setDialogTitle("Load Vamsas file");
1700 * chooser.setToolTipText("Import");
1702 * int value = chooser.showOpenDialog(this);
1704 * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
1705 * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
1707 v_client = new VamsasApplication(this);
1708 setupVamsasConnectedGui();
1709 v_client.initial_update(); // TODO: thread ?
1713 // store current data in session.
1714 v_client.push_update(); // TODO: thread
1718 protected void setupVamsasConnectedGui()
1720 vamsasStart.setText("Session Update");
1721 vamsasSave.setVisible(true);
1722 vamsasStop.setVisible(true);
1723 vamsasImport.setVisible(false); // Document import to existing session is
1724 // not possible for vamsas-client-1.0.
1727 protected void setupVamsasDisconnectedGui()
1729 vamsasSave.setVisible(false);
1730 vamsasStop.setVisible(false);
1731 vamsasImport.setVisible(true);
1732 vamsasStart.setText("New Vamsas Session");
1735 public void vamsasStop_actionPerformed(ActionEvent e)
1737 if (v_client != null)
1739 v_client.end_session();
1741 setupVamsasDisconnectedGui();
1745 protected void buildVamsasStMenu()
1747 if (v_client == null)
1749 String[] sess = null;
1752 sess = VamsasApplication.getSessionList();
1753 } catch (Exception e)
1755 jalview.bin.Cache.log.warn(
1756 "Problem getting current sessions list.", e);
1761 jalview.bin.Cache.log.debug("Got current sessions list: "
1762 + sess.length + " entries.");
1763 VamsasStMenu.removeAll();
1764 for (int i = 0; i < sess.length; i++)
1766 JMenuItem sessit = new JMenuItem();
1767 sessit.setText(sess[i]);
1768 sessit.setToolTipText("Connect to session " + sess[i]);
1769 final Desktop dsktp = this;
1770 final String mysesid = sess[i];
1771 sessit.addActionListener(new ActionListener()
1774 public void actionPerformed(ActionEvent e)
1776 if (dsktp.v_client == null)
1778 Thread rthr = new Thread(new Runnable()
1783 dsktp.v_client = new VamsasApplication(dsktp, mysesid);
1784 dsktp.setupVamsasConnectedGui();
1785 dsktp.v_client.initial_update();
1793 VamsasStMenu.add(sessit);
1795 // don't show an empty menu.
1796 VamsasStMenu.setVisible(sess.length > 0);
1801 jalview.bin.Cache.log.debug("No current vamsas sessions.");
1802 VamsasStMenu.removeAll();
1803 VamsasStMenu.setVisible(false);
1808 // Not interested in the content. Just hide ourselves.
1809 VamsasStMenu.setVisible(false);
1813 public void vamsasSave_actionPerformed(ActionEvent e)
1815 if (v_client != null)
1817 JalviewFileChooser chooser = new JalviewFileChooser(
1818 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1819 { "vdj" }, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
1821 { "Vamsas Document" }, "Vamsas Document");
1823 chooser.setFileView(new JalviewFileView());
1824 chooser.setDialogTitle("Save Vamsas Document Archive");
1826 int value = chooser.showSaveDialog(this);
1828 if (value == JalviewFileChooser.APPROVE_OPTION)
1830 java.io.File choice = chooser.getSelectedFile();
1831 JPanel progpanel = addProgressPanel("Saving VAMSAS Document to "
1832 + choice.getName());
1833 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1834 String warnmsg = null;
1835 String warnttl = null;
1838 v_client.vclient.storeDocument(choice);
1841 warnttl = "Serious Problem saving Vamsas Document";
1842 warnmsg = ex.toString();
1843 jalview.bin.Cache.log.error("Error Whilst saving document to "
1846 } catch (Exception ex)
1848 warnttl = "Problem saving Vamsas Document.";
1849 warnmsg = ex.toString();
1850 jalview.bin.Cache.log.warn("Exception Whilst saving document to "
1854 removeProgressPanel(progpanel);
1855 if (warnmsg != null)
1857 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1859 warnmsg, warnttl, JOptionPane.ERROR_MESSAGE);
1865 JPanel vamUpdate = null;
1868 * hide vamsas user gui bits when a vamsas document event is being handled.
1871 * true to hide gui, false to reveal gui
1873 public void setVamsasUpdate(boolean b)
1875 jalview.bin.Cache.log.debug("Setting gui for Vamsas update "
1876 + (b ? "in progress" : "finished"));
1878 if (vamUpdate != null)
1880 this.removeProgressPanel(vamUpdate);
1884 vamUpdate = this.addProgressPanel("Updating vamsas session");
1886 vamsasStart.setVisible(!b);
1887 vamsasStop.setVisible(!b);
1888 vamsasSave.setVisible(!b);
1891 public JInternalFrame[] getAllFrames()
1893 return desktop.getAllFrames();
1897 * Checks the given url to see if it gives a response indicating that the user
1898 * should be informed of a new questionnaire.
1902 public void checkForQuestionnaire(String url)
1904 UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
1905 // javax.swing.SwingUtilities.invokeLater(jvq);
1906 new Thread(jvq).start();
1910 * Proxy class for JDesktopPane which optionally displays the current memory
1911 * usage and highlights the desktop area with a red bar if free memory runs
1916 public class MyDesktopPane extends JDesktopPane implements Runnable
1919 boolean showMemoryUsage = false;
1923 java.text.NumberFormat df;
1925 float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
1928 public MyDesktopPane(boolean showMemoryUsage)
1930 showMemoryUsage(showMemoryUsage);
1933 public void showMemoryUsage(boolean showMemoryUsage)
1935 this.showMemoryUsage = showMemoryUsage;
1936 if (showMemoryUsage)
1938 Thread worker = new Thread(this);
1943 public boolean isShowMemoryUsage()
1945 return showMemoryUsage;
1950 df = java.text.NumberFormat.getNumberInstance();
1951 df.setMaximumFractionDigits(2);
1952 runtime = Runtime.getRuntime();
1954 while (showMemoryUsage)
1958 maxMemory = runtime.maxMemory() / 1048576f;
1959 allocatedMemory = runtime.totalMemory() / 1048576f;
1960 freeMemory = runtime.freeMemory() / 1048576f;
1961 totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
1963 percentUsage = (totalFreeMemory / maxMemory) * 100;
1965 // if (percentUsage < 20)
1967 // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
1969 // instance.set.setBorder(border1);
1972 // sleep after showing usage
1974 } catch (Exception ex)
1976 ex.printStackTrace();
1981 public void paintComponent(Graphics g)
1983 if (showMemoryUsage && g != null && df != null)
1985 if (percentUsage < 20)
1986 g.setColor(Color.red);
1987 FontMetrics fm = g.getFontMetrics();
1991 "Total Free Memory: " + df.format(totalFreeMemory)
1992 + "MB; Max Memory: " + df.format(maxMemory)
1993 + "MB; " + df.format(percentUsage) + "%", 10,
1994 getHeight() - fm.getHeight());
2002 * fixes stacking order after a modal dialog to ensure windows that should be on top actually are
2004 public void relayerWindows()
2006 if (jvnews!=null && jvnews.isVisible())
2012 protected JMenuItem groovyShell;
2014 public void doGroovyCheck()
2016 if (jalview.bin.Cache.groovyJarsPresent())
2018 groovyShell = new JMenuItem();
2019 groovyShell.setText("Groovy Console...");
2020 groovyShell.addActionListener(new ActionListener()
2022 public void actionPerformed(ActionEvent e)
2024 groovyShell_actionPerformed(e);
2027 toolsMenu.add(groovyShell);
2028 groovyShell.setVisible(true);
2033 * Accessor method to quickly get all the AlignmentFrames loaded.
2035 public static AlignFrame[] getAlignframes()
2037 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2043 Vector avp = new Vector();
2047 for (int i = frames.length - 1; i > -1; i--)
2049 if (frames[i] instanceof AlignFrame)
2051 AlignFrame af = (AlignFrame) frames[i];
2055 } catch (Exception ex)
2057 ex.printStackTrace();
2059 if (avp.size() == 0)
2063 AlignFrame afs[] = new AlignFrame[avp.size()];
2064 for (int i = 0, j = avp.size(); i < j; i++)
2066 afs[i] = (AlignFrame) avp.elementAt(i);
2071 public AppJmol[] getJmols()
2073 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2079 Vector avp = new Vector();
2083 for (int i = frames.length - 1; i > -1; i--)
2085 if (frames[i] instanceof AppJmol)
2087 AppJmol af = (AppJmol) frames[i];
2091 } catch (Exception ex)
2093 ex.printStackTrace();
2095 if (avp.size() == 0)
2099 AppJmol afs[] = new AppJmol[avp.size()];
2100 for (int i = 0, j = avp.size(); i < j; i++)
2102 afs[i] = (AppJmol) avp.elementAt(i);
2109 * Add Groovy Support to Jalview
2111 public void groovyShell_actionPerformed(ActionEvent e)
2113 // use reflection to avoid creating compilation dependency.
2114 if (!jalview.bin.Cache.groovyJarsPresent())
2117 "Implementation Error. Cannot create groovyShell without Groovy on the classpath!");
2121 Class gcClass = Desktop.class.getClassLoader().loadClass(
2122 "groovy.ui.Console");
2123 Constructor gccons = gcClass.getConstructor(null);
2124 java.lang.reflect.Method setvar = gcClass.getMethod("setVariable",
2126 { String.class, Object.class });
2127 java.lang.reflect.Method run = gcClass.getMethod("run", null);
2128 Object gc = gccons.newInstance(null);
2129 setvar.invoke(gc, new Object[]
2130 { "Jalview", this });
2131 run.invoke(gc, null);
2132 } catch (Exception ex)
2134 jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
2136 .showInternalMessageDialog(
2139 "Couldn't create the groovy Shell. Check the error log for the details of what went wrong.",
2140 "Jalview Groovy Support Failed",
2141 JOptionPane.ERROR_MESSAGE);
2146 * Progress bars managed by the IProgressIndicator method.
2148 private Hashtable<Long,JPanel> progressBars;
2149 private Hashtable<Long,IProgressIndicatorHandler> progressBarHandlers;
2154 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2156 public void setProgressBar(String message, long id)
2158 if (progressBars == null)
2160 progressBars = new Hashtable<Long,JPanel>();
2161 progressBarHandlers = new Hashtable<Long,IProgressIndicatorHandler>();
2164 if (progressBars.get(new Long(id)) != null)
2166 JPanel progressPanel = progressBars
2167 .remove(new Long(id));
2168 if (progressBarHandlers.contains(new Long(id)))
2170 progressBarHandlers.remove(new Long(id));
2172 removeProgressPanel(progressPanel);
2176 progressBars.put(new Long(id), addProgressPanel(message));
2183 * @see jalview.gui.IProgressIndicator#registerHandler(long,
2184 * jalview.gui.IProgressIndicatorHandler)
2186 public void registerHandler(final long id,
2187 final IProgressIndicatorHandler handler)
2189 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
2192 "call setProgressBar before registering the progress bar's handler.");
2194 progressBarHandlers.put(new Long(id), handler);
2195 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
2196 if (handler.canCancel())
2198 JButton cancel = new JButton("Cancel");
2199 final IProgressIndicator us = this;
2200 cancel.addActionListener(new ActionListener()
2203 public void actionPerformed(ActionEvent e)
2205 handler.cancelActivity(id);
2208 + ((JLabel) progressPanel.getComponent(0))
2212 progressPanel.add(cancel, BorderLayout.EAST);
2217 * This will return the first AlignFrame viewing AlignViewport av. It will
2218 * break if there are more than one AlignFrames viewing a particular av. This
2221 * @return alignFrame for av
2223 public static AlignFrame getAlignFrameFor(AlignViewport av)
2225 if (desktop != null)
2227 AlignmentPanel[] aps = getAlignmentPanels(av.getSequenceSetId());
2228 for (int panel = 0; aps != null && panel < aps.length; panel++)
2230 if (aps[panel] != null && aps[panel].av == av)
2232 return aps[panel].alignFrame;
2239 public VamsasApplication getVamsasApplication()
2246 * flag set if jalview GUI is being operated programmatically
2248 private boolean inBatchMode = false;
2251 * check if jalview GUI is being operated programmatically
2253 * @return inBatchMode
2255 public boolean isInBatchMode()
2261 * set flag if jalview GUI is being operated programmatically
2263 * @param inBatchMode
2265 public void setInBatchMode(boolean inBatchMode)
2267 this.inBatchMode = inBatchMode;
2270 public void startServiceDiscovery()
2272 startServiceDiscovery(false);
2275 public void startServiceDiscovery(boolean blocking)
2277 boolean alive = true;
2278 Thread t0 = null, t1 = null, t2 = null;
2280 // todo: changesupport handlers need to be transferred
2281 if (discoverer == null)
2283 discoverer = new jalview.ws.jws1.Discoverer();
2284 // register PCS handler for desktop.
2285 discoverer.addPropertyChangeListener(changeSupport);
2287 // JAL-940 - disabled JWS1 service configuration - always start discoverer until we phase out completely
2290 (t0 = new Thread(discoverer)).start();
2295 if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
2297 // EnfinEnvision web service menu entries are rebuild every time the
2298 // menu is shown, so no changeSupport events are needed.
2299 jalview.ws.EnfinEnvision2OneWay.getInstance();
2300 (t1 = new Thread(jalview.ws.EnfinEnvision2OneWay.getInstance()))
2303 } catch (Exception e)
2306 .info("Exception when trying to launch Envision2 workflow discovery.",
2308 Cache.log.info(e.getStackTrace());
2310 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
2312 if (jalview.ws.jws2.Jws2Discoverer.getDiscoverer().isRunning())
2314 jalview.ws.jws2.Jws2Discoverer.getDiscoverer().setAborted(true);
2316 t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer().startDiscoverer(
2322 // TODO: do rest service discovery
2331 } catch (Exception e)
2334 alive = (t1 != null && t1.isAlive())
2335 || (t2 != null && t2.isAlive())
2336 || (t3 != null && t3.isAlive())
2337 || (t0 != null && t0.isAlive());
2343 * called to check if the service discovery process completed successfully.
2347 protected void JalviewServicesChanged(PropertyChangeEvent evt)
2349 if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
2351 final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2352 .getErrorMessages();
2355 if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
2357 if (serviceChangedDialog == null)
2359 // only run if we aren't already displaying one of these.
2360 javax.swing.SwingUtilities
2361 .invokeLater(serviceChangedDialog = new Runnable()
2367 .showInternalMessageDialog(
2370 + "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",
2371 "Preferences Problem",
2372 JOptionPane.WARNING_MESSAGE);
2373 serviceChangedDialog = null;
2382 .error("Errors reported by JABA discovery service. Check web services preferences.\n"
2389 private Runnable serviceChangedDialog = null;
2392 * start a thread to open a URL in the configured browser. Pops up a warning
2393 * dialog to the user if there is an exception when calling out to the browser
2398 public static void showUrl(final String url)
2400 showUrl(url, Desktop.instance);
2403 * Like showUrl but allows progress handler to be specified
2405 * @param progress (null) or object implementing IProgressIndicator
2407 public static void showUrl(final String url, final IProgressIndicator progress)
2409 new Thread(new Runnable()
2415 if (progress!=null) {
2416 progress.setProgressBar("Opening "+url, this.hashCode());
2418 jalview.util.BrowserLauncher.openURL(url);
2419 } catch (Exception ex)
2422 .showInternalMessageDialog(
2424 "Unixers: Couldn't find default web browser."
2425 + "\nAdd the full path to your browser in Preferences.",
2426 "Web browser not found",
2427 JOptionPane.WARNING_MESSAGE);
2429 ex.printStackTrace();
2431 if (progress!=null) {
2432 progress.setProgressBar(null, this.hashCode());
2438 public static WsParamSetManager wsparamManager = null;
2440 public static ParamManager getUserParameterStore()
2442 if (wsparamManager == null)
2444 wsparamManager = new WsParamSetManager();
2446 return wsparamManager;