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.bin.Cache;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.SequenceI;
27 import jalview.gui.StructureViewer.ViewerType;
28 import jalview.structures.models.AAStructureBindingModel;
29 import jalview.util.BrowserLauncher;
30 import jalview.util.MessageManager;
31 import jalview.util.Platform;
32 import jalview.ws.dbsources.Pdb;
34 import java.awt.BorderLayout;
35 import java.awt.Color;
36 import java.awt.Dimension;
38 import java.awt.Graphics;
39 import java.awt.Rectangle;
40 import java.awt.event.ActionEvent;
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.Vector;
46 import javax.swing.JCheckBoxMenuItem;
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 BACKSLASH = "\"";
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"));
157 IProgressIndicator progressBar = null;
160 protected IProgressIndicator getIProgressIndicator()
166 * display a single PDB structure in a new Jmol view
173 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
174 final AlignmentPanel ap)
176 progressBar = ap.alignFrame;
178 openNewJmol(ap, new PDBEntry[] { pdbentry }, new SequenceI[][] { seq });
181 private void openNewJmol(AlignmentPanel ap, PDBEntry[] pdbentrys,
184 progressBar = ap.alignFrame;
185 jmb = new AppJmolBinding(this, ap.getStructureSelectionManager(),
186 pdbentrys, seqs, null);
187 addAlignmentPanel(ap);
188 useAlignmentPanelForColourbyseq(ap);
190 alignAddedStructures = true;
191 useAlignmentPanelForSuperposition(ap);
193 jmb.setColourBySequence(true);
194 setSize(400, 400); // probably should be a configurable/dynamic default here
196 addingStructures = false;
197 worker = new Thread(this);
200 this.addInternalFrameListener(new InternalFrameAdapter()
203 public void internalFrameClosing(
204 InternalFrameEvent internalFrameEvent)
213 * create a new Jmol containing several structures superimposed using the
220 public AppJmol(AlignmentPanel ap, PDBEntry[] pe, SequenceI[][] seqs)
222 openNewJmol(ap, pe, seqs);
226 void initJmol(String command)
228 jmb.setFinishedInit(false);
229 renderPanel = new RenderPanel();
230 // TODO: consider waiting until the structure/view is fully loaded before
232 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
233 jalview.gui.Desktop.addInternalFrame(this, jmb.getViewerTitle(),
234 getBounds().width, getBounds().height);
235 if (scriptWindow == null)
237 BorderLayout bl = new BorderLayout();
240 scriptWindow = new JPanel(bl);
241 scriptWindow.setVisible(false);
244 jmb.allocateViewer(renderPanel, true, "", null, null, "", scriptWindow,
246 // jmb.newJmolPopup("Jmol");
251 jmb.evalStateCommand(command);
252 jmb.evalStateCommand("set hoverDelay=0.1");
253 jmb.setFinishedInit(true);
256 boolean allChainsSelected = false;
259 void showSelectedChains()
261 Vector<String> toshow = new Vector<>();
262 for (int i = 0; i < chainMenu.getItemCount(); i++)
264 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
266 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
267 if (item.isSelected())
269 toshow.addElement(item.getText());
273 jmb.centerViewer(toshow);
277 public void closeViewer(boolean closeExternalViewer)
279 // Jmol does not use an external viewer
284 setAlignmentPanel(null);
288 // TODO: check for memory leaks where instance isn't finalised because jmb
289 // holds a reference to the window
299 List<String> files = fetchPdbFiles();
300 if (files.size() > 0)
302 showFilesInViewer(files);
312 * Either adds the given files to a structure viewer or opens a new viewer to
316 * list of absolute paths to structure files
318 void showFilesInViewer(List<String> files)
320 long lastnotify = jmb.getLoadNotifiesHandled();
321 StringBuilder fileList = new StringBuilder();
322 for (String s : files)
324 fileList.append(SPACE).append(BACKSLASH)
325 .append(Platform.escapeString(s)).append(BACKSLASH);
327 String filesString = fileList.toString();
329 if (!addingStructures)
333 initJmol("load FILES " + filesString);
334 } catch (OutOfMemoryError oomerror)
336 new OOMWarning("When trying to open the Jmol viewer!", oomerror);
337 Cache.log.debug("File locations are " + filesString);
338 } catch (Exception ex)
340 Cache.log.error("Couldn't open Jmol viewer!", ex);
345 StringBuilder cmd = new StringBuilder();
346 cmd.append("loadingJalviewdata=true\nload APPEND ");
347 cmd.append(filesString);
348 cmd.append("\nloadingJalviewdata=null");
349 final String command = cmd.toString();
350 lastnotify = jmb.getLoadNotifiesHandled();
354 jmb.evalStateCommand(command);
355 } catch (OutOfMemoryError oomerror)
357 new OOMWarning("When trying to add structures to the Jmol viewer!",
359 Cache.log.debug("File locations are " + filesString);
360 } catch (Exception ex)
362 Cache.log.error("Couldn't add files to Jmol viewer!", ex);
366 // need to wait around until script has finished
367 int waitMax = JMOL_LOAD_TIMEOUT;
370 while (addingStructures ? lastnotify >= jmb.getLoadNotifiesHandled()
371 : !(jmb.isFinishedInit() && jmb.getStructureFiles() != null
372 && jmb.getStructureFiles().length == files.size()))
376 Cache.log.debug("Waiting around for jmb notify.");
377 Thread.sleep(waitFor);
378 waitTotal += waitFor;
379 } catch (Exception e)
382 if (waitTotal > waitMax)
384 System.err.println("Timed out waiting for Jmol to load files after "
386 // System.err.println("finished: " + jmb.isFinishedInit()
387 // + "; loaded: " + Arrays.toString(jmb.getPdbFile())
388 // + "; files: " + files.toString());
389 jmb.getStructureFiles();
394 // refresh the sequence colours for the new structure(s)
395 for (AlignmentPanel ap : _colourwith)
397 jmb.updateColours(ap);
399 // do superposition if asked to
400 if (Cache.getDefault("AUTOSUPERIMPOSE", true) && alignAddedStructures)
402 alignAddedStructures();
404 addingStructures = false;
408 * Queues a thread to align structures with Jalview alignments
410 void alignAddedStructures()
412 javax.swing.SwingUtilities.invokeLater(new Runnable()
417 if (jmb.viewer.isScriptExecuting())
419 SwingUtilities.invokeLater(this);
423 } catch (InterruptedException q)
430 alignStructs_withAllAlignPanels();
434 alignAddedStructures = false;
438 * Retrieves and saves as file any modelled PDB entries for which we do not
439 * already have a file saved. Returns a list of absolute paths to structure
440 * files which were either retrieved, or already stored but not modelled in
441 * the structure viewer (i.e. files to add to the viewer display).
445 List<String> fetchPdbFiles()
447 // todo - record which pdbids were successfully imported.
448 StringBuilder errormsgs = new StringBuilder();
450 List<String> files = new ArrayList<>();
454 String[] filesInViewer = jmb.getStructureFiles();
455 // TODO: replace with reference fetching/transfer code (validate PDBentry
457 Pdb pdbclient = new Pdb();
458 for (int pi = 0; pi < jmb.getPdbCount(); pi++)
460 String file = jmb.getPdbEntry(pi).getFile();
463 // retrieve the pdb and store it locally
464 AlignmentI pdbseq = null;
465 pdbid = jmb.getPdbEntry(pi).getId();
466 long hdl = pdbid.hashCode() - System.currentTimeMillis();
467 if (progressBar != null)
469 progressBar.setProgressBar(MessageManager
470 .formatMessage("status.fetching_pdb", new String[]
475 pdbseq = pdbclient.getSequenceRecords(pdbid);
476 } catch (OutOfMemoryError oomerror)
478 new OOMWarning("Retrieving PDB id " + pdbid, oomerror);
479 } catch (Exception ex)
481 ex.printStackTrace();
482 errormsgs.append("'").append(pdbid).append("'");
485 if (progressBar != null)
487 progressBar.setProgressBar(
488 MessageManager.getString("label.state_completed"),
494 // just transfer the file name from the first sequence's first
496 file = new File(pdbseq.getSequenceAt(0).getAllPDBEntries()
497 .elementAt(0).getFile()).getAbsolutePath();
498 jmb.getPdbEntry(pi).setFile(file);
503 errormsgs.append("'").append(pdbid).append("' ");
508 if (filesInViewer != null && filesInViewer.length > 0)
510 addingStructures = true; // already files loaded.
511 for (int c = 0; c < filesInViewer.length; c++)
513 if (filesInViewer[c].equals(file))
526 } catch (OutOfMemoryError oomerror)
528 new OOMWarning("Retrieving PDB files: " + pdbid, oomerror);
529 } catch (Exception ex)
531 ex.printStackTrace();
532 errormsgs.append("When retrieving pdbfiles : current was: '")
533 .append(pdbid).append("'");
535 if (errormsgs.length() > 0)
537 JvOptionPane.showInternalMessageDialog(Desktop.desktop,
538 MessageManager.formatMessage(
539 "label.pdb_entries_couldnt_be_retrieved", new String[]
540 { errormsgs.toString() }),
541 MessageManager.getString("label.couldnt_load_file"),
542 JvOptionPane.ERROR_MESSAGE);
548 public void eps_actionPerformed(ActionEvent e)
550 makePDBImage(jalview.util.ImageMaker.TYPE.EPS);
554 public void png_actionPerformed(ActionEvent e)
556 makePDBImage(jalview.util.ImageMaker.TYPE.PNG);
559 void makePDBImage(jalview.util.ImageMaker.TYPE type)
561 int width = getWidth();
562 int height = getHeight();
564 jalview.util.ImageMaker im;
566 if (type == jalview.util.ImageMaker.TYPE.PNG)
568 im = new jalview.util.ImageMaker(this,
569 jalview.util.ImageMaker.TYPE.PNG, "Make PNG image from view",
570 width, height, null, null, null, 0, false);
572 else if (type == jalview.util.ImageMaker.TYPE.EPS)
574 im = new jalview.util.ImageMaker(this,
575 jalview.util.ImageMaker.TYPE.EPS, "Make EPS file from view",
576 width, height, null, this.getTitle(), null, 0, false);
581 im = new jalview.util.ImageMaker(this,
582 jalview.util.ImageMaker.TYPE.SVG, "Make SVG file from PCA",
583 width, height, null, this.getTitle(), null, 0, false);
586 if (im.getGraphics() != null)
588 jmb.viewer.renderScreenImage(im.getGraphics(), width, height);
594 public void showHelp_actionPerformed(ActionEvent actionEvent)
599 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
600 } catch (Exception ex)
605 public void showConsole(boolean showConsole)
610 if (splitPane == null)
612 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
613 splitPane.setTopComponent(renderPanel);
614 splitPane.setBottomComponent(scriptWindow);
615 this.getContentPane().add(splitPane, BorderLayout.CENTER);
616 splitPane.setDividerLocation(getHeight() - 200);
617 scriptWindow.setVisible(true);
618 scriptWindow.validate();
619 splitPane.validate();
625 if (splitPane != null)
627 splitPane.setVisible(false);
632 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
638 class RenderPanel extends JPanel
640 final Dimension currentSize = new Dimension();
643 public void paintComponent(Graphics g)
645 getSize(currentSize);
647 if (jmb != null && jmb.hasFileLoadingError())
649 g.setColor(Color.black);
650 g.fillRect(0, 0, currentSize.width, currentSize.height);
651 g.setColor(Color.white);
652 g.setFont(new Font("Verdana", Font.BOLD, 14));
653 g.drawString(MessageManager.getString("label.error_loading_file")
654 + "...", 20, currentSize.height / 2);
655 StringBuffer sb = new StringBuffer();
657 for (int e = 0; e < jmb.getPdbCount(); e++)
659 sb.append(jmb.getPdbEntry(e).getId());
660 if (e < jmb.getPdbCount() - 1)
665 if (e == jmb.getPdbCount() - 1 || sb.length() > 20)
668 g.drawString(sb.toString(), 20, currentSize.height / 2
669 - lines * g.getFontMetrics().getHeight());
673 else if (jmb == null || jmb.viewer == null || !jmb.isFinishedInit())
675 g.setColor(Color.black);
676 g.fillRect(0, 0, currentSize.width, currentSize.height);
677 g.setColor(Color.white);
678 g.setFont(new Font("Verdana", Font.BOLD, 14));
679 g.drawString(MessageManager.getString("label.retrieving_pdb_data"),
680 20, currentSize.height / 2);
684 jmb.viewer.renderScreenImage(g, currentSize.width,
691 public AAStructureBindingModel getBinding()
697 public String getStateInfo()
699 return jmb == null ? null : jmb.viewer.getStateInfo();
703 public ViewerType getViewerType()
705 return ViewerType.JMOL;
709 protected String getViewerName()