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;
45 import java.util.Vector;
47 import javax.swing.JCheckBoxMenuItem;
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 QUOTE = "\"";
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"));
159 * display a single PDB structure in a new Jmol view
166 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
167 final AlignmentPanel ap)
169 setProgressIndicator(ap.alignFrame);
171 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
176 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
177 PDBEntry[] pdbentrys,
180 setProgressIndicator(ap.alignFrame);
181 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
182 pdbentrys, seqs, null);
183 addAlignmentPanel(ap);
184 useAlignmentPanelForColourbyseq(ap);
186 alignAddedStructures = alignAdded;
187 useAlignmentPanelForSuperposition(ap);
189 jmb.setColourBySequence(true);
190 setSize(400, 400); // probably should be a configurable/dynamic default here
192 addingStructures = false;
193 worker = new Thread(this);
196 this.addInternalFrameListener(new InternalFrameAdapter()
199 public void internalFrameClosing(
200 InternalFrameEvent internalFrameEvent)
209 * create a new Jmol containing several structures optionally superimposed
210 * using the given alignPanel.
214 * - true to superimpose
218 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
221 openNewJmol(ap, alignAdded, pe, seqs);
225 void initJmol(String command)
227 jmb.setFinishedInit(false);
228 renderPanel = new RenderPanel();
229 // TODO: consider waiting until the structure/view is fully loaded before
231 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
232 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
233 getBounds().width, getBounds().height);
234 if (scriptWindow == null)
236 BorderLayout bl = new BorderLayout();
239 scriptWindow = new JPanel(bl);
240 scriptWindow.setVisible(false);
243 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
245 // jmb.newJmolPopup("Jmol");
250 jmb.evalStateCommand(command);
251 jmb.evalStateCommand("set hoverDelay=0.1");
252 jmb.setFinishedInit(true);
256 void showSelectedChains()
258 Vector<String> toshow = new Vector<>();
259 for (int i = 0; i < chainMenu.getItemCount(); i++)
261 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
263 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
264 if (item.isSelected())
266 toshow.addElement(item.getText());
270 jmb.centerViewer(toshow);
274 public void closeViewer(boolean closeExternalViewer)
276 // Jmol does not use an external viewer
281 setAlignmentPanel(null);
285 // TODO: check for memory leaks where instance isn't finalised because jmb
286 // holds a reference to the window
296 List<String> files = fetchPdbFiles();
297 if (files.size() > 0)
299 showFilesInViewer(files);
309 * Either adds the given files to a structure viewer or opens a new viewer to
313 * list of absolute paths to structure files
315 void showFilesInViewer(List<String> files)
317 long lastnotify = jmb.getLoadNotifiesHandled();
318 StringBuilder fileList = new StringBuilder();
319 for (String s : files)
321 fileList.append(SPACE).append(QUOTE)
322 .append(Platform.escapeBackslashes(s)).append(QUOTE);
324 String filesString = fileList.toString();
326 if (!addingStructures)
330 initJmol("load FILES " + filesString);
331 } catch (OutOfMemoryError oomerror)
333 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
334 Cache.log.debug("File locations are " + filesString);
335 } catch (Exception ex)
337 Cache.log.error("Couldn't open Jmol viewer!", ex);
342 StringBuilder cmd = new StringBuilder();
343 cmd.append("loadingJalviewdata=true\nload APPEND ");
344 cmd.append(filesString);
345 cmd.append("\nloadingJalviewdata=null");
346 final String command = cmd.toString();
347 lastnotify = jmb.getLoadNotifiesHandled();
351 jmb.evalStateCommand(command);
352 } catch (OutOfMemoryError oomerror)
354 new OOMWarning("When trying to add structures to the Jmol viewer!",
356 Cache.log.debug("File locations are " + filesString);
357 } catch (Exception ex)
359 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
363 // need to wait around until script has finished
364 int waitMax = JMOL_LOAD_TIMEOUT;
367 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
368 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
369 && jmb.getStructureFiles().length == files.size()))
373 Cache.log.debug("Waiting around for jmb notify.");
374 Thread.sleep(waitFor);
375 waitTotal += waitFor;
376 } catch (Exception e)
379 if (waitTotal > waitMax)
381 System.err.println("Timed out waiting for Jmol to load files after "
383 // System.err.println("finished: " + jmb.isFinishedInit()
384 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
385 // + "; files: " + files.toString());
386 jmb.getStructureFiles();
391 // refresh the sequence colours for the new structure(s)
392 for (AlignmentViewPanel ap : _colourwith)
394 jmb.updateColours(ap);
396 // do superposition if asked to
397 if (alignAddedStructures)
399 alignAddedStructures();
401 addingStructures = false;
405 * Queues a thread to align structures with Jalview alignments
407 void alignAddedStructures()
409 javax.swing.SwingUtilities.invokeLater(new Runnable()
414 if (jmb.jmolViewer.isScriptExecuting())
416 SwingUtilities.invokeLater(this);
420 } catch (InterruptedException q)
427 alignStructs_withAllAlignPanels();
435 * Retrieves and saves as file any modelled PDB entries for which we do not
436 * already have a file saved. Returns a list of absolute paths to structure
437 * files which were either retrieved, or already stored but not modelled in
438 * the structure viewer (i.e. files to add to the viewer display).
442 List<String> fetchPdbFiles()
444 // todo - record which pdbids were successfully imported.
445 StringBuilder errormsgs = new StringBuilder();
447 List<String> files = new ArrayList<>();
451 String[] filesInViewer = jmb.getStructureFiles();
452 // TODO: replace with reference fetching/transfer code (validate PDBentry
454 Pdb pdbclient = new Pdb();
455 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
457 String file = jmb.getPdbEntry(pi).getFile();
460 // todo: extract block as method and pull up (also ChimeraViewFrame)
461 // retrieve the pdb and store it locally
462 AlignmentI pdbseq = null;
463 pdbid = jmb.getPdbEntry(pi).getId();
464 long hdl = pdbid.hashCode() - System.currentTimeMillis();
465 setProgressMessage(MessageManager
466 .formatMessage("status.fetching_pdb", new String[]
470 pdbseq = pdbclient.getSequenceRecords(pdbid);
471 } catch (OutOfMemoryError oomerror)
473 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
474 } catch (Exception ex)
476 ex.printStackTrace();
477 errormsgs.append("'").append(pdbid).append("'");
481 MessageManager.getString("label.state_completed"), hdl);
485 // just transfer the file name from the first sequence's first
487 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
488 .elementAt(0).getFile()).getAbsolutePath();
489 jmb.getPdbEntry(pi).setFile(file);
494 errormsgs.append("'").append(pdbid).append("' ");
499 if (filesInViewer != null && filesInViewer.length > 0)
501 addingStructures = true; // already files loaded.
502 for (int c = 0; c < filesInViewer.length; c++)
504 if (Platform.pathEquals(filesInViewer[c], file))
517 } catch (OutOfMemoryError oomerror)
519 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
520 } catch (Exception ex)
522 ex.printStackTrace();
523 errormsgs.append("When retrieving pdbfiles : current was: '")
524 .append(pdbid).append("'");
526 if (errormsgs.length() > 0)
528 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
529 MessageManager.formatMessage(
530 "label.pdb_entries_couldnt_be_retrieved", new String[]
531 { errormsgs.toString() }),
532 MessageManager.getString("label.couldnt_load_file"),
533 JvOptionPane.ERROR_MESSAGE);
539 public void eps_actionPerformed(ActionEvent e)
541 makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
545 public void png_actionPerformed(ActionEvent e)
547 makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
550 void makePDBImage(jalview.util.ImageMaker.TYPE type)
552 int width = getWidth();
553 int height = getHeight();
555 jalview.util.ImageMaker im;
557 if (type == jalview.util.ImageMaker.TYPE.PNG)
559 im = new jalview.util.ImageMaker(this,
560 jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from view",
561 width, height, null, null, null, 0, false);
563 else if (type == jalview.util.ImageMaker.TYPE.EPS)
565 im = new jalview.util.ImageMaker(this,
566 jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from view",
567 width, height, null, this.getTitle(), null, 0, false);
572 im = new jalview.util.ImageMaker(this,
573 jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
574 width, height, null, this.getTitle(), null, 0, false);
577 if (im.getGraphics() != null)
579 jmb.jmolViewer.renderScreenImage(im.getGraphics(), width, height);
585 public void showHelp_actionPerformed(ActionEvent actionEvent)
590 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
591 } catch (Exception ex)
593 System.err.println("Show Jmol help failed with: " + ex.getMessage());
598 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.jmolViewer == 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.jmolViewer.renderScreenImage(g, currentSize.width,
683 public AAStructureBindingModel getBinding()
689 public String getStateInfo()
691 return jmb == null ? null : jmb.jmolViewer.getStateInfo();
695 public ViewerType getViewerType()
697 return ViewerType.JMOL;
701 protected String getViewerName()