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.JMenu;
49 import javax.swing.JPanel;
50 import javax.swing.JSplitPane;
51 import javax.swing.SwingUtilities;
52 import javax.swing.event.InternalFrameAdapter;
53 import javax.swing.event.InternalFrameEvent;
55 public class AppJmol extends StructureViewerBase
57 // ms to wait for Jmol to load files
58 private static final int JMOL_LOAD_TIMEOUT = 20000;
60 private static final String SPACE = " ";
62 private static final String BACKSLASH = "\"";
70 RenderPanel renderPanel;
79 * - add the alignment panel to the list used for colouring these
82 * - add the alignment panel to the list used for aligning these
84 * @param leaveColouringToJmol
85 * - do not update the colours from any other source. Jmol is
91 public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
92 AlignmentPanel ap, boolean usetoColour, boolean useToAlign,
93 boolean leaveColouringToJmol, String loadStatus,
94 Rectangle bounds, String viewid)
96 PDBEntry[] pdbentrys = new PDBEntry[files.length];
97 for (int i = 0; i < pdbentrys.length; i++)
99 // PDBEntry pdbentry = new PDBEntry(files[i], ids[i]);
100 PDBEntry pdbentry = new PDBEntry(ids[i], null, PDBEntry.Type.PDB,
102 pdbentrys[i] = pdbentry;
104 // / TODO: check if protocol is needed to be set, and if chains are
106 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
107 pdbentrys, seqs, null);
109 jmb.setLoadingFromArchive(true);
110 addAlignmentPanel(ap);
113 useAlignmentPanelForSuperposition(ap);
116 if (leaveColouringToJmol || !usetoColour)
118 jmb.setColourBySequence(false);
119 seqColour.setSelected(false);
120 viewerColour.setSelected(true);
122 else if (usetoColour)
124 useAlignmentPanelForColourbyseq(ap);
125 jmb.setColourBySequence(true);
126 seqColour.setSelected(true);
127 viewerColour.setSelected(false);
129 this.setBounds(bounds);
131 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
132 // bounds.width,bounds.height);
134 this.addInternalFrameListener(new InternalFrameAdapter()
137 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
142 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
146 protected void initMenus()
150 viewerActionMenu = new JMenu(MessageManager.getString("label.jmol"));
153 .setText(MessageManager.getString("label.colour_with_jmol"));
154 viewerColour.setToolTipText(MessageManager
155 .getString("label.let_jmol_manage_structure_colours"));
158 IProgressIndicator progressBar = null;
161 * add a single PDB structure to a new or existing Jmol view
168 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
169 final AlignmentPanel ap)
171 progressBar = ap.alignFrame;
172 String pdbId = pdbentry.getId();
175 * If the PDB file is already loaded, the user may just choose to add to an
176 * existing viewer (or cancel)
178 if (addAlreadyLoadedFile(seq, chains, ap, pdbId))
184 * Check if there are other Jmol views involving this alignment and prompt
185 * user about adding this molecule to one of them
187 if (addToExistingViewer(pdbentry, seq, chains, ap, pdbId))
193 * If the options above are declined or do not apply, open a new viewer
195 openNewJmol(ap, new PDBEntry[] { pdbentry }, new SequenceI[][] { seq });
198 private void openNewJmol(AlignmentPanel ap, PDBEntry[] pdbentrys,
201 progressBar = ap.alignFrame;
202 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
203 pdbentrys, seqs, null);
204 addAlignmentPanel(ap);
205 useAlignmentPanelForColourbyseq(ap);
207 if (pdbentrys.length > 1)
209 alignAddedStructures = true;
210 useAlignmentPanelForSuperposition(ap);
212 jmb.setColourBySequence(true);
213 setSize(400, 400); // probably should be a configurable/dynamic default here
215 addingStructures = false;
216 worker = new Thread(this);
219 this.addInternalFrameListener(new InternalFrameAdapter()
222 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
231 * create a new Jmol containing several structures superimposed using the
238 public AppJmol(AlignmentPanel ap, PDBEntry[] pe, SequenceI[][] seqs)
240 openNewJmol(ap, pe, seqs);
244 * Returns a list of any Jmol viewers. The list is restricted to those linked
245 * to the given alignment panel if it is not null.
248 protected List<StructureViewerBase> getViewersFor(AlignmentPanel apanel)
250 List<StructureViewerBase> result = new ArrayList<StructureViewerBase>();
251 JInternalFrame[] frames = Desktop.instance.getAllFrames();
253 for (JInternalFrame frame : frames)
255 if (frame instanceof AppJmol)
258 || ((StructureViewerBase) frame).isLinkedWith(apanel))
260 result.add((StructureViewerBase) frame);
267 void initJmol(String command)
269 jmb.setFinishedInit(false);
270 renderPanel = new RenderPanel();
271 // TODO: consider waiting until the structure/view is fully loaded before
273 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
274 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
275 getBounds().width, getBounds().height);
276 if (scriptWindow == null)
278 BorderLayout bl = new BorderLayout();
281 scriptWindow = new JPanel(bl);
282 scriptWindow.setVisible(false);
285 jmb.allocateViewer(renderPanel, true, "", null, null, "",
287 // jmb.newJmolPopup("Jmol");
292 jmb.evalStateCommand(command);
293 jmb.evalStateCommand("set hoverDelay=0.1");
294 jmb.setFinishedInit(true);
299 boolean allChainsSelected = false;
302 void showSelectedChains()
304 Vector<String> toshow = new Vector<String>();
305 for (int i = 0; i < chainMenu.getItemCount(); i++)
307 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
309 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
310 if (item.isSelected())
312 toshow.addElement(item.getText());
316 jmb.centerViewer(toshow);
320 public void closeViewer(boolean closeExternalViewer)
322 // Jmol does not use an external viewer
327 setAlignmentPanel(null);
331 // TODO: check for memory leaks where instance isn't finalised because jmb
332 // holds a reference to the window
342 List<String> files = fetchPdbFiles();
343 if (files.size() > 0)
345 showFilesInViewer(files);
355 * Either adds the given files to a structure viewer or opens a new viewer to
359 * list of absolute paths to structure files
361 void showFilesInViewer(List<String> files)
363 long lastnotify = jmb.getLoadNotifiesHandled();
364 StringBuilder fileList = new StringBuilder();
365 for (String s : files)
367 fileList.append(SPACE).append(BACKSLASH)
368 .append(Platform.escapeString(s)).append(BACKSLASH);
370 String filesString = fileList.toString();
372 if (!addingStructures)
376 initJmol("load FILES " + filesString);
377 } catch (OutOfMemoryError oomerror)
379 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
380 Cache.log.debug("File locations are " + filesString);
381 } catch (Exception ex)
383 Cache.log.error("Couldn't open Jmol viewer!", ex);
388 StringBuilder cmd = new StringBuilder();
389 cmd.append("loadingJalviewdata=true\nload APPEND ");
390 cmd.append(filesString);
391 cmd.append("\nloadingJalviewdata=null");
392 final String command = cmd.toString();
393 lastnotify = jmb.getLoadNotifiesHandled();
397 jmb.evalStateCommand(command);
398 } catch (OutOfMemoryError oomerror)
400 new OOMWarning("When trying to add structures to the Jmol viewer!",
402 Cache.log.debug("File locations are " + filesString);
403 } catch (Exception ex)
405 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
409 // need to wait around until script has finished
410 int waitMax = JMOL_LOAD_TIMEOUT;
413 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
414 : !(jmb.isFinishedInit() && jmb.getPdbFile() != null && jmb
415 .getPdbFile().length == files.size()))
419 Cache.log.debug("Waiting around for jmb notify.");
420 Thread.sleep(waitFor);
421 waitTotal += waitFor;
422 } catch (Exception e)
425 if (waitTotal > waitMax)
428 .println("Timed out waiting for Jmol to load files after "
430 // System.err.println("finished: " + jmb.isFinishedInit()
431 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
432 // + "; files: " + files.toString());
438 // refresh the sequence colours for the new structure(s)
439 for (AlignmentPanel ap : _colourwith)
441 jmb.updateColours(ap);
443 // do superposition if asked to
444 if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
446 alignAddedStructures();
448 addingStructures = false;
452 * Queues a thread to align structures with Jalview alignments
454 void alignAddedStructures()
456 javax.swing.SwingUtilities.invokeLater(new Runnable()
461 if (jmb.viewer.isScriptExecuting())
463 SwingUtilities.invokeLater(this);
467 } catch (InterruptedException q)
474 alignStructs_withAllAlignPanels();
478 alignAddedStructures = false;
482 * Retrieves and saves as file any modelled PDB entries for which we do not
483 * already have a file saved. Returns a list of absolute paths to structure
484 * files which were either retrieved, or already stored but not modelled in
485 * the structure viewer (i.e. files to add to the viewer display).
489 List<String> fetchPdbFiles()
491 // todo - record which pdbids were successfully imported.
492 StringBuilder errormsgs = new StringBuilder();
494 List<String> files = new ArrayList<String>();
498 String[] filesInViewer = jmb.getPdbFile();
499 // TODO: replace with reference fetching/transfer code (validate PDBentry
501 Pdb pdbclient = new Pdb();
502 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
504 String file = jmb.getPdbEntry(pi).getFile();
507 // retrieve the pdb and store it locally
508 AlignmentI pdbseq = null;
509 pdbid = jmb.getPdbEntry(pi).getId();
510 long hdl = pdbid.hashCode() - System.currentTimeMillis();
511 if (progressBar != null)
513 progressBar.setProgressBar(MessageManager.formatMessage(
514 "status.fetching_pdb", new String[] { pdbid }), hdl);
518 pdbseq = pdbclient.getSequenceRecords(pdbid);
519 } catch (OutOfMemoryError oomerror)
521 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
522 } catch (Exception ex)
524 ex.printStackTrace();
525 errormsgs.append("'").append(pdbid).append("'");
528 if (progressBar != null)
530 progressBar.setProgressBar(
531 MessageManager.getString("label.state_completed"),
537 // just transfer the file name from the first sequence's first
539 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
540 .elementAt(0).getFile()).getAbsolutePath();
541 jmb.getPdbEntry(pi).setFile(file);
546 errormsgs.append("'").append(pdbid).append("' ");
551 if (filesInViewer != null && filesInViewer.length > 0)
553 addingStructures = true; // already files loaded.
554 for (int c = 0; c < filesInViewer.length; c++)
556 if (filesInViewer[c].equals(file))
569 } catch (OutOfMemoryError oomerror)
571 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
572 } catch (Exception ex)
574 ex.printStackTrace();
575 errormsgs.append("When retrieving pdbfiles : current was: '")
576 .append(pdbid).append("'");
578 if (errormsgs.length() > 0)
580 JvOptionPane.showInternalMessageDialog(Desktop.desktop, MessageManager
581 .formatMessage("label.pdb_entries_couldnt_be_retrieved",
582 new String[] { errormsgs.toString() }),
583 MessageManager.getString("label.couldnt_load_file"),
584 JvOptionPane.ERROR_MESSAGE);
590 public void eps_actionPerformed(ActionEvent e)
592 makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
596 public void png_actionPerformed(ActionEvent e)
598 makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
601 void makePDBImage(jalview.util.ImageMaker.TYPE type)
603 int width = getWidth();
604 int height = getHeight();
606 jalview.util.ImageMaker im;
608 if (type == jalview.util.ImageMaker.TYPE.PNG)
610 im = new jalview.util.ImageMaker(this,
611 jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from view",
612 width, height, null, null, null, 0, false);
614 else if (type == jalview.util.ImageMaker.TYPE.EPS)
616 im = new jalview.util.ImageMaker(this,
617 jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from view",
618 width, height, null, this.getTitle(), null, 0, false);
623 im = new jalview.util.ImageMaker(this,
624 jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
625 width, height, null, this.getTitle(), null, 0, false);
628 if (im.getGraphics() != null)
630 jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
636 public void showHelp_actionPerformed(ActionEvent actionEvent)
641 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
642 } catch (Exception ex)
647 public void showConsole(boolean showConsole)
652 if (splitPane == null)
654 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
655 splitPane.setTopComponent(renderPanel);
656 splitPane.setBottomComponent(scriptWindow);
657 this.getContentPane().add(splitPane, BorderLayout.CENTER);
658 splitPane.setDividerLocation(getHeight() - 200);
659 scriptWindow.setVisible(true);
660 scriptWindow.validate();
661 splitPane.validate();
667 if (splitPane != null)
669 splitPane.setVisible(false);
674 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
680 class RenderPanel extends JPanel
682 final Dimension currentSize = new Dimension();
685 public void paintComponent(Graphics g)
687 getSize(currentSize);
689 if (jmb != null && jmb.hasFileLoadingError())
691 g.setColor(Color.black);
692 g.fillRect(0, 0, currentSize.width, currentSize.height);
693 g.setColor(Color.white);
694 g.setFont(new Font("Verdana", Font.BOLD, 14));
695 g.drawString(MessageManager.getString("label.error_loading_file")
696 + "...", 20, currentSize.height / 2);
697 StringBuffer sb = new StringBuffer();
699 for (int e = 0; e < jmb.getPdbCount(); e++)
701 sb.append(jmb.getPdbEntry(e).getId());
702 if (e < jmb.getPdbCount() - 1)
707 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
710 g.drawString(sb.toString(), 20, currentSize.height / 2 - lines
711 * g.getFontMetrics().getHeight());
715 else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
717 g.setColor(Color.black);
718 g.fillRect(0, 0, currentSize.width, currentSize.height);
719 g.setColor(Color.white);
720 g.setFont(new Font("Verdana", Font.BOLD, 14));
721 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
722 20, currentSize.height / 2);
726 jmb.viewer.renderScreenImage(g, currentSize.width,
733 public AAStructureBindingModel getBinding()
739 public String getStateInfo()
741 return jmb == null ? null : jmb.viewer.getStateInfo();
745 public ViewerType getViewerType()
747 return ViewerType.JMOL;
751 protected String getViewerName()