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.api.AlignmentViewPanel;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.PDBEntry;
27 import jalview.datamodel.SequenceI;
28 import jalview.gui.StructureViewer.ViewerType;
29 import jalview.structures.models.AAStructureBindingModel;
30 import jalview.util.BrowserLauncher;
31 import jalview.util.MessageManager;
32 import jalview.util.Platform;
33 import jalview.ws.dbsources.Pdb;
35 import java.awt.BorderLayout;
36 import java.awt.Color;
37 import java.awt.Dimension;
39 import java.awt.Graphics;
40 import java.awt.Rectangle;
41 import java.awt.event.ActionEvent;
43 import java.util.ArrayList;
44 import java.util.List;
46 import javax.swing.JPanel;
47 import javax.swing.JSplitPane;
48 import javax.swing.SwingUtilities;
49 import javax.swing.event.InternalFrameAdapter;
50 import javax.swing.event.InternalFrameEvent;
52 public class AppJmol extends StructureViewerBase
54 // ms to wait for Jmol to load files
55 private static final int JMOL_LOAD_TIMEOUT = 20000;
57 private static final String SPACE = " ";
59 private static final String QUOTE = "\"";
67 RenderPanel renderPanel;
76 * - add the alignment panel to the list used for colouring these
79 * - add the alignment panel to the list used for aligning these
81 * @param leaveColouringToJmol
82 * - do not update the colours from any other source. Jmol is
88 public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
89 AlignmentPanel ap, boolean usetoColour, boolean useToAlign,
90 boolean leaveColouringToJmol, String loadStatus, Rectangle bounds,
93 PDBEntry[] pdbentrys = new PDBEntry[files.length];
94 for (int i = 0; i < pdbentrys.length; i++)
96 // PDBEntry pdbentry = new PDBEntry(files[i], ids[i]);
97 PDBEntry pdbentry = new PDBEntry(ids[i], null, PDBEntry.Type.PDB,
99 pdbentrys[i] = pdbentry;
101 // / TODO: check if protocol is needed to be set, and if chains are
103 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
104 pdbentrys, seqs, null);
106 jmb.setLoadingFromArchive(true);
107 addAlignmentPanel(ap);
110 useAlignmentPanelForSuperposition(ap);
113 if (leaveColouringToJmol || !usetoColour)
115 jmb.setColourBySequence(false);
116 seqColour.setSelected(false);
117 viewerColour.setSelected(true);
119 else if (usetoColour)
121 useAlignmentPanelForColourbyseq(ap);
122 jmb.setColourBySequence(true);
123 seqColour.setSelected(true);
124 viewerColour.setSelected(false);
126 this.setBounds(bounds);
128 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
129 // bounds.width,bounds.height);
131 this.addInternalFrameListener(new InternalFrameAdapter()
134 public void internalFrameClosing(
135 InternalFrameEvent internalFrameEvent)
140 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
144 protected void initMenus()
148 viewerActionMenu.setText(MessageManager.getString("label.jmol"));
151 .setText(MessageManager.getString("label.colour_with_jmol"));
152 viewerColour.setToolTipText(MessageManager
153 .getString("label.let_jmol_manage_structure_colours"));
156 IProgressIndicator progressBar = null;
159 protected IProgressIndicator getIProgressIndicator()
165 * display a single PDB structure in a new Jmol view
172 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
173 final AlignmentPanel ap)
175 progressBar = ap.alignFrame;
177 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
182 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
183 PDBEntry[] pdbentrys,
186 progressBar = ap.alignFrame;
187 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
188 pdbentrys, seqs, null);
189 addAlignmentPanel(ap);
190 useAlignmentPanelForColourbyseq(ap);
192 alignAddedStructures = alignAdded;
193 useAlignmentPanelForSuperposition(ap);
195 jmb.setColourBySequence(true);
196 setSize(400, 400); // probably should be a configurable/dynamic default here
198 addingStructures = false;
199 worker = new Thread(this);
202 this.addInternalFrameListener(new InternalFrameAdapter()
205 public void internalFrameClosing(
206 InternalFrameEvent internalFrameEvent)
215 * create a new Jmol containing several structures optionally superimposed
216 * using the given alignPanel.
220 * - true to superimpose
224 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
227 openNewJmol(ap, alignAdded, pe, seqs);
231 void initJmol(String command)
233 jmb.setFinishedInit(false);
234 renderPanel = new RenderPanel();
235 // TODO: consider waiting until the structure/view is fully loaded before
237 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
238 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
239 getBounds().width, getBounds().height);
240 if (scriptWindow == null)
242 BorderLayout bl = new BorderLayout();
245 scriptWindow = new JPanel(bl);
246 scriptWindow.setVisible(false);
249 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
251 // jmb.newJmolPopup("Jmol");
256 jmb.evalStateCommand(command);
257 jmb.evalStateCommand("set hoverDelay=0.1");
258 jmb.setFinishedInit(true);
262 public void closeViewer(boolean closeExternalViewer)
264 // Jmol does not use an external viewer
269 setAlignmentPanel(null);
273 // TODO: check for memory leaks where instance isn't finalised because jmb
274 // holds a reference to the window
284 List<String> files = fetchPdbFiles();
285 if (files.size() > 0)
287 showFilesInViewer(files);
297 * Either adds the given files to a structure viewer or opens a new viewer to
301 * list of absolute paths to structure files
303 void showFilesInViewer(List<String> files)
305 long lastnotify = jmb.getLoadNotifiesHandled();
306 StringBuilder fileList = new StringBuilder();
307 for (String s : files)
309 fileList.append(SPACE).append(QUOTE)
310 .append(Platform.escapeBackslashes(s)).append(QUOTE);
312 String filesString = fileList.toString();
314 if (!addingStructures)
318 initJmol("load FILES " + filesString);
319 } catch (OutOfMemoryError oomerror)
321 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
322 Cache.log.debug("File locations are " + filesString);
323 } catch (Exception ex)
325 Cache.log.error("Couldn't open Jmol viewer!", ex);
330 StringBuilder cmd = new StringBuilder();
331 cmd.append("loadingJalviewdata=true\nload APPEND ");
332 cmd.append(filesString);
333 cmd.append("\nloadingJalviewdata=null");
334 final String command = cmd.toString();
335 lastnotify = jmb.getLoadNotifiesHandled();
339 jmb.evalStateCommand(command);
340 } catch (OutOfMemoryError oomerror)
342 new OOMWarning("When trying to add structures to the Jmol viewer!",
344 Cache.log.debug("File locations are " + filesString);
345 } catch (Exception ex)
347 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
351 // need to wait around until script has finished
352 int waitMax = JMOL_LOAD_TIMEOUT;
355 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
356 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
357 && jmb.getStructureFiles().length == files.size()))
361 Cache.log.debug("Waiting around for jmb notify.");
362 Thread.sleep(waitFor);
363 waitTotal += waitFor;
364 } catch (Exception e)
367 if (waitTotal > waitMax)
369 System.err.println("Timed out waiting for Jmol to load files after "
371 // System.err.println("finished: " + jmb.isFinishedInit()
372 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
373 // + "; files: " + files.toString());
374 jmb.getStructureFiles();
379 // refresh the sequence colours for the new structure(s)
380 for (AlignmentViewPanel avp : _colourwith)
382 jmb.updateColours(avp);
384 // do superposition if asked to
385 if (alignAddedStructures)
387 alignAddedStructures();
389 addingStructures = false;
393 * Queues a thread to align structures with Jalview alignments
395 void alignAddedStructures()
397 javax.swing.SwingUtilities.invokeLater(new Runnable()
402 if (jmb.viewer.isScriptExecuting())
404 SwingUtilities.invokeLater(this);
408 } catch (InterruptedException q)
415 alignStructs_withAllAlignPanels();
423 * Retrieves and saves as file any modelled PDB entries for which we do not
424 * already have a file saved. Returns a list of absolute paths to structure
425 * files which were either retrieved, or already stored but not modelled in
426 * the structure viewer (i.e. files to add to the viewer display).
430 List<String> fetchPdbFiles()
432 // todo - record which pdbids were successfully imported.
433 StringBuilder errormsgs = new StringBuilder();
435 List<String> files = new ArrayList<>();
439 String[] filesInViewer = jmb.getStructureFiles();
440 // TODO: replace with reference fetching/transfer code (validate PDBentry
442 Pdb pdbclient = new Pdb();
443 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
445 String file = jmb.getPdbEntry(pi).getFile();
448 // todo: extract block as method and pull up (also ChimeraViewFrame)
449 // retrieve the pdb and store it locally
450 AlignmentI pdbseq = null;
451 pdbid = jmb.getPdbEntry(pi).getId();
452 long hdl = pdbid.hashCode() - System.currentTimeMillis();
453 if (progressBar != null)
455 progressBar.setProgressBar(MessageManager
456 .formatMessage("status.fetching_pdb", new String[]
461 pdbseq = pdbclient.getSequenceRecords(pdbid);
462 } catch (OutOfMemoryError oomerror)
464 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
465 } catch (Exception ex)
467 ex.printStackTrace();
468 errormsgs.append("'").append(pdbid).append("'");
471 if (progressBar != null)
473 progressBar.setProgressBar(
474 MessageManager.getString("label.state_completed"),
480 // just transfer the file name from the first sequence's first
482 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
483 .elementAt(0).getFile()).getAbsolutePath();
484 jmb.getPdbEntry(pi).setFile(file);
489 errormsgs.append("'").append(pdbid).append("' ");
494 if (filesInViewer != null && filesInViewer.length > 0)
496 addingStructures = true; // already files loaded.
497 for (int c = 0; c < filesInViewer.length; c++)
499 if (Platform.pathEquals(filesInViewer[c], file))
512 } catch (OutOfMemoryError oomerror)
514 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
515 } catch (Exception ex)
517 ex.printStackTrace();
518 errormsgs.append("When retrieving pdbfiles : current was: '")
519 .append(pdbid).append("'");
521 if (errormsgs.length() > 0)
523 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
524 MessageManager.formatMessage(
525 "label.pdb_entries_couldnt_be_retrieved", new String[]
526 { errormsgs.toString() }),
527 MessageManager.getString("label.couldnt_load_file"),
528 JvOptionPane.ERROR_MESSAGE);
534 public void eps_actionPerformed(ActionEvent e)
536 makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
540 public void png_actionPerformed(ActionEvent e)
542 makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
545 void makePDBImage(jalview.util.ImageMaker.TYPE type)
547 int width = getWidth();
548 int height = getHeight();
550 jalview.util.ImageMaker im;
552 if (type == jalview.util.ImageMaker.TYPE.PNG)
554 im = new jalview.util.ImageMaker(this,
555 jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from view",
556 width, height, null, null, null, 0, false);
558 else if (type == jalview.util.ImageMaker.TYPE.EPS)
560 im = new jalview.util.ImageMaker(this,
561 jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from view",
562 width, height, null, this.getTitle(), null, 0, false);
567 im = new jalview.util.ImageMaker(this,
568 jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
569 width, height, null, this.getTitle(), null, 0, false);
572 if (im.getGraphics() != null)
574 jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
580 public void showHelp_actionPerformed(ActionEvent actionEvent)
585 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
586 } catch (Exception ex)
591 public void showConsole(boolean showConsole)
596 if (splitPane == null)
598 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
599 splitPane.setTopComponent(renderPanel);
600 splitPane.setBottomComponent(scriptWindow);
601 this.getContentPane().add(splitPane, BorderLayout.CENTER);
602 splitPane.setDividerLocation(getHeight() - 200);
603 scriptWindow.setVisible(true);
604 scriptWindow.validate();
605 splitPane.validate();
611 if (splitPane != null)
613 splitPane.setVisible(false);
618 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
624 class RenderPanel extends JPanel
626 final Dimension currentSize = new Dimension();
629 public void paintComponent(Graphics g)
631 getSize(currentSize);
633 if (jmb != null && jmb.hasFileLoadingError())
635 g.setColor(Color.black);
636 g.fillRect(0, 0, currentSize.width, currentSize.height);
637 g.setColor(Color.white);
638 g.setFont(new Font("Verdana", Font.BOLD, 14));
639 g.drawString(MessageManager.getString("label.error_loading_file")
640 + "...", 20, currentSize.height / 2);
641 StringBuffer sb = new StringBuffer();
643 for (int e = 0; e < jmb.getPdbCount(); e++)
645 sb.append(jmb.getPdbEntry(e).getId());
646 if (e < jmb.getPdbCount() - 1)
651 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
654 g.drawString(sb.toString(), 20, currentSize.height / 2
655 - lines * g.getFontMetrics().getHeight());
659 else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
661 g.setColor(Color.black);
662 g.fillRect(0, 0, currentSize.width, currentSize.height);
663 g.setColor(Color.white);
664 g.setFont(new Font("Verdana", Font.BOLD, 14));
665 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
666 20, currentSize.height / 2);
670 jmb.viewer.renderScreenImage(g, currentSize.width,
677 public AAStructureBindingModel getBinding()
683 public String getStateInfo()
685 return jmb == null ? null : jmb.viewer.getStateInfo();
689 public ViewerType getViewerType()
691 return ViewerType.JMOL;
695 protected String getViewerName()