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 jalview.bin.Cache;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.SequenceI;
27 import jalview.gui.StructureViewer.ViewerType;
28 import jalview.structures.models.AAStructureBindingModel;
29 import jalview.util.BrowserLauncher;
30 import jalview.util.MessageManager;
31 import jalview.util.Platform;
32 import jalview.ws.dbsources.Pdb;
34 import java.awt.BorderLayout;
35 import java.awt.Color;
36 import java.awt.Dimension;
38 import java.awt.Graphics;
39 import java.awt.Rectangle;
40 import java.awt.event.ActionEvent;
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.Vector;
46 import javax.swing.JCheckBoxMenuItem;
47 import javax.swing.JInternalFrame;
48 import javax.swing.JPanel;
49 import javax.swing.JSplitPane;
50 import javax.swing.SwingUtilities;
51 import javax.swing.event.InternalFrameAdapter;
52 import javax.swing.event.InternalFrameEvent;
54 public class AppJmol extends StructureViewerBase
56 // ms to wait for Jmol to load files
57 private static final int JMOL_LOAD_TIMEOUT = 20000;
59 private static final String SPACE = " ";
61 private static final String BACKSLASH = "\"";
69 RenderPanel renderPanel;
78 * - add the alignment panel to the list used for colouring these
81 * - add the alignment panel to the list used for aligning these
83 * @param leaveColouringToJmol
84 * - do not update the colours from any other source. Jmol is
90 public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
91 AlignmentPanel ap, boolean usetoColour, boolean useToAlign,
92 boolean leaveColouringToJmol, String loadStatus,
93 Rectangle bounds, String viewid)
95 PDBEntry[] pdbentrys = new PDBEntry[files.length];
96 for (int i = 0; i < pdbentrys.length; i++)
98 // PDBEntry pdbentry = new PDBEntry(files[i], ids[i]);
99 PDBEntry pdbentry = new PDBEntry(ids[i], null, PDBEntry.Type.PDB,
101 pdbentrys[i] = pdbentry;
103 // / TODO: check if protocol is needed to be set, and if chains are
105 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
106 pdbentrys, seqs, null);
108 jmb.setLoadingFromArchive(true);
109 addAlignmentPanel(ap);
112 useAlignmentPanelForSuperposition(ap);
115 if (leaveColouringToJmol || !usetoColour)
117 jmb.setColourBySequence(false);
118 seqColour.setSelected(false);
119 viewerColour.setSelected(true);
121 else if (usetoColour)
123 useAlignmentPanelForColourbyseq(ap);
124 jmb.setColourBySequence(true);
125 seqColour.setSelected(true);
126 viewerColour.setSelected(false);
128 this.setBounds(bounds);
130 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
131 // bounds.width,bounds.height);
133 this.addInternalFrameListener(new InternalFrameAdapter()
136 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
141 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
145 protected void initMenus()
149 viewerActionMenu.setText(MessageManager.getString("label.jmol"));
152 .setText(MessageManager.getString("label.colour_with_jmol"));
153 viewerColour.setToolTipText(MessageManager
154 .getString("label.let_jmol_manage_structure_colours"));
157 IProgressIndicator progressBar = null;
160 * add a single PDB structure to a new or existing Jmol view
167 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
168 final AlignmentPanel ap)
170 progressBar = ap.alignFrame;
171 String pdbId = pdbentry.getId();
174 * If the PDB file is already loaded, the user may just choose to add to an
175 * existing viewer (or cancel)
177 if (addAlreadyLoadedFile(seq, chains, ap, pdbId))
183 * Check if there are other Jmol views involving this alignment and prompt
184 * user about adding this molecule to one of them
186 if (addToExistingViewer(pdbentry, seq, chains, ap, pdbId))
192 * If the options above are declined or do not apply, open a new viewer
194 openNewJmol(ap, new PDBEntry[] { pdbentry }, new SequenceI[][] { seq });
197 private void openNewJmol(AlignmentPanel ap, PDBEntry[] pdbentrys,
200 progressBar = ap.alignFrame;
201 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
202 pdbentrys, seqs, null);
203 addAlignmentPanel(ap);
204 useAlignmentPanelForColourbyseq(ap);
206 if (pdbentrys.length > 1)
208 alignAddedStructures = true;
209 useAlignmentPanelForSuperposition(ap);
211 jmb.setColourBySequence(true);
212 setSize(400, 400); // probably should be a configurable/dynamic default here
214 addingStructures = false;
215 worker = new Thread(this);
218 this.addInternalFrameListener(new InternalFrameAdapter()
221 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
230 * create a new Jmol containing several structures superimposed using the
237 public AppJmol(AlignmentPanel ap, PDBEntry[] pe, SequenceI[][] seqs)
239 openNewJmol(ap, pe, seqs);
243 * Returns a list of any Jmol viewers. The list is restricted to those linked
244 * to the given alignment panel if it is not null.
247 protected List<StructureViewerBase> getViewersFor(AlignmentPanel apanel)
249 List<StructureViewerBase> result = new ArrayList<StructureViewerBase>();
250 JInternalFrame[] frames = Desktop.instance.getAllFrames();
252 for (JInternalFrame frame : frames)
254 if (frame instanceof AppJmol)
257 || ((StructureViewerBase) frame).isLinkedWith(apanel))
259 result.add((StructureViewerBase) frame);
266 void initJmol(String command)
268 jmb.setFinishedInit(false);
269 renderPanel = new RenderPanel();
270 // TODO: consider waiting until the structure/view is fully loaded before
272 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
273 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
274 getBounds().width, getBounds().height);
275 if (scriptWindow == null)
277 BorderLayout bl = new BorderLayout();
280 scriptWindow = new JPanel(bl);
281 scriptWindow.setVisible(false);
284 jmb.allocateViewer(renderPanel, true, "", null, null, "",
286 // jmb.newJmolPopup("Jmol");
291 jmb.evalStateCommand(command);
292 jmb.evalStateCommand("set hoverDelay=0.1");
293 jmb.setFinishedInit(true);
298 boolean allChainsSelected = false;
301 void showSelectedChains()
303 Vector<String> toshow = new Vector<String>();
304 for (int i = 0; i < chainMenu.getItemCount(); i++)
306 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
308 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
309 if (item.isSelected())
311 toshow.addElement(item.getText());
315 jmb.centerViewer(toshow);
319 public void closeViewer(boolean closeExternalViewer)
321 // Jmol does not use an external viewer
326 setAlignmentPanel(null);
330 // TODO: check for memory leaks where instance isn't finalised because jmb
331 // holds a reference to the window
341 List<String> files = fetchPdbFiles();
342 if (files.size() > 0)
344 showFilesInViewer(files);
354 * Either adds the given files to a structure viewer or opens a new viewer to
358 * list of absolute paths to structure files
360 void showFilesInViewer(List<String> files)
362 long lastnotify = jmb.getLoadNotifiesHandled();
363 StringBuilder fileList = new StringBuilder();
364 for (String s : files)
366 fileList.append(SPACE).append(BACKSLASH)
367 .append(Platform.escapeString(s)).append(BACKSLASH);
369 String filesString = fileList.toString();
371 if (!addingStructures)
375 initJmol("load FILES " + filesString);
376 } catch (OutOfMemoryError oomerror)
378 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
379 Cache.log.debug("File locations are " + filesString);
380 } catch (Exception ex)
382 Cache.log.error("Couldn't open Jmol viewer!", ex);
387 StringBuilder cmd = new StringBuilder();
388 cmd.append("loadingJalviewdata=true\nload APPEND ");
389 cmd.append(filesString);
390 cmd.append("\nloadingJalviewdata=null");
391 final String command = cmd.toString();
392 lastnotify = jmb.getLoadNotifiesHandled();
396 jmb.evalStateCommand(command);
397 } catch (OutOfMemoryError oomerror)
399 new OOMWarning("When trying to add structures to the Jmol viewer!",
401 Cache.log.debug("File locations are " + filesString);
402 } catch (Exception ex)
404 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
408 // need to wait around until script has finished
409 int waitMax = JMOL_LOAD_TIMEOUT;
412 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
413 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null && jmb
414 .getStructureFiles().length == files.size()))
418 Cache.log.debug("Waiting around for jmb notify.");
419 Thread.sleep(waitFor);
420 waitTotal += waitFor;
421 } catch (Exception e)
424 if (waitTotal > waitMax)
427 .println("Timed out waiting for Jmol to load files after "
429 // System.err.println("finished: " + jmb.isFinishedInit()
430 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
431 // + "; files: " + files.toString());
432 jmb.getStructureFiles();
437 // refresh the sequence colours for the new structure(s)
438 for (AlignmentPanel ap : _colourwith)
440 jmb.updateColours(ap);
442 // do superposition if asked to
443 if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
445 alignAddedStructures();
447 addingStructures = false;
451 * Queues a thread to align structures with Jalview alignments
453 void alignAddedStructures()
455 javax.swing.SwingUtilities.invokeLater(new Runnable()
460 if (jmb.viewer.isScriptExecuting())
462 SwingUtilities.invokeLater(this);
466 } catch (InterruptedException q)
473 alignStructs_withAllAlignPanels();
477 alignAddedStructures = false;
481 * Retrieves and saves as file any modelled PDB entries for which we do not
482 * already have a file saved. Returns a list of absolute paths to structure
483 * files which were either retrieved, or already stored but not modelled in
484 * the structure viewer (i.e. files to add to the viewer display).
488 List<String> fetchPdbFiles()
490 // todo - record which pdbids were successfully imported.
491 StringBuilder errormsgs = new StringBuilder();
493 List<String> files = new ArrayList<String>();
497 String[] filesInViewer = jmb.getStructureFiles();
498 // TODO: replace with reference fetching/transfer code (validate PDBentry
500 Pdb pdbclient = new Pdb();
501 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
503 String file = jmb.getPdbEntry(pi).getFile();
506 // retrieve the pdb and store it locally
507 AlignmentI pdbseq = null;
508 pdbid = jmb.getPdbEntry(pi).getId();
509 long hdl = pdbid.hashCode() - System.currentTimeMillis();
510 if (progressBar != null)
512 progressBar.setProgressBar(MessageManager.formatMessage(
513 "status.fetching_pdb", new String[] { pdbid }), hdl);
517 pdbseq = pdbclient.getSequenceRecords(pdbid);
518 } catch (OutOfMemoryError oomerror)
520 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
521 } catch (Exception ex)
523 ex.printStackTrace();
524 errormsgs.append("'").append(pdbid).append("'");
527 if (progressBar != null)
529 progressBar.setProgressBar(
530 MessageManager.getString("label.state_completed"),
536 // just transfer the file name from the first sequence's first
538 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
539 .elementAt(0).getFile()).getAbsolutePath();
540 jmb.getPdbEntry(pi).setFile(file);
545 errormsgs.append("'").append(pdbid).append("' ");
550 if (filesInViewer != null && filesInViewer.length > 0)
552 addingStructures = true; // already files loaded.
553 for (int c = 0; c < filesInViewer.length; c++)
555 if (filesInViewer[c].equals(file))
568 } catch (OutOfMemoryError oomerror)
570 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
571 } catch (Exception ex)
573 ex.printStackTrace();
574 errormsgs.append("When retrieving pdbfiles : current was: '")
575 .append(pdbid).append("'");
577 if (errormsgs.length() > 0)
579 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
580 .formatMessage("label.pdb_entries_couldnt_be_retrieved",
581 new String[] { errormsgs.toString() }),
582 MessageManager.getString("label.couldnt_load_file"),
583 JvOptionPane.ERROR_MESSAGE);
589 public void eps_actionPerformed(ActionEvent e)
591 makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
595 public void png_actionPerformed(ActionEvent e)
597 makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
600 void makePDBImage(jalview.util.ImageMaker.TYPE type)
602 int width = getWidth();
603 int height = getHeight();
605 jalview.util.ImageMaker im;
607 if (type == jalview.util.ImageMaker.TYPE.PNG)
609 im = new jalview.util.ImageMaker(this,
610 jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from view",
611 width, height, null, null, null, 0, false);
613 else if (type == jalview.util.ImageMaker.TYPE.EPS)
615 im = new jalview.util.ImageMaker(this,
616 jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from view",
617 width, height, null, this.getTitle(), null, 0, false);
622 im = new jalview.util.ImageMaker(this,
623 jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
624 width, height, null, this.getTitle(), null, 0, false);
627 if (im.getGraphics() != null)
629 jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
635 public void showHelp_actionPerformed(ActionEvent actionEvent)
640 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
641 } catch (Exception ex)
646 public void showConsole(boolean showConsole)
651 if (splitPane == null)
653 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
654 splitPane.setTopComponent(renderPanel);
655 splitPane.setBottomComponent(scriptWindow);
656 this.getContentPane().add(splitPane, BorderLayout.CENTER);
657 splitPane.setDividerLocation(getHeight() - 200);
658 scriptWindow.setVisible(true);
659 scriptWindow.validate();
660 splitPane.validate();
666 if (splitPane != null)
668 splitPane.setVisible(false);
673 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
679 class RenderPanel extends JPanel
681 final Dimension currentSize = new Dimension();
684 public void paintComponent(Graphics g)
686 getSize(currentSize);
688 if (jmb != null && jmb.hasFileLoadingError())
690 g.setColor(Color.black);
691 g.fillRect(0, 0, currentSize.width, currentSize.height);
692 g.setColor(Color.white);
693 g.setFont(new Font("Verdana", Font.BOLD, 14));
694 g.drawString(MessageManager.getString("label.error_loading_file")
695 + "...", 20, currentSize.height / 2);
696 StringBuffer sb = new StringBuffer();
698 for (int e = 0; e < jmb.getPdbCount(); e++)
700 sb.append(jmb.getPdbEntry(e).getId());
701 if (e < jmb.getPdbCount() - 1)
706 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
709 g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
710 * g.getFontMetrics().getHeight());
714 else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
716 g.setColor(Color.black);
717 g.fillRect(0, 0, currentSize.width, currentSize.height);
718 g.setColor(Color.white);
719 g.setFont(new Font("Verdana", Font.BOLD, 14));
720 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
721 20, currentSize.height / 2);
725 jmb.viewer.renderScreenImage(g, currentSize.width,
732 public AAStructureBindingModel getBinding()
738 public String getStateInfo()
740 return jmb == null ? null : jmb.viewer.getStateInfo();
744 public ViewerType getViewerType()
746 return ViewerType.JMOL;
750 protected String getViewerName()