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 default1)
355 jvnews.setVisible(default1);
358 jvnews.refreshNews();
365 * recover the last known dimensions for a jalview window
368 * - empty string is desktop, all other windows have unique prefix
369 * @return null or last known dimensions scaled to current geometry (if last
370 * window geom was known)
372 Rectangle getLastKnownDimensions(String windowName)
374 // TODO: lock aspect ratio for scaling desktop Bug #0058199
375 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
376 String x = jalview.bin.Cache.getProperty(windowName + "SCREEN_X");
377 String y = jalview.bin.Cache.getProperty(windowName + "SCREEN_Y");
378 String width = jalview.bin.Cache.getProperty(windowName
380 String height = jalview.bin.Cache.getProperty(windowName
382 if ((x != null) && (y != null) && (width != null) && (height != null))
384 int ix = Integer.parseInt(x), iy = Integer.parseInt(y), iw = Integer
385 .parseInt(width), ih = Integer.parseInt(height);
386 if (jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
388 // attempt #1 - try to cope with change in screen geometry - this
389 // version doesn't preserve original jv aspect ratio.
390 // take ratio of current screen size vs original screen size.
391 double sw = ((1f * screenSize.width) / (1f * Integer
392 .parseInt(jalview.bin.Cache
393 .getProperty("SCREENGEOMETRY_WIDTH"))));
394 double sh = ((1f * screenSize.height) / (1f * Integer
395 .parseInt(jalview.bin.Cache
396 .getProperty("SCREENGEOMETRY_HEIGHT"))));
397 // rescale the bounds depending upon the current screen geometry.
398 ix = (int) (ix * sw);
399 iw = (int) (iw * sw);
400 iy = (int) (iy * sh);
401 ih = (int) (ih * sh);
402 while (ix >= screenSize.width)
404 jalview.bin.Cache.log
405 .debug("Window geometry location recall error: shifting horizontal to within screenbounds.");
406 ix -= screenSize.width;
408 while (iy >= screenSize.height)
410 jalview.bin.Cache.log
411 .debug("Window geometry location recall error: shifting vertical to within screenbounds.");
412 iy -= screenSize.height;
414 jalview.bin.Cache.log.debug("Got last known dimensions for "
415 + windowName + ": x:" + ix + " y:" + iy + " width:" + iw
418 // return dimensions for new instance
419 return new Rectangle(ix, iy, iw, ih);
424 private void doVamsasClientCheck()
426 if (jalview.bin.Cache.vamsasJarsPresent())
428 setupVamsasDisconnectedGui();
429 VamsasMenu.setVisible(true);
430 final Desktop us = this;
431 VamsasMenu.addMenuListener(new MenuListener()
433 // this listener remembers when the menu was first selected, and
434 // doesn't rebuild the session list until it has been cleared and
436 boolean refresh = true;
438 public void menuCanceled(MenuEvent e)
443 public void menuDeselected(MenuEvent e)
448 public void menuSelected(MenuEvent e)
452 us.buildVamsasStMenu();
457 vamsasStart.setVisible(true);
461 void showPasteMenu(int x, int y)
463 JPopupMenu popup = new JPopupMenu();
464 JMenuItem item = new JMenuItem("Paste To New Window");
465 item.addActionListener(new ActionListener()
467 public void actionPerformed(ActionEvent evt)
474 popup.show(this, x, y);
481 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
482 Transferable contents = c.getContents(this);
484 if (contents != null)
486 String file = (String) contents
487 .getTransferData(DataFlavor.stringFlavor);
489 String format = new IdentifyFile().Identify(file,
490 FormatAdapter.PASTE);
492 new FileLoader().LoadFile(file, FormatAdapter.PASTE, format);
495 } catch (Exception ex)
498 .println("Unable to paste alignment from system clipboard:\n"
504 * Adds and opens the given frame to the desktop
515 public static synchronized void addInternalFrame(
516 final JInternalFrame frame, String title, int w, int h)
518 addInternalFrame(frame, title, w, h, true);
535 public static synchronized void addInternalFrame(
536 final JInternalFrame frame, String title, int w, int h,
540 // TODO: allow callers to determine X and Y position of frame (eg. via
542 // TODO: consider fixing method to update entries in the window submenu with
543 // the current window title
545 frame.setTitle(title);
546 if (frame.getWidth() < 1 || frame.getHeight() < 1)
550 // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
551 // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
552 // IF JALVIEW IS RUNNING HEADLESS
553 // ///////////////////////////////////////////////
554 if (System.getProperty("java.awt.headless") != null
555 && System.getProperty("java.awt.headless").equals("true"))
562 frame.setVisible(true);
563 frame.setClosable(true);
564 frame.setResizable(resizable);
565 frame.setMaximizable(resizable);
566 frame.setIconifiable(resizable);
567 frame.setFrameIcon(null);
569 if (frame.getX() < 1 && frame.getY() < 1)
571 frame.setLocation(xOffset * openFrameCount, yOffset
572 * ((openFrameCount - 1) % 10) + yOffset);
575 final JMenuItem menuItem = new JMenuItem(title);
576 frame.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
578 public void internalFrameActivated(
579 javax.swing.event.InternalFrameEvent evt)
581 JInternalFrame itf = desktop.getSelectedFrame();
589 public void internalFrameClosed(
590 javax.swing.event.InternalFrameEvent evt)
592 PaintRefresher.RemoveComponent(frame);
594 windowMenu.remove(menuItem);
595 JInternalFrame itf = desktop.getSelectedFrame();
604 menuItem.addActionListener(new ActionListener()
606 public void actionPerformed(ActionEvent e)
610 frame.setSelected(true);
611 frame.setIcon(false);
612 } catch (java.beans.PropertyVetoException ex)
618 menuItem.addMouseListener(new MouseListener()
622 public void mouseReleased(MouseEvent e)
627 public void mousePressed(MouseEvent e)
632 public void mouseExited(MouseEvent e)
636 frame.setSelected(false);
637 } catch (PropertyVetoException e1)
643 public void mouseEntered(MouseEvent e)
647 frame.setSelected(true);
648 } catch (PropertyVetoException e1)
654 public void mouseClicked(MouseEvent e)
660 windowMenu.add(menuItem);
666 frame.setSelected(true);
667 frame.requestFocus();
668 } catch (java.beans.PropertyVetoException ve)
671 catch (java.lang.ClassCastException cex)
673 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);
677 public void lostOwnership(Clipboard clipboard, Transferable contents)
681 Desktop.jalviewClipboard = null;
684 internalCopy = false;
687 public void dragEnter(DropTargetDragEvent evt)
691 public void dragExit(DropTargetEvent evt)
695 public void dragOver(DropTargetDragEvent evt)
699 public void dropActionChanged(DropTargetDragEvent evt)
709 public void drop(DropTargetDropEvent evt)
711 Transferable t = evt.getTransferable();
712 java.util.List files = null;
713 java.util.List protocols = null;
717 DataFlavor uriListFlavor = new DataFlavor(
718 "text/uri-list;class=java.lang.String");
719 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
721 // Works on Windows and MacOSX
722 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
723 files = (java.util.List) t
724 .getTransferData(DataFlavor.javaFileListFlavor);
726 else if (t.isDataFlavorSupported(uriListFlavor))
728 // This is used by Unix drag system
729 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
730 String data = (String) t.getTransferData(uriListFlavor);
731 files = new java.util.ArrayList(1);
732 protocols = new java.util.ArrayList(1);
733 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
734 data, "\r\n"); st.hasMoreTokens();)
736 String s = st.nextToken();
737 if (s.startsWith("#"))
739 // the line is a comment (as per the RFC 2483)
742 java.net.URI uri = new java.net.URI(s);
743 if (uri.getScheme().toLowerCase().startsWith("http"))
745 protocols.add(FormatAdapter.URL);
746 files.add(uri.toString());
750 // otherwise preserve old behaviour: catch all for file objects
751 java.io.File file = new java.io.File(uri);
752 protocols.add(FormatAdapter.FILE);
753 files.add(file.toString());
757 } catch (Exception e)
765 for (int i = 0; i < files.size(); i++)
767 String file = files.get(i).toString();
768 String protocol = (protocols == null) ? FormatAdapter.FILE
769 : (String) protocols.get(i);
770 String format = null;
772 if (file.endsWith(".jar"))
779 format = new IdentifyFile().Identify(file, protocol);
782 new FileLoader().LoadFile(file, protocol, format);
785 } catch (Exception ex)
797 public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
799 JalviewFileChooser chooser = new JalviewFileChooser(
800 jalview.bin.Cache.getProperty("LAST_DIRECTORY"),
801 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
802 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
803 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
805 chooser.setFileView(new JalviewFileView());
806 chooser.setDialogTitle("Open local file");
807 chooser.setToolTipText("Open");
809 int value = chooser.showOpenDialog(this);
811 if (value == JalviewFileChooser.APPROVE_OPTION)
813 String choice = chooser.getSelectedFile().getPath();
814 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
815 .getSelectedFile().getParent());
817 String format = null;
818 if (chooser.getSelectedFormat().equals("Jalview"))
824 format = new IdentifyFile().Identify(choice, FormatAdapter.FILE);
827 if (viewport != null)
829 new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE,
834 new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
845 public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
847 // This construct allows us to have a wider textfield
849 JLabel label = new JLabel("Enter URL of Input File");
850 final JComboBox history = new JComboBox();
852 JPanel panel = new JPanel(new GridLayout(2, 1));
855 history.setPreferredSize(new Dimension(400, 20));
856 history.setEditable(true);
857 history.addItem("http://www.");
859 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
863 if (historyItems != null)
865 st = new StringTokenizer(historyItems, "\t");
867 while (st.hasMoreTokens())
869 history.addItem(st.nextElement());
873 int reply = JOptionPane.showInternalConfirmDialog(desktop, panel,
874 "Input Alignment From URL", JOptionPane.OK_CANCEL_OPTION);
876 if (reply != JOptionPane.OK_OPTION)
881 String url = history.getSelectedItem().toString();
883 if (url.toLowerCase().endsWith(".jar"))
885 if (viewport != null)
887 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL,
892 new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
897 String format = new IdentifyFile().Identify(url, FormatAdapter.URL);
899 if (format.equals("URL NOT FOUND"))
901 JOptionPane.showInternalMessageDialog(Desktop.desktop,
902 "Couldn't locate " + url, "URL not found",
903 JOptionPane.WARNING_MESSAGE);
908 if (viewport != null)
910 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
914 new FileLoader().LoadFile(url, FormatAdapter.URL, format);
925 public void inputTextboxMenuItem_actionPerformed(AlignViewport viewport)
927 CutAndPasteTransfer cap = new CutAndPasteTransfer();
928 cap.setForInput(viewport);
929 Desktop.addInternalFrame(cap, "Cut & Paste Alignment File", 600, 500);
937 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
939 .setProperty("SCREENGEOMETRY_WIDTH", screen.width + "");
940 jalview.bin.Cache.setProperty("SCREENGEOMETRY_HEIGHT", screen.height
942 storeLastKnownDimensions("", new Rectangle(getBounds().x,
943 getBounds().y, getWidth(), getHeight()));
945 if (jconsole != null)
947 storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
948 jconsole.stopConsole();
952 storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
959 private void storeLastKnownDimensions(String string, Rectangle jc)
961 jalview.bin.Cache.log.debug("Storing last known dimensions for "
962 + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
963 + " height:" + jc.height);
965 jalview.bin.Cache.setProperty(string + "SCREEN_X", jc.x + "");
966 jalview.bin.Cache.setProperty(string + "SCREEN_Y", jc.y + "");
967 jalview.bin.Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
968 jalview.bin.Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
977 public void aboutMenuItem_actionPerformed(ActionEvent e)
979 StringBuffer message = new StringBuffer("Jalview version "
980 + jalview.bin.Cache.getProperty("VERSION") + "; last updated: "
981 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
983 if (!jalview.bin.Cache.getProperty("LATEST_VERSION").equals(
984 jalview.bin.Cache.getProperty("VERSION")))
986 message.append("\n\n!! Jalview version "
987 + jalview.bin.Cache.getProperty("LATEST_VERSION")
988 + " is available for download from "+jalview.bin.Cache.getDefault("www.jalview.org","http://www.jalview.org")+" !!\n");
991 // TODO: update this text for each release or centrally store it for lite
993 message.append("\nAuthors: Jim Procter, Andrew Waterhouse, Michele Clamp, James Cuff, Steve Searle,\n David Martin & Geoff Barton."
994 + "\nDevelopment managed by The Barton Group, University of Dundee, Scotland, UK.\n"
995 + "\nFor help, see the FAQ at www.jalview.org and/or join the jalview-discuss@jalview.org mailing list\n"
996 + "\nIf you use Jalview, please cite:"
997 + "\nWaterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
998 + "\nJalview Version 2 - a multiple sequence alignment editor and analysis workbench"
999 + "\nBioinformatics doi: 10.1093/bioinformatics/btp033");
1000 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1002 message.toString(), "About Jalview", JOptionPane.INFORMATION_MESSAGE);
1011 public void documentationMenuItem_actionPerformed(ActionEvent e)
1015 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
1016 java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
1017 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
1019 javax.help.HelpBroker hb = hs.createHelpBroker();
1020 hb.setCurrentID("home");
1021 hb.setDisplayed(true);
1022 } catch (Exception ex)
1027 public void closeAll_actionPerformed(ActionEvent e)
1029 JInternalFrame[] frames = desktop.getAllFrames();
1030 for (int i = 0; i < frames.length; i++)
1034 frames[i].setClosed(true);
1035 } catch (java.beans.PropertyVetoException ex)
1039 System.out.println("ALL CLOSED");
1040 if (v_client != null)
1042 // TODO clear binding to vamsas document objects on close_all
1047 public void raiseRelated_actionPerformed(ActionEvent e)
1049 reorderAssociatedWindows(false, false);
1052 public void minimizeAssociated_actionPerformed(ActionEvent e)
1054 reorderAssociatedWindows(true, false);
1057 void closeAssociatedWindows()
1059 reorderAssociatedWindows(false, true);
1065 * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1068 protected void garbageCollect_actionPerformed(ActionEvent e)
1070 // We simply collect the garbage
1071 jalview.bin.Cache.log.debug("Collecting garbage...");
1073 jalview.bin.Cache.log.debug("Finished garbage collection.");
1080 * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
1083 protected void showMemusage_actionPerformed(ActionEvent e)
1085 desktop.showMemoryUsage(showMemusage.isSelected());
1092 * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1095 protected void showConsole_actionPerformed(ActionEvent e)
1097 showConsole(showConsole.isSelected());
1100 Console jconsole = null;
1103 * control whether the java console is visible or not
1107 void showConsole(boolean selected)
1109 showConsole.setSelected(selected);
1110 // TODO: decide if we should update properties file
1111 Cache.setProperty("SHOW_JAVA_CONSOLE", Boolean.valueOf(selected)
1113 jconsole.setVisible(selected);
1116 void reorderAssociatedWindows(boolean minimize, boolean close)
1118 JInternalFrame[] frames = desktop.getAllFrames();
1119 if (frames == null || frames.length < 1)
1124 AlignViewport source = null, target = null;
1125 if (frames[0] instanceof AlignFrame)
1127 source = ((AlignFrame) frames[0]).getCurrentView();
1129 else if (frames[0] instanceof TreePanel)
1131 source = ((TreePanel) frames[0]).getViewPort();
1133 else if (frames[0] instanceof PCAPanel)
1135 source = ((PCAPanel) frames[0]).av;
1137 else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1139 source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1144 for (int i = 0; i < frames.length; i++)
1147 if (frames[i] == null)
1151 if (frames[i] instanceof AlignFrame)
1153 target = ((AlignFrame) frames[i]).getCurrentView();
1155 else if (frames[i] instanceof TreePanel)
1157 target = ((TreePanel) frames[i]).getViewPort();
1159 else if (frames[i] instanceof PCAPanel)
1161 target = ((PCAPanel) frames[i]).av;
1163 else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1165 target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1168 if (source == target)
1174 frames[i].setClosed(true);
1178 frames[i].setIcon(minimize);
1181 frames[i].toFront();
1185 } catch (java.beans.PropertyVetoException ex)
1199 protected void preferences_actionPerformed(ActionEvent e)
1210 public void saveState_actionPerformed(ActionEvent e)
1212 JalviewFileChooser chooser = new JalviewFileChooser(
1213 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1214 { "jar" }, new String[]
1215 { "Jalview Project" }, "Jalview Project");
1217 chooser.setFileView(new JalviewFileView());
1218 chooser.setDialogTitle("Save State");
1220 int value = chooser.showSaveDialog(this);
1222 if (value == JalviewFileChooser.APPROVE_OPTION)
1224 final Desktop me = this;
1225 final java.io.File choice = chooser.getSelectedFile();
1226 new Thread(new Runnable()
1231 setProgressBar("Saving jalview project " + choice.getName(),
1233 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1234 // TODO catch and handle errors for savestate
1235 // TODO prevent user from messing with the Desktop whilst we're saving
1238 new Jalview2XML().SaveState(choice);
1239 } catch (OutOfMemoryError oom)
1242 "Whilst saving current state to " + choice.getName(), oom);
1243 } catch (Exception ex)
1246 .error("Problems whilst trying to save to "
1247 + choice.getName(), ex);
1248 JOptionPane.showMessageDialog(me,
1249 "Error whilst saving current state to " + choice.getName(),
1250 "Couldn't save project", JOptionPane.WARNING_MESSAGE);
1252 setProgressBar(null, choice.hashCode());
1264 public void loadState_actionPerformed(ActionEvent e)
1266 JalviewFileChooser chooser = new JalviewFileChooser(
1267 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1268 { "jar" }, new String[]
1269 { "Jalview Project" }, "Jalview Project");
1270 chooser.setFileView(new JalviewFileView());
1271 chooser.setDialogTitle("Restore state");
1273 int value = chooser.showOpenDialog(this);
1275 if (value == JalviewFileChooser.APPROVE_OPTION)
1277 final String choice = chooser.getSelectedFile().getAbsolutePath();
1278 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
1279 .getSelectedFile().getParent());
1280 new Thread(new Runnable()
1284 setProgressBar("loading jalview project " + choice,
1288 new Jalview2XML().LoadJalviewAlign(choice);
1289 } catch (OutOfMemoryError oom)
1291 new OOMWarning("Whilst loading project from " + choice, oom);
1292 } catch (Exception ex)
1294 Cache.log.error("Problems whilst loading project from "
1296 JOptionPane.showMessageDialog(Desktop.desktop,
1297 "Error whilst loading project from " + choice,
1298 "Couldn't load project", JOptionPane.WARNING_MESSAGE);
1300 setProgressBar(null, choice.hashCode());
1306 public void inputSequence_actionPerformed(ActionEvent e)
1308 new SequenceFetcher(this);
1311 JPanel progressPanel;
1312 ArrayList<JPanel> fileLoadingPanels=new ArrayList<JPanel>();
1313 public void startLoading(final String fileName)
1315 if (fileLoadingCount == 0)
1317 fileLoadingPanels.add(addProgressPanel("Loading File: " + fileName + " "));
1322 private JPanel addProgressPanel(String string)
1324 if (progressPanel == null)
1326 progressPanel = new JPanel(new GridLayout(1,1));
1327 totalProgressCount = 0;
1328 instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
1330 JPanel thisprogress=new JPanel(new BorderLayout(10,5));
1331 JProgressBar progressBar = new JProgressBar();
1332 progressBar.setIndeterminate(true);
1334 thisprogress.add(new JLabel(string), BorderLayout.WEST);
1336 thisprogress.add(progressBar, BorderLayout.CENTER);
1337 progressPanel.add(thisprogress);
1338 ((GridLayout)progressPanel.getLayout()).setRows(((GridLayout)progressPanel.getLayout()).getRows()+1);
1339 ++totalProgressCount;
1340 instance.validate();
1341 return thisprogress;
1344 int totalProgressCount = 0;
1346 private void removeProgressPanel(JPanel progbar)
1348 if (progressPanel != null)
1350 progressPanel.remove(progbar);
1351 GridLayout gl = (GridLayout) progressPanel.getLayout();
1352 gl.setRows(gl.getRows()-1);
1353 if (--totalProgressCount < 1)
1355 this.getContentPane().remove(progressPanel);
1356 progressPanel = null;
1362 public void stopLoading()
1365 if (fileLoadingCount < 1)
1367 for (JPanel flp : fileLoadingPanels)
1369 removeProgressPanel(flp);
1371 fileLoadingPanels.clear();
1372 fileLoadingCount = 0;
1377 public static int getViewCount(String alignmentId)
1379 AlignViewport[] aps = getViewports(alignmentId);
1380 return (aps == null) ? 0 : aps.length;
1385 * @param alignmentId
1386 * @return all AlignmentPanels concerning the alignmentId sequence set
1388 public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
1391 if (Desktop.desktop == null)
1393 // no frames created and in headless mode
1394 // TODO: verify that frames are recoverable when in headless mode
1397 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1398 ArrayList aps = new ArrayList();
1399 for (int t = 0; t < frames.length; t++)
1401 if (frames[t] instanceof AlignFrame)
1403 AlignFrame af = (AlignFrame) frames[t];
1404 for (int a = 0; a < af.alignPanels.size(); a++)
1407 .equals(((AlignmentPanel) af.alignPanels.elementAt(a)).av
1408 .getSequenceSetId()))
1410 aps.add(af.alignPanels.elementAt(a));
1415 if (aps.size() == 0)
1419 AlignmentPanel[] vap = new AlignmentPanel[aps.size()];
1420 for (int t = 0; t < vap.length; t++)
1422 vap[t] = (AlignmentPanel) aps.get(t);
1428 * get all the viewports on an alignment.
1430 * @param sequenceSetId
1431 * unique alignment id
1432 * @return all viewports on the alignment bound to sequenceSetId
1434 public static AlignViewport[] getViewports(String sequenceSetId)
1436 Vector viewp = new Vector();
1437 if (desktop != null)
1439 javax.swing.JInternalFrame[] frames = instance.getAllFrames();
1441 for (int t = 0; t < frames.length; t++)
1443 if (frames[t] instanceof AlignFrame)
1445 AlignFrame afr = ((AlignFrame) frames[t]);
1446 if (afr.getViewport().getSequenceSetId().equals(sequenceSetId))
1448 if (afr.alignPanels != null)
1450 for (int a = 0; a < afr.alignPanels.size(); a++)
1452 if (sequenceSetId.equals(((AlignmentPanel) afr.alignPanels
1453 .elementAt(a)).av.getSequenceSetId()))
1455 viewp.addElement(((AlignmentPanel) afr.alignPanels
1462 viewp.addElement(((AlignFrame) frames[t]).getViewport());
1467 if (viewp.size() > 0)
1469 AlignViewport[] vp = new AlignViewport[viewp.size()];
1477 public void explodeViews(AlignFrame af)
1479 int size = af.alignPanels.size();
1485 for (int i = 0; i < size; i++)
1487 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(i);
1488 AlignFrame newaf = new AlignFrame(ap);
1489 if (ap.av.explodedPosition != null
1490 && !ap.av.explodedPosition.equals(af.getBounds()))
1492 newaf.setBounds(ap.av.explodedPosition);
1495 ap.av.gatherViewsHere = false;
1497 addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1498 AlignFrame.DEFAULT_HEIGHT);
1501 af.alignPanels.clear();
1502 af.closeMenuItem_actionPerformed(true);
1506 public void gatherViews(AlignFrame source)
1508 source.viewport.gatherViewsHere = true;
1509 source.viewport.explodedPosition = source.getBounds();
1510 JInternalFrame[] frames = desktop.getAllFrames();
1511 String viewId = source.viewport.sequenceSetID;
1513 for (int t = 0; t < frames.length; t++)
1515 if (frames[t] instanceof AlignFrame && frames[t] != source)
1517 AlignFrame af = (AlignFrame) frames[t];
1518 boolean gatherThis = false;
1519 for (int a = 0; a < af.alignPanels.size(); a++)
1521 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(a);
1522 if (viewId.equals(ap.av.getSequenceSetId()))
1525 ap.av.gatherViewsHere = false;
1526 ap.av.explodedPosition = af.getBounds();
1527 source.addAlignmentPanel(ap, false);
1533 af.alignPanels.clear();
1534 af.closeMenuItem_actionPerformed(true);
1541 jalview.gui.VamsasApplication v_client = null;
1543 public void vamsasImport_actionPerformed(ActionEvent e)
1545 if (v_client == null)
1547 // Load and try to start a session.
1548 JalviewFileChooser chooser = new JalviewFileChooser(
1549 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
1551 chooser.setFileView(new JalviewFileView());
1552 chooser.setDialogTitle("Open a saved VAMSAS session");
1553 chooser.setToolTipText("select a vamsas session to be opened as a new vamsas session.");
1555 int value = chooser.showOpenDialog(this);
1557 if (value == JalviewFileChooser.APPROVE_OPTION)
1559 String fle = chooser.getSelectedFile().toString();
1560 if (!vamsasImport(chooser.getSelectedFile()))
1562 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1563 "Couldn't import '" + fle + "' as a new vamsas session.",
1564 "Vamsas Document Import Failed",
1565 JOptionPane.ERROR_MESSAGE);
1571 jalview.bin.Cache.log
1572 .error("Implementation error - load session from a running session is not supported.");
1577 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1580 * @return true if import was a success and a session was started.
1582 public boolean vamsasImport(URL url)
1584 // TODO: create progress bar
1585 if (v_client != null)
1588 jalview.bin.Cache.log
1589 .error("Implementation error - load session from a running session is not supported.");
1595 // copy the URL content to a temporary local file
1596 // TODO: be a bit cleverer here with nio (?!)
1597 File file = File.createTempFile("vdocfromurl", ".vdj");
1598 FileOutputStream fos = new FileOutputStream(file);
1599 BufferedInputStream bis = new BufferedInputStream(url.openStream());
1600 byte[] buffer = new byte[2048];
1602 while ((ln = bis.read(buffer)) > -1)
1604 fos.write(buffer, 0, ln);
1608 v_client = new jalview.gui.VamsasApplication(this, file,
1609 url.toExternalForm());
1610 } catch (Exception ex)
1612 jalview.bin.Cache.log.error(
1613 "Failed to create new vamsas session from contents of URL "
1617 setupVamsasConnectedGui();
1618 v_client.initial_update(); // TODO: thread ?
1619 return v_client.inSession();
1623 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1626 * @return true if import was a success and a session was started.
1628 public boolean vamsasImport(File file)
1630 if (v_client != null)
1633 jalview.bin.Cache.log
1634 .error("Implementation error - load session from a running session is not supported.");
1638 setProgressBar("Importing VAMSAS session from " + file.getName(),
1642 v_client = new jalview.gui.VamsasApplication(this, file, null);
1643 } catch (Exception ex)
1645 setProgressBar("Importing VAMSAS session from " + file.getName(),
1647 jalview.bin.Cache.log.error(
1648 "New vamsas session from existing session file failed:", ex);
1651 setupVamsasConnectedGui();
1652 v_client.initial_update(); // TODO: thread ?
1653 setProgressBar("Importing VAMSAS session from " + file.getName(),
1655 return v_client.inSession();
1658 public boolean joinVamsasSession(String mysesid)
1660 if (v_client != null)
1663 "Trying to join a vamsas session when another is already connected.");
1665 if (mysesid == null)
1667 throw new Error("Invalid vamsas session id.");
1669 v_client = new VamsasApplication(this, mysesid);
1670 setupVamsasConnectedGui();
1671 v_client.initial_update();
1672 return (v_client.inSession());
1675 public void vamsasStart_actionPerformed(ActionEvent e)
1677 if (v_client == null)
1680 // we just start a default session for moment.
1682 * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
1683 * getProperty("LAST_DIRECTORY"));
1685 * chooser.setFileView(new JalviewFileView());
1686 * chooser.setDialogTitle("Load Vamsas file");
1687 * chooser.setToolTipText("Import");
1689 * int value = chooser.showOpenDialog(this);
1691 * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
1692 * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
1694 v_client = new VamsasApplication(this);
1695 setupVamsasConnectedGui();
1696 v_client.initial_update(); // TODO: thread ?
1700 // store current data in session.
1701 v_client.push_update(); // TODO: thread
1705 protected void setupVamsasConnectedGui()
1707 vamsasStart.setText("Session Update");
1708 vamsasSave.setVisible(true);
1709 vamsasStop.setVisible(true);
1710 vamsasImport.setVisible(false); // Document import to existing session is
1711 // not possible for vamsas-client-1.0.
1714 protected void setupVamsasDisconnectedGui()
1716 vamsasSave.setVisible(false);
1717 vamsasStop.setVisible(false);
1718 vamsasImport.setVisible(true);
1719 vamsasStart.setText("New Vamsas Session");
1722 public void vamsasStop_actionPerformed(ActionEvent e)
1724 if (v_client != null)
1726 v_client.end_session();
1728 setupVamsasDisconnectedGui();
1732 protected void buildVamsasStMenu()
1734 if (v_client == null)
1736 String[] sess = null;
1739 sess = VamsasApplication.getSessionList();
1740 } catch (Exception e)
1742 jalview.bin.Cache.log.warn(
1743 "Problem getting current sessions list.", e);
1748 jalview.bin.Cache.log.debug("Got current sessions list: "
1749 + sess.length + " entries.");
1750 VamsasStMenu.removeAll();
1751 for (int i = 0; i < sess.length; i++)
1753 JMenuItem sessit = new JMenuItem();
1754 sessit.setText(sess[i]);
1755 sessit.setToolTipText("Connect to session " + sess[i]);
1756 final Desktop dsktp = this;
1757 final String mysesid = sess[i];
1758 sessit.addActionListener(new ActionListener()
1761 public void actionPerformed(ActionEvent e)
1763 if (dsktp.v_client == null)
1765 Thread rthr = new Thread(new Runnable()
1770 dsktp.v_client = new VamsasApplication(dsktp, mysesid);
1771 dsktp.setupVamsasConnectedGui();
1772 dsktp.v_client.initial_update();
1780 VamsasStMenu.add(sessit);
1782 // don't show an empty menu.
1783 VamsasStMenu.setVisible(sess.length > 0);
1788 jalview.bin.Cache.log.debug("No current vamsas sessions.");
1789 VamsasStMenu.removeAll();
1790 VamsasStMenu.setVisible(false);
1795 // Not interested in the content. Just hide ourselves.
1796 VamsasStMenu.setVisible(false);
1800 public void vamsasSave_actionPerformed(ActionEvent e)
1802 if (v_client != null)
1804 JalviewFileChooser chooser = new JalviewFileChooser(
1805 jalview.bin.Cache.getProperty("LAST_DIRECTORY"), new String[]
1806 { "vdj" }, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
1808 { "Vamsas Document" }, "Vamsas Document");
1810 chooser.setFileView(new JalviewFileView());
1811 chooser.setDialogTitle("Save Vamsas Document Archive");
1813 int value = chooser.showSaveDialog(this);
1815 if (value == JalviewFileChooser.APPROVE_OPTION)
1817 java.io.File choice = chooser.getSelectedFile();
1818 JPanel progpanel = addProgressPanel("Saving VAMSAS Document to "
1819 + choice.getName());
1820 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1821 String warnmsg = null;
1822 String warnttl = null;
1825 v_client.vclient.storeDocument(choice);
1828 warnttl = "Serious Problem saving Vamsas Document";
1829 warnmsg = ex.toString();
1830 jalview.bin.Cache.log.error("Error Whilst saving document to "
1833 } catch (Exception ex)
1835 warnttl = "Problem saving Vamsas Document.";
1836 warnmsg = ex.toString();
1837 jalview.bin.Cache.log.warn("Exception Whilst saving document to "
1841 removeProgressPanel(progpanel);
1842 if (warnmsg != null)
1844 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1846 warnmsg, warnttl, JOptionPane.ERROR_MESSAGE);
1852 JPanel vamUpdate = null;
1855 * hide vamsas user gui bits when a vamsas document event is being handled.
1858 * true to hide gui, false to reveal gui
1860 public void setVamsasUpdate(boolean b)
1862 jalview.bin.Cache.log.debug("Setting gui for Vamsas update "
1863 + (b ? "in progress" : "finished"));
1865 if (vamUpdate != null)
1867 this.removeProgressPanel(vamUpdate);
1871 vamUpdate = this.addProgressPanel("Updating vamsas session");
1873 vamsasStart.setVisible(!b);
1874 vamsasStop.setVisible(!b);
1875 vamsasSave.setVisible(!b);
1878 public JInternalFrame[] getAllFrames()
1880 return desktop.getAllFrames();
1884 * Checks the given url to see if it gives a response indicating that the user
1885 * should be informed of a new questionnaire.
1889 public void checkForQuestionnaire(String url)
1891 UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
1892 // javax.swing.SwingUtilities.invokeLater(jvq);
1893 new Thread(jvq).start();
1897 * Proxy class for JDesktopPane which optionally displays the current memory
1898 * usage and highlights the desktop area with a red bar if free memory runs
1903 public class MyDesktopPane extends JDesktopPane implements Runnable
1906 boolean showMemoryUsage = false;
1910 java.text.NumberFormat df;
1912 float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
1915 public MyDesktopPane(boolean showMemoryUsage)
1917 showMemoryUsage(showMemoryUsage);
1920 public void showMemoryUsage(boolean showMemoryUsage)
1922 this.showMemoryUsage = showMemoryUsage;
1923 if (showMemoryUsage)
1925 Thread worker = new Thread(this);
1930 public boolean isShowMemoryUsage()
1932 return showMemoryUsage;
1937 df = java.text.NumberFormat.getNumberInstance();
1938 df.setMaximumFractionDigits(2);
1939 runtime = Runtime.getRuntime();
1941 while (showMemoryUsage)
1945 maxMemory = runtime.maxMemory() / 1048576f;
1946 allocatedMemory = runtime.totalMemory() / 1048576f;
1947 freeMemory = runtime.freeMemory() / 1048576f;
1948 totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
1950 percentUsage = (totalFreeMemory / maxMemory) * 100;
1952 // if (percentUsage < 20)
1954 // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
1956 // instance.set.setBorder(border1);
1959 // sleep after showing usage
1961 } catch (Exception ex)
1963 ex.printStackTrace();
1968 public void paintComponent(Graphics g)
1970 if (showMemoryUsage && g != null && df != null)
1972 if (percentUsage < 20)
1973 g.setColor(Color.red);
1974 FontMetrics fm = g.getFontMetrics();
1978 "Total Free Memory: " + df.format(totalFreeMemory)
1979 + "MB; Max Memory: " + df.format(maxMemory)
1980 + "MB; " + df.format(percentUsage) + "%", 10,
1981 getHeight() - fm.getHeight());
1988 protected JMenuItem groovyShell;
1990 public void doGroovyCheck()
1992 if (jalview.bin.Cache.groovyJarsPresent())
1994 groovyShell = new JMenuItem();
1995 groovyShell.setText("Groovy Console...");
1996 groovyShell.addActionListener(new ActionListener()
1998 public void actionPerformed(ActionEvent e)
2000 groovyShell_actionPerformed(e);
2003 toolsMenu.add(groovyShell);
2004 groovyShell.setVisible(true);
2009 * Accessor method to quickly get all the AlignmentFrames loaded.
2011 public static AlignFrame[] getAlignframes()
2013 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2019 Vector avp = new Vector();
2023 for (int i = frames.length - 1; i > -1; i--)
2025 if (frames[i] instanceof AlignFrame)
2027 AlignFrame af = (AlignFrame) frames[i];
2031 } catch (Exception ex)
2033 ex.printStackTrace();
2035 if (avp.size() == 0)
2039 AlignFrame afs[] = new AlignFrame[avp.size()];
2040 for (int i = 0, j = avp.size(); i < j; i++)
2042 afs[i] = (AlignFrame) avp.elementAt(i);
2047 public AppJmol[] getJmols()
2049 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2055 Vector avp = new Vector();
2059 for (int i = frames.length - 1; i > -1; i--)
2061 if (frames[i] instanceof AppJmol)
2063 AppJmol af = (AppJmol) frames[i];
2067 } catch (Exception ex)
2069 ex.printStackTrace();
2071 if (avp.size() == 0)
2075 AppJmol afs[] = new AppJmol[avp.size()];
2076 for (int i = 0, j = avp.size(); i < j; i++)
2078 afs[i] = (AppJmol) avp.elementAt(i);
2085 * Add Groovy Support to Jalview
2087 public void groovyShell_actionPerformed(ActionEvent e)
2089 // use reflection to avoid creating compilation dependency.
2090 if (!jalview.bin.Cache.groovyJarsPresent())
2093 "Implementation Error. Cannot create groovyShell without Groovy on the classpath!");
2097 Class gcClass = Desktop.class.getClassLoader().loadClass(
2098 "groovy.ui.Console");
2099 Constructor gccons = gcClass.getConstructor(null);
2100 java.lang.reflect.Method setvar = gcClass.getMethod("setVariable",
2102 { String.class, Object.class });
2103 java.lang.reflect.Method run = gcClass.getMethod("run", null);
2104 Object gc = gccons.newInstance(null);
2105 setvar.invoke(gc, new Object[]
2106 { "Jalview", this });
2107 run.invoke(gc, null);
2108 } catch (Exception ex)
2110 jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
2112 .showInternalMessageDialog(
2115 "Couldn't create the groovy Shell. Check the error log for the details of what went wrong.",
2116 "Jalview Groovy Support Failed",
2117 JOptionPane.ERROR_MESSAGE);
2122 * Progress bars managed by the IProgressIndicator method.
2124 private Hashtable<Long,JPanel> progressBars;
2125 private Hashtable<Long,IProgressIndicatorHandler> progressBarHandlers;
2130 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2132 public void setProgressBar(String message, long id)
2134 if (progressBars == null)
2136 progressBars = new Hashtable<Long,JPanel>();
2137 progressBarHandlers = new Hashtable<Long,IProgressIndicatorHandler>();
2140 if (progressBars.get(new Long(id)) != null)
2142 JPanel progressPanel = progressBars
2143 .remove(new Long(id));
2144 if (progressBarHandlers.contains(new Long(id)))
2146 progressBarHandlers.remove(new Long(id));
2148 removeProgressPanel(progressPanel);
2152 progressBars.put(new Long(id), addProgressPanel(message));
2159 * @see jalview.gui.IProgressIndicator#registerHandler(long,
2160 * jalview.gui.IProgressIndicatorHandler)
2162 public void registerHandler(final long id,
2163 final IProgressIndicatorHandler handler)
2165 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
2168 "call setProgressBar before registering the progress bar's handler.");
2170 progressBarHandlers.put(new Long(id), handler);
2171 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
2172 if (handler.canCancel())
2174 JButton cancel = new JButton("Cancel");
2175 final IProgressIndicator us = this;
2176 cancel.addActionListener(new ActionListener()
2179 public void actionPerformed(ActionEvent e)
2181 handler.cancelActivity(id);
2184 + ((JLabel) progressPanel.getComponent(0))
2188 progressPanel.add(cancel, BorderLayout.EAST);
2193 * This will return the first AlignFrame viewing AlignViewport av. It will
2194 * break if there are more than one AlignFrames viewing a particular av. This
2197 * @return alignFrame for av
2199 public static AlignFrame getAlignFrameFor(AlignViewport av)
2201 if (desktop != null)
2203 AlignmentPanel[] aps = getAlignmentPanels(av.getSequenceSetId());
2204 for (int panel = 0; aps != null && panel < aps.length; panel++)
2206 if (aps[panel] != null && aps[panel].av == av)
2208 return aps[panel].alignFrame;
2215 public VamsasApplication getVamsasApplication()
2222 * flag set if jalview GUI is being operated programmatically
2224 private boolean inBatchMode = false;
2227 * check if jalview GUI is being operated programmatically
2229 * @return inBatchMode
2231 public boolean isInBatchMode()
2237 * set flag if jalview GUI is being operated programmatically
2239 * @param inBatchMode
2241 public void setInBatchMode(boolean inBatchMode)
2243 this.inBatchMode = inBatchMode;
2246 public void startServiceDiscovery()
2248 startServiceDiscovery(false);
2251 public void startServiceDiscovery(boolean blocking)
2253 boolean alive = true;
2254 Thread t0 = null, t1 = null, t2 = null;
2256 // todo: changesupport handlers need to be transferred
2257 if (discoverer == null)
2259 discoverer = new jalview.ws.jws1.Discoverer();
2260 // register PCS handler for desktop.
2261 discoverer.addPropertyChangeListener(changeSupport);
2263 // JAL-940 - disabled JWS1 service configuration - always start discoverer until we phase out completely
2266 (t0 = new Thread(discoverer)).start();
2271 if (Cache.getDefault("SHOW_ENFIN_SERVICES", true))
2273 // EnfinEnvision web service menu entries are rebuild every time the
2274 // menu is shown, so no changeSupport events are needed.
2275 jalview.ws.EnfinEnvision2OneWay.getInstance();
2276 (t1 = new Thread(jalview.ws.EnfinEnvision2OneWay.getInstance()))
2279 } catch (Exception e)
2282 .info("Exception when trying to launch Envision2 workflow discovery.",
2284 Cache.log.info(e.getStackTrace());
2286 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
2288 if (jalview.ws.jws2.Jws2Discoverer.getDiscoverer().isRunning())
2290 jalview.ws.jws2.Jws2Discoverer.getDiscoverer().setAborted(true);
2292 t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer().startDiscoverer(
2298 // TODO: do rest service discovery
2307 } catch (Exception e)
2310 alive = (t1 != null && t1.isAlive())
2311 || (t2 != null && t2.isAlive())
2312 || (t3 != null && t3.isAlive())
2313 || (t0 != null && t0.isAlive());
2319 * called to check if the service discovery process completed successfully.
2323 protected void JalviewServicesChanged(PropertyChangeEvent evt)
2325 if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
2327 final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2328 .getErrorMessages();
2331 if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
2333 if (serviceChangedDialog == null)
2335 // only run if we aren't already displaying one of these.
2336 javax.swing.SwingUtilities
2337 .invokeLater(serviceChangedDialog = new Runnable()
2343 .showInternalMessageDialog(
2346 + "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",
2347 "Preferences Problem",
2348 JOptionPane.WARNING_MESSAGE);
2349 serviceChangedDialog = null;
2358 .error("Errors reported by JABA discovery service. Check web services preferences.\n"
2365 private Runnable serviceChangedDialog = null;
2368 * start a thread to open a URL in the configured browser. Pops up a warning
2369 * dialog to the user if there is an exception when calling out to the browser
2374 public static void showUrl(final String url)
2376 showUrl(url, Desktop.instance);
2379 * Like showUrl but allows progress handler to be specified
2381 * @param progress (null) or object implementing IProgressIndicator
2383 public static void showUrl(final String url, final IProgressIndicator progress)
2385 new Thread(new Runnable()
2391 if (progress!=null) {
2392 progress.setProgressBar("Opening "+url, this.hashCode());
2394 jalview.util.BrowserLauncher.openURL(url);
2395 } catch (Exception ex)
2398 .showInternalMessageDialog(
2400 "Unixers: Couldn't find default web browser."
2401 + "\nAdd the full path to your browser in Preferences.",
2402 "Web browser not found",
2403 JOptionPane.WARNING_MESSAGE);
2405 ex.printStackTrace();
2407 if (progress!=null) {
2408 progress.setProgressBar(null, this.hashCode());
2414 public static WsParamSetManager wsparamManager = null;
2416 public static ParamManager getUserParameterStore()
2418 if (wsparamManager == null)
2420 wsparamManager = new WsParamSetManager();
2422 return wsparamManager;