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, Rectangle bounds,
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(
137 InternalFrameEvent internalFrameEvent)
142 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
146 protected void initMenus()
150 viewerActionMenu.setText(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 protected IProgressIndicator getIProgressIndicator()
166 * add a single PDB structure to a new or existing Jmol view
173 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
174 final AlignmentPanel ap)
176 progressBar = ap.alignFrame;
177 String pdbId = pdbentry.getId();
180 * If the PDB file is already loaded, the user may just choose to add to an
181 * existing viewer (or cancel)
183 if (addAlreadyLoadedFile(seq, chains, ap, pdbId))
189 * Check if there are other Jmol views involving this alignment and prompt
190 * user about adding this molecule to one of them
192 if (addToExistingViewer(pdbentry, seq, chains, ap, pdbId))
198 * If the options above are declined or do not apply, open a new viewer
200 openNewJmol(ap, new PDBEntry[] { pdbentry }, new SequenceI[][] { seq });
203 private void openNewJmol(AlignmentPanel ap, PDBEntry[] pdbentrys,
206 progressBar = ap.alignFrame;
207 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
208 pdbentrys, seqs, null);
209 addAlignmentPanel(ap);
210 useAlignmentPanelForColourbyseq(ap);
212 if (pdbentrys.length > 1)
214 alignAddedStructures = true;
215 useAlignmentPanelForSuperposition(ap);
217 jmb.setColourBySequence(true);
218 setSize(400, 400); // probably should be a configurable/dynamic default here
220 addingStructures = false;
221 worker = new Thread(this);
224 this.addInternalFrameListener(new InternalFrameAdapter()
227 public void internalFrameClosing(
228 InternalFrameEvent internalFrameEvent)
237 * create a new Jmol containing several structures superimposed using the
244 public AppJmol(AlignmentPanel ap, PDBEntry[] pe, SequenceI[][] seqs)
246 openNewJmol(ap, pe, seqs);
250 * Returns a list of any Jmol viewers. The list is restricted to those linked
251 * to the given alignment panel if it is not null.
254 protected List<StructureViewerBase> getViewersFor(AlignmentPanel apanel)
256 List<StructureViewerBase> result = new ArrayList<>();
257 JInternalFrame[] frames = Desktop.instance.getAllFrames();
259 for (JInternalFrame frame : frames)
261 if (frame instanceof AppJmol)
264 || ((StructureViewerBase) frame).isLinkedWith(apanel))
266 result.add((StructureViewerBase) frame);
273 void initJmol(String command)
275 jmb.setFinishedInit(false);
276 renderPanel = new RenderPanel();
277 // TODO: consider waiting until the structure/view is fully loaded before
279 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
280 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
281 getBounds().width, getBounds().height);
282 if (scriptWindow == null)
284 BorderLayout bl = new BorderLayout();
287 scriptWindow = new JPanel(bl);
288 scriptWindow.setVisible(false);
291 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
293 // jmb.newJmolPopup("Jmol");
298 jmb.evalStateCommand(command);
299 jmb.evalStateCommand("set hoverDelay=0.1");
300 jmb.setFinishedInit(true);
303 boolean allChainsSelected = false;
306 void showSelectedChains()
308 Vector<String> toshow = new Vector<>();
309 for (int i = 0; i < chainMenu.getItemCount(); i++)
311 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
313 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
314 if (item.isSelected())
316 toshow.addElement(item.getText());
320 jmb.centerViewer(toshow);
324 public void closeViewer(boolean closeExternalViewer)
326 // Jmol does not use an external viewer
331 setAlignmentPanel(null);
335 // TODO: check for memory leaks where instance isn't finalised because jmb
336 // holds a reference to the window
346 List<String> files = fetchPdbFiles();
347 if (files.size() > 0)
349 showFilesInViewer(files);
359 * Either adds the given files to a structure viewer or opens a new viewer to
363 * list of absolute paths to structure files
365 void showFilesInViewer(List<String> files)
367 long lastnotify = jmb.getLoadNotifiesHandled();
368 StringBuilder fileList = new StringBuilder();
369 for (String s : files)
371 fileList.append(SPACE).append(BACKSLASH)
372 .append(Platform.escapeString(s)).append(BACKSLASH);
374 String filesString = fileList.toString();
376 if (!addingStructures)
380 initJmol("load FILES " + filesString);
381 } catch (OutOfMemoryError oomerror)
383 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
384 Cache.log.debug("File locations are " + filesString);
385 } catch (Exception ex)
387 Cache.log.error("Couldn't open Jmol viewer!", ex);
392 StringBuilder cmd = new StringBuilder();
393 cmd.append("loadingJalviewdata=true\nload APPEND ");
394 cmd.append(filesString);
395 cmd.append("\nloadingJalviewdata=null");
396 final String command = cmd.toString();
397 lastnotify = jmb.getLoadNotifiesHandled();
401 jmb.evalStateCommand(command);
402 } catch (OutOfMemoryError oomerror)
404 new OOMWarning("When trying to add structures to the Jmol viewer!",
406 Cache.log.debug("File locations are " + filesString);
407 } catch (Exception ex)
409 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
413 // need to wait around until script has finished
414 int waitMax = JMOL_LOAD_TIMEOUT;
417 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
418 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
419 && jmb.getStructureFiles().length == files.size()))
423 Cache.log.debug("Waiting around for jmb notify.");
424 Thread.sleep(waitFor);
425 waitTotal += waitFor;
426 } catch (Exception e)
429 if (waitTotal > waitMax)
431 System.err.println("Timed out waiting for Jmol to load files after "
433 // System.err.println("finished: " + jmb.isFinishedInit()
434 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
435 // + "; files: " + files.toString());
436 jmb.getStructureFiles();
441 // refresh the sequence colours for the new structure(s)
442 for (AlignmentPanel ap : _colourwith)
444 jmb.updateColours(ap);
446 // do superposition if asked to
447 if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
449 alignAddedStructures();
451 addingStructures = false;
455 * Queues a thread to align structures with Jalview alignments
457 void alignAddedStructures()
459 javax.swing.SwingUtilities.invokeLater(new Runnable()
464 if (jmb.viewer.isScriptExecuting())
466 SwingUtilities.invokeLater(this);
470 } catch (InterruptedException q)
477 alignStructs_withAllAlignPanels();
481 alignAddedStructures = false;
485 * Retrieves and saves as file any modelled PDB entries for which we do not
486 * already have a file saved. Returns a list of absolute paths to structure
487 * files which were either retrieved, or already stored but not modelled in
488 * the structure viewer (i.e. files to add to the viewer display).
492 List<String> fetchPdbFiles()
494 // todo - record which pdbids were successfully imported.
495 StringBuilder errormsgs = new StringBuilder();
497 List<String> files = new ArrayList<>();
501 String[] filesInViewer = jmb.getStructureFiles();
502 // TODO: replace with reference fetching/transfer code (validate PDBentry
504 Pdb pdbclient = new Pdb();
505 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
507 String file = jmb.getPdbEntry(pi).getFile();
510 // retrieve the pdb and store it locally
511 AlignmentI pdbseq = null;
512 pdbid = jmb.getPdbEntry(pi).getId();
513 long hdl = pdbid.hashCode() - System.currentTimeMillis();
514 if (progressBar != null)
516 progressBar.setProgressBar(MessageManager
517 .formatMessage("status.fetching_pdb", new String[]
522 pdbseq = pdbclient.getSequenceRecords(pdbid);
523 } catch (OutOfMemoryError oomerror)
525 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
526 } catch (Exception ex)
528 ex.printStackTrace();
529 errormsgs.append("'").append(pdbid).append("'");
532 if (progressBar != null)
534 progressBar.setProgressBar(
535 MessageManager.getString("label.state_completed"),
541 // just transfer the file name from the first sequence's first
543 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
544 .elementAt(0).getFile()).getAbsolutePath();
545 jmb.getPdbEntry(pi).setFile(file);
550 errormsgs.append("'").append(pdbid).append("' ");
555 if (filesInViewer != null && filesInViewer.length > 0)
557 addingStructures = true; // already files loaded.
558 for (int c = 0; c < filesInViewer.length; c++)
560 if (filesInViewer[c].equals(file))
573 } catch (OutOfMemoryError oomerror)
575 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
576 } catch (Exception ex)
578 ex.printStackTrace();
579 errormsgs.append("When retrieving pdbfiles : current was: '")
580 .append(pdbid).append("'");
582 if (errormsgs.length() > 0)
584 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
585 MessageManager.formatMessage(
586 "label.pdb_entries_couldnt_be_retrieved", new String[]
587 { errormsgs.toString() }),
588 MessageManager.getString("label.couldnt_load_file"),
589 JvOptionPane.ERROR_MESSAGE);
595 public void eps_actionPerformed(ActionEvent e)
597 makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
601 public void png_actionPerformed(ActionEvent e)
603 makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
606 void makePDBImage(jalview.util.ImageMaker.TYPE type)
608 int width = getWidth();
609 int height = getHeight();
611 jalview.util.ImageMaker im;
613 if (type == jalview.util.ImageMaker.TYPE.PNG)
615 im = new jalview.util.ImageMaker(this,
616 jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from view",
617 width, height, null, null, null, 0, false);
619 else if (type == jalview.util.ImageMaker.TYPE.EPS)
621 im = new jalview.util.ImageMaker(this,
622 jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from view",
623 width, height, null, this.getTitle(), null, 0, false);
628 im = new jalview.util.ImageMaker(this,
629 jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
630 width, height, null, this.getTitle(), null, 0, false);
633 if (im.getGraphics() != null)
635 jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
641 public void showHelp_actionPerformed(ActionEvent actionEvent)
646 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
647 } catch (Exception ex)
652 public void showConsole(boolean showConsole)
657 if (splitPane == null)
659 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
660 splitPane.setTopComponent(renderPanel);
661 splitPane.setBottomComponent(scriptWindow);
662 this.getContentPane().add(splitPane, BorderLayout.CENTER);
663 splitPane.setDividerLocation(getHeight() - 200);
664 scriptWindow.setVisible(true);
665 scriptWindow.validate();
666 splitPane.validate();
672 if (splitPane != null)
674 splitPane.setVisible(false);
679 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
685 class RenderPanel extends JPanel
687 final Dimension currentSize = new Dimension();
690 public void paintComponent(Graphics g)
692 getSize(currentSize);
694 if (jmb != null && jmb.hasFileLoadingError())
696 g.setColor(Color.black);
697 g.fillRect(0, 0, currentSize.width, currentSize.height);
698 g.setColor(Color.white);
699 g.setFont(new Font("Verdana", Font.BOLD, 14));
700 g.drawString(MessageManager.getString("label.error_loading_file")
701 + "...", 20, currentSize.height / 2);
702 StringBuffer sb = new StringBuffer();
704 for (int e = 0; e < jmb.getPdbCount(); e++)
706 sb.append(jmb.getPdbEntry(e).getId());
707 if (e < jmb.getPdbCount() - 1)
712 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
715 g.drawString(sb.toString(), 20, currentSize.height / 2
716 - lines * g.getFontMetrics().getHeight());
720 else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
722 g.setColor(Color.black);
723 g.fillRect(0, 0, currentSize.width, currentSize.height);
724 g.setColor(Color.white);
725 g.setFont(new Font("Verdana", Font.BOLD, 14));
726 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
727 20, currentSize.height / 2);
731 jmb.viewer.renderScreenImage(g, currentSize.width,
738 public AAStructureBindingModel getBinding()
744 public String getStateInfo()
746 return jmb == null ? null : jmb.viewer.getStateInfo();
750 public ViewerType getViewerType()
752 return ViewerType.JMOL;
756 protected String getViewerName()