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.structure.StructureCommand;
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;
44 import java.util.ArrayList;
45 import java.util.List;
47 import javax.swing.JPanel;
48 import javax.swing.JSplitPane;
49 import javax.swing.SwingUtilities;
50 import javax.swing.event.InternalFrameAdapter;
51 import javax.swing.event.InternalFrameEvent;
53 public class AppJmol extends StructureViewerBase
55 // ms to wait for Jmol to load files
56 private static final int JMOL_LOAD_TIMEOUT = 20000;
58 private static final String SPACE = " ";
60 private static final String QUOTE = "\"";
68 RenderPanel renderPanel;
77 * - add the alignment panel to the list used for colouring these
80 * - add the alignment panel to the list used for aligning these
82 * @param leaveColouringToJmol
83 * - do not update the colours from any other source. Jmol is
89 public AppJmol(String[] files, String[] ids, SequenceI[][] seqs,
90 AlignmentPanel ap, boolean usetoColour, boolean useToAlign,
91 boolean leaveColouringToJmol, String loadStatus, Rectangle bounds,
94 PDBEntry[] pdbentrys = new PDBEntry[files.length];
95 for (int i = 0; i < pdbentrys.length; i++)
97 // PDBEntry pdbentry = new PDBEntry(files[i], ids[i]);
98 PDBEntry pdbentry = new PDBEntry(ids[i], null, PDBEntry.Type.PDB,
100 pdbentrys[i] = pdbentry;
102 // / TODO: check if protocol is needed to be set, and if chains are
104 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
105 pdbentrys, seqs, null);
107 jmb.setLoadingFromArchive(true);
108 addAlignmentPanel(ap);
111 useAlignmentPanelForSuperposition(ap);
114 if (leaveColouringToJmol || !usetoColour)
116 jmb.setColourBySequence(false);
117 seqColour.setSelected(false);
118 viewerColour.setSelected(true);
120 else if (usetoColour)
122 useAlignmentPanelForColourbyseq(ap);
123 jmb.setColourBySequence(true);
124 seqColour.setSelected(true);
125 viewerColour.setSelected(false);
127 this.setBounds(bounds);
129 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
130 // bounds.width,bounds.height);
132 this.addInternalFrameListener(new InternalFrameAdapter()
135 public void internalFrameClosing(
136 InternalFrameEvent internalFrameEvent)
141 initJmol(loadStatus); // pdbentry, seq, JBPCHECK!
145 protected void initMenus()
149 viewerActionMenu.setText(MessageManager.getString("label.jmol"));
152 .setText(MessageManager.getString("label.colour_with_jmol"));
153 viewerColour.setToolTipText(MessageManager
154 .getString("label.let_jmol_manage_structure_colours"));
158 * display a single PDB structure in a new Jmol view
165 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
166 final AlignmentPanel ap)
168 setProgressIndicator(ap.alignFrame);
170 openNewJmol(ap, alignAddedStructures, new PDBEntry[] { pdbentry },
175 private void openNewJmol(AlignmentPanel ap, boolean alignAdded,
176 PDBEntry[] pdbentrys,
179 setProgressIndicator(ap.alignFrame);
180 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
181 pdbentrys, seqs, null);
182 addAlignmentPanel(ap);
183 useAlignmentPanelForColourbyseq(ap);
185 alignAddedStructures = alignAdded;
186 useAlignmentPanelForSuperposition(ap);
188 jmb.setColourBySequence(true);
189 setSize(400, 400); // probably should be a configurable/dynamic default here
191 addingStructures = false;
192 worker = new Thread(this);
195 this.addInternalFrameListener(new InternalFrameAdapter()
198 public void internalFrameClosing(
199 InternalFrameEvent internalFrameEvent)
208 * create a new Jmol containing several structures optionally superimposed
209 * using the given alignPanel.
213 * - true to superimpose
217 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
220 openNewJmol(ap, alignAdded, pe, seqs);
224 void initJmol(String command)
226 jmb.setFinishedInit(false);
227 renderPanel = new RenderPanel();
228 // TODO: consider waiting until the structure/view is fully loaded before
230 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
231 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
232 getBounds().width, getBounds().height);
233 if (scriptWindow == null)
235 BorderLayout bl = new BorderLayout();
238 scriptWindow = new JPanel(bl);
239 scriptWindow.setVisible(false);
242 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
244 // jmb.newJmolPopup("Jmol");
249 jmb.executeCommand(new StructureCommand(command), false);
250 jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
251 jmb.setFinishedInit(true);
255 public void closeViewer(boolean closeExternalViewer)
257 // Jmol does not use an external viewer
262 setAlignmentPanel(null);
266 // TODO: check for memory leaks where instance isn't finalised because jmb
267 // holds a reference to the window
277 List<String> files = fetchPdbFiles();
278 if (files.size() > 0)
280 showFilesInViewer(files);
290 * Either adds the given files to a structure viewer or opens a new viewer to
294 * list of absolute paths to structure files
296 void showFilesInViewer(List<String> files)
298 long lastnotify = jmb.getLoadNotifiesHandled();
299 StringBuilder fileList = new StringBuilder();
300 for (String s : files)
302 fileList.append(SPACE).append(QUOTE)
303 .append(Platform.escapeBackslashes(s)).append(QUOTE);
305 String filesString = fileList.toString();
307 if (!addingStructures)
311 initJmol("load FILES " + filesString);
312 } catch (OutOfMemoryError oomerror)
314 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
315 Cache.log.debug("File locations are " + filesString);
316 } catch (Exception ex)
318 Cache.log.error("Couldn't open Jmol viewer!", ex);
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);
338 } catch (Exception ex)
340 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
344 // need to wait around until script has finished
345 int waitMax = JMOL_LOAD_TIMEOUT;
348 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
349 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
350 && jmb.getStructureFiles().length == files.size()))
354 Cache.log.debug("Waiting around for jmb notify.");
355 Thread.sleep(waitFor);
356 waitTotal += waitFor;
357 } catch (Exception e)
360 if (waitTotal > waitMax)
362 System.err.println("Timed out waiting for Jmol to load files after "
364 // System.err.println("finished: " + jmb.isFinishedInit()
365 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
366 // + "; files: " + files.toString());
367 jmb.getStructureFiles();
372 // refresh the sequence colours for the new structure(s)
373 for (AlignmentViewPanel ap : _colourwith)
375 jmb.updateColours(ap);
377 // do superposition if asked to
378 if (alignAddedStructures)
380 alignAddedStructures();
382 addingStructures = false;
386 * Queues a thread to align structures with Jalview alignments
388 void alignAddedStructures()
390 javax.swing.SwingUtilities.invokeLater(new Runnable()
395 if (jmb.jmolViewer.isScriptExecuting())
397 SwingUtilities.invokeLater(this);
401 } catch (InterruptedException q)
408 alignStructsWithAllAlignPanels();
416 * Retrieves and saves as file any modelled PDB entries for which we do not
417 * already have a file saved. Returns a list of absolute paths to structure
418 * files which were either retrieved, or already stored but not modelled in
419 * the structure viewer (i.e. files to add to the viewer display).
423 List<String> fetchPdbFiles()
425 // todo - record which pdbids were successfully imported.
426 StringBuilder errormsgs = new StringBuilder();
428 List<String> files = new ArrayList<>();
432 String[] filesInViewer = jmb.getStructureFiles();
433 // TODO: replace with reference fetching/transfer code (validate PDBentry
435 Pdb pdbclient = new Pdb();
436 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
438 String file = jmb.getPdbEntry(pi).getFile();
441 // todo: extract block as method and pull up (also ChimeraViewFrame)
442 // retrieve the pdb and store it locally
443 AlignmentI pdbseq = null;
444 pdbid = jmb.getPdbEntry(pi).getId();
445 long hdl = pdbid.hashCode() - System.currentTimeMillis();
446 setProgressMessage(MessageManager
447 .formatMessage("status.fetching_pdb", new String[]
451 pdbseq = pdbclient.getSequenceRecords(pdbid);
452 } catch (OutOfMemoryError oomerror)
454 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
455 } catch (Exception ex)
457 ex.printStackTrace();
458 errormsgs.append("'").append(pdbid).append("'");
462 MessageManager.getString("label.state_completed"), hdl);
466 // just transfer the file name from the first sequence's first
468 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
469 .elementAt(0).getFile()).getAbsolutePath();
470 jmb.getPdbEntry(pi).setFile(file);
475 errormsgs.append("'").append(pdbid).append("' ");
480 if (filesInViewer != null && filesInViewer.length > 0)
482 addingStructures = true; // already files loaded.
483 for (int c = 0; c < filesInViewer.length; c++)
485 if (Platform.pathEquals(filesInViewer[c], file))
498 } catch (OutOfMemoryError oomerror)
500 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
501 } catch (Exception ex)
503 ex.printStackTrace();
504 errormsgs.append("When retrieving pdbfiles : current was: '")
505 .append(pdbid).append("'");
507 if (errormsgs.length() > 0)
509 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
510 MessageManager.formatMessage(
511 "label.pdb_entries_couldnt_be_retrieved", new String[]
512 { errormsgs.toString() }),
513 MessageManager.getString("label.couldnt_load_file"),
514 JvOptionPane.ERROR_MESSAGE);
520 public void eps_actionPerformed()
522 makePDBImage(ImageMaker.TYPE.EPS);
526 public void png_actionPerformed()
528 makePDBImage(ImageMaker.TYPE.PNG);
531 void makePDBImage(ImageMaker.TYPE type)
533 int width = getWidth();
534 int height = getHeight();
538 if (type == ImageMaker.TYPE.PNG)
540 im = new ImageMaker(this, ImageMaker.TYPE.PNG,
541 "Make PNG image from view",
542 width, height, null, null, null, 0, false);
544 else if (type == ImageMaker.TYPE.EPS)
546 im = new ImageMaker(this, ImageMaker.TYPE.EPS,
547 "Make EPS file from view",
548 width, height, null, this.getTitle(), null, 0, false);
552 im = new jalview.util.ImageMaker(this,
553 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()
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()