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;
28 import java.awt.Rectangle;
30 import java.util.ArrayList;
31 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.gui.StructureViewer.ViewerType;
45 import jalview.structure.StructureCommand;
46 import jalview.structures.models.AAStructureBindingModel;
47 import jalview.util.BrowserLauncher;
48 import jalview.util.ImageMaker;
49 import jalview.util.MessageManager;
50 import jalview.util.Platform;
51 import jalview.ws.dbsources.Pdb;
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 if (pdbentrys.length > 1)
188 useAlignmentPanelForSuperposition(ap);
191 jmb.setColourBySequence(true);
192 setSize(400, 400); // probably should be a configurable/dynamic default here
194 addingStructures = false;
195 worker = new Thread(this);
198 this.addInternalFrameListener(new InternalFrameAdapter()
201 public void internalFrameClosing(
202 InternalFrameEvent internalFrameEvent)
211 * create a new Jmol containing several structures optionally superimposed
212 * using the given alignPanel.
216 * - true to superimpose
220 public AppJmol(AlignmentPanel ap, boolean alignAdded, PDBEntry[] pe,
223 openNewJmol(ap, alignAdded, pe, seqs);
227 void initJmol(String command)
229 jmb.setFinishedInit(false);
230 renderPanel = new RenderPanel();
231 // TODO: consider waiting until the structure/view is fully loaded before
233 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
234 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
235 getBounds().width, getBounds().height);
236 if (scriptWindow == null)
238 BorderLayout bl = new BorderLayout();
241 scriptWindow = new JPanel(bl);
242 scriptWindow.setVisible(false);
245 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
247 // jmb.newJmolPopup("Jmol");
252 jmb.executeCommand(new StructureCommand(command), false);
253 jmb.executeCommand(new StructureCommand("set hoverDelay=0.1"), false);
254 jmb.setFinishedInit(true);
263 List<String> files = fetchPdbFiles();
264 if (files.size() > 0)
266 showFilesInViewer(files);
276 * Either adds the given files to a structure viewer or opens a new viewer to
280 * list of absolute paths to structure files
282 void showFilesInViewer(List<String> files)
284 long lastnotify = jmb.getLoadNotifiesHandled();
285 StringBuilder fileList = new StringBuilder();
286 for (String s : files)
288 fileList.append(SPACE).append(QUOTE)
289 .append(Platform.escapeBackslashes(s)).append(QUOTE);
291 String filesString = fileList.toString();
293 if (!addingStructures)
297 initJmol("load FILES " + filesString);
298 } catch (OutOfMemoryError oomerror)
300 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
301 Cache.log.debug("File locations are " + filesString);
302 } catch (Exception ex)
304 Cache.log.error("Couldn't open Jmol viewer!", ex);
309 StringBuilder cmd = new StringBuilder();
310 cmd.append("loadingJalviewdata=true\nload APPEND ");
311 cmd.append(filesString);
312 cmd.append("\nloadingJalviewdata=null");
313 final StructureCommand command = new StructureCommand(cmd.toString());
314 lastnotify = jmb.getLoadNotifiesHandled();
318 jmb.executeCommand(command, false);
319 } catch (OutOfMemoryError oomerror)
321 new OOMWarning("When trying to add structures to the Jmol viewer!",
323 Cache.log.debug("File locations are " + filesString);
324 } catch (Exception ex)
326 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
330 // need to wait around until script has finished
331 int waitMax = JMOL_LOAD_TIMEOUT;
334 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
335 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
336 && jmb.getStructureFiles().length == files.size()))
340 Cache.log.debug("Waiting around for jmb notify.");
341 Thread.sleep(waitFor);
342 waitTotal += waitFor;
343 } catch (Exception e)
346 if (waitTotal > waitMax)
348 System.err.println("Timed out waiting for Jmol to load files after "
350 // System.err.println("finished: " + jmb.isFinishedInit()
351 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
352 // + "; files: " + files.toString());
353 jmb.getStructureFiles();
358 // refresh the sequence colours for the new structure(s)
359 for (AlignmentViewPanel ap : _colourwith)
361 jmb.updateColours(ap);
363 // do superposition if asked to
364 if (alignAddedStructures)
366 alignAddedStructures();
368 addingStructures = false;
372 * Queues a thread to align structures with Jalview alignments
374 void alignAddedStructures()
376 javax.swing.SwingUtilities.invokeLater(new Runnable()
381 if (jmb.jmolViewer.isScriptExecuting())
383 SwingUtilities.invokeLater(this);
387 } catch (InterruptedException q)
394 alignStructsWithAllAlignPanels();
402 * Retrieves and saves as file any modelled PDB entries for which we do not
403 * already have a file saved. Returns a list of absolute paths to structure
404 * files which were either retrieved, or already stored but not modelled in
405 * the structure viewer (i.e. files to add to the viewer display).
409 List<String> fetchPdbFiles()
411 // todo - record which pdbids were successfully imported.
412 StringBuilder errormsgs = new StringBuilder();
414 List<String> files = new ArrayList<>();
418 String[] filesInViewer = jmb.getStructureFiles();
419 // TODO: replace with reference fetching/transfer code (validate PDBentry
421 Pdb pdbclient = new Pdb();
422 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
424 String file = jmb.getPdbEntry(pi).getFile();
427 // todo: extract block as method and pull up (also ChimeraViewFrame)
428 // retrieve the pdb and store it locally
429 AlignmentI pdbseq = null;
430 pdbid = jmb.getPdbEntry(pi).getId();
431 long hdl = pdbid.hashCode() - System.currentTimeMillis();
432 setProgressMessage(MessageManager
433 .formatMessage("status.fetching_pdb", new String[]
437 pdbseq = pdbclient.getSequenceRecords(pdbid);
438 } catch (OutOfMemoryError oomerror)
440 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
441 } catch (Exception ex)
443 ex.printStackTrace();
444 errormsgs.append("'").append(pdbid).append("'");
448 MessageManager.getString("label.state_completed"), hdl);
452 // just transfer the file name from the first sequence's first
454 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
455 .elementAt(0).getFile()).getAbsolutePath();
456 jmb.getPdbEntry(pi).setFile(file);
461 errormsgs.append("'").append(pdbid).append("' ");
466 if (filesInViewer != null && filesInViewer.length > 0)
468 addingStructures = true; // already files loaded.
469 for (int c = 0; c < filesInViewer.length; c++)
471 if (Platform.pathEquals(filesInViewer[c], file))
484 } catch (OutOfMemoryError oomerror)
486 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
487 } catch (Exception ex)
489 ex.printStackTrace();
490 errormsgs.append("When retrieving pdbfiles : current was: '")
491 .append(pdbid).append("'");
493 if (errormsgs.length() > 0)
495 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
496 MessageManager.formatMessage(
497 "label.pdb_entries_couldnt_be_retrieved", new String[]
498 { errormsgs.toString() }),
499 MessageManager.getString("label.couldnt_load_file"),
500 JvOptionPane.ERROR_MESSAGE);
506 public void eps_actionPerformed()
508 makePDBImage(ImageMaker.TYPE.EPS);
512 public void png_actionPerformed()
514 makePDBImage(ImageMaker.TYPE.PNG);
517 void makePDBImage(ImageMaker.TYPE type)
519 int width = getWidth();
520 int height = getHeight();
524 if (type == ImageMaker.TYPE.PNG)
526 im = new ImageMaker(this, ImageMaker.TYPE.PNG,
527 "Make PNG image from view",
528 width, height, null, null, null, 0, false);
530 else if (type == ImageMaker.TYPE.EPS)
532 im = new ImageMaker(this, ImageMaker.TYPE.EPS,
533 "Make EPS file from view",
534 width, height, null, this.getTitle(), null, 0, false);
538 im = new jalview.util.ImageMaker(this,
539 ImageMaker.TYPE.SVG, "Make SVG file from PCA",
540 width, height, null, this.getTitle(), null, 0, false);
543 if (im.getGraphics() != null)
545 jmb.jmolViewer.renderScreenImage(im.getGraphics(), width, height);
551 public void showHelp_actionPerformed()
556 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
557 } catch (Exception ex)
559 System.err.println("Show Jmol help failed with: " + ex.getMessage());
564 public void showConsole(boolean showConsole)
568 if (splitPane == null)
570 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
571 splitPane.setTopComponent(renderPanel);
572 splitPane.setBottomComponent(scriptWindow);
573 this.getContentPane().add(splitPane, BorderLayout.CENTER);
574 splitPane.setDividerLocation(getHeight() - 200);
575 scriptWindow.setVisible(true);
576 scriptWindow.validate();
577 splitPane.validate();
583 if (splitPane != null)
585 splitPane.setVisible(false);
590 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
596 class RenderPanel extends JPanel
598 final Dimension currentSize = new Dimension();
601 public void paintComponent(Graphics g)
603 getSize(currentSize);
605 if (jmb != null && jmb.hasFileLoadingError())
607 g.setColor(Color.black);
608 g.fillRect(0, 0, currentSize.width, currentSize.height);
609 g.setColor(Color.white);
610 g.setFont(new Font("Verdana", Font.BOLD, 14));
611 g.drawString(MessageManager.getString("label.error_loading_file")
612 + "...", 20, currentSize.height / 2);
613 StringBuffer sb = new StringBuffer();
615 for (int e = 0; e < jmb.getPdbCount(); e++)
617 sb.append(jmb.getPdbEntry(e).getId());
618 if (e < jmb.getPdbCount() - 1)
623 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
626 g.drawString(sb.toString(), 20, currentSize.height / 2
627 - lines * g.getFontMetrics().getHeight());
631 else if (jmb == null || jmb.jmolViewer == null || !jmb.isFinishedInit())
633 g.setColor(Color.black);
634 g.fillRect(0, 0, currentSize.width, currentSize.height);
635 g.setColor(Color.white);
636 g.setFont(new Font("Verdana", Font.BOLD, 14));
637 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
638 20, currentSize.height / 2);
642 jmb.jmolViewer.renderScreenImage(g, currentSize.width,
649 public AAStructureBindingModel getBinding()
655 public ViewerType getViewerType()
657 return ViewerType.JMOL;
661 protected String getViewerName()