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 java.awt.BorderLayout;
24 import java.awt.Color;
25 import java.awt.Dimension;
27 import java.awt.Graphics;
29 import java.util.ArrayList;
30 import java.util.List;
33 import javax.swing.JPanel;
34 import javax.swing.JSplitPane;
35 import javax.swing.SwingUtilities;
36 import javax.swing.event.InternalFrameAdapter;
37 import javax.swing.event.InternalFrameEvent;
39 import jalview.api.AlignmentViewPanel;
40 import jalview.bin.Cache;
41 import jalview.datamodel.AlignmentI;
42 import jalview.datamodel.PDBEntry;
43 import jalview.datamodel.SequenceI;
44 import jalview.datamodel.StructureViewerModel;
45 import jalview.datamodel.StructureViewerModel.StructureData;
46 import jalview.gui.ImageExporter.ImageWriterI;
47 import jalview.gui.StructureViewer.ViewerType;
48 import jalview.structure.StructureCommand;
49 import jalview.structures.models.AAStructureBindingModel;
50 import jalview.util.BrowserLauncher;
51 import jalview.util.ImageMaker;
52 import jalview.util.MessageManager;
53 import jalview.util.Platform;
54 import jalview.ws.dbsources.EBIAlfaFold;
55 import jalview.ws.dbsources.Pdb;
57 public class AppJmol extends StructureViewerBase
59 // ms to wait for Jmol to load files
60 private static final int JMOL_LOAD_TIMEOUT = 20000;
62 private static final String SPACE = " ";
64 private static final String QUOTE = "\"";
72 RenderPanel renderPanel;
81 * - add the alignment panel to the list used for colouring these
84 * - add the alignment panel to the list used for aligning these
86 * @param leaveColouringToJmol
87 * - do not update the colours from any other source. Jmol is
93 public AppJmol(StructureViewerModel viewerModel, AlignmentPanel ap,
94 String sessionFile, String viewid)
96 Map<File, StructureData> pdbData = viewerModel.getFileData();
97 PDBEntry[] pdbentrys = new PDBEntry[pdbData.size()];
98 SequenceI[][] seqs = new SequenceI[pdbData.size()][];
100 for (StructureData data : pdbData.values())
102 PDBEntry pdbentry = new PDBEntry(data.getPdbId(), null,
103 PDBEntry.Type.PDB, data.getFilePath());
104 pdbentrys[i] = pdbentry;
105 List<SequenceI> sequencesForPdb = data.getSeqList();
106 seqs[i] = sequencesForPdb
107 .toArray(new SequenceI[sequencesForPdb.size()]);
111 // TODO: check if protocol is needed to be set, and if chains are
113 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
114 pdbentrys, seqs, null);
116 jmb.setLoadingFromArchive(true);
117 addAlignmentPanel(ap);
118 if (viewerModel.isAlignWithPanel())
120 useAlignmentPanelForSuperposition(ap);
123 boolean useToColour = viewerModel.isColourWithAlignPanel();
124 boolean leaveColouringToJmol = viewerModel.isColourByViewer();
125 if (leaveColouringToJmol || !useToColour)
127 jmb.setColourBySequence(false);
128 seqColour.setSelected(false);
129 viewerColour.setSelected(true);
131 else if (useToColour)
133 useAlignmentPanelForColourbyseq(ap);
134 jmb.setColourBySequence(true);
135 seqColour.setSelected(true);
136 viewerColour.setSelected(false);
139 this.setBounds(viewerModel.getX(), viewerModel.getY(),
140 viewerModel.getWidth(), viewerModel.getHeight());
143 this.addInternalFrameListener(new InternalFrameAdapter()
146 public void internalFrameClosing(
147 InternalFrameEvent internalFrameEvent)
152 StringBuilder cmd = new StringBuilder();
153 cmd.append("load FILES ").append(QUOTE)
154 .append(Platform.escapeBackslashes(sessionFile)).append(QUOTE);
155 initJmol(cmd.toString());
159 protected void initMenus()
164 .setText(MessageManager.getString("label.colour_with_jmol"));
165 viewerColour.setToolTipText(MessageManager
166 .getString("label.let_jmol_manage_structure_colours"));
170 * display a single PDB structure in a new Jmol view
177 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
178 final AlignmentPanel ap)
180 setProgressIndicator(ap.alignFrame);
182 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
187 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
188 PDBEntry[] pdbentrys,
191 setProgressIndicator(ap.alignFrame);
192 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
193 pdbentrys, seqs, null);
194 addAlignmentPanel(ap);
195 useAlignmentPanelForColourbyseq(ap);
197 alignAddedStructures = alignAdded;
198 if (pdbentrys.length > 1)
200 useAlignmentPanelForSuperposition(ap);
203 jmb.setColourBySequence(true);
204 setSize(400, 400); // probably should be a configurable/dynamic default here
206 addingStructures = false;
207 worker = new Thread(this);
210 this.addInternalFrameListener(new InternalFrameAdapter()
213 public void internalFrameClosing(
214 InternalFrameEvent internalFrameEvent)
223 * create a new Jmol containing several structures optionally superimposed
224 * using the given alignPanel.
228 * - true to superimpose
232 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
235 openNewJmol(ap, alignAdded, pe, seqs);
239 void initJmol(String command)
241 jmb.setFinishedInit(false);
242 renderPanel = new RenderPanel();
243 // TODO: consider waiting until the structure/view is fully loaded before
245 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
246 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
247 getBounds().width, getBounds().height);
248 if (scriptWindow == null)
250 BorderLayout bl = new BorderLayout();
253 scriptWindow = new JPanel(bl);
254 scriptWindow.setVisible(false);
257 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
259 // jmb.newJmolPopup("Jmol");
264 jmb.executeCommand(new StructureCommand(command), false);
265 jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
266 jmb.setFinishedInit(true);
275 List<String> files = fetchPdbFiles();
276 if (files.size() > 0)
278 showFilesInViewer(files);
288 * Either adds the given files to a structure viewer or opens a new viewer to
292 * list of absolute paths to structure files
294 void showFilesInViewer(List<String> files)
296 long lastnotify = jmb.getLoadNotifiesHandled();
297 StringBuilder fileList = new StringBuilder();
298 for (String s : files)
300 fileList.append(SPACE).append(QUOTE)
301 .append(Platform.escapeBackslashes(s)).append(QUOTE);
303 String filesString = fileList.toString();
305 if (!addingStructures)
309 initJmol("load FILES " + filesString);
310 } catch (OutOfMemoryError oomerror)
312 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
313 Cache.log.debug("File locations are " + filesString);
314 } catch (Exception ex)
316 Cache.log.error("Couldn't open Jmol viewer!", ex);
317 ex.printStackTrace();
323 StringBuilder cmd = new StringBuilder();
324 cmd.append("loadingJalviewdata=true\nload APPEND ");
325 cmd.append(filesString);
326 cmd.append("\nloadingJalviewdata=null");
327 final StructureCommand command = new StructureCommand(cmd.toString());
328 lastnotify = jmb.getLoadNotifiesHandled();
332 jmb.executeCommand(command, false);
333 } catch (OutOfMemoryError oomerror)
335 new OOMWarning("When trying to add structures to the Jmol viewer!",
337 Cache.log.debug("File locations are " + filesString);
339 } catch (Exception ex)
341 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
342 ex.printStackTrace();
347 // need to wait around until script has finished
348 int waitMax = JMOL_LOAD_TIMEOUT;
351 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
352 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
353 && jmb.getStructureFiles().length == files.size()))
357 Cache.log.debug("Waiting around for jmb notify.");
358 waitTotal += waitFor;
360 // Thread.sleep() throws an exception in JS
361 Thread.sleep(waitFor);
362 } catch (Exception e)
365 if (waitTotal > waitMax)
367 System.err.println("Timed out waiting for Jmol to load files after "
369 // System.err.println("finished: " + jmb.isFinishedInit()
370 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
371 // + "; files: " + files.toString());
372 jmb.getStructureFiles();
377 // refresh the sequence colours for the new structure(s)
378 for (AlignmentViewPanel ap : _colourwith)
380 jmb.updateColours(ap);
382 // do superposition if asked to
383 if (alignAddedStructures)
385 alignAddedStructures();
387 addingStructures = false;
391 * Queues a thread to align structures with Jalview alignments
393 void alignAddedStructures()
395 javax.swing.SwingUtilities.invokeLater(new Runnable()
400 if (jmb.jmolViewer.isScriptExecuting())
402 SwingUtilities.invokeLater(this);
406 } catch (InterruptedException q)
413 alignStructsWithAllAlignPanels();
421 * Retrieves and saves as file any modelled PDB entries for which we do not
422 * already have a file saved. Returns a list of absolute paths to structure
423 * files which were either retrieved, or already stored but not modelled in
424 * the structure viewer (i.e. files to add to the viewer display).
428 List<String> fetchPdbFiles()
430 // todo - record which pdbids were successfully imported.
431 StringBuilder errormsgs = new StringBuilder();
433 List<String> files = new ArrayList<>();
437 String[] filesInViewer = jmb.getStructureFiles();
438 // TODO: replace with reference fetching/transfer code (validate PDBentry
440 Pdb pdbclient = new Pdb();
441 EBIAlfaFold afclient = new EBIAlfaFold();
443 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
445 String file = jmb.getPdbEntry(pi).getFile();
448 // todo: extract block as method and pull up (also ChimeraViewFrame)
449 // retrieve the pdb and store it locally
450 AlignmentI pdbseq = null;
451 pdbid = jmb.getPdbEntry(pi).getId();
452 long hdl = pdbid.hashCode() - System.currentTimeMillis();
453 setProgressMessage(MessageManager
454 .formatMessage("status.fetching_pdb", new String[]
458 if (afclient.isValidReference(pdbid))
460 pdbseq = afclient.getSequenceRecords(pdbid);
462 pdbseq = pdbclient.getSequenceRecords(pdbid);
464 } catch (OutOfMemoryError oomerror)
466 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
467 } catch (Exception ex)
469 ex.printStackTrace();
470 errormsgs.append("'").append(pdbid).append("'");
474 MessageManager.getString("label.state_completed"), hdl);
478 // just transfer the file name from the first sequence's first
480 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
481 .elementAt(0).getFile()).getAbsolutePath();
482 jmb.getPdbEntry(pi).setFile(file);
487 errormsgs.append("'").append(pdbid).append("' ");
492 if (filesInViewer != null && filesInViewer.length > 0)
494 addingStructures = true; // already files loaded.
495 for (int c = 0; c < filesInViewer.length; c++)
497 if (Platform.pathEquals(filesInViewer[c], file))
510 } catch (OutOfMemoryError oomerror)
512 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
513 } catch (Exception ex)
515 ex.printStackTrace();
516 errormsgs.append("When retrieving pdbfiles : current was: '")
517 .append(pdbid).append("'");
519 if (errormsgs.length() > 0)
521 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
522 MessageManager.formatMessage(
523 "label.pdb_entries_couldnt_be_retrieved", new String[]
524 { errormsgs.toString() }),
525 MessageManager.getString("label.couldnt_load_file"),
526 JvOptionPane.ERROR_MESSAGE);
532 * Outputs the Jmol viewer image as an image file, after prompting the user to
533 * choose a file and (for EPS) choice of Text or Lineart character rendering
534 * (unless a preference for this is set)
539 public void makePDBImage(ImageMaker.TYPE type)
541 int width = getWidth();
542 int height = getHeight();
543 ImageWriterI writer = new ImageWriterI()
546 public void exportImage(Graphics g) throws Exception
548 jmb.jmolViewer.renderScreenImage(g, width, height);
551 String view = MessageManager.getString("action.view").toLowerCase();
552 ImageExporter exporter = new ImageExporter(writer,
553 getProgressIndicator(), type, getTitle());
554 exporter.doExport(null, this, width, height, view);
558 public void showHelp_actionPerformed()
562 BrowserLauncher // BH 2018
563 .openURL("http://wiki.jmol.org");//http://jmol.sourceforge.net/docs/JmolUserGuide/");
564 } catch (Exception ex)
566 System.err.println("Show Jmol help failed with: " + ex.getMessage());
571 public void showConsole(boolean showConsole)
575 if (splitPane == null)
577 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
578 splitPane.setTopComponent(renderPanel);
579 splitPane.setBottomComponent(scriptWindow);
580 this.getContentPane().add(splitPane, BorderLayout.CENTER);
581 splitPane.setDividerLocation(getHeight() - 200);
582 scriptWindow.setVisible(true);
583 scriptWindow.validate();
584 splitPane.validate();
590 if (splitPane != null)
592 splitPane.setVisible(false);
597 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
603 class RenderPanel extends JPanel
605 final Dimension currentSize = new Dimension();
608 public void paintComponent(Graphics g)
610 getSize(currentSize);
612 if (jmb != null && jmb.hasFileLoadingError())
614 g.setColor(Color.black);
615 g.fillRect(0, 0, currentSize.width, currentSize.height);
616 g.setColor(Color.white);
617 g.setFont(new Font("Verdana", Font.BOLD, 14));
618 g.drawString(MessageManager.getString("label.error_loading_file")
619 + "...", 20, currentSize.height / 2);
620 StringBuffer sb = new StringBuffer();
622 for (int e = 0; e < jmb.getPdbCount(); e++)
624 sb.append(jmb.getPdbEntry(e).getId());
625 if (e < jmb.getPdbCount() - 1)
630 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
633 g.drawString(sb.toString(), 20, currentSize.height / 2
634 - lines * g.getFontMetrics().getHeight());
638 else if (jmb == null || jmb.jmolViewer == null || !jmb.isFinishedInit())
640 g.setColor(Color.black);
641 g.fillRect(0, 0, currentSize.width, currentSize.height);
642 g.setColor(Color.white);
643 g.setFont(new Font("Verdana", Font.BOLD, 14));
644 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
645 20, currentSize.height / 2);
649 jmb.jmolViewer.renderScreenImage(g, currentSize.width,
656 public AAStructureBindingModel getBinding()
662 public ViewerType getViewerType()
664 return ViewerType.JMOL;
668 protected String getViewerName()