2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import static jalview.util.UrlConstants.SEQUENCE_ID;
25 import jalview.api.AlignViewportI;
26 import jalview.api.AlignmentViewPanel;
27 import jalview.bin.Cache;
28 import jalview.bin.Jalview;
29 import jalview.io.BackupFiles;
30 import jalview.io.DataSourceType;
31 import jalview.io.FileFormat;
32 import jalview.io.FileFormatException;
33 import jalview.io.FileFormatI;
34 import jalview.io.FileFormats;
35 import jalview.io.FileLoader;
36 import jalview.io.FormatAdapter;
37 import jalview.io.IdentifyFile;
38 import jalview.io.JalviewFileChooser;
39 import jalview.io.JalviewFileView;
40 import jalview.jbgui.GSplitFrame;
41 import jalview.jbgui.GStructureViewer;
42 import jalview.project.Jalview2XML;
43 import jalview.structure.StructureSelectionManager;
44 import jalview.urls.IdOrgSettings;
45 import jalview.util.ImageMaker;
46 import jalview.util.MessageManager;
47 import jalview.util.Platform;
48 import jalview.util.UrlConstants;
49 import jalview.viewmodel.AlignmentViewport;
50 import jalview.ws.params.ParamManager;
51 import jalview.ws.utils.UrlDownloadClient;
53 import java.awt.BorderLayout;
54 import java.awt.Color;
55 import java.awt.Dimension;
56 import java.awt.FontMetrics;
57 import java.awt.Graphics;
58 import java.awt.GridLayout;
59 import java.awt.Point;
60 import java.awt.Rectangle;
61 import java.awt.Toolkit;
62 import java.awt.Window;
63 import java.awt.datatransfer.Clipboard;
64 import java.awt.datatransfer.ClipboardOwner;
65 import java.awt.datatransfer.DataFlavor;
66 import java.awt.datatransfer.Transferable;
67 import java.awt.dnd.DnDConstants;
68 import java.awt.dnd.DropTargetDragEvent;
69 import java.awt.dnd.DropTargetDropEvent;
70 import java.awt.dnd.DropTargetEvent;
71 import java.awt.dnd.DropTargetListener;
72 import java.awt.event.ActionEvent;
73 import java.awt.event.ActionListener;
74 import java.awt.event.InputEvent;
75 import java.awt.event.KeyEvent;
76 import java.awt.event.MouseAdapter;
77 import java.awt.event.MouseEvent;
78 import java.awt.event.WindowAdapter;
79 import java.awt.event.WindowEvent;
80 import java.beans.PropertyChangeEvent;
81 import java.beans.PropertyChangeListener;
82 import java.io.BufferedInputStream;
84 import java.io.FileOutputStream;
85 import java.io.IOException;
87 import java.util.ArrayList;
88 import java.util.Hashtable;
89 import java.util.List;
90 import java.util.ListIterator;
91 import java.util.StringTokenizer;
92 import java.util.Vector;
93 import java.util.concurrent.ExecutorService;
94 import java.util.concurrent.Executors;
95 import java.util.concurrent.Semaphore;
97 import javax.swing.AbstractAction;
98 import javax.swing.Action;
99 import javax.swing.ActionMap;
100 import javax.swing.Box;
101 import javax.swing.BoxLayout;
102 import javax.swing.DefaultDesktopManager;
103 import javax.swing.DesktopManager;
104 import javax.swing.InputMap;
105 import javax.swing.JButton;
106 import javax.swing.JCheckBox;
107 import javax.swing.JComboBox;
108 import javax.swing.JComponent;
109 import javax.swing.JDesktopPane;
110 import javax.swing.JFrame;
111 import javax.swing.JInternalFrame;
112 import javax.swing.JLabel;
113 import javax.swing.JMenuItem;
114 import javax.swing.JPanel;
115 import javax.swing.JPopupMenu;
116 import javax.swing.JProgressBar;
117 import javax.swing.KeyStroke;
118 import javax.swing.SwingUtilities;
119 import javax.swing.event.HyperlinkEvent;
120 import javax.swing.event.HyperlinkEvent.EventType;
121 import javax.swing.event.InternalFrameAdapter;
122 import javax.swing.event.InternalFrameEvent;
123 import javax.swing.event.MenuEvent;
124 import javax.swing.event.MenuListener;
126 import org.stackoverflowusers.file.WindowsShortcut;
133 * @version $Revision: 1.155 $
135 public class Desktop extends jalview.jbgui.GDesktop
136 implements DropTargetListener, ClipboardOwner, IProgressIndicator,
137 jalview.api.StructureSelectionManagerProvider
139 private static int DEFAULT_MIN_WIDTH = 300;
141 private static int DEFAULT_MIN_HEIGHT = 250;
143 private static int ALIGN_FRAME_DEFAULT_MIN_WIDTH = 600;
145 private static int ALIGN_FRAME_DEFAULT_MIN_HEIGHT = 70;
147 private static final String EXPERIMENTAL_FEATURES = "EXPERIMENTAL_FEATURES";
149 private JalviewChangeSupport changeSupport = new JalviewChangeSupport();
152 * news reader - null if it was never started.
154 private BlogReader jvnews = null;
156 private File projectFile;
160 * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.beans.PropertyChangeListener)
162 public void addJalviewPropertyChangeListener(
163 PropertyChangeListener listener)
165 changeSupport.addJalviewPropertyChangeListener(listener);
169 * @param propertyName
171 * @see jalview.gui.JalviewChangeSupport#addJalviewPropertyChangeListener(java.lang.String,
172 * java.beans.PropertyChangeListener)
174 public void addJalviewPropertyChangeListener(String propertyName,
175 PropertyChangeListener listener)
177 changeSupport.addJalviewPropertyChangeListener(propertyName, listener);
181 * @param propertyName
183 * @see jalview.gui.JalviewChangeSupport#removeJalviewPropertyChangeListener(java.lang.String,
184 * java.beans.PropertyChangeListener)
186 public void removeJalviewPropertyChangeListener(String propertyName,
187 PropertyChangeListener listener)
189 changeSupport.removeJalviewPropertyChangeListener(propertyName,
193 /** Singleton Desktop instance */
194 public static Desktop instance;
196 public static MyDesktopPane desktop;
198 static int openFrameCount = 0;
200 static final int xOffset = 30;
202 static final int yOffset = 30;
204 public static jalview.ws.jws1.Discoverer discoverer;
206 public static Object[] jalviewClipboard;
208 public static boolean internalCopy = false;
210 static int fileLoadingCount = 0;
212 class MyDesktopManager implements DesktopManager
215 private DesktopManager delegate;
217 public MyDesktopManager(DesktopManager delegate)
219 this.delegate = delegate;
223 public void activateFrame(JInternalFrame f)
227 delegate.activateFrame(f);
228 } catch (NullPointerException npe)
230 Point p = getMousePosition();
231 instance.showPasteMenu(p.x, p.y);
236 public void beginDraggingFrame(JComponent f)
238 delegate.beginDraggingFrame(f);
242 public void beginResizingFrame(JComponent f, int direction)
244 delegate.beginResizingFrame(f, direction);
248 public void closeFrame(JInternalFrame f)
250 delegate.closeFrame(f);
254 public void deactivateFrame(JInternalFrame f)
256 delegate.deactivateFrame(f);
260 public void deiconifyFrame(JInternalFrame f)
262 delegate.deiconifyFrame(f);
266 public void dragFrame(JComponent f, int newX, int newY)
272 delegate.dragFrame(f, newX, newY);
276 public void endDraggingFrame(JComponent f)
278 delegate.endDraggingFrame(f);
283 public void endResizingFrame(JComponent f)
285 delegate.endResizingFrame(f);
290 public void iconifyFrame(JInternalFrame f)
292 delegate.iconifyFrame(f);
296 public void maximizeFrame(JInternalFrame f)
298 delegate.maximizeFrame(f);
302 public void minimizeFrame(JInternalFrame f)
304 delegate.minimizeFrame(f);
308 public void openFrame(JInternalFrame f)
310 delegate.openFrame(f);
314 public void resizeFrame(JComponent f, int newX, int newY, int newWidth,
321 delegate.resizeFrame(f, newX, newY, newWidth, newHeight);
325 public void setBoundsForFrame(JComponent f, int newX, int newY,
326 int newWidth, int newHeight)
328 delegate.setBoundsForFrame(f, newX, newY, newWidth, newHeight);
331 // All other methods, simply delegate
336 * Creates a new Desktop object.
341 * A note to implementors. It is ESSENTIAL that any activities that might
342 * block are spawned off as threads rather than waited for during this
346 doVamsasClientCheck();
348 doConfigureStructurePrefs();
349 setTitle("Jalview " + jalview.bin.Cache.getProperty("VERSION"));
350 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
351 boolean selmemusage = jalview.bin.Cache.getDefault("SHOW_MEMUSAGE",
353 boolean showjconsole = jalview.bin.Cache.getDefault("SHOW_JAVA_CONSOLE",
355 desktop = new MyDesktopPane(selmemusage);
356 showMemusage.setSelected(selmemusage);
357 desktop.setBackground(Color.white);
358 getContentPane().setLayout(new BorderLayout());
359 // alternate config - have scrollbars - see notes in JAL-153
360 // JScrollPane sp = new JScrollPane();
361 // sp.getViewport().setView(desktop);
362 // getContentPane().add(sp, BorderLayout.CENTER);
363 getContentPane().add(desktop, BorderLayout.CENTER);
364 desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
366 // This line prevents Windows Look&Feel resizing all new windows to maximum
367 // if previous window was maximised
368 desktop.setDesktopManager(new MyDesktopManager(
369 (Platform.isWindows() ? new DefaultDesktopManager()
371 ? new AquaInternalFrameManager(
372 desktop.getDesktopManager())
373 : desktop.getDesktopManager())));
375 Rectangle dims = getLastKnownDimensions("");
382 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
383 setBounds((screenSize.width - 900) / 2, (screenSize.height - 650) / 2,
386 jconsole = new Console(this, showjconsole);
387 // add essential build information
389 "Jalview Version: " + jalview.bin.Cache.getProperty("VERSION")
390 + "\n" + "Jalview Installation: "
391 + jalview.bin.Cache.getDefault("INSTALLATION",
393 + "\n" + "Build Date: "
394 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown")
395 + "\n" + "Java version: "
396 + System.getProperty("java.version") + "\n"
397 + System.getProperty("os.arch") + " "
398 + System.getProperty("os.name") + " "
399 + System.getProperty("os.version"));
401 showConsole(showjconsole);
403 showNews.setVisible(false);
405 experimentalFeatures.setSelected(showExperimental());
407 getIdentifiersOrgData();
411 this.addWindowListener(new WindowAdapter()
414 public void windowClosing(WindowEvent evt)
421 this.addMouseListener(ma = new MouseAdapter()
424 public void mousePressed(MouseEvent evt)
426 if (evt.isPopupTrigger()) // Mac
428 showPasteMenu(evt.getX(), evt.getY());
433 public void mouseReleased(MouseEvent evt)
435 if (evt.isPopupTrigger()) // Windows
437 showPasteMenu(evt.getX(), evt.getY());
441 desktop.addMouseListener(ma);
443 this.setDropTarget(new java.awt.dnd.DropTarget(desktop, this));
444 // Spawn a thread that shows the splashscreen
445 SwingUtilities.invokeLater(new Runnable()
454 // Thread off a new instance of the file chooser - this reduces the time it
455 // takes to open it later on.
456 new Thread(new Runnable()
461 Cache.log.debug("Filechooser init thread started.");
462 String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
463 JalviewFileChooser.forRead(Cache.getProperty("LAST_DIRECTORY"),
465 Cache.log.debug("Filechooser init thread finished.");
468 // Add the service change listener
469 changeSupport.addJalviewPropertyChangeListener("services",
470 new PropertyChangeListener()
474 public void propertyChange(PropertyChangeEvent evt)
476 Cache.log.debug("Firing service changed event for "
477 + evt.getNewValue());
478 JalviewServicesChanged(evt);
485 * Answers true if user preferences to enable experimental features is True
490 public boolean showExperimental()
492 String experimental = Cache.getDefault(EXPERIMENTAL_FEATURES,
493 Boolean.FALSE.toString());
494 return Boolean.valueOf(experimental).booleanValue();
497 public void doConfigureStructurePrefs()
499 // configure services
500 StructureSelectionManager ssm = StructureSelectionManager
501 .getStructureSelectionManager(this);
502 if (jalview.bin.Cache.getDefault(Preferences.ADD_SS_ANN, true))
504 ssm.setAddTempFacAnnot(jalview.bin.Cache
505 .getDefault(Preferences.ADD_TEMPFACT_ANN, true));
506 ssm.setProcessSecondaryStructure(jalview.bin.Cache
507 .getDefault(Preferences.STRUCT_FROM_PDB, true));
508 ssm.setSecStructServices(
509 jalview.bin.Cache.getDefault(Preferences.USE_RNAVIEW, true));
513 ssm.setAddTempFacAnnot(false);
514 ssm.setProcessSecondaryStructure(false);
515 ssm.setSecStructServices(false);
519 public void checkForNews()
521 final Desktop me = this;
522 // Thread off the news reader, in case there are connection problems.
523 new Thread(new Runnable()
528 Cache.log.debug("Starting news thread.");
530 jvnews = new BlogReader(me);
531 showNews.setVisible(true);
532 Cache.log.debug("Completed news thread.");
537 public void getIdentifiersOrgData()
539 // Thread off the identifiers fetcher
540 new Thread(new Runnable()
545 Cache.log.debug("Downloading data from identifiers.org");
546 UrlDownloadClient client = new UrlDownloadClient();
549 client.download(IdOrgSettings.getUrl(),
550 IdOrgSettings.getDownloadLocation());
551 } catch (IOException e)
553 Cache.log.debug("Exception downloading identifiers.org data"
562 protected void showNews_actionPerformed(ActionEvent e)
564 showNews(showNews.isSelected());
567 void showNews(boolean visible)
570 Cache.log.debug((visible ? "Showing" : "Hiding") + " news.");
571 showNews.setSelected(visible);
572 if (visible && !jvnews.isVisible())
574 new Thread(new Runnable()
579 long now = System.currentTimeMillis();
580 Desktop.instance.setProgressBar(
581 MessageManager.getString("status.refreshing_news"),
583 jvnews.refreshNews();
584 Desktop.instance.setProgressBar(null, now);
593 * recover the last known dimensions for a jalview window
596 * - empty string is desktop, all other windows have unique prefix
597 * @return null or last known dimensions scaled to current geometry (if last
598 * window geom was known)
600 Rectangle getLastKnownDimensions(String windowName)
602 // TODO: lock aspect ratio for scaling desktop Bug #0058199
603 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
604 String x = jalview.bin.Cache.getProperty(windowName + "SCREEN_X");
605 String y = jalview.bin.Cache.getProperty(windowName + "SCREEN_Y");
606 String width = jalview.bin.Cache
607 .getProperty(windowName + "SCREEN_WIDTH");
608 String height = jalview.bin.Cache
609 .getProperty(windowName + "SCREEN_HEIGHT");
610 if ((x != null) && (y != null) && (width != null) && (height != null))
612 int ix = Integer.parseInt(x), iy = Integer.parseInt(y),
613 iw = Integer.parseInt(width), ih = Integer.parseInt(height);
614 if (jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH") != null)
616 // attempt #1 - try to cope with change in screen geometry - this
617 // version doesn't preserve original jv aspect ratio.
618 // take ratio of current screen size vs original screen size.
619 double sw = ((1f * screenSize.width) / (1f * Integer.parseInt(
620 jalview.bin.Cache.getProperty("SCREENGEOMETRY_WIDTH"))));
621 double sh = ((1f * screenSize.height) / (1f * Integer.parseInt(
622 jalview.bin.Cache.getProperty("SCREENGEOMETRY_HEIGHT"))));
623 // rescale the bounds depending upon the current screen geometry.
624 ix = (int) (ix * sw);
625 iw = (int) (iw * sw);
626 iy = (int) (iy * sh);
627 ih = (int) (ih * sh);
628 while (ix >= screenSize.width)
630 jalview.bin.Cache.log.debug(
631 "Window geometry location recall error: shifting horizontal to within screenbounds.");
632 ix -= screenSize.width;
634 while (iy >= screenSize.height)
636 jalview.bin.Cache.log.debug(
637 "Window geometry location recall error: shifting vertical to within screenbounds.");
638 iy -= screenSize.height;
640 jalview.bin.Cache.log.debug(
641 "Got last known dimensions for " + windowName + ": x:" + ix
642 + " y:" + iy + " width:" + iw + " height:" + ih);
644 // return dimensions for new instance
645 return new Rectangle(ix, iy, iw, ih);
650 private void doVamsasClientCheck()
652 if (jalview.bin.Cache.vamsasJarsPresent())
654 setupVamsasDisconnectedGui();
655 VamsasMenu.setVisible(true);
656 final Desktop us = this;
657 VamsasMenu.addMenuListener(new MenuListener()
659 // this listener remembers when the menu was first selected, and
660 // doesn't rebuild the session list until it has been cleared and
662 boolean refresh = true;
665 public void menuCanceled(MenuEvent e)
671 public void menuDeselected(MenuEvent e)
677 public void menuSelected(MenuEvent e)
681 us.buildVamsasStMenu();
686 vamsasStart.setVisible(true);
690 void showPasteMenu(int x, int y)
692 JPopupMenu popup = new JPopupMenu();
693 JMenuItem item = new JMenuItem(
694 MessageManager.getString("label.paste_new_window"));
695 item.addActionListener(new ActionListener()
698 public void actionPerformed(ActionEvent evt)
705 popup.show(this, x, y);
712 Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
713 Transferable contents = c.getContents(this);
715 if (contents != null)
717 String file = (String) contents
718 .getTransferData(DataFlavor.stringFlavor);
720 FileFormatI format = new IdentifyFile().identify(file,
721 DataSourceType.PASTE);
723 new FileLoader().LoadFile(file, DataSourceType.PASTE, format);
726 } catch (Exception ex)
729 "Unable to paste alignment from system clipboard:\n" + ex);
734 * Adds and opens the given frame to the desktop
745 public static synchronized void addInternalFrame(
746 final JInternalFrame frame, String title, int w, int h)
748 addInternalFrame(frame, title, true, w, h, true, false);
752 * Add an internal frame to the Jalview desktop
759 * When true, display frame immediately, otherwise, caller must call
760 * setVisible themselves.
766 public static synchronized void addInternalFrame(
767 final JInternalFrame frame, String title, boolean makeVisible,
770 addInternalFrame(frame, title, makeVisible, w, h, true, false);
774 * Add an internal frame to the Jalview desktop and make it visible
787 public static synchronized void addInternalFrame(
788 final JInternalFrame frame, String title, int w, int h,
791 addInternalFrame(frame, title, true, w, h, resizable, false);
795 * Add an internal frame to the Jalview desktop
802 * When true, display frame immediately, otherwise, caller must call
803 * setVisible themselves.
810 * @param ignoreMinSize
811 * Do not set the default minimum size for frame
813 public static synchronized void addInternalFrame(
814 final JInternalFrame frame, String title, boolean makeVisible,
815 int w, int h, boolean resizable, boolean ignoreMinSize)
818 // TODO: allow callers to determine X and Y position of frame (eg. via
820 // TODO: consider fixing method to update entries in the window submenu with
821 // the current window title
823 frame.setTitle(title);
824 if (frame.getWidth() < 1 || frame.getHeight() < 1)
828 // THIS IS A PUBLIC STATIC METHOD, SO IT MAY BE CALLED EVEN IN
829 // A HEADLESS STATE WHEN NO DESKTOP EXISTS. MUST RETURN
830 // IF JALVIEW IS RUNNING HEADLESS
831 // ///////////////////////////////////////////////
832 if (instance == null || (System.getProperty("java.awt.headless") != null
833 && System.getProperty("java.awt.headless").equals("true")))
842 frame.setMinimumSize(
843 new Dimension(DEFAULT_MIN_WIDTH, DEFAULT_MIN_HEIGHT));
845 // Set default dimension for Alignment Frame window.
846 // The Alignment Frame window could be added from a number of places,
848 // I did this here in order not to miss out on any Alignment frame.
849 if (frame instanceof AlignFrame)
851 frame.setMinimumSize(new Dimension(ALIGN_FRAME_DEFAULT_MIN_WIDTH,
852 ALIGN_FRAME_DEFAULT_MIN_HEIGHT));
856 frame.setVisible(makeVisible);
857 frame.setClosable(true);
858 frame.setResizable(resizable);
859 frame.setMaximizable(resizable);
860 frame.setIconifiable(resizable);
861 frame.setOpaque(false);
863 if (frame.getX() < 1 && frame.getY() < 1)
865 frame.setLocation(xOffset * openFrameCount,
866 yOffset * ((openFrameCount - 1) % 10) + yOffset);
870 * add an entry for the new frame in the Window menu
871 * (and remove it when the frame is closed)
873 final JMenuItem menuItem = new JMenuItem(title);
874 frame.addInternalFrameListener(new InternalFrameAdapter()
877 public void internalFrameActivated(InternalFrameEvent evt)
879 JInternalFrame itf = desktop.getSelectedFrame();
882 if (itf instanceof AlignFrame)
884 Jalview.setCurrentAlignFrame((AlignFrame) itf);
891 public void internalFrameClosed(InternalFrameEvent evt)
893 PaintRefresher.RemoveComponent(frame);
896 * defensive check to prevent frames being
897 * added half off the window
899 if (openFrameCount > 0)
905 * ensure no reference to alignFrame retained by menu item listener
907 if (menuItem.getActionListeners().length > 0)
909 menuItem.removeActionListener(menuItem.getActionListeners()[0]);
911 windowMenu.remove(menuItem);
915 menuItem.addActionListener(new ActionListener()
918 public void actionPerformed(ActionEvent e)
922 frame.setSelected(true);
923 frame.setIcon(false);
924 } catch (java.beans.PropertyVetoException ex)
931 setKeyBindings(frame);
935 windowMenu.add(menuItem);
940 frame.setSelected(true);
941 frame.requestFocus();
942 } catch (java.beans.PropertyVetoException ve)
944 } catch (java.lang.ClassCastException cex)
947 "Squashed a possible GUI implementation error. If you can recreate this, please look at http://issues.jalview.org/browse/JAL-869",
953 * Add key bindings to a JInternalFrame so that Ctrl-W and Cmd-W will close
958 private static void setKeyBindings(JInternalFrame frame)
960 @SuppressWarnings("serial")
961 final Action closeAction = new AbstractAction()
964 public void actionPerformed(ActionEvent e)
971 * set up key bindings for Ctrl-W and Cmd-W, with the same (Close) action
973 KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
974 InputEvent.CTRL_DOWN_MASK);
975 KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
976 Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
978 InputMap inputMap = frame
979 .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
980 String ctrlW = ctrlWKey.toString();
981 inputMap.put(ctrlWKey, ctrlW);
982 inputMap.put(cmdWKey, ctrlW);
984 ActionMap actionMap = frame.getActionMap();
985 actionMap.put(ctrlW, closeAction);
989 public void lostOwnership(Clipboard clipboard, Transferable contents)
993 Desktop.jalviewClipboard = null;
996 internalCopy = false;
1000 public void dragEnter(DropTargetDragEvent evt)
1005 public void dragExit(DropTargetEvent evt)
1010 public void dragOver(DropTargetDragEvent evt)
1015 public void dropActionChanged(DropTargetDragEvent evt)
1026 public void drop(DropTargetDropEvent evt)
1028 boolean success = true;
1029 // JAL-1552 - acceptDrop required before getTransferable call for
1030 // Java's Transferable for native dnd
1031 evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
1032 Transferable t = evt.getTransferable();
1033 List<String> files = new ArrayList<>();
1034 List<DataSourceType> protocols = new ArrayList<>();
1038 Desktop.transferFromDropTarget(files, protocols, evt, t);
1039 } catch (Exception e)
1041 e.printStackTrace();
1049 for (int i = 0; i < files.size(); i++)
1051 String file = files.get(i).toString();
1052 DataSourceType protocol = (protocols == null)
1053 ? DataSourceType.FILE
1055 FileFormatI format = null;
1057 if (file.endsWith(".jar"))
1059 format = FileFormat.Jalview;
1064 format = new IdentifyFile().identify(file, protocol);
1067 new FileLoader().LoadFile(file, protocol, format);
1070 } catch (Exception ex)
1075 evt.dropComplete(success); // need this to ensure input focus is properly
1076 // transfered to any new windows created
1086 public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
1088 String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
1089 JalviewFileChooser chooser = JalviewFileChooser
1090 .forRead(Cache.getProperty("LAST_DIRECTORY"), fileFormat, true);
1092 chooser.setFileView(new JalviewFileView());
1093 chooser.setDialogTitle(
1094 MessageManager.getString("label.open_local_file"));
1095 chooser.setToolTipText(MessageManager.getString("action.open"));
1097 int value = chooser.showOpenDialog(this);
1099 if (value == JalviewFileChooser.APPROVE_OPTION)
1101 String choice = chooser.getSelectedFile().getPath();
1102 Cache.setProperty("LAST_DIRECTORY",
1103 chooser.getSelectedFile().getParent());
1105 FileFormatI format = chooser.getSelectedFormat();
1108 * Call IdentifyFile to verify the file contains what its extension implies.
1109 * Skip this step for dynamically added file formats, because
1110 * IdentifyFile does not know how to recognise them.
1112 if (FileFormats.getInstance().isIdentifiable(format))
1116 format = new IdentifyFile().identify(choice, DataSourceType.FILE);
1117 } catch (FileFormatException e)
1119 // format = null; //??
1123 if (viewport != null)
1125 new FileLoader().LoadFile(viewport, choice, DataSourceType.FILE,
1130 new FileLoader().LoadFile(choice, DataSourceType.FILE, format);
1142 public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
1144 // This construct allows us to have a wider textfield
1146 JLabel label = new JLabel(
1147 MessageManager.getString("label.input_file_url"));
1148 final JComboBox history = new JComboBox();
1150 JPanel panel = new JPanel(new GridLayout(2, 1));
1153 history.setPreferredSize(new Dimension(400, 20));
1154 history.setEditable(true);
1155 history.addItem("http://www.");
1157 String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
1161 if (historyItems != null)
1163 st = new StringTokenizer(historyItems, "\t");
1165 while (st.hasMoreTokens())
1167 history.addItem(st.nextElement());
1171 int reply = JvOptionPane.showInternalConfirmDialog(desktop, panel,
1172 MessageManager.getString("label.input_alignment_from_url"),
1173 JvOptionPane.OK_CANCEL_OPTION);
1175 if (reply != JvOptionPane.OK_OPTION)
1180 String url = history.getSelectedItem().toString();
1182 if (url.toLowerCase().endsWith(".jar"))
1184 if (viewport != null)
1186 new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
1187 FileFormat.Jalview);
1191 new FileLoader().LoadFile(url, DataSourceType.URL,
1192 FileFormat.Jalview);
1197 FileFormatI format = null;
1200 format = new IdentifyFile().identify(url, DataSourceType.URL);
1201 } catch (FileFormatException e)
1203 // TODO revise error handling, distinguish between
1204 // URL not found and response not valid
1209 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1210 MessageManager.formatMessage("label.couldnt_locate",
1213 MessageManager.getString("label.url_not_found"),
1214 JvOptionPane.WARNING_MESSAGE);
1219 if (viewport != null)
1221 new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
1226 new FileLoader().LoadFile(url, DataSourceType.URL, format);
1232 * Opens the CutAndPaste window for the user to paste an alignment in to
1235 * - if not null, the pasted alignment is added to the current
1236 * alignment; if null, to a new alignment window
1239 public void inputTextboxMenuItem_actionPerformed(
1240 AlignmentViewPanel viewPanel)
1242 CutAndPasteTransfer cap = new CutAndPasteTransfer();
1243 cap.setForInput(viewPanel);
1244 Desktop.addInternalFrame(cap,
1245 MessageManager.getString("label.cut_paste_alignmen_file"), true,
1255 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
1256 jalview.bin.Cache.setProperty("SCREENGEOMETRY_WIDTH",
1258 jalview.bin.Cache.setProperty("SCREENGEOMETRY_HEIGHT",
1259 screen.height + "");
1260 storeLastKnownDimensions("", new Rectangle(getBounds().x, getBounds().y,
1261 getWidth(), getHeight()));
1263 if (jconsole != null)
1265 storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
1266 jconsole.stopConsole();
1270 storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
1273 if (dialogExecutor != null)
1275 dialogExecutor.shutdownNow();
1277 closeAll_actionPerformed(null);
1279 if (groovyConsole != null)
1281 // suppress a possible repeat prompt to save script
1282 groovyConsole.setDirty(false);
1283 groovyConsole.exit();
1288 private void storeLastKnownDimensions(String string, Rectangle jc)
1290 jalview.bin.Cache.log.debug("Storing last known dimensions for "
1291 + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
1292 + " height:" + jc.height);
1294 jalview.bin.Cache.setProperty(string + "SCREEN_X", jc.x + "");
1295 jalview.bin.Cache.setProperty(string + "SCREEN_Y", jc.y + "");
1296 jalview.bin.Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
1297 jalview.bin.Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
1307 public void aboutMenuItem_actionPerformed(ActionEvent e)
1309 // StringBuffer message = getAboutMessage(false);
1310 // JvOptionPane.showInternalMessageDialog(Desktop.desktop,
1312 // message.toString(), "About Jalview", JvOptionPane.INFORMATION_MESSAGE);
1313 new Thread(new Runnable()
1318 new SplashScreen(true);
1323 public StringBuffer getAboutMessage(boolean shortv)
1325 StringBuffer message = new StringBuffer();
1326 message.append("<html>");
1329 message.append("<h1><strong>Version: "
1330 + jalview.bin.Cache.getProperty("VERSION")
1331 + "</strong></h1>");
1332 message.append("<strong>Last Updated: <em>"
1333 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown")
1334 + "</em></strong>");
1340 message.append("<strong>Version "
1341 + jalview.bin.Cache.getProperty("VERSION")
1342 + "; last updated: "
1343 + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
1346 if (jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking")
1347 .equals("Checking"))
1349 message.append("<br>...Checking latest version...</br>");
1351 else if (!jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking")
1352 .equals(jalview.bin.Cache.getProperty("VERSION")))
1354 boolean red = false;
1355 if (jalview.bin.Cache.getProperty("VERSION").toLowerCase()
1356 .indexOf("automated build") == -1)
1359 // Displayed when code version and jnlp version do not match and code
1360 // version is not a development build
1361 message.append("<div style=\"color: #FF0000;font-style: bold;\">");
1364 message.append("<br>!! Version "
1365 + jalview.bin.Cache.getDefault("LATEST_VERSION",
1367 + " is available for download from "
1368 + jalview.bin.Cache.getDefault("www.jalview.org",
1369 "http://www.jalview.org")
1373 message.append("</div>");
1376 message.append("<br>Authors: " + jalview.bin.Cache.getDefault(
1378 "The Jalview Authors (See AUTHORS file for current list)")
1379 + "<br><br>Development managed by The Barton Group, University of Dundee, Scotland, UK.<br>"
1380 + "<br><br>For help, see the FAQ at <a href=\"http://www.jalview.org/faq\">www.jalview.org/faq</a> and/or join the jalview-discuss@jalview.org mailing list"
1381 + "<br><br>If you use Jalview, please cite:"
1382 + "<br>Waterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
1383 + "<br>Jalview Version 2 - a multiple sequence alignment editor and analysis workbench"
1384 + "<br>Bioinformatics doi: 10.1093/bioinformatics/btp033"
1396 public void documentationMenuItem_actionPerformed(ActionEvent e)
1400 Help.showHelpWindow();
1401 } catch (Exception ex)
1407 public void closeAll_actionPerformed(ActionEvent e)
1409 // TODO show a progress bar while closing?
1410 JInternalFrame[] frames = desktop.getAllFrames();
1411 for (int i = 0; i < frames.length; i++)
1415 frames[i].setClosed(true);
1416 } catch (java.beans.PropertyVetoException ex)
1420 Jalview.setCurrentAlignFrame(null);
1421 System.out.println("ALL CLOSED");
1422 if (v_client != null)
1424 // TODO clear binding to vamsas document objects on close_all
1428 * reset state of singleton objects as appropriate (clear down session state
1429 * when all windows are closed)
1431 StructureSelectionManager ssm = StructureSelectionManager
1432 .getStructureSelectionManager(this);
1440 public void raiseRelated_actionPerformed(ActionEvent e)
1442 reorderAssociatedWindows(false, false);
1446 public void minimizeAssociated_actionPerformed(ActionEvent e)
1448 reorderAssociatedWindows(true, false);
1451 void closeAssociatedWindows()
1453 reorderAssociatedWindows(false, true);
1459 * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
1463 protected void garbageCollect_actionPerformed(ActionEvent e)
1465 // We simply collect the garbage
1466 jalview.bin.Cache.log.debug("Collecting garbage...");
1468 jalview.bin.Cache.log.debug("Finished garbage collection.");
1475 * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
1479 protected void showMemusage_actionPerformed(ActionEvent e)
1481 desktop.showMemoryUsage(showMemusage.isSelected());
1488 * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
1492 protected void showConsole_actionPerformed(ActionEvent e)
1494 showConsole(showConsole.isSelected());
1497 Console jconsole = null;
1500 * control whether the java console is visible or not
1504 void showConsole(boolean selected)
1506 showConsole.setSelected(selected);
1507 // TODO: decide if we should update properties file
1508 Cache.setProperty("SHOW_JAVA_CONSOLE",
1509 Boolean.valueOf(selected).toString());
1510 jconsole.setVisible(selected);
1513 void reorderAssociatedWindows(boolean minimize, boolean close)
1515 JInternalFrame[] frames = desktop.getAllFrames();
1516 if (frames == null || frames.length < 1)
1521 AlignmentViewport source = null, target = null;
1522 if (frames[0] instanceof AlignFrame)
1524 source = ((AlignFrame) frames[0]).getCurrentView();
1526 else if (frames[0] instanceof TreePanel)
1528 source = ((TreePanel) frames[0]).getViewPort();
1530 else if (frames[0] instanceof PCAPanel)
1532 source = ((PCAPanel) frames[0]).av;
1534 else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
1536 source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
1541 for (int i = 0; i < frames.length; i++)
1544 if (frames[i] == null)
1548 if (frames[i] instanceof AlignFrame)
1550 target = ((AlignFrame) frames[i]).getCurrentView();
1552 else if (frames[i] instanceof TreePanel)
1554 target = ((TreePanel) frames[i]).getViewPort();
1556 else if (frames[i] instanceof PCAPanel)
1558 target = ((PCAPanel) frames[i]).av;
1560 else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
1562 target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
1565 if (source == target)
1571 frames[i].setClosed(true);
1575 frames[i].setIcon(minimize);
1578 frames[i].toFront();
1582 } catch (java.beans.PropertyVetoException ex)
1597 protected void preferences_actionPerformed(ActionEvent e)
1603 * Shows a file chooser dialog and writes out the current session as a Jalview
1607 public void saveState_actionPerformed()
1609 saveState_actionPerformed(false);
1612 public void saveState_actionPerformed(boolean saveAs)
1614 java.io.File projectFile = getProjectFile();
1615 // autoSave indicates we already have a file and don't need to ask
1616 boolean autoSave = projectFile != null && !saveAs
1617 && BackupFiles.getEnabled();
1619 // System.out.println("autoSave="+autoSave+", projectFile='"+projectFile+"',
1620 // saveAs="+saveAs+", Backups
1621 // "+(BackupFiles.getEnabled()?"enabled":"disabled"));
1623 boolean approveSave = false;
1626 JalviewFileChooser chooser = new JalviewFileChooser("jvp",
1629 chooser.setFileView(new JalviewFileView());
1630 chooser.setDialogTitle(MessageManager.getString("label.save_state"));
1632 int value = chooser.showSaveDialog(this);
1634 if (value == JalviewFileChooser.APPROVE_OPTION)
1636 projectFile = chooser.getSelectedFile();
1637 setProjectFile(projectFile);
1642 if (approveSave || autoSave)
1644 final Desktop me = this;
1645 final java.io.File chosenFile = projectFile;
1646 new Thread(new Runnable()
1651 // TODO: refactor to Jalview desktop session controller action.
1652 setProgressBar(MessageManager.formatMessage(
1653 "label.saving_jalview_project", new Object[]
1654 { chosenFile.getName() }), chosenFile.hashCode());
1655 jalview.bin.Cache.setProperty("LAST_DIRECTORY",
1656 chosenFile.getParent());
1657 // TODO catch and handle errors for savestate
1658 // TODO prevent user from messing with the Desktop whilst we're saving
1661 BackupFiles backupfiles = new BackupFiles(chosenFile);
1663 new Jalview2XML().saveState(backupfiles.getTempFile());
1665 backupfiles.setWriteSuccess(true);
1666 backupfiles.rollBackupsAndRenameTempFile();
1667 } catch (OutOfMemoryError oom)
1669 new OOMWarning("Whilst saving current state to "
1670 + chosenFile.getName(), oom);
1671 } catch (Exception ex)
1673 Cache.log.error("Problems whilst trying to save to "
1674 + chosenFile.getName(), ex);
1675 JvOptionPane.showMessageDialog(me,
1676 MessageManager.formatMessage(
1677 "label.error_whilst_saving_current_state_to",
1679 { chosenFile.getName() }),
1680 MessageManager.getString("label.couldnt_save_project"),
1681 JvOptionPane.WARNING_MESSAGE);
1683 setProgressBar(null, chosenFile.hashCode());
1690 public void saveAsState_actionPerformed(ActionEvent e)
1692 saveState_actionPerformed(true);
1695 private void setProjectFile(File choice)
1697 this.projectFile = choice;
1700 public File getProjectFile()
1702 return this.projectFile;
1706 * Shows a file chooser dialog and tries to read in the selected file as a
1710 public void loadState_actionPerformed()
1712 final String[] suffix = new String[] { "jvp", "jar" };
1713 final String[] desc = new String[] { "Jalview Project",
1714 "Jalview Project (old)" };
1715 JalviewFileChooser chooser = new JalviewFileChooser(
1716 Cache.getProperty("LAST_DIRECTORY"), suffix, desc,
1717 "Jalview Project", true, true); // last two booleans: allFiles,
1719 chooser.setFileView(new JalviewFileView());
1720 chooser.setDialogTitle(MessageManager.getString("label.restore_state"));
1722 int value = chooser.showOpenDialog(this);
1724 if (value == JalviewFileChooser.APPROVE_OPTION)
1726 final File selectedFile = chooser.getSelectedFile();
1727 setProjectFile(selectedFile);
1728 final String choice = selectedFile.getAbsolutePath();
1729 Cache.setProperty("LAST_DIRECTORY", selectedFile.getParent());
1730 new Thread(new Runnable()
1735 setProgressBar(MessageManager.formatMessage(
1736 "label.loading_jalview_project", new Object[]
1737 { choice }), choice.hashCode());
1740 new Jalview2XML().loadJalviewAlign(choice);
1741 } catch (OutOfMemoryError oom)
1743 new OOMWarning("Whilst loading project from " + choice, oom);
1744 } catch (Exception ex)
1747 "Problems whilst loading project from " + choice, ex);
1748 JvOptionPane.showMessageDialog(Desktop.desktop,
1749 MessageManager.formatMessage(
1750 "label.error_whilst_loading_project_from",
1753 MessageManager.getString("label.couldnt_load_project"),
1754 JvOptionPane.WARNING_MESSAGE);
1756 setProgressBar(null, choice.hashCode());
1763 public void inputSequence_actionPerformed(ActionEvent e)
1765 new SequenceFetcher(this);
1768 JPanel progressPanel;
1770 ArrayList<JPanel> fileLoadingPanels = new ArrayList<>();
1772 public void startLoading(final String fileName)
1774 if (fileLoadingCount == 0)
1776 fileLoadingPanels.add(addProgressPanel(MessageManager
1777 .formatMessage("label.loading_file", new Object[]
1783 private JPanel addProgressPanel(String string)
1785 if (progressPanel == null)
1787 progressPanel = new JPanel(new GridLayout(1, 1));
1788 totalProgressCount = 0;
1789 instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
1791 JPanel thisprogress = new JPanel(new BorderLayout(10, 5));
1792 JProgressBar progressBar = new JProgressBar();
1793 progressBar.setIndeterminate(true);
1795 thisprogress.add(new JLabel(string), BorderLayout.WEST);
1797 thisprogress.add(progressBar, BorderLayout.CENTER);
1798 progressPanel.add(thisprogress);
1799 ((GridLayout) progressPanel.getLayout()).setRows(
1800 ((GridLayout) progressPanel.getLayout()).getRows() + 1);
1801 ++totalProgressCount;
1802 instance.validate();
1803 return thisprogress;
1806 int totalProgressCount = 0;
1808 private void removeProgressPanel(JPanel progbar)
1810 if (progressPanel != null)
1812 synchronized (progressPanel)
1814 progressPanel.remove(progbar);
1815 GridLayout gl = (GridLayout) progressPanel.getLayout();
1816 gl.setRows(gl.getRows() - 1);
1817 if (--totalProgressCount < 1)
1819 this.getContentPane().remove(progressPanel);
1820 progressPanel = null;
1827 public void stopLoading()
1830 if (fileLoadingCount < 1)
1832 while (fileLoadingPanels.size() > 0)
1834 removeProgressPanel(fileLoadingPanels.remove(0));
1836 fileLoadingPanels.clear();
1837 fileLoadingCount = 0;
1842 public static int getViewCount(String alignmentId)
1844 AlignmentViewport[] aps = getViewports(alignmentId);
1845 return (aps == null) ? 0 : aps.length;
1850 * @param alignmentId
1851 * - if null, all sets are returned
1852 * @return all AlignmentPanels concerning the alignmentId sequence set
1854 public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
1856 if (Desktop.desktop == null)
1858 // no frames created and in headless mode
1859 // TODO: verify that frames are recoverable when in headless mode
1862 List<AlignmentPanel> aps = new ArrayList<>();
1863 AlignFrame[] frames = getAlignFrames();
1868 for (AlignFrame af : frames)
1870 for (AlignmentPanel ap : af.alignPanels)
1872 if (alignmentId == null
1873 || alignmentId.equals(ap.av.getSequenceSetId()))
1879 if (aps.size() == 0)
1883 AlignmentPanel[] vap = aps.toArray(new AlignmentPanel[aps.size()]);
1888 * get all the viewports on an alignment.
1890 * @param sequenceSetId
1891 * unique alignment id (may be null - all viewports returned in that
1893 * @return all viewports on the alignment bound to sequenceSetId
1895 public static AlignmentViewport[] getViewports(String sequenceSetId)
1897 List<AlignmentViewport> viewp = new ArrayList<>();
1898 if (desktop != null)
1900 AlignFrame[] frames = Desktop.getAlignFrames();
1902 for (AlignFrame afr : frames)
1904 if (sequenceSetId == null || afr.getViewport().getSequenceSetId()
1905 .equals(sequenceSetId))
1907 if (afr.alignPanels != null)
1909 for (AlignmentPanel ap : afr.alignPanels)
1911 if (sequenceSetId == null
1912 || sequenceSetId.equals(ap.av.getSequenceSetId()))
1920 viewp.add(afr.getViewport());
1924 if (viewp.size() > 0)
1926 return viewp.toArray(new AlignmentViewport[viewp.size()]);
1933 * Explode the views in the given frame into separate AlignFrame
1937 public static void explodeViews(AlignFrame af)
1939 int size = af.alignPanels.size();
1945 for (int i = 0; i < size; i++)
1947 AlignmentPanel ap = af.alignPanels.get(i);
1948 AlignFrame newaf = new AlignFrame(ap);
1951 * Restore the view's last exploded frame geometry if known. Multiple
1952 * views from one exploded frame share and restore the same (frame)
1953 * position and size.
1955 Rectangle geometry = ap.av.getExplodedGeometry();
1956 if (geometry != null)
1958 newaf.setBounds(geometry);
1961 ap.av.setGatherViewsHere(false);
1963 addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1964 AlignFrame.DEFAULT_HEIGHT);
1967 af.alignPanels.clear();
1968 af.closeMenuItem_actionPerformed(true);
1973 * Gather expanded views (separate AlignFrame's) with the same sequence set
1974 * identifier back in to this frame as additional views, and close the
1975 * expanded views. Note the expanded frames may themselves have multiple
1976 * views. We take the lot.
1980 public void gatherViews(AlignFrame source)
1982 source.viewport.setGatherViewsHere(true);
1983 source.viewport.setExplodedGeometry(source.getBounds());
1984 JInternalFrame[] frames = desktop.getAllFrames();
1985 String viewId = source.viewport.getSequenceSetId();
1987 for (int t = 0; t < frames.length; t++)
1989 if (frames[t] instanceof AlignFrame && frames[t] != source)
1991 AlignFrame af = (AlignFrame) frames[t];
1992 boolean gatherThis = false;
1993 for (int a = 0; a < af.alignPanels.size(); a++)
1995 AlignmentPanel ap = af.alignPanels.get(a);
1996 if (viewId.equals(ap.av.getSequenceSetId()))
1999 ap.av.setGatherViewsHere(false);
2000 ap.av.setExplodedGeometry(af.getBounds());
2001 source.addAlignmentPanel(ap, false);
2007 af.alignPanels.clear();
2008 af.closeMenuItem_actionPerformed(true);
2015 jalview.gui.VamsasApplication v_client = null;
2018 public void vamsasImport_actionPerformed(ActionEvent e)
2020 if (v_client == null)
2022 // Load and try to start a session.
2023 JalviewFileChooser chooser = new JalviewFileChooser(
2024 jalview.bin.Cache.getProperty("LAST_DIRECTORY"));
2026 chooser.setFileView(new JalviewFileView());
2027 chooser.setDialogTitle(
2028 MessageManager.getString("label.open_saved_vamsas_session"));
2029 chooser.setToolTipText(MessageManager.getString(
2030 "label.select_vamsas_session_opened_as_new_vamsas_session"));
2032 int value = chooser.showOpenDialog(this);
2034 if (value == JalviewFileChooser.APPROVE_OPTION)
2036 String fle = chooser.getSelectedFile().toString();
2037 if (!vamsasImport(chooser.getSelectedFile()))
2039 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2040 MessageManager.formatMessage(
2041 "label.couldnt_import_as_vamsas_session",
2045 .getString("label.vamsas_document_import_failed"),
2046 JvOptionPane.ERROR_MESSAGE);
2052 jalview.bin.Cache.log.error(
2053 "Implementation error - load session from a running session is not supported.");
2058 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
2061 * @return true if import was a success and a session was started.
2063 public boolean vamsasImport(URL url)
2065 // TODO: create progress bar
2066 if (v_client != null)
2069 jalview.bin.Cache.log.error(
2070 "Implementation error - load session from a running session is not supported.");
2076 // copy the URL content to a temporary local file
2077 // TODO: be a bit cleverer here with nio (?!)
2078 File file = File.createTempFile("vdocfromurl", ".vdj");
2079 FileOutputStream fos = new FileOutputStream(file);
2080 BufferedInputStream bis = new BufferedInputStream(url.openStream());
2081 byte[] buffer = new byte[2048];
2083 while ((ln = bis.read(buffer)) > -1)
2085 fos.write(buffer, 0, ln);
2089 v_client = new jalview.gui.VamsasApplication(this, file,
2090 url.toExternalForm());
2091 } catch (Exception ex)
2093 jalview.bin.Cache.log.error(
2094 "Failed to create new vamsas session from contents of URL "
2099 setupVamsasConnectedGui();
2100 v_client.initial_update(); // TODO: thread ?
2101 return v_client.inSession();
2105 * import file into a new vamsas session (uses jalview.gui.VamsasApplication)
2108 * @return true if import was a success and a session was started.
2110 public boolean vamsasImport(File file)
2112 if (v_client != null)
2115 jalview.bin.Cache.log.error(
2116 "Implementation error - load session from a running session is not supported.");
2120 setProgressBar(MessageManager.formatMessage(
2121 "status.importing_vamsas_session_from", new Object[]
2122 { file.getName() }), file.hashCode());
2125 v_client = new jalview.gui.VamsasApplication(this, file, null);
2126 } catch (Exception ex)
2128 setProgressBar(MessageManager.formatMessage(
2129 "status.importing_vamsas_session_from", new Object[]
2130 { file.getName() }), file.hashCode());
2131 jalview.bin.Cache.log.error(
2132 "New vamsas session from existing session file failed:", ex);
2135 setupVamsasConnectedGui();
2136 v_client.initial_update(); // TODO: thread ?
2137 setProgressBar(MessageManager.formatMessage(
2138 "status.importing_vamsas_session_from", new Object[]
2139 { file.getName() }), file.hashCode());
2140 return v_client.inSession();
2143 public boolean joinVamsasSession(String mysesid)
2145 if (v_client != null)
2147 throw new Error(MessageManager
2148 .getString("error.try_join_vamsas_session_another"));
2150 if (mysesid == null)
2153 MessageManager.getString("error.invalid_vamsas_session_id"));
2155 v_client = new VamsasApplication(this, mysesid);
2156 setupVamsasConnectedGui();
2157 v_client.initial_update();
2158 return (v_client.inSession());
2162 public void vamsasStart_actionPerformed(ActionEvent e)
2164 if (v_client == null)
2167 // we just start a default session for moment.
2169 * JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache.
2170 * getProperty("LAST_DIRECTORY"));
2172 * chooser.setFileView(new JalviewFileView());
2173 * chooser.setDialogTitle("Load Vamsas file");
2174 * chooser.setToolTipText("Import");
2176 * int value = chooser.showOpenDialog(this);
2178 * if (value == JalviewFileChooser.APPROVE_OPTION) { v_client = new
2179 * jalview.gui.VamsasApplication(this, chooser.getSelectedFile());
2181 v_client = new VamsasApplication(this);
2182 setupVamsasConnectedGui();
2183 v_client.initial_update(); // TODO: thread ?
2187 // store current data in session.
2188 v_client.push_update(); // TODO: thread
2192 protected void setupVamsasConnectedGui()
2194 vamsasStart.setText(MessageManager.getString("label.session_update"));
2195 vamsasSave.setVisible(true);
2196 vamsasStop.setVisible(true);
2197 vamsasImport.setVisible(false); // Document import to existing session is
2198 // not possible for vamsas-client-1.0.
2201 protected void setupVamsasDisconnectedGui()
2203 vamsasSave.setVisible(false);
2204 vamsasStop.setVisible(false);
2205 vamsasImport.setVisible(true);
2207 .setText(MessageManager.getString("label.new_vamsas_session"));
2211 public void vamsasStop_actionPerformed(ActionEvent e)
2213 if (v_client != null)
2215 v_client.end_session();
2217 setupVamsasDisconnectedGui();
2221 protected void buildVamsasStMenu()
2223 if (v_client == null)
2225 String[] sess = null;
2228 sess = VamsasApplication.getSessionList();
2229 } catch (Exception e)
2231 jalview.bin.Cache.log.warn("Problem getting current sessions list.",
2237 jalview.bin.Cache.log.debug(
2238 "Got current sessions list: " + sess.length + " entries.");
2239 VamsasStMenu.removeAll();
2240 for (int i = 0; i < sess.length; i++)
2242 JMenuItem sessit = new JMenuItem();
2243 sessit.setText(sess[i]);
2244 sessit.setToolTipText(MessageManager
2245 .formatMessage("label.connect_to_session", new Object[]
2247 final Desktop dsktp = this;
2248 final String mysesid = sess[i];
2249 sessit.addActionListener(new ActionListener()
2253 public void actionPerformed(ActionEvent e)
2255 if (dsktp.v_client == null)
2257 Thread rthr = new Thread(new Runnable()
2263 dsktp.v_client = new VamsasApplication(dsktp, mysesid);
2264 dsktp.setupVamsasConnectedGui();
2265 dsktp.v_client.initial_update();
2273 VamsasStMenu.add(sessit);
2275 // don't show an empty menu.
2276 VamsasStMenu.setVisible(sess.length > 0);
2281 jalview.bin.Cache.log.debug("No current vamsas sessions.");
2282 VamsasStMenu.removeAll();
2283 VamsasStMenu.setVisible(false);
2288 // Not interested in the content. Just hide ourselves.
2289 VamsasStMenu.setVisible(false);
2294 public void vamsasSave_actionPerformed(ActionEvent e)
2296 if (v_client != null)
2298 // TODO: VAMSAS DOCUMENT EXTENSION is VDJ
2299 JalviewFileChooser chooser = new JalviewFileChooser("vdj",
2302 chooser.setFileView(new JalviewFileView());
2303 chooser.setDialogTitle(MessageManager
2304 .getString("label.save_vamsas_document_archive"));
2306 int value = chooser.showSaveDialog(this);
2308 if (value == JalviewFileChooser.APPROVE_OPTION)
2310 java.io.File choice = chooser.getSelectedFile();
2311 JPanel progpanel = addProgressPanel(MessageManager
2312 .formatMessage("label.saving_vamsas_doc", new Object[]
2313 { choice.getName() }));
2314 Cache.setProperty("LAST_DIRECTORY", choice.getParent());
2315 String warnmsg = null;
2316 String warnttl = null;
2319 v_client.vclient.storeDocument(choice);
2322 warnttl = "Serious Problem saving Vamsas Document";
2323 warnmsg = ex.toString();
2324 jalview.bin.Cache.log
2325 .error("Error Whilst saving document to " + choice, ex);
2327 } catch (Exception ex)
2329 warnttl = "Problem saving Vamsas Document.";
2330 warnmsg = ex.toString();
2331 jalview.bin.Cache.log.warn(
2332 "Exception Whilst saving document to " + choice, ex);
2335 removeProgressPanel(progpanel);
2336 if (warnmsg != null)
2338 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2340 warnmsg, warnttl, JvOptionPane.ERROR_MESSAGE);
2346 JPanel vamUpdate = null;
2349 * hide vamsas user gui bits when a vamsas document event is being handled.
2352 * true to hide gui, false to reveal gui
2354 public void setVamsasUpdate(boolean b)
2356 Cache.log.debug("Setting gui for Vamsas update "
2357 + (b ? "in progress" : "finished"));
2359 if (vamUpdate != null)
2361 this.removeProgressPanel(vamUpdate);
2365 vamUpdate = this.addProgressPanel(
2366 MessageManager.getString("label.updating_vamsas_session"));
2368 vamsasStart.setVisible(!b);
2369 vamsasStop.setVisible(!b);
2370 vamsasSave.setVisible(!b);
2373 public JInternalFrame[] getAllFrames()
2375 return desktop.getAllFrames();
2379 * Checks the given url to see if it gives a response indicating that the user
2380 * should be informed of a new questionnaire.
2384 public void checkForQuestionnaire(String url)
2386 UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
2387 // javax.swing.SwingUtilities.invokeLater(jvq);
2388 new Thread(jvq).start();
2391 public void checkURLLinks()
2393 // Thread off the URL link checker
2394 addDialogThread(new Runnable()
2399 if (Cache.getDefault("CHECKURLLINKS", true))
2401 // check what the actual links are - if it's just the default don't
2402 // bother with the warning
2403 List<String> links = Preferences.sequenceUrlLinks
2406 // only need to check links if there is one with a
2407 // SEQUENCE_ID which is not the default EMBL_EBI link
2408 ListIterator<String> li = links.listIterator();
2409 boolean check = false;
2410 List<JLabel> urls = new ArrayList<>();
2411 while (li.hasNext())
2413 String link = li.next();
2414 if (link.contains(SEQUENCE_ID)
2415 && !UrlConstants.isDefaultString(link))
2418 int barPos = link.indexOf("|");
2419 String urlMsg = barPos == -1 ? link
2420 : link.substring(0, barPos) + ": "
2421 + link.substring(barPos + 1);
2422 urls.add(new JLabel(urlMsg));
2430 // ask user to check in case URL links use old style tokens
2431 // ($SEQUENCE_ID$ for sequence id _or_ accession id)
2432 JPanel msgPanel = new JPanel();
2433 msgPanel.setLayout(new BoxLayout(msgPanel, BoxLayout.PAGE_AXIS));
2434 msgPanel.add(Box.createVerticalGlue());
2435 JLabel msg = new JLabel(MessageManager
2436 .getString("label.SEQUENCE_ID_for_DB_ACCESSION1"));
2437 JLabel msg2 = new JLabel(MessageManager
2438 .getString("label.SEQUENCE_ID_for_DB_ACCESSION2"));
2440 for (JLabel url : urls)
2446 final JCheckBox jcb = new JCheckBox(
2447 MessageManager.getString("label.do_not_display_again"));
2448 jcb.addActionListener(new ActionListener()
2451 public void actionPerformed(ActionEvent e)
2453 // update Cache settings for "don't show this again"
2454 boolean showWarningAgain = !jcb.isSelected();
2455 Cache.setProperty("CHECKURLLINKS",
2456 Boolean.valueOf(showWarningAgain).toString());
2461 JvOptionPane.showMessageDialog(Desktop.desktop, msgPanel,
2463 .getString("label.SEQUENCE_ID_no_longer_used"),
2464 JvOptionPane.WARNING_MESSAGE);
2471 * Proxy class for JDesktopPane which optionally displays the current memory
2472 * usage and highlights the desktop area with a red bar if free memory runs
2477 public class MyDesktopPane extends JDesktopPane implements Runnable
2480 private static final float ONE_MB = 1048576f;
2482 boolean showMemoryUsage = false;
2486 java.text.NumberFormat df;
2488 float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
2491 public MyDesktopPane(boolean showMemoryUsage)
2493 showMemoryUsage(showMemoryUsage);
2496 public void showMemoryUsage(boolean showMemory)
2498 this.showMemoryUsage = showMemory;
2501 Thread worker = new Thread(this);
2507 public boolean isShowMemoryUsage()
2509 return showMemoryUsage;
2515 df = java.text.NumberFormat.getNumberInstance();
2516 df.setMaximumFractionDigits(2);
2517 runtime = Runtime.getRuntime();
2519 while (showMemoryUsage)
2523 maxMemory = runtime.maxMemory() / ONE_MB;
2524 allocatedMemory = runtime.totalMemory() / ONE_MB;
2525 freeMemory = runtime.freeMemory() / ONE_MB;
2526 totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
2528 percentUsage = (totalFreeMemory / maxMemory) * 100;
2530 // if (percentUsage < 20)
2532 // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
2534 // instance.set.setBorder(border1);
2537 // sleep after showing usage
2539 } catch (Exception ex)
2541 ex.printStackTrace();
2547 public void paintComponent(Graphics g)
2549 if (showMemoryUsage && g != null && df != null)
2551 if (percentUsage < 20)
2553 g.setColor(Color.red);
2555 FontMetrics fm = g.getFontMetrics();
2558 g.drawString(MessageManager.formatMessage("label.memory_stats",
2560 { df.format(totalFreeMemory), df.format(maxMemory),
2561 df.format(percentUsage) }),
2562 10, getHeight() - fm.getHeight());
2569 * Accessor method to quickly get all the AlignmentFrames loaded.
2571 * @return an array of AlignFrame, or null if none found
2573 public static AlignFrame[] getAlignFrames()
2575 if (Jalview.isHeadlessMode())
2577 // Desktop.desktop is null in headless mode
2578 return new AlignFrame[] { Jalview.currentAlignFrame };
2581 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2587 List<AlignFrame> avp = new ArrayList<>();
2589 for (int i = frames.length - 1; i > -1; i--)
2591 if (frames[i] instanceof AlignFrame)
2593 avp.add((AlignFrame) frames[i]);
2595 else if (frames[i] instanceof SplitFrame)
2598 * Also check for a split frame containing an AlignFrame
2600 GSplitFrame sf = (GSplitFrame) frames[i];
2601 if (sf.getTopFrame() instanceof AlignFrame)
2603 avp.add((AlignFrame) sf.getTopFrame());
2605 if (sf.getBottomFrame() instanceof AlignFrame)
2607 avp.add((AlignFrame) sf.getBottomFrame());
2611 if (avp.size() == 0)
2615 AlignFrame afs[] = avp.toArray(new AlignFrame[avp.size()]);
2620 * Returns an array of any AppJmol frames in the Desktop (or null if none).
2624 public GStructureViewer[] getJmols()
2626 JInternalFrame[] frames = Desktop.desktop.getAllFrames();
2632 List<GStructureViewer> avp = new ArrayList<>();
2634 for (int i = frames.length - 1; i > -1; i--)
2636 if (frames[i] instanceof AppJmol)
2638 GStructureViewer af = (GStructureViewer) frames[i];
2642 if (avp.size() == 0)
2646 GStructureViewer afs[] = avp.toArray(new GStructureViewer[avp.size()]);
2651 * Add Groovy Support to Jalview
2654 public void groovyShell_actionPerformed()
2658 openGroovyConsole();
2659 } catch (Exception ex)
2661 jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
2662 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
2664 MessageManager.getString("label.couldnt_create_groovy_shell"),
2665 MessageManager.getString("label.groovy_support_failed"),
2666 JvOptionPane.ERROR_MESSAGE);
2671 * Open the Groovy console
2673 void openGroovyConsole()
2675 if (groovyConsole == null)
2677 groovyConsole = new groovy.ui.Console();
2678 groovyConsole.setVariable("Jalview", this);
2679 groovyConsole.run();
2682 * We allow only one console at a time, so that AlignFrame menu option
2683 * 'Calculate | Run Groovy script' is unambiguous.
2684 * Disable 'Groovy Console', and enable 'Run script', when the console is
2685 * opened, and the reverse when it is closed
2687 Window window = (Window) groovyConsole.getFrame();
2688 window.addWindowListener(new WindowAdapter()
2691 public void windowClosed(WindowEvent e)
2694 * rebind CMD-Q from Groovy Console to Jalview Quit
2697 enableExecuteGroovy(false);
2703 * show Groovy console window (after close and reopen)
2705 ((Window) groovyConsole.getFrame()).setVisible(true);
2708 * if we got this far, enable 'Run Groovy' in AlignFrame menus
2709 * and disable opening a second console
2711 enableExecuteGroovy(true);
2715 * Bind Ctrl/Cmd-Q to Quit - for reset as Groovy Console takes over this
2716 * binding when opened
2718 protected void addQuitHandler()
2720 getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
2721 .put(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
2722 Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()),
2724 getRootPane().getActionMap().put("Quit", new AbstractAction()
2727 public void actionPerformed(ActionEvent e)
2735 * Enable or disable 'Run Groovy script' in AlignFrame calculate menus
2738 * true if Groovy console is open
2740 public void enableExecuteGroovy(boolean enabled)
2743 * disable opening a second Groovy console
2744 * (or re-enable when the console is closed)
2746 groovyShell.setEnabled(!enabled);
2748 AlignFrame[] alignFrames = getAlignFrames();
2749 if (alignFrames != null)
2751 for (AlignFrame af : alignFrames)
2753 af.setGroovyEnabled(enabled);
2759 * Progress bars managed by the IProgressIndicator method.
2761 private Hashtable<Long, JPanel> progressBars;
2763 private Hashtable<Long, IProgressIndicatorHandler> progressBarHandlers;
2768 * @see jalview.gui.IProgressIndicator#setProgressBar(java.lang.String, long)
2771 public void setProgressBar(String message, long id)
2773 if (progressBars == null)
2775 progressBars = new Hashtable<>();
2776 progressBarHandlers = new Hashtable<>();
2779 if (progressBars.get(new Long(id)) != null)
2781 JPanel panel = progressBars.remove(new Long(id));
2782 if (progressBarHandlers.contains(new Long(id)))
2784 progressBarHandlers.remove(new Long(id));
2786 removeProgressPanel(panel);
2790 progressBars.put(new Long(id), addProgressPanel(message));
2797 * @see jalview.gui.IProgressIndicator#registerHandler(long,
2798 * jalview.gui.IProgressIndicatorHandler)
2801 public void registerHandler(final long id,
2802 final IProgressIndicatorHandler handler)
2804 if (progressBarHandlers == null
2805 || !progressBars.containsKey(new Long(id)))
2807 throw new Error(MessageManager.getString(
2808 "error.call_setprogressbar_before_registering_handler"));
2810 progressBarHandlers.put(new Long(id), handler);
2811 final JPanel progressPanel = progressBars.get(new Long(id));
2812 if (handler.canCancel())
2814 JButton cancel = new JButton(
2815 MessageManager.getString("action.cancel"));
2816 final IProgressIndicator us = this;
2817 cancel.addActionListener(new ActionListener()
2821 public void actionPerformed(ActionEvent e)
2823 handler.cancelActivity(id);
2824 us.setProgressBar(MessageManager
2825 .formatMessage("label.cancelled_params", new Object[]
2826 { ((JLabel) progressPanel.getComponent(0)).getText() }),
2830 progressPanel.add(cancel, BorderLayout.EAST);
2836 * @return true if any progress bars are still active
2839 public boolean operationInProgress()
2841 if (progressBars != null && progressBars.size() > 0)
2849 * This will return the first AlignFrame holding the given viewport instance.
2850 * It will break if there are more than one AlignFrames viewing a particular
2854 * @return alignFrame for viewport
2856 public static AlignFrame getAlignFrameFor(AlignViewportI viewport)
2858 if (desktop != null)
2860 AlignmentPanel[] aps = getAlignmentPanels(
2861 viewport.getSequenceSetId());
2862 for (int panel = 0; aps != null && panel < aps.length; panel++)
2864 if (aps[panel] != null && aps[panel].av == viewport)
2866 return aps[panel].alignFrame;
2873 public VamsasApplication getVamsasApplication()
2880 * flag set if jalview GUI is being operated programmatically
2882 private boolean inBatchMode = false;
2885 * check if jalview GUI is being operated programmatically
2887 * @return inBatchMode
2889 public boolean isInBatchMode()
2895 * set flag if jalview GUI is being operated programmatically
2897 * @param inBatchMode
2899 public void setInBatchMode(boolean inBatchMode)
2901 this.inBatchMode = inBatchMode;
2904 public void startServiceDiscovery()
2906 startServiceDiscovery(false);
2909 public void startServiceDiscovery(boolean blocking)
2911 boolean alive = true;
2912 Thread t0 = null, t1 = null, t2 = null;
2913 // JAL-940 - JALVIEW 1 services are now being EOLed as of JABA 2.1 release
2916 // todo: changesupport handlers need to be transferred
2917 if (discoverer == null)
2919 discoverer = new jalview.ws.jws1.Discoverer();
2920 // register PCS handler for desktop.
2921 discoverer.addPropertyChangeListener(changeSupport);
2923 // JAL-940 - disabled JWS1 service configuration - always start discoverer
2924 // until we phase out completely
2925 (t0 = new Thread(discoverer)).start();
2928 if (Cache.getDefault("SHOW_JWS2_SERVICES", true))
2930 t2 = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2931 .startDiscoverer(changeSupport);
2935 // TODO: do rest service discovery
2944 } catch (Exception e)
2947 alive = (t1 != null && t1.isAlive()) || (t2 != null && t2.isAlive())
2948 || (t3 != null && t3.isAlive())
2949 || (t0 != null && t0.isAlive());
2955 * called to check if the service discovery process completed successfully.
2959 protected void JalviewServicesChanged(PropertyChangeEvent evt)
2961 if (evt.getNewValue() == null || evt.getNewValue() instanceof Vector)
2963 final String ermsg = jalview.ws.jws2.Jws2Discoverer.getDiscoverer()
2964 .getErrorMessages();
2967 if (Cache.getDefault("SHOW_WSDISCOVERY_ERRORS", true))
2969 if (serviceChangedDialog == null)
2971 // only run if we aren't already displaying one of these.
2972 addDialogThread(serviceChangedDialog = new Runnable()
2979 * JalviewDialog jd =new JalviewDialog() {
2981 * @Override protected void cancelPressed() { // TODO
2982 * Auto-generated method stub
2984 * }@Override protected void okPressed() { // TODO
2985 * Auto-generated method stub
2987 * }@Override protected void raiseClosed() { // TODO
2988 * Auto-generated method stub
2990 * } }; jd.initDialogFrame(new
2991 * JLabel("<html><table width=\"450\"><tr><td>" + ermsg +
2992 * "<br/>It may be that you have invalid JABA URLs in your web service preferences,"
2993 * + " or mis-configured HTTP proxy settings.<br/>" +
2994 * "Check the <em>Connections</em> and <em>Web services</em> tab of the"
2996 * " Tools->Preferences dialog box to change them.</td></tr></table></html>"
2997 * ), true, true, "Web Service Configuration Problem", 450,
3000 * jd.waitForInput();
3002 JvOptionPane.showConfirmDialog(Desktop.desktop,
3003 new JLabel("<html><table width=\"450\"><tr><td>"
3004 + ermsg + "</td></tr></table>"
3005 + "<p>It may be that you have invalid JABA URLs<br/>in your web service preferences,"
3006 + "<br>or as a command-line argument, or mis-configured HTTP proxy settings.</p>"
3007 + "<p>Check the <em>Connections</em> and <em>Web services</em> tab<br/>of the"
3008 + " Tools->Preferences dialog box to change them.</p></html>"),
3009 "Web Service Configuration Problem",
3010 JvOptionPane.DEFAULT_OPTION,
3011 JvOptionPane.ERROR_MESSAGE);
3012 serviceChangedDialog = null;
3021 "Errors reported by JABA discovery service. Check web services preferences.\n"
3028 private Runnable serviceChangedDialog = null;
3031 * start a thread to open a URL in the configured browser. Pops up a warning
3032 * dialog to the user if there is an exception when calling out to the browser
3037 public static void showUrl(final String url)
3039 showUrl(url, Desktop.instance);
3043 * Like showUrl but allows progress handler to be specified
3047 * (null) or object implementing IProgressIndicator
3049 public static void showUrl(final String url,
3050 final IProgressIndicator progress)
3052 new Thread(new Runnable()
3059 if (progress != null)
3061 progress.setProgressBar(MessageManager
3062 .formatMessage("status.opening_params", new Object[]
3063 { url }), this.hashCode());
3065 jalview.util.BrowserLauncher.openURL(url);
3066 } catch (Exception ex)
3068 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
3070 .getString("label.web_browser_not_found_unix"),
3071 MessageManager.getString("label.web_browser_not_found"),
3072 JvOptionPane.WARNING_MESSAGE);
3074 ex.printStackTrace();
3076 if (progress != null)
3078 progress.setProgressBar(null, this.hashCode());
3084 public static WsParamSetManager wsparamManager = null;
3086 public static ParamManager getUserParameterStore()
3088 if (wsparamManager == null)
3090 wsparamManager = new WsParamSetManager();
3092 return wsparamManager;
3096 * static hyperlink handler proxy method for use by Jalview's internal windows
3100 public static void hyperlinkUpdate(HyperlinkEvent e)
3102 if (e.getEventType() == EventType.ACTIVATED)
3107 url = e.getURL().toString();
3108 Desktop.showUrl(url);
3109 } catch (Exception x)
3113 if (Cache.log != null)
3115 Cache.log.error("Couldn't handle string " + url + " as a URL.");
3120 "Couldn't handle string " + url + " as a URL.");
3123 // ignore any exceptions due to dud links.
3130 * single thread that handles display of dialogs to user.
3132 ExecutorService dialogExecutor = Executors.newSingleThreadExecutor();
3135 * flag indicating if dialogExecutor should try to acquire a permit
3137 private volatile boolean dialogPause = true;
3142 private java.util.concurrent.Semaphore block = new Semaphore(0);
3144 private static groovy.ui.Console groovyConsole;
3147 * add another dialog thread to the queue
3151 public void addDialogThread(final Runnable prompter)
3153 dialogExecutor.submit(new Runnable()
3163 } catch (InterruptedException x)
3168 if (instance == null)
3174 SwingUtilities.invokeAndWait(prompter);
3175 } catch (Exception q)
3177 Cache.log.warn("Unexpected Exception in dialog thread.", q);
3183 public void startDialogQueue()
3185 // set the flag so we don't pause waiting for another permit and semaphore
3186 // the current task to begin
3187 dialogPause = false;
3192 protected void snapShotWindow_actionPerformed(ActionEvent e)
3196 ImageMaker im = new jalview.util.ImageMaker(
3197 this, ImageMaker.TYPE.EPS, "View of Desktop", getWidth(),
3198 getHeight(), of = new File("Jalview_snapshot"
3199 + System.currentTimeMillis() + ".eps"),
3200 "View of desktop", null, 0, false);
3203 paintAll(im.getGraphics());
3205 } catch (Exception q)
3207 Cache.log.error("Couldn't write snapshot to " + of.getAbsolutePath(),
3211 Cache.log.info("Successfully written snapshot to file "
3212 + of.getAbsolutePath());
3216 * Explode the views in the given SplitFrame into separate SplitFrame windows.
3217 * This respects (remembers) any previous 'exploded geometry' i.e. the size
3218 * and location last time the view was expanded (if any). However it does not
3219 * remember the split pane divider location - this is set to match the
3220 * 'exploding' frame.
3224 public void explodeViews(SplitFrame sf)
3226 AlignFrame oldTopFrame = (AlignFrame) sf.getTopFrame();
3227 AlignFrame oldBottomFrame = (AlignFrame) sf.getBottomFrame();
3228 List<? extends AlignmentViewPanel> topPanels = oldTopFrame
3230 List<? extends AlignmentViewPanel> bottomPanels = oldBottomFrame
3232 int viewCount = topPanels.size();
3239 * Processing in reverse order works, forwards order leaves the first panels
3240 * not visible. I don't know why!
3242 for (int i = viewCount - 1; i >= 0; i--)
3245 * Make new top and bottom frames. These take over the respective
3246 * AlignmentPanel objects, including their AlignmentViewports, so the
3247 * cdna/protein relationships between the viewports is carried over to the
3250 * explodedGeometry holds the (x, y) position of the previously exploded
3251 * SplitFrame, and the (width, height) of the AlignFrame component
3253 AlignmentPanel topPanel = (AlignmentPanel) topPanels.get(i);
3254 AlignFrame newTopFrame = new AlignFrame(topPanel);
3255 newTopFrame.setSize(oldTopFrame.getSize());
3256 newTopFrame.setVisible(true);
3257 Rectangle geometry = ((AlignViewport) topPanel.getAlignViewport())
3258 .getExplodedGeometry();
3259 if (geometry != null)
3261 newTopFrame.setSize(geometry.getSize());
3264 AlignmentPanel bottomPanel = (AlignmentPanel) bottomPanels.get(i);
3265 AlignFrame newBottomFrame = new AlignFrame(bottomPanel);
3266 newBottomFrame.setSize(oldBottomFrame.getSize());
3267 newBottomFrame.setVisible(true);
3268 geometry = ((AlignViewport) bottomPanel.getAlignViewport())
3269 .getExplodedGeometry();
3270 if (geometry != null)
3272 newBottomFrame.setSize(geometry.getSize());
3275 topPanel.av.setGatherViewsHere(false);
3276 bottomPanel.av.setGatherViewsHere(false);
3277 JInternalFrame splitFrame = new SplitFrame(newTopFrame,
3279 if (geometry != null)
3281 splitFrame.setLocation(geometry.getLocation());
3283 Desktop.addInternalFrame(splitFrame, sf.getTitle(), -1, -1);
3287 * Clear references to the panels (now relocated in the new SplitFrames)
3288 * before closing the old SplitFrame.
3291 bottomPanels.clear();
3296 * Gather expanded split frames, sharing the same pairs of sequence set ids,
3297 * back into the given SplitFrame as additional views. Note that the gathered
3298 * frames may themselves have multiple views.
3302 public void gatherViews(GSplitFrame source)
3305 * special handling of explodedGeometry for a view within a SplitFrame: - it
3306 * holds the (x, y) position of the enclosing SplitFrame, and the (width,
3307 * height) of the AlignFrame component
3309 AlignFrame myTopFrame = (AlignFrame) source.getTopFrame();
3310 AlignFrame myBottomFrame = (AlignFrame) source.getBottomFrame();
3311 myTopFrame.viewport.setExplodedGeometry(new Rectangle(source.getX(),
3312 source.getY(), myTopFrame.getWidth(), myTopFrame.getHeight()));
3313 myBottomFrame.viewport
3314 .setExplodedGeometry(new Rectangle(source.getX(), source.getY(),
3315 myBottomFrame.getWidth(), myBottomFrame.getHeight()));
3316 myTopFrame.viewport.setGatherViewsHere(true);
3317 myBottomFrame.viewport.setGatherViewsHere(true);
3318 String topViewId = myTopFrame.viewport.getSequenceSetId();
3319 String bottomViewId = myBottomFrame.viewport.getSequenceSetId();
3321 JInternalFrame[] frames = desktop.getAllFrames();
3322 for (JInternalFrame frame : frames)
3324 if (frame instanceof SplitFrame && frame != source)
3326 SplitFrame sf = (SplitFrame) frame;
3327 AlignFrame topFrame = (AlignFrame) sf.getTopFrame();
3328 AlignFrame bottomFrame = (AlignFrame) sf.getBottomFrame();
3329 boolean gatherThis = false;
3330 for (int a = 0; a < topFrame.alignPanels.size(); a++)
3332 AlignmentPanel topPanel = topFrame.alignPanels.get(a);
3333 AlignmentPanel bottomPanel = bottomFrame.alignPanels.get(a);
3334 if (topViewId.equals(topPanel.av.getSequenceSetId())
3335 && bottomViewId.equals(bottomPanel.av.getSequenceSetId()))
3338 topPanel.av.setGatherViewsHere(false);
3339 bottomPanel.av.setGatherViewsHere(false);
3340 topPanel.av.setExplodedGeometry(
3341 new Rectangle(sf.getLocation(), topFrame.getSize()));
3342 bottomPanel.av.setExplodedGeometry(
3343 new Rectangle(sf.getLocation(), bottomFrame.getSize()));
3344 myTopFrame.addAlignmentPanel(topPanel, false);
3345 myBottomFrame.addAlignmentPanel(bottomPanel, false);
3351 topFrame.getAlignPanels().clear();
3352 bottomFrame.getAlignPanels().clear();
3359 * The dust settles...give focus to the tab we did this from.
3361 myTopFrame.setDisplayedView(myTopFrame.alignPanel);
3364 public static groovy.ui.Console getGroovyConsole()
3366 return groovyConsole;
3370 * handles the payload of a drag and drop event.
3372 * TODO refactor to desktop utilities class
3375 * - Data source strings extracted from the drop event
3377 * - protocol for each data source extracted from the drop event
3381 * - the payload from the drop event
3384 public static void transferFromDropTarget(List<String> files,
3385 List<DataSourceType> protocols, DropTargetDropEvent evt,
3386 Transferable t) throws Exception
3389 DataFlavor uriListFlavor = new DataFlavor(
3390 "text/uri-list;class=java.lang.String"), urlFlavour = null;
3393 urlFlavour = new DataFlavor(
3394 "application/x-java-url; class=java.net.URL");
3395 } catch (ClassNotFoundException cfe)
3397 Cache.log.debug("Couldn't instantiate the URL dataflavor.", cfe);
3400 if (urlFlavour != null && t.isDataFlavorSupported(urlFlavour))
3405 java.net.URL url = (URL) t.getTransferData(urlFlavour);
3406 // nb: java 8 osx bug https://bugs.openjdk.java.net/browse/JDK-8156099
3407 // means url may be null.
3410 protocols.add(DataSourceType.URL);
3411 files.add(url.toString());
3412 Cache.log.debug("Drop handled as URL dataflavor "
3413 + files.get(files.size() - 1));
3418 if (Platform.isAMac())
3421 "Please ignore plist error - occurs due to problem with java 8 on OSX");
3425 } catch (Throwable ex)
3427 Cache.log.debug("URL drop handler failed.", ex);
3430 if (t.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
3432 // Works on Windows and MacOSX
3433 Cache.log.debug("Drop handled as javaFileListFlavor");
3434 for (Object file : (List) t
3435 .getTransferData(DataFlavor.javaFileListFlavor))
3437 files.add(((File) file).toString());
3438 protocols.add(DataSourceType.FILE);
3443 // Unix like behaviour
3444 boolean added = false;
3446 if (t.isDataFlavorSupported(uriListFlavor))
3448 Cache.log.debug("Drop handled as uriListFlavor");
3449 // This is used by Unix drag system
3450 data = (String) t.getTransferData(uriListFlavor);
3454 // fallback to text: workaround - on OSX where there's a JVM bug
3455 Cache.log.debug("standard URIListFlavor failed. Trying text");
3456 // try text fallback
3457 DataFlavor textDf = new DataFlavor(
3458 "text/plain;class=java.lang.String");
3459 if (t.isDataFlavorSupported(textDf))
3461 data = (String) t.getTransferData(textDf);
3464 Cache.log.debug("Plain text drop content returned "
3465 + (data == null ? "Null - failed" : data));
3470 while (protocols.size() < files.size())
3472 Cache.log.debug("Adding missing FILE protocol for "
3473 + files.get(protocols.size()));
3474 protocols.add(DataSourceType.FILE);
3476 for (java.util.StringTokenizer st = new java.util.StringTokenizer(
3477 data, "\r\n"); st.hasMoreTokens();)
3480 String s = st.nextToken();
3481 if (s.startsWith("#"))
3483 // the line is a comment (as per the RFC 2483)
3486 java.net.URI uri = new java.net.URI(s);
3487 if (uri.getScheme().toLowerCase().startsWith("http"))
3489 protocols.add(DataSourceType.URL);
3490 files.add(uri.toString());
3494 // otherwise preserve old behaviour: catch all for file objects
3495 java.io.File file = new java.io.File(uri);
3496 protocols.add(DataSourceType.FILE);
3497 files.add(file.toString());
3502 if (Cache.log.isDebugEnabled())
3504 if (data == null || !added)
3507 if (t.getTransferDataFlavors() != null
3508 && t.getTransferDataFlavors().length > 0)
3511 "Couldn't resolve drop data. Here are the supported flavors:");
3512 for (DataFlavor fl : t.getTransferDataFlavors())
3515 "Supported transfer dataflavor: " + fl.toString());
3516 Object df = t.getTransferData(fl);
3519 Cache.log.debug("Retrieves: " + df);
3523 Cache.log.debug("Retrieved nothing");
3529 Cache.log.debug("Couldn't resolve dataflavor for drop: "
3535 if (Platform.isWindows())
3538 Cache.log.debug("Scanning dropped content for Windows Link Files");
3540 // resolve any .lnk files in the file drop
3541 for (int f = 0; f < files.size(); f++)
3543 String source = files.get(f).toLowerCase();
3544 if (protocols.get(f).equals(DataSourceType.FILE)
3545 && (source.endsWith(".lnk") || source.endsWith(".url")
3546 || source.endsWith(".site")))
3550 File lf = new File(files.get(f));
3551 // process link file to get a URL
3552 Cache.log.debug("Found potential link file: " + lf);
3553 WindowsShortcut wscfile = new WindowsShortcut(lf);
3554 String fullname = wscfile.getRealFilename();
3555 protocols.set(f, FormatAdapter.checkProtocol(fullname));
3556 files.set(f, fullname);
3557 Cache.log.debug("Parsed real filename " + fullname
3558 + " to extract protocol: " + protocols.get(f));
3559 } catch (Exception ex)
3562 "Couldn't parse " + files.get(f) + " as a link file.",
3571 * Sets the Preferences property for experimental features to True or False
3572 * depending on the state of the controlling menu item
3575 protected void showExperimental_actionPerformed(boolean selected)
3577 Cache.setProperty(EXPERIMENTAL_FEATURES, Boolean.toString(selected));
3581 * Answers a (possibly empty) list of any structure viewer frames (currently
3582 * for either Jmol or Chimera) which are currently open. This may optionally
3583 * be restricted to viewers of a specified class, or viewers linked to a
3584 * specified alignment panel.
3587 * if not null, only return viewers linked to this panel
3588 * @param structureViewerClass
3589 * if not null, only return viewers of this class
3592 public List<StructureViewerBase> getStructureViewers(
3593 AlignmentPanel apanel,
3594 Class<? extends StructureViewerBase> structureViewerClass)
3596 List<StructureViewerBase> result = new ArrayList<>();
3597 JInternalFrame[] frames = Desktop.instance.getAllFrames();
3599 for (JInternalFrame frame : frames)
3601 if (frame instanceof StructureViewerBase)
3603 if (structureViewerClass == null
3604 || structureViewerClass.isInstance(frame))
3607 || ((StructureViewerBase) frame).isLinkedWith(apanel))
3609 result.add((StructureViewerBase) frame);