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"));
156 IProgressIndicator progressBar = null;
159 protected IProgressIndicator getIProgressIndicator()
165 * display a single PDB structure in a new Jmol view
172 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
173 final AlignmentPanel ap)
175 progressBar = ap.alignFrame;
177 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
182 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
183 PDBEntry[] pdbentrys,
186 progressBar = ap.alignFrame;
187 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
188 pdbentrys, seqs, null);
189 addAlignmentPanel(ap);
190 useAlignmentPanelForColourbyseq(ap);
192 alignAddedStructures = alignAdded;
193 useAlignmentPanelForSuperposition(ap);
195 jmb.setColourBySequence(true);
196 setSize(400, 400); // probably should be a configurable/dynamic default here
198 addingStructures = false;
199 worker = new Thread(this);
202 this.addInternalFrameListener(new InternalFrameAdapter()
205 public void internalFrameClosing(
206 InternalFrameEvent internalFrameEvent)
215 * create a new Jmol containing several structures optionally superimposed
216 * using the given alignPanel.
220 * - true to superimpose
224 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
227 openNewJmol(ap, alignAdded, pe, seqs);
231 void initJmol(String command)
233 jmb.setFinishedInit(false);
234 renderPanel = new RenderPanel();
235 // TODO: consider waiting until the structure/view is fully loaded before
237 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
238 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
239 getBounds().width, getBounds().height);
240 if (scriptWindow == null)
242 BorderLayout bl = new BorderLayout();
245 scriptWindow = new JPanel(bl);
246 scriptWindow.setVisible(false);
249 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
251 // jmb.newJmolPopup("Jmol");
256 jmb.evalStateCommand(command);
257 jmb.evalStateCommand("set hoverDelay=0.1");
258 jmb.setFinishedInit(true);
262 void showSelectedChains()
269 public void closeViewer(boolean closeExternalViewer)
271 // Jmol does not use an external viewer
276 setAlignmentPanel(null);
280 // TODO: check for memory leaks where instance isn't finalised because jmb
281 // holds a reference to the window
291 List<String> files = fetchPdbFiles();
292 if (files.size() > 0)
294 showFilesInViewer(files);
304 * Either adds the given files to a structure viewer or opens a new viewer to
308 * list of absolute paths to structure files
310 void showFilesInViewer(List<String> files)
312 long lastnotify = jmb.getLoadNotifiesHandled();
313 StringBuilder fileList = new StringBuilder();
314 for (String s : files)
316 fileList.append(SPACE).append(QUOTE)
317 .append(Platform.escapeBackslashes(s)).append(QUOTE);
319 String filesString = fileList.toString();
321 if (!addingStructures)
325 initJmol("load FILES " + filesString);
326 } catch (OutOfMemoryError oomerror)
328 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
329 Cache.log.debug("File locations are " + filesString);
330 } catch (Exception ex)
332 Cache.log.error("Couldn't open Jmol viewer!", ex);
337 StringBuilder cmd = new StringBuilder();
338 cmd.append("loadingJalviewdata=true\nload APPEND ");
339 cmd.append(filesString);
340 cmd.append("\nloadingJalviewdata=null");
341 final String command = cmd.toString();
342 lastnotify = jmb.getLoadNotifiesHandled();
346 jmb.evalStateCommand(command);
347 } catch (OutOfMemoryError oomerror)
349 new OOMWarning("When trying to add structures to the Jmol viewer!",
351 Cache.log.debug("File locations are " + filesString);
352 } catch (Exception ex)
354 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
358 // need to wait around until script has finished
359 int waitMax = JMOL_LOAD_TIMEOUT;
362 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
363 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
364 && jmb.getStructureFiles().length == files.size()))
368 Cache.log.debug("Waiting around for jmb notify.");
369 Thread.sleep(waitFor);
370 waitTotal += waitFor;
371 } catch (Exception e)
374 if (waitTotal > waitMax)
376 System.err.println("Timed out waiting for Jmol to load files after "
378 // System.err.println("finished: " + jmb.isFinishedInit()
379 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
380 // + "; files: " + files.toString());
381 jmb.getStructureFiles();
386 // refresh the sequence colours for the new structure(s)
387 for (AlignmentViewPanel avp : _colourwith)
389 jmb.updateColours(avp);
391 // do superposition if asked to
392 if (alignAddedStructures)
394 alignAddedStructures();
396 addingStructures = false;
400 * Queues a thread to align structures with Jalview alignments
402 void alignAddedStructures()
404 javax.swing.SwingUtilities.invokeLater(new Runnable()
409 if (jmb.viewer.isScriptExecuting())
411 SwingUtilities.invokeLater(this);
415 } catch (InterruptedException q)
422 alignStructs_withAllAlignPanels();
430 * Retrieves and saves as file any modelled PDB entries for which we do not
431 * already have a file saved. Returns a list of absolute paths to structure
432 * files which were either retrieved, or already stored but not modelled in
433 * the structure viewer (i.e. files to add to the viewer display).
437 List<String> fetchPdbFiles()
439 // todo - record which pdbids were successfully imported.
440 StringBuilder errormsgs = new StringBuilder();
442 List<String> files = new ArrayList<>();
446 String[] filesInViewer = jmb.getStructureFiles();
447 // TODO: replace with reference fetching/transfer code (validate PDBentry
449 Pdb pdbclient = new Pdb();
450 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
452 String file = jmb.getPdbEntry(pi).getFile();
455 // todo: extract block as method and pull up (also ChimeraViewFrame)
456 // retrieve the pdb and store it locally
457 AlignmentI pdbseq = null;
458 pdbid = jmb.getPdbEntry(pi).getId();
459 long hdl = pdbid.hashCode() - System.currentTimeMillis();
460 if (progressBar != null)
462 progressBar.setProgressBar(MessageManager
463 .formatMessage("status.fetching_pdb", new String[]
468 pdbseq = pdbclient.getSequenceRecords(pdbid);
469 } catch (OutOfMemoryError oomerror)
471 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
472 } catch (Exception ex)
474 ex.printStackTrace();
475 errormsgs.append("'").append(pdbid).append("'");
478 if (progressBar != null)
480 progressBar.setProgressBar(
481 MessageManager.getString("label.state_completed"),
487 // just transfer the file name from the first sequence's first
489 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
490 .elementAt(0).getFile()).getAbsolutePath();
491 jmb.getPdbEntry(pi).setFile(file);
496 errormsgs.append("'").append(pdbid).append("' ");
501 if (filesInViewer != null && filesInViewer.length > 0)
503 addingStructures = true; // already files loaded.
504 for (int c = 0; c < filesInViewer.length; c++)
506 if (Platform.pathEquals(filesInViewer[c], file))
519 } catch (OutOfMemoryError oomerror)
521 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
522 } catch (Exception ex)
524 ex.printStackTrace();
525 errormsgs.append("When retrieving pdbfiles : current was: '")
526 .append(pdbid).append("'");
528 if (errormsgs.length() > 0)
530 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
531 MessageManager.formatMessage(
532 "label.pdb_entries_couldnt_be_retrieved", new String[]
533 { errormsgs.toString() }),
534 MessageManager.getString("label.couldnt_load_file"),
535 JvOptionPane.ERROR_MESSAGE);
541 public void eps_actionPerformed(ActionEvent e)
543 makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
547 public void png_actionPerformed(ActionEvent e)
549 makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
552 void makePDBImage(jalview.util.ImageMaker.TYPE type)
554 int width = getWidth();
555 int height = getHeight();
557 jalview.util.ImageMaker im;
559 if (type == jalview.util.ImageMaker.TYPE.PNG)
561 im = new jalview.util.ImageMaker(this,
562 jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from view",
563 width, height, null, null, null, 0, false);
565 else if (type == jalview.util.ImageMaker.TYPE.EPS)
567 im = new jalview.util.ImageMaker(this,
568 jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from view",
569 width, height, null, this.getTitle(), null, 0, false);
574 im = new jalview.util.ImageMaker(this,
575 jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
576 width, height, null, this.getTitle(), null, 0, false);
579 if (im.getGraphics() != null)
581 jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
587 public void showHelp_actionPerformed(ActionEvent actionEvent)
592 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
593 } catch (Exception ex)
598 public void showConsole(boolean showConsole)
603 if (splitPane == null)
605 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
606 splitPane.setTopComponent(renderPanel);
607 splitPane.setBottomComponent(scriptWindow);
608 this.getContentPane().add(splitPane, BorderLayout.CENTER);
609 splitPane.setDividerLocation(getHeight() - 200);
610 scriptWindow.setVisible(true);
611 scriptWindow.validate();
612 splitPane.validate();
618 if (splitPane != null)
620 splitPane.setVisible(false);
625 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
631 class RenderPanel extends JPanel
633 final Dimension currentSize = new Dimension();
636 public void paintComponent(Graphics g)
638 getSize(currentSize);
640 if (jmb != null && jmb.hasFileLoadingError())
642 g.setColor(Color.black);
643 g.fillRect(0, 0, currentSize.width, currentSize.height);
644 g.setColor(Color.white);
645 g.setFont(new Font("Verdana", Font.BOLD, 14));
646 g.drawString(MessageManager.getString("label.error_loading_file")
647 + "...", 20, currentSize.height / 2);
648 StringBuffer sb = new StringBuffer();
650 for (int e = 0; e < jmb.getPdbCount(); e++)
652 sb.append(jmb.getPdbEntry(e).getId());
653 if (e < jmb.getPdbCount() - 1)
658 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
661 g.drawString(sb.toString(), 20, currentSize.height / 2
662 - lines * g.getFontMetrics().getHeight());
666 else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
668 g.setColor(Color.black);
669 g.fillRect(0, 0, currentSize.width, currentSize.height);
670 g.setColor(Color.white);
671 g.setFont(new Font("Verdana", Font.BOLD, 14));
672 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
673 20, currentSize.height / 2);
677 jmb.viewer.renderScreenImage(g, currentSize.width,
684 public AAStructureBindingModel getBinding()
690 public String getStateInfo()
692 return jmb == null ? null : jmb.viewer.getStateInfo();
696 public ViewerType getViewerType()
698 return ViewerType.JMOL;
702 protected String getViewerName()