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"));
157 * display a single PDB structure in a new Jmol view
164 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
165 final AlignmentPanel ap)
167 setProgressIndicator(ap.alignFrame);
169 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
174 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
175 PDBEntry[] pdbentrys,
178 setProgressIndicator(ap.alignFrame);
179 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
180 pdbentrys, seqs, null);
181 addAlignmentPanel(ap);
182 useAlignmentPanelForColourbyseq(ap);
184 alignAddedStructures = alignAdded;
185 useAlignmentPanelForSuperposition(ap);
187 jmb.setColourBySequence(true);
188 setSize(400, 400); // probably should be a configurable/dynamic default here
190 addingStructures = false;
191 worker = new Thread(this);
194 this.addInternalFrameListener(new InternalFrameAdapter()
197 public void internalFrameClosing(
198 InternalFrameEvent internalFrameEvent)
207 * create a new Jmol containing several structures optionally superimposed
208 * using the given alignPanel.
212 * - true to superimpose
216 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
219 openNewJmol(ap, alignAdded, pe, seqs);
223 void initJmol(String command)
225 jmb.setFinishedInit(false);
226 renderPanel = new RenderPanel();
227 // TODO: consider waiting until the structure/view is fully loaded before
229 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
230 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
231 getBounds().width, getBounds().height);
232 if (scriptWindow == null)
234 BorderLayout bl = new BorderLayout();
237 scriptWindow = new JPanel(bl);
238 scriptWindow.setVisible(false);
241 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
243 // jmb.newJmolPopup("Jmol");
248 jmb.executeCommand(command, false);
249 jmb.executeCommand("set hoverDelay=0.1", false);
250 jmb.setFinishedInit(true);
254 public void closeViewer(boolean closeExternalViewer)
256 // Jmol does not use an external viewer
261 setAlignmentPanel(null);
265 // TODO: check for memory leaks where instance isn't finalised because jmb
266 // holds a reference to the window
276 List<String> files = fetchPdbFiles();
277 if (files.size() > 0)
279 showFilesInViewer(files);
289 * Either adds the given files to a structure viewer or opens a new viewer to
293 * list of absolute paths to structure files
295 void showFilesInViewer(List<String> files)
297 long lastnotify = jmb.getLoadNotifiesHandled();
298 StringBuilder fileList = new StringBuilder();
299 for (String s : files)
301 fileList.append(SPACE).append(QUOTE)
302 .append(Platform.escapeBackslashes(s)).append(QUOTE);
304 String filesString = fileList.toString();
306 if (!addingStructures)
310 initJmol("load FILES " + filesString);
311 } catch (OutOfMemoryError oomerror)
313 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
314 Cache.log.debug("File locations are " + filesString);
315 } catch (Exception ex)
317 Cache.log.error("Couldn't open Jmol viewer!", ex);
322 StringBuilder cmd = new StringBuilder();
323 cmd.append("loadingJalviewdata=true\nload APPEND ");
324 cmd.append(filesString);
325 cmd.append("\nloadingJalviewdata=null");
326 final String command = cmd.toString();
327 lastnotify = jmb.getLoadNotifiesHandled();
331 jmb.executeCommand(command, false);
332 } catch (OutOfMemoryError oomerror)
334 new OOMWarning("When trying to add structures to the Jmol viewer!",
336 Cache.log.debug("File locations are " + filesString);
337 } catch (Exception ex)
339 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
343 // need to wait around until script has finished
344 int waitMax = JMOL_LOAD_TIMEOUT;
347 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
348 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
349 && jmb.getStructureFiles().length == files.size()))
353 Cache.log.debug("Waiting around for jmb notify.");
354 Thread.sleep(waitFor);
355 waitTotal += waitFor;
356 } catch (Exception e)
359 if (waitTotal > waitMax)
361 System.err.println("Timed out waiting for Jmol to load files after "
363 // System.err.println("finished: " + jmb.isFinishedInit()
364 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
365 // + "; files: " + files.toString());
366 jmb.getStructureFiles();
371 // refresh the sequence colours for the new structure(s)
372 for (AlignmentViewPanel ap : _colourwith)
374 jmb.updateColours(ap);
376 // do superposition if asked to
377 if (alignAddedStructures)
379 alignAddedStructures();
381 addingStructures = false;
385 * Queues a thread to align structures with Jalview alignments
387 void alignAddedStructures()
389 javax.swing.SwingUtilities.invokeLater(new Runnable()
394 if (jmb.jmolViewer.isScriptExecuting())
396 SwingUtilities.invokeLater(this);
400 } catch (InterruptedException q)
407 alignStructs_withAllAlignPanels();
415 * Retrieves and saves as file any modelled PDB entries for which we do not
416 * already have a file saved. Returns a list of absolute paths to structure
417 * files which were either retrieved, or already stored but not modelled in
418 * the structure viewer (i.e. files to add to the viewer display).
422 List<String> fetchPdbFiles()
424 // todo - record which pdbids were successfully imported.
425 StringBuilder errormsgs = new StringBuilder();
427 List<String> files = new ArrayList<>();
431 String[] filesInViewer = jmb.getStructureFiles();
432 // TODO: replace with reference fetching/transfer code (validate PDBentry
434 Pdb pdbclient = new Pdb();
435 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
437 String file = jmb.getPdbEntry(pi).getFile();
440 // todo: extract block as method and pull up (also ChimeraViewFrame)
441 // retrieve the pdb and store it locally
442 AlignmentI pdbseq = null;
443 pdbid = jmb.getPdbEntry(pi).getId();
444 long hdl = pdbid.hashCode() - System.currentTimeMillis();
445 setProgressMessage(MessageManager
446 .formatMessage("status.fetching_pdb", new String[]
450 pdbseq = pdbclient.getSequenceRecords(pdbid);
451 } catch (OutOfMemoryError oomerror)
453 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
454 } catch (Exception ex)
456 ex.printStackTrace();
457 errormsgs.append("'").append(pdbid).append("'");
461 MessageManager.getString("label.state_completed"), hdl);
465 // just transfer the file name from the first sequence's first
467 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
468 .elementAt(0).getFile()).getAbsolutePath();
469 jmb.getPdbEntry(pi).setFile(file);
474 errormsgs.append("'").append(pdbid).append("' ");
479 if (filesInViewer != null && filesInViewer.length > 0)
481 addingStructures = true; // already files loaded.
482 for (int c = 0; c < filesInViewer.length; c++)
484 if (Platform.pathEquals(filesInViewer[c], file))
497 } catch (OutOfMemoryError oomerror)
499 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
500 } catch (Exception ex)
502 ex.printStackTrace();
503 errormsgs.append("When retrieving pdbfiles : current was: '")
504 .append(pdbid).append("'");
506 if (errormsgs.length() > 0)
508 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
509 MessageManager.formatMessage(
510 "label.pdb_entries_couldnt_be_retrieved", new String[]
511 { errormsgs.toString() }),
512 MessageManager.getString("label.couldnt_load_file"),
513 JvOptionPane.ERROR_MESSAGE);
519 public void eps_actionPerformed(ActionEvent e)
521 makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
525 public void png_actionPerformed(ActionEvent e)
527 makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
530 void makePDBImage(jalview.util.ImageMaker.TYPE type)
532 int width = getWidth();
533 int height = getHeight();
535 jalview.util.ImageMaker im;
537 if (type == jalview.util.ImageMaker.TYPE.PNG)
539 im = new jalview.util.ImageMaker(this,
540 jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from view",
541 width, height, null, null, null, 0, false);
543 else if (type == jalview.util.ImageMaker.TYPE.EPS)
545 im = new jalview.util.ImageMaker(this,
546 jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from view",
547 width, height, null, this.getTitle(), null, 0, false);
552 im = new jalview.util.ImageMaker(this,
553 jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
554 width, height, null, this.getTitle(), null, 0, false);
557 if (im.getGraphics() != null)
559 jmb.jmolViewer.renderScreenImage(im.getGraphics(), width, height);
565 public void showHelp_actionPerformed(ActionEvent actionEvent)
570 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
571 } catch (Exception ex)
573 System.err.println("Show Jmol help failed with: " + ex.getMessage());
578 public void showConsole(boolean showConsole)
582 if (splitPane == null)
584 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
585 splitPane.setTopComponent(renderPanel);
586 splitPane.setBottomComponent(scriptWindow);
587 this.getContentPane().add(splitPane, BorderLayout.CENTER);
588 splitPane.setDividerLocation(getHeight() - 200);
589 scriptWindow.setVisible(true);
590 scriptWindow.validate();
591 splitPane.validate();
597 if (splitPane != null)
599 splitPane.setVisible(false);
604 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
610 class RenderPanel extends JPanel
612 final Dimension currentSize = new Dimension();
615 public void paintComponent(Graphics g)
617 getSize(currentSize);
619 if (jmb != null && jmb.hasFileLoadingError())
621 g.setColor(Color.black);
622 g.fillRect(0, 0, currentSize.width, currentSize.height);
623 g.setColor(Color.white);
624 g.setFont(new Font("Verdana", Font.BOLD, 14));
625 g.drawString(MessageManager.getString("label.error_loading_file")
626 + "...", 20, currentSize.height / 2);
627 StringBuffer sb = new StringBuffer();
629 for (int e = 0; e < jmb.getPdbCount(); e++)
631 sb.append(jmb.getPdbEntry(e).getId());
632 if (e < jmb.getPdbCount() - 1)
637 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
640 g.drawString(sb.toString(), 20, currentSize.height / 2
641 - lines * g.getFontMetrics().getHeight());
645 else if (jmb == null || jmb.jmolViewer == null || !jmb.isFinishedInit())
647 g.setColor(Color.black);
648 g.fillRect(0, 0, currentSize.width, currentSize.height);
649 g.setColor(Color.white);
650 g.setFont(new Font("Verdana", Font.BOLD, 14));
651 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
652 20, currentSize.height / 2);
656 jmb.jmolViewer.renderScreenImage(g, currentSize.width,
663 public AAStructureBindingModel getBinding()
669 public String getStateInfo()
671 return jmb == null ? null : jmb.jmolViewer.getStateInfo();
675 public ViewerType getViewerType()
677 return ViewerType.JMOL;
681 protected String getViewerName()