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.*;
27 import java.io.BufferedInputStream;
28 import java.io.BufferedOutputStream;
30 import java.io.FileOutputStream;
31 import java.io.InputStream;
32 import java.lang.reflect.Constructor;
34 import java.net.URLConnection;
35 import java.nio.channels.ReadableByteChannel;
39 import javax.swing.event.MenuEvent;
40 import javax.swing.event.MenuListener;
48 public class Desktop extends jalview.jbgui.GDesktop implements
49 DropTargetListener, ClipboardOwner, IProgressIndicator
52 public static Desktop instance;
54 // Need to decide if the Memory Usage is to be included in
55 // Next release or not.
56 public static MyDesktopPane desktop;
58 // public static JDesktopPane desktop;
60 static int openFrameCount = 0;
62 static final int xOffset = 30;
64 static final int yOffset = 30;
66 public static jalview.ws.Discoverer discoverer;
68 public static Object[] jalviewClipboard;
70 public static boolean internalCopy = false;
72 static int fileLoadingCount = 0;
75 * Creates a new Desktop object.
80 * A note to implementors. It is ESSENTIAL that any activities that might
81 * block are spawned off as threads rather than waited for during this
85 doVamsasClientCheck();
88 setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
89 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
90 boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",
92 desktop = new MyDesktopPane(selmemusage);
93 showMemusage.setSelected(selmemusage);
94 desktop.setBackground(Color.white);
95 getContentPane().setLayout(new BorderLayout());
96 getContentPane().add(desktop, BorderLayout.CENTER);
97 desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
99 // This line prevents Windows Look&Feel resizing all new windows to maximum
100 // if previous window was maximised
101 desktop.setDesktopManager(new DefaultDesktopManager());
103 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
104 String x = jalview.bin.Cache.getProperty("SCREEN_X");
105 String y = jalview.bin.Cache.getProperty("SCREEN_Y");
106 String width = jalview.bin.Cache.getProperty("SCREEN_WIDTH");
107 String height = jalview.bin.Cache.getProperty("SCREEN_HEIGHT");
109 if ((x != null) && (y != null) && (width != null) && (height != null))
111 setBounds(Integer.parseInt(x), Integer.parseInt(y), Integer
112 .parseInt(width), Integer.parseInt(height));
116 setBounds((int) (screenSize.width - 900) / 2,
117 (int) (screenSize.height - 650) / 2, 900, 650);
120 this.addWindowListener(new WindowAdapter()
122 public void windowClosing(WindowEvent evt)
128 this.addMouseListener(new MouseAdapter()
130 public void mousePressed(MouseEvent evt)
132 if (SwingUtilities.isRightMouseButton(evt))
134 showPasteMenu(evt.getX(), evt.getY());
139 this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
140 // Spawn a thread that shows the splashscreen
143 discoverer = new jalview.ws.Discoverer(); // Only gets started if gui is
147 private void doVamsasClientCheck()
149 if (jalview.bin.Cache.vamsasJarsPresent())
151 setupVamsasDisconnectedGui();
152 VamsasMenu.setVisible(true);
153 final Desktop us = this;
154 VamsasMenu.addMenuListener(new MenuListener()
156 // this listener remembers when the menu was first selected, and
157 // doesn't rebuild the session list until it has been cleared and
159 boolean refresh = true;
161 public void menuCanceled(MenuEvent e)
166 public void menuDeselected(MenuEvent e)
171 public void menuSelected(MenuEvent e)
175 us.buildVamsasStMenu();
180 vamsasStart.setVisible(true);
184 void showPasteMenu(int x, int y)
186 JPopupMenu popup = new JPopupMenu();
187 JMenuItem item = new JMenuItem("Paste To New Window");
188 item.addActionListener(new ActionListener()
190 public void actionPerformed(ActionEvent evt)
197 popup.show(this, x, y);
204 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
205 Transferable contents = c.getContents(this);
207 if (contents != null)
209 String file = (String) contents
210 .getTransferData(DataFlavor.stringFlavor);
212 String format = new IdentifyFile().Identify(file,
213 FormatAdapter.PASTE);
215 new FileLoader().LoadFile(file, FormatAdapter.PASTE, format);
218 } catch (Exception ex)
221 .println("Unable to paste alignment from system clipboard:\n"
238 public static synchronized void addInternalFrame(
239 final JInternalFrame frame, String title, int w, int h)
241 addInternalFrame(frame, title, w, h, true);
258 public static synchronized void addInternalFrame(
259 final JInternalFrame frame, String title, int w, int h,
263 // TODO: consider fixing method to update entries in the window submenu with
264 // the current window title
266 frame.setTitle(title);
267 if (frame.getWidth() < 1 || frame.getHeight() < 1)
271 // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
272 // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
273 // IF JALVIEW IS RUNNING HEADLESS
274 // ///////////////////////////////////////////////
275 if (System.getProperty("java.awt.headless") != null
276 && System.getProperty("java.awt.headless").equals("true"))
283 frame.setVisible(true);
284 frame.setClosable(true);
285 frame.setResizable(resizable);
286 frame.setMaximizable(resizable);
287 frame.setIconifiable(resizable);
288 frame.setFrameIcon(null);
290 if (frame.getX() < 1 && frame.getY() < 1)
292 frame.setLocation(xOffset * openFrameCount, yOffset
293 * ((openFrameCount - 1) % 10) + yOffset);
296 final JMenuItem menuItem = new JMenuItem(title);
298 .addInternalFrameListener(new javax.swing.event.InternalFrameAdapter()
300 public void internalFrameActivated(
301 javax.swing.event.InternalFrameEvent evt)
303 JInternalFrame itf = desktop.getSelectedFrame();
311 public void internalFrameClosed(
312 javax.swing.event.InternalFrameEvent evt)
314 PaintRefresher.RemoveComponent(frame);
316 windowMenu.remove(menuItem);
317 JInternalFrame itf = desktop.getSelectedFrame();
326 menuItem.addActionListener(new ActionListener()
328 public void actionPerformed(ActionEvent e)
332 frame.setSelected(true);
333 frame.setIcon(false);
334 } catch (java.beans.PropertyVetoException ex)
341 windowMenu.add(menuItem);
347 frame.setSelected(true);
348 frame.requestFocus();
349 } catch (java.beans.PropertyVetoException ve)
354 public void lostOwnership(Clipboard clipboard, Transferable contents)
358 Desktop.jalviewClipboard = null;
361 internalCopy = false;
364 public void dragEnter(DropTargetDragEvent evt)
368 public void dragExit(DropTargetEvent evt)
372 public void dragOver(DropTargetDragEvent evt)
376 public void dropActionChanged(DropTargetDragEvent evt)
386 public void drop(DropTargetDropEvent evt)
388 Transferable t = evt.getTransferable();
389 java.util.List files = null;
390 java.util.List protocols = null;
394 DataFlavor uriListFlavor = new DataFlavor(
395 "text/uri-list;class=java.lang.String");
396 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
398 // Works on Windows and MacOSX
399 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
400 files = (java.util.List) t
401 .getTransferData(DataFlavor.javaFileListFlavor);
403 else if (t.isDataFlavorSupported(uriListFlavor))
405 // This is used by Unix drag system
406 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
407 String data = (String) t.getTransferData(uriListFlavor);
408 files = new java.util.ArrayList(1);
409 protocols = new java.util.ArrayList(1);
410 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
411 data, "\r\n"); st.hasMoreTokens();)
413 String s = st.nextToken();
414 if (s.startsWith("#"))
416 // the line is a comment (as per the RFC 2483)
419 java.net.URI uri = new java.net.URI(s);
420 if (uri.getScheme().toLowerCase().startsWith("http"))
422 protocols.add(FormatAdapter.URL);
423 files.add(uri.toString());
427 // otherwise preserve old behaviour: catch all for file objects
428 java.io.File file = new java.io.File(uri);
429 protocols.add(FormatAdapter.FILE);
430 files.add(file.toString());
434 } catch (Exception e)
442 for (int i = 0; i < files.size(); i++)
444 String file = files.get(i).toString();
445 String protocol = (protocols==null) ? FormatAdapter.FILE : (String) protocols.get(i);
446 String format = null;
448 if (file.endsWith(".jar"))
455 format = new IdentifyFile().Identify(file, protocol);
458 new FileLoader().LoadFile(file, protocol, format);
461 } catch (Exception ex)
473 public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
475 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
476 .getProperty("LAST_DIRECTORY"),
477 jalview.io.AppletFormatAdapter.READABLE_EXTENSIONS,
478 jalview.io.AppletFormatAdapter.READABLE_FNAMES,
479 jalview.bin.Cache.getProperty("DEFAULT_FILE_FORMAT"));
481 chooser.setFileView(new JalviewFileView());
482 chooser.setDialogTitle("Open local file");
483 chooser.setToolTipText("Open");
485 int value = chooser.showOpenDialog(this);
487 if (value == JalviewFileChooser.APPROVE_OPTION)
489 String choice = chooser.getSelectedFile().getPath();
490 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
491 .getSelectedFile().getParent());
493 String format = null;
494 if (chooser.getSelectedFormat().equals("Jalview"))
500 format = new IdentifyFile().Identify(choice, FormatAdapter.FILE);
503 if (viewport != null)
505 new FileLoader().LoadFile(viewport, choice, FormatAdapter.FILE,
510 new FileLoader().LoadFile(choice, FormatAdapter.FILE, format);
521 public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
523 // This construct allows us to have a wider textfield
525 JLabel label = new JLabel("Enter URL of Input File");
526 final JComboBox history = new JComboBox();
528 JPanel panel = new JPanel(new GridLayout(2, 1));
531 history.setPreferredSize(new Dimension(400, 20));
532 history.setEditable(true);
533 history.addItem("http://www.");
535 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
539 if (historyItems != null)
541 st = new StringTokenizer(historyItems, "\t");
543 while (st.hasMoreTokens())
545 history.addItem(st.nextElement());
549 int reply = JOptionPane.showInternalConfirmDialog(desktop, panel,
550 "Input Alignment From URL", JOptionPane.OK_CANCEL_OPTION);
552 if (reply != JOptionPane.OK_OPTION)
557 String url = history.getSelectedItem().toString();
559 if (url.toLowerCase().endsWith(".jar"))
561 if (viewport != null)
563 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL,
568 new FileLoader().LoadFile(url, FormatAdapter.URL, "Jalview");
573 String format = new IdentifyFile().Identify(url, FormatAdapter.URL);
575 if (format.equals("URL NOT FOUND"))
577 JOptionPane.showInternalMessageDialog(Desktop.desktop,
578 "Couldn't locate " + url, "URL not found",
579 JOptionPane.WARNING_MESSAGE);
584 if (viewport != null)
586 new FileLoader().LoadFile(viewport, url, FormatAdapter.URL, format);
590 new FileLoader().LoadFile(url, FormatAdapter.URL, format);
601 public void inputTextboxMenuItem_actionPerformed(AlignViewport viewport)
603 CutAndPasteTransfer cap = new CutAndPasteTransfer();
604 cap.setForInput(viewport);
605 Desktop.addInternalFrame(cap, "Cut & Paste Alignment File", 600, 500);
613 jalview.bin.Cache.setProperty("SCREEN_X", getBounds().x + "");
614 jalview.bin.Cache.setProperty("SCREEN_Y", getBounds().y + "");
615 jalview.bin.Cache.setProperty("SCREEN_WIDTH", getWidth() + "");
616 jalview.bin.Cache.setProperty("SCREEN_HEIGHT", getHeight() + "");
626 public void aboutMenuItem_actionPerformed(ActionEvent e)
628 StringBuffer message = new StringBuffer("Jalview version "
629 + jalview.bin.Cache.getProperty("VERSION") + "; last updated: "
630 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
632 if (!jalview.bin.Cache.getProperty("LATEST_VERSION").equals(
633 jalview.bin.Cache.getProperty("VERSION")))
636 .append("\n\n!! Jalview version "
637 + jalview.bin.Cache.getProperty("LATEST_VERSION")
638 + " is available for download from http://www.jalview.org !!\n");
641 // TODO: update this text for each release or centrally store it for lite
644 .append("\nAuthors: Andrew Waterhouse, Jim Procter, Michele Clamp, James Cuff, Steve Searle,\n David Martin & Geoff Barton."
645 + "\nDevelopment managed by The Barton Group, University of Dundee, Scotland, UK.\n"
646 + "\nFor help, see the FAQ at www.jalview.org and/or join the jalview-discuss@jalview.org mailing list\n"
647 + "\nIf you use Jalview, please cite:"
648 + "\nWaterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
649 + "\nJalview Version 2 - a multiple sequence alignment editor and analysis workbench"
650 + "\nBioinformatics doi: 10.1093/bioinformatics/btp033");
651 JOptionPane.showInternalMessageDialog(Desktop.desktop,
653 message.toString(), "About Jalview", JOptionPane.INFORMATION_MESSAGE);
662 public void documentationMenuItem_actionPerformed(ActionEvent e)
666 ClassLoader cl = jalview.gui.Desktop.class.getClassLoader();
667 java.net.URL url = javax.help.HelpSet.findHelpSet(cl, "help/help");
668 javax.help.HelpSet hs = new javax.help.HelpSet(cl, url);
670 javax.help.HelpBroker hb = hs.createHelpBroker();
671 hb.setCurrentID("home");
672 hb.setDisplayed(true);
673 } catch (Exception ex)
678 public void closeAll_actionPerformed(ActionEvent e)
680 JInternalFrame[] frames = desktop.getAllFrames();
681 for (int i = 0; i < frames.length; i++)
685 frames[i].setClosed(true);
686 } catch (java.beans.PropertyVetoException ex)
690 System.out.println("ALL CLOSED");
691 if (v_client != null)
693 // TODO clear binding to vamsas document objects on close_all
698 public void raiseRelated_actionPerformed(ActionEvent e)
700 reorderAssociatedWindows(false, false);
703 public void minimizeAssociated_actionPerformed(ActionEvent e)
705 reorderAssociatedWindows(true, false);
708 void closeAssociatedWindows()
710 reorderAssociatedWindows(false, true);
716 * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
719 protected void garbageCollect_actionPerformed(ActionEvent e)
721 // We simply collect the garbage
722 jalview.bin.Cache.log.debug("Collecting garbage...");
724 jalview.bin.Cache.log.debug("Finished garbage collection.");
731 * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
734 protected void showMemusage_actionPerformed(ActionEvent e)
736 desktop.showMemoryUsage(showMemusage.isSelected());
739 void reorderAssociatedWindows(boolean minimize, boolean close)
741 JInternalFrame[] frames = desktop.getAllFrames();
742 if (frames == null || frames.length < 1)
747 AlignViewport source = null, target = null;
748 if (frames[0] instanceof AlignFrame)
750 source = ((AlignFrame) frames[0]).getCurrentView();
752 else if (frames[0] instanceof TreePanel)
754 source = ((TreePanel) frames[0]).getViewPort();
756 else if (frames[0] instanceof PCAPanel)
758 source = ((PCAPanel) frames[0]).av;
760 else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
762 source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
767 for (int i = 0; i < frames.length; i++)
770 if (frames[i] == null)
774 if (frames[i] instanceof AlignFrame)
776 target = ((AlignFrame) frames[i]).getCurrentView();
778 else if (frames[i] instanceof TreePanel)
780 target = ((TreePanel) frames[i]).getViewPort();
782 else if (frames[i] instanceof PCAPanel)
784 target = ((PCAPanel) frames[i]).av;
786 else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
788 target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
791 if (source == target)
797 frames[i].setClosed(true);
801 frames[i].setIcon(minimize);
808 } catch (java.beans.PropertyVetoException ex)
822 protected void preferences_actionPerformed(ActionEvent e)
833 public void saveState_actionPerformed(ActionEvent e)
835 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
836 .getProperty("LAST_DIRECTORY"), new String[]
837 { "jar" }, new String[]
838 { "Jalview Project" }, "Jalview Project");
840 chooser.setFileView(new JalviewFileView());
841 chooser.setDialogTitle("Save State");
843 int value = chooser.showSaveDialog(this);
845 if (value == JalviewFileChooser.APPROVE_OPTION)
847 java.io.File choice = chooser.getSelectedFile();
848 JProgressBar progpanel = addProgressPanel("Saving jalview project "+choice.getName());
849 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
850 // TODO catch and handle errors for savestate
851 new Jalview2XML().SaveState(choice);
852 removeProgressPanel(progpanel);
863 public void loadState_actionPerformed(ActionEvent e)
865 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
866 .getProperty("LAST_DIRECTORY"), new String[]
867 { "jar" }, new String[]
868 { "Jalview Project" }, "Jalview Project");
869 chooser.setFileView(new JalviewFileView());
870 chooser.setDialogTitle("Restore state");
872 int value = chooser.showOpenDialog(this);
874 if (value == JalviewFileChooser.APPROVE_OPTION)
876 String choice = chooser.getSelectedFile().getAbsolutePath();
877 setProgressBar("loading jalview project "+chooser.getSelectedFile().getName(),choice.hashCode());
878 jalview.bin.Cache.setProperty("LAST_DIRECTORY", chooser
879 .getSelectedFile().getParent());
880 new Jalview2XML().LoadJalviewAlign(choice);
881 setProgressBar(null,choice.hashCode());
885 public void inputSequence_actionPerformed(ActionEvent e)
887 new SequenceFetcher(this);
890 JPanel progressPanel;
892 public void startLoading(final String fileName)
894 if (fileLoadingCount == 0)
896 addProgressPanel("Loading File: " + fileName + " ");
902 private JProgressBar addProgressPanel(String string)
904 if (progressPanel == null)
906 progressPanel = new JPanel(new BorderLayout());
907 totalProgressCount = 0;
909 JProgressBar progressBar = new JProgressBar();
910 progressBar.setIndeterminate(true);
912 progressPanel.add(new JLabel(string), BorderLayout.WEST);
914 progressPanel.add(progressBar, BorderLayout.CENTER);
916 instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
917 totalProgressCount++;
922 int totalProgressCount = 0;
924 private void removeProgressPanel(JProgressBar progbar)
926 if (progressPanel != null)
928 progressPanel.remove(progbar);
929 if (--totalProgressCount < 1)
931 this.getContentPane().remove(progressPanel);
932 progressPanel = null;
938 public void stopLoading()
941 if (fileLoadingCount < 1)
943 if (progressPanel != null)
945 this.getContentPane().remove(progressPanel);
946 progressPanel = null;
948 fileLoadingCount = 0;
953 public static int getViewCount(String viewId)
955 AlignViewport[] aps = getViewports(viewId);
956 return (aps == null) ? 0 : aps.length;
962 * @return all AlignmentPanels concerning the viewId sequence set
964 public static AlignmentPanel[] getAlignmentPanels(String viewId)
967 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
968 ArrayList aps = new ArrayList();
969 for (int t = 0; t < frames.length; t++)
971 if (frames[t] instanceof AlignFrame)
973 AlignFrame af = (AlignFrame) frames[t];
974 for (int a = 0; a < af.alignPanels.size(); a++)
977 .equals(((AlignmentPanel) af.alignPanels.elementAt(a)).av
978 .getSequenceSetId()))
980 aps.add(af.alignPanels.elementAt(a));
989 AlignmentPanel[] vap = new AlignmentPanel[aps.size()];
990 for (int t = 0; t < vap.length; t++)
992 vap[t] = (AlignmentPanel) aps.get(t);
998 * get all the viewports on an alignment.
1000 * @param sequenceSetId
1001 * unique alignment id
1002 * @return all viewports on the alignment bound to sequenceSetId
1004 public static AlignViewport[] getViewports(String sequenceSetId)
1006 Vector viewp = new Vector();
1007 if (desktop != null)
1009 javax.swing.JInternalFrame[] frames = instance.getAllFrames();
1011 for (int t = 0; t < frames.length; t++)
1013 if (frames[t] instanceof AlignFrame)
1015 AlignFrame afr = ((AlignFrame) frames[t]);
1016 if (afr.getViewport().getSequenceSetId().equals(sequenceSetId))
1018 if (afr.alignPanels != null)
1020 for (int a = 0; a < afr.alignPanels.size(); a++)
1022 if (sequenceSetId.equals(((AlignmentPanel) afr.alignPanels
1023 .elementAt(a)).av.getSequenceSetId()))
1025 viewp.addElement(((AlignmentPanel) afr.alignPanels
1032 viewp.addElement(((AlignFrame) frames[t]).getViewport());
1037 if (viewp.size() > 0)
1039 AlignViewport[] vp = new AlignViewport[viewp.size()];
1047 public void explodeViews(AlignFrame af)
1049 int size = af.alignPanels.size();
1055 for (int i = 0; i < size; i++)
1057 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(i);
1058 AlignFrame newaf = new AlignFrame(ap);
1059 if (ap.av.explodedPosition != null
1060 && !ap.av.explodedPosition.equals(af.getBounds()))
1062 newaf.setBounds(ap.av.explodedPosition);
1065 ap.av.gatherViewsHere = false;
1067 addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1068 AlignFrame.DEFAULT_HEIGHT);
1071 af.alignPanels.clear();
1072 af.closeMenuItem_actionPerformed(true);
1076 public void gatherViews(AlignFrame source)
1078 source.viewport.gatherViewsHere = true;
1079 source.viewport.explodedPosition = source.getBounds();
1080 JInternalFrame[] frames = desktop.getAllFrames();
1081 String viewId = source.viewport.sequenceSetID;
1083 for (int t = 0; t < frames.length; t++)
1085 if (frames[t] instanceof AlignFrame && frames[t] != source)
1087 AlignFrame af = (AlignFrame) frames[t];
1088 boolean gatherThis = false;
1089 for (int a = 0; a < af.alignPanels.size(); a++)
1091 AlignmentPanel ap = (AlignmentPanel) af.alignPanels.elementAt(a);
1092 if (viewId.equals(ap.av.getSequenceSetId()))
1095 ap.av.gatherViewsHere = false;
1096 ap.av.explodedPosition = af.getBounds();
1097 source.addAlignmentPanel(ap, false);
1103 af.alignPanels.clear();
1104 af.closeMenuItem_actionPerformed(true);
1111 jalview.gui.VamsasApplication v_client = null;
1113 public void vamsasImport_actionPerformed(ActionEvent e)
1115 if (v_client == null)
1117 // Load and try to start a session.
1118 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
1119 .getProperty("LAST_DIRECTORY"));
1121 chooser.setFileView(new JalviewFileView());
1122 chooser.setDialogTitle("Open a saved VAMSAS session");
1124 .setToolTipText("select a vamsas session to be opened as a new vamsas session.");
1126 int value = chooser.showOpenDialog(this);
1128 if (value == JalviewFileChooser.APPROVE_OPTION)
1130 String fle = chooser.getSelectedFile().toString();
1131 if (!vamsasImport(chooser.getSelectedFile()))
1133 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1134 "Couldn't import '" + fle + "' as a new vamsas session.",
1135 "Vamsas Document Import Failed",
1136 JOptionPane.ERROR_MESSAGE);
1142 jalview.bin.Cache.log
1143 .error("Implementation error - load session from a running session is not supported.");
1148 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1150 * @return true if import was a success and a session was started.
1152 public boolean vamsasImport(URL url)
1154 // TODO: create progress bar
1155 if (v_client != null)
1158 jalview.bin.Cache.log
1159 .error("Implementation error - load session from a running session is not supported.");
1165 // copy the URL content to a temporary local file
1166 // TODO: be a bit cleverer here with nio (?!)
1167 File file = File.createTempFile("vdocfromurl", ".vdj");
1168 FileOutputStream fos = new FileOutputStream(file);
1169 BufferedInputStream bis = new BufferedInputStream(url.openStream());
1170 byte[] buffer = new byte[2048];
1172 while ((ln = bis.read(buffer))>-1)
1174 fos.write(buffer,0,ln);
1178 v_client = new jalview.gui.VamsasApplication(this, file, url.toExternalForm());
1179 } catch (Exception ex)
1181 jalview.bin.Cache.log.error(
1182 "Failed to create new vamsas session from contents of URL "+url,ex);
1185 setupVamsasConnectedGui();
1186 v_client.initial_update(); // TODO: thread ?
1187 return v_client.inSession();
1191 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
1193 * @return true if import was a success and a session was started.
1195 public boolean vamsasImport(File file)
1197 if (v_client != null)
1200 jalview.bin.Cache.log
1201 .error("Implementation error - load session from a running session is not supported.");
1205 setProgressBar("Importing VAMSAS session from "+file.getName(),file.hashCode());
1208 v_client = new jalview.gui.VamsasApplication(this, file,null);
1209 } catch (Exception ex)
1211 setProgressBar("Importing VAMSAS session from "+file.getName(),file.hashCode());
1212 jalview.bin.Cache.log.error(
1213 "New vamsas session from existing session file failed:", ex);
1216 setupVamsasConnectedGui();
1217 v_client.initial_update(); // TODO: thread ?
1218 setProgressBar("Importing VAMSAS session from "+file.getName(),file.hashCode());
1219 return v_client.inSession();
1221 public boolean joinVamsasSession(String mysesid) {
1224 throw new Error("Trying to join a vamsas session when another is already connected.");
1228 throw new Error("Invalid vamsas session id.");
1230 v_client = new VamsasApplication(this, mysesid);
1231 setupVamsasConnectedGui();
1232 v_client.initial_update();
1233 return (v_client.inSession());
1236 public void vamsasStart_actionPerformed(ActionEvent e)
1238 if (v_client == null)
1241 // we just start a default session for moment.
1243 * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
1244 * getProperty("LAST_DIRECTORY"));
1246 * chooser.setFileView(new JalviewFileView());
1247 * chooser.setDialogTitle("Load Vamsas file");
1248 * chooser.setToolTipText("Import");
1250 * int value = chooser.showOpenDialog(this);
1252 * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
1253 * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
1255 v_client = new VamsasApplication(this);
1256 setupVamsasConnectedGui();
1257 v_client.initial_update(); // TODO: thread ?
1261 // store current data in session.
1262 v_client.push_update(); // TODO: thread
1266 protected void setupVamsasConnectedGui()
1268 vamsasStart.setText("Session Update");
1269 vamsasSave.setVisible(true);
1270 vamsasStop.setVisible(true);
1271 vamsasImport.setVisible(false); // Document import to existing session is
1272 // not possible for vamsas-client-1.0.
1275 protected void setupVamsasDisconnectedGui()
1277 vamsasSave.setVisible(false);
1278 vamsasStop.setVisible(false);
1279 vamsasImport.setVisible(true);
1280 vamsasStart.setText("New Vamsas Session");
1283 public void vamsasStop_actionPerformed(ActionEvent e)
1285 if (v_client != null)
1287 v_client.end_session();
1289 setupVamsasDisconnectedGui();
1293 protected void buildVamsasStMenu()
1295 if (v_client == null)
1297 String[] sess = null;
1300 sess = VamsasApplication.getSessionList();
1301 } catch (Exception e)
1303 jalview.bin.Cache.log.warn(
1304 "Problem getting current sessions list.", e);
1309 jalview.bin.Cache.log.debug("Got current sessions list: "
1310 + sess.length + " entries.");
1311 VamsasStMenu.removeAll();
1312 for (int i = 0; i < sess.length; i++)
1314 JMenuItem sessit = new JMenuItem();
1315 sessit.setText(sess[i]);
1316 sessit.setToolTipText("Connect to session " + sess[i]);
1317 final Desktop dsktp = this;
1318 final String mysesid = sess[i];
1319 sessit.addActionListener(new ActionListener()
1322 public void actionPerformed(ActionEvent e)
1324 if (dsktp.v_client == null)
1326 Thread rthr = new Thread(new Runnable()
1331 dsktp.v_client = new VamsasApplication(dsktp, mysesid);
1332 dsktp.setupVamsasConnectedGui();
1333 dsktp.v_client.initial_update();
1341 VamsasStMenu.add(sessit);
1343 // don't show an empty menu.
1344 VamsasStMenu.setVisible(sess.length > 0);
1349 jalview.bin.Cache.log.debug("No current vamsas sessions.");
1350 VamsasStMenu.removeAll();
1351 VamsasStMenu.setVisible(false);
1356 // Not interested in the content. Just hide ourselves.
1357 VamsasStMenu.setVisible(false);
1361 public void vamsasSave_actionPerformed(ActionEvent e)
1363 if (v_client != null)
1365 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
1366 .getProperty("LAST_DIRECTORY"), new String[]
1367 { "vdj" }, // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
1369 { "Vamsas Document" }, "Vamsas Document");
1371 chooser.setFileView(new JalviewFileView());
1372 chooser.setDialogTitle("Save Vamsas Document Archive");
1374 int value = chooser.showSaveDialog(this);
1376 if (value == JalviewFileChooser.APPROVE_OPTION)
1378 java.io.File choice = chooser.getSelectedFile();
1379 JProgressBar progpanel = addProgressPanel("Saving VAMSAS Document to "+choice.getName());
1380 jalview.bin.Cache.setProperty("LAST_DIRECTORY", choice.getParent());
1381 String warnmsg = null;
1382 String warnttl = null;
1385 v_client.vclient.storeDocument(choice);
1388 warnttl = "Serious Problem saving Vamsas Document";
1389 warnmsg = ex.toString();
1390 jalview.bin.Cache.log.error("Error Whilst saving document to "
1393 } catch (Exception ex)
1395 warnttl = "Problem saving Vamsas Document.";
1396 warnmsg = ex.toString();
1397 jalview.bin.Cache.log.warn("Exception Whilst saving document to "
1401 removeProgressPanel(progpanel);
1402 if (warnmsg != null)
1404 JOptionPane.showInternalMessageDialog(Desktop.desktop,
1406 warnmsg, warnttl, JOptionPane.ERROR_MESSAGE);
1412 JProgressBar vamUpdate = null;
1415 * hide vamsas user gui bits when a vamsas document event is being handled.
1418 * true to hide gui, false to reveal gui
1420 public void setVamsasUpdate(boolean b)
1422 jalview.bin.Cache.log.debug("Setting gui for Vamsas update "
1423 + (b ? "in progress" : "finished"));
1425 if (vamUpdate != null)
1427 this.removeProgressPanel(vamUpdate);
1431 vamUpdate = this.addProgressPanel("Updating vamsas session");
1433 vamsasStart.setVisible(!b);
1434 vamsasStop.setVisible(!b);
1435 vamsasSave.setVisible(!b);
1438 public JInternalFrame[] getAllFrames()
1440 return desktop.getAllFrames();
1444 * Checks the given url to see if it gives a response indicating that the user
1445 * should be informed of a new questionnaire.
1449 public void checkForQuestionnaire(String url)
1451 UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
1452 // javax.swing.SwingUtilities.invokeLater(jvq);
1453 new Thread(jvq).start();
1457 * Proxy class for JDesktopPane which optionally displays the current memory
1458 * usage and highlights the desktop area with a red bar if free memory runs
1463 public class MyDesktopPane extends JDesktopPane implements Runnable
1466 boolean showMemoryUsage = false;
1470 java.text.NumberFormat df;
1472 float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
1475 public MyDesktopPane(boolean showMemoryUsage)
1477 showMemoryUsage(showMemoryUsage);
1480 public void showMemoryUsage(boolean showMemoryUsage)
1482 this.showMemoryUsage = showMemoryUsage;
1483 if (showMemoryUsage)
1485 Thread worker = new Thread(this);
1490 public boolean isShowMemoryUsage()
1492 return showMemoryUsage;
1497 df = java.text.NumberFormat.getNumberInstance();
1498 df.setMaximumFractionDigits(2);
1499 runtime = Runtime.getRuntime();
1501 while (showMemoryUsage)
1506 maxMemory = runtime.maxMemory() / 1048576f;
1507 allocatedMemory = runtime.totalMemory() / 1048576f;
1508 freeMemory = runtime.freeMemory() / 1048576f;
1509 totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
1511 percentUsage = (totalFreeMemory / maxMemory) * 100;
1513 // if (percentUsage < 20)
1515 // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
1517 // instance.set.setBorder(border1);
1521 } catch (Exception ex)
1523 ex.printStackTrace();
1528 public void paintComponent(Graphics g)
1530 if (showMemoryUsage)
1532 if (percentUsage < 20)
1533 g.setColor(Color.red);
1535 g.drawString("Total Free Memory: " + df.format(totalFreeMemory)
1536 + "MB; Max Memory: " + df.format(maxMemory) + "MB; "
1537 + df.format(percentUsage) + "%", 10, getHeight()
1538 - g.getFontMetrics().getHeight());
1544 protected JMenuItem groovyShell;
1546 public void doGroovyCheck()
1548 if (jalview.bin.Cache.groovyJarsPresent())
1550 groovyShell = new JMenuItem();
1551 groovyShell.setText("Groovy Console...");
1552 groovyShell.addActionListener(new ActionListener()
1554 public void actionPerformed(ActionEvent e)
1556 groovyShell_actionPerformed(e);
1559 toolsMenu.add(groovyShell);
1560 groovyShell.setVisible(true);
1565 * Accessor method to quickly get all the AlignmentFrames loaded.
1567 public static AlignFrame[] getAlignframes()
1569 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
1575 Vector avp = new Vector();
1579 for (int i = frames.length - 1; i > -1; i--)
1581 if (frames[i] instanceof AlignFrame)
1583 AlignFrame af = (AlignFrame) frames[i];
1587 } catch (Exception ex)
1589 ex.printStackTrace();
1591 if (avp.size() == 0)
1595 AlignFrame afs[] = new AlignFrame[avp.size()];
1596 for (int i = 0, j = avp.size(); i < j; i++)
1598 afs[i] = (AlignFrame) avp.elementAt(i);
1605 * Add Groovy Support to Jalview
1607 public void groovyShell_actionPerformed(ActionEvent e)
1609 // use reflection to avoid creating compilation dependency.
1610 if (!jalview.bin.Cache.groovyJarsPresent())
1613 "Implementation Error. Cannot create groovyShell without Groovy on the classpath!");
1617 Class gcClass = Desktop.class.getClassLoader().loadClass(
1618 "groovy.ui.Console");
1619 Constructor gccons = gcClass.getConstructor(null);
1620 java.lang.reflect.Method setvar = gcClass.getMethod("setVariable",
1622 { String.class, Object.class });
1623 java.lang.reflect.Method run = gcClass.getMethod("run", null);
1624 Object gc = gccons.newInstance(null);
1625 setvar.invoke(gc, new Object[]
1626 { "Jalview", this });
1627 run.invoke(gc, null);
1628 } catch (Exception ex)
1630 jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
1632 .showInternalMessageDialog(
1635 "Couldn't create the groovy Shell. Check the error log for the details of what went wrong.",
1636 "Jalview Groovy Support Failed",
1637 JOptionPane.ERROR_MESSAGE);
1642 * Progress bars managed by the IProgressIndicator method.
1644 private Hashtable progressBars, progressBarHandlers;
1649 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
1651 public void setProgressBar(String message, long id)
1653 if (progressBars == null)
1655 progressBars = new Hashtable();
1656 progressBarHandlers = new Hashtable();
1659 if (progressBars.get(new Long(id)) != null)
1661 JProgressBar progressPanel = (JProgressBar) progressBars
1662 .remove(new Long(id));
1663 if (progressBarHandlers.contains(new Long(id)))
1665 progressBarHandlers.remove(new Long(id));
1667 removeProgressPanel(progressPanel);
1671 progressBars.put(new Long(id), addProgressPanel(message));
1678 * @see jalview.gui.IProgressIndicator#registerHandler(long,
1679 * jalview.gui.IProgressIndicatorHandler)
1681 public void registerHandler(final long id,
1682 final IProgressIndicatorHandler handler)
1684 if (progressBarHandlers == null || !progressBars.contains(new Long(id)))
1687 "call setProgressBar before registering the progress bar's handler.");
1689 progressBarHandlers.put(new Long(id), handler);
1690 final JPanel progressPanel = (JPanel) progressBars.get(new Long(id));
1691 if (handler.canCancel())
1693 JButton cancel = new JButton("Cancel");
1694 final IProgressIndicator us = this;
1695 cancel.addActionListener(new ActionListener()
1698 public void actionPerformed(ActionEvent e)
1700 handler.cancelActivity(id);
1701 us.setProgressBar("Cancelled "
1702 + ((JLabel) progressPanel.getComponent(0)).getText(), id);
1705 progressPanel.add(cancel, BorderLayout.EAST);
1710 * This will return the first AlignFrame viewing AlignViewport av. It will
1711 * break if there are more than one AlignFrames viewing a particular av. This
1714 * @return alignFrame for av
1716 public static AlignFrame getAlignFrameFor(AlignViewport av)
1718 if (desktop != null)
1720 AlignmentPanel[] aps = getAlignmentPanels(av.getSequenceSetId());
1721 for (int panel = 0; aps != null && panel < aps.length; panel++)
1723 if (aps[panel] != null && aps[panel].av == av)
1725 return aps[panel].alignFrame;
1732 public VamsasApplication getVamsasApplication()