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 static jalview.util.ImageMaker.TYPE.PNG;
25 import jalview.bin.Cache;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.PDBEntry;
28 import jalview.datamodel.SequenceI;
29 import jalview.gui.StructureViewer.ViewerType;
30 import jalview.structures.models.AAStructureBindingModel;
31 import jalview.util.BrowserLauncher;
32 import jalview.util.ImageMaker;
33 import jalview.util.MessageManager;
34 import jalview.util.Platform;
35 import jalview.ws.dbsources.Pdb;
37 import java.awt.BorderLayout;
38 import java.awt.Color;
39 import java.awt.Dimension;
41 import java.awt.Graphics;
42 import java.awt.Rectangle;
43 import java.awt.event.ActionEvent;
45 import java.util.ArrayList;
46 import java.util.List;
47 import java.util.Vector;
49 import javax.swing.JCheckBoxMenuItem;
50 import javax.swing.JPanel;
51 import javax.swing.JSplitPane;
52 import javax.swing.SwingUtilities;
53 import javax.swing.event.InternalFrameAdapter;
54 import javax.swing.event.InternalFrameEvent;
56 public class AppJmol extends StructureViewerBase
58 // ms to wait for Jmol to load files
59 private static final int JMOL_LOAD_TIMEOUT = 20000;
61 private static final String SPACE = " ";
63 private static final String QUOTE = "\"";
71 RenderPanel renderPanel;
80 * - add the alignment panel to the list used for colouring these
83 * - add the alignment panel to the list used for aligning these
85 * @param leaveColouringToJmol
86 * - do not update the colours from any other source. Jmol is
92 public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
93 AlignmentPanel ap, boolean usetoColour, boolean useToAlign,
94 boolean leaveColouringToJmol, String loadStatus, Rectangle bounds,
97 PDBEntry[] pdbentrys = new PDBEntry[files.length];
98 for (int i = 0; i < pdbentrys.length; i++)
100 // PDBEntry pdbentry = new PDBEntry(files[i], ids[i]);
101 PDBEntry pdbentry = new PDBEntry(ids[i], null, PDBEntry.Type.PDB,
103 pdbentrys[i] = pdbentry;
105 // / TODO: check if protocol is needed to be set, and if chains are
107 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
108 pdbentrys, seqs, null);
110 jmb.setLoadingFromArchive(true);
111 addAlignmentPanel(ap);
114 useAlignmentPanelForSuperposition(ap);
117 if (leaveColouringToJmol || !usetoColour)
119 jmb.setColourBySequence(false);
120 seqColour.setSelected(false);
121 viewerColour.setSelected(true);
123 else if (usetoColour)
125 useAlignmentPanelForColourbyseq(ap);
126 jmb.setColourBySequence(true);
127 seqColour.setSelected(true);
128 viewerColour.setSelected(false);
130 this.setBounds(bounds);
132 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
133 // bounds.width,bounds.height);
135 this.addInternalFrameListener(new InternalFrameAdapter()
138 public void internalFrameClosing(
139 InternalFrameEvent internalFrameEvent)
144 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
148 protected void initMenus()
152 viewerActionMenu.setText(MessageManager.getString("label.jmol"));
155 .setText(MessageManager.getString("label.colour_with_jmol"));
156 viewerColour.setToolTipText(MessageManager
157 .getString("label.let_jmol_manage_structure_colours"));
160 IProgressIndicator progressBar = null;
163 protected IProgressIndicator getIProgressIndicator()
169 * display a single PDB structure in a new Jmol view
176 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
177 final AlignmentPanel ap)
179 progressBar = ap.alignFrame;
181 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
186 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
187 PDBEntry[] pdbentrys,
190 progressBar = ap.alignFrame;
191 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
192 pdbentrys, seqs, null);
193 addAlignmentPanel(ap);
194 useAlignmentPanelForColourbyseq(ap);
196 alignAddedStructures = alignAdded;
197 useAlignmentPanelForSuperposition(ap);
199 jmb.setColourBySequence(true);
200 setSize(400, 400); // probably should be a configurable/dynamic default here
202 addingStructures = false;
203 worker = new Thread(this);
206 this.addInternalFrameListener(new InternalFrameAdapter()
209 public void internalFrameClosing(
210 InternalFrameEvent internalFrameEvent)
219 * create a new Jmol containing several structures optionally superimposed
220 * using the given alignPanel.
224 * - true to superimpose
228 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
231 openNewJmol(ap, alignAdded, pe, seqs);
235 void initJmol(String command)
237 jmb.setFinishedInit(false);
238 renderPanel = new RenderPanel();
239 // TODO: consider waiting until the structure/view is fully loaded before
241 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
242 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
243 getBounds().width, getBounds().height);
244 if (scriptWindow == null)
246 BorderLayout bl = new BorderLayout();
249 scriptWindow = new JPanel(bl);
250 scriptWindow.setVisible(false);
253 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
255 // jmb.newJmolPopup("Jmol");
260 jmb.evalStateCommand(command);
261 jmb.evalStateCommand("set hoverDelay=0.1");
262 jmb.setFinishedInit(true);
266 void showSelectedChains()
268 Vector<String> toshow = new Vector<>();
269 for (int i = 0; i < chainMenu.getItemCount(); i++)
271 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
273 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
274 if (item.isSelected())
276 toshow.addElement(item.getText());
280 jmb.centerViewer(toshow);
284 public void closeViewer(boolean closeExternalViewer)
286 // Jmol does not use an external viewer
291 setAlignmentPanel(null);
295 // TODO: check for memory leaks where instance isn't finalised because jmb
296 // holds a reference to the window
306 List<String> files = fetchPdbFiles();
307 if (files.size() > 0)
309 showFilesInViewer(files);
319 * Either adds the given files to a structure viewer or opens a new viewer to
323 * list of absolute paths to structure files
325 void showFilesInViewer(List<String> files)
327 long lastnotify = jmb.getLoadNotifiesHandled();
328 StringBuilder fileList = new StringBuilder();
329 for (String s : files)
331 fileList.append(SPACE).append(QUOTE)
332 .append(Platform.escapeBackslashes(s)).append(QUOTE);
334 String filesString = fileList.toString();
336 if (!addingStructures)
340 initJmol("load FILES " + filesString);
341 } catch (OutOfMemoryError oomerror)
343 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
344 Cache.log.debug("File locations are " + filesString);
345 } catch (Exception ex)
347 Cache.log.error("Couldn't open Jmol viewer!", ex);
352 StringBuilder cmd = new StringBuilder();
353 cmd.append("loadingJalviewdata=true\nload APPEND ");
354 cmd.append(filesString);
355 cmd.append("\nloadingJalviewdata=null");
356 final String command = cmd.toString();
357 lastnotify = jmb.getLoadNotifiesHandled();
361 jmb.evalStateCommand(command);
362 } catch (OutOfMemoryError oomerror)
364 new OOMWarning("When trying to add structures to the Jmol viewer!",
366 Cache.log.debug("File locations are " + filesString);
367 } catch (Exception ex)
369 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
373 // need to wait around until script has finished
374 int waitMax = JMOL_LOAD_TIMEOUT;
377 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
378 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
379 && jmb.getStructureFiles().length == files.size()))
383 Cache.log.debug("Waiting around for jmb notify.");
384 Thread.sleep(waitFor);
385 waitTotal += waitFor;
386 } catch (Exception e)
389 if (waitTotal > waitMax)
391 System.err.println("Timed out waiting for Jmol to load files after "
393 // System.err.println("finished: " + jmb.isFinishedInit()
394 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
395 // + "; files: " + files.toString());
396 jmb.getStructureFiles();
401 // refresh the sequence colours for the new structure(s)
402 for (AlignmentPanel ap : _colourwith)
404 jmb.updateColours(ap);
406 // do superposition if asked to
407 if (alignAddedStructures)
409 alignAddedStructures();
411 addingStructures = false;
415 * Queues a thread to align structures with Jalview alignments
417 void alignAddedStructures()
419 javax.swing.SwingUtilities.invokeLater(new Runnable()
424 if (jmb.viewer.isScriptExecuting())
426 SwingUtilities.invokeLater(this);
430 } catch (InterruptedException q)
437 alignStructs_withAllAlignPanels();
445 * Retrieves and saves as file any modelled PDB entries for which we do not
446 * already have a file saved. Returns a list of absolute paths to structure
447 * files which were either retrieved, or already stored but not modelled in
448 * the structure viewer (i.e. files to add to the viewer display).
452 List<String> fetchPdbFiles()
454 // todo - record which pdbids were successfully imported.
455 StringBuilder errormsgs = new StringBuilder();
457 List<String> files = new ArrayList<>();
461 String[] filesInViewer = jmb.getStructureFiles();
462 // TODO: replace with reference fetching/transfer code (validate PDBentry
464 Pdb pdbclient = new Pdb();
465 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
467 String file = jmb.getPdbEntry(pi).getFile();
470 // todo: extract block as method and pull up (also ChimeraViewFrame)
471 // retrieve the pdb and store it locally
472 AlignmentI pdbseq = null;
473 pdbid = jmb.getPdbEntry(pi).getId();
474 long hdl = pdbid.hashCode() - System.currentTimeMillis();
475 if (progressBar != null)
477 progressBar.setProgressBar(MessageManager
478 .formatMessage("status.fetching_pdb", new String[]
483 pdbseq = pdbclient.getSequenceRecords(pdbid);
484 } catch (OutOfMemoryError oomerror)
486 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
487 } catch (Exception ex)
489 ex.printStackTrace();
490 errormsgs.append("'").append(pdbid).append("'");
493 if (progressBar != null)
495 progressBar.setProgressBar(
496 MessageManager.getString("label.state_completed"),
502 // just transfer the file name from the first sequence's first
504 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
505 .elementAt(0).getFile()).getAbsolutePath();
506 jmb.getPdbEntry(pi).setFile(file);
511 errormsgs.append("'").append(pdbid).append("' ");
516 if (filesInViewer != null && filesInViewer.length > 0)
518 addingStructures = true; // already files loaded.
519 for (int c = 0; c < filesInViewer.length; c++)
521 if (Platform.pathEquals(filesInViewer[c], file))
534 } catch (OutOfMemoryError oomerror)
536 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
537 } catch (Exception ex)
539 ex.printStackTrace();
540 errormsgs.append("When retrieving pdbfiles : current was: '")
541 .append(pdbid).append("'");
543 if (errormsgs.length() > 0)
545 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
546 MessageManager.formatMessage(
547 "label.pdb_entries_couldnt_be_retrieved", new String[]
548 { errormsgs.toString() }),
549 MessageManager.getString("label.couldnt_load_file"),
550 JvOptionPane.ERROR_MESSAGE);
556 public void eps_actionPerformed(ActionEvent e)
558 makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
562 public void png_actionPerformed(ActionEvent e)
564 makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
567 void makePDBImage(jalview.util.ImageMaker.TYPE type)
569 int width = getWidth();
570 int height = getHeight();
572 String dialogTitle = MessageManager
573 .formatMessage("label.make_pdb_image", type.getName());
574 String imageTitle = type == PNG ? null : this.getTitle();
575 ImageMaker im = new ImageMaker(this, type, dialogTitle, width, height,
576 null, imageTitle, null, 0, false);
578 if (im.getGraphics() != null)
580 jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
586 public void showHelp_actionPerformed(ActionEvent actionEvent)
591 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
592 } catch (Exception ex)
597 public void showConsole(boolean showConsole)
602 if (splitPane == null)
604 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
605 splitPane.setTopComponent(renderPanel);
606 splitPane.setBottomComponent(scriptWindow);
607 this.getContentPane().add(splitPane, BorderLayout.CENTER);
608 splitPane.setDividerLocation(getHeight() - 200);
609 scriptWindow.setVisible(true);
610 scriptWindow.validate();
611 splitPane.validate();
617 if (splitPane != null)
619 splitPane.setVisible(false);
624 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
630 class RenderPanel extends JPanel
632 final Dimension currentSize = new Dimension();
635 public void paintComponent(Graphics g)
637 getSize(currentSize);
639 if (jmb != null && jmb.hasFileLoadingError())
641 g.setColor(Color.black);
642 g.fillRect(0, 0, currentSize.width, currentSize.height);
643 g.setColor(Color.white);
644 g.setFont(new Font("Verdana", Font.BOLD, 14));
645 g.drawString(MessageManager.getString("label.error_loading_file")
646 + "...", 20, currentSize.height / 2);
647 StringBuffer sb = new StringBuffer();
649 for (int e = 0; e < jmb.getPdbCount(); e++)
651 sb.append(jmb.getPdbEntry(e).getId());
652 if (e < jmb.getPdbCount() - 1)
657 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
660 g.drawString(sb.toString(), 20, currentSize.height / 2
661 - lines * g.getFontMetrics().getHeight());
665 else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
667 g.setColor(Color.black);
668 g.fillRect(0, 0, currentSize.width, currentSize.height);
669 g.setColor(Color.white);
670 g.setFont(new Font("Verdana", Font.BOLD, 14));
671 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
672 20, currentSize.height / 2);
676 jmb.viewer.renderScreenImage(g, currentSize.width,
683 public AAStructureBindingModel getBinding()
689 public String getStateInfo()
691 return jmb == null ? null : jmb.viewer.getStateInfo();
695 public ViewerType getViewerType()
697 return ViewerType.JMOL;
701 protected String getViewerName()