+ frame.toFront();
+ try
+ {
+ frame.setSelected(true);
+ frame.requestFocus();
+ } catch (java.beans.PropertyVetoException ve)
+ {
+ } catch (java.lang.ClassCastException cex)
+ {
+ Cache.log.warn(
+ "Squashed a possible GUI implementation error. If you can recreate this, please look at http://issues.jalview.org/browse/JAL-869",
+ cex);
+ }
+ }
+
+ /**
+ * Add key bindings to a JInternalFrame so that Ctrl-W and Cmd-W will close
+ * the window
+ *
+ * @param frame
+ */
+ private static void setKeyBindings(JInternalFrame frame)
+ {
+ @SuppressWarnings("serial")
+ final Action closeAction = new AbstractAction()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ frame.dispose();
+ }
+ };
+
+ /*
+ * set up key bindings for Ctrl-W and Cmd-W, with the same (Close) action
+ */
+ KeyStroke ctrlWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
+ InputEvent.CTRL_DOWN_MASK);
+ KeyStroke cmdWKey = KeyStroke.getKeyStroke(KeyEvent.VK_W,
+ jalview.util.ShortcutKeyMaskExWrapper.getMenuShortcutKeyMaskEx());
+
+ InputMap inputMap = frame
+ .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
+ String ctrlW = ctrlWKey.toString();
+ inputMap.put(ctrlWKey, ctrlW);
+ inputMap.put(cmdWKey, ctrlW);
+
+ ActionMap actionMap = frame.getActionMap();
+ actionMap.put(ctrlW, closeAction);
+ }
+
+ @Override
+ public void lostOwnership(Clipboard clipboard, Transferable contents)
+ {
+ if (!internalCopy)
+ {
+ Desktop.jalviewClipboard = null;
+ }
+
+ internalCopy = false;
+ }
+
+ @Override
+ public void dragEnter(DropTargetDragEvent evt)
+ {
+ }
+
+ @Override
+ public void dragExit(DropTargetEvent evt)
+ {
+ }
+
+ @Override
+ public void dragOver(DropTargetDragEvent evt)
+ {
+ }
+
+ @Override
+ public void dropActionChanged(DropTargetDragEvent evt)
+ {
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param evt
+ * DOCUMENT ME!
+ */
+ @Override
+ public void drop(DropTargetDropEvent evt)
+ {
+ boolean success = true;
+ // JAL-1552 - acceptDrop required before getTransferable call for
+ // Java's Transferable for native dnd
+ evt.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
+ Transferable t = evt.getTransferable();
+ List<String> files = new ArrayList<>();
+ List<DataSourceType> protocols = new ArrayList<>();
+
+ try
+ {
+ Desktop.transferFromDropTarget(files, protocols, evt, t);
+ } catch (Exception e)
+ {
+ e.printStackTrace();
+ success = false;
+ }
+
+ if (files != null)
+ {
+ try
+ {
+ for (int i = 0; i < files.size(); i++)
+ {
+ String file = files.get(i).toString();
+ DataSourceType protocol = (protocols == null)
+ ? DataSourceType.FILE
+ : protocols.get(i);
+ FileFormatI format = null;
+
+ if (file.endsWith(".jar"))
+ {
+ format = FileFormat.Jalview;
+
+ }
+ else
+ {
+ format = new IdentifyFile().identify(file, protocol);
+ }
+
+ new FileLoader().LoadFile(file, protocol, format);
+
+ }
+ } catch (Exception ex)
+ {
+ success = false;
+ }
+ }
+ evt.dropComplete(success); // need this to ensure input focus is properly
+ // transfered to any new windows created
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param e
+ * DOCUMENT ME!
+ */
+ @Override
+ public void inputLocalFileMenuItem_actionPerformed(AlignViewport viewport)
+ {
+ String fileFormat = Cache.getProperty("DEFAULT_FILE_FORMAT");
+ JalviewFileChooser chooser = JalviewFileChooser
+ .forRead(Cache.getProperty("LAST_DIRECTORY"), fileFormat, BackupFiles.getEnabled());
+
+ chooser.setFileView(new JalviewFileView());
+ chooser.setDialogTitle(
+ MessageManager.getString("label.open_local_file"));
+ chooser.setToolTipText(MessageManager.getString("action.open"));
+
+ int value = chooser.showOpenDialog(this);
+
+ if (value == JalviewFileChooser.APPROVE_OPTION)
+ {
+ String choice = chooser.getSelectedFile().getPath();
+ Cache.setProperty("LAST_DIRECTORY",
+ chooser.getSelectedFile().getParent());
+
+ FileFormatI format = chooser.getSelectedFormat();
+
+ /*
+ * Call IdentifyFile to verify the file contains what its extension implies.
+ * Skip this step for dynamically added file formats, because
+ * IdentifyFile does not know how to recognise them.
+ */
+ if (FileFormats.getInstance().isIdentifiable(format))
+ {
+ try
+ {
+ format = new IdentifyFile().identify(choice, DataSourceType.FILE);
+ } catch (FileFormatException e)
+ {
+ // format = null; //??
+ }
+ }
+
+ if (viewport != null)
+ {
+ new FileLoader().LoadFile(viewport, choice, DataSourceType.FILE,
+ format);
+ }
+ else
+ {
+ new FileLoader().LoadFile(choice, DataSourceType.FILE, format);
+ }
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param e
+ * DOCUMENT ME!
+ */
+ @Override
+ public void inputURLMenuItem_actionPerformed(AlignViewport viewport)
+ {
+ // This construct allows us to have a wider textfield
+ // for viewing
+ JLabel label = new JLabel(
+ MessageManager.getString("label.input_file_url"));
+ final JComboBox history = new JComboBox();
+
+ JPanel panel = new JPanel(new GridLayout(2, 1));
+ panel.add(label);
+ panel.add(history);
+ history.setPreferredSize(new Dimension(400, 20));
+ history.setEditable(true);
+ history.addItem("http://www.");
+
+ String historyItems = jalview.bin.Cache.getProperty("RECENT_URL");
+
+ StringTokenizer st;
+
+ if (historyItems != null)
+ {
+ st = new StringTokenizer(historyItems, "\t");
+
+ while (st.hasMoreTokens())
+ {
+ history.addItem(st.nextElement());
+ }
+ }
+
+ int reply = JvOptionPane.showInternalConfirmDialog(desktop, panel,
+ MessageManager.getString("label.input_alignment_from_url"),
+ JvOptionPane.OK_CANCEL_OPTION);
+
+ if (reply != JvOptionPane.OK_OPTION)
+ {
+ return;
+ }
+
+ String url = history.getSelectedItem().toString();
+
+ if (url.toLowerCase().endsWith(".jar"))
+ {
+ if (viewport != null)
+ {
+ new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
+ FileFormat.Jalview);
+ }
+ else
+ {
+ new FileLoader().LoadFile(url, DataSourceType.URL,
+ FileFormat.Jalview);
+ }
+ }
+ else
+ {
+ FileFormatI format = null;
+ try
+ {
+ format = new IdentifyFile().identify(url, DataSourceType.URL);
+ } catch (FileFormatException e)
+ {
+ // TODO revise error handling, distinguish between
+ // URL not found and response not valid
+ }
+
+ if (format == null)
+ {
+ JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ MessageManager.formatMessage("label.couldnt_locate",
+ new Object[]
+ { url }),
+ MessageManager.getString("label.url_not_found"),
+ JvOptionPane.WARNING_MESSAGE);
+
+ return;
+ }
+
+ if (viewport != null)
+ {
+ new FileLoader().LoadFile(viewport, url, DataSourceType.URL,
+ format);
+ }
+ else
+ {
+ new FileLoader().LoadFile(url, DataSourceType.URL, format);
+ }
+ }
+ }
+
+ /**
+ * Opens the CutAndPaste window for the user to paste an alignment in to
+ *
+ * @param viewPanel
+ * - if not null, the pasted alignment is added to the current
+ * alignment; if null, to a new alignment window
+ */
+ @Override
+ public void inputTextboxMenuItem_actionPerformed(
+ AlignmentViewPanel viewPanel)
+ {
+ CutAndPasteTransfer cap = new CutAndPasteTransfer();
+ cap.setForInput(viewPanel);
+ Desktop.addInternalFrame(cap,
+ MessageManager.getString("label.cut_paste_alignmen_file"), true,
+ 600, 500);
+ }
+
+ /*
+ * Exit the program
+ */
+ @Override
+ public void quit()
+ {
+ Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
+ jalview.bin.Cache.setProperty("SCREENGEOMETRY_WIDTH",
+ screen.width + "");
+ jalview.bin.Cache.setProperty("SCREENGEOMETRY_HEIGHT",
+ screen.height + "");
+ storeLastKnownDimensions("", new Rectangle(getBounds().x, getBounds().y,
+ getWidth(), getHeight()));
+
+ if (jconsole != null)
+ {
+ storeLastKnownDimensions("JAVA_CONSOLE_", jconsole.getBounds());
+ jconsole.stopConsole();
+ }
+ if (jvnews != null)
+ {
+ storeLastKnownDimensions("JALVIEW_RSS_WINDOW_", jvnews.getBounds());
+
+ }
+ if (dialogExecutor != null)
+ {
+ dialogExecutor.shutdownNow();
+ }
+ closeAll_actionPerformed(null);
+
+ if (groovyConsole != null)
+ {
+ // suppress a possible repeat prompt to save script
+ groovyConsole.setDirty(false);
+ groovyConsole.exit();
+ }
+ System.exit(0);
+ }
+
+ private void storeLastKnownDimensions(String string, Rectangle jc)
+ {
+ jalview.bin.Cache.log.debug("Storing last known dimensions for "
+ + string + ": x:" + jc.x + " y:" + jc.y + " width:" + jc.width
+ + " height:" + jc.height);
+
+ jalview.bin.Cache.setProperty(string + "SCREEN_X", jc.x + "");
+ jalview.bin.Cache.setProperty(string + "SCREEN_Y", jc.y + "");
+ jalview.bin.Cache.setProperty(string + "SCREEN_WIDTH", jc.width + "");
+ jalview.bin.Cache.setProperty(string + "SCREEN_HEIGHT", jc.height + "");
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param e
+ * DOCUMENT ME!
+ */
+ @Override
+ public void aboutMenuItem_actionPerformed(ActionEvent e)
+ {
+ // StringBuffer message = getAboutMessage(false);
+ // JvOptionPane.showInternalMessageDialog(Desktop.desktop,
+ //
+ // message.toString(), "About Jalview", JvOptionPane.INFORMATION_MESSAGE);
+ new Thread(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ new SplashScreen(true);
+ }
+ }).start();
+ }
+
+ public StringBuffer getAboutMessage(boolean shortv)
+ {
+ StringBuffer message = new StringBuffer();
+ message.append("<html>");
+ if (shortv)
+ {
+ message.append("<h1><strong>Version: "
+ + jalview.bin.Cache.getProperty("VERSION")
+ + "</strong></h1>");
+ message.append("<strong>Built: <em>"
+ + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown")
+ + "</em> from " + jalview.bin.Cache.getBuildDetailsForSplash()
+ + "</strong>");
+
+ }
+ else
+ {
+
+ message.append("<strong>Version "
+ + jalview.bin.Cache.getProperty("VERSION")
+ + "; last updated: "
+ + jalview.bin.Cache.getDefault("BUILD_DATE", "unknown"));
+ }
+
+ if (jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking")
+ .equals("Checking"))
+ {
+ // JBP removed this message for 2.11: May be reinstated in future version
+ // message.append("<br>...Checking latest version...</br>");
+ }
+ else if (!jalview.bin.Cache.getDefault("LATEST_VERSION", "Checking")
+ .equals(jalview.bin.Cache.getProperty("VERSION")))
+ {
+ boolean red = false;
+ if (jalview.bin.Cache.getProperty("VERSION").toLowerCase()
+ .indexOf("automated build") == -1)
+ {
+ red = true;
+ // Displayed when code version and jnlp version do not match and code
+ // version is not a development build
+ message.append("<div style=\"color: #FF0000;font-style: bold;\">");
+ }
+
+ message.append("<br>!! Version "
+ + jalview.bin.Cache.getDefault("LATEST_VERSION",
+ "..Checking..")
+ + " is available for download from "
+ + jalview.bin.Cache.getDefault("www.jalview.org",
+ "http://www.jalview.org")
+ + " !!");
+ if (red)
+ {
+ message.append("</div>");
+ }
+ }
+ message.append("<br>Authors: " + jalview.bin.Cache.getDefault(
+ "AUTHORFNAMES",
+ "The Jalview Authors (See AUTHORS file for current list)")
+ + "<br><br>Development managed by The Barton Group, University of Dundee, Scotland, UK.<br>"
+ + "<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"
+ + "<br><br>If you use Jalview, please cite:"
+ + "<br>Waterhouse, A.M., Procter, J.B., Martin, D.M.A, Clamp, M. and Barton, G. J. (2009)"
+ + "<br>Jalview Version 2 - a multiple sequence alignment editor and analysis workbench"
+ + "<br>Bioinformatics doi: 10.1093/bioinformatics/btp033"
+ + "</html>");
+ return message;
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param e
+ * DOCUMENT ME!
+ */
+ @Override
+ public void documentationMenuItem_actionPerformed(ActionEvent e)
+ {
+ try
+ {
+ Help.showHelpWindow();
+ } catch (Exception ex)
+ {
+ }
+ }
+
+ @Override
+ public void closeAll_actionPerformed(ActionEvent e)
+ {
+ // TODO show a progress bar while closing?
+ JInternalFrame[] frames = desktop.getAllFrames();
+ for (int i = 0; i < frames.length; i++)
+ {
+ try
+ {
+ frames[i].setClosed(true);
+ } catch (java.beans.PropertyVetoException ex)
+ {
+ }
+ }
+ Jalview.setCurrentAlignFrame(null);
+ System.out.println("ALL CLOSED");
+
+ /*
+ * reset state of singleton objects as appropriate (clear down session state
+ * when all windows are closed)
+ */
+ StructureSelectionManager ssm = StructureSelectionManager
+ .getStructureSelectionManager(this);
+ if (ssm != null)
+ {
+ ssm.resetAll();
+ }
+ }
+
+ @Override
+ public void raiseRelated_actionPerformed(ActionEvent e)
+ {
+ reorderAssociatedWindows(false, false);
+ }
+
+ @Override
+ public void minimizeAssociated_actionPerformed(ActionEvent e)
+ {
+ reorderAssociatedWindows(true, false);
+ }
+
+ void closeAssociatedWindows()
+ {
+ reorderAssociatedWindows(false, true);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @seejalview.jbgui.GDesktop#garbageCollect_actionPerformed(java.awt.event.
+ * ActionEvent)
+ */
+ @Override
+ protected void garbageCollect_actionPerformed(ActionEvent e)
+ {
+ // We simply collect the garbage
+ jalview.bin.Cache.log.debug("Collecting garbage...");
+ System.gc();
+ jalview.bin.Cache.log.debug("Finished garbage collection.");
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * jalview.jbgui.GDesktop#showMemusage_actionPerformed(java.awt.event.ActionEvent
+ * )
+ */
+ @Override
+ protected void showMemusage_actionPerformed(ActionEvent e)
+ {
+ desktop.showMemoryUsage(showMemusage.isSelected());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * jalview.jbgui.GDesktop#showConsole_actionPerformed(java.awt.event.ActionEvent
+ * )
+ */
+ @Override
+ protected void showConsole_actionPerformed(ActionEvent e)
+ {
+ showConsole(showConsole.isSelected());
+ }
+
+ Console jconsole = null;
+
+ /**
+ * control whether the java console is visible or not
+ *
+ * @param selected
+ */
+ void showConsole(boolean selected)
+ {
+ showConsole.setSelected(selected);
+ // TODO: decide if we should update properties file
+ Cache.setProperty("SHOW_JAVA_CONSOLE",
+ Boolean.valueOf(selected).toString());
+ jconsole.setVisible(selected);
+ }
+
+ void reorderAssociatedWindows(boolean minimize, boolean close)
+ {
+ JInternalFrame[] frames = desktop.getAllFrames();
+ if (frames == null || frames.length < 1)
+ {
+ return;
+ }
+
+ AlignmentViewport source = null, target = null;
+ if (frames[0] instanceof AlignFrame)
+ {
+ source = ((AlignFrame) frames[0]).getCurrentView();
+ }
+ else if (frames[0] instanceof TreePanel)
+ {
+ source = ((TreePanel) frames[0]).getViewPort();
+ }
+ else if (frames[0] instanceof PCAPanel)
+ {
+ source = ((PCAPanel) frames[0]).av;
+ }
+ else if (frames[0].getContentPane() instanceof PairwiseAlignPanel)
+ {
+ source = ((PairwiseAlignPanel) frames[0].getContentPane()).av;
+ }
+
+ if (source != null)
+ {
+ for (int i = 0; i < frames.length; i++)
+ {
+ target = null;
+ if (frames[i] == null)
+ {
+ continue;
+ }
+ if (frames[i] instanceof AlignFrame)
+ {
+ target = ((AlignFrame) frames[i]).getCurrentView();
+ }
+ else if (frames[i] instanceof TreePanel)
+ {
+ target = ((TreePanel) frames[i]).getViewPort();
+ }
+ else if (frames[i] instanceof PCAPanel)
+ {
+ target = ((PCAPanel) frames[i]).av;
+ }
+ else if (frames[i].getContentPane() instanceof PairwiseAlignPanel)
+ {
+ target = ((PairwiseAlignPanel) frames[i].getContentPane()).av;
+ }
+
+ if (source == target)
+ {
+ try
+ {
+ if (close)
+ {
+ frames[i].setClosed(true);
+ }
+ else
+ {
+ frames[i].setIcon(minimize);
+ if (!minimize)
+ {
+ frames[i].toFront();
+ }
+ }
+
+ } catch (java.beans.PropertyVetoException ex)
+ {
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * DOCUMENT ME!
+ *
+ * @param e
+ * DOCUMENT ME!
+ */
+ @Override
+ protected void preferences_actionPerformed(ActionEvent e)
+ {
+ new Preferences();
+ }
+
+ /**
+ * Shows a file chooser dialog and writes out the current session as a Jalview
+ * project file
+ */
+ @Override
+ public void saveState_actionPerformed()
+ {
+ saveState_actionPerformed(false);
+ }
+
+ public void saveState_actionPerformed(boolean saveAs)
+ {
+ java.io.File projectFile = getProjectFile();
+ // autoSave indicates we already have a file and don't need to ask
+ boolean autoSave = projectFile != null && !saveAs
+ && BackupFiles.getEnabled();
+
+ // System.out.println("autoSave="+autoSave+", projectFile='"+projectFile+"',
+ // saveAs="+saveAs+", Backups
+ // "+(BackupFiles.getEnabled()?"enabled":"disabled"));
+
+ boolean approveSave = false;
+ if (!autoSave)
+ {
+ JalviewFileChooser chooser = new JalviewFileChooser("jvp",
+ "Jalview Project");
+
+ chooser.setFileView(new JalviewFileView());
+ chooser.setDialogTitle(MessageManager.getString("label.save_state"));
+
+ int value = chooser.showSaveDialog(this);
+
+ if (value == JalviewFileChooser.APPROVE_OPTION)
+ {
+ projectFile = chooser.getSelectedFile();
+ setProjectFile(projectFile);
+ approveSave = true;
+ }
+ }
+
+ if (approveSave || autoSave)
+ {
+ final Desktop me = this;
+ final java.io.File chosenFile = projectFile;
+ new Thread(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ // TODO: refactor to Jalview desktop session controller action.
+ setProgressBar(MessageManager.formatMessage(
+ "label.saving_jalview_project", new Object[]
+ { chosenFile.getName() }), chosenFile.hashCode());
+ jalview.bin.Cache.setProperty("LAST_DIRECTORY",
+ chosenFile.getParent());
+ // TODO catch and handle errors for savestate
+ // TODO prevent user from messing with the Desktop whilst we're saving
+ try
+ {
+ BackupFiles backupfiles = new BackupFiles(chosenFile);
+
+ new Jalview2XML().saveState(backupfiles.getTempFile());
+
+ backupfiles.setWriteSuccess(true);
+ backupfiles.rollBackupsAndRenameTempFile();
+ } catch (OutOfMemoryError oom)
+ {
+ new OOMWarning("Whilst saving current state to "
+ + chosenFile.getName(), oom);
+ } catch (Exception ex)
+ {
+ Cache.log.error("Problems whilst trying to save to "
+ + chosenFile.getName(), ex);
+ JvOptionPane.showMessageDialog(me,
+ MessageManager.formatMessage(
+ "label.error_whilst_saving_current_state_to",
+ new Object[]
+ { chosenFile.getName() }),
+ MessageManager.getString("label.couldnt_save_project"),
+ JvOptionPane.WARNING_MESSAGE);
+ }
+ setProgressBar(null, chosenFile.hashCode());
+ }
+ }).start();
+ }
+ }
+
+ @Override
+ public void saveAsState_actionPerformed(ActionEvent e)
+ {
+ saveState_actionPerformed(true);
+ }
+
+ private void setProjectFile(File choice)
+ {
+ this.projectFile = choice;
+ }
+
+ public File getProjectFile()
+ {
+ return this.projectFile;
+ }
+
+ /**
+ * Shows a file chooser dialog and tries to read in the selected file as a
+ * Jalview project
+ */
+ @Override
+ public void loadState_actionPerformed()
+ {
+ final String[] suffix = new String[] { "jvp", "jar" };
+ final String[] desc = new String[] { "Jalview Project",
+ "Jalview Project (old)" };
+ JalviewFileChooser chooser = new JalviewFileChooser(
+ Cache.getProperty("LAST_DIRECTORY"), suffix, desc,
+ "Jalview Project", true, BackupFiles.getEnabled()); // last two booleans: allFiles,
+ // allowBackupFiles
+ chooser.setFileView(new JalviewFileView());
+ chooser.setDialogTitle(MessageManager.getString("label.restore_state"));
+
+ int value = chooser.showOpenDialog(this);
+
+ if (value == JalviewFileChooser.APPROVE_OPTION)
+ {
+ final File selectedFile = chooser.getSelectedFile();
+ setProjectFile(selectedFile);
+ final String choice = selectedFile.getAbsolutePath();
+ Cache.setProperty("LAST_DIRECTORY", selectedFile.getParent());
+ new Thread(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ setProgressBar(MessageManager.formatMessage(
+ "label.loading_jalview_project", new Object[]
+ { choice }), choice.hashCode());
+ try
+ {
+ new Jalview2XML().loadJalviewAlign(choice);
+ } catch (OutOfMemoryError oom)
+ {
+ new OOMWarning("Whilst loading project from " + choice, oom);
+ } catch (Exception ex)
+ {
+ Cache.log.error(
+ "Problems whilst loading project from " + choice, ex);
+ JvOptionPane.showMessageDialog(Desktop.desktop,
+ MessageManager.formatMessage(
+ "label.error_whilst_loading_project_from",
+ new Object[]
+ { choice }),
+ MessageManager.getString("label.couldnt_load_project"),
+ JvOptionPane.WARNING_MESSAGE);
+ }
+ setProgressBar(null, choice.hashCode());
+ }
+ }).start();
+ }
+ }
+
+ @Override
+ public void inputSequence_actionPerformed(ActionEvent e)
+ {
+ new SequenceFetcher(this);
+ }
+
+ JPanel progressPanel;
+
+ ArrayList<JPanel> fileLoadingPanels = new ArrayList<>();
+
+ public void startLoading(final String fileName)
+ {
+ if (fileLoadingCount == 0)
+ {
+ fileLoadingPanels.add(addProgressPanel(MessageManager
+ .formatMessage("label.loading_file", new Object[]
+ { fileName })));
+ }
+ fileLoadingCount++;
+ }
+
+ private JPanel addProgressPanel(String string)
+ {
+ if (progressPanel == null)
+ {
+ progressPanel = new JPanel(new GridLayout(1, 1));
+ totalProgressCount = 0;
+ instance.getContentPane().add(progressPanel, BorderLayout.SOUTH);
+ }
+ JPanel thisprogress = new JPanel(new BorderLayout(10, 5));
+ JProgressBar progressBar = new JProgressBar();
+ progressBar.setIndeterminate(true);
+
+ thisprogress.add(new JLabel(string), BorderLayout.WEST);
+
+ thisprogress.add(progressBar, BorderLayout.CENTER);
+ progressPanel.add(thisprogress);
+ ((GridLayout) progressPanel.getLayout()).setRows(
+ ((GridLayout) progressPanel.getLayout()).getRows() + 1);
+ ++totalProgressCount;
+ instance.validate();
+ return thisprogress;
+ }
+
+ int totalProgressCount = 0;
+
+ private void removeProgressPanel(JPanel progbar)
+ {
+ if (progressPanel != null)
+ {
+ synchronized (progressPanel)
+ {
+ progressPanel.remove(progbar);
+ GridLayout gl = (GridLayout) progressPanel.getLayout();
+ gl.setRows(gl.getRows() - 1);
+ if (--totalProgressCount < 1)
+ {
+ this.getContentPane().remove(progressPanel);
+ progressPanel = null;
+ }
+ }
+ }
+ validate();
+ }
+
+ public void stopLoading()
+ {
+ fileLoadingCount--;
+ if (fileLoadingCount < 1)
+ {
+ while (fileLoadingPanels.size() > 0)
+ {
+ removeProgressPanel(fileLoadingPanels.remove(0));
+ }
+ fileLoadingPanels.clear();
+ fileLoadingCount = 0;
+ }
+ validate();
+ }
+
+ public static int getViewCount(String alignmentId)
+ {
+ AlignmentViewport[] aps = getViewports(alignmentId);
+ return (aps == null) ? 0 : aps.length;
+ }
+
+ /**
+ *
+ * @param alignmentId
+ * - if null, all sets are returned
+ * @return all AlignmentPanels concerning the alignmentId sequence set
+ */
+ public static AlignmentPanel[] getAlignmentPanels(String alignmentId)
+ {
+ if (Desktop.desktop == null)
+ {
+ // no frames created and in headless mode
+ // TODO: verify that frames are recoverable when in headless mode
+ return null;
+ }
+ List<AlignmentPanel> aps = new ArrayList<>();
+ AlignFrame[] frames = getAlignFrames();
+ if (frames == null)
+ {
+ return null;
+ }
+ for (AlignFrame af : frames)
+ {
+ for (AlignmentPanel ap : af.alignPanels)
+ {
+ if (alignmentId == null
+ || alignmentId.equals(ap.av.getSequenceSetId()))
+ {
+ aps.add(ap);
+ }
+ }
+ }
+ if (aps.size() == 0)
+ {
+ return null;
+ }
+ AlignmentPanel[] vap = aps.toArray(new AlignmentPanel[aps.size()]);
+ return vap;
+ }
+
+ /**
+ * get all the viewports on an alignment.
+ *
+ * @param sequenceSetId
+ * unique alignment id (may be null - all viewports returned in that
+ * case)
+ * @return all viewports on the alignment bound to sequenceSetId
+ */
+ public static AlignmentViewport[] getViewports(String sequenceSetId)
+ {
+ List<AlignmentViewport> viewp = new ArrayList<>();
+ if (desktop != null)
+ {
+ AlignFrame[] frames = Desktop.getAlignFrames();
+
+ for (AlignFrame afr : frames)
+ {
+ if (sequenceSetId == null || afr.getViewport().getSequenceSetId()
+ .equals(sequenceSetId))
+ {
+ if (afr.alignPanels != null)
+ {
+ for (AlignmentPanel ap : afr.alignPanels)
+ {
+ if (sequenceSetId == null
+ || sequenceSetId.equals(ap.av.getSequenceSetId()))
+ {
+ viewp.add(ap.av);
+ }
+ }
+ }
+ else
+ {
+ viewp.add(afr.getViewport());
+ }
+ }
+ }
+ if (viewp.size() > 0)
+ {
+ return viewp.toArray(new AlignmentViewport[viewp.size()]);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Explode the views in the given frame into separate AlignFrame
+ *
+ * @param af
+ */
+ public static void explodeViews(AlignFrame af)
+ {
+ int size = af.alignPanels.size();
+ if (size < 2)
+ {
+ return;
+ }
+
+ for (int i = 0; i < size; i++)
+ {
+ AlignmentPanel ap = af.alignPanels.get(i);
+ AlignFrame newaf = new AlignFrame(ap);
+
+ /*
+ * Restore the view's last exploded frame geometry if known. Multiple
+ * views from one exploded frame share and restore the same (frame)
+ * position and size.
+ */
+ Rectangle geometry = ap.av.getExplodedGeometry();
+ if (geometry != null)
+ {
+ newaf.setBounds(geometry);
+ }
+
+ ap.av.setGatherViewsHere(false);
+
+ addInternalFrame(newaf, af.getTitle(), AlignFrame.DEFAULT_WIDTH,
+ AlignFrame.DEFAULT_HEIGHT);
+ }
+
+ af.alignPanels.clear();
+ af.closeMenuItem_actionPerformed(true);
+
+ }
+
+ /**
+ * Gather expanded views (separate AlignFrame's) with the same sequence set
+ * identifier back in to this frame as additional views, and close the
+ * expanded views. Note the expanded frames may themselves have multiple
+ * views. We take the lot.
+ *
+ * @param source
+ */
+ public void gatherViews(AlignFrame source)
+ {
+ source.viewport.setGatherViewsHere(true);
+ source.viewport.setExplodedGeometry(source.getBounds());
+ JInternalFrame[] frames = desktop.getAllFrames();
+ String viewId = source.viewport.getSequenceSetId();
+
+ for (int t = 0; t < frames.length; t++)
+ {
+ if (frames[t] instanceof AlignFrame && frames[t] != source)
+ {
+ AlignFrame af = (AlignFrame) frames[t];
+ boolean gatherThis = false;
+ for (int a = 0; a < af.alignPanels.size(); a++)
+ {
+ AlignmentPanel ap = af.alignPanels.get(a);
+ if (viewId.equals(ap.av.getSequenceSetId()))
+ {
+ gatherThis = true;
+ ap.av.setGatherViewsHere(false);
+ ap.av.setExplodedGeometry(af.getBounds());
+ source.addAlignmentPanel(ap, false);
+ }
+ }
+
+ if (gatherThis)
+ {
+ af.alignPanels.clear();
+ af.closeMenuItem_actionPerformed(true);
+ }
+ }
+ }
+
+ }
+
+ public JInternalFrame[] getAllFrames()
+ {
+ return desktop.getAllFrames();
+ }
+
+ /**
+ * Checks the given url to see if it gives a response indicating that the user
+ * should be informed of a new questionnaire.
+ *
+ * @param url
+ */
+ public void checkForQuestionnaire(String url)
+ {
+ UserQuestionnaireCheck jvq = new UserQuestionnaireCheck(url);
+ // javax.swing.SwingUtilities.invokeLater(jvq);
+ new Thread(jvq).start();
+ }
+
+ public void checkURLLinks()
+ {
+ // Thread off the URL link checker
+ addDialogThread(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ if (Cache.getDefault("CHECKURLLINKS", true))
+ {
+ // check what the actual links are - if it's just the default don't
+ // bother with the warning
+ List<String> links = Preferences.sequenceUrlLinks
+ .getLinksForMenu();
+
+ // only need to check links if there is one with a
+ // SEQUENCE_ID which is not the default EMBL_EBI link
+ ListIterator<String> li = links.listIterator();
+ boolean check = false;
+ List<JLabel> urls = new ArrayList<>();
+ while (li.hasNext())
+ {
+ String link = li.next();
+ if (link.contains(jalview.util.UrlConstants.SEQUENCE_ID)
+ && !UrlConstants.isDefaultString(link))
+ {
+ check = true;
+ int barPos = link.indexOf("|");
+ String urlMsg = barPos == -1 ? link
+ : link.substring(0, barPos) + ": "
+ + link.substring(barPos + 1);
+ urls.add(new JLabel(urlMsg));
+ }
+ }
+ if (!check)
+ {
+ return;
+ }
+
+ // ask user to check in case URL links use old style tokens
+ // ($SEQUENCE_ID$ for sequence id _or_ accession id)
+ JPanel msgPanel = new JPanel();
+ msgPanel.setLayout(new BoxLayout(msgPanel, BoxLayout.PAGE_AXIS));
+ msgPanel.add(Box.createVerticalGlue());
+ JLabel msg = new JLabel(MessageManager
+ .getString("label.SEQUENCE_ID_for_DB_ACCESSION1"));
+ JLabel msg2 = new JLabel(MessageManager
+ .getString("label.SEQUENCE_ID_for_DB_ACCESSION2"));
+ msgPanel.add(msg);
+ for (JLabel url : urls)
+ {
+ msgPanel.add(url);
+ }
+ msgPanel.add(msg2);
+
+ final JCheckBox jcb = new JCheckBox(
+ MessageManager.getString("label.do_not_display_again"));
+ jcb.addActionListener(new ActionListener()
+ {
+ @Override
+ public void actionPerformed(ActionEvent e)
+ {
+ // update Cache settings for "don't show this again"
+ boolean showWarningAgain = !jcb.isSelected();
+ Cache.setProperty("CHECKURLLINKS",
+ Boolean.valueOf(showWarningAgain).toString());
+ }
+ });
+ msgPanel.add(jcb);
+
+ JvOptionPane.showMessageDialog(Desktop.desktop, msgPanel,
+ MessageManager
+ .getString("label.SEQUENCE_ID_no_longer_used"),
+ JvOptionPane.WARNING_MESSAGE);
+ }
+ }
+ });
+ }
+
+ /**
+ * Proxy class for JDesktopPane which optionally displays the current memory
+ * usage and highlights the desktop area with a red bar if free memory runs
+ * low.
+ *
+ * @author AMW
+ */
+ public class MyDesktopPane extends JDesktopPane implements Runnable
+ {
+
+ private static final float ONE_MB = 1048576f;
+
+ boolean showMemoryUsage = false;
+
+ Runtime runtime;
+
+ java.text.NumberFormat df;
+
+ float maxMemory, allocatedMemory, freeMemory, totalFreeMemory,
+ percentUsage;
+
+ public MyDesktopPane(boolean showMemoryUsage)
+ {
+ showMemoryUsage(showMemoryUsage);
+ }
+
+ public void showMemoryUsage(boolean showMemory)
+ {
+ this.showMemoryUsage = showMemory;
+ if (showMemory)
+ {
+ Thread worker = new Thread(this);
+ worker.start();
+ }
+ repaint();
+ }
+
+ public boolean isShowMemoryUsage()
+ {
+ return showMemoryUsage;
+ }
+
+ @Override
+ public void run()
+ {
+ df = java.text.NumberFormat.getNumberInstance();
+ df.setMaximumFractionDigits(2);
+ runtime = Runtime.getRuntime();
+
+ while (showMemoryUsage)
+ {
+ try
+ {
+ maxMemory = runtime.maxMemory() / ONE_MB;
+ allocatedMemory = runtime.totalMemory() / ONE_MB;
+ freeMemory = runtime.freeMemory() / ONE_MB;
+ totalFreeMemory = freeMemory + (maxMemory - allocatedMemory);
+
+ percentUsage = (totalFreeMemory / maxMemory) * 100;
+
+ // if (percentUsage < 20)
+ {
+ // border1 = BorderFactory.createMatteBorder(12, 12, 12, 12,
+ // Color.red);
+ // instance.set.setBorder(border1);
+ }
+ repaint();
+ // sleep after showing usage
+ Thread.sleep(3000);
+ } catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void paintComponent(Graphics g)
+ {
+ if (showMemoryUsage && g != null && df != null)
+ {
+ if (percentUsage < 20)
+ {
+ g.setColor(Color.red);
+ }
+ FontMetrics fm = g.getFontMetrics();
+ if (fm != null)
+ {
+ g.drawString(MessageManager.formatMessage("label.memory_stats",
+ new Object[]
+ { df.format(totalFreeMemory), df.format(maxMemory),
+ df.format(percentUsage) }),
+ 10, getHeight() - fm.getHeight());
+ }
+ }
+ }
+ }
+
+ /**
+ * Accessor method to quickly get all the AlignmentFrames loaded.
+ *
+ * @return an array of AlignFrame, or null if none found
+ */
+ public static AlignFrame[] getAlignFrames()
+ {
+ if (Jalview.isHeadlessMode())
+ {
+ // Desktop.desktop is null in headless mode
+ return new AlignFrame[] { Jalview.currentAlignFrame };
+ }
+
+ JInternalFrame[] frames = Desktop.desktop.getAllFrames();
+
+ if (frames == null)
+ {
+ return null;
+ }
+ List<AlignFrame> avp = new ArrayList<>();
+ // REVERSE ORDER
+ for (int i = frames.length - 1; i > -1; i--)
+ {
+ if (frames[i] instanceof AlignFrame)
+ {
+ avp.add((AlignFrame) frames[i]);
+ }
+ else if (frames[i] instanceof SplitFrame)
+ {
+ /*
+ * Also check for a split frame containing an AlignFrame
+ */
+ GSplitFrame sf = (GSplitFrame) frames[i];
+ if (sf.getTopFrame() instanceof AlignFrame)
+ {
+ avp.add((AlignFrame) sf.getTopFrame());
+ }
+ if (sf.getBottomFrame() instanceof AlignFrame)
+ {
+ avp.add((AlignFrame) sf.getBottomFrame());
+ }
+ }
+ }
+ if (avp.size() == 0)
+ {
+ return null;
+ }
+ AlignFrame afs[] = avp.toArray(new AlignFrame[avp.size()]);
+ return afs;
+ }
+
+ /**
+ * Returns an array of any AppJmol frames in the Desktop (or null if none).
+ *
+ * @return
+ */
+ public GStructureViewer[] getJmols()
+ {
+ JInternalFrame[] frames = Desktop.desktop.getAllFrames();
+
+ if (frames == null)
+ {
+ return null;
+ }
+ List<GStructureViewer> avp = new ArrayList<>();
+ // REVERSE ORDER
+ for (int i = frames.length - 1; i > -1; i--)
+ {
+ if (frames[i] instanceof AppJmol)
+ {
+ GStructureViewer af = (GStructureViewer) frames[i];
+ avp.add(af);
+ }
+ }
+ if (avp.size() == 0)
+ {
+ return null;
+ }
+ GStructureViewer afs[] = avp.toArray(new GStructureViewer[avp.size()]);
+ return afs;
+ }
+
+ /**
+ * Add Groovy Support to Jalview
+ */
+ @Override
+ public void groovyShell_actionPerformed()
+ {
+ try
+ {
+ openGroovyConsole();
+ } catch (Exception ex)
+ {
+ jalview.bin.Cache.log.error("Groovy Shell Creation failed.", ex);
+ JvOptionPane.showInternalMessageDialog(Desktop.desktop,