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.ImageExporter.ImageWriterI;
28 import jalview.gui.StructureViewer.ViewerType;
29 import jalview.structures.models.AAStructureBindingModel;
30 import jalview.util.BrowserLauncher;
31 import jalview.util.ImageMaker;
32 import jalview.util.MessageManager;
33 import jalview.util.Platform;
34 import jalview.ws.dbsources.Pdb;
36 import java.awt.BorderLayout;
37 import java.awt.Color;
38 import java.awt.Dimension;
40 import java.awt.Graphics;
41 import java.awt.Rectangle;
42 import java.awt.event.ActionEvent;
44 import java.util.ArrayList;
45 import java.util.List;
46 import java.util.Vector;
48 import javax.swing.JCheckBoxMenuItem;
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 QUOTE = "\"";
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, Rectangle bounds,
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(
138 InternalFrameEvent internalFrameEvent)
143 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
147 protected void initMenus()
151 viewerActionMenu.setText(MessageManager.getString("label.jmol"));
154 .setText(MessageManager.getString("label.colour_with_jmol"));
155 viewerColour.setToolTipText(MessageManager
156 .getString("label.let_jmol_manage_structure_colours"));
159 IProgressIndicator progressBar = null;
162 protected IProgressIndicator getIProgressIndicator()
168 * display a single PDB structure in a new Jmol view
175 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
176 final AlignmentPanel ap)
178 progressBar = ap.alignFrame;
180 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
185 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
186 PDBEntry[] pdbentrys,
189 progressBar = ap.alignFrame;
190 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
191 pdbentrys, seqs, null);
192 addAlignmentPanel(ap);
193 useAlignmentPanelForColourbyseq(ap);
195 alignAddedStructures = alignAdded;
196 useAlignmentPanelForSuperposition(ap);
198 jmb.setColourBySequence(true);
199 setSize(400, 400); // probably should be a configurable/dynamic default here
201 addingStructures = false;
202 worker = new Thread(this);
205 this.addInternalFrameListener(new InternalFrameAdapter()
208 public void internalFrameClosing(
209 InternalFrameEvent internalFrameEvent)
218 * create a new Jmol containing several structures optionally superimposed
219 * using the given alignPanel.
223 * - true to superimpose
227 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
230 openNewJmol(ap, alignAdded, pe, seqs);
234 void initJmol(String command)
236 jmb.setFinishedInit(false);
237 renderPanel = new RenderPanel();
238 // TODO: consider waiting until the structure/view is fully loaded before
240 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
241 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
242 getBounds().width, getBounds().height);
243 if (scriptWindow == null)
245 BorderLayout bl = new BorderLayout();
248 scriptWindow = new JPanel(bl);
249 scriptWindow.setVisible(false);
252 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
254 // jmb.newJmolPopup("Jmol");
259 jmb.evalStateCommand(command);
260 jmb.evalStateCommand("set hoverDelay=0.1");
261 jmb.setFinishedInit(true);
265 void showSelectedChains()
267 Vector<String> toshow = new Vector<>();
268 for (int i = 0; i < chainMenu.getItemCount(); i++)
270 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
272 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
273 if (item.isSelected())
275 toshow.addElement(item.getText());
279 jmb.centerViewer(toshow);
283 public void closeViewer(boolean closeExternalViewer)
285 // Jmol does not use an external viewer
290 setAlignmentPanel(null);
294 // TODO: check for memory leaks where instance isn't finalised because jmb
295 // holds a reference to the window
305 List<String> files = fetchPdbFiles();
306 if (files.size() > 0)
308 showFilesInViewer(files);
318 * Either adds the given files to a structure viewer or opens a new viewer to
322 * list of absolute paths to structure files
324 void showFilesInViewer(List<String> files)
326 long lastnotify = jmb.getLoadNotifiesHandled();
327 StringBuilder fileList = new StringBuilder();
328 for (String s : files)
330 fileList.append(SPACE).append(QUOTE)
331 .append(Platform.escapeString(s)).append(QUOTE);
333 String filesString = fileList.toString();
335 if (!addingStructures)
339 initJmol("load FILES " + filesString);
340 } catch (OutOfMemoryError oomerror)
342 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
343 Cache.log.debug("File locations are " + filesString);
344 } catch (Exception ex)
346 Cache.log.error("Couldn't open Jmol viewer!", ex);
351 StringBuilder cmd = new StringBuilder();
352 cmd.append("loadingJalviewdata=true\nload APPEND ");
353 cmd.append(filesString);
354 cmd.append("\nloadingJalviewdata=null");
355 final String command = cmd.toString();
356 lastnotify = jmb.getLoadNotifiesHandled();
360 jmb.evalStateCommand(command);
361 } catch (OutOfMemoryError oomerror)
363 new OOMWarning("When trying to add structures to the Jmol viewer!",
365 Cache.log.debug("File locations are " + filesString);
366 } catch (Exception ex)
368 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
372 // need to wait around until script has finished
373 int waitMax = JMOL_LOAD_TIMEOUT;
376 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
377 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
378 && jmb.getStructureFiles().length == files.size()))
382 Cache.log.debug("Waiting around for jmb notify.");
383 Thread.sleep(waitFor);
384 waitTotal += waitFor;
385 } catch (Exception e)
388 if (waitTotal > waitMax)
390 System.err.println("Timed out waiting for Jmol to load files after "
392 // System.err.println("finished: " + jmb.isFinishedInit()
393 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
394 // + "; files: " + files.toString());
395 jmb.getStructureFiles();
400 // refresh the sequence colours for the new structure(s)
401 for (AlignmentPanel ap : _colourwith)
403 jmb.updateColours(ap);
405 // do superposition if asked to
406 if (alignAddedStructures)
408 alignAddedStructures();
410 addingStructures = false;
414 * Queues a thread to align structures with Jalview alignments
416 void alignAddedStructures()
418 javax.swing.SwingUtilities.invokeLater(new Runnable()
423 if (jmb.viewer.isScriptExecuting())
425 SwingUtilities.invokeLater(this);
429 } catch (InterruptedException q)
436 alignStructs_withAllAlignPanels();
444 * Retrieves and saves as file any modelled PDB entries for which we do not
445 * already have a file saved. Returns a list of absolute paths to structure
446 * files which were either retrieved, or already stored but not modelled in
447 * the structure viewer (i.e. files to add to the viewer display).
451 List<String> fetchPdbFiles()
453 // todo - record which pdbids were successfully imported.
454 StringBuilder errormsgs = new StringBuilder();
456 List<String> files = new ArrayList<>();
460 String[] filesInViewer = jmb.getStructureFiles();
461 // TODO: replace with reference fetching/transfer code (validate PDBentry
463 Pdb pdbclient = new Pdb();
464 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
466 String file = jmb.getPdbEntry(pi).getFile();
469 // todo: extract block as method and pull up (also ChimeraViewFrame)
470 // retrieve the pdb and store it locally
471 AlignmentI pdbseq = null;
472 pdbid = jmb.getPdbEntry(pi).getId();
473 long hdl = pdbid.hashCode() - System.currentTimeMillis();
474 if (progressBar != null)
476 progressBar.setProgressBar(MessageManager
477 .formatMessage("status.fetching_pdb", new String[]
482 pdbseq = pdbclient.getSequenceRecords(pdbid);
483 } catch (OutOfMemoryError oomerror)
485 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
486 } catch (Exception ex)
488 ex.printStackTrace();
489 errormsgs.append("'").append(pdbid).append("'");
492 if (progressBar != null)
494 progressBar.setProgressBar(
495 MessageManager.getString("label.state_completed"),
501 // just transfer the file name from the first sequence's first
503 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
504 .elementAt(0).getFile()).getAbsolutePath();
505 jmb.getPdbEntry(pi).setFile(file);
510 errormsgs.append("'").append(pdbid).append("' ");
515 if (filesInViewer != null && filesInViewer.length > 0)
517 addingStructures = true; // already files loaded.
518 for (int c = 0; c < filesInViewer.length; c++)
520 if (filesInViewer[c].equals(file))
533 } catch (OutOfMemoryError oomerror)
535 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
536 } catch (Exception ex)
538 ex.printStackTrace();
539 errormsgs.append("When retrieving pdbfiles : current was: '")
540 .append(pdbid).append("'");
542 if (errormsgs.length() > 0)
544 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
545 MessageManager.formatMessage(
546 "label.pdb_entries_couldnt_be_retrieved", new String[]
547 { errormsgs.toString() }),
548 MessageManager.getString("label.couldnt_load_file"),
549 JvOptionPane.ERROR_MESSAGE);
555 * Outputs the Jmol viewer image as an image file, after prompting the user to
556 * choose a file and (for EPS) choice of Text or Lineart character rendering
557 * (unless a preference for this is set)
561 public void makePDBImage(ImageMaker.TYPE type)
563 int width = getWidth();
564 int height = getHeight();
565 ImageWriterI writer = new ImageWriterI()
568 public void exportImage(Graphics g) throws Exception
570 jmb.viewer.renderScreenImage(g, width, height);
573 String view = MessageManager.getString("action.view").toLowerCase();
574 ImageExporter exporter = new ImageExporter(writer,
575 jmb.getIProgressIndicator(), type, getTitle());
576 exporter.doExport(null, this, width, height, view);
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()