2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 import java.awt.datatransfer.*;
25 import java.awt.dnd.*;
26 import java.awt.event.*;
28 import java.lang.reflect.Constructor;
32 import javax.swing.event.MenuEvent;
33 import javax.swing.event.MenuListener;
41 public class Desktop extends jalview.jbgui.GDesktop implements
42 DropTargetListener, ClipboardOwner, IProgressIndicator
45 public static Desktop instance;
47 // Need to decide if the Memory Usage is to be included in
48 // Next release or not.
49 public static MyDesktopPane desktop;
51 // public static JDesktopPane desktop;
53 static int openFrameCount = 0;
55 static final int xOffset = 30;
57 static final int yOffset = 30;
59 public static jalview.ws.Discoverer discoverer;
61 public static Object[] jalviewClipboard;
63 public static boolean internalCopy = false;
65 static int fileLoadingCount = 0;
68 * Creates a new Desktop object.
73 * A note to implementors. It is ESSENTIAL that any activities that might
74 * block are spawned off as threads rather than waited for during this
78 doVamsasClientCheck();
81 setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
82 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
83 boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",
85 desktop = new MyDesktopPane(selmemusage);
86 showMemusage.setSelected(selmemusage);
87 desktop.setBackground(Color.white);
88 getContentPane().setLayout(new BorderLayout());
89 getContentPane().add(desktop, BorderLayout.CENTER);
90 desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
92 // This line prevents Windows Look&Feel resizing all new windows to maximum
93 // if previous window was maximised
94 desktop.setDesktopManager(new DefaultDesktopManager());
96 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
97 String x = jalview.bin.Cache.getProperty("SCREEN_X");
98 String y = jalview.bin.Cache.getProperty("SCREEN_Y");
99 String width = jalview.bin.Cache.getProperty("SCREEN_WIDTH");
100 String height = jalview.bin.Cache.getProperty("SCREEN_HEIGHT");
102 if ((x != null) && (y != null) && (width != null) && (height != null))
104 setBounds(Integer.parseInt(x), Integer.parseInt(y), Integer
105 .parseInt(width), Integer.parseInt(height));
109 setBounds((int) (screenSize.width - 900) / 2,
110 (int) (screenSize.height - 650) / 2, 900, 650);
113 this.addWindowListener(new WindowAdapter()
115 public void windowClosing(WindowEvent evt)
121 this.addMouseListener(new MouseAdapter()
123 public void mousePressed(MouseEvent evt)
125 if (SwingUtilities.isRightMouseButton(evt))
127 showPasteMenu(evt.getX(), evt.getY());
132 this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
133 // Spawn a thread that shows the splashscreen
136 discoverer = new jalview.ws.Discoverer(); // Only gets started if gui is
140 private void doVamsasClientCheck()
142 if (jalview.bin.Cache.vamsasJarsPresent())
144 setupVamsasDisconnectedGui();
145 VamsasMenu.setVisible(true);
146 final Desktop us = this;
147 VamsasMenu.addMenuListener(new MenuListener()
149 // this listener remembers when the menu was first selected, and
150 // doesn't rebuild the session list until it has been cleared and
152 boolean refresh = true;
154 public void menuCanceled(MenuEvent e)
159 public void menuDeselected(MenuEvent e)
164 public void menuSelected(MenuEvent e)
168 us.buildVamsasStMenu();
173 vamsasStart.setVisible(true);
177 void showPasteMenu(int x, int y)
179 JPopupMenu popup = new JPopupMenu();
180 JMenuItem item = new JMenuItem("Paste To New Window");
181 item.addActionListener(new ActionListener()
183 public void actionPerformed(ActionEvent evt)
190 popup.show(this, x, y);
197 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
198 Transferable contents = c.getContents(this);
200 if (contents != null)
202 String file = (String) contents
203 .getTransferData(DataFlavor.stringFlavor);
205 String format = new IdentifyFile().Identify(file,
206 FormatAdapter.PASTE);
208 new FileLoader().LoadFile(file, FormatAdapter.PASTE, format);
211 } catch (Exception ex)
214 .println("Unable to paste alignment from system clipboard:\n"
231 public static synchronized void addInternalFrame(
232 final JInternalFrame frame, String title, int w, int h)
234 addInternalFrame(frame, title, w, h, true);
251 public static synchronized void addInternalFrame(
252 final JInternalFrame frame, String title, int w, int h,
256 // TODO: consider fixing method to update entries in the window submenu with
257 // the current window title
259 frame.setTitle(title);
260 if (frame.getWidth() < 1 || frame.getHeight() < 1)
264 // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
265 // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
266 // IF JALVIEW IS RUNNING HEADLESS
267 // ///////////////////////////////////////////////
268 if (System.getProperty("java.awt.headless") != null
269 && System.getProperty("java.awt.headless").equals("true"))
276 frame.setVisible(true);
277 frame.setClosable(true);
278 frame.setResizable(resizable);
279 frame.setMaximizable(resizable);
280 frame.setIconifiable(resizable);
281 frame.setFrameIcon(null);
283 if (frame.getX() < 1 && frame.getY() < 1)
285 frame.setLocation(xOffset * openFrameCount, yOffset
286 * ((openFrameCount - 1) % 10) + yOffset);
289 final JMenuItem menuItem = new JMenuItem(title);
291 .addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
293 public void internalFrameActivated(
294 javax.swing.event.InternalFrameEvent evt)
296 JInternalFrame itf = desktop.getSelectedFrame();
304 public void internalFrameClosed(
305 javax.swing.event.InternalFrameEvent evt)
307 PaintRefresher.RemoveComponent(frame);
309 windowMenu.remove(menuItem);
310 JInternalFrame itf = desktop.getSelectedFrame();
319 menuItem.addActionListener(new ActionListener()
321 public void actionPerformed(ActionEvent e)
325 frame.setSelected(true);
326 frame.setIcon(false);
327 } catch (java.beans.PropertyVetoException ex)
334 windowMenu.add(menuItem);
340 frame.setSelected(true);
341 frame.requestFocus();
342 } catch (java.beans.PropertyVetoException ve)
347 public void lostOwnership(Clipboard clipboard, Transferable contents)
351 Desktop.jalviewClipboard = null;
354 internalCopy = false;
357 public void dragEnter(DropTargetDragEvent evt)
361 public void dragExit(DropTargetEvent evt)
365 public void dragOver(DropTargetDragEvent evt)
369 public void dropActionChanged(DropTargetDragEvent evt)
379 public void drop(DropTargetDropEvent evt)
381 Transferable t = evt.getTransferable();
382 java.util.List files = null;
386 DataFlavor uriListFlavor = new DataFlavor(
387 "text/uri-list;class=java.lang.String");
388 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
390 // Works on Windows and MacOSX
391 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
392 files = (java.util.List) t
393 .getTransferData(DataFlavor.javaFileListFlavor);
395 else if (t.isDataFlavorSupported(uriListFlavor))
397 // This is used by Unix drag system
398 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
399 String data = (String) t.getTransferData(uriListFlavor);
400 files = new java.util.ArrayList(1);
401 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
402 data, "\r\n"); st.hasMoreTokens();)
404 String s = st.nextToken();
405 if (s.startsWith("#"))
407 // the line is a comment (as per the RFC 2483)
411 java.net.URI uri = new java.net.URI(s);
412 java.io.File file = new java.io.File(uri);
416 } catch (Exception e)
424 for (int i = 0; i < files.size(); i++)
426 String file = files.get(i).toString();
427 String protocol = FormatAdapter.FILE;
428 String format = null;
430 if (file.endsWith(".jar"))
437 format = new IdentifyFile().Identify(file, protocol);
440 new FileLoader().LoadFile(file, protocol, format);
443 } catch (Exception ex)
455 public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
457 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
458 .getProperty("LAST_DIRECTORY"),
459 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
460 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
461 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
463 chooser.setFileView(new JalviewFileView());
464 chooser.setDialogTitle("Open local file");
465 chooser.setToolTipText("Open");
467 int value = chooser.showOpenDialog(this);
469 if (value == JalviewFileChooser.APPROVE_OPTION)
471 String choice = chooser.getSelectedFile().getPath();
472 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
473 .getSelectedFile().getParent());
475 String format = null;
476 if (chooser.getSelectedFormat().equals("Jalview"))
482 format = new IdentifyFile().Identify(choice, FormatAdapter.FILE);
485 if (viewport != null)
487 new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE,
492 new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
503 public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
505 // This construct allows us to have a wider textfield
507 JLabel label = new JLabel("Enter URL of Input File");
508 final JComboBox history = new JComboBox();
510 JPanel panel = new JPanel(new GridLayout(2, 1));
513 history.setPreferredSize(new Dimension(400, 20));
514 history.setEditable(true);
515 history.addItem("http://www.");
517 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
521 if (historyItems != null)
523 st = new StringTokenizer(historyItems, "\t");
525 while (st.hasMoreTokens())
527 history.addItem(st.nextElement());
531 int reply = JOptionPane.showInternalConfirmDialog(desktop, panel,
532 "Input Alignment From URL", JOptionPane.OK_CANCEL_OPTION);
534 if (reply != JOptionPane.OK_OPTION)
539 String url = history.getSelectedItem().toString();
541 if (url.toLowerCase().endsWith(".jar"))
543 if (viewport != null)
545 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL,
550 new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
555 String format = new IdentifyFile().Identify(url, FormatAdapter.URL);
557 if (format.equals("URL NOT FOUND"))
559 JOptionPane.showInternalMessageDialog(Desktop.desktop,
560 "Couldn't locate " + url, "URL not found",
561 JOptionPane.WARNING_MESSAGE);
566 if (viewport != null)
568 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
572 new FileLoader().LoadFile(url, FormatAdapter.URL, format);
583 public void inputTextboxMenuItem_actionPerformed(AlignViewport viewport)
585 CutAndPasteTransfer cap = new CutAndPasteTransfer();
586 cap.setForInput(viewport);
587 Desktop.addInternalFrame(cap, "Cut & Paste Alignment File", 600, 500);
595 jalview.bin.Cache.setProperty("SCREEN_X", getBounds().x + "");
596 jalview.bin.Cache.setProperty("SCREEN_Y", getBounds().y + "");
597 jalview.bin.Cache.setProperty("SCREEN_WIDTH", getWidth() + "");
598 jalview.bin.Cache.setProperty("SCREEN_HEIGHT", getHeight() + "");
608 public void aboutMenuItem_actionPerformed(ActionEvent e)
610 StringBuffer message = new StringBuffer("Jalview version "
611 + jalview.bin.Cache.getProperty("VERSION") + "; last updated: "
612 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
614 if (!jalview.bin.Cache.getProperty("LATEST_VERSION").equals(
615 jalview.bin.Cache.getProperty("VERSION")))
618 .append("\n\n!! Jalview version "
619 + jalview.bin.Cache.getProperty("LATEST_VERSION")
620 + " is available for download from http://www.jalview.org !!\n");
623 // TODO: update this text for each release or centrally store it for lite
626 .append("\nAuthors: Andrew Waterhouse, Jim Procter, Michele Clamp, James Cuff, Steve Searle,\n David Martin & Geoff Barton."
627 + "\nDevelopment managed by The Barton Group, University of Dundee, Scotland, UK.\n"
628 + "\nFor help, see the FAQ at www.jalview.org and/or join the jalview-discuss@jalview.org mailing list\n"
629 + "\nIf you use Jalview, please cite:"
630 + "\nWaterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
631 + "\nJalview Version 2 - a multiple sequence alignment editor and analysis workbench"
632 + "\nBioinformatics doi: 10.1093/bioinformatics/btp033");
633 JOptionPane.showInternalMessageDialog(Desktop.desktop,
635 message.toString(), "About Jalview", JOptionPane.INFORMATION_MESSAGE);
644 public void documentationMenuItem_actionPerformed(ActionEvent e)
648 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
649 java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
650 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
652 javax.help.HelpBroker hb = hs.createHelpBroker();
653 hb.setCurrentID("home");
654 hb.setDisplayed(true);
655 } catch (Exception ex)
660 public void closeAll_actionPerformed(ActionEvent e)
662 JInternalFrame[] frames = desktop.getAllFrames();
663 for (int i = 0; i < frames.length; i++)
667 frames[i].setClosed(true);
668 } catch (java.beans.PropertyVetoException ex)
672 System.out.println("ALL CLOSED");
673 if (v_client != null)
675 // TODO clear binding to vamsas document objects on close_all
680 public void raiseRelated_actionPerformed(ActionEvent e)
682 reorderAssociatedWindows(false, false);
685 public void minimizeAssociated_actionPerformed(ActionEvent e)
687 reorderAssociatedWindows(true, false);
690 void closeAssociatedWindows()
692 reorderAssociatedWindows(false, true);
698 * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
701 protected void garbageCollect_actionPerformed(ActionEvent e)
703 // We simply collect the garbage
704 jalview.bin.Cache.log.debug("Collecting garbage...");
706 jalview.bin.Cache.log.debug("Finished garbage collection.");
713 * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
716 protected void showMemusage_actionPerformed(ActionEvent e)
718 desktop.showMemoryUsage(showMemusage.isSelected());
721 void reorderAssociatedWindows(boolean minimize, boolean close)
723 JInternalFrame[] frames = desktop.getAllFrames();
724 if (frames == null || frames.length < 1)
729 AlignViewport source = null, target = null;
730 if (frames[0] instanceof AlignFrame)
732 source = ((AlignFrame) frames[0]).getCurrentView();
734 else if (frames[0] instanceof TreePanel)
736 source = ((TreePanel) frames[0]).getViewPort();
738 else if (frames[0] instanceof PCAPanel)
740 source = ((PCAPanel) frames[0]).av;
742 else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
744 source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
749 for (int i = 0; i < frames.length; i++)
752 if (frames[i] == null)
756 if (frames[i] instanceof AlignFrame)
758 target = ((AlignFrame) frames[i]).getCurrentView();
760 else if (frames[i] instanceof TreePanel)
762 target = ((TreePanel) frames[i]).getViewPort();
764 else if (frames[i] instanceof PCAPanel)
766 target = ((PCAPanel) frames[i]).av;
768 else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
770 target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
773 if (source == target)
779 frames[i].setClosed(true);
783 frames[i].setIcon(minimize);
790 } catch (java.beans.PropertyVetoException ex)
804 protected void preferences_actionPerformed(ActionEvent e)
815 public void saveState_actionPerformed(ActionEvent e)
817 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
818 .getProperty("LAST_DIRECTORY"), new String[]
819 { "jar" }, new String[]
820 { "Jalview Project" }, "Jalview Project");
822 chooser.setFileView(new JalviewFileView());
823 chooser.setDialogTitle("Save State");
825 int value = chooser.showSaveDialog(this);
827 if (value == JalviewFileChooser.APPROVE_OPTION)
829 java.io.File choice = chooser.getSelectedFile();
830 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
831 new Jalview2XML().SaveState(choice);
841 public void loadState_actionPerformed(ActionEvent e)
843 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
844 .getProperty("LAST_DIRECTORY"), new String[]
845 { "jar" }, new String[]
846 { "Jalview Project" }, "Jalview Project");
847 chooser.setFileView(new JalviewFileView());
848 chooser.setDialogTitle("Restore state");
850 int value = chooser.showOpenDialog(this);
852 if (value == JalviewFileChooser.APPROVE_OPTION)
854 String choice = chooser.getSelectedFile().getAbsolutePath();
855 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
856 .getSelectedFile().getParent());
857 new Jalview2XML().LoadJalviewAlign(choice);
861 public void inputSequence_actionPerformed(ActionEvent e)
863 new SequenceFetcher(this);
866 JPanel progressPanel;
868 public void startLoading(final String fileName)
870 if (fileLoadingCount == 0)
872 addProgressPanel("Loading File: " + fileName + " ");
878 private JProgressBar addProgressPanel(String string)
880 if (progressPanel == null)
882 progressPanel = new JPanel(new BorderLayout());
883 totalProgressCount = 0;
885 JProgressBar progressBar = new JProgressBar();
886 progressBar.setIndeterminate(true);
888 progressPanel.add(new JLabel(string), BorderLayout.WEST);
890 progressPanel.add(progressBar, BorderLayout.CENTER);
892 instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
893 totalProgressCount++;
898 int totalProgressCount = 0;
900 private void removeProgressPanel(JProgressBar progbar)
902 if (progressPanel != null)
904 progressPanel.remove(progbar);
905 if (--totalProgressCount < 1)
907 this.getContentPane().remove(progressPanel);
908 progressPanel = null;
914 public void stopLoading()
917 if (fileLoadingCount < 1)
919 if (progressPanel != null)
921 this.getContentPane().remove(progressPanel);
922 progressPanel = null;
924 fileLoadingCount = 0;
929 public static int getViewCount(String viewId)
931 AlignViewport[] aps = getViewports(viewId);
932 return (aps == null) ? 0 : aps.length;
938 * @return all AlignmentPanels concerning the viewId sequence set
940 public static AlignmentPanel[] getAlignmentPanels(String viewId)
943 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
944 ArrayList aps = new ArrayList();
945 for (int t = 0; t < frames.length; t++)
947 if (frames[t] instanceof AlignFrame)
949 AlignFrame af = (AlignFrame) frames[t];
950 for (int a = 0; a < af.alignPanels.size(); a++)
953 .equals(((AlignmentPanel) af.alignPanels.elementAt(a)).av
954 .getSequenceSetId()))
956 aps.add(af.alignPanels.elementAt(a));
965 AlignmentPanel[] vap = new AlignmentPanel[aps.size()];
966 for (int t = 0; t < vap.length; t++)
968 vap[t] = (AlignmentPanel) aps.get(t);
974 * get all the viewports on an alignment.
976 * @param sequenceSetId
977 * unique alignment id
978 * @return all viewports on the alignment bound to sequenceSetId
980 public static AlignViewport[] getViewports(String sequenceSetId)
982 Vector viewp = new Vector();
985 javax.swing.JInternalFrame[] frames = instance.getAllFrames();
987 for (int t = 0; t < frames.length; t++)
989 if (frames[t] instanceof AlignFrame)
991 AlignFrame afr = ((AlignFrame) frames[t]);
992 if (afr.getViewport().getSequenceSetId().equals(sequenceSetId))
994 if (afr.alignPanels != null)
996 for (int a = 0; a < afr.alignPanels.size(); a++)
998 if (sequenceSetId.equals(((AlignmentPanel) afr.alignPanels
999 .elementAt(a)).av.getSequenceSetId()))
1001 viewp.addElement(((AlignmentPanel) afr.alignPanels
1008 viewp.addElement(((AlignFrame) frames[t]).getViewport());
1013 if (viewp.size() > 0)
1015 AlignViewport[] vp = new AlignViewport[viewp.size()];
1023 public void explodeViews(AlignFrame af)
1025 int size = af.alignPanels.size();
1031 for (int i = 0; i < size; i++)
1033 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(i);
1034 AlignFrame newaf = new AlignFrame(ap);
1035 if (ap.av.explodedPosition != null
1036 && !ap.av.explodedPosition.equals(af.getBounds()))
1038 newaf.setBounds(ap.av.explodedPosition);
1041 ap.av.gatherViewsHere = false;
1043 addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1044 AlignFrame.DEFAULT_HEIGHT);
1047 af.alignPanels.clear();
1048 af.closeMenuItem_actionPerformed(true);
1052 public void gatherViews(AlignFrame source)
1054 source.viewport.gatherViewsHere = true;
1055 source.viewport.explodedPosition = source.getBounds();
1056 JInternalFrame[] frames = desktop.getAllFrames();
1057 String viewId = source.viewport.sequenceSetID;
1059 for (int t = 0; t < frames.length; t++)
1061 if (frames[t] instanceof AlignFrame && frames[t] != source)
1063 AlignFrame af = (AlignFrame) frames[t];
1064 boolean gatherThis = false;
1065 for (int a = 0; a < af.alignPanels.size(); a++)
1067 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(a);
1068 if (viewId.equals(ap.av.getSequenceSetId()))
1071 ap.av.gatherViewsHere = false;
1072 ap.av.explodedPosition = af.getBounds();
1073 source.addAlignmentPanel(ap, false);
1079 af.alignPanels.clear();
1080 af.closeMenuItem_actionPerformed(true);
1087 jalview.gui.VamsasApplication v_client = null;
1089 public void vamsasImport_actionPerformed(ActionEvent e)
1091 if (v_client == null)
1093 // Load and try to start a session.
1094 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
1095 .getProperty("LAST_DIRECTORY"));
1097 chooser.setFileView(new JalviewFileView());
1098 chooser.setDialogTitle("Open a saved VAMSAS session");
1100 .setToolTipText("select a vamsas session to be opened as a new vamsas session.");
1102 int value = chooser.showOpenDialog(this);
1104 if (value == JalviewFileChooser.APPROVE_OPTION)
1106 String fle = chooser.getSelectedFile().toString();
1107 if (!vamsasImport(chooser.getSelectedFile()))
1109 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1110 "Couldn't import '" + fle + "' as a new vamsas session.",
1111 "Vamsas Document Import Failed",
1112 JOptionPane.ERROR_MESSAGE);
1118 jalview.bin.Cache.log
1119 .error("Implementation error - load session from a running session is not supported.");
1124 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1126 * @return true if import was a success and a session was started.
1128 public boolean vamsasImport(File file)
1130 if (v_client != null)
1133 jalview.bin.Cache.log
1134 .error("Implementation error - load session from a running session is not supported.");
1140 v_client = new jalview.gui.VamsasApplication(this, file);
1141 } catch (Exception ex)
1143 jalview.bin.Cache.log.error(
1144 "New vamsas session from existing session file failed:", ex);
1147 setupVamsasConnectedGui();
1148 v_client.initial_update(); // TODO: thread ?
1149 return v_client.inSession();
1151 public boolean joinVamsasSession(String mysesid) {
1154 throw new Error("Trying to join a vamsas session when another is already connected.");
1158 throw new Error("Invalid vamsas session id.");
1160 v_client = new VamsasApplication(this, mysesid);
1161 setupVamsasConnectedGui();
1162 v_client.initial_update();
1163 return (v_client.inSession());
1166 public void vamsasStart_actionPerformed(ActionEvent e)
1168 if (v_client == null)
1171 // we just start a default session for moment.
1173 * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
1174 * getProperty("LAST_DIRECTORY"));
1176 * chooser.setFileView(new JalviewFileView());
1177 * chooser.setDialogTitle("Load Vamsas file");
1178 * chooser.setToolTipText("Import");
1180 * int value = chooser.showOpenDialog(this);
1182 * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
1183 * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
1185 v_client = new VamsasApplication(this);
1186 setupVamsasConnectedGui();
1187 v_client.initial_update(); // TODO: thread ?
1191 // store current data in session.
1192 v_client.push_update(); // TODO: thread
1196 protected void setupVamsasConnectedGui()
1198 vamsasStart.setText("Session Update");
1199 vamsasSave.setVisible(true);
1200 vamsasStop.setVisible(true);
1201 vamsasImport.setVisible(false); // Document import to existing session is
1202 // not possible for vamsas-client-1.0.
1205 protected void setupVamsasDisconnectedGui()
1207 vamsasSave.setVisible(false);
1208 vamsasStop.setVisible(false);
1209 vamsasImport.setVisible(true);
1210 vamsasStart.setText("New Vamsas Session");
1213 public void vamsasStop_actionPerformed(ActionEvent e)
1215 if (v_client != null)
1217 v_client.end_session();
1219 setupVamsasDisconnectedGui();
1223 protected void buildVamsasStMenu()
1225 if (v_client == null)
1227 String[] sess = null;
1230 sess = VamsasApplication.getSessionList();
1231 } catch (Exception e)
1233 jalview.bin.Cache.log.warn(
1234 "Problem getting current sessions list.", e);
1239 jalview.bin.Cache.log.debug("Got current sessions list: "
1240 + sess.length + " entries.");
1241 VamsasStMenu.removeAll();
1242 for (int i = 0; i < sess.length; i++)
1244 JMenuItem sessit = new JMenuItem();
1245 sessit.setText(sess[i]);
1246 sessit.setToolTipText("Connect to session " + sess[i]);
1247 final Desktop dsktp = this;
1248 final String mysesid = sess[i];
1249 sessit.addActionListener(new ActionListener()
1252 public void actionPerformed(ActionEvent e)
1254 if (dsktp.v_client == null)
1256 Thread rthr = new Thread(new Runnable()
1261 dsktp.v_client = new VamsasApplication(dsktp, mysesid);
1262 dsktp.setupVamsasConnectedGui();
1263 dsktp.v_client.initial_update();
1271 VamsasStMenu.add(sessit);
1273 // don't show an empty menu.
1274 VamsasStMenu.setVisible(sess.length > 0);
1279 jalview.bin.Cache.log.debug("No current vamsas sessions.");
1280 VamsasStMenu.removeAll();
1281 VamsasStMenu.setVisible(false);
1286 // Not interested in the content. Just hide ourselves.
1287 VamsasStMenu.setVisible(false);
1291 public void vamsasSave_actionPerformed(ActionEvent e)
1293 if (v_client != null)
1295 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
1296 .getProperty("LAST_DIRECTORY"), new String[]
1297 { "vdj" }, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
1299 { "Vamsas Document" }, "Vamsas Document");
1301 chooser.setFileView(new JalviewFileView());
1302 chooser.setDialogTitle("Save Vamsas Document Archive");
1304 int value = chooser.showSaveDialog(this);
1306 if (value == JalviewFileChooser.APPROVE_OPTION)
1308 java.io.File choice = chooser.getSelectedFile();
1309 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1310 String warnmsg = null;
1311 String warnttl = null;
1314 v_client.vclient.storeDocument(choice);
1317 warnttl = "Serious Problem saving Vamsas Document";
1318 warnmsg = ex.toString();
1319 jalview.bin.Cache.log.error("Error Whilst saving document to "
1322 } catch (Exception ex)
1324 warnttl = "Problem saving Vamsas Document.";
1325 warnmsg = ex.toString();
1326 jalview.bin.Cache.log.warn("Exception Whilst saving document to "
1330 if (warnmsg != null)
1332 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1334 warnmsg, warnttl, JOptionPane.ERROR_MESSAGE);
1340 JProgressBar vamUpdate = null;
1343 * hide vamsas user gui bits when a vamsas document event is being handled.
1346 * true to hide gui, false to reveal gui
1348 public void setVamsasUpdate(boolean b)
1350 jalview.bin.Cache.log.debug("Setting gui for Vamsas update "
1351 + (b ? "in progress" : "finished"));
1353 if (vamUpdate != null)
1355 this.removeProgressPanel(vamUpdate);
1359 vamUpdate = this.addProgressPanel("Updating vamsas session");
1361 vamsasStart.setVisible(!b);
1362 vamsasStop.setVisible(!b);
1363 vamsasSave.setVisible(!b);
1366 public JInternalFrame[] getAllFrames()
1368 return desktop.getAllFrames();
1372 * Checks the given url to see if it gives a response indicating that the user
1373 * should be informed of a new questionnaire.
1377 public void checkForQuestionnaire(String url)
1379 UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
1380 // javax.swing.SwingUtilities.invokeLater(jvq);
1381 new Thread(jvq).start();
1385 * Proxy class for JDesktopPane which optionally displays the current memory
1386 * usage and highlights the desktop area with a red bar if free memory runs
1391 public class MyDesktopPane extends JDesktopPane implements Runnable
1394 boolean showMemoryUsage = false;
1398 java.text.NumberFormat df;
1400 float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
1403 public MyDesktopPane(boolean showMemoryUsage)
1405 showMemoryUsage(showMemoryUsage);
1408 public void showMemoryUsage(boolean showMemoryUsage)
1410 this.showMemoryUsage = showMemoryUsage;
1411 if (showMemoryUsage)
1413 Thread worker = new Thread(this);
1418 public boolean isShowMemoryUsage()
1420 return showMemoryUsage;
1425 df = java.text.NumberFormat.getNumberInstance();
1426 df.setMaximumFractionDigits(2);
1427 runtime = Runtime.getRuntime();
1429 while (showMemoryUsage)
1434 maxMemory = runtime.maxMemory() / 1048576f;
1435 allocatedMemory = runtime.totalMemory() / 1048576f;
1436 freeMemory = runtime.freeMemory() / 1048576f;
1437 totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
1439 percentUsage = (totalFreeMemory / maxMemory) * 100;
1441 // if (percentUsage < 20)
1443 // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
1445 // instance.set.setBorder(border1);
1449 } catch (Exception ex)
1451 ex.printStackTrace();
1456 public void paintComponent(Graphics g)
1458 if (showMemoryUsage)
1460 if (percentUsage < 20)
1461 g.setColor(Color.red);
1463 g.drawString("Total Free Memory: " + df.format(totalFreeMemory)
1464 + "MB; Max Memory: " + df.format(maxMemory) + "MB; "
1465 + df.format(percentUsage) + "%", 10, getHeight()
1466 - g.getFontMetrics().getHeight());
1472 protected JMenuItem groovyShell;
1474 public void doGroovyCheck()
1476 if (jalview.bin.Cache.groovyJarsPresent())
1478 groovyShell = new JMenuItem();
1479 groovyShell.setText("Groovy Console...");
1480 groovyShell.addActionListener(new ActionListener()
1482 public void actionPerformed(ActionEvent e)
1484 groovyShell_actionPerformed(e);
1487 toolsMenu.add(groovyShell);
1488 groovyShell.setVisible(true);
1493 * Accessor method to quickly get all the AlignmentFrames loaded.
1495 public static AlignFrame[] getAlignframes()
1497 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1503 Vector avp = new Vector();
1507 for (int i = frames.length - 1; i > -1; i--)
1509 if (frames[i] instanceof AlignFrame)
1511 AlignFrame af = (AlignFrame) frames[i];
1515 } catch (Exception ex)
1517 ex.printStackTrace();
1519 if (avp.size() == 0)
1523 AlignFrame afs[] = new AlignFrame[avp.size()];
1524 for (int i = 0, j = avp.size(); i < j; i++)
1526 afs[i] = (AlignFrame) avp.elementAt(i);
1533 * Add Groovy Support to Jalview
1535 public void groovyShell_actionPerformed(ActionEvent e)
1537 // use reflection to avoid creating compilation dependency.
1538 if (!jalview.bin.Cache.groovyJarsPresent())
1541 "Implementation Error. Cannot create groovyShell without Groovy on the classpath!");
1545 Class gcClass = Desktop.class.getClassLoader().loadClass(
1546 "groovy.ui.Console");
1547 Constructor gccons = gcClass.getConstructor(null);
1548 java.lang.reflect.Method setvar = gcClass.getMethod("setVariable",
1550 { String.class, Object.class });
1551 java.lang.reflect.Method run = gcClass.getMethod("run", null);
1552 Object gc = gccons.newInstance(null);
1553 setvar.invoke(gc, new Object[]
1554 { "Jalview", this });
1555 run.invoke(gc, null);
1556 } catch (Exception ex)
1558 jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
1560 .showInternalMessageDialog(
1563 "Couldn't create the groovy Shell. Check the error log for the details of what went wrong.",
1564 "Jalview Groovy Support Failed",
1565 JOptionPane.ERROR_MESSAGE);
1570 * Progress bars managed by the IProgressIndicator method.
1572 private Hashtable progressBars, progressBarHandlers;
1577 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1579 public void setProgressBar(String message, long id)
1581 if (progressBars == null)
1583 progressBars = new Hashtable();
1584 progressBarHandlers = new Hashtable();
1587 if (progressBars.get(new Long(id)) != null)
1589 JProgressBar progressPanel = (JProgressBar) progressBars
1590 .remove(new Long(id));
1591 if (progressBarHandlers.contains(new Long(id)))
1593 progressBarHandlers.remove(new Long(id));
1595 removeProgressPanel(progressPanel);
1599 progressBars.put(new Long(id), addProgressPanel(message));
1606 * @see jalview.gui.IProgressIndicator#registerHandler(long,
1607 * jalview.gui.IProgressIndicatorHandler)
1609 public void registerHandler(final long id,
1610 final IProgressIndicatorHandler handler)
1612 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
1615 "call setProgressBar before registering the progress bar's handler.");
1617 progressBarHandlers.put(new Long(id), handler);
1618 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
1619 if (handler.canCancel())
1621 JButton cancel = new JButton("Cancel");
1622 final IProgressIndicator us = this;
1623 cancel.addActionListener(new ActionListener()
1626 public void actionPerformed(ActionEvent e)
1628 handler.cancelActivity(id);
1629 us.setProgressBar("Cancelled "
1630 + ((JLabel) progressPanel.getComponent(0)).getText(), id);
1633 progressPanel.add(cancel, BorderLayout.EAST);
1638 * This will return the first AlignFrame viewing AlignViewport av. It will
1639 * break if there are more than one AlignFrames viewing a particular av. This
1642 * @return alignFrame for av
1644 public static AlignFrame getAlignFrameFor(AlignViewport av)
1646 if (desktop != null)
1648 AlignmentPanel[] aps = getAlignmentPanels(av.getSequenceSetId());
1649 for (int panel = 0; aps != null && panel < aps.length; panel++)
1651 if (aps[panel] != null && aps[panel].av == av)
1653 return aps[panel].alignFrame;
1660 public VamsasApplication getVamsasApplication()